MVP
N/A

Sem data

📡 Eventos e Schemas MVP — AegisTech IA

Tópicos Kafka e JSON Schemas para comunicação assíncrona entre serviços do MVP GovTech


📋 Índice

  1. Visão Geral
  2. Tópicos Kafka
  3. Schemas de Eventos
  4. Schemas de Dados
  5. Configuração Kafka
  6. Monitoramento

1. Visão Geral

Arquitetura de Eventos

O MVP utiliza Apache Kafka para comunicação assíncrona entre serviços, garantindo escalabilidade, confiabilidade e compliance LGPD/CNMP:

Carregando diagrama...

Princípios de Design

  • Event Sourcing: Todos os eventos são persistidos
  • Schema Registry: Validação de schemas centralizada
  • Idempotência: Operações seguras para retry
  • Auditoria: Todos os eventos são auditáveis
  • Compliance: Conformidade LGPD/CNMP

2. Tópicos Kafka

2.1 Tópicos de Manifestação

manifestation.created

topic: manifestation.created
partitions: 12
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

manifestation.updated

topic: manifestation.updated
partitions: 12
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

manifestation.triaged

topic: manifestation.triaged
partitions: 12
replication_factor: 3
retention_ms: 2592000000  # 30 dias
cleanup_policy: delete
compression_type: lz4

manifestation.resolved

topic: manifestation.resolved
partitions: 12
replication_factor: 3
retention_ms: 2592000000  # 30 dias
cleanup_policy: delete
compression_type: lz4

2.2 Tópicos de Mídia

media.uploaded

topic: media.uploaded
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

media.processing.started

topic: media.processing.started
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

media.processing.completed

topic: media.processing.completed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

media.processing.failed

topic: media.processing.failed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

2.3 Tópicos de Processamento

text.ocr.completed

topic: text.ocr.completed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

text.asr.completed

topic: text.asr.completed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

text.nlp.completed

topic: text.nlp.completed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

2.4 Tópicos de Triagem

triage.assigned

topic: triage.assigned
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

triage.completed

topic: triage.completed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

triage.escalated

topic: triage.escalated
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

2.5 Tópicos de Integração

integration.sent

topic: integration.sent
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

integration.received

topic: integration.received
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

integration.failed

topic: integration.failed
partitions: 8
replication_factor: 3
retention_ms: 604800000  # 7 dias
cleanup_policy: delete
compression_type: lz4

3. Schemas de Eventos

3.1 Schema Base de Evento

BaseEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "BaseEvent",
  "description": "Schema base para todos os eventos do MVP",
  "required": [
    "eventId",
    "eventType",
    "timestamp",
    "tenantId",
    "traceId",
    "spanId",
    "requestId",
    "version"
  ],
  "properties": {
    "eventId": {
      "type": "string",
      "format": "uuid",
      "description": "ID único do evento"
    },
    "eventType": {
      "type": "string",
      "description": "Tipo do evento"
    },
    "timestamp": {
      "type": "string",
      "format": "date-time",
      "description": "Timestamp do evento"
    },
    "tenantId": {
      "type": "string",
      "format": "uuid",
      "description": "ID do tenant"
    },
    "traceId": {
      "type": "string",
      "description": "ID de rastreamento distribuído"
    },
    "spanId": {
      "type": "string",
      "description": "ID do span"
    },
    "requestId": {
      "type": "string",
      "format": "uuid",
      "description": "ID da requisição"
    },
    "version": {
      "type": "string",
      "description": "Versão do schema"
    },
    "metadata": {
      "type": "object",
      "description": "Metadados adicionais"
    }
  }
}

3.2 Schemas de Manifestação

ManifestationCreatedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "ManifestationCreatedEvent",
  "description": "Evento de criação de manifestação",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "manifestationId",
        "type",
        "content",
        "consentData"
      ],
      "properties": {
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "type": {
          "type": "string",
          "enum": ["denuncia", "solicitacao", "reclamacao", "elogio"],
          "description": "Tipo da manifestação"
        },
        "content": {
          "type": "string",
          "description": "Conteúdo da manifestação"
        },
        "contentHash": {
          "type": "string",
          "description": "Hash SHA-256 do conteúdo"
        },
        "consentData": {
          "type": "object",
          "description": "Dados de consentimento LGPD",
          "properties": {
            "granted": {
              "type": "boolean"
            },
            "consentType": {
              "type": "string",
              "enum": ["processing", "storage", "sharing", "analysis"]
            },
            "legalBasis": {
              "type": "string"
            },
            "grantedAt": {
              "type": "string",
              "format": "date-time"
            }
          }
        },
        "anonymized": {
          "type": "boolean",
          "description": "Se a manifestação foi anonimizada"
        },
        "mediaFiles": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "fileId": {
                "type": "string",
                "format": "uuid"
              },
              "fileName": {
                "type": "string"
              },
              "fileType": {
                "type": "string",
                "enum": ["pdf", "image", "audio", "video"]
              },
              "fileSize": {
                "type": "integer"
              },
              "fileHash": {
                "type": "string"
              }
            }
          }
        }
      }
    }
  ]
}

ManifestationTriagedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "ManifestationTriagedEvent",
  "description": "Evento de triagem de manifestação",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "manifestationId",
        "triageId",
        "analystId",
        "priorityScore",
        "urgencyScore",
        "gravityScore",
        "status"
      ],
      "properties": {
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "triageId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da triagem"
        },
        "analystId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do analista"
        },
        "priorityScore": {
          "type": "integer",
          "minimum": 0,
          "maximum": 100,
          "description": "Score de prioridade"
        },
        "urgencyScore": {
          "type": "integer",
          "minimum": 0,
          "maximum": 100,
          "description": "Score de urgência"
        },
        "gravityScore": {
          "type": "integer",
          "minimum": 0,
          "maximum": 100,
          "description": "Score de gravidade"
        },
        "status": {
          "type": "string",
          "enum": ["pending", "in_progress", "completed", "escalated"],
          "description": "Status da triagem"
        },
        "humanDecision": {
          "type": "string",
          "description": "Decisão humana"
        },
        "aiExplanation": {
          "type": "string",
          "description": "Explicação da IA"
        },
        "processingTime": {
          "type": "integer",
          "description": "Tempo de processamento em segundos"
        }
      }
    }
  ]
}

3.3 Schemas de Mídia

MediaUploadedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "MediaUploadedEvent",
  "description": "Evento de upload de mídia",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "mediaFileId",
        "manifestationId",
        "fileName",
        "fileType",
        "fileSize",
        "fileHash",
        "storagePath"
      ],
      "properties": {
        "mediaFileId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do arquivo de mídia"
        },
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "fileName": {
          "type": "string",
          "description": "Nome do arquivo"
        },
        "fileType": {
          "type": "string",
          "enum": ["pdf", "image", "audio", "video"],
          "description": "Tipo do arquivo"
        },
        "mimeType": {
          "type": "string",
          "description": "Tipo MIME"
        },
        "fileSize": {
          "type": "integer",
          "description": "Tamanho do arquivo em bytes"
        },
        "fileHash": {
          "type": "string",
          "description": "Hash SHA-256 do arquivo"
        },
        "storagePath": {
          "type": "string",
          "description": "Caminho de armazenamento"
        },
        "encryptionKey": {
          "type": "string",
          "description": "Chave de criptografia"
        }
      }
    }
  ]
}

MediaProcessingCompletedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "MediaProcessingCompletedEvent",
  "description": "Evento de conclusão de processamento de mídia",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "mediaFileId",
        "manifestationId",
        "processingJobId",
        "jobType",
        "status",
        "result"
      ],
      "properties": {
        "mediaFileId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do arquivo de mídia"
        },
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "processingJobId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do job de processamento"
        },
        "jobType": {
          "type": "string",
          "enum": ["ocr", "asr", "nlp", "classification"],
          "description": "Tipo do job"
        },
        "status": {
          "type": "string",
          "enum": ["completed", "failed"],
          "description": "Status do processamento"
        },
        "result": {
          "type": "object",
          "description": "Resultado do processamento",
          "properties": {
            "extractedText": {
              "type": "string",
              "description": "Texto extraído (OCR/ASR)"
            },
            "confidenceScore": {
              "type": "number",
              "minimum": 0,
              "maximum": 1,
              "description": "Score de confiança"
            },
            "processingTime": {
              "type": "integer",
              "description": "Tempo de processamento em segundos"
            },
            "metadata": {
              "type": "object",
              "description": "Metadados do processamento"
            }
          }
        },
        "error": {
          "type": "object",
          "description": "Erro (se status = failed)",
          "properties": {
            "code": {
              "type": "string"
            },
            "message": {
              "type": "string"
            },
            "details": {
              "type": "object"
            }
          }
        }
      }
    }
  ]
}

