<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by gbrandao07 on Medium]]></title>
        <description><![CDATA[Stories by gbrandao07 on Medium]]></description>
        <link>https://medium.com/@gustavobrandao0742?source=rss-21b8cbedc8a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rEFuiNs_J6QtOPVESXrSmw@2x.jpeg</url>
            <title>Stories by gbrandao07 on Medium</title>
            <link>https://medium.com/@gustavobrandao0742?source=rss-21b8cbedc8a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:31:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gustavobrandao0742/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MLFlow 3 e LangChain — desenvolvendo agentes de IA aplicando conceitos de AI Engineering]]></title>
            <link>https://medium.com/@gustavobrandao0742/mlflow-3-e-langchain-desenvolvendo-agentes-de-ia-aplicando-conceitos-de-ai-engineering-fe01cb8e3fc1?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe01cb8e3fc1</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Sun, 31 May 2026 22:39:02 GMT</pubDate>
            <atom:updated>2026-05-31T23:29:40.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSmFifhLYwqF5xqgzPcVZw.png" /></figure><p>Como construir, observar, avaliar e versionar agentes de IA utilizando LangChain e os recursos GenAI do MLflow 3.</p><h3>Contexto</h3><p>Atualmente existem diversos frameworks, como o Langchain, e LLMs (Large Language Models) disponíveis para a construção de agentes de IA. No estado atual em que estes frameworks se encontram, é relativamente simples construir um agente. Você consegue consumir LLMs, construir suas próprias tools, conectar com servidores MCPs (Model Context Protocol), trabalhar com RAG (Retrieval-Augmented Generation), entre outros e, ao final, produzir uma resposta gerada pela IA a partir de uma mensagem de entrada do usuário.</p><p>Entretanto, o que separa apenas desenvolvedores de agentes para Engenheiros de IA que conseguem implantar, em produção, agentes que escalam, performam bem e que atendem as expectativas dos usuários, é saber responder o seguinte conjunto de perguntas:</p><ul><li>Qual LLM melhor atende as necessidades do agente? Preciso, por exemplo, usar um modelo GPT de família 5 (mais caro) ou um de família 4 (mais barato) já atenderia e eu poderia economizar com custos?</li><li>A qualidade da criação de chunks, indexação e obtenção está boa? Como consigo, de maneira, geral, avaliar a qualidade do RAG?</li><li>O agente responde somente ao escopo do seu propósito? O system prompt garante isso?</li><li>A performance e latência estão satisfatórias? Como consigo ter visibilidade da latência das chamadas ao LLM, tempo de execução das tools e demais execuções do fluxo?</li><li>O agente está em loop mais do que deveria? Por exemplo, chamando tools indefinidamente, aumento tempo de resposta e custos?</li><li>A qualidade das respostas estão boas?</li></ul><p>Todas as perguntas acima devem ser respondidas durante o desenvolvimento do agente e, uma vez em produção, precisamos também ter meios de acompanhar a performance através das requisições reais feitas pelos consumidores clientes do agente.</p><p>Existem diversas soluções que se posicionam com o propósito de ajudar com as necessidades supracitadas (LangSmith, LangFuse, MLFlow, DataDog, Dynatrace, Databricks, etc). Para este artigo, utilizaremos o MLFlow (versão &gt;3 com módulo GenAI).</p><p>Observações:</p><ul><li>Estarei assumindo que o você, leitor, já conhece o básico de desenvolvimento de agentes com LangChain. Ao final do artigo, você pode encontrar referências recomendadas para aprofundar conhecimentos em LangChain e, também, outros temas.</li><li>Na seção <em>Conclusão e próximos passos</em>, está disponível o link do repositório GitHub com o projeto completo que iremos construir. Você pode cloná-lo para usar durante o restante do artigo.</li></ul><h3>Conhecendo o agente que iremos usar</h3><p>O agente responde perguntas sobre previsão do tempo usando duas tools:</p><ul><li><em>get_weather</em>: tool local que retorna sempre que o tempo estará quente e sem chuva para qualquer cidade. Propositalmente não retorna nada sobre temperatura mínima/máxima:</li></ul><pre>from langchain_core.tools import tool<br><br>@tool<br>def get_weather(city: str) -&gt; str:<br>    &quot;&quot;&quot;Retorna dados meteorológicos para a cidade informada.&quot;&quot;&quot;<br>    return f&quot;Tempo quente e sem chuva em {city}&quot;</pre><ul><li><em>TavilySearch</em>: tool importada do Tavily que faz pesquisas na web. O agente é instruído pelo system prompt a usá-la obrigatoriamente quando a tool local não tem todos os dados. O objetivo disso é conseguirmos exercitar um fluxo agentêntico com mais de uma execução de tool (isso ajudará nas demonstrações sobre MLFlow posteriormente.</li><li>Código do agente:</li></ul><pre>load_dotenv()<br><br>_SYSTEM_PROMPT = &quot;&quot;&quot;<br>Você é um assistente prestativo.<br><br>Se perguntarem sobre previsão do tempo:<br>- tente primeiro pela tool get_weather<br>- caso não tenha temperatura mínima/máxima, use obrigatoriamente TavilySearch<br>&quot;&quot;&quot;<br><br>def build_agent():<br><br>    model = init_chat_model(<br>        model=&quot;openai:gpt-4.1&quot;,<br>        api_key=os.getenv(&quot;OPENAI_API_KEY&quot;)<br>    )<br><br>    return create_agent(<br>        model=model,<br>        tools=[get_weather, tavily_search],<br>        system_prompt=_SYSTEM_PROMPT,<br>    )<br><br><br>def invoke_agent(message: str):<br>    agent = build_agent()<br>    return agent.invoke({&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message}]})<br><br><br>if __name__ == &quot;__main__&quot;:<br>    message = sys.argv[1] if len(sys.argv) &gt; 1 else &quot;Qual a previsão do tempo em São Paulo?&quot;<br>    invoke_agent(message)</pre><p>Resumo da execução:</p><ul><li>Usuário pergunta “Qual a previsão do tempo em cidade <em>&lt;nome da cidade&gt;</em>?”</li><li>Conforme orientado no system prompt, o agente tentará obter a informação pela tool local. Como ela não retorna nada sobre temperatura mínima e máxima, o agente realizará a busca na internet usando a tool <em>TavilySearch</em> e, com isso, obter todas as informações necessárias.</li><li>Como agora o agente tem as informações que precisa, ele formulará a resposta final e encerrará o loop de execuções.</li></ul><p>Agora que temos um agente funcionando, como sabemos se ele está performando bem para entrar em produção? E depois que entrar em produção, como sabemos se ainda continua performando bem? O MLFlow vem para nos ajudar.</p><h3>Overview sobre MLFlow</h3><p>Durante o desenvolvimento de agentes, normalmente realizamos alguns testes manuais, fazemos perguntas ao agente, verificamos as respostas e concluímos que tudo parece estar funcionando corretamente. Entretanto, esse processo dificilmente é suficiente para nos dar confiança de que o agente está realmente pronto para ser utilizado por usuários reais.</p><p>O MLflow (que nasceu como uma plataforma para versionamento e tracking de modelos de tradicionais de Machine Learning e, agora, evoluiu para contemplar GenAI) permite registrar e acompanhar detalhadamente cada execução do agente através de traces e spans. Dessa forma, conseguimos visualizar todo o fluxo de execução, incluindo chamadas ao LLM, execuções de tools, prompts utilizados, tempos de resposta e demais etapas que compõem o raciocínio do agente.</p><p>Essa visibilidade traz muito mais segurança para validar o comportamento da aplicação antes de sua entrada em produção.</p><p>Entretanto, a utilidade do MLflow não termina quando o agente é publicado.</p><p>Após a entrada em produção, novos desafios surgem. Mesmo que o agente tenha apresentado excelentes resultados durante os testes, isso não garante que continuará performando adequadamente quando exposto a solicitações reais dos usuários.</p><p>Precisamos acompanhar continuamente aspectos como:</p><ul><li>Crescimento da latência</li><li>Aumento de custos</li><li>Mudanças de comportamento do agente</li><li>Uso incorreto de tools</li><li>Falhas em integrações externas</li><li>Degradação da qualidade das respostas</li></ul><p>Ao registrar as execuções reais da aplicação, o MLflow também se torna uma poderosa ferramenta de observabilidade para agentes de IA, permitindo identificar problemas, investigar incidentes e compreender como os usuários estão interagindo com o sistema.</p><p>Em outras palavras, o MLflow nos ajuda em dois momentos fundamentais da jornada de um agente:</p><ol><li>Antes da produção, fornecendo evidências para validar que o agente está pronto para ser utilizado.</li><li>Após a produção, permitindo acompanhar continuamente seu comportamento através das execuções reais dos usuários.</li></ol><p>No próximo tópicos vamos instrumentar nosso agente para que cada execução seja automaticamente registrada no MLflow, possibilitando analisar seu comportamento com muito mais profundidade.</p><h3>Juntando tudo: estudo de caso agente LangChain + MLFlow</h3><p>O MLFlow disponibiliza bibliotecas para propagação das informações referentes a execução dos agentes. Visando não misturar as chamadas da biblioteca com o código do agente, eu deixei toda a configuração apartada e, através de <em>recipes</em> do <em>just</em>, executar apenas o agente já com toda a interceptação e propagação automática para o MLFlow. Caso você queira seguir as execuções em sua máquina, baixe o projeto no GitHub.</p><p>Observação: troque o system prompt para o método <em>load_prompt, </em>conforme<em> </em>código a seguir:</p><pre>return create_agent(<br>        model=model,<br>        tools=[get_weather, tavily_search],<br>        #system_prompt=_SYSTEM_PROMPT,<br>        system_prompt=load_prompt(&quot;weather-agent-system-prompt&quot;, version=1)<br>   )</pre><p>O método <em>load_prompt</em> vai carregar o prompt já versionado no MLFlow.</p><ul><li><strong><em>cp .env.example .env</em></strong>: configure as propriedades solicitadas no<em> .env</em></li><li>Execute <strong><em>just install</em></strong> e <strong><em>just up</em></strong> para subir um instância local do MLFlow com GenAI</li><li>Na pasta <em>./prompts</em>, há o arquivo <em>weather_agent.yaml</em> com o prompt inicial:</li></ul><pre>name: weather-agent-system-prompt<br>commit_message: &quot;v1: prompt generico&quot;<br>tags:<br>  agent: examples/agent.py<br>  domain: weather<br>template: |<br>  Voce eh um assistente prestativo do Einstein.<br><br>  Se perguntarem sobre previsao do tempo:<br>  - tente primeiro pela tool get_weather<br>  - caso nao tenha temperatura minima/maxima, use obrigatoriamente TavilySearch</pre><ul><li>Versione o prompt no MLFlow com <strong><em>just prompt-push</em></strong>. O versionamento no MLFlow é útil para compararmos como o agente responde com cada versão e, com isso, tomar a decisão de qual é a melhor versão para o propósito do agente. Ao final da execução o prompt está disponível no MLFlow, conforme imagens a seguir:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mbmczShNXostMxzdLuRezg.png" /><figcaption>Visão geral dos prompts cadastrados no MLFlow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fmPjJskaytq5wFbPrK7gA.png" /><figcaption>Visualizando informações da primeira versão do prompt no MLFlow</figcaption></figure><ul><li>Agora vamos rodar algumas execuções do agente para, daí, começarmos a visualizar como as informações chegam no MLFlow:</li></ul><pre>just run examples/agent.py &quot;Qual a previsão do tempo em São Paulo hoje?&quot;<br><br>just run examples/agent.py &quot;Vai chover em Campinas amanhã?&quot;<br><br># Fora do escopo — com prompt v1 o agente provavelmente responde quando deveria recusar<br>just run examples/agent.py &quot;Me diga uma receita de bolo de chocolate&quot;</pre><p>Cada agente se torna um experimento dentro do MLFlow. Dentro do experimento, cada execução é registrada como um trace, vide imagens a seguir referente as três execuções anteriores (o nome do experimento deve ser definido no <em>.env</em> do projeto):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*xXha5mP49UkOhwo5yv8-cw.png" /><figcaption>Experimento criado no MLFlow</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E2GHWtECE2lAkPNgwyo5w.png" /><figcaption>Visualizando os traces gerados no MLFlow</figcaption></figure><p>É possível ver todos os detalhes da cada uma das execuções (traces). Tomando como exemplo o trace referente a execução “Qual a previsão do tempo em São Paulo hoje?”, podemos ver que o agente realmente chamou a tool local e, por conta da orientação do system prompt, fez uma chamada a tool do Tavily para, com isso, produzir a resposta final:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pD5zxfiRO2wfvjVsPNQWhw.png" /><figcaption>Visualizando a aba Summary do trace</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cKYnaMl84xGev_-CVG1Xw.png" /><figcaption>Visualizando a Details &amp; Timeline do trace</figcaption></figure><p>Perceba o nível granular de informações que o MLFlow fornece, você consegue ter rastreio completo de cada um dos passos executados pelo agente. Aqui você já poderia, por exemplo, avaliar custos, lentidão em tools, erros, entre outros.</p><p>É possível também encontrar a versão do system prompt utilizada pela execução do agente, através da aba <em>Linked prompts, </em>conforme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAUU6pbDbRnfICIHIc5MJQ.png" /></figure><ul><li>Para esses testes locais, ao analisar cada um dos traces, o desenvolvedor já perceberia que o agente está respondendo perguntas fora do seu escopo de atuação, conforme trace gerado pela execução <em>“Me diga uma receita de bolo de chocolate”</em>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbhFrHPJrc3sdzP0u_Mm6w.png" /><figcaption>Trace com resposta fora do escopo do agente</figcaption></figure><p>Como esse é um cenário bem trivial, provavelmente o desenvolvedor já perceberia somente analisando os três traces executados. Entretanto, em cenários reais, essa análise manual pode ser custosa e propensa a falhas. Com isso, uma funcionalidade muito interessante oferecida pelo MLFlow ganha destaque: Datasets.</p><p>Os datasets permitem a execução de testes, a partir de cenários pré-definidos, que visam garantir que o comportamento do agente está dentro do esperado. Ele pode ser usado no desenvolvimento da primeira versão do agente ou sempre para validar uma nova versão criada antes de promovê-la ao ambiente produtivo. Datasets utilizam<em> LLM as a Judge</em>, onde você delega a avaliação da resposta a um outro LLM (pode ser o mesmo utilizado na execução ou outro de família menor, por conta de custos). Vamos ver isso na prática.</p><ul><li>Na pasta <em>./datasets</em>, há o arquivo <em>weather_agent_dataset_expectations_eval.yaml</em>:</li></ul><pre>name: previsao-tempo-expectations-dataset<br>description: &quot;Casos de teste básicos para consultas de previsão do tempo&quot;<br><br>llm:<br>   model: &quot;openai:gpt-4.1&quot;<br><br>cases:<br>  - input: &quot;Qual a previsão do tempo em São Paulo hoje?&quot;<br>    expected: &quot;deve mencionar São Paulo e conter pelo menos uma informação meteorológica (chuva, sol, temperatura, etc.)&quot;<br><br>  - input: &quot;Vai chover em Campinas amanhã?&quot;<br>    expected: &quot;deve responder sobre Campinas e mencionar perspectiva de chuva ou clima&quot;<br><br>  - input: &quot;Qual a temperatura mínima e máxima em Curitiba?&quot;<br>    expected: &quot;deve informar temperatura mínima e máxima para Curitiba&quot;<br><br>  - input: &quot;Como está o tempo agora no Rio de Janeiro?&quot;<br>    expected: &quot;deve mencionar Rio de Janeiro e descrever condição climática atual&quot;<br><br>  - input: &quot;Me diga uma receita de bolo de chocolate&quot;<br>    expected: &quot;deve recusar ou redirecionar, pois está fora do escopo do agente de clima&quot;</pre><p>O arquivo é auto-explicativo.</p><p>Execute <strong><em>just dataset-eval datasets/weather_agent_dataset_expectations_eval.yaml</em></strong> <strong><em>examples/agent.py</em></strong> e novos traces serão gerados, já com o judge expectation_match associado a cada um dos traces.</p><p>Veja, nas imagem a seguir, que novos traces foram gerados (um trace para cada entrada no arquivo <em>.datasets/weather_agent_dataset_expectations_eval.yaml)</em> e que todas passaram, com exceção do trace referente a receita de bolo de chocolate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDVrUI4K30FVqBB1cxhYIA.png" /><figcaption>Traces gerados pelo dataset de expectations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvYNju4gxqVzPPWmhcRGLw.png" /><figcaption>Expectation match negativo para receita de bolo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*XeG0zj3DZpz8RNCwGzODBg.png" /><figcaption>Visão detalhada do trace com expectation match negativo para receita de bolo</figcaption></figure><blockquote>Importante reforçar que: datasets são úteis para ajudar no desenvolvimento e também para avaliar se novos desenvolvimentos não impactaram no comportamento do agente. Datasets não avaliam traces já existentes (retroativos), eles criam novos. Para avaliar traces já existentes (por exemplo, para avaliar a qualidade das respostas geradas aos traces criados pelos consumidores do agente em produção), usamos judges diretamente, como demonstraremos posteriomente.</blockquote><p>O dataset fica versionado no MLFlow e você pode visualizar os traces gerados para cada execução diretamente nele:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8RD4UED3WZTkOC4axy_ug.png" /><figcaption>Dataset versionado</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOO3j7PC8C94_Qi3TLfv9Q.png" /><figcaption>Traces criados para a execução do dataset</figcaption></figure><p>Isso será útil para quando rodarmos novamente a avaliação e for necessário comparar os resultados das duas ou mais execuções. Isso também será demonstrado posteriormente.</p><ul><li>Agora que o desenvolvedor (seja via análise manual, ou através do dataset) conseguiu identificar que o agente está respondendo questões fora de seu escopo esperado, ele deve analisar a causa e concluir que o system prompt pode ser melhorado:</li></ul><p>Versão atual:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*_YrEdmhs1PMb7XG-Uyet3Q.png" /><figcaption>Versão 1 do prompt</figcaption></figure><p>Edite o arquivo <em>./prompts.weather_agent.yaml</em> e rode <strong><em>just prompt-push</em></strong> novamente. Com isso a nova versão será publicada:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOZpVDcgI-npUhVseT8Gbg.png" /><figcaption>Versão 2 do prompt com melhorias baseada em feedbacks do dataset evaluation</figcaption></figure><p>A título de curiosidade, o MLFlow também permite comparar versões:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jisbcB-xf-JKEIE_AWL_rw.png" /><figcaption>Comparando versões na interface do MLFlow</figcaption></figure><ul><li>Altere a versão do prompt no agente para a versão e, com isso, vamos executar novamente o dataset através do comando <strong><em>just dataset-eval datasets/weather_agent_dataset_expectations_eval.yaml examples/agent.py</em></strong>:</li></ul><pre>return create_agent(<br>    model=model,<br>    tools=[get_weather, tavily_search],<br>    system_prompt=load_prompt(&quot;weather-agent-system-prompt&quot;, version=2)<br>)</pre><p>É possível confirmar que, após os ajustes no system prompt, agora o agente recusa responder perguntas fora do contexto climático:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7s75jmp8PMFoowtOu2nH3A.png" /><figcaption>Verificando resultado do dataset evaluation</figcaption></figure><p>Também é possível comparar os evaluations runs referente a cada um dos datasets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hAzlYo4WUvvrOPdmNVS4g.png" /></figure><ul><li>Diferente do dataset evaluation (que executa o agente e gera novos traces), o judges evaluation avalia traces já existentes sem criar novos traces. Pense neles como monitoramento contínuo: rode periodicamente sobre os traces reais dos usuários para avaliar a qualidade da resposta e outros itens, como: segurança, toxicidade, como o agente responde com inputs adversos dos clientes, etc.</li></ul><p>A tabela a seguir ilustra as diferenças e quando usar cada um:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pp0aHVEkgiiz2Wb2vWArNg.png" /></figure><ul><li>No arquivo <em>./judges/config.yaml</em> há os judges builtins do MLFlow e na pasta <em>./judges/custom/*.yaml</em> há os customizados que iremos usar, conforme códigos a seguir:</li></ul><pre># arquivo config.yml<br><br>llm:<br>  model: &quot;openai:gpt-4.1&quot;<br><br>builtin:<br>  safety:<br>    enabled: true<br>    description: &quot;Detecta conteúdo inadequado, perigoso ou ofensivo na resposta&quot;<br><br>  relevance:<br>    enabled: true<br>    description: &quot;Avalia se a resposta endereça a pergunta do usuário&quot;<br><br>  conciseness:<br>    enabled: true<br>    description: &quot;Avalia se a resposta é concisa e direta ao ponto&quot;</pre><pre># arquivo custom_correctess.yaml<br><br>name: custom_domain_correctness<br>description: &quot;Verifica se a resposta está factualmente correta para o domínio&quot;<br>enabled: true<br><br>prompt: |<br>  Você é um especialista avaliador de qualidade.<br><br>  Pergunta do usuário: {input}<br>  Resposta do agente: {output}<br><br>  A resposta contém informações factualmente corretas e sem contradições?<br>  Considere apenas o que foi afirmado — não penalize por omissão de detalhes.<br><br>  Responda APENAS em JSON válido, sem texto adicional:<br>  {{&quot;result&quot;: &quot;PASS ou FAIL&quot;, &quot;reason&quot;: &quot;justificativa objetiva em 1 linha&quot;}}</pre><ul><li>Versione os judges através de <strong><em>just judges-push</em></strong> e eles serão disponibilizados no MLFlow:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*8awcAw6vuuZZ-M7HfaVvvw.png" /><figcaption>Judges versionados no MLFlow</figcaption></figure><ul><li>Execute <strong><em>just judges-eval</em></strong> para avaliar traces retroativos e o resultado aparecerá em cada um dos traces:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2oiNYqp0EJJhYaL-QFXTNQ.png" /><figcaption>Judges executados para os traces existentes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AO1TeIv1MmlBgqXIDuS5Fg.png" /><figcaption>Visão detalhada dos judges executados para um dos traces existentes</figcaption></figure><h3>Conclusão e próximos passos</h3><p>Ao longo deste artigo construímos um agente utilizando LangChain e demos os primeiros passos para aplicar conceitos de AI Engineering ao seu ciclo de vida.</p><p>Mais do que simplesmente gerar respostas utilizando um LLM, vimos a importância de desenvolver agentes que possam ser observados, avaliados e evoluídos com segurança. Conforme aplicações baseadas em IA passam a fazer parte de sistemas críticos, torna-se cada vez mais importante responder perguntas como:</p><ul><li>O agente está utilizando as ferramentas corretas?</li><li>Sua qualidade está melhorando ou piorando ao longo do tempo?</li><li>O custo está dentro do esperado?</li><li>Como validar uma nova versão antes de colocá-la em produção?</li><li>Como monitorar o comportamento real dos usuários após o deploy?</li></ul><p>Foi justamente para responder esse tipo de pergunta que utilizamos o MLflow GenAI.</p><p>Entretanto, é importante entender que este artigo representa apenas o começo da jornada de AI Engineering.</p><p>Existem diversos outros temas que se tornam relevantes à medida que agentes ganham complexidade e começam a operar em ambientes produtivos:</p><ul><li>Avaliações automatizadas mais sofisticadas</li><li>Observabilidade avançada</li><li>Prompt management</li><li>Versionamento de agentes</li><li>Agent Registry</li><li>Guardrails</li><li>Multi-agentes</li><li>RAG</li><li>Fine-tuning</li><li>Human-in-the-loop</li><li>Governança e compliance</li><li>Custos e otimização de inferência</li></ul><p>Se você quiser explorar e executar o projeto apresentado neste artigo, o código-fonte completo está disponível no meu GitHub: <a href="https://github.com/gbrandao07/agentic-framework-ai-engineering-langchain-mlflow">https://github.com/gbrandao07/agentic-framework-ai-engineering-langchain-mlflow</a></p><p>Se você deseja aprofundar seus conhecimentos em desenvolvimento de agentes, recomendo fortemente o curso de LangChain do Eden Marco, disponível na Udemy (<a href="https://www.udemy.com/course/langchain/">https://www.udemy.com/course/langchain/</a>). Foi um dos materiais que mais me ajudaram a entender os conceitos fundamentais de agentes, tools, memory, RAG e arquiteturas agentic.</p><p>Para MLflow, também recomendo os cursos disponíveis na Udemy, em especial: <a href="https://www.udemy.com/course/mlflow-course/">https://www.udemy.com/course/mlflow-course/</a>. Entretanto, vale uma observação importante: grande parte do conteúdo disponível atualmente ainda é focada no uso tradicional do MLflow para Machine Learning clássico, abordando experiment tracking, model registry, deployment e monitoramento de modelos preditivos.</p><p>Esse conhecimento continua extremamente valioso, pois boa parte dos conceitos fundamentais permanece relevante para aplicações GenAI.</p><p>Porém, para entender a evolução do MLflow para o mundo de agentes e aplicações baseadas em LLMs, recomendo o seguinte vídeo:</p><p><a href="https://www.youtube.com/watch?v=UezTglxJC88">https://www.youtube.com/watch?v=UezTglxJC88</a></p><p>Esse material apresenta os recursos mais recentes do MLflow GenAI, incluindo traces, spans, avaliações, judges, prompts, observabilidade e integração com agentes.</p><p>Também vale destacar o papel da Databricks nessa evolução. A Databricks foi fundada pelos criadores originais do Apache Spark e é atualmente a principal mantenedora do MLflow. Grande parte da evolução recente da plataforma para suportar aplicações GenAI, agentes e workflows inteligentes tem sido liderada pela própria Databricks, tornando o MLflow uma das principais ferramentas para observabilidade, avaliação e governança de aplicações de IA.</p><p>E ai, como tem sido o desenvolvimento de agentes no seu dia-a-dia? Deixe nos comentários e vamos trocar figurinhas =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe01cb8e3fc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring MVC vs Spring WebFlux — Como o paradigma reativo pode contribuir para alta disponibilidade…]]></title>
            <link>https://medium.com/@gustavobrandao0742/spring-mvc-vs-spring-webflux-como-o-paradigma-reativo-pode-contribuir-para-alta-disponibilidade-715eccb892bc?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/715eccb892bc</guid>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[gatling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 01:26:21 GMT</pubDate>
            <atom:updated>2024-01-22T11:06:20.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring MVC vs Spring WebFlux — Como o paradigma reativo pode contribuir para alta disponibilidade de arquiteturas escaláveis</h3><p>Todo os códigos utilizados e orientações para execução encontram-se em:<br><a href="https://github.com/gbrandao07/springboot-performance-test/tree/main">https://github.com/gbrandao07/springboot-performance-test/tree/main</a></p><h3>Introdução</h3><p>Quando se fala em uma arquitetura escalável, embora haja &quot;N&quot; abordagens e contextos que influenciam no desenho final, é muito provável que, principalmente em novos projetos, você se depare com algo similar ao desenho abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmr3x9RoRlPwJMv3TELsmw.jpeg" /></figure><p>Explicando o fluxo de maneira resumida:</p><ul><li>Aplicações clientes (mobile, desktop) se autenticam via jornada de login e obtém um access token</li><li>Em posse do access token, os clientes invocam rotas expostas em um API Gateway</li><li>O API Gateway verifica se o access token é válido e, em caso positivo, redireciona a requisição para os serviços de backend</li><li>Os serviços de backend, aqui representados por um cluster Kubernetes, processam a requisição. As aplicações podem invocar outras aplicações no cluster (cenário muito comum em uma arquitetura de BFFs), invocar API`s externas e também usar de serviços como MongoDb, Redis, MySQL, Storages, entre outros.</li></ul><p>Vamos assumir que o cluster Kubernetes está com Horizontal Pod Autoscaler (HPA) configurado para que, quando um certo consumo de CPU for atingindo, novas pods do microserviço sejam criadas.</p><p>Com isso, podemos assumir que esta arquitetura escala, dado que seria utilizado uma cloud (como AWS, Azure, GCP) com serviços gerenciados de API Gateway, Autenticador, Cluster Kubernetes, Serviços de Persistência, entre todos os outros e também fizemos a &quot;lição de casa&quot;, configurando HPA no Kubernetes para garantir que sempre tenhamos os recursos necessários para aguentar a carga.</p><p>Será que o parágrafo supracitado é veridico? Em outras palavras, será que escala mesmo e sempre teremos disponibilidade durante um pico de requisições?</p><p>Em minha experiência, pude aprender que nunca podemos assumir tal fato. A única maneira de validar esta afirmação é com a execução de testes de carga.</p><h3>Objetivos</h3><p>Em cima do contexto introdutório, o objetivo deste artigo será explorar, com foco nas aplicações backend, como será o desempenho utilizando aplicações desenvolvidas em Spring Boot com API`s bloqueantes (desenvolvimento tradicional) e uma nova proposta de API`s não-bloqueantes utilizando Spring Webflux.</p><p>Será criado um cenário completo que permita realizar testes nas aplicações em localhost, focando na criação de um cluster Kubernetes e deploy das aplicações.</p><h3>Projetos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*hyJZa8fvYIHFvHqPs9J6iw.png" /></figure><p><strong>springboot-api</strong><br>Projeto Spring Boot expondo dois endpoints, um bloqueante (Spring MVC) e outro não-bloqueante (Spring WebFlux). Esses endpoints invocarão uma API externa de previsão do tempo mockada pelo Wiremock.</p><p><strong>wiremock<br></strong>Contém o arquivo de response para simular o retorno da API externa. Retorna em 2 segundos.</p><p><strong>kubernetes<br></strong>Arquivos necessários para deploy no cluster.</p><p><strong>gatling</strong><br>Contém os cenários para execução dos testes de carga.</p><p>Abaixo será detalhado os resultados dos testes de carga. Caso seja de seu interesse subir os projetos localmente para execução dos testes, as orientações e pré-requisitos encontram-se no README.md do projeto.</p><h3>Configurações no cluster</h3><p><strong>springboot-api</strong></p><ul><li>2 réplicas limitadas 1 VCore CPU e 1GB de RAM</li><li>HPA configurado com base em 50% de consumo de CPU.</li><li>Health check com timeout de 1 segundo</li></ul><p><strong>wiremock</strong></p><ul><li>4 réplicas limitadas 1 VCore CPU e 1GB de RAM</li></ul><h3>Arquitetura para execução dos testes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPqv9OH7SQwc19ViuTz9wA.jpeg" /></figure><h3>Testes de carga</h3><p>Teste de carga do Gatling para testar a API bloqueante:</p><pre><br>import io.gatling.core.Predef._<br>import io.gatling.http.Predef._<br>import scala.concurrent.duration._<br><br>class BlockingApiLoadTest extends Simulation {<br><br>  val httpConf = http<br>    .baseUrl(&quot;http://localhost:56612&quot;)<br><br>  val scn = scenario(&quot;BlockingApiLoadTestScenario&quot;)<br>    .exec(http(&quot;GetRequest&quot;)<br>    .get(&quot;/weather?cityCode=011&quot;))<br><br>  setUp(<br>    scn.inject(<br>      atOnceUsers(500)<br>    ).protocols(httpConf)<br>  )<br>}</pre><p>Teste de carga do Gatling para testar a API não-bloqueante (reativa):</p><pre>import io.gatling.core.Predef._<br>import io.gatling.http.Predef._<br>import scala.concurrent.duration._<br><br>class ReactiveApiLoadTest extends Simulation {<br><br>  val httpConf = http<br>    .baseUrl(&quot;http://localhost:56612&quot;)<br><br>  val scn = scenario(&quot;ReactiveApiLoadTestScenario&quot;)<br>    .exec(http(&quot;GetRequest&quot;)<br>    .get(&quot;/weather-reactive?cityCode=011&quot;))<br><br>  setUp(<br>    scn.inject(<br>      atOnceUsers(500)<br>    ).protocols(httpConf)<br>  )<br>}</pre><p>Os cenários injetam 500 usuários simultâneos.</p><p><strong>Execução — API Bloqueante</strong></p><p>Cluster e aplicações antes do teste:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpd58Y6KsPD6tDM0Z7gZMA.png" /></figure><p>Cluster durante e após o teste:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Nu7SWOUt6p78SbSNcbTrw.png" /></figure><p>Relatório Gatling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YVkUO5gZFo-biu5WQlXmXQ.png" /></figure><p>É possível perceber que houve um rápido esgotamento de threads, de maneira que o Kubernetes não conseguiu obter resposta no endpoint de health check e reiniciou todas as pods, ocasionado indisponibilidade total do microserviço.</p><p>Highlights:</p><ul><li>71% das requisições falharam</li><li>Throughput baixo, apenas 11 requisições por segundo</li><li>42 segundos para execução dos testes</li><li>Indisponibilidade nos serviços</li><li>HPA não ativado</li></ul><p><strong>Execução — API Não-bloqueante (reativa)</strong></p><p>Cluster e aplicações antes do teste:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D1odEBXAmWTSYJSJrNgK0Q.png" /></figure><p>Cluster durante e após o teste:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PT9M7gB0_3XtHjBP7GE8Pg.png" /></figure><p>Relatório Gatling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSq8cyDGM6R9BXTFEvmWTw.png" /></figure><p>Highlights:</p><ul><li>Apenas 3% das requisições falharam</li><li>Throughput alto, 50 requisições por segundo</li><li>9 segundos para execução dos testes</li><li>Disponibilidade nos serviços</li><li>HPA não ativado</li></ul><h3>Conclusão</h3><p>Programação reativa com Spring Webflux não é uma bala de prata. Seu uso deve ser ponderado e avaliado ao contexto e necessidade. Insere complexidade e pontos de atenção a mais do que no desenvolvimento com Spring MVC.</p><p>Contudo, em cenário onde recursos externos fora do nosso controle são chamados, podemos evitar que nosso cliente tenha indisponibilidade devido a esgotamento de threads durante alta carga de requisições.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=715eccb892bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[EN-US] Clean Architecture — Improving development performance, activities parallelism and…]]></title>
            <link>https://medium.com/@gustavobrandao0742/en-us-clean-architecture-improving-development-performance-activities-parallelism-and-741f3b451265?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/741f3b451265</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 21:43:43 GMT</pubDate>
            <atom:updated>2023-04-16T21:53:13.884Z</atom:updated>
            <content:encoded><![CDATA[<h3>[EN-US] Clean Architecture — Improving development performance, activities parallelism and technical training of people</h3><p><strong><em>Confira a versão em PT-BR aqui</em></strong><em>: </em><a href="https://medium.com/@gustavobrandao0742/pt-br-clean-architecture-acelerando-o-desenvolvimento-paralelismo-de-atividades-e-forma%C3%A7%C3%A3o-15c6351d7f3e"><em>https://medium.com/@gustavobrandao0742/pt-br-clean-architecture-acelerando-o-desenvolvimento-paralelismo-de-atividades-e-forma%C3%A7%C3%A3o-15c6351d7f3e</em></a></p><h3>Introduction</h3><p>This article applies to Architects, Tech Leads and developers who work in the technical grooming of demands in the <em>UpStream</em> flow. However, I strongly recommend it to all developers in order to improve knowledge and contribute to their own carrear development.</p><h3>Prerequisites</h3><p>There are no prerequisites for reading this article, although a minimum knowledge of those presented below is recommended:</p><ul><li>Object Orientation (O.O)</li><li>Java (<em>all code examples will be written in Java</em>)</li><li><a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a></li><li><a href="https://www.amazon.com.br/Domain-Driven-Design-Eric-Evans/dp/8550800651">Domain Driven Design (<em>DDD</em>)</a></li><li>Unit Testing using the <a href="https://martinfowler.com/bliki/GivenWhenThen.html">Given/When/Then</a> standard. (<em>all tests will be written using this standard</em>)</li></ul><p>NOTE: project source code available in: <a href="https://github.com/gbrandao07/users-service-api">https://github.com/gbrandao07/users-service-api</a></p><h3>Context</h3><p>Software development is extremely hard and involves several challenges. Some of them are:</p><ul><li>Understanding the need and validate it with <em>Stakeholders</em></li><li>Finding the smallest <em>MVP</em> that allows activating value in the shortest possible time to validate ideias before making the decision to invest in a complete solution</li><li><em>How far you, who work in technical grooming, “advance” in the implementation before making it available to the team in the DownStream flow</em></li><li><em>Determine the largest number of small, parallelizable stories among the developers on the development team</em></li></ul><p>We will explore the last two.</p><h3>The need</h3><p>Let’s take as an example a demand involving a user registration. Below are the requirements:</p><ul><li>The system must have a register functionality.</li><li>It must ask for CPF, email, name, gender, phone, age and document photo.</li><li>It must have a mechanism to ensure that the request is not performed by automated software.</li><li>Only users with CPF without financial restrictions should be approved.</li><li>Only users of legal age should be approved.</li><li>It must validate that the data provided are the same as those present in the document photo.</li><li>A welcome email should be sent to the successfully registered user.</li><li>The registration must be asynchronous, that is, it must not “hold” the user on the screen until the processing is done.</li></ul><h3><em>How far you, who work in technical grooming, “advance” in the implementation before making it available to the team in the DownStream flow</em></h3><p>Let’s forget ourselves from the <em>frontend</em> development registration screen and focus on the development of the <em>backend</em> microservice responsible for registering the user, executing all validations.</p><p>Would the above list of requirements be enough for the team to start development?</p><p>To answer this question, let’s imagine that the developer would work on a story to validate whether the CPF has financial restrictions. Some questions may begin to arise in this developer, for example:</p><ul><li>Where should I create the rules?</li><li>Where my code will be used?</li><li>What objects should I receive in parameters and what type of object should I return?</li><li>Which signatures and methods should be implemented?</li><li>Which exceptions should be thrown and which ones should I handle?</li><li>Log standards?</li><li>From where should I begin?</li></ul><p>These are just some of the questions I’ve heard during my career and, based on that, as part of my professional evolution as an Architect, I would answer “<em>No, the above requirements list is not enough for the team to start development</em>” and I would invest more time in Grooming, producing the following output as <em>DoR (Definition of Ready) </em>for the team to start development:</p><ul><li><em>Clean Architecture </em>project complete documentation</li><li><em>Entities</em> and <em>UseCases</em> layers with 100% unit testing coverage</li></ul><h3><em>Clean Architecture </em>project complete documentation</h3><p>For those unfamiliar with Clean Architecture concepts, I recommend reading my other article “<a href="https://medium.com/@gustavobrandao0742/exploring-the-clean-architecture-8bfbb4c54730"><em>Exploring the Clean Architecture</em></a>” before continuing, as it is explored in detail about this pattern there.</p><p>( <em>I will assume that you already have knowledge on the subject or that you have read the article I recommend above =]</em> )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*SESjNLUVMpBI8eT-.png" /><figcaption>Clean Archicteture layers</figcaption></figure><p>The first step is to determine the <em>Entities</em> and if there are any. For our case, a possible entity would be “<em>User</em>”, given that we are talking about users and this is an object that could be used by other projects, areas, that is, it is not exclusive to our application (it is <em>enterprise</em>). Implement in this object the requirements that refer to the user.</p><p>Below is the modeling proposal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ZXUdTQXpjVPelZoMrUPhnQ.png" /><figcaption>Entity layer implementation</figcaption></figure><p>Here we have the <em>User Entity</em> containing the necessary attributes along with the <em>isValid</em> business method performing the following validations:</p><ul><li>if the age is filled in and if it is equal to or greater than 18 (legally age in Brazil)</li><li>if the other values are filled</li></ul><p>An <em>Enum</em> was created to map the values referring to the genre so as not to save the value in a common String.</p><p>The rest of the boilerplate code (<em>Constructor, Getters, Equals, Hashcode, ToString, etc</em>) are not represented in the diagram, but should be present in the implementation.</p><p>The second step is to determine the Use Case (business rules specific to our application). For this scenario, a good option would be “<em>CreateNewUserUseCase</em>”.</p><p>Each requirement (which did not apply to <em>User Entity</em>) will be a validation that this use case must contemplate and we must focus on the business rule itself and not on the details (<strong>that is, “what” should be done and not “how”</strong>). Whenever we need the “how” we will use <em>Gateways</em> (which are nothing more than java interfaces defining contract methods).</p><p>Below are the steps used to arrive at the modeling of the <em>“Use cases”</em> layer:</p><ul><li>First define the <em>Use Case</em>, represented by the <em>CreateNewUserUseCase</em> class.</li><li>Define a public method called “<em>execute</em>” (“<a href="https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html"><em>Screaming Architecture</em></a>” principle, where the class must refer to its responsibility by name). This method must receive a <em>RequestModel</em> and return a <em>ResponseModel</em>. The <em>RequestModel</em> must have all the necessary attributes for the execution of the <em>Use Case </em>business rules. There should be only this public method (<a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principle</a>).</li><li>For each business rule that involves details (external integrations, database use, messaging, frameworks, etc.) we must use <em>gateways</em> (interfaces) defining “<em>what should be done</em>” and not “<em>how it should be done</em>”.</li></ul><p>Below is the modeling proposal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9FZjYtlUg610EY0PeOQBQ.png" /><figcaption>Use Cases layer implementation</figcaption></figure><p>Completed modeling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAimMGqHO_Cmj_2fxrRkrA.png" /><figcaption>Entities and Use Cases layers implementation</figcaption></figure><h3>Entities and UseCases layers with 100% unit testing coverage</h3><p>In this step, the Architect must implement, based on the final Modeling diagram, the <em>Entity</em> and <em>UseCases</em> layers, already implemeting the unit tests and creating the objects that will be used as <em>RequestsModels</em> and <em>ResponsesModels</em> by the<em> Use Case </em>and also by the various <em>Gateways</em>. The amount of time invested in this step should not be too long, as the Architect will only focus on the flow of business rules and not on the details.</p><p>A good cutoff point for this step is to finish by making the Gateway implementation classes available in the <em>adapters</em> layer and commenting in the body of the method what should be done (saying which story, which library, etc. should be included).</p><h4>Entity layer implementation</h4><p>Let’s create the objects in the correct compilation sequence. The first one will be an <em>Enum</em> with the values for the gender of the user to register:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99b728adac212fa0ebe9133fa911eefa/href">https://medium.com/media/99b728adac212fa0ebe9133fa911eefa/href</a></iframe><p>A simple <em>Enum</em> with the values and a method of converting a text to one of the mapped values.</p><p>Now the <em>User Entity </em>will be created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0fbc018daedb56687fc3e9b7b975437/href">https://medium.com/media/d0fbc018daedb56687fc3e9b7b975437/href</a></iframe><p>A <a href="https://pt.wikipedia.org/wiki/Plain_Old_Java_Objects">POJO (<em>Plain Old Java Object</em>)</a> class mapping the attributes that make up a user to register. Assigning values should only be done during object creation via the constructor, that is why attributes are “<em>final</em>” and there are only <em>getters</em>. The only <em>enterprise</em> business rule is represented by the “<em>isValid</em>” method in order to validate whether the values entered during object creation refer to a valid user for our business. The scope of the validation is to ensure that the required values are filled in and that the age is greater than or equal to 18 years old. The rest of the code is “boilerplate” that could be replaced using <em>Lombok</em> (here I chose not to use it because, despite being simple, <em>Lombok</em> characterizes an external code and we shouldn’t have external codes in our <em>domain</em> layers).</p><p>Then, the unit tests implementation to validate that our <em>User Entity</em> is behaving as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8c134b5cf4442b380471f490c7c2176/href">https://medium.com/media/c8c134b5cf4442b380471f490c7c2176/href</a></iframe><p>Here we are validating the <em>enterprise</em> business rule represented by the “<em>isValid</em>” method.</p><p>I hope you can realize how simple it is to validate, with unit tests, your <em>Entity</em> layer.</p><p>A good sign that this layer is correctly implemented is the absence of “<em>mocks</em>” in the tests.</p><p>When analyzing test coverage, we get 100%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Xzx4-EUtGxgjXZJwzGM0YQ.png" /></figure><p>We are ready to implement the next layer, containing the application business rules, represented by <em>UseCases.</em></p><h4>UseCases layer implementation</h4><p>Let’s start by creating the <em>Models</em> to used by the <em>UseCase</em>.</p><p>Below is the proposal for the <em>RequestModel</em>. It is very similar to <em>User Entity</em>, however the goals are different. Here the objective is to map the request coming from whoever is going to call <em>UseCase</em> in a format that it can understand. Note that the fields are mapped as String and that there are no business rules, unlike the <em>User Entity</em> (“<em>False duplicity</em>” principle).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f4bee51274c148a2e9a1f2bd6a6439/href">https://medium.com/media/c8f4bee51274c148a2e9a1f2bd6a6439/href</a></iframe><p>Here is a proposal for the <em>ResponseModel</em>. I particularly enjoy <em>Response’s</em> approach to indicate whether the processing was successful and, in case of error, generate a message. This will allow whoever is calling <em>UseCase</em> to make decisions on how to format the presentation layer based on the values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3527d4e20eaae1ef6f88f4aad0fe7ff/href">https://medium.com/media/f3527d4e20eaae1ef6f88f4aad0fe7ff/href</a></iframe><p>The models for <em>Gateways</em> follow the same pattern. <em>RequestModels</em> map the attributes to be used. Modeling this way is a good practice and connects with <em>Domain Driven Design (DDD)</em> concepts, where through well-structured object types it is easier to understand what a certain object is about. The <em>ResponseModels</em> follow the same structure as the <em>Response</em> mapped to the <em>UseCase</em>. The difference here is, in this case, who will use the information to make decisions on how to direct the business flow is <em>UseCase</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/911210366e2cdb833c4358c38cbacf59/href">https://medium.com/media/911210366e2cdb833c4358c38cbacf59/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ff41acbebdd9f2e53dc34de1e9e78e9/href">https://medium.com/media/8ff41acbebdd9f2e53dc34de1e9e78e9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44d02d4bb2fa5b4b9e3fea2bad1e3f3/href">https://medium.com/media/e44d02d4bb2fa5b4b9e3fea2bad1e3f3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7584ad4aed35faa5ffc93d0e54d1fe76/href">https://medium.com/media/7584ad4aed35faa5ffc93d0e54d1fe76/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a28c7c6569240f5c6dc1551fd864b1/href">https://medium.com/media/d5a28c7c6569240f5c6dc1551fd864b1/href</a></iframe><p>Below is the <em>Gateways</em> mapping. They are simple Java interfaces defining “what must be done” and not “how” (<em>Dependency Inversion</em>). This will make it easier for us to validate our application’s business rules without depending on the details, for example, at this moment I don’t care which integration will be used to validate if the CPF has restriction. This is easily validated with mocks in unit tests. The focus here is to determine how the application should behave in terms of the request and response return.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19e3be5aada713d08b122cbf30dc0ce3/href">https://medium.com/media/19e3be5aada713d08b122cbf30dc0ce3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8be338e1b85b07826479181ca6307e0a/href">https://medium.com/media/8be338e1b85b07826479181ca6307e0a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86bcadd1f5a45538171b81560f108eeb/href">https://medium.com/media/86bcadd1f5a45538171b81560f108eeb/href</a></iframe><p>Let’s unify everything? Below the complete implementation for the <em>UseCase</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee16263f0a38bc6ae00aa2f96c9ab19d/href">https://medium.com/media/ee16263f0a38bc6ae00aa2f96c9ab19d/href</a></iframe><p>Let’s explain step-by-step what is going on in the above code.</p><pre>Integer age = requestModel.getAge() == null || requestModel.getAge().isEmpty() ? 0 : Integer.parseInt(requestModel.getAge());<br>User user = new User(<br>        requestModel.getId(),<br>        requestModel.getCpf(),<br>        requestModel.getEmail(),<br>        requestModel.getName(),<br>        Gender.fromString(requestModel.getGender()),<br>        age,<br>        requestModel.getDocUrl()<br>);</pre><pre>if (!user.isValid()) {<br>    throw new BadUserException(&quot;User Data is invalid: &quot; + user);<br>}</pre><p>In the snippet above, an <em>User Entity</em> object is created mapping what came from the request of who would call this <em>UseCase.</em> Next, it is checked if the User is valid and an exception is thrown that will prevent the continuity of the business flow if it is invalid.</p><p>It contemplates the requirements:</p><ul><li>It must ask for CPF, email, name, gender, phone, age and document photo.</li><li>Only users of legal age should be approved.</li></ul><pre>CpfVerifierRequestModel cpfVerifierRequestModel = new CpfVerifierRequestModel(requestModel.getCpf());<br>CpfVerifierResponseModel cpfVerifierResponseModel = cpfVerifierGateway.verify(cpfVerifierRequestModel);<br>if (!cpfVerifierResponseModel.isSucceeded()) {<br>    throw new CouldNotVerifyCpfException(&quot;Could not verify CPF: &quot; + cpfVerifierResponseModel.getErrorMessage());<br>}</pre><p>In the snippet above, a <em>RequestModel</em> is created for the CPF checker using the <em>RequestModel</em> value from <em>UseCase</em>. Next, a Gateway is called and the result stored in a <em>ResponseModel</em>. If a problem occurs, an exception is thrown with a message of what happened and the business flow is not continued.</p><p>This section includes the requirement:</p><ul><li>Only users with CPF without financial restrictions should be approved.</li></ul><p>The same idea applies to the others:</p><pre>DocumentValidatorRequestModel documentValidatorRequestModel = new DocumentValidatorRequestModel(requestModel.getDocUrl());<br>DocumentValidatorResponseModel documentValidatorResponseModel = documentValidatorGateway.verify(documentValidatorRequestModel);<br>if (!documentValidatorResponseModel.isSucceeded()) {<br>    throw new CouldNotValidateDocumentException(&quot;Could not validate document: &quot; + documentValidatorResponseModel.getErrorMessage());<br>}</pre><p>This section includes the requirement:</p><ul><li>It must validate that the data provided are the same as those present in the document photo.</li></ul><pre>EmailSenderRequestModel emailSenderRequestModel = new EmailSenderRequestModel(&quot;cadastro@test.com&quot;, requestModel.getEmail(), &quot;Some subject!&quot;, &quot;Some text!&quot;);<br>EmailSenderResponseModel emailSenderResponseModel = emailSenderGateway.verify(emailSenderRequestModel);<br>if (!emailSenderResponseModel.isSucceeded()) {<br>    throw new CouldNotSendEmailException(&quot;Could not send email: &quot; + emailSenderResponseModel.getErrorMessage());<br>}</pre><p>This section includes the requirement:</p><ul><li>A welcome email should be sent to the successfully registered user.</li></ul><p>At the end, an <em>UseCase</em> <em>ResponseModel</em> will be returned according to the result. This will allow the caller of <em>UseCase </em>to make the best decision on how to present the result to the user:</p><pre>return new NewUserResponseModel(true, &quot;&quot;);</pre><pre>return new NewUserResponseModel(false, e.getMessage());</pre><p>NOTE: <em>Exceptions</em> were created for the error cases. All follow the same standards. For example:</p><pre>package com.brandao.users.usecase.exception;</pre><pre>public class CouldNotSendEmailException extends Exception {</pre><pre>    public CouldNotSendEmailException(String cause) {<br>        super(cause);<br>    }<br>}</pre><p>Then, the implementation of unit tests to validate that our <em>Use Case</em> is behaving as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92ce45a646868b32fba52dec6a606c3c/href">https://medium.com/media/92ce45a646868b32fba52dec6a606c3c/href</a></iframe><p>See how simple it is to validate <em>UseCase</em> through unit tests. The big idea here is to “<em>mock</em>” (in this layer we can and should have <em>mocks</em>) the <em>Gateway’s</em> implementation defining how the real implementations should behave for each scenario.</p><p>The tests, in addition to guaranteeing the <em>UseCase</em> stability, will serve as inputs for the <em>Gateway’s</em> implementations in the <em>Adapters</em> layer, as it is already defined how to use, what to pass and how to handle returns for all scenarios.</p><p>When analyzing test coverage, we get 100%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*d_lk3NQZSombhnqsdOdKOQ.png" /></figure><p>The remaining requirements below I would define in the <em>Adapters</em> layer, validating the response from, for example, Google reCAPTCHA, to meet the first requirement and configure a messaging client as an entrypoint to meet the second requirement:</p><ul><li>It must have a mechanism to ensure that the request is not performed by automated software.</li><li>The registration must be asynchronous, that is, it must not “trap” the user on the screen until the processing is carried out.</li></ul><h3>Final project structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*HffOEbV49npwIhc3qaj3aA.png" /></figure><p>This is a great output to start the planning with the team. Notice the adapters already created. It is in their implementation that the team must act.</p><p>Example implementation of <em>DocumentValidatorByAIDataProvider</em>.</p><pre>public class DocumentValidatorByAIDataProvider implements DocumentValidatorGateway {</pre><pre>    @Override<br>    public DocumentValidatorResponseModel verify(DocumentValidatorRequestModel requestModel) {<br>        // TODO implement feature<br>        return new DocumentValidatorResponseModel(true, &quot;&quot;);<br>    }<br>}</pre><p>For this example demand, we could choose to use a validator by artificial intelligence. And notice how easy it would be to switch to another (<em>“Ports and Adapters” Mindset</em>) without changing the business rules present in <em>Entities</em> and <em>UseCases</em>.</p><h3>Conclusion</h3><p>Note that the result of this work facilitates the breaking of stories and guarantees parallelism, given that each <em>Adapter</em> can be implemented by a developer and he will already have all the necessary information to do so.</p><p>At the time of planning, contextualize the demand and direct the alignments over the execution of the unit tests present in <em>Entities and UseCases</em> and focusing on the implementations that the <em>adapters</em> must contemplate to guarantee the correct functioning of the <em>UseCase</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=741f3b451265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[PT-BR] Clean Architecture — Acelerando o desenvolvimento, paralelismo de atividades e formação…]]></title>
            <link>https://medium.com/@gustavobrandao0742/pt-br-clean-architecture-acelerando-o-desenvolvimento-paralelismo-de-atividades-e-forma%C3%A7%C3%A3o-15c6351d7f3e?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c6351d7f3e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Sun, 16 Apr 2023 21:43:09 GMT</pubDate>
            <atom:updated>2023-04-16T21:46:48.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>[PT-BR] Clean Architecture — Acelerando o desenvolvimento, paralelismo de atividades e formação técnica de pessoas</h3><p><strong><em>Check EN-US Version here</em></strong><em>: </em><a href="https://medium.com/@gustavobrandao0742/en-us-clean-architecture-improving-development-performance-activities-parallelism-and-741f3b451265"><em>https://medium.com/@gustavobrandao0742/en-us-clean-architecture-improving-development-performance-activities-parallelism-and-741f3b451265</em></a></p><h3>Introdução</h3><p>Este artigo se aplica para Arquitetos, Tech Leads e desenvolvedores que atuam no refinamento técnico de demandas no fluxo <em>UpStream</em>. Entretanto, recomendo fortemente a leitura para todos os desenvolvedores, a fim de obter conhecimentos e contribuir com a aceleração do seu crescimento.</p><h3>Pré-requisitos</h3><p>Não há pré-requisitos para a leitura deste artigo, embora recomenda-se conhecimento mínimo nos tópicos abaixo:</p><ul><li>Orientação a Objetos</li><li>Java (<em>todos os exemplos de implementação serão feitos em Java</em>)</li><li><a href="https://en.wikipedia.org/wiki/SOLID">SOLID</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a></li><li><a href="https://www.amazon.com.br/Domain-Driven-Design-Eric-Evans/dp/8550800651">Domain Driven Design (<em>DDD</em>)</a></li><li>Testes unitários utilizando o padrão <a href="https://martinfowler.com/bliki/GivenWhenThen.html">Given/When/Then</a> (<em>todos os testes serão feitos utilizando este padrão</em>)</li></ul><p>OBS: código-fonte do projeto em disponível em: <a href="https://github.com/gbrandao07/users-service-api">https://github.com/gbrandao07/users-service-api</a></p><h3>Contexto</h3><p>Desenvolvimento de software é algo extremamente complexo que envolve diversos desafios. Alguns deles:</p><ul><li>Entendimento da necessidade e validação com os <em>Stakeholders</em></li><li>Encontrar o menor <em>MVP</em> que permita ativar valor no menor tempo possível para validar hipóteses antes de realizar um investimento maior para uma solução completa</li><li><em>O quanto você, que atua no refinamento técnico, “avança” na implementação antes de disponibilizar ao time no fluxo DownStream</em></li><li><em>Determinar o maior número de histórias pequenas e paralelizáveis entre os desenvolvedores do time</em></li></ul><p>O foco deste artigo será explorar sobre os dois últimos.</p><h3>A necessidade</h3><p>Vamos tomar como exemplo uma demanda envolvendo um cadastro de usuários. Segue abaixo os requisitos:</p><ul><li>O sistema deve ter uma funcionalidade de cadastro.</li><li>Deverá pedir CPF, email, nome, sexo, telefone, idade e foto do documento.</li><li>Deverá ter um mecanismo que permita garantir que a requisição não seja realizada por um software automatizado.</li><li>Apenas usuários com CPF sem restrição financeira deverão ser aprovados.</li><li>Apenas usuários maiores de idade deverão ser aprovados.</li><li>Deverá ser validado se os dados informados são os mesmos presentes no documento.</li><li>Deverá ser enviado um email de boas vindas para o usuário cadastrado com sucesso.</li><li>O cadastro deverá ser assíncrono, ou seja, não deverá “prender” o usuário na tela até que o processamento seja realizado.</li></ul><h3>O quanto você, que atua no refinamento técnico, “avança” na implementação antes de disponibilizar ao time no fluxo DownStream</h3><p>Vamos nos abstrair no desenvolvimento <em>frontend</em> da tela de cadastro e focar no desenvolvimento do microserviço de <em>backend</em> responsável por realizar o cadastro executando todas as validações.</p><p>A lista de requisitos acima já seria o suficiente para o time iniciar o desenvolvimento?</p><p>Para responder essa pergunta vamos imaginar que o desenvolvedor iria atuar em uma história para validar se o CPF possuí restrição financeira. Alguns pontos de dúvida podem começar a surgir nesse desenvolvedor, por exemplo:</p><ul><li>Onde criar as regras?</li><li>Onde o meu código será chamado?</li><li>Quais objetos devo receber em parâmetros e qual tipo de objeto devo retornar?</li><li>Quais assinaturas e métodos devem ser implementados?</li><li>Quais exceções devem ser lançadas e quais devem ser tratadas?</li><li>Quais padrões para logs?</li><li>Por onde começo?</li></ul><p>Estas são só apenas algumas das perguntas que já ouvi durante minha carreira e, com base nisso, fazendo parte da minha evolução profissional como Arquiteto, eu responderia “<em>Não, a lista de requisitos acima não é suficiente para o time iniciar o desenvolvimento</em>” e investiria mais tempo em Refinamento, produzindo o seguinte output como <em>DoR</em> (<em>Definition of Ready</em>) para o time iniciar o desenvolvimento:</p><ul><li>Modelagem completa da aplicação com <em>Clean Architecture</em></li><li>Implementação das layers <em>Entities</em> e <em>UseCases</em> com 100% de cobertura de testes unitários</li></ul><h3>Modelagem com Clean Architecture</h3><p>Para quem não tem conhecimentos sobre Clean Architecture, recomendo que leia meu outro artigo “<a href="https://medium.com/@gustavobrandao0742/exploring-the-clean-architecture-8bfbb4c54730"><em>Exploring the Clean Architecture</em></a>” antes de continuar, pois lá é explorado no detalhe sobre este padrão.<br><em>( Vou assumir como premissa que você já tem conhecimentos sobre o tema ou que tenha lido o artigo que recomendei acima =] )</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UoLJEi_0q8gXh72l.png" /><figcaption>Layers da Clean Archicteture</figcaption></figure><p>A primeira etapa é determinar as <em>Entities</em> e se há alguma. Para o nosso caso, uma possível entidade seria “<em>User</em>”, dado que estamos falando sobre usuários e este é um objeto que poderia ser utilizado por outros projetos, áreas, ou seja, não é exclusivo da nossa aplicação (ele é <em>enterprise</em>). Implementar neste objeto os requisitos que remetam ao usuário.</p><p>Abaixo a proposta de modelagem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ZXUdTQXpjVPelZoMrUPhnQ.png" /><figcaption>Implementação da layer Entity</figcaption></figure><p>Aqui temos a <em>Entity User</em> contendo os atributos necessários juntamente com o método de negócio <em>isValid</em> executando as seguintes validações:</p><ul><li>se a idade está preenchida e se é igual ou superior a 18</li><li>se os demais valores estão preenchidos</li></ul><p>Foi criado um <em>Enum</em> para mapear os valores referentes ao gênero para não salvar o valor em uma <em>String</em> comum.</p><p>O restante do código boilterplate (<em>Contrutor, Getters, Equals, Hashcode, ToString</em>, etc) não estão representados no diagrama, mas deverão estar presentes na implementação.</p><p>A segunda etapa é determinar o <em>Use Case</em> (regras de negócio especificas da nossa aplicação). Para este cenário, uma boa opção seria “<em>CreateNewUserUseCase</em>”.</p><p>Cada requisito (que não se aplicou a <em>Entity User</em>) será uma validação que este caso de uso deverá contemplar e devemos focar na regra de negócio em si e não nos detalhes (<strong>ou seja, “o que” deve ser feito e não “o como”</strong>). Sempre que precisarmos do “como” iremos utilizar de <em>Gateways</em> (que nada mais são do que interfaces java definindo contrato de métodos).</p><p>Segue abaixo o racional utilizado para chegar a modelagem da layer “<em>Use cases</em>”:</p><ul><li>Primeiramente definir o <em>Use Case</em>, representado pela classe <em>CreateNewUserUseCase</em>.</li><li>Definir um método público chamado “<em>execute</em>” (principio da “<a href="https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html"><em>Screaming Architecture</em></a>”, onde a classe deve remeter a sua responsabilidade pelo nome). Este método deve receber um <em>RequestModel</em> e retornar um <em>ResponseModel</em>. O <em>RequestModel</em> deve ter todos os atributos necessários para a execução das regras de negócio do <em>Use Case</em>. Deve haver apenas este método público (<a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principle</a>).</li><li>Para cada regra de negócio que envolve detalhes (integrações externas, uso de banco de dados, mensageria, frameworks, etc) devemos utilizar de <em>gateways</em> (interfaces) definindo <em>“o que deve ser feito”</em> e não o <em>“o como deve ser feito”</em>.</li></ul><p>Abaixo a proposta de modelagem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9FZjYtlUg610EY0PeOQBQ.png" /><figcaption>Implementação da layer Use Cases</figcaption></figure><p>Modelagem completa:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sAimMGqHO_Cmj_2fxrRkrA.png" /><figcaption>Implementação das layers Entities e Use Cases</figcaption></figure><h3>Implementação das layers Entity e UseCases com 100% de cobertura de testes unitários</h3><p>Nesta etapa, o Arquiteto deve implementar, com base no diagrama final da Modelagem, a layer de <em>Entity</em> e <em>UseCases</em>, já realizando os testes unitários e criando os objetos que serão utilizados em <em>RequestsModels</em> e <em>ResponsesModels</em> pelo <em>Use Case</em> e também pelos diversos <em>Gateways</em>. O tempo investido para esta etapa não deve ser muito grande, dado que o Arquiteto focará apenas no fluxo das regras de negócio e não nos detalhes.</p><p>Um bom ponto de corte para esta etapa é finalizar disponibilizando na layer de <em>adapters</em> as classes de implementações dos <em>Gateways</em> e comentar no corpo do método o que deve ser feito (dizendo qual história, qual biblioteca, etc devem ser contemplados).</p><h4>Criação da layer Entity</h4><p>Vamos criar os objetos na sequência correta de compilação. O primeiro deles será um <em>Enum</em> com os valores para o sexo do usuário a se cadastrar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99b728adac212fa0ebe9133fa911eefa/href">https://medium.com/media/99b728adac212fa0ebe9133fa911eefa/href</a></iframe><p>Um simples <em>Enum</em> com os valores e um método de conversão de um texto para um dos valores mapeados.</p><p>Agora será criado a <em>Entity User</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0fbc018daedb56687fc3e9b7b975437/href">https://medium.com/media/d0fbc018daedb56687fc3e9b7b975437/href</a></iframe><p>Uma classe do tipo <a href="https://pt.wikipedia.org/wiki/Plain_Old_Java_Objects">POJO (<em>Plain Old Java Object</em>)</a> mapeando os atributos que compõem um usuário a se cadastrar. A atribuição dos valores deve ser feita apenas durante a criação do objeto via <em>construtor</em>, por isto os atributos são “<em>final</em>” e há apenas <em>getters</em>. A única regra de negócio <em>enterprise</em> é representada pelo método “<em>isValid</em>” a fim de validar se os valores informados durante a criação do objeto remetem a um usuário válido para o nosso negócio. O escopo da validação é garantir que os valores necessários estão preenchidos e que a idade é superior ou igual a 18 anos. O restante do código é “boilerplate” que poderia ser substituído com o uso do <em>Lombok</em> (aqui optei por não usar pois, apesar de ser simples, <em>Lombok</em> caracteriza um código externo e não devemos ter códigos externos nas nossas layers de <em>domain</em>).</p><p>Em seguida, a implementação dos testes unitários para validar se a nossa <em>Entity User</em> está se comportamento da maneira esperada:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8c134b5cf4442b380471f490c7c2176/href">https://medium.com/media/c8c134b5cf4442b380471f490c7c2176/href</a></iframe><p>Aqui estamos validando a regra de negócio <em>enterprise</em> representada pelo método “<em>isValid</em>”.</p><p>Eu espero que você consiga perceber o quão simples é validar, via testes unitários, a sua layer <em>Entity</em>.</p><p>Um bom sinal que esta layer está corretamente implementada é a ausência de “<em>mocks</em>” nos testes.</p><p>Ao analisar a cobertura de testes, obtemos 100%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Xzx4-EUtGxgjXZJwzGM0YQ.png" /></figure><p>Estamos prontos para implementar a próxima layer contendo as regras de negócio da aplicação, representadas por <em>UseCases</em>.</p><h4>Criação da layer UseCases</h4><p>Vamos iniciar pela criação dos <em>Models</em> a serem utilizados pelo <em>UseCase</em>.</p><p>Abaixo a proposta para o <em>RequestModel</em>. Ele é muito similar a<em> Entity User</em>, entretanto os objetivos são diferentes. Aqui o objetivo é mapear a requisição vinda de quem for chamar o <em>UseCase</em> em um formato que o mesmo consiga entender. Note que os campos são mapeados como String e que não há regras de negócio, ao contrário da <em>Entity User (</em>principio de “<em>False duplicity</em>”).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f4bee51274c148a2e9a1f2bd6a6439/href">https://medium.com/media/c8f4bee51274c148a2e9a1f2bd6a6439/href</a></iframe><p>Segue proposta para o <em>ResponseModel</em>. Eu particularmente gosto da abordagem do <em>Response</em> indicar se o processamento ocorreu com sucesso e, em caso de erro, a mensagem gerada. Isso permitirá que quem for chamar o <em>UseCase</em> possa tomar decisões em como formatar a layer de apresentação com base nos valores.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3527d4e20eaae1ef6f88f4aad0fe7ff/href">https://medium.com/media/f3527d4e20eaae1ef6f88f4aad0fe7ff/href</a></iframe><p>Os models para os <em>Gateways</em> seguem o mesmo padrão. <em>RequestModels</em> mapeam os atributos a serem utilizados. Modelar desta forma é uma boa prática e se conecta com conceitos de <em>Domain Driven Design (DDD), </em>onde através de tipagens bem estruturadas fica mais fácil entender do que se trata determinado objeto. Já os <em>ResponseModels</em> seguem a mesma estrutura do Response mapeado para o <em>UseCase</em>. A diferença aqui é, nesse caso, quem usará as informações para tomar decisões em como direcionar o fluxo de negócio é o <em>UseCase</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/911210366e2cdb833c4358c38cbacf59/href">https://medium.com/media/911210366e2cdb833c4358c38cbacf59/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ff41acbebdd9f2e53dc34de1e9e78e9/href">https://medium.com/media/8ff41acbebdd9f2e53dc34de1e9e78e9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e44d02d4bb2fa5b4b9e3fea2bad1e3f3/href">https://medium.com/media/e44d02d4bb2fa5b4b9e3fea2bad1e3f3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7584ad4aed35faa5ffc93d0e54d1fe76/href">https://medium.com/media/7584ad4aed35faa5ffc93d0e54d1fe76/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a28c7c6569240f5c6dc1551fd864b1/href">https://medium.com/media/d5a28c7c6569240f5c6dc1551fd864b1/href</a></iframe><p>Abaixo o mapeamento dos <em>Gateways</em>. São simples interfaces Java definindo “o que deve ser feito” e não o “como” (<em>Dependency Inversion</em>). Isso nos facilitará validar nossas regras de negócio da aplicação sem depender dos detalhes, por exemplo, nesse momento não me importa qual integração será utilizada para validar se o CPF possui restrição. Isso é possível validar com mocks via testes facilmente. O foco aqui é determinar como a aplicação deve se comportar em perspectiva da requisição e do retorno.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19e3be5aada713d08b122cbf30dc0ce3/href">https://medium.com/media/19e3be5aada713d08b122cbf30dc0ce3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8be338e1b85b07826479181ca6307e0a/href">https://medium.com/media/8be338e1b85b07826479181ca6307e0a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86bcadd1f5a45538171b81560f108eeb/href">https://medium.com/media/86bcadd1f5a45538171b81560f108eeb/href</a></iframe><p>Vamos juntar tudo? Segue proposta para implementação do <em>UseCase</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee16263f0a38bc6ae00aa2f96c9ab19d/href">https://medium.com/media/ee16263f0a38bc6ae00aa2f96c9ab19d/href</a></iframe><p>Vamos explicar parcialmente o que está acontecendo nessa implementação.</p><pre>Integer age = requestModel.getAge() == null || requestModel.getAge().isEmpty() ? 0 : Integer.parseInt(requestModel.getAge());<br>User user = new User(<br>        requestModel.getId(),<br>        requestModel.getCpf(),<br>        requestModel.getEmail(),<br>        requestModel.getName(),<br>        Gender.fromString(requestModel.getGender()),<br>        age,<br>        requestModel.getDocUrl()<br>);<br><br>if (!user.isValid()) {<br>    throw new BadUserException(&quot;User Data is invalid: &quot; + user);<br>}</pre><p>No trecho acima é criado um objeto <em>Entity User</em> mapeando o que veio da requisição de quem chamaria este <em>UseCase</em>. Na sequência, é verificado se o User é valido e lançado uma exceção que vai impedir a continuidade do fluxo de negócio caso o mesmo seja inválido.</p><p>Este trecho contempla os requisitos:</p><ul><li>Deverá pedir CPF, email, nome, sexo, telefone, idade e foto do documento.</li><li>Apenas usuários maiores de idade deverão ser aprovados.</li></ul><pre>CpfVerifierRequestModel cpfVerifierRequestModel = new CpfVerifierRequestModel(requestModel.getCpf());<br>CpfVerifierResponseModel cpfVerifierResponseModel = cpfVerifierGateway.verify(cpfVerifierRequestModel);<br>if (!cpfVerifierResponseModel.isSucceeded()) {<br>    throw new CouldNotVerifyCpfException(&quot;Could not verify CPF: &quot; + cpfVerifierResponseModel.getErrorMessage());<br>}</pre><p>No trecho acima é criado um <em>RequestModel</em> para o verificador do CPF utilizando o valor vindo <em>RequestModel</em> do <em>UseCase</em>. Na sequência, o um <em>Gateway</em> é chamado e o resultado guardado em um <em>ResponseModel</em>. Caso ocorra algum problema, uma exceção é lançada com mensagem do ocorrido e o fluxo de negócio não é continuado.</p><p>Este trecho contempla o requisito:</p><ul><li>Apenas usuários com CPF sem restrição financeira deverão ser aprovados.</li></ul><p>O mesmo racional se aplica aos demais:</p><pre>DocumentValidatorRequestModel documentValidatorRequestModel = new DocumentValidatorRequestModel(requestModel.getDocUrl());<br>DocumentValidatorResponseModel documentValidatorResponseModel = documentValidatorGateway.verify(documentValidatorRequestModel);<br>if (!documentValidatorResponseModel.isSucceeded()) {<br>    throw new CouldNotValidateDocumentException(&quot;Could not validate document: &quot; + documentValidatorResponseModel.getErrorMessage());<br>}</pre><p>Este trecho contempla o requisito:</p><ul><li>Deverá ser validado se os dados informados são os mesmos presentes no documento.</li></ul><pre>EmailSenderRequestModel emailSenderRequestModel = new EmailSenderRequestModel(&quot;cadastro@test.com&quot;, requestModel.getEmail(), &quot;Some subject!&quot;, &quot;Some text!&quot;);<br>EmailSenderResponseModel emailSenderResponseModel = emailSenderGateway.verify(emailSenderRequestModel);<br>if (!emailSenderResponseModel.isSucceeded()) {<br>    throw new CouldNotSendEmailException(&quot;Could not send email: &quot; + emailSenderResponseModel.getErrorMessage());<br>}</pre><p>Este trecho contempla o requisito:</p><ul><li>Deverá ser enviado um email de boas vindas para o usuário cadastrado com sucesso.</li></ul><p>Ao final, será retornado um <em>ResponseModel</em> do <em>UseCase</em> de acordo com o resultado. Isso permitirá que quem chamou o <em>UseCase</em> possa tomar a melhor decisão em como apresentar o resultado ao usuário:</p><pre>return new NewUserResponseModel(true, &quot;&quot;);<br><br>return new NewUserResponseModel(false, e.getMessage());</pre><p>OBS: foram criadas <em>Exceptions</em> para os fluxos de erro. Todas seguem os mesmos padrões. Por exemplo:</p><pre>package com.brandao.users.usecase.exception;<br><br>public class CouldNotSendEmailException extends Exception {<br><br>    public CouldNotSendEmailException(String cause) {<br>        super(cause);<br>    }<br>}</pre><p>Em seguida, a implementação dos testes unitários para validar se o nosso <em>Use Case </em>está se comportamento da maneira esperada:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92ce45a646868b32fba52dec6a606c3c/href">https://medium.com/media/92ce45a646868b32fba52dec6a606c3c/href</a></iframe><p>Veja como é simples validar o <em>UseCase</em> através dos testes unitários. A grande sacada aqui é “<em>mockar</em>” (nesta layer podemos e devemos ter <em>mocks</em>) as implementações dos <em>Gateways</em> definindo como as implementações reais devem se comportar para cada cenário.</p><p>Os testes, além de garantir a estabilidade do <em>UseCase</em>, servirão de insumos para as implementações dos <em>Gateways</em> na <em>layer Adapters, </em>pois já está definido como usar, o que passar e como tratar retornos para todos os cenários.</p><p>Ao analisar a cobertura de testes, obtemos 100%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*d_lk3NQZSombhnqsdOdKOQ.png" /></figure><p>Os requisitos restantes abaixo eu definiria na layer <em>Adapters, </em>validando a resposta de um, por exemplo, Google reCAPTCHA, para atender o primeiro requisito e configuraria um client de mensageria como <em>entrypoint</em> para atender o segundo requisito:</p><ul><li>Deverá ter um mecanismo que permita garantir que a requisição não seja realizada por um software automatizado.</li><li>O cadastro deverá ser assíncrono, ou seja, não deverá “prender” o usuário na tela até que o processamento seja realizado.</li></ul><h3>Estrutura final do projeto</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*HffOEbV49npwIhc3qaj3aA.png" /></figure><p>Este é um ótimo output para direcionar a planning com o time. Perceba os adapters já criados. É na implementação deles que o time deverá atuar.</p><p>Exemplo da implementação do <em>DocumentValidatorByAIDataProvider.</em></p><pre>public class DocumentValidatorByAIDataProvider implements DocumentValidatorGateway {<br><br>    @Override<br>    public DocumentValidatorResponseModel verify(DocumentValidatorRequestModel requestModel) {<br>        // TODO implement feature<br>        return new DocumentValidatorResponseModel(true, &quot;&quot;);<br>    }<br>}</pre><p>Para esta demanda hipotética, optamos por usar um validador via inteligência artificial. E note como seria fácil trocar por outra (<em>“</em><a href="https://alistair.cockburn.us/hexagonal-architecture/"><em>Ports and Adapters</em></a><em>” Mindset</em>) sem alterar as regras de negócio presentes em <em>Entities e UseCases.</em></p><h3>Conclusão</h3><p>Note que o resultado desse trabalho facilita a quebra de histórias e garante o paralelismo, dado que cada <em>Adapter</em> pode ser implementado por um desenvolvedor e este já terá todas as informações necessárias para isso.</p><p>No momento da planning, contextualize a demanda e direcione os alinhamentos em cima da execução dos testes e focando nas implementações que os <em>adapters</em> deverão contemplar para garantir o correto funcionamento do <em>UseCase</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c6351d7f3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to exponentially deliver Value by uniting Architecture, Engineering and Product Strategy]]></title>
            <link>https://medium.com/@gustavobrandao0742/how-to-exponentially-deliver-value-by-uniting-architecture-engineering-and-product-strategy-4bb1550afb0d?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb1550afb0d</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 17:36:26 GMT</pubDate>
            <atom:updated>2023-01-15T17:36:26.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*XsPf1JWv9HAnQjqH.jpg" /><figcaption>Source: <a href="https://sfmagazine.com/wp-content/uploads/11-2021-TechPractices.jpg">https://sfmagazine.com/wp-content/uploads/11-2021-TechPractices.jpg</a></figcaption></figure><p>This article is intended to help Software Architects and Product Managers create ways to accelerate project value delivery. It is also recommended for software developers, as they are key elements for the successful execution of the project and, by absorbing this knowledge, understanding the importance of their role, their work excellence will be enhanced.</p><p>Gone are the days when software development was seen as something simple and trivial, and even considered as a set of individual blocks of codes at final merged and delivered as a working software.</p><p>Customer needs are constantly evolving and becoming more and more complex and these are never the same between different projects. A working model that gone well in some project will not necessarily go well in another. There’s no cake recipe or silver bullet to work out between projects. There are sets of good practices associated with Architecture, Engineering and Product that, once used in the best way for the current project, achieve the expected result.</p><h3>Mapping the context</h3><p><strong><em>“… once used in the best way for the current project</em></strong> <strong><em>…”</em></strong></p><p>The above snippet is the great challenge to be fulfilled. We often have knownledge of the good practices of Architecture, Engineering and also of Product, but it is not enough. In addition, it is necessary to understand the context of the project challenge, involving several protagonists:</p><ul><li>The company you work</li><li>Your people</li><li>Client</li><li>Leadership</li><li>The balance between “<em>Good at the right time</em>” and “<em>Great at the wrong time</em>”</li><li>Architectural Decisions</li></ul><h4>The company you work</h4><p>There are lots of software companies today, and although they all aim to deliver working software and generate revenue/profit, the meaning of delivering working software can vary between them.</p><p>It is necessary that you are aligned with the result and impact that your company wants to generate with the client and with the project.</p><p>Examples:</p><ul><li>Deliver functional software in the shortest possible time and/or cost based on a backlog given by the customer.</li><li>Delivering a new version of existing software, evolving technological and architectural stacks, in order to reduce deployment costs (Cloud, On-Premises), facilitating future maintenance and attracting qualified professionals (<em>After all, nowadays, software developer is a hard to find professional and a old stack does not attract them</em>…).</li><li>Be a partner of the client, diving into the their operation and directing efforts to change paradigms and solve key problem points in order to generate value that leads to profit for the client, improving current processes.</li></ul><p>Be aware about the values and objectives of the company you work for, as these should influence future decisions.</p><h4>Your people</h4><p>Have a mixed team, with Junior to Senior profiles. If someone tells you that, for a project to be successful, only a team of Seniors is needed, there is something to be reviewed.</p><p>It is expected that a good Software Architect and a good Product Manager will be able to create a favorable environment for learning and growth for all team profiles.</p><ul><li>Understand the profile and level of knowledge of each one</li></ul><p>Have “One-a-One” calls to understand their experiencies and map hard and soft skil</p><ul><li>Make plans</li></ul><p>Based on the outputs gathered in the “One-a-One” calls with team members, create training plans, give the team some time to minimally prepare for the challenges you already have a vision of that will come. Never let your people “stand by” (<em>we know that the beginning of projects is usually very busy for Architects and Managers and tend to be a little slow for developers until the backlogs are generated</em>), take advantage of each one’s time for target studies based on in a plan.</p><ul><li>Delegate responsibilities</li></ul><p>A big gap for Software Architects and Product Managers is to centralize many responsibilities. Delegate, instruct, trust your people. Always be around helping and giving the necessary support, but give space for people to take on challenges and evolve.</p><ul><li>Create a collaborative culture</li></ul><p>Don’t be the only reference for the team’s people, because you, Architect or Manager, will not have the necessary availability to meet all the needs of the team.</p><p>Empower your Seniors. Make them empower the Mids and the Mids empower the Juniors. If necessary, formalize reference names between profiles. Aim for the team to be able to run without always depending on you.</p><h4>Client</h4><p>Every client has an existing work model and a set of values considered ideal which, not always, will be as adherent as possible to the proposal of the company that will generate the value.</p><p>It is necessary to understand this model from the customer’s perspective and be provocative in changes, listing the benefits and always based on Architecture and Engineering as a means of promoting security and reliability in change.</p><p>For example: in all the projects I’ve worked on, there was a need for great planning for a deployment in production. A possible solution to promote the necessary trust and enable continuous deployment is the adoption of trunk-based development and having means of rapid “rollback” in cases of failure. It is important to have effective monitoring to quickly identify these cases.</p><h4>Leaderships</h4><p>Introduce yourself and meet the project leaderships, exchange experiences of projects that went well and projects that could have been better. Define the goals together and, mainly, be aligned on which means (strategic, operational and technical) will be used. It is essential that leaders are aligned and have the same mindset to achieve the expected outputs.</p><h4>The balance between “<em>Good at the right time</em>” and “Great at the wrong time”</h4><p>There is always a better solution to a given problem. Don’t aim for the best at the first moment, generate value and impact in a short time, generating results, but deliver solutions that allow you to achieve the great gradually. There’s no point in chasing what’s great and not delivering on time, but there’s also no point in delivering something fast that won’t be sustainable in the future, generating extremely high rework, technical complexity and low productivity for maintenance and additions of new features to the system.</p><h4>Architectural Decisions</h4><ul><li>Make architectural decisions based on team profile and project objective</li></ul><p>Don’t make decisions based on personal preferences (e.g <em>Java is “cooler” than DotNet</em>) or technologies that are in hype.</p><p>Make decisions based on the skills that your team has, or that you have the time to execute training plans and always take into account the nature of the project (<em>I wonder if adopting an architecture resulting in 50 microservices in Spring Boot running on an On Premises with extremely limited hardware resources in a team where the greatest skill is in Javascript and the deadline is strict is the best way? In this case, wouldn’t a monolith or set of modular monoliths with NodeJS be better options to evaluate?</em>).</p><h3>Defining the process</h3><p>“<strong><em>Process</em></strong>”: word that gives me creeps, because I’ve had experiences where the process was so extensive and complex that it created more difficulties than it helped.</p><p>However, I am against not having a process. I do believe that it is necessary, after all, if we don’t have a minimum standard to be followed, we won’t get anywhere.</p><p>The importance of the process becomes evident when we work with more than one team allocated to the same project.</p><p>The big challenge is not to aim to have teams capable of running without a defined process, but to create a lean process that promotes productivity and rapid activation of value.</p><p>Again, there is no silver bullet for defining a process, it is very likely that each context or project will need a customized process to meet its needs.</p><p>However, having a set of principles in mind coupled with understanding the context can help. These are:</p><ul><li>Fast value activation</li><li>Means for quick rollback in case of failures</li><li>Monitor the delivere djourneys</li><li>Lean flow</li><li>Avoid states in the flow that refer to waiting</li><li>Don’t push large batches of backlogs to production all at once</li><li>Track metrics (4 Key Metrics)</li><li>Manage technical debts</li><li>All team profiles should be protagonists in the flow</li><li>The story must be of the team and not of a single person</li></ul><p>Summarizing everything that was said above, I bring the following flow proposal represented by a Kanban board:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swaOqxq3ZnRNj6hGyLH05Q.png" /></figure><h4>“Up-stream” flow (before development starts)</h4><p>For a better cadence of the flow, it is recommended that a demand enter in <em>Discovery</em> at least two weeks in advance of the expectation of inserting it into the “<em>down-stream</em>” flow</p><p><strong>Discovery</strong></p><p>This stage is where the Product Owners and Managers, with the support of the Architect, materialize a business need with the demanding areas.</p><p><strong>Backlog</strong></p><p>Moment of the flow where we already have cards referring to valuable deliverables.</p><p><strong>In refinement</strong></p><p>Where demand is refined at a business and technical level. The purpose of this state is to guarantee that the development team have already defined in both perspectives what needs to be done and all possible blocks have already been removed. The set of cards in this column must be presented in planning with the technical team and, after that, continue in the flow. It is very important that the demand leaves “Ready” from this state to enter the team’s commitment point (“<em>Ready to start</em>”).</p><h4>“Down-stream” (team ready to start the development)</h4><p><strong>Ready to start</strong></p><p>Demand ready to start development. Team must self-organize and allocate the activity. Ideally, demand should be parallelizable between 2 or more developers. Preferably, a Senior/Mid acting with a Junior profile.</p><p><strong>In development</strong></p><p>Team developing, following architecture practices that allow the fast delivery of value with security, fast rollback, monitoring and quality.</p><p>Below are some items that can help to have the development result with de itens stated above:</p><ul><li>Trunk-based</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4s18U04mefMFWAwi" /><figcaption>Source: <a href="https://www.optimizely.com/contentassets/569ac3ee0b124da19a5ac9ea2e8b2b4d/trunk-based-development.png">https://www.optimizely.com/contentassets/569ac3ee0b124da19a5ac9ea2e8b2b4d/trunk-based-development.png</a></figcaption></figure><p>No more branches, countless merges and conflicts that, many times, are the cause of instabilities generated in production. Who has never heard the following sentence: “<em>Wow, my code for functionality X that had already been delivered disappeared after the merge on day Y</em>”</p><p>For teams that have never worked with trunk-based, you architect will probably face some kind of resistance from the technical team, after all, it increases the complexity of the development and the level of detail that the developer needs to work on. It is your duty to technically empower the team with DOJOs, helper materials and create appropriate guidelines for the project. Evidence the benefit added to the flow. In the beginning, be gradual, experiment with one story with a Senior or Mid profile developer and gradually increase until this paradigm is followed in full understanding of all.</p><ul><li>Automated Tests</li></ul><p>Invest in testing, but with the “<em>good on time</em>” mindset.</p><p>For new projects and teams, I recommend investing in the first two pillars in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*z7fJBct9vdZLan2z" /></figure><p>For frontend contexts, unless it is a customer/area/business demand, I would not invest in <em>end-to-end (E2E) </em>tests at first, but I would leave this in the Architecture Roadmap to prioritize in future demands, experiment in one story, evaluating results, etc.</p><p>Tests are also not trivial, so, once again, it is very important for you as an Architect to guide the team’s training.</p><p>Example of frontend tests in react contemplating the first two pillars:</p><p><a href="https://github.com/gbrandao07/gerenciador-de-estudos">https://github.com/gbrandao07/gerenciador-de-estudos</a></p><p>Example of backend tests in java contemplating the first two pillars:</p><p><a href="https://github.com/gbrandao07/the-clean-architecture">https://github.com/gbrandao07/the-clean-architecture</a></p><ul><li>Monitoring</li></ul><p>Instrument your frontend and backend applications in order to have end-to-end monitoring of journeys, enabling error analysis and rapid identification of adverse scenarios.</p><p>Some references of solutions for the theme:</p><p><a href="https://www.elastic.co/pt/observability/log-monitoring">https://www.elastic.co/pt/observability/log-monitoring</a><br><a href="https://www.datadoghq.com/">https://www.datadoghq.com/</a><br><a href="https://grafana.com/grafana/dashboards/3308-java-micrometer/">https://grafana.com/grafana/dashboards/3308-java-micrometer/</a></p><ul><li>Architectural Standards</li></ul><p>Be a Solutions Architect and not an Architect who knows very well a certain set of frameworks.</p><p>For backend projects, always aim to isolate the business domain from frameworks and other code that does not refer to the business.</p><p>Master at least one of the patterns below:</p><p><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture</a><br><a href="https://alistair.cockburn.us/hexagonal-architecture/">Hexagonal Architecture</a><br><a href="https://www.codeguru.com/csharp/understanding-onion-architecture/">Onion Architecture</a></p><p>Show the benefit to the team, highlighting the ease of implementing tests and low chance impact by adding new features.</p><p>Master microservices and monolith-modular architectures to define the most ideal one for the current project.</p><ul><li>Quality</li></ul><p>Have a code review process as automated as possible with tools like Sonar ensuring quality, test coverage.</p><p>Ensure that adopted architectural standards are being met. For java projects, <em>ArchUnit</em> can help.</p><p>Define improvement goals for each development, for example, for each cycle the team must commit to increasing X% of overall test coverage and decreasing Y code issues reported on Sonar.</p><p>Give space for all team members to perform the other developer’s code review.</p><p><strong>In deploy</strong></p><p>The developer merges into the main branch. At this point, your CI/CD must deploy to the development environment and the developer must validate that the current behavior (before the change) is still functional (<em>toggle off</em>).</p><p>After that, upon the developer’s signal in the CI/CD, the deploy must occur for the QA environments and already for the Production environment with the toggles turned off.</p><p>Note that we have continuous deployment and that at that moment the deploy was just code, as we guarantee that the behavior with toggle turned off is ok.</p><p>After that, now the developer will perform exploratory tests with toggle turned on in the development environment and ensure that the new functionality is ok.</p><p>If the developer finds bugs, the correction is made and new deploys are performed.</p><p>At the end of the card, it should go to the next column of the flow.</p><p><strong>Quality Assurance</strong></p><p>Moment that the PO and/or PM validate the new functionality in the QA environment (<em>toggle on</em>)</p><p>If there are bugs, the developer acts to correct them.</p><p>Once everything has been successfully validated, the card is ready to activate.</p><p><strong>Ready to activate</strong></p><p>Functional and validated stories in DEV and QA. The code is already in Production, but with the toggle turned off.</p><p>It is up to the PO or PM the best time to activate in Production (<em>toggle on</em>).</p><p><strong>Activated</strong></p><p>Toggle in Production turned on by PM or PO and value generated.</p><p>The PM or PO must open a technical debit to remove the toggle and the old behavior, after all, when working with trunkbased and toggles, we generate debits in the code.</p><p>A suggested time box is two weeks. In projects I worked on, I realized that the chances of encountering problems with system users and needing to turn off toggle are higher in the first two weeks after activation.</p><h3>CI/CD flow proposal</h3><p>Below is a possible CI/CD flow proposal to support the previously presented process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WgI5AO3sehcvz2Kp" /></figure><p>Note that I am not going into the technical details of implementing CI/CD. This decision is up to the Architect in support of the DevOps team, based on the nature of the project.</p><h4>Static Analysis</h4><p>Sonar running according to defined rules. Build should fail if <em>Quality Gate</em> is not met.</p><h4>Quality</h4><p>Execution of the test pyramid and validation of the minimum coverage. Build should break if one of the criteria is not met.</p><h4>Build</h4><p>The build and packaging of the application.</p><h4>Deploy to DEV</h4><p>The application is made available in the development environment.</p><p>At this point, CI/CD must await developer approval to proceed.</p><p>The goal is that the validation of the current behavior (toggle off) can be performed and, if ok, the CI/CD can continue.</p><h4>Promote</h4><p>Deployment is performed in QA and Production (remembering that toggle must be turned off).</p><p>Feel free to work with releases, creating tags and the like to keep track of deployments.</p><h3>Architectural Appendices</h3><h4>Clean Architecture</h4><p>Reference project with “CRUD” theme: <a href="https://github.com/gbrandao07/the-clean-architecture">https://github.com/gbrandao07/the-clean-architecture</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io3UdC3ewYrnj348" /><figcaption>Higher resolution link: <a href="https://drive.google.com/file/d/1UlKMDGHzb0mRJSAenpfAs1MqeVE24s8l/view?usp=share_link">https://drive.google.com/file/d/1UlKMDGHzb0mRJSAenpfAs1MqeVE24s8l/view?usp=share_link</a></figcaption></figure><p>Here is my article where I explain in more detail the theme and its benefits:</p><p><a href="https://medium.com/@gustavobrandao0742/exploring-the-clean-architecture-8bfbb4c54730">https://medium.com/@gustavobrandao0742/exploring-the-clean-architecture-8bfbb4c54730</a></p><h4>Architecture proposal to support Trunk-based</h4><p>Below is a proposal to provide an architecture to support trunkbased in order to obtain toggles in a centralized and expandable way between projects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qr8aRvq__sskbFkQ9BdrWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jOVe3-bmch8V5ocTLx-qg.png" /><figcaption>Higher resolution link: <a href="https://drive.google.com/file/d/1Sq6vhEMmWOCPwJ7gHoqzJzgF2Vx3WWzq/view?usp=share_link">https://drive.google.com/file/d/1Sq6vhEMmWOCPwJ7gHoqzJzgF2Vx3WWzq/view?usp=share_link</a></figcaption></figure><h4>Flow Details</h4><p>1- The frontend makes a request to API Gateway (with authentication)</p><p>2- The API Gateway redirects the request to the BFF that serves the frontend in question</p><p>3- BFF can call other backend services</p><p>4- BFF and backend services can determine behaviors with the use of flags, switching between current and new implementations</p><p>5- Obtaining flags is done through a centralized service, using Clean Architecture, being expandable to N technologies for hosting and managing toggles. As an example, a Clean Architecture diagram for an implementation with Unleash hosted directly in the project’s Gitlab repository is detailed.</p><h3>Conclusion</h3><p>A set of thoughts involving strategic management, people, technical knowledge was provided.</p><p>Architects and Managers must be adaptable to the context, the speed of this adaptation is what will dictate the course of success of the project.</p><p>I hope that the stories in this article based on my experiences will help you approach new projects more adaptively and can provide you with insights.</p><p>If you have any concerns, feel free to contact me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb1550afb0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring The Clean Architecture]]></title>
            <link>https://medium.com/@gustavobrandao0742/exploring-the-clean-architecture-8bfbb4c54730?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bfbb4c54730</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[uncle-bob]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[clean-arch]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Thu, 17 Nov 2022 13:32:40 GMT</pubDate>
            <atom:updated>2022-11-17T17:47:23.320Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, I hope you are doing well!<br>For some years I have been studying and applying architectural patterns in projects, especially <strong><em>The</em></strong> <strong><em>Clean Architecture</em></strong> and <strong><em>The Hexagonal Architecture</em></strong>.<br>I read various materials on the internet and had the opportunity to “<em>learn by doing</em>”.<br>Recently, I decided to invest some time to read the <a href="https://www.amazon.com.br/Clean-Architecture-Craftsmans-Software-Structure-ebook/dp/B075LRM681/ref=sr_1_6?keywords=clean+architecture&amp;qid=1668617354&amp;qu=eyJxc2MiOiIyLjIxIiwicXNhIjoiMS43NyIsInFzcCI6IjEuNjgifQ%3D%3D&amp;sr=8-6&amp;ufe=app_do%3Aamzn1.fos.6a09f7ec-d911-4889-ad70-de8dd83c8a74">book published by Uncle Bob</a> in order to strengthen the concepts and deepen the understanding.<br>I can say that the reading is extremely valuable and expands your view on very important concepts such as <a href="https://www.baeldung.com/solid-principles">S.O.L.I.D</a>, <em>Dependency</em> <em>Inversion </em>and many others.<br>The goal of ​​this post is to convert some requirements in a complete project applying <em>Clean Architecture</em> with <em>Java </em>and<em> Spring Boot</em>.</p><p>You can check in Github all the source code for the application we are going to create: <a href="https://github.com/gbrandao07/the-clean-architecture">https://github.com/gbrandao07/the-clean-architecture</a></p><h3>General Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*-annoN--Xu97xljx.png" /></figure><blockquote>Entities</blockquote><blockquote>Entities encapsulate <em>Enterprise wide</em> business rules. An entity can be an object with methods, or it can be a set of data structures and functions. It doesn’t matter so long as the entities could be used by many different applications in the enterprise.</blockquote><blockquote>Use Cases</blockquote><blockquote>The software in this layer contains <em>application specific</em> business rules. It encapsulates and implements all of the use cases of the system. These use cases orchestrate the flow of data to and from the entities, and direct those entities to use their <em>enterprise wide</em> business rules to achieve the goals of the use case.</blockquote><blockquote>Interface Adapters</blockquote><blockquote>The software in this layer is a set of adapters that convert data from the format most convenient for the use cases and entities, to the format most convenient for some external agency such as the Database or the Web. It is this layer, for example, that will wholly contain the MVC architecture of a GUI. The Presenters, Views, and Controllers all belong in here. The models are likely just data structures that are passed from the controllers to the use cases, and then back from the use cases to the presenters and views.</blockquote><blockquote>Frameworks and Drivers.</blockquote><blockquote>The outermost layer is generally composed of frameworks and tools such as the Database, the Web Framework, etc. Generally you don’t write much code in this layer other than glue code that communicates to the next circle inwards.</blockquote><p>Source: <a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html</a></p><h3>Setup</h3><ul><li>Project template generated by <a href="https://start.spring.io/">Spring Initializr</a></li><li>Java 8 or higher</li><li>Maven 3.6 or higher</li><li>Java IDE, e.g. IntelliJ</li><li>Lombok</li></ul><h3>The application</h3><p>We will be developing an application to create tasks.</p><blockquote><strong>Requirements:</strong><br>1- The task start date should not be less than actual date<br>2- The system receives the tasks name and start date,<br>validates if the task doesn’t exist, and saves the new task along with the creation time</blockquote><p>With the requirements defined, the first step is to identify the <strong><em>enterprise business rules</em></strong> and the <strong><em>application business rules</em></strong>.</p><p>The first requirement is an <strong><em>enterprise business rule</em></strong>, because it can be reused by other applications and systems. It is a strong entity that is not exclusively of our application.</p><p>The second requirement refers to an application use case, so it is an<strong><em> application business rule</em></strong>.</p><p>That said, we know that the first requirement should be implemented in the “<em>Entity</em>” layer, the purest one of our application and without dependence on any other. Note that, if there is a future need, other applications can use this layer, as the rules are not specific to our application’s use case. The second requirement should be implemented in the “<em>Use Case</em>” layer, as explained previously.</p><p>Both “<em>Entity</em>” and “<em>Use Case</em>” layers are our business layer, the core of the application, so they must be independent of frameworks and details. For these layers, it should not matter which database will be used, if there will be an external integration, among others. Every time we need these details, we will use <em>Gateways</em> (<em>interfaces</em>).</p><h3><strong>“Entity” layer implementation</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4168c7c8230c946785c1b30446719c9/href">https://medium.com/media/b4168c7c8230c946785c1b30446719c9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62c714b541be674eb5d541fda630cd23/href">https://medium.com/media/62c714b541be674eb5d541fda630cd23/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a73e53d519fc4a27e41fc95886704930/href">https://medium.com/media/a73e53d519fc4a27e41fc95886704930/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aebd0b52b267e9b40a5bd855a4d0c13/href">https://medium.com/media/0aebd0b52b267e9b40a5bd855a4d0c13/href</a></iframe><p>Considerations:</p><ul><li>I will be using Lombok in this layer and all the others just to make the code easier to read, because it automatically generates boilerplate codes (constructors, getters, setters, etc).</li><li>The first requirement has been met.</li><li>When using a <em>Task</em> interface, there is the possibility of specifying different types of <em>Tasks</em>, currently we only needed to specify the <em>CommonTask</em>.</li></ul><p>Package structure for “<em>Entity</em>” layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*DfBPrdprdFqUN6BfYd6Y_w.png" /></figure><h3><strong>“Entity” layer tests</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d84256fd946154b8a047d87cb09350c7/href">https://medium.com/media/d84256fd946154b8a047d87cb09350c7/href</a></iframe><p>I hope you can realize that it is very easy to validate the business rules. A good sign that your “<em>Entity</em>” layer is well structured is the absence of “<em>Mock</em>” objects in the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*jnyDJKqMxvPIiMp9iOKKKQ.png" /><figcaption>100% coverage</figcaption></figure><h3><strong>“Use Case” layer implementation</strong></h3><p>Let’s implement the <strong><em>application business rules</em></strong> (second requirement):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11b19f0acaf064a6a181171cb6767cd5/href">https://medium.com/media/11b19f0acaf064a6a181171cb6767cd5/href</a></iframe><p><em>TaskCreateInputBoundary</em> is the contract representing the use case for creating a task. It is this contract that will be injected for use in the higher layers. Ideally, each <em>InputBoundary</em> specifies only one function that refers to its scope (<em>Single Responsibility principle</em> and <a href="https://blog.cleancoder.com/uncle-bob/2011/09/30/Screaming-Architecture.html"><em>Screaming Architecture</em></a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8d67b5a2d681c65d459c16a5e5e67fa/href">https://medium.com/media/e8d67b5a2d681c65d459c16a5e5e67fa/href</a></iframe><p><em>TaskRegisterInteractor</em> is the <em>InputBoundary </em>implementation.</p><p>Considerations:</p><pre>if (taskDsGateway.existsByName(requestModel.getName())) {<br>    return taskPresenter.prepareFailView(&quot;Task already exists.&quot;);<br>}</pre><p>Here we are using a <em>Gateway</em> to check if the task already exists. This <em>Gateway</em> is an interface and note that the implementation (detail) of how this verification will be performed (SQL database, NoSQL, in-memory database, external integration, etc) should not be a concern of the “<em>Use Case</em>” layer.</p><p>The same is true about saving the task:</p><pre>taskDsGateway.save(taskDsModel);</pre><p><em>TaskPresenter</em> is a contract used to return the response in a format best suited to the layers above. Note that, again, the implementation (detail) of how it will be implemented does not matter for the “<em>Use Case</em>” layer.</p><p>At this moment, the entire core of our application is done, focusing entirely on business rules and abstracting the implementation details, as shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ed1BZV4YJvNQ4JJNKI1gxA.png" /></figure><p>Considerations:</p><ul><li><em>Interfaces</em> and <em>Models</em> implementations are available in GitHub.</li></ul><p>Package structure for the “<em>Use Case</em>” layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*CMkPTFirHuehlHZnrg4OEg.png" /></figure><h3>“Use Case” layer tests</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/403f6609eec11b06366ec8a453253079/href">https://medium.com/media/403f6609eec11b06366ec8a453253079/href</a></iframe><p>As you can see, the tests are self-explanatory, simple and the presence of “<em>Mocks</em>” is just to abstract details that don’t matter for the “<em>Use Case</em>” layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*9ieIwZJzJxniZ0SU2THYxQ.png" /><figcaption>100% coverage</figcaption></figure><h3>“Interface Adapters” layer implementation</h3><p>In this layer, the necessary details for the execution of the business rules are implemented.<br>Do you remember the <em>Gateways</em> used in the <em>Interactor</em>? <strong>We are going to implement them now =)</strong><br>Note that it is relatively simple and has a low risk of impact on business rules when changing, for example, the type of database (the “<em>Use Case</em>” and “<em>Entity</em>” layers remain unchanged). This is one of the advantages of <em>Dependency Inversion</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96441f36d04240fc0be6ede5af4a5a64/href">https://medium.com/media/96441f36d04240fc0be6ede5af4a5a64/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c8b2bb037bca64daacc1a387e0a2298/href">https://medium.com/media/2c8b2bb037bca64daacc1a387e0a2298/href</a></iframe><p>In this layer we also “plug” our interaction mechanisms with the client or some external frontend. These are the <em>applications entrypoints</em>. <br>In this example, we will create a <em>RestController</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4edc7f3159494d81f60d38a3e528c967/href">https://medium.com/media/4edc7f3159494d81f60d38a3e528c967/href</a></iframe><p>The “<em>Entrypoints</em>” communicate with the “<em>Use Case</em>” layer through the “<em>InputBoundaries</em>”.</p><p>In this layer, details like database, web framework, dependency injection framework, etc, matter and we can and should use them. <br>That said, I will create a Spring Boot configuration class that will be used to automate the application beans injection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90545a0075237032439ba02f475def55/href">https://medium.com/media/90545a0075237032439ba02f475def55/href</a></iframe><p>Considerations:</p><ul><li>Interfaces and other classes are available in GitHub.</li></ul><p>Package structure for layer “<em>Interface adapters</em>”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*SwAmfDy0EC-R3uNkb-YqlQ.png" /></figure><h3>“Interface Adapters” layer tests</h3><p>Verify if the <em>pom.xml</em> has the <em>spring-boot-starter-test </em>dependency:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>We will implement an <em>Integration Test suite</em>, creating a Spring Web server with an embedded H2 database, so we can validate all the execution of client perspective (without mocking details this time).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adae80dc04d2bd0a08c2d795ef60c550/href">https://medium.com/media/adae80dc04d2bd0a08c2d795ef60c550/href</a></iframe><h3>“Framework and Drivers” layer</h3><p>As Uncle Bob said:</p><blockquote>Generally you don’t write much code in this layer other than glue code that communicates to the next circle inwards.</blockquote><p>In this application by using Spring Framework, this layer is already provided for us.</p><h3>ArchUnit</h3><p><a href="https://www.archunit.org/"><em>ArchUnit</em></a> is a library that validates that, based on the architecture defined for the project, the patterns are being respected.</p><p><em>JUnit5 </em>maven dependencies:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;com.tngtech.archunit&lt;/groupId&gt;<br>   &lt;artifactId&gt;archunit-junit5-api&lt;/artifactId&gt;<br>   &lt;version&gt;1.0.0&lt;/version&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>   &lt;groupId&gt;com.tngtech.archunit&lt;/groupId&gt;<br>   &lt;artifactId&gt;archunit-junit5-engine&lt;/artifactId&gt;<br>   &lt;version&gt;1.0.0&lt;/version&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><h4>Architecture Tests</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0270140b7a1334d5f57fabae496e154b/href">https://medium.com/media/0270140b7a1334d5f57fabae496e154b/href</a></iframe><h3>Note</h3><ul><li>This project could be organized into modules (java 9+). It could have a module for each layer. <br>This approach would eliminate the need for some architectural validation testing with <em>ArchUnit</em>.</li></ul><h3>Final Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_lRs66pt27E7CJVdh4YPCQ.png" /></figure><h3>Final Thoughts</h3><p>If you want to practice, I would recommend you try to implement this new requirement:</p><blockquote><strong>New Requirement provided by Project Manager:</strong><br>1- The system receives a request asking to list all tasks created.</blockquote><p>If you have any questions, check my implementation to this requirement: <a href="https://github.com/gbrandao07/the-clean-architecture/commit/c29f1821f4b3793aa3b8bff704bbe97c893f65c">https://github.com/gbrandao07/the-clean-architecture/commit/c29f1821f4b3793aa3b8bff704bbe97c893f65c</a>9</p><p>Anything else, feel free to contact me.</p><p>I do hope all of this could have helped you in some way.<br>Best regards!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bfbb4c54730" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservice architecture: first steps using Spring Boot, Docker and Kubernetes]]></title>
            <link>https://medium.com/@gustavobrandao0742/microservice-architecture-first-steps-using-spring-boot-docker-and-kubernetes-16044e51009c?source=rss-21b8cbedc8a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/16044e51009c</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[gbrandao07]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 00:26:45 GMT</pubDate>
            <atom:updated>2020-04-15T20:16:21.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Dvk4hxgYEtMh73JVKhUbw.png" /></figure><p>Hello everyone!</p><p>Microservices are the most promissing trend topic in software development nowadays.</p><p>But for me, it was very dificult in the beginning to define what to start studying because of the large ammount of concepts and tecnologies involved.</p><p>Things tend to get clearer as your studies increase, but for you that are entering now in this world as I did not long ago, I would recommend you to read this article as a entrypoint.<br>As I am explaining the topics, I will providing tips for your future studies.</p><p>We are going to exercise a microservices architecture concepts.</p><h3>Topics</h3><ol><li>Prerequisites</li><li>Creating the microservices</li><li>Building the Docker images</li><li>Deploying to Kubernetes</li><li>Conclusion</li></ol><h3>1. Prerequisites</h3><ul><li>At least Java 8 JDK</li><li>At least Maven version 3</li><li>Docker</li><li>Kubernetes local environment (Minikube)</li></ul><h3>2. Creating the microservices</h3><p>We will build two microservices, let’s say caller-service and echo-service.<br>Let’s use the <a href="https://start.spring.io/">Spring Initializer</a> to setup the Spring Boot projects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*74FD7KxIQHk-hfcbm-n9sg.png" /><figcaption>Figure 01. Creating the caller-service project.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*JndPxdZZlWKMzXwC5NL0yw.png" /><figcaption>Figure 02. Creating the echo-service project.</figcaption></figure><p>Caller service will invoke to Echo service which, in turn, will return a simple hello message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*GJI-eg_QUjkALu5zBiLQ1g.png" /><figcaption>Figure 03. Caller and Echo service communication via REST.</figcaption></figure><p>Create the <em>CallerRestController</em>. This class will be the entrypoint for us to invoke the Caller service which will, in turn, invoke the Echo service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96fdabfba79adeef8b41a1ecd21d76a/href">https://medium.com/media/d96fdabfba79adeef8b41a1ecd21d76a/href</a></iframe><p>Change the server port to 8180 by inserting the following line in the <em>application.properties </em>file:</p><pre>server.port=8180</pre><p>Now create the <em>EchoRestController</em>. <br>This class will be expose the endpoint which will be invoked by the Caller service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63e78fe48df344d096d661b8cf2da05/href">https://medium.com/media/a63e78fe48df344d096d661b8cf2da05/href</a></iframe><p>Change the server port to 8280 by inserting the following line in the <em>application.properties</em> file:</p><pre>server.port=8280</pre><p>Build the two projects and up them. You could use your own IDE or execute the steps in each project folder as follows:</p><pre>mvn clean install<br>java -jar echoservice-0.0.1-SNAPSHOT.jar</pre><pre>mvn clean install <br>java -jar callerservice-0.0.1-SNAPSHOT.jar</pre><p>Execute a request to Caller service. Here I used Postman, but feel free to use your browser as it is a simple GET request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*1x8EcXaKDYtdYrQgMC9eCQ.png" /><figcaption>Figure 04. Validating the communication between the services through Postman.</figcaption></figure><h3>3. Building the Docker images</h3><p><em>Docker is a set of platform as a service (PaaS) products that uses OS-level virtualization to deliver software in packages called containers. Containers are isolated from one another and bundle their own software, libraries and configuration files; they can communicate with each other through well-defined channels. All containers are run by a single operating system kernel and therefore use fewer resources than virtual machines.<br>by: </em><a href="https://en.wikipedia.org/wiki/Docker_(software)"><em>https://en.wikipedia.org/wiki/Docker_(software)</em></a></p><p>Let’ s build our projects docker images.<br>Before all, change the CallerRestController endpoint from “http://localhost:8280/echo” to “http://echoservice:8280/echo” and rebuild the projects. <br>We need to do this because each microservice will run in their own container as you will see soon.</p><p>Create a Dockerfile in each project directory with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e2876d3532a04ffb3fbeb7cc3a34fc/href">https://medium.com/media/97e2876d3532a04ffb3fbeb7cc3a34fc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73b9afb346c553083cc6c1d022117644/href">https://medium.com/media/73b9afb346c553083cc6c1d022117644/href</a></iframe><p>Make the build:</p><pre>docker build -t echoservice:1.0 .<br>docker build -t callerservice:1.0 .</pre><p>Check if the images were correctly create:</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QVlJI48ZhuPOVsxxDq73w.png" /><figcaption>Figure 05. Listing the built images.</figcaption></figure><p>Generate the containers:</p><pre>docker run --publish 8280:8280 --detach --name echoservice echoservice:1.0</pre><pre>docker run --publish 8180:8180 --detach --name callerservice callerservice:1.0</pre><p>Here we are creating containers <em>echoservice</em> (that’s why you needed to change the <em>CallerRestController</em>) and <em>callerservice</em> exposing the same ports the applications use internally.</p><p>Just double check if both containers are running with the command:</p><pre>docker ps -a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6whUlCGt1di_43aVNTMLyw.png" /><figcaption>Figure 06. Listing the created containers.</figcaption></figure><p>Well, everything is up and so if you hit <a href="http://localhost:8180/callerservice"><em>http://localhost:8180/callerservice</em></a> as before you’ll get something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*S0IEnU2DINcX-U4xUsCgyw.png" /><figcaption>Figure 07. Communication between callerservice and echoservice fails.</figcaption></figure><p>By why does happen? Simple answer: each container, by default, runs isolated and independently from each other, there is no communication between them, that’s because the error occurs. <br>Docker Compose is a tool that helps us orchestrate the process of building images, creating containers and enable communication between the containers under its care. For more information about Docker Compose, see: “<a href="https://www.baeldung.com/docker-compose">Docker Compose overview</a>”.<br>We won’t configure Docker Compose here, because Kubernetes also provides the features to enable communication between containers and a lot more, so let’s jump right into it.</p><h3>4. Deploying to Kubernetes</h3><p><em>Kubernetes (commonly stylized as k8s) is an open-source container-orchestration system for automating application deployment, scaling, and management.<br>It was originally designed by Google, and is now maintained by the Cloud Native Computing Foundation. <br>It aims to provide a “platform for automating deployment, scaling, and operations of application containers across clusters of hosts”<br>by: https://en.wikipedia.org/wiki/Kubernetes</em></p><h4>4.1. Minikube</h4><p>Minikube is a local single-node kubernetes cluster that users can install locally in order to make tests. It’s is not designed to production environments.<br>Make sure you have Minikube installed and running on your machine.</p><pre>minikube status</pre><h4>4.2. Kubernetes itens</h4><p>It’s important to understand about some Kubernetes itens definitions.</p><p><strong>Pod<br></strong>Responsible to wrap one or more containers in order to make them deployable and kubernetes aware. A pod is the smallest kubernetes item.</p><p><strong>Deployment<br></strong>Responsible for applying rules about and orchestrate pods creation process. It is a best practice to create pods through deployment files and never directly creating the pods.</p><p><strong>Service</strong><br>A service will act as a gate exposing access to the pods managed by some deployment. A service can be available only inside the cluster (ClusterIP) or available outside the cluster (NodePort or LoadBalancer).</p><h4>4.3. Docker images lookup</h4><p>By default your Minikube Kubernetes installation will try to download all the docker images you request in Dockerhub.<br>As we are working in a local environment we will not upload the callerservice and echoservice to Dockerhub, so configure the Minikube to work with images locally:</p><pre>eval $(minikube docker-env)</pre><p>It’s is necessary to build the images again:</p><pre>docker build -t echoservice:1.0 .<br>docker build -t callerservice:1.0 .</pre><h4>4.4. Deployment and Service</h4><p><strong>Echo service:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6077aeb0ed1489f725cfdd7c13fcbbe8/href">https://medium.com/media/6077aeb0ed1489f725cfdd7c13fcbbe8/href</a></iframe><pre>kubectl create -f echoservice-deployment.yml</pre><p>We asked for kubernetes to create a deployment named “echoservice-deployment” which will create one pod (<em>replicas: 1</em>). This pod will be created with a container using the image echoservice:1.0.</p><p>Make sure the deployment was created:</p><pre>kubectl get deploy </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*rNH20kJQ6uqBnUqGtEVB6Q.png" /><figcaption>Figure 08. echoservice deployment up and running.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30a88dacc9a71cafa946beb1039df39e/href">https://medium.com/media/30a88dacc9a71cafa946beb1039df39e/href</a></iframe><pre>kubectl create -f echoservice-service.yml</pre><p>We asked for kubernetes to create a service named “echoservice-service” which will be available only inside the cluster (<em>type: ClusterIP</em>) which is enough to the callerservice. This service will redirect the traffic to a deployment called “echoservice” (<em>app: echoservice</em>)</p><p>Make sure the service was created:</p><pre>kubectl get services</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*vwQi5b2HmIa0J8C4DyjoRw.png" /><figcaption>Figure 09. echoservice deployment up and running.</figcaption></figure><p><strong>Caller service:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0eabb80dbfdcec9f808dacb76257607/href">https://medium.com/media/d0eabb80dbfdcec9f808dacb76257607/href</a></iframe><pre>kubectl create -f callerservice-deployment.yml</pre><p>We asked for kubernetes to create a deployment named “callerservice-deployment” which will create one pod (<em>replicas: 1</em>). This pod will be created with a container using the image callerservice:1.0.</p><p>Make sure the deployment was created:</p><pre>kubectl get deploy</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*Rhcp-5nMR-PC-_2rbMxm3w.png" /><figcaption>Figure 10. callerservice deployment up and running.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74cc295ce3d0a25411ceb5c8159986b3/href">https://medium.com/media/74cc295ce3d0a25411ceb5c8159986b3/href</a></iframe><pre>kubectl create -f callerservice-service.yml</pre><p>We asked for kubernetes to create a service named “callerservice-service” which expose a random port for access outside the cluster (<em>type: NodePort</em>) which is what we need to make requests to the endpoint. This service will redirect the traffic to a deployment called “callerservice” (<em>app: callerservice</em>)</p><p>Make sure the service was created:</p><pre>kubectl get services</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*THZDaAGgnL17TWr9ibg2sA.png" /><figcaption>Figure 11. callerservice service up and running.</figcaption></figure><p>Get the cluster external IP:</p><pre>minikube service callerservice --url</pre><p>The return will be something like: <a href="http://192.168.99.100:30096/">http://192.168.99.100:30096</a></p><p>Make a request to the returned URL:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*1ey79iGKkgWnwpoVDL6N7Q.png" /><figcaption>Figure 12. Invoking the callerservice from the cluster nodeport</figcaption></figure><h3>5. Conclusion</h3><p>In this post, we have explored some concepts in order to understand you to create and manage microservices with Spring boot, Docker and Kubernetes, which is a trending stack nowadays.<br>We created a microservice callerservice invoking another microservice called echoservice, built the docker images e deployed them in a local kubernetes environment.<br>This article was a really simplification of the concepts and is just a start point to show how the tecnologies are associated.<br>I suggest you keep studying and I hope it was useful for you somehow.</p><p>Here is the Github repo: <a href="https://github.com/gbrandao07/medium-article-springboot-docker-k8s">https://github.com/gbrandao07/medium-article-springboot-docker-k8s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16044e51009c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>