Saga Pattern in Microservices - Parte 4
Tags: kotlin, graphql, postgres, node
Published: 2024-03-12 02:09:56

Ferramentas necessárias:
* [Java] (https://www.oracle.com/java/technologies/downloads/)
* [Docker](https://docs.docker.com/desktop/windows/install/#:~:text=%20Install%20Docker%20Desktop%20on%20Windows%20%F0%9F%94%97%20,to%20authorize%20the%20installer%20and%20proceed...%20More%20)
* IDE de sua preferencia
* [Configuração do ambiente conforme a parte 2 do artigo](https://dev.to/2020nani/teste-16oa-temp-slug-8201349?preview=92424408771c77939281b5ffdd2520e8e738ea34aa40fabb79b714d7e861f958d9a6a4c22310af4b7b3d96e4501163c596956f0aaedb6365c2ec2f3e)

Vamos criar três aplicações com os nomes de **Adress-Service(Java)**, **UserRegistration** e **Validated-Document-Service(Kotlin)** no [spring starter](https://start.spring.io/) com as seguintes dependências necessárias

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qo02g8thtvztdr2r81lb.png)

Essas apis receberam o payload via tópico kafka conforme listener do kafka configurado nelas e integrarão com outro service nosso construído em Nodejs/Graph que nos retornara os dados que precisamos, a **AdressService** ira buscar e adicionar o endereço do usuário no payload enquanto que a **Validated-Document-Service** ira validar se o documento do usuário não esta guardado dentro de uma lista de documentos bloqueados.
Feito isso a mensagem e enviada para o topico a api **User-Registration** que com o payload com os dados completo do usuário armazeno-os no banco de dados postgres.
Abaixo deixarei o link para acessar o código das aplicações no github.

[API Saga Pattern - AdressService(Java)](https://github.com/2020nani/saga_pattern/tree/master/adress-service)
[API Saga Pattern - ValidatedService(Kotlin)](https://github.com/2020nani/saga_pattern/tree/master/validated-document-service)
[API Saga Pattern - UserRegistration(Kotlin)](https://github.com/2020nani/saga_pattern/tree/master/user-registration)

Essas apis integrarão com outra api nossa construído em Nodejs/Graphql que nos fornecerão os dados de endereço do usuário e a lista de documentos bloqueados.
[API Saga Pattern - DataService(Nodejs/Graphql)](https://github.com/2020nani/saga_pattern/tree/master/data-service)

Podemos testar agora a saga para cadastrar um usuário e validar o comportamento dos microservices se integrando entre si através da orientação a eventos.
Acesse nossa primeira api atraves do swagger por este [link](http://localhost:3000/swagger-ui/index.html).

No endpoint /user vamos fazer a requisição inicial passando nome, cpf valido e o cep do usuario.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxowahlrdpajm5o244sc.png)

Logs do fluxo da nossa saga na api orquestradora

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3u8fsyuqs0l3n0j67gbp.png)
Vamos pegar o transactionId no payload de retorno da requisição que fizemos acima e consultar via endpoint /user/event

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbxuzgbxkfjn6k323bue.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9sh29izikrysycm07so.png)
Isso nos retornara todo o processo que aconteceu na nossa transação com sucesso.
```
{
  "id": "65efb539e7a8223c9344944f",
  "userId": "65efb538e7a8223c9344944e",
  "transactionId": "1710208312995_b931560b-58d2-4d8a-8351-3abdcf2e7268",
  "payload": {
    "id": "65efb538e7a8223c9344944e",
    "transactionId": "1710208312995_b931560b-58d2-4d8a-8351-3abdcf2e7268",
    "name": "Teste",
    "document": "91549825020",
    "cep": "18608-456",
    "createdAt": "2024-03-12T01:51:52.996"
  },
  "source": "ORCHESTRATOR",
  "status": "SUCCESS",
  "eventHistory": [
    {
      "source": "ORCHESTRATOR",
      "status": "SUCCESS",
      "message": "Saga started!",
      "createdAt": "2024-03-11T22:51:53.032"
    },
    {
      "source": "ADRESS_VALIDATION_SERVICE",
      "status": "SUCCESS",
      "message": "adress was validated successfully! {}",
      "createdAt": "2024-03-11T22:51:53.188"
    },
    {
      "source": "VALIDATED_SERVICE",
      "status": "SUCCESS",
      "message": "Document was validated successfully! {}",
      "createdAt": "2024-03-11T22:51:53.287"
    },
    {
      "source": "REGISTRATION_SERVICE",
      "status": "SUCCESS",
      "message": "user persisted with successfully! {}",
      "createdAt": "2024-03-11T22:51:54.476"
    },
    {
      "source": "ORCHESTRATOR",
      "status": "SUCCESS",
      "message": "Saga finished successfully!",
      "createdAt": "2024-03-11T22:51:54.741"
    }
  ],
  "createdAt": "2024-03-12T01:51:54.999"
}
```
Vamos repetir esse processo porem passando um cpf que contem na lista de documentos bloqueados

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91crggwxr4zqq5salus7.png)

Veja pelos logs da nossa api orquestradora que ocorreu um erro na api de validated-document e que a partir dai foi enviada, via kafka, uma mensagem de rollback para api validated-service e adress-service para que ambas apaguem o que já haviam feito nessa transação

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wytfil2d6fsuq3j62yi5.png)

Vamos pegar o transactionId no payload de retorno da requisição que fizemos acima e consultar via endpoint /user/event o retorno dessa saga.
```
{
  "id": "65efb708e7a8223c93449451",
  "userId": "65efb708e7a8223c93449450",
  "transactionId": "1710208776483_c53613c4-4779-4402-9702-77f9e376c2a5",
  "payload": {
    "id": "65efb708e7a8223c93449450",
    "transactionId": "1710208776483_c53613c4-4779-4402-9702-77f9e376c2a5",
    "name": "Teste",
    "document": "86060970044",
    "cep": "18608-490",
    "createdAt": "2024-03-12T01:59:36.483"
  },
  "source": "ORCHESTRATOR",
  "status": "FAIL",
  "eventHistory": [
    {
      "source": "ORCHESTRATOR",
      "status": "SUCCESS",
      "message": "Saga started!",
      "createdAt": "2024-03-11T22:59:36.507"
    },
    {
      "source": "ADRESS_VALIDATION_SERVICE",
      "status": "SUCCESS",
      "message": "adress was validated successfully! {}",
      "createdAt": "2024-03-11T22:59:36.579"
    },
    {
      "source": "VALIDATED_SERVICE",
      "status": "ROLLBACK_PENDING",
      "message": "Fail to validate adress: Document {} has some pendency in our base",
      "createdAt": "2024-03-11T22:59:36.635"
    },
    {
      "source": "VALIDATED_SERVICE",
      "status": "FAIL",
      "message": "Rollback executed on validated-document validation!",
      "createdAt": "2024-03-11T22:59:36.733"
    },
    {
      "source": "ADRESS_VALIDATION_SERVICE",
      "status": "FAIL",
      "message": "Rollback executed on adress validation!",
      "createdAt": "2024-03-11T22:59:36.876"
    },
    {
      "source": "ORCHESTRATOR",
      "status": "FAIL",
      "message": "Saga finished with errors!",
      "createdAt": "2024-03-11T22:59:36.933"
    }
  ],
  "createdAt": "2024-03-12T01:59:36.955"
}
```
Vlw pessoal por visualizarem mais esse artigo e deixo aqui minhas redes sociais para quem quiser me adicionar e trocar uma ideia sobre desenvolvimento de softwares para aprendermos juntos.

[linkedin](https://www.linkedin.com/in/nanialmeida/)
[github](https://github.com/2020nani)