3.4 Schemas de Processamento

TextOCRCompletedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "TextOCRCompletedEvent",
  "description": "Evento de conclusão de OCR",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "ocrResultId",
        "processingJobId",
        "manifestationId",
        "extractedText",
        "confidenceScore"
      ],
      "properties": {
        "ocrResultId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do resultado OCR"
        },
        "processingJobId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do job de processamento"
        },
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "extractedText": {
          "type": "string",
          "description": "Texto extraído"
        },
        "confidenceScore": {
          "type": "number",
          "minimum": 0,
          "maximum": 1,
          "description": "Score de confiança"
        },
        "boundingBoxes": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "text": {
                "type": "string"
              },
              "confidence": {
                "type": "number"
              },
              "bbox": {
                "type": "object",
                "properties": {
                  "x": {"type": "number"},
                  "y": {"type": "number"},
                  "width": {"type": "number"},
                  "height": {"type": "number"}
                }
              }
            }
          }
        },
        "processingTime": {
          "type": "integer",
          "description": "Tempo de processamento em segundos"
        }
      }
    }
  ]
}

TextNLPCompletedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "TextNLPCompletedEvent",
  "description": "Evento de conclusão de NLP",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "nlpResultId",
        "manifestationId",
        "summary",
        "entities",
        "classification",
        "embeddings"
      ],
      "properties": {
        "nlpResultId": {
          "type": "string",
          "format": "uuid",
          "description": "ID do resultado NLP"
        },
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "summary": {
          "type": "string",
          "description": "Resumo do texto"
        },
        "entities": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "type": {
                "type": "string",
                "enum": ["pessoa", "organizacao", "local", "data", "valor"]
              },
              "value": {
                "type": "string"
              },
              "confidence": {
                "type": "number",
                "minimum": 0,
                "maximum": 1
              }
            }
          }
        },
        "classification": {
          "type": "object",
          "properties": {
            "category": {
              "type": "string"
            },
            "confidence": {
              "type": "number",
              "minimum": 0,
              "maximum": 1
            },
            "subcategories": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {
                  "name": {"type": "string"},
                  "confidence": {"type": "number"}
                }
              }
            }
          }
        },
        "embeddings": {
          "type": "array",
          "items": {
            "type": "number"
          },
          "description": "Embeddings vetoriais"
        },
        "confidenceScore": {
          "type": "number",
          "minimum": 0,
          "maximum": 1,
          "description": "Score de confiança geral"
        },
        "processingTime": {
          "type": "integer",
          "description": "Tempo de processamento em segundos"
        }
      }
    }
  ]
}

3.5 Schemas de Integração

IntegrationSentEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "IntegrationSentEvent",
  "description": "Evento de envio de integração",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "integrationId",
        "manifestationId",
        "externalSystem",
        "endpoint",
        "payload"
      ],
      "properties": {
        "integrationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da integração"
        },
        "manifestationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da manifestação"
        },
        "externalSystem": {
          "type": "string",
          "enum": ["pje", "esus", "sinesp", "ouvidoria"],
          "description": "Sistema externo"
        },
        "endpoint": {
          "type": "string",
          "description": "Endpoint de destino"
        },
        "payload": {
          "type": "object",
          "description": "Dados enviados"
        },
        "payloadHash": {
          "type": "string",
          "description": "Hash SHA-256 do payload"
        },
        "retryCount": {
          "type": "integer",
          "minimum": 0,
          "description": "Número de tentativas"
        },
        "maxRetries": {
          "type": "integer",
          "minimum": 0,
          "description": "Número máximo de tentativas"
        }
      }
    }
  ]
}

IntegrationReceivedEvent

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "IntegrationReceivedEvent",
  "description": "Evento de recebimento de integração",
  "allOf": [
    {
      "$ref": "#/definitions/BaseEvent"
    },
    {
      "type": "object",
      "required": [
        "integrationId",
        "externalSystem",
        "responseCode",
        "responseData"
      ],
      "properties": {
        "integrationId": {
          "type": "string",
          "format": "uuid",
          "description": "ID da integração"
        },
        "externalSystem": {
          "type": "string",
          "enum": ["pje", "esus", "sinesp", "ouvidoria"],
          "description": "Sistema externo"
        },
        "responseCode": {
          "type": "integer",
          "description": "Código de resposta HTTP"
        },
        "responseData": {
          "type": "object",
          "description": "Dados de resposta"
        },
        "responseTime": {
          "type": "integer",
          "description": "Tempo de resposta em ms"
        },
        "success": {
          "type": "boolean",
          "description": "Se a integração foi bem-sucedida"
        }
      }
    }
  ]
}

