SchemaRegistryService.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. package com.provectus.kafka.ui.service;
  2. import static org.springframework.http.HttpStatus.CONFLICT;
  3. import static org.springframework.http.HttpStatus.NOT_FOUND;
  4. import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;
  5. import com.provectus.kafka.ui.exception.SchemaCompatibilityException;
  6. import com.provectus.kafka.ui.exception.SchemaFailedToDeleteException;
  7. import com.provectus.kafka.ui.exception.SchemaNotFoundException;
  8. import com.provectus.kafka.ui.exception.SchemaTypeNotSupportedException;
  9. import com.provectus.kafka.ui.exception.UnprocessableEntityException;
  10. import com.provectus.kafka.ui.exception.ValidationException;
  11. import com.provectus.kafka.ui.model.CompatibilityLevelDTO;
  12. import com.provectus.kafka.ui.model.InternalSchemaRegistry;
  13. import com.provectus.kafka.ui.model.KafkaCluster;
  14. import com.provectus.kafka.ui.model.NewSchemaSubjectDTO;
  15. import com.provectus.kafka.ui.model.SchemaSubjectDTO;
  16. import com.provectus.kafka.ui.model.SchemaTypeDTO;
  17. import com.provectus.kafka.ui.model.schemaregistry.ErrorResponse;
  18. import com.provectus.kafka.ui.model.schemaregistry.InternalCompatibilityCheck;
  19. import com.provectus.kafka.ui.model.schemaregistry.InternalCompatibilityLevel;
  20. import com.provectus.kafka.ui.model.schemaregistry.InternalNewSchema;
  21. import com.provectus.kafka.ui.model.schemaregistry.SubjectIdResponse;
  22. import java.io.IOException;
  23. import java.net.URI;
  24. import java.util.Collections;
  25. import java.util.Formatter;
  26. import java.util.List;
  27. import java.util.Objects;
  28. import java.util.Optional;
  29. import java.util.function.Function;
  30. import java.util.function.Supplier;
  31. import java.util.stream.Collectors;
  32. import lombok.RequiredArgsConstructor;
  33. import lombok.extern.slf4j.Slf4j;
  34. import org.jetbrains.annotations.NotNull;
  35. import org.jetbrains.annotations.Nullable;
  36. import org.springframework.http.HttpHeaders;
  37. import org.springframework.http.HttpMethod;
  38. import org.springframework.http.HttpStatus;
  39. import org.springframework.http.MediaType;
  40. import org.springframework.stereotype.Service;
  41. import org.springframework.util.LinkedMultiValueMap;
  42. import org.springframework.util.MultiValueMap;
  43. import org.springframework.web.reactive.function.BodyInserters;
  44. import org.springframework.web.reactive.function.client.ClientResponse;
  45. import org.springframework.web.reactive.function.client.WebClient;
  46. import org.springframework.web.reactive.function.client.WebClientRequestException;
  47. import org.springframework.web.util.UriComponentsBuilder;
  48. import reactor.core.publisher.Flux;
  49. import reactor.core.publisher.Mono;
  50. @Service
  51. @Slf4j
  52. @RequiredArgsConstructor
  53. public class SchemaRegistryService {
  54. public static final String NO_SUCH_SCHEMA_VERSION = "No such schema %s with version %s";
  55. public static final String NO_SUCH_SCHEMA = "No such schema %s";
  56. private static final String URL_SUBJECTS = "/subjects";
  57. private static final String URL_SUBJECT = "/subjects/{schemaName}";
  58. private static final String URL_SUBJECT_VERSIONS = "/subjects/{schemaName}/versions";
  59. private static final String URL_SUBJECT_BY_VERSION = "/subjects/{schemaName}/versions/{version}";
  60. private static final String LATEST = "latest";
  61. private static final String UNRECOGNIZED_FIELD_SCHEMA_TYPE = "Unrecognized field: schemaType";
  62. private static final String INCOMPATIBLE_WITH_AN_EARLIER_SCHEMA = "incompatible with an earlier schema";
  63. private static final String INVALID_SCHEMA = "Invalid Schema";
  64. private final WebClient webClient;
  65. public Mono<List<SchemaSubjectDTO>> getAllLatestVersionSchemas(KafkaCluster cluster,
  66. List<String> subjects) {
  67. return Flux.fromIterable(subjects)
  68. .concatMap(subject -> getLatestSchemaVersionBySubject(cluster, subject))
  69. .collect(Collectors.toList());
  70. }
  71. public Mono<String[]> getAllSubjectNames(KafkaCluster cluster) {
  72. return configuredWebClient(
  73. cluster,
  74. HttpMethod.GET,
  75. URL_SUBJECTS)
  76. .retrieve()
  77. .bodyToMono(String[].class)
  78. .doOnError(e -> log.error("Unexpected error", e))
  79. .as(m -> failoverAble(m,
  80. new FailoverMono<>(cluster.getSchemaRegistry(), () -> this.getAllSubjectNames(cluster))));
  81. }
  82. public Flux<SchemaSubjectDTO> getAllVersionsBySubject(KafkaCluster cluster, String subject) {
  83. Flux<Integer> versions = getSubjectVersions(cluster, subject);
  84. return versions.flatMap(version -> getSchemaSubjectByVersion(cluster, subject, version));
  85. }
  86. private Flux<Integer> getSubjectVersions(KafkaCluster cluster, String schemaName) {
  87. return configuredWebClient(
  88. cluster,
  89. HttpMethod.GET,
  90. URL_SUBJECT_VERSIONS,
  91. schemaName)
  92. .retrieve()
  93. .onStatus(NOT_FOUND::equals,
  94. throwIfNotFoundStatus(formatted(NO_SUCH_SCHEMA, schemaName)))
  95. .bodyToFlux(Integer.class)
  96. .as(f -> failoverAble(f, new FailoverFlux<>(cluster.getSchemaRegistry(),
  97. () -> this.getSubjectVersions(cluster, schemaName))));
  98. }
  99. public Mono<SchemaSubjectDTO> getSchemaSubjectByVersion(KafkaCluster cluster, String schemaName,
  100. Integer version) {
  101. return this.getSchemaSubject(cluster, schemaName, String.valueOf(version));
  102. }
  103. public Mono<SchemaSubjectDTO> getLatestSchemaVersionBySubject(KafkaCluster cluster,
  104. String schemaName) {
  105. return this.getSchemaSubject(cluster, schemaName, LATEST);
  106. }
  107. private Mono<SchemaSubjectDTO> getSchemaSubject(KafkaCluster cluster, String schemaName,
  108. String version) {
  109. return configuredWebClient(
  110. cluster,
  111. HttpMethod.GET,
  112. SchemaRegistryService.URL_SUBJECT_BY_VERSION,
  113. List.of(schemaName, version))
  114. .retrieve()
  115. .onStatus(NOT_FOUND::equals,
  116. throwIfNotFoundStatus(formatted(NO_SUCH_SCHEMA_VERSION, schemaName, version))
  117. )
  118. .bodyToMono(SchemaSubjectDTO.class)
  119. .map(this::withSchemaType)
  120. .zipWith(getSchemaCompatibilityInfoOrGlobal(cluster, schemaName))
  121. .map(tuple -> {
  122. SchemaSubjectDTO schema = tuple.getT1();
  123. String compatibilityLevel = tuple.getT2().getCompatibilityLevel();
  124. schema.setCompatibilityLevel(compatibilityLevel);
  125. return schema;
  126. })
  127. .as(m -> failoverAble(m, new FailoverMono<>(cluster.getSchemaRegistry(),
  128. () -> this.getSchemaSubject(cluster, schemaName, version))));
  129. }
  130. /**
  131. * If {@link SchemaSubjectDTO#getSchemaType()} is null, then AVRO, otherwise,
  132. * adds the schema type as is.
  133. */
  134. @NotNull
  135. private SchemaSubjectDTO withSchemaType(SchemaSubjectDTO s) {
  136. return s.schemaType(Optional.ofNullable(s.getSchemaType()).orElse(SchemaTypeDTO.AVRO));
  137. }
  138. public Mono<Void> deleteSchemaSubjectByVersion(KafkaCluster cluster,
  139. String schemaName,
  140. Integer version) {
  141. return this.deleteSchemaSubject(cluster, schemaName, String.valueOf(version));
  142. }
  143. public Mono<Void> deleteLatestSchemaSubject(KafkaCluster cluster,
  144. String schemaName) {
  145. return this.deleteSchemaSubject(cluster, schemaName, LATEST);
  146. }
  147. private Mono<Void> deleteSchemaSubject(KafkaCluster cluster, String schemaName,
  148. String version) {
  149. return configuredWebClient(
  150. cluster,
  151. HttpMethod.DELETE,
  152. SchemaRegistryService.URL_SUBJECT_BY_VERSION,
  153. List.of(schemaName, version))
  154. .retrieve()
  155. .onStatus(NOT_FOUND::equals,
  156. throwIfNotFoundStatus(formatted(NO_SUCH_SCHEMA_VERSION, schemaName, version))
  157. )
  158. .toBodilessEntity()
  159. .then()
  160. .as(m -> failoverAble(m, new FailoverMono<>(cluster.getSchemaRegistry(),
  161. () -> this.deleteSchemaSubject(cluster, schemaName, version))));
  162. }
  163. public Mono<Void> deleteSchemaSubjectEntirely(KafkaCluster cluster,
  164. String schemaName) {
  165. return configuredWebClient(
  166. cluster,
  167. HttpMethod.DELETE,
  168. URL_SUBJECT,
  169. schemaName)
  170. .retrieve()
  171. .onStatus(HttpStatus::isError, errorOnSchemaDeleteFailure(schemaName))
  172. .toBodilessEntity()
  173. .then()
  174. .as(m -> failoverAble(m, new FailoverMono<>(cluster.getSchemaRegistry(),
  175. () -> this.deleteSchemaSubjectEntirely(cluster, schemaName))));
  176. }
  177. /**
  178. * Checks whether the provided schema duplicates the previous or not, creates a new schema
  179. * and then returns the whole content by requesting its latest version.
  180. */
  181. public Mono<SchemaSubjectDTO> registerNewSchema(KafkaCluster cluster,
  182. Mono<NewSchemaSubjectDTO> newSchemaSubject) {
  183. return newSchemaSubject
  184. .flatMap(schema -> {
  185. SchemaTypeDTO schemaType =
  186. SchemaTypeDTO.AVRO == schema.getSchemaType() ? null : schema.getSchemaType();
  187. Mono<InternalNewSchema> newSchema =
  188. Mono.just(new InternalNewSchema(schema.getSchema(), schemaType));
  189. String subject = schema.getSubject();
  190. return submitNewSchema(subject, newSchema, cluster)
  191. .flatMap(resp -> getLatestSchemaVersionBySubject(cluster, subject));
  192. });
  193. }
  194. @NotNull
  195. private Mono<SubjectIdResponse> submitNewSchema(String subject,
  196. Mono<InternalNewSchema> newSchemaSubject,
  197. KafkaCluster cluster) {
  198. return configuredWebClient(
  199. cluster,
  200. HttpMethod.POST,
  201. URL_SUBJECT_VERSIONS, subject)
  202. .contentType(MediaType.APPLICATION_JSON)
  203. .body(BodyInserters.fromPublisher(newSchemaSubject, InternalNewSchema.class))
  204. .retrieve()
  205. .onStatus(status -> UNPROCESSABLE_ENTITY.equals(status) || CONFLICT.equals(status),
  206. r -> r.bodyToMono(ErrorResponse.class)
  207. .flatMap(this::getMonoError))
  208. .bodyToMono(SubjectIdResponse.class)
  209. .as(m -> failoverAble(m, new FailoverMono<>(cluster.getSchemaRegistry(),
  210. () -> submitNewSchema(subject, newSchemaSubject, cluster))));
  211. }
  212. @NotNull
  213. private Mono<Throwable> getMonoError(ErrorResponse x) {
  214. if (isUnrecognizedFieldSchemaTypeMessage(x.getMessage())) {
  215. return Mono.error(new SchemaTypeNotSupportedException());
  216. } else if (isIncompatibleSchemaMessage(x.getMessage())) {
  217. return Mono.error(new SchemaCompatibilityException(x.getMessage()));
  218. } else {
  219. log.error(x.getMessage());
  220. return Mono.error(new UnprocessableEntityException(INVALID_SCHEMA));
  221. }
  222. }
  223. @NotNull
  224. private Function<ClientResponse, Mono<? extends Throwable>> throwIfNotFoundStatus(
  225. String formatted) {
  226. return resp -> Mono.error(new SchemaNotFoundException(formatted));
  227. }
  228. /**
  229. * Updates a compatibility level for a <code>schemaName</code>.
  230. *
  231. * @param schemaName is a schema subject name
  232. * @see com.provectus.kafka.ui.model.CompatibilityLevelDTO.CompatibilityEnum
  233. */
  234. public Mono<Void> updateSchemaCompatibility(KafkaCluster cluster, @Nullable String schemaName,
  235. Mono<CompatibilityLevelDTO> compatibilityLevel) {
  236. String configEndpoint = Objects.isNull(schemaName) ? "/config" : "/config/{schemaName}";
  237. return configuredWebClient(
  238. cluster,
  239. HttpMethod.PUT,
  240. configEndpoint,
  241. schemaName)
  242. .contentType(MediaType.APPLICATION_JSON)
  243. .body(BodyInserters.fromPublisher(compatibilityLevel, CompatibilityLevelDTO.class))
  244. .retrieve()
  245. .onStatus(NOT_FOUND::equals,
  246. throwIfNotFoundStatus(formatted(NO_SUCH_SCHEMA, schemaName)))
  247. .bodyToMono(Void.class)
  248. .as(m -> failoverAble(m, new FailoverMono<>(cluster.getSchemaRegistry(),
  249. () -> this.updateSchemaCompatibility(cluster, schemaName, compatibilityLevel))));
  250. }
  251. public Mono<Void> updateSchemaCompatibility(KafkaCluster cluster,
  252. Mono<CompatibilityLevelDTO> compatibilityLevel) {
  253. return updateSchemaCompatibility(cluster, null, compatibilityLevel);
  254. }
  255. public Mono<InternalCompatibilityLevel> getSchemaCompatibilityLevel(KafkaCluster cluster,
  256. String schemaName) {
  257. String globalConfig = Objects.isNull(schemaName) ? "/config" : "/config/{schemaName}";
  258. final var values = new LinkedMultiValueMap<String, String>();
  259. values.add("defaultToGlobal", "true");
  260. return configuredWebClient(
  261. cluster,
  262. HttpMethod.GET,
  263. globalConfig,
  264. (schemaName == null ? Collections.emptyList() : List.of(schemaName)),
  265. values)
  266. .retrieve()
  267. .bodyToMono(InternalCompatibilityLevel.class)
  268. .onErrorResume(error -> Mono.empty());
  269. }
  270. public Mono<InternalCompatibilityLevel> getGlobalSchemaCompatibilityLevel(KafkaCluster cluster) {
  271. return this.getSchemaCompatibilityLevel(cluster, null);
  272. }
  273. private Mono<InternalCompatibilityLevel> getSchemaCompatibilityInfoOrGlobal(KafkaCluster cluster,
  274. String schemaName) {
  275. return this.getSchemaCompatibilityLevel(cluster, schemaName)
  276. .switchIfEmpty(this.getGlobalSchemaCompatibilityLevel(cluster));
  277. }
  278. public Mono<InternalCompatibilityCheck> checksSchemaCompatibility(
  279. KafkaCluster cluster, String schemaName, Mono<NewSchemaSubjectDTO> newSchemaSubject) {
  280. return configuredWebClient(
  281. cluster,
  282. HttpMethod.POST,
  283. "/compatibility/subjects/{schemaName}/versions/latest",
  284. schemaName)
  285. .contentType(MediaType.APPLICATION_JSON)
  286. .body(BodyInserters.fromPublisher(newSchemaSubject, NewSchemaSubjectDTO.class))
  287. .retrieve()
  288. .onStatus(NOT_FOUND::equals,
  289. throwIfNotFoundStatus(formatted(NO_SUCH_SCHEMA, schemaName)))
  290. .bodyToMono(InternalCompatibilityCheck.class)
  291. .as(m -> failoverAble(m, new FailoverMono<>(cluster.getSchemaRegistry(),
  292. () -> this.checksSchemaCompatibility(cluster, schemaName, newSchemaSubject))));
  293. }
  294. public String formatted(String str, Object... args) {
  295. try (Formatter formatter = new Formatter()) {
  296. return formatter.format(str, args).toString();
  297. }
  298. }
  299. private void setBasicAuthIfEnabled(InternalSchemaRegistry schemaRegistry, HttpHeaders headers) {
  300. if (schemaRegistry.getUsername() != null && schemaRegistry.getPassword() != null) {
  301. headers.setBasicAuth(
  302. schemaRegistry.getUsername(),
  303. schemaRegistry.getPassword()
  304. );
  305. } else if (schemaRegistry.getUsername() != null) {
  306. throw new ValidationException(
  307. "You specified username but did not specify password");
  308. } else if (schemaRegistry.getPassword() != null) {
  309. throw new ValidationException(
  310. "You specified password but did not specify username");
  311. }
  312. }
  313. private boolean isUnrecognizedFieldSchemaTypeMessage(String errorMessage) {
  314. return errorMessage.contains(UNRECOGNIZED_FIELD_SCHEMA_TYPE);
  315. }
  316. private boolean isIncompatibleSchemaMessage(String message) {
  317. return message.contains(INCOMPATIBLE_WITH_AN_EARLIER_SCHEMA);
  318. }
  319. private WebClient.RequestBodySpec configuredWebClient(KafkaCluster cluster, HttpMethod method,
  320. String uri) {
  321. return configuredWebClient(cluster, method, uri, Collections.emptyList(),
  322. new LinkedMultiValueMap<>());
  323. }
  324. private WebClient.RequestBodySpec configuredWebClient(KafkaCluster cluster, HttpMethod method,
  325. String uri, List<String> uriVariables) {
  326. return configuredWebClient(cluster, method, uri, uriVariables, new LinkedMultiValueMap<>());
  327. }
  328. private WebClient.RequestBodySpec configuredWebClient(KafkaCluster cluster, HttpMethod method,
  329. String uri, @Nullable String uriVariable) {
  330. List<String> uriVariables = uriVariable == null ? Collections.emptyList() : List.of(uriVariable);
  331. return configuredWebClient(cluster, method, uri, uriVariables, new LinkedMultiValueMap<>());
  332. }
  333. private WebClient.RequestBodySpec configuredWebClient(KafkaCluster cluster,
  334. HttpMethod method, String path,
  335. List<String> uriVariables,
  336. MultiValueMap<String, String> queryParams) {
  337. final var schemaRegistry = cluster.getSchemaRegistry();
  338. return webClient
  339. .method(method)
  340. .uri(buildUri(schemaRegistry, path, uriVariables, queryParams))
  341. .headers(headers -> setBasicAuthIfEnabled(schemaRegistry, headers));
  342. }
  343. private URI buildUri(InternalSchemaRegistry schemaRegistry, String path, List<String> uriVariables,
  344. MultiValueMap<String, String> queryParams) {
  345. final var builder = UriComponentsBuilder
  346. .fromHttpUrl(schemaRegistry.getUri() + path);
  347. builder.queryParams(queryParams);
  348. return builder.build(uriVariables.toArray());
  349. }
  350. private Function<ClientResponse, Mono<? extends Throwable>> errorOnSchemaDeleteFailure(String schemaName) {
  351. return resp -> {
  352. if (NOT_FOUND.equals(resp.statusCode())) {
  353. return Mono.error(new SchemaNotFoundException(schemaName));
  354. }
  355. return Mono.error(new SchemaFailedToDeleteException(schemaName));
  356. };
  357. }
  358. private <T> Mono<T> failoverAble(Mono<T> request, FailoverMono<T> failoverMethod) {
  359. return request.onErrorResume(failoverMethod::failover);
  360. }
  361. private <T> Flux<T> failoverAble(Flux<T> request, FailoverFlux<T> failoverMethod) {
  362. return request.onErrorResume(failoverMethod::failover);
  363. }
  364. private abstract static class Failover<E> {
  365. private final InternalSchemaRegistry schemaRegistry;
  366. private final Supplier<E> failover;
  367. private Failover(InternalSchemaRegistry schemaRegistry, Supplier<E> failover) {
  368. this.schemaRegistry = Objects.requireNonNull(schemaRegistry);
  369. this.failover = Objects.requireNonNull(failover);
  370. }
  371. abstract E error(Throwable error);
  372. public E failover(Throwable error) {
  373. if (error instanceof WebClientRequestException
  374. && error.getCause() instanceof IOException
  375. && schemaRegistry.isFailoverAvailable()) {
  376. var uri = ((WebClientRequestException) error).getUri();
  377. schemaRegistry.markAsUnavailable(String.format("%s://%s", uri.getScheme(), uri.getAuthority()));
  378. return failover.get();
  379. }
  380. return error(error);
  381. }
  382. }
  383. private static class FailoverMono<T> extends Failover<Mono<T>> {
  384. private FailoverMono(InternalSchemaRegistry schemaRegistry, Supplier<Mono<T>> failover) {
  385. super(schemaRegistry, failover);
  386. }
  387. @Override
  388. Mono<T> error(Throwable error) {
  389. return Mono.error(error);
  390. }
  391. }
  392. private static class FailoverFlux<T> extends Failover<Flux<T>> {
  393. private FailoverFlux(InternalSchemaRegistry schemaRegistry, Supplier<Flux<T>> failover) {
  394. super(schemaRegistry, failover);
  395. }
  396. @Override
  397. Flux<T> error(Throwable error) {
  398. return Flux.error(error);
  399. }
  400. }
  401. }