SchemaRegistryService.java 19 KB

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