4. Schemas de Dados

4.1 Schema de Manifestação

ManifestationData

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "ManifestationData",
  "description": "Schema de dados de manifestação",
  "required": [
    "id",
    "tenantId",
    "type",
    "content",
    "status",
    "createdAt"
  ],
  "properties": {
    "id": {
      "type": "string",
      "format": "uuid",
      "description": "ID único da manifestação"
    },
    "tenantId": {
      "type": "string",
      "format": "uuid",
      "description": "ID do tenant"
    },
    "type": {
      "type": "string",
      "enum": ["denuncia", "solicitacao", "reclamacao", "elogio"],
      "description": "Tipo da manifestação"
    },
    "content": {
      "type": "string",
      "description": "Conteúdo da manifestação"
    },
    "contentHash": {
      "type": "string",
      "description": "Hash SHA-256 do conteúdo"
    },
    "status": {
      "type": "string",
      "enum": ["pending", "processing", "triaged", "resolved", "archived"],
      "description": "Status da manifestação"
    },
    "metadata": {
      "type": "object",
      "description": "Metadados adicionais"
    },
    "consentData": {
      "type": "object",
      "description": "Dados de consentimento LGPD",
      "properties": {
        "granted": {
          "type": "boolean"
        },
        "consentType": {
          "type": "string",
          "enum": ["processing", "storage", "sharing", "analysis"]
        },
        "legalBasis": {
          "type": "string"
        },
        "grantedAt": {
          "type": "string",
          "format": "date-time"
        }
      }
    },
    "anonymized": {
      "type": "boolean",
      "description": "Se a manifestação foi anonimizada"
    },
    "createdAt": {
      "type": "string",
      "format": "date-time",
      "description": "Data de criação"
    },
    "updatedAt": {
      "type": "string",
      "format": "date-time",
      "description": "Data de atualização"
    }
  }
}

4.2 Schema de Mídia

MediaFileData

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "MediaFileData",
  "description": "Schema de dados de arquivo de mídia",
  "required": [
    "id",
    "manifestationId",
    "fileName",
    "fileType",
    "fileSize",
    "fileHash",
    "storagePath"
  ],
  "properties": {
    "id": {
      "type": "string",
      "format": "uuid",
      "description": "ID único do arquivo"
    },
    "manifestationId": {
      "type": "string",
      "format": "uuid",
      "description": "ID da manifestação"
    },
    "fileName": {
      "type": "string",
      "description": "Nome do arquivo"
    },
    "fileType": {
      "type": "string",
      "enum": ["pdf", "image", "audio", "video"],
      "description": "Tipo do arquivo"
    },
    "mimeType": {
      "type": "string",
      "description": "Tipo MIME"
    },
    "fileSize": {
      "type": "integer",
      "description": "Tamanho do arquivo em bytes"
    },
    "fileHash": {
      "type": "string",
      "description": "Hash SHA-256 do arquivo"
    },
    "storagePath": {
      "type": "string",
      "description": "Caminho de armazenamento"
    },
    "encryptionKey": {
      "type": "string",
      "description": "Chave de criptografia"
    },
    "metadata": {
      "type": "object",
      "description": "Metadados do arquivo"
    },
    "createdAt": {
      "type": "string",
      "format": "date-time",
      "description": "Data de criação"
    },
    "updatedAt": {
      "type": "string",
      "format": "date-time",
      "description": "Data de atualização"
    }
  }
}

4.3 Schema de Triagem

TriageData

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "TriageData",
  "description": "Schema de dados de triagem",
  "required": [
    "id",
    "manifestationId",
    "userId",
    "priorityScore",
    "urgencyScore",
    "gravityScore",
    "status"
  ],
  "properties": {
    "id": {
      "type": "string",
      "format": "uuid",
      "description": "ID único da triagem"
    },
    "manifestationId": {
      "type": "string",
      "format": "uuid",
      "description": "ID da manifestação"
    },
    "userId": {
      "type": "string",
      "format": "uuid",
      "description": "ID do usuário"
    },
    "priorityScore": {
      "type": "integer",
      "minimum": 0,
      "maximum": 100,
      "description": "Score de prioridade"
    },
    "urgencyScore": {
      "type": "integer",
      "minimum": 0,
      "maximum": 100,
      "description": "Score de urgência"
    },
    "gravityScore": {
      "type": "integer",
      "minimum": 0,
      "maximum": 100,
      "description": "Score de gravidade"
    },
    "status": {
      "type": "string",
      "enum": ["pending", "in_progress", "completed", "escalated"],
      "description": "Status da triagem"
    },
    "humanDecision": {
      "type": "string",
      "description": "Decisão humana"
    },
    "aiExplanation": {
      "type": "string",
      "description": "Explicação da IA"
    },
    "metadata": {
      "type": "object",
      "description": "Metadados da triagem"
    },
    "createdAt": {
      "type": "string",
      "format": "date-time",
      "description": "Data de criação"
    },
    "updatedAt": {
      "type": "string",
      "format": "date-time",
      "description": "Data de atualização"
    }
  }
}

5. Configuração Kafka

5.1 Configuração do Cluster

Kafka Broker

kafka:
  brokers:
    - "kafka-1:9092"
    - "kafka-2:9092"
    - "kafka-3:9092"
  
  security:
    protocol: "SASL_SSL"
    sasl:
      mechanism: "PLAIN"
      username: "kafka-user"
      password: "kafka-password"
    ssl:
      truststore_location: "/opt/kafka/truststore.jks"
      truststore_password: "truststore-password"
  
  producer:
    acks: "all"
    retries: 3
    batch_size: 16384
    linger_ms: 5
    buffer_memory: 33554432
    compression_type: "lz4"
    max_in_flight_requests_per_connection: 5
    enable_idempotence: true
  
  consumer:
    group_id: "mvp-consumer-group"
    auto_offset_reset: "earliest"
    enable_auto_commit: false
    max_poll_records: 500
    session_timeout_ms: 30000
    heartbeat_interval_ms: 10000
    max_poll_interval_ms: 300000

Schema Registry

schema_registry:
  url: "http://schema-registry:8081"
  username: "schema-registry-user"
  password: "schema-registry-password"
  
  compatibility:
    level: "BACKWARD"
    default: true
  
  subjects:
    - "manifestation.created-value"
    - "manifestation.updated-value"
    - "manifestation.triaged-value"
    - "media.uploaded-value"
    - "media.processing.completed-value"
    - "text.ocr.completed-value"
    - "text.nlp.completed-value"
    - "triage.completed-value"
    - "integration.sent-value"
    - "integration.received-value"

5.2 Configuração de Produção

Producer Configuration

import { Kafka, Producer } from 'kafkajs';

const kafka = new Kafka({
  clientId: 'mvp-producer',
  brokers: ['kafka-1:9092', 'kafka-2:9092', 'kafka-3:9092'],
  sasl: {
    mechanism: 'plain',
    username: 'kafka-user',
    password: 'kafka-password',
  },
  ssl: true,
});

const producer: Producer = kafka.producer({
  maxInFlightRequests: 1,
  idempotent: true,
  transactionTimeout: 30000,
});

export class EventProducer {
  async sendEvent(topic: string, event: any): Promise<void> {
    try {
      await producer.send({
        topic,
        messages: [{
          key: event.eventId,
          value: JSON.stringify(event),
          headers: {
            'event-type': event.eventType,
            'tenant-id': event.tenantId,
            'trace-id': event.traceId,
            'span-id': event.spanId,
            'request-id': event.requestId,
            'version': event.version,
          },
        }],
      });
    } catch (error) {
      console.error('Error sending event:', error);
      throw error;
    }
  }
}

5.3 Configuração de Consumo

Consumer Configuration

import { Kafka, Consumer } from 'kafkajs';

const kafka = new Kafka({
  clientId: 'mvp-consumer',
  brokers: ['kafka-1:9092', 'kafka-2:9092', 'kafka-3:9092'],
  sasl: {
    mechanism: 'plain',
    username: 'kafka-user',
    password: 'kafka-password',
  },
  ssl: true,
});

const consumer: Consumer = kafka.consumer({
  groupId: 'mvp-consumer-group',
  sessionTimeout: 30000,
  heartbeatInterval: 10000,
  maxWaitTimeInMs: 5000,
});

export class EventConsumer {
  async consumeEvents(topics: string[]): Promise<void> {
    await consumer.subscribe({ topics });
    
    await consumer.run({
      eachMessage: async ({ topic, partition, message }) => {
        try {
          const event = JSON.parse(message.value?.toString() || '{}');
          
          // Processar evento
          await this.processEvent(topic, event);
          
          // Commit manual
          await consumer.commitOffsets([{
            topic,
            partition,
            offset: message.offset,
          }]);
        } catch (error) {
          console.error('Error processing event:', error);
          // Implementar dead letter queue
        }
      },
    });
  }
  
  private async processEvent(topic: string, event: any): Promise<void> {
    // Implementar processamento específico por tópico
    switch (topic) {
      case 'manifestation.created':
        await this.handleManifestationCreated(event);
        break;
      case 'media.processing.completed':
        await this.handleMediaProcessingCompleted(event);
        break;
      case 'triage.completed':
        await this.handleTriageCompleted(event);
        break;
      default:
        console.warn(`Unknown topic: ${topic}`);
    }
  }
}

6. Monitoramento

6.1 Métricas Kafka

Métricas de Produção

kafka_producer_metrics:
  - "kafka.producer.record-send-rate"
  - "kafka.producer.record-send-total"
  - "kafka.producer.record-error-rate"
  - "kafka.producer.record-error-total"
  - "kafka.producer.record-retry-rate"
  - "kafka.producer.record-retry-total"
  - "kafka.producer.batch-size-avg"
  - "kafka.producer.batch-size-max"
  - "kafka.producer.compression-ratio-avg"
  - "kafka.producer.produce-throttle-time-avg"

Métricas de Consumo

kafka_consumer_metrics:
  - "kafka.consumer.records-consumed-rate"
  - "kafka.consumer.records-consumed-total"
  - "kafka.consumer.records-lag-max"
  - "kafka.consumer.records-lag-avg"
  - "kafka.consumer.fetch-rate"
  - "kafka.consumer.fetch-total"
  - "kafka.consumer.fetch-latency-avg"
  - "kafka.consumer.fetch-latency-max"
  - "kafka.consumer.commit-rate"
  - "kafka.consumer.commit-total"

6.2 Alertas Kafka

Alertas de Produção

kafka_producer_alerts:
  high_error_rate:
    condition: "kafka.producer.record-error-rate > 0.01"
    duration: "5m"
    severity: "warning"
    notification: ["slack", "email"]
  
  high_retry_rate:
    condition: "kafka.producer.record-retry-rate > 0.05"
    duration: "5m"
    severity: "warning"
    notification: ["slack"]
  
  low_throughput:
    condition: "kafka.producer.record-send-rate < 100"
    duration: "10m"
    severity: "info"
    notification: ["slack"]

Alertas de Consumo

kafka_consumer_alerts:
  high_lag:
    condition: "kafka.consumer.records-lag-max > 1000"
    duration: "5m"
    severity: "critical"
    notification: ["pagerduty", "slack"]
  
  consumer_lag:
    condition: "kafka.consumer.records-lag-avg > 500"
    duration: "10m"
    severity: "warning"
    notification: ["slack"]
  
  low_throughput:
    condition: "kafka.consumer.records-consumed-rate < 50"
    duration: "15m"
    severity: "info"
    notification: ["slack"]

6.3 Dashboards Kafka

Dashboard de Produção

kafka_producer_dashboard:
  panels:
    - title: "Record Send Rate"
      type: "graph"
      query: "rate(kafka.producer.record-send-total[5m])"
    
    - title: "Record Error Rate"
      type: "graph"
      query: "rate(kafka.producer.record-error-total[5m])"
    
    - title: "Batch Size"
      type: "graph"
      query: "kafka.producer.batch-size-avg"
    
    - title: "Compression Ratio"
      type: "graph"
      query: "kafka.producer.compression-ratio-avg"

Dashboard de Consumo

kafka_consumer_dashboard:
  panels:
    - title: "Records Consumed Rate"
      type: "graph"
      query: "rate(kafka.consumer.records-consumed-total[5m])"
    
    - title: "Consumer Lag"
      type: "graph"
      query: "kafka.consumer.records-lag-max"
    
    - title: "Fetch Latency"
      type: "graph"
      query: "kafka.consumer.fetch-latency-avg"
    
    - title: "Commit Rate"
      type: "graph"
      query: "rate(kafka.consumer.commit-total[5m])"

📚 Referências