diff --git a/README.md b/README.md index 464125e..ca65153 100644 --- a/README.md +++ b/README.md @@ -15,29 +15,23 @@ A estrutura de pastas do projeto é organizada da seguinte forma: ``` / +├── compose.ministack.yaml # MiniStack + API e gerador locais ├── terraform/ -│ ├── main.tf -│ ├── variables.tf -│ ├── outputs.tf -│ ├── terraform.tfvars.example -│ ├── api-gateway/ -│ ├── bucket_s3/ -│ ├── dynamodb/ -│ │ ├── certificates/ -│ │ ├── orders/ -│ │ ├── participants/ -│ │ └── products/ -│ ├── lambda/ -│ └── sqs/ +│ ├── env/ +│ │ ├── dev/ # AWS, backend S3 +│ │ └── ministack/ # Local, backend local +│ └── modules/ +│ ├── 02.dynamodb/single_table/ +│ ├── 03.bucket_s3/ +│ ├── 04.sqs/ +│ ├── 05.lambda/ +│ └── 06.api-gateway/ └── README.md ``` -- **terraform/**: Contém todos os arquivos de configuração do Terraform. -- **terraform/main.tf**: Arquivo principal que define os módulos e a configuração do provider. -- **terraform/variables.tf**: Declaração das variáveis utilizadas no projeto. -- **terraform/outputs.tf**: Definição dos outputs do Terraform. -- **terraform/terraform.tfvars.example**: Arquivo de exemplo para as variáveis do Terraform. -- **terraform/[module]/**: Cada pasta representa um módulo do Terraform que provisiona um serviço específico na AWS. +- **terraform/env/dev/**: Perfil Terraform AWS, com state remoto em S3. +- **terraform/env/ministack/**: Perfil isolado para MiniStack, com state local. +- **terraform/modules/**: Módulos reutilizáveis para DynamoDB, S3, SQS, Lambda e API Gateway. ## Serviços Criados e Suas Variáveis @@ -65,19 +59,46 @@ A seguir estão os serviços da AWS criados por este projeto e suas respectivas - `region`: Região da AWS. - `lifecycle_rule`: Regras de ciclo de vida dos objetos S3. -### DynamoDB +### DynamoDB Single-Table -- **Descrição**: Cria as tabelas do DynamoDB para a aplicação. -- **Módulos**: - - `certificates`: Tabela de certificados. - - `orders`: Tabela de pedidos. - - `participants`: Tabela de participantes. - - `products`: Tabela de produtos. -- **Variáveis (por módulo)**: +- **Descrição**: Cria a tabela DynamoDB com padrão Single-Table Design. +- **Módulo**: `single_table` +- **Variáveis**: - `table_name`: Nome da tabela. - `environment`: Ambiente de deploy. - `project_name`: Nome do projeto. +#### Estrutura da Tabela + +A tabela utiliza um design Single-Table com chaves compostas e 4 Global Secondary Indexes (GSIs). + +| Atributo | Tipo | Descrição | +|----------|------|-----------| +| `PK` | String | Chave de Partição principal | +| `SK` | String | Chave de Ordenação principal | +| `GSI1PK`, `GSI1SK` | String | GSI1 - Certificate por UUID | +| `GSI2PK`, `GSI2SK` | String | GSI2 - Orders, Certificates, Participants por email | +| `GSI3PK`, `GSI3SK` | String | GSI3 - Products por nome, Certificates/Orders por product | +| `GSI4PK`, `GSI4SK` | String | GSI4 - Certificados por status de sucesso | + +#### GSIs (Global Secondary Indexes) + +| GSI | Key Schema | Access Pattern | +|-----|------------|----------------| +| GSI1 | `PK: UUID, SK: CERT#` | Certificate by UUID | +| GSI2 | `PK: email, SK: ENTITY#` | Orders, Certificates, Participants by email | +| GSI3 | `PK: product, SK: ENTITY#` | Products by name, Certificates/Orders by product | +| GSI4 | `PK: SUCCESS#Y/N, SK: CERT#` | Successful/Failed certificates | + +#### Entidades Suportadas + +| Entidade | PK | SK | GSIs Utilizados | +|----------|----|----|----------------| +| Certificate | `CERTIFICATE#` | `CERTIFICATE#` | GSI1, GSI2, GSI3, GSI4 | +| Order | `ORDER#` | `ORDER#` | GSI2, GSI3 | +| Product | `PRODUCT#` | `PRODUCT#` | GSI3 | +| Participant | `PARTICIPANT#` | `PARTICIPANT#` | GSI2 | + ### Lambda - **Descrição**: Cria as funções Lambda no formato ZIP e a infraestrutura associada. @@ -104,7 +125,129 @@ A seguir estão os serviços da AWS criados por este projeto e suas respectivas - O Terraform cria as funções Lambda, roles, filas SQS, tabelas DynamoDB, bucket S3 e API Gateway. - Cada função é inicializada com um ZIP placeholder mínimo apenas para permitir a criação do recurso. - Os repositórios `certified-builder-api-py`, `certified_builder_py` e `certified-builder-notification-py` publicam o código real usando `aws lambda update-function-code`. -- O fluxo local com Docker é apenas para emulação de runtime em `localhost:9000`. +- O perfil MiniStack em `terraform/env/ministack` usa o backend local e endpoint `localhost:4566`; ele é separado de `terraform/env/dev`, que continua usando o backend S3 da AWS. + +### Deploy na AWS + +Para provisionar na AWS, use apenas o perfil `terraform/env/dev` e suas variáveis reais fornecidas pela configuração segura do ambiente: + +```sh +cd terraform/env/dev +terraform init +terraform plan -out=tfplan +terraform apply tfplan +``` + +Depois do provisionamento, publique os pacotes de código das três Lambdas pelos workflows dos repositórios relacionados. O `apply` do perfil `dev` cria ou altera recursos AWS; o perfil `ministack` abaixo não usa nem atualiza esse state. + +## Desenvolvimento e testes locais com MiniStack + +O Compose sobe o emulador AWS MiniStack, a API em runtime Lambda local (RIE) e o gerador de certificados. O MiniStack persiste os dados no volume Docker `ministack-data`. + +### Requisitos + +- Docker Desktop/Engine em execução. +- Terraform instalado. +- AWS CLI instalado (as chamadas abaixo usam apenas `--endpoint-url http://localhost:4566` e credenciais fictícias). + +### Subir os serviços + +Execute na raiz deste repositório: + +```sh +docker compose -f compose.ministack.yaml up -d --build +curl -fsS http://localhost:4566/_ministack/health +docker compose -f compose.ministack.yaml ps +``` + +Portas locais: + +| Serviço | Endereço | Uso | +|---------|----------|-----| +| MiniStack | `http://localhost:4566` | APIs AWS simuladas | +| API Lambda RIE | `http://localhost:9000` | Invocação Lambda local | +| Gerador Lambda RIE | `http://localhost:9001` | Geração do certificado | +| Mock Solana | apenas na rede Compose | Responde com URL de transação de teste; não envia transação real | + +Por padrão, a API é compilada do checkout vizinho `../certified-builder-api-py`, e o gerador de `../certified_builder_py`. Para usar outro worktree ou checkout, informe `API_BUILD_CONTEXT` ou `BUILDER_BUILD_CONTEXT` ao executar Compose. Exemplo: + +```sh +API_BUILD_CONTEXT=/caminho/para/api-worktree \ +BUILDER_BUILD_CONTEXT=/caminho/para/builder-worktree \ +docker compose -f compose.ministack.yaml up -d --build +``` + +### Criar a infraestrutura single-table + +O perfil local tem provider apontado diretamente para MiniStack, credenciais fictícias e backend Terraform local. Não use credenciais AWS reais nele. + +```sh +cd terraform/env/ministack +terraform init -backend=false +terraform apply \ + -var='aws_account_id=000000000000' \ + -var='github_actions_role_arn=arn:aws:iam::000000000000:role/local' \ + -var='api_key_value=00000000-0000-4000-8000-000000000000' \ + -var='service_url_registration_api_solana=http://example.local/register' \ + -var='service_api_key_registration_api_solana=local-test-key' \ + -var='tech_floripa_certificate_validate_url=http://example.local/validate' +``` + +O comando cria a tabela single-table, bucket S3, filas SQS, Lambdas placeholder e API Gateway no MiniStack. O estado fica em `terraform/env/ministack/terraform.tfstate`; o backend S3 de `terraform/env/dev` não é inicializado. + +### Testar geração de certificado + +O gerador recebe um evento SQS Lambda: `Records[0].body` deve ser uma string JSON contendo uma lista de participantes. Os campos de entrada são `order_id`, `product_id`, `product_name`, `email`, `first_name`, `last_name`, `certificate_details`, `certificate_logo`, `certificate_background` e `order_date` (`YYYY-MM-DD HH:MM:SS`). `time_checkin` é opcional. + +Crie um evento temporário com dados fictícios. As imagens usam o serviço público de placeholders; substitua-as por arquivos de teste locais se quiser executar sem acesso externo: + +```sh +cat > /tmp/certificate-event.json <<'JSON' +{ + "Records": [{ + "body": "[{\"order_id\":123456,\"product_id\":42,\"product_name\":\"Demo Event\",\"email\":\"alex@example.test\",\"first_name\":\"Alex\",\"last_name\":\"Example\",\"certificate_details\":\"This is a fictional certificate for local testing.\",\"certificate_logo\":\"https://placehold.co/150x150.jpg?text=Demo+Logo\",\"certificate_background\":\"https://placehold.co/1200x627.png?text=Demo+Certificate\",\"order_date\":\"2025-01-15 12:00:00\"}]" + }] +} +JSON + +curl -sS -X POST \ + http://localhost:9001/2015-03-31/functions/function/invocations \ + -H 'Content-Type: application/json' \ + --data-binary @/tmp/certificate-event.json +``` + +O endpoint de invocação pode responder `200` mesmo quando a geração interna falha. Confirme o resultado pelos logs e pelo objeto S3: + +```sh +docker compose -f compose.ministack.yaml logs --tail=150 certified_builder_lambda_function + +AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 \ +aws s3api list-objects-v2 \ + --endpoint-url http://localhost:4566 \ + --bucket tech-floripa-certificates-dev-bucket \ + --prefix certificates/42/123456/ \ + --query 'Contents[].{Key:Key,Size:Size}' --output table +``` + +Uma geração bem-sucedida registra `Certificado gerado` e o upload para S3 nos logs. Uma falha registra `Erro ao gerar certificado` ou `Erro ao enviar o arquivo`. A chave final inclui o código de validação aleatório criado na execução. + +O gerador envia também uma notificação para SQS. As Lambdas criadas pelo Terraform usam código placeholder; portanto, a Lambda de notificação local pode consumir a mensagem sem atualizar o item no DynamoDB. Para testar atualização de status, publique o código real do repositório de notificações apontando seus clientes AWS para MiniStack. O `success` que já estiver no item de seed não comprova o resultado da execução atual. + +### Parar e limpar + +Pare os containers sem remover o volume persistente: + +```sh +docker compose -f compose.ministack.yaml down +``` + +Para remover também os dados locais do MiniStack, remova o volume apenas quando não precisar mais do estado e dos objetos de teste: + +```sh +docker compose -f compose.ministack.yaml down -v +``` + +Para excluir os recursos do Terraform local, execute `terraform destroy` dentro de `terraform/env/ministack`, passando as mesmas variáveis fictícias usadas no `apply`. ### SQS (Simple Queue Service) diff --git a/compose.ministack.yaml b/compose.ministack.yaml new file mode 100644 index 0000000..01710b1 --- /dev/null +++ b/compose.ministack.yaml @@ -0,0 +1,76 @@ +services: + ministack: + image: ministackorg/ministack:latest + ports: + - "4566:4566" + environment: + MINISTACK_REGION: us-east-1 + MINISTACK_ACCOUNT_ID: "000000000000" + PERSIST_STATE: "1" + STATE_DIR: /data/state + DOCKER_NETWORK: certified-builder-infra-py_default + volumes: + - ministack-data:/data + - /var/run/docker.sock:/var/run/docker.sock + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:4566/_ministack/health')"] + interval: 5s + timeout: 3s + retries: 30 + + certified_build_lambda_function: + build: + context: ${API_BUILD_CONTEXT:-../certified-builder-api-py} + dockerfile: Dockerfile + ports: + - "9000:8080" + environment: + REGION: us-east-1 + AWS_REGION: us-east-1 + AWS_DEFAULT_REGION: us-east-1 + AWS_ACCESS_KEY_ID: test + AWS_SECRET_ACCESS_KEY: test + AWS_ENDPOINT_URL: http://ministack:4566 + ENVIRONMENT: dev + PROJECT_NAME: tech-floripa-certificates + BUILDER_QUEUE_URL: http://ministack:4566/000000000000/tech-floripa-certificates-builder-queue + S3_BUCKET_NAME: tech-floripa-certificates-dev-bucket + URL_SERVICE_TECH: https://example.test/wp-json/custom/v1 + depends_on: + ministack: + condition: service_healthy + + certified_builder_lambda_function: + build: + context: ${BUILDER_BUILD_CONTEXT:-../certified_builder_py} + dockerfile: Dockerfile + ports: + - "9001:8080" + environment: + REGION: us-east-1 + AWS_REGION: us-east-1 + AWS_DEFAULT_REGION: us-east-1 + AWS_ACCESS_KEY_ID: test + AWS_SECRET_ACCESS_KEY: test + AWS_ENDPOINT_URL_S3: http://ministack:4566 + AWS_ENDPOINT_URL_SQS: http://ministack:4566 + BUCKET_NAME: tech-floripa-certificates-dev-bucket + QUEUE_URL: http://ministack:4566/000000000000/tech-floripa-certificates-notification-queue + SERVICE_URL_REGISTRATION_API_SOLANA: http://solana-mock:8081/register + SERVICE_API_KEY_REGISTRATION_API_SOLANA: local-test-key + TECH_FLORIPA_CERTIFICATE_VALIDATE_URL: http://localhost:9000/api/v1/certificate/validate + TECH_FLORIPA_LOGO_URL: https://placehold.co/150x150.png?text=Demo+Logo + depends_on: + ministack: + condition: service_healthy + solana-mock: + condition: service_started + + solana-mock: + image: python:3.13-slim + command: ["python", "/mock_solana.py"] + volumes: + - ./scripts/mock_solana.py:/mock_solana.py:ro + +volumes: + ministack-data: diff --git a/scripts/mock_solana.py b/scripts/mock_solana.py new file mode 100644 index 0000000..491c1e5 --- /dev/null +++ b/scripts/mock_solana.py @@ -0,0 +1,21 @@ +import json +from http.server import BaseHTTPRequestHandler, HTTPServer + + +class Handler(BaseHTTPRequestHandler): + def do_POST(self): + self.rfile.read(int(self.headers.get("Content-Length", "0"))) + body = json.dumps( + {"blockchain": {"explorer_url": "https://explorer.solana.com/tx/local-test"}} + ).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format, *args): + return + + +HTTPServer(("0.0.0.0", 8081), Handler).serve_forever() diff --git a/terraform/env/dev/main.tf b/terraform/env/dev/main.tf index 5d084ef..6a74afe 100644 --- a/terraform/env/dev/main.tf +++ b/terraform/env/dev/main.tf @@ -7,31 +7,10 @@ module "s3" { region = var.aws_region } -# DynamoDB Tables -module "certificates_table" { - source = "../../modules/02.dynamodb/certificates" - table_name = "${var.project_name}-certificates-${var.environment}" - environment = var.environment - project_name = var.project_name -} - -module "orders_table" { - source = "../../modules/02.dynamodb/orders" - table_name = "${var.project_name}-orders-${var.environment}" - environment = var.environment - project_name = var.project_name -} - -module "participants_table" { - source = "../../modules/02.dynamodb/participants" - table_name = "${var.project_name}-participants-${var.environment}" - environment = var.environment - project_name = var.project_name -} - -module "products_table" { - source = "../../modules/02.dynamodb/products" - table_name = "${var.project_name}-products-${var.environment}" +# DynamoDB Single Table +module "dynamodb_single_table" { + source = "../../modules/02.dynamodb/single_table" + table_name = "${var.project_name}-${var.environment}" environment = var.environment project_name = var.project_name } @@ -63,10 +42,7 @@ module "lambda" { notification_queue_arn = module.sqs.notification_queue_arn notification_queue_url = module.sqs.notification_queue_url dynamodb_table_arns = [ - module.certificates_table.table_arn, - module.orders_table.table_arn, - module.participants_table.table_arn, - module.products_table.table_arn + module.dynamodb_single_table.table_arn ] s3_bucket_arn = module.s3.bucket_arn s3_bucket_name = module.s3.bucket_name diff --git a/terraform/env/dev/outputs.tf b/terraform/env/dev/outputs.tf index 3d70568..d2cf03e 100644 --- a/terraform/env/dev/outputs.tf +++ b/terraform/env/dev/outputs.tf @@ -9,48 +9,15 @@ output "s3_bucket_arn" { value = module.s3.bucket_arn } -# Informações das tabelas de certificados -output "certificates_table_name" { - description = "Nome da tabela de certificados" - value = module.certificates_table.table_name +# Informações da tabela única DynamoDB (single-table design) +output "dynamodb_single_table_name" { + description = "Nome da tabela DynamoDB única" + value = module.dynamodb_single_table.table_name } -output "certificates_table_arn" { - description = "ARN da tabela de certificados" - value = module.certificates_table.table_arn -} - -# Informações das tabelas de pedidos -output "orders_table_name" { - description = "Nome da tabela de pedidos" - value = module.orders_table.table_name -} - -output "orders_table_arn" { - description = "ARN da tabela de pedidos" - value = module.orders_table.table_arn -} - -# Informações das tabelas de participantes -output "participants_table_name" { - description = "Nome da tabela de participantes" - value = module.participants_table.table_name -} - -output "participants_table_arn" { - description = "ARN da tabela de participantes" - value = module.participants_table.table_arn -} - -# Informações das tabelas de produtos -output "products_table_name" { - description = "Nome da tabela de produtos" - value = module.products_table.table_name -} - -output "products_table_arn" { - description = "ARN da tabela de produtos" - value = module.products_table.table_arn +output "dynamodb_single_table_arn" { + description = "ARN da tabela DynamoDB única" + value = module.dynamodb_single_table.table_arn } # Informações do SQS diff --git a/terraform/env/ministack/.terraform.lock.hcl b/terraform/env/ministack/.terraform.lock.hcl new file mode 100644 index 0000000..f13f0da --- /dev/null +++ b/terraform/env/ministack/.terraform.lock.hcl @@ -0,0 +1,46 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/archive" { + version = "2.7.1" + constraints = "2.7.1" + hashes = [ + "h1:A7EnRBVm4h9ryO9LwxYnKr4fy7ExPMwD5a1DsY7m1Y0=", + "zh:19881bb356a4a656a865f48aee70c0b8a03c35951b7799b6113883f67f196e8e", + "zh:2fcfbf6318dd514863268b09bbe19bfc958339c636bcbcc3664b45f2b8bf5cc6", + "zh:3323ab9a504ce0a115c28e64d0739369fe85151291a2ce480d51ccbb0c381ac5", + "zh:362674746fb3da3ab9bd4e70c75a3cdd9801a6cf258991102e2c46669cf68e19", + "zh:7140a46d748fdd12212161445c46bbbf30a3f4586c6ac97dd497f0c2565fe949", + "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", + "zh:875e6ce78b10f73b1efc849bfcc7af3a28c83a52f878f503bb22776f71d79521", + "zh:b872c6ed24e38428d817ebfb214da69ea7eefc2c38e5a774db2ccd58e54d3a22", + "zh:cd6a44f731c1633ae5d37662af86e7b01ae4c96eb8b04144255824c3f350392d", + "zh:e0600f5e8da12710b0c52d6df0ba147a5486427c1a2cc78f31eea37a47ee1b07", + "zh:f21b2e2563bbb1e44e73557bcd6cdbc1ceb369d471049c40eb56cb84b6317a60", + "zh:f752829eba1cc04a479cf7ae7271526b402e206d5bcf1fcce9f535de5ff9e4e6", + ] +} + +provider "registry.terraform.io/hashicorp/aws" { + version = "6.22.1" + constraints = "6.22.1" + hashes = [ + "h1:PTgxp+nMDBd6EFHAIH6ceFfvwa2blqkCwXglZn6Dqa8=", + "h1:zfVzyJmwHhNP+YtLuroU36LTjuZTv2pBUpEJgtnX4HA=", + "zh:3995ca97e6c2c1ed9e231c453287585d3dc1ca2a304683ac0b269b3448fda7c0", + "zh:4f69f70d2edeb0dde9c693b7cd7e8e21c781b2fac7062bed5300092dbadb71e1", + "zh:5c76042fdf3df56a1f581bc477e5d6fc3e099d4d6544fe725b3747e9990726bd", + "zh:6ff8221340955f4b3ba9230918bb026c4414a5aebe9d0967845c43e8e8908aec", + "zh:73cdd8638cb52bbe25887cd5b7946cc3fcb891867de11bcb0fde9b35c4f70a41", + "zh:7af5aec2fd01fa5e5f600f1db1bcf200aaadc05a2c8ffcbb4b6b61cd2bd3e33b", + "zh:7e055cfa7f40b667f5f7af564db9544f46aa189cdbe5530ad812e027647132f5", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:aba898190c668ade4471da65c96db414679367174ac5b73e8ce7551056c77e3e", + "zh:aedaa8d7d71e6d58cdc09a7e3bcb8031b3ea496a7ac142376eb679d1756057f3", + "zh:cb9739952d467b3f6d72d57722943956e80ab235b58a0e34758538381dcc386c", + "zh:e12a2681028a70cb08eaf4c3364ddab386416502f966067bf99e79ba6be0d7b6", + "zh:e32a922a7d6fd5df69b3cc92932fc2689dc195b0f8b493dcd686abdd892b06cd", + "zh:f2dea7dead6f34b51e8b6aae177a8b333834a41d25529baa634a087d99ea32f6", + "zh:f6eee6df0366e8452d912cfd498792579aede88de3b67c15d36b8949e37479b1", + ] +} diff --git a/terraform/env/ministack/README.md b/terraform/env/ministack/README.md new file mode 100644 index 0000000..e3a7275 --- /dev/null +++ b/terraform/env/ministack/README.md @@ -0,0 +1,28 @@ +# Ambiente local com MiniStack + +Esse diretório aplica a infraestrutura da branch single-table ao MiniStack. Ele usa o backend local e endpoint `localhost:4566`; o ambiente AWS em `../dev` permanece separado. + +O Compose também expõe a API em `localhost:9000` e o gerador de certificados em `localhost:9001`. A chamada de registro Solana do gerador é roteada para um mock local, para o teste não enviar transações reais. As URLs de imagem de fundo e logo são baixadas normalmente. + +Na raiz de `certified-builder-infra-py`, suba os serviços: + +```sh +docker compose -f compose.ministack.yaml up -d --build +``` + +Para compilar a API a partir de outro checkout, defina `API_BUILD_CONTEXT` no comando do Compose. O padrão é `../certified-builder-api-py`. + +Inicialize e aplique Terraform neste diretório: + +```sh +terraform init -backend=false +terraform apply \ + -var='aws_account_id=000000000000' \ + -var='github_actions_role_arn=arn:aws:iam::000000000000:role/local' \ + -var='api_key_value=00000000-0000-4000-8000-000000000000' \ + -var='service_url_registration_api_solana=http://example.local/register' \ + -var='service_api_key_registration_api_solana=local-test-key' \ + -var='tech_floripa_certificate_validate_url=http://example.local/validate' +``` + +O endpoint do emulador é configurado diretamente no provider local. Não passe variáveis AWS reais para esse ambiente. diff --git a/terraform/env/ministack/main.tf b/terraform/env/ministack/main.tf new file mode 100644 index 0000000..6a74afe --- /dev/null +++ b/terraform/env/ministack/main.tf @@ -0,0 +1,62 @@ +# S3 Bucket +module "s3" { + source = "../../modules/03.bucket_s3" + bucket_name = "${var.project_name}-${var.environment}-bucket" + environment = var.environment + project_name = var.project_name + region = var.aws_region +} + +# DynamoDB Single Table +module "dynamodb_single_table" { + source = "../../modules/02.dynamodb/single_table" + table_name = "${var.project_name}-${var.environment}" + environment = var.environment + project_name = var.project_name +} + +# SQS +module "sqs" { + source = "../../modules/04.sqs" + project_name = var.project_name + environment = var.environment +} + +# Lambda +module "lambda" { + source = "../../modules/05.lambda" + project_name = var.project_name + environment = var.environment + aws_region = var.aws_region + lambda_timeout = var.lambda_timeout + lambda_memory_size = var.lambda_memory_size + log_retention_days = var.log_retention_days + url_service_tech = var.url_service_tech + prefix_api_version = var.prefix_api_version + service_url_registration_api_solana = var.service_url_registration_api_solana + service_api_key_registration_api_solana = var.service_api_key_registration_api_solana + tech_floripa_certificate_validate_url = var.tech_floripa_certificate_validate_url + tech_floripa_logo_url = var.tech_floripa_logo_url + builder_queue_url = module.sqs.builder_queue_url + builder_queue_arn = module.sqs.builder_queue_arn + notification_queue_arn = module.sqs.notification_queue_arn + notification_queue_url = module.sqs.notification_queue_url + dynamodb_table_arns = [ + module.dynamodb_single_table.table_arn + ] + s3_bucket_arn = module.s3.bucket_arn + s3_bucket_name = module.s3.bucket_name + api_gateway_download_url = module.api_gateway.api_endpoint_download_certificate +} + +# API Gateway +module "api_gateway" { + source = "../../modules/06.api-gateway" + project_name = var.project_name + environment = var.environment + lambda_function_name = module.lambda.function_name + lambda_invoke_arn = module.lambda.invoke_arn + throttle_rate_limit = var.api_throttle_rate_limit + throttle_burst_limit = var.api_throttle_burst_limit + api_key_value = var.api_key_value +} diff --git a/terraform/env/ministack/outputs.tf b/terraform/env/ministack/outputs.tf new file mode 100644 index 0000000..d2cf03e --- /dev/null +++ b/terraform/env/ministack/outputs.tf @@ -0,0 +1,116 @@ +# Informações do s3 +output "s3_bucket_name" { + description = "Nome do bucket S3" + value = module.s3.bucket_name +} + +output "s3_bucket_arn" { + description = "ARN do bucket S3" + value = module.s3.bucket_arn +} + +# Informações da tabela única DynamoDB (single-table design) +output "dynamodb_single_table_name" { + description = "Nome da tabela DynamoDB única" + value = module.dynamodb_single_table.table_name +} + +output "dynamodb_single_table_arn" { + description = "ARN da tabela DynamoDB única" + value = module.dynamodb_single_table.table_arn +} + +# Informações do SQS +output "sqs_queue_url" { + description = "URL da fila SQS principal" + value = module.sqs.queue_url +} + +output "sqs_queue_arn" { + description = "ARN da fila SQS principal" + value = module.sqs.queue_arn +} + +output "sqs_dlq_url" { + description = "URL da Dead Letter Queue (builder)" + value = module.sqs.builder_dlq_url +} + +# Informações do Lambda +output "lambda_function_name" { + description = "Nome da função Lambda" + value = module.lambda.function_name +} + +output "lambda_function_arn" { + description = "ARN da função Lambda" + value = module.lambda.function_arn +} + +output "lambda_builder_function_name" { + description = "Nome da função Lambda Builder" + value = module.lambda.builder_function_name +} + +output "lambda_builder_function_arn" { + description = "ARN da função Lambda Builder" + value = module.lambda.builder_function_arn +} + +# Informações da Lambda de Notificação +output "lambda_notification_function_name" { + description = "Nome da função Lambda de Notificação" + value = module.lambda.notification_function_name +} + +output "lambda_notification_function_arn" { + description = "ARN da função Lambda de Notificação" + value = module.lambda.notification_function_arn +} + +# Informações do API Gateway +output "api_gateway_url" { + description = "URL base do API Gateway" + value = module.api_gateway.api_url +} + +output "api_gateway_endpoint_create_certificate" { + description = "URL completa do endpoint para criar certificado" + value = module.api_gateway.api_endpoint_create_certificate +} + +output "api_gateway_endpoint_download_certificate" { + description = "URL base do endpoint para download de certificados" + value = module.api_gateway.api_endpoint_download_certificate +} + +output "api_gateway_id" { + description = "ID do API Gateway" + value = module.api_gateway.api_id +} + +# Resumo completo da infraestrutura +output "infrastructure_summary" { + description = "Resumo completo da infraestrutura criada" + value = { + api_gateway = { + id = module.api_gateway.api_id + url = module.api_gateway.api_url + endpoint_create_cert = module.api_gateway.api_endpoint_create_certificate + } + lambda = { + function_name = module.lambda.function_name + function_arn = module.lambda.function_arn + builder_function_name = module.lambda.builder_function_name + builder_function_arn = module.lambda.builder_function_arn + notification_function_name = module.lambda.notification_function_name + notification_function_arn = module.lambda.notification_function_arn + } + sqs = { + queue_url = module.sqs.queue_url + dlq_url = module.sqs.builder_dlq_url + } + environment = var.environment + project = var.project_name + } +} diff --git a/terraform/env/ministack/provider.tf b/terraform/env/ministack/provider.tf new file mode 100644 index 0000000..56c9633 --- /dev/null +++ b/terraform/env/ministack/provider.tf @@ -0,0 +1,44 @@ +terraform { + required_version = ">= 1.5.7, < 2.0.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "6.22.1" + } + archive = { + source = "hashicorp/archive" + version = "2.7.1" + } + } +} + +provider "aws" { + region = var.aws_region + access_key = "test" + secret_key = "test" + skip_credentials_validation = true + skip_metadata_api_check = true + skip_requesting_account_id = true + s3_use_path_style = true + + endpoints { + apigateway = "http://localhost:4566" + cloudwatch = "http://localhost:4566" + dynamodb = "http://localhost:4566" + iam = "http://localhost:4566" + lambda = "http://localhost:4566" + logs = "http://localhost:4566" + s3 = "http://localhost:4566" + sqs = "http://localhost:4566" + sts = "http://localhost:4566" + } + + default_tags { + tags = { + Project = var.project_name + Environment = "ministack" + ManagedBy = "terraform" + } + } +} diff --git a/terraform/env/ministack/variables.tf b/terraform/env/ministack/variables.tf new file mode 100644 index 0000000..d0b064b --- /dev/null +++ b/terraform/env/ministack/variables.tf @@ -0,0 +1,131 @@ +# Variáveis para configuração do Terraform + +# Região AWS onde os recursos serão criados +variable "aws_region" { + description = "Região AWS para deploy dos recursos" + type = string + default = "us-east-1" +} + +variable "aws_account_id" { + description = "ID da conta AWS onde os recursos serão criados" + type = string +} + +# Github + +variable "github_org" { + description = "Organização do GitHub" + type = string + default = "PythonFloripa" +} + +variable "github_repo" { + description = "Repositório do GitHub" + type = string + default = "certified-builder-infra-py" +} + +variable "github_actions_role_arn" { + description = "ARN da role IAM para GitHub Actions" + type = string +} + +# Ambiente de deploy (dev ou live) +variable "environment" { + description = "Ambiente de deploy" + type = string + default = "dev" + + validation { + condition = contains(["dev", "live"], var.environment) + error_message = "O ambiente deve ser: dev ou live." + } +} + +# Nome do projeto +variable "project_name" { + description = "Nome do projeto" + type = string + default = "tech-floripa-certificates" +} + +# Configuração do DynamoDB - Modo de Baixo Custo +# Todas as tabelas usam PAY_PER_REQUEST por padrão (paga apenas pelo que usar) + +variable "lambda_timeout" { + description = "Timeout da função Lambda em segundos" + type = number + default = 900 +} + +variable "lambda_memory_size" { + description = "Memória alocada para a função Lambda em MB" + type = number + default = 512 +} + +variable "log_retention_days" { + description = "Dias de retenção dos logs do CloudWatch" + type = number + default = 90 +} + +variable "url_service_tech" { + description = "URL do serviço Tech Floripa" + type = string + default = "https://example.test/wp-json/custom/v1" +} + +variable "prefix_api_version" { + description = "Prefixo da versão da API" + type = string + default = "/api/v1" +} + +# Variáveis para API Gateway +variable "api_throttle_rate_limit" { + description = "Limite de taxa por segundo para throttling do API Gateway" + type = number + default = 100 +} + +variable "api_throttle_burst_limit" { + description = "Limite de burst para throttling do API Gateway" + type = number + default = 200 +} + +variable "api_key_value" { + description = "Valor da API Key para autenticação do API Gateway (deve ser fornecido via terraform.tfvars)" + type = string + sensitive = true + + validation { + condition = can(regex("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", var.api_key_value)) + error_message = "A API Key deve estar no formato UUID válido (ex: 8a3f1e2c-9d7b-4f4a-8453-bf3c1d2a6f29)." + } +} + +# Variáveis para integração com API Solana +variable "service_url_registration_api_solana" { + description = "URL do serviço de registro da API Solana" + type = string +} + +variable "service_api_key_registration_api_solana" { + description = "API Key do serviço de registro da API Solana" + type = string + sensitive = true +} + +variable "tech_floripa_certificate_validate_url" { + description = "URL para validação de certificados do Tech Floripa" + type = string +} + +variable "tech_floripa_logo_url" { + description = "URL do logo do Tech Floripa" + type = string + default = "https://placehold.co/150x150.png?text=Demo+Logo" +} diff --git a/terraform/modules/02.dynamodb/single_table/main.tf b/terraform/modules/02.dynamodb/single_table/main.tf new file mode 100644 index 0000000..a26ef7b --- /dev/null +++ b/terraform/modules/02.dynamodb/single_table/main.tf @@ -0,0 +1,114 @@ +# Single Table Design - DynamoDB +# Baseado no padrão: https://aws.amazon.com/pt/blogs/compute/creating-a-single-table-design-with-amazon-dynamodb/ +# +# Entity Patterns: +# PK: EntityType#EntityId (ex: ORDER#123, PRODUCT#1, PARTICIPANT#uuid, CERTIFICATE#123) +# SK: EntityType#EntityId (mesmo formato para acesso direto) +# +# GSIs para padrões de acesso: +# GSI1: Acesso por UUID (certificate by ID) +# GSI2: Acesso por email (orders, certificates, participants) +# GSI3: Acesso por product (products, orders, certificates) +# GSI4: Acesso por success flag (certificates) + +resource "aws_dynamodb_table" "single_table" { + name = var.table_name + billing_mode = "PAY_PER_REQUEST" + hash_key = "PK" + range_key = "SK" + + attribute { + name = "PK" + type = "S" + } + + attribute { + name = "SK" + type = "S" + } + + # Atributos base - entidades + attribute { + name = "GSI1PK" + type = "S" + } + + attribute { + name = "GSI1SK" + type = "S" + } + + attribute { + name = "GSI2PK" + type = "S" + } + + attribute { + name = "GSI2SK" + type = "S" + } + + attribute { + name = "GSI3PK" + type = "S" + } + + attribute { + name = "GSI3SK" + type = "S" + } + + attribute { + name = "GSI4PK" + type = "S" + } + + attribute { + name = "GSI4SK" + type = "S" + } + + # GSI1: CERT# lookups (certificate find_by_id) + global_secondary_index { + name = "GSI1" + hash_key = "GSI1PK" + range_key = "GSI1SK" + projection_type = "ALL" + } + + # GSI2: EMAIL# lookups (email lookups across entities) + global_secondary_index { + name = "GSI2" + hash_key = "GSI2PK" + range_key = "GSI2SK" + projection_type = "ALL" + } + + # GSI3: PRODUCT# lookups (product lookups) + global_secondary_index { + name = "GSI3" + hash_key = "GSI3PK" + range_key = "GSI3SK" + projection_type = "ALL" + } + + # GSI4: SUCCESS# lookups (certificate success flag) + global_secondary_index { + name = "GSI4" + hash_key = "GSI4PK" + range_key = "GSI4SK" + projection_type = "ALL" + } + + server_side_encryption { + enabled = true + } + + tags = { + Name = var.table_name + Environment = var.environment + Project = var.project_name + Design = "SingleTable" + CostCenter = "low-cost" + } +} diff --git a/terraform/modules/02.dynamodb/single_table/outputs.tf b/terraform/modules/02.dynamodb/single_table/outputs.tf new file mode 100644 index 0000000..d2e5d3c --- /dev/null +++ b/terraform/modules/02.dynamodb/single_table/outputs.tf @@ -0,0 +1,14 @@ +output "table_name" { + value = aws_dynamodb_table.single_table.name + description = "Nome da tabela única" +} + +output "table_arn" { + value = aws_dynamodb_table.single_table.arn + description = "ARN da tabela única" +} + +output "table_id" { + value = aws_dynamodb_table.single_table.id + description = "ID da tabela única" +} diff --git a/terraform/modules/02.dynamodb/single_table/variables.tf b/terraform/modules/02.dynamodb/single_table/variables.tf new file mode 100644 index 0000000..eba4420 --- /dev/null +++ b/terraform/modules/02.dynamodb/single_table/variables.tf @@ -0,0 +1,14 @@ +variable "table_name" { + description = "Nome da tabela única" + type = string +} + +variable "environment" { + description = "Ambiente de deploy" + type = string +} + +variable "project_name" { + description = "Nome do projeto" + type = string +}