franchising 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cli/template-assets/api/src/main.ts +13 -11
  2. package/dist/cli/template-assets/api/src/modules/health/controller.ts +25 -4
  3. package/dist/cli/template-assets/api/src/shared/http/errors.ts +17 -0
  4. package/dist/cli/template-assets/cloudflare/cache.service.ts +1 -0
  5. package/dist/cli/template-assets/cloudflare/queue.service.ts +1 -0
  6. package/dist/cli/template-assets/cloudflare/worker.ts +4 -0
  7. package/dist/cli/template-assets/github/PULL_REQUEST_TEMPLATE.md +37 -0
  8. package/dist/cli/template-assets/observability/adapters.ts +37 -0
  9. package/dist/cli/template-assets/observability/bootstrap.ts +48 -0
  10. package/dist/cli/template-assets/observability/env.ts +21 -0
  11. package/dist/cli/template-assets/observability/index.ts +10 -0
  12. package/dist/cli/template-assets/observability/lifecycle.ts +97 -0
  13. package/dist/cli/template-assets/observability/local-index.ts +9 -0
  14. package/dist/cli/template-assets/observability/register.ts +12 -0
  15. package/dist/cli/template-assets/packages/jobs/src/index.ts +4 -40
  16. package/dist/cli/template-assets/packages/jobs/src/shared/queue/job-id.ts +9 -0
  17. package/dist/cli/template-assets/packages/jobs/src/shared/queue/options.ts +7 -0
  18. package/dist/cli/template-assets/packages/jobs/src/shared/queue/prefix.ts +18 -0
  19. package/dist/cli/template-assets/packages/queue/src/index.ts +4 -0
  20. package/dist/cli/template-assets/packages/queue/src/shared/errors/failure-reason.ts +7 -0
  21. package/dist/cli/template-assets/packages/{queue-runtime/src/index.ts → queue/src/shared/redis/connection.ts} +2 -15
  22. package/dist/cli/template-assets/packages/queue/src/types/redis/connection.ts +6 -0
  23. package/dist/cli/template-assets/packages/webhooks/src/index.ts +11 -0
  24. package/dist/cli/template-assets/packages/webhooks/src/shared/crypto/secret.ts +81 -0
  25. package/dist/cli/template-assets/packages/webhooks/src/shared/signing/headers.ts +43 -0
  26. package/dist/cli/template-assets/packages/webhooks/src/shared/url/deliverable.ts +58 -0
  27. package/dist/cli/template-assets/packages/webhooks/src/types/webhooks/job.ts +18 -0
  28. package/dist/cli/template-assets/packages/webhooks/test/webhooks.test.ts.tpl +69 -0
  29. package/dist/cli/template-assets/root/dot-dockerignore +88 -8
  30. package/dist/cli/template-assets/root/dot-oxlintrc.json +22 -0
  31. package/dist/cli/template-assets/root/lefthook.yml +32 -8
  32. package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +2 -3
  33. package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +1 -1
  34. package/dist/cli/template-assets/web/src/app/page.tsx +1 -0
  35. package/dist/cli/template-assets/web/src/{lib/api-client.ts → shared/api/client.ts} +11 -8
  36. package/dist/cli/template-assets/web/src/{lib/server-auth.ts → shared/auth/server.ts} +1 -2
  37. package/dist/cli/template-assets/web/src/types/api.ts +0 -15
  38. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/controller.ts +81 -0
  39. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/create-endpoint.dto.ts +25 -0
  40. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/dto/endpoint.dto.ts +28 -0
  41. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/module.ts +27 -0
  42. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/repository.ts +147 -0
  43. package/dist/cli/template-assets/webhooks/api/src/modules/webhooks/service.ts +119 -0
  44. package/dist/cli/template-assets/webhooks/api/src/types/webhooks/endpoint.ts +26 -0
  45. package/dist/cli/template-assets/webhooks/worker/src/env.ts +18 -0
  46. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/dispatcher.ts +119 -0
  47. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/module.ts +16 -0
  48. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/processor.ts +176 -0
  49. package/dist/cli/template-assets/webhooks/worker/src/modules/queue/repository.ts +187 -0
  50. package/dist/cli/template-assets/webhooks/worker/src/shared/http/deliver.ts +41 -0
  51. package/dist/cli/template-assets/webhooks/worker/src/types/webhooks/dispatch.ts +26 -0
  52. package/dist/cli/template-assets/worker/src/app.module.ts +14 -0
  53. package/dist/cli/template-assets/worker/src/main.ts +24 -0
  54. package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +26 -3
  55. package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +22 -7
  56. package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +13 -1
  57. package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +6 -6
  58. package/dist/cli/template-assets/worker-messaging/src/env.ts +1 -1
  59. package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +2 -4
  60. package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +1 -1
  61. package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +32 -10
  62. package/dist/cli.js +631 -314
  63. package/dist/{index-BDYdEWl2.d.ts → index-B_byXBRW.d.cts} +10 -2
  64. package/dist/{index-BDYdEWl2.d.cts → index-B_byXBRW.d.ts} +10 -2
  65. package/dist/{index-u3ArUXO0.d.ts → index-CNlb6WNr.d.ts} +2 -2
  66. package/dist/{index--EJQTnHy.d.cts → index-I_Nx5SsQ.d.cts} +2 -2
  67. package/dist/index.cjs +1 -1
  68. package/dist/index.d.cts +1 -1
  69. package/dist/index.d.ts +1 -1
  70. package/dist/index.js +1 -1
  71. package/dist/messaging/index.cjs +1 -1
  72. package/dist/messaging/index.d.cts +1 -1
  73. package/dist/messaging/index.d.ts +1 -1
  74. package/dist/messaging/index.js +1 -1
  75. package/dist/sso/client.d.cts +7 -2
  76. package/dist/sso/client.d.ts +7 -2
  77. package/dist/sso/index.cjs +3 -1
  78. package/dist/sso/index.cjs.map +1 -1
  79. package/dist/sso/index.d.cts +1 -1
  80. package/dist/sso/index.d.ts +1 -1
  81. package/dist/sso/index.js +3 -1
  82. package/dist/sso/index.js.map +1 -1
  83. package/dist/sso/nestjs.d.cts +2 -2
  84. package/dist/sso/nestjs.d.ts +2 -2
  85. package/dist/sso/resource.d.cts +2 -2
  86. package/dist/sso/resource.d.ts +2 -2
  87. package/dist/version-Cm1EJ-YK.js +1 -0
  88. package/dist/{version-CrBclf1K.cjs → version-iERj9NJ6.cjs} +1 -1
  89. package/package.json +1 -1
  90. package/dist/cli/template-assets/api/src/errors/codes.ts +0 -17
  91. package/dist/cli/template-assets/api/src/errors/index.ts +0 -16
  92. package/dist/cli/template-assets/api/src/filters/exception.ts +0 -53
  93. package/dist/cli/template-assets/api/src/shared/exceptions.ts +0 -40
  94. package/dist/cli/template-assets/api/src/shared/response.ts +0 -31
  95. package/dist/cli/template-assets/api/src/telemetry.ts +0 -59
  96. package/dist/version-BhZpPjUh.js +0 -1
  97. /package/dist/cli/template-assets/web/src/{lib/auth-client.ts → shared/auth/client.ts} +0 -0
@@ -5,7 +5,7 @@ import 'reflect-metadata';
5
5
  * e a auto-instrumentacao precisa envolver o Nest, o banco e os clients HTTP
6
6
  * antes de eles existirem.
7
7
  */
8
- import './telemetry';
8
+ import '__ROCK_OBSERVABILITY__/register';
9
9
  // #endif
10
10
  import { Logger, ValidationPipe, VersioningType } from '@nestjs/common';
11
11
  import { NestFactory } from '@nestjs/core';
@@ -15,10 +15,8 @@ import {
15
15
  } from '@nestjs/platform-fastify';
16
16
  import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
17
17
  // #if telemetry
18
- import {
19
- createTelemetryFastifyOptions,
20
- TelemetryNestLogger,
21
- } from 'franchising/telemetry';
18
+ import { createTelemetryFastifyOptions } from 'franchising/telemetry';
19
+ import { bootstrapFailed, observeProcess } from '__ROCK_OBSERVABILITY__';
22
20
  // #endif
23
21
  import scalarApiReference from '@scalar/fastify-api-reference';
24
22
  // #if inlineAuth
@@ -31,7 +29,6 @@ import { MessagingService } from './modules/messaging/service';
31
29
  // #endif
32
30
  import { AppModule } from './app.module';
33
31
  import { env } from './env';
34
- import { ApiExceptionFilter } from './filters/exception';
35
32
  import { API_DOCS_PATH, API_VERSION, API_VERSION_PREFIX } from './types';
36
33
 
37
34
  async function bootstrap() {
@@ -55,7 +52,7 @@ async function bootstrap() {
55
52
  { bodyParser: false, bufferLogs: true },
56
53
  );
57
54
 
58
- app.useLogger(app.get(TelemetryNestLogger));
55
+ observeProcess(app);
59
56
  // #else
60
57
  const app = await NestFactory.create<NestFastifyApplication>(
61
58
  AppModule,
@@ -77,6 +74,7 @@ async function bootstrap() {
77
74
  });
78
75
 
79
76
  app.enableCors({ origin: env.CLIENT_ORIGIN, credentials: true });
77
+
80
78
  app.useGlobalPipes(
81
79
  new ValidationPipe({
82
80
  whitelist: true,
@@ -84,7 +82,6 @@ async function bootstrap() {
84
82
  transform: true,
85
83
  }),
86
84
  );
87
- app.useGlobalFilters(new ApiExceptionFilter());
88
85
 
89
86
  // #if inlineAuth
90
87
  /*
@@ -98,10 +95,12 @@ async function bootstrap() {
98
95
  messagingService: app.get(MessagingService),
99
96
  // #endif
100
97
  });
98
+
101
99
  const httpAdapter = app.getHttpAdapter().getInstance();
102
100
 
103
101
  httpAdapter.all(`/${API_VERSION_PREFIX}/auth/*`, async (request, reply) => {
104
102
  const url = new URL(request.url, env.BETTER_AUTH_URL);
103
+
105
104
  const response = await auth.handler(
106
105
  new Request(url, {
107
106
  method: request.method,
@@ -125,7 +124,7 @@ async function bootstrap() {
125
124
  new DocumentBuilder()
126
125
  .setTitle('__ROCK_PROJECT_NAME__')
127
126
  .setDescription(
128
- 'Sucesso responde `{ ok: true, data }`; erro responde `{ ok: false, code, message, errors? }`.',
127
+ 'Sucesso responde `{ ok: true, data, pagination? }`; erro responde `{ ok: false, error: { code, message, extra? } }` (franchising/http).',
129
128
  )
130
129
  .setVersion('1.0.0')
131
130
  .addBearerAuth(
@@ -181,9 +180,12 @@ async function bootstrap() {
181
180
 
182
181
  logger.log(`API em http://localhost:${env.PORT}/${API_VERSION_PREFIX}`);
183
182
 
184
- if (env.API_DOCS_ENABLED) {
183
+ if (env.API_DOCS_ENABLED)
185
184
  logger.log(`Docs em http://localhost:${env.PORT}/${API_DOCS_PATH}`);
186
- }
187
185
  }
188
186
 
187
+ // #if telemetry
188
+ void bootstrap().catch(bootstrapFailed('a API'));
189
+ // #else
189
190
  void bootstrap();
191
+ // #endif
@@ -1,9 +1,12 @@
1
1
  import { Controller, Get } from '@nestjs/common';
2
- import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
2
+ import { ApiOperation, ApiTags } from '@nestjs/swagger';
3
3
  // #if authModule
4
4
  import { AllowAnonymous } from '@thallesp/nestjs-better-auth';
5
5
  // #endif
6
- import { ok } from '../../shared/response';
6
+ import { ok, serviceUnavailable } from 'franchising/http';
7
+ import { APIEnvelope, APIErrors } from 'franchising/http/swagger';
8
+ import { Errors } from '../../shared/http/errors';
9
+ import { HealthResponseDto } from './dto/response.dto';
7
10
  import { HealthService } from './service';
8
11
 
9
12
  @ApiTags('Saude')
@@ -11,13 +14,31 @@ import { HealthService } from './service';
11
14
  export class HealthController {
12
15
  constructor(private readonly service: HealthService) {}
13
16
 
17
+ /**
18
+ * Disponibilidade da API.
19
+ *
20
+ * @remarks
21
+ * Banco ou cache fora do ar respondem 503, e nao 200 com `degraded`: o
22
+ * healthcheck do orquestrador olha o status, e e com uma dependencia caida
23
+ * que ele precisa tirar a instancia do ar ou reinicia-la.
24
+ */
14
25
  @Get()
15
26
  // #if authModule
16
27
  @AllowAnonymous()
17
28
  // #endif
18
29
  @ApiOperation({ summary: 'Verifica a disponibilidade da API' })
19
- @ApiOkResponse({ description: 'Estado da API e das dependencias.' })
30
+ @APIEnvelope(HealthResponseDto)
31
+ @APIErrors({ 503: [Errors.DependencyUnavailable] })
20
32
  async check() {
21
- return ok(await this.service.check());
33
+ const health = await this.service.check();
34
+
35
+ /*
36
+ * Sem `extra`: todo 5xx sai com corpo generico pelo `ErrorFilter`, entao
37
+ * o detalhe de qual dependencia caiu so apareceria no log.
38
+ */
39
+ if (health.status !== 'ok')
40
+ throw serviceUnavailable(Errors.DependencyUnavailable);
41
+
42
+ return ok(health);
22
43
  }
23
44
  }
@@ -0,0 +1,17 @@
1
+ import { defineErrors } from 'franchising/http';
2
+
3
+ /**
4
+ * Erros da API.
5
+ *
6
+ * @remarks
7
+ * Cada chave vira o `code` do envelope `{ ok: false, error: { code, message } }`,
8
+ * e o cliente ramifica por ele, nunca pela mensagem. Os codigos genericos
9
+ * (`NotFound`, `ValidationFailed`, `InternalError`...) ja vem em
10
+ * `CommonErrors` e sao reservados: aqui entram so os do dominio do app.
11
+ */
12
+ export const Errors = defineErrors({
13
+ DependencyUnavailable: {
14
+ message: 'A required dependency is unavailable.',
15
+ status: 503,
16
+ },
17
+ });
@@ -18,6 +18,7 @@ export class CacheService {
18
18
  async ping(): Promise<string> {
19
19
  if (!this.namespace) return 'disabled';
20
20
  await this.namespace.get('__health');
21
+
21
22
  return 'up';
22
23
  }
23
24
  }
@@ -10,6 +10,7 @@ export class QueueService {
10
10
  async send(queue: JobQueue, job: Job): Promise<void> {
11
11
  const bindings = env as unknown as Record<string, Queue<Job>>;
12
12
  const binding = bindings[queueBindings[queue]];
13
+
13
14
  if (!binding) throw new Error('Queue binding is missing.');
14
15
  await binding.send(job);
15
16
  }
@@ -14,16 +14,20 @@ export default {
14
14
  let cleanup: Promise<void> | undefined;
15
15
  const close = () => (cleanup ??= app.close());
16
16
  const release = () => context.waitUntil(close());
17
+
17
18
  server.once('request', (_request, response) => {
18
19
  response.once('finish', release);
19
20
  response.once('close', release);
20
21
  });
22
+
21
23
  try {
22
24
  /* `address()` do Node tambem devolve string (pipe); o Worker nunca usa pipe. */
23
25
  const handler = httpServerHandler(
24
26
  server as unknown as Parameters<typeof httpServerHandler>[0],
25
27
  );
28
+
26
29
  if (!handler.fetch) throw new Error('Cloudflare HTTP handler is unavailable.');
30
+
27
31
  return await handler.fetch(request, bindings, context);
28
32
  } catch (error) {
29
33
  await close();
@@ -0,0 +1,37 @@
1
+ ## Resumo
2
+
3
+ Descreva de forma breve o que mudou e por quê.
4
+
5
+ ## Contexto
6
+
7
+ - Problema ou objetivo:
8
+ - Escopo:
9
+ - Fora de escopo:
10
+
11
+ ## Por quê?
12
+
13
+ Por que isso foi necessário?
14
+
15
+ ## Como validar
16
+
17
+ - [ ] Testei localmente
18
+ - [ ] Os checks relevantes passaram
19
+ - [ ] Atualizei documentação, variáveis ou configurações, se necessário
20
+
21
+ Detalhes da validação:
22
+
23
+ ```text
24
+ Liste aqui os principais comandos, testes ou evidências.
25
+ ```
26
+
27
+ ## Impacto e risco
28
+
29
+ - [ ] Pequeno
30
+ - [ ] Médio
31
+ - [ ] Alto
32
+
33
+ ## Checklist final
34
+
35
+ - [ ] O título do PR está claro e objetivo
36
+ - [ ] A mudança está consistente com o escopo proposto
37
+ - [ ] Revisei o diff antes de pedir review
@@ -0,0 +1,37 @@
1
+ // #if posthog
2
+ import { posthog } from 'franchising/telemetry/posthog';
3
+ // #endif
4
+ // #if betterstack
5
+ import { betterstack } from 'franchising/telemetry/betterstack';
6
+ // #endif
7
+ import { env } from '../../env';
8
+
9
+ /**
10
+ * Destinos externos dos sinais de telemetria.
11
+ *
12
+ * @remarks
13
+ * O adapter e sempre criado, sem checar se a credencial veio: em producao o
14
+ * env nao sobe sem ela, e no dev local `TELEMETRY_ENABLED=false` desliga o
15
+ * envio antes de o adapter ser usado. Um so lugar para a API e os workers
16
+ * mandarem para o mesmo destino.
17
+ */
18
+ export const adapters = [
19
+ // #if posthog
20
+ /*
21
+ * O PostHog recebe evento de produto (`telemetry.event`) e excecao. Log
22
+ * tecnico — debug, info, warn e error — nao vai para ele de proposito:
23
+ * analytics e diagnostico operacional sao coisas diferentes.
24
+ */
25
+ posthog({ apiKey: env.POSTHOG_API_KEY, host: env.POSTHOG_HOST }),
26
+ // #endif
27
+ // #if betterstack
28
+ /*
29
+ * O Better Stack recebe os cinco sinais. O token da source fica no
30
+ * Collector, nunca no repositorio: aqui so entra o endereco dele.
31
+ */
32
+ betterstack({
33
+ otlp: { endpoint: env.BETTERSTACK_OTLP_ENDPOINT },
34
+ errors: { dsn: env.BETTERSTACK_ERRORS_DSN },
35
+ }),
36
+ // #endif
37
+ ];
@@ -0,0 +1,48 @@
1
+ import { type INestApplicationContext, Logger } from '@nestjs/common';
2
+ import { Telemetry, TelemetryNestLogger } from 'franchising/telemetry';
3
+
4
+ /**
5
+ * Liga o processo a telemetria.
6
+ *
7
+ * @remarks
8
+ * Troca o logger do Nest pelo do telemetry (JSON com `trace_id` e
9
+ * `request_id`) e reporta o que escapa de qualquer request ou job: uma
10
+ * promise rejeitada sem `catch` e uma excecao nao tratada. A excecao nao
11
+ * tratada ainda derruba o processo, mas so depois de a telemetria esvaziar a
12
+ * fila de envio; sem isso o erro que matou o processo nunca chegaria.
13
+ */
14
+ export function observeProcess(app: INestApplicationContext): void {
15
+ app.useLogger(app.get(TelemetryNestLogger));
16
+
17
+ const telemetry = app.get(Telemetry);
18
+
19
+ process.on('unhandledRejection', (reason) =>
20
+ telemetry.captureException(reason, { origin: 'unhandledRejection' }),
21
+ );
22
+
23
+ process.on('uncaughtException', (error) => {
24
+ telemetry.captureException(error, { origin: 'uncaughtException' });
25
+
26
+ void telemetry.shutdown().finally(() => process.exit(1));
27
+ });
28
+ }
29
+
30
+ /**
31
+ * Handler do `bootstrap().catch(...)` de cada `main.ts`.
32
+ *
33
+ * @remarks
34
+ * Falha antes de o app existir: nao ha facade da telemetria ainda, entao o
35
+ * log sai pelo `Logger` do Nest e o processo termina com codigo de erro, para
36
+ * a plataforma de deploy reiniciar e mostrar a falha.
37
+ */
38
+ export function bootstrapFailed(service: string) {
39
+ return (error: unknown): void => {
40
+ Logger.error(
41
+ error instanceof Error ? error.message : `Falha ao iniciar ${service}.`,
42
+ error instanceof Error ? error.stack : void 0,
43
+ 'Bootstrap',
44
+ );
45
+
46
+ process.exitCode = 1;
47
+ };
48
+ }
@@ -0,0 +1,21 @@
1
+ import 'dotenv/config';
2
+ import { bool, cleanEnv, str } from 'envalid';
3
+
4
+ /**
5
+ * Variaveis da telemetria, lidas do `.env` do app que importa o package.
6
+ *
7
+ * @remarks
8
+ * `devDefault`: a credencial pode faltar no dev local, onde a telemetria vem
9
+ * desligada, mas o processo nao sobe sem ela em producao.
10
+ */
11
+ export const env = cleanEnv(process.env, {
12
+ TELEMETRY_ENABLED: bool({ default: true, devDefault: false }),
13
+ // #if posthog
14
+ POSTHOG_API_KEY: str({ devDefault: '' }),
15
+ POSTHOG_HOST: str({ default: 'https://us.i.posthog.com' }),
16
+ // #endif
17
+ // #if betterstack
18
+ BETTERSTACK_OTLP_ENDPOINT: str({ devDefault: '' }),
19
+ BETTERSTACK_ERRORS_DSN: str({ devDefault: '' }),
20
+ // #endif
21
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Observabilidade compartilhada da API e dos workers.
3
+ *
4
+ * @remarks
5
+ * O registro do SDK fica no subpath `/register`, importado primeiro no
6
+ * `main.ts` de cada app: aqui so entra o que roda depois do bootstrap.
7
+ */
8
+ export { bootstrapFailed, observeProcess } from './shared/bootstrap/process';
9
+ export { observeWorker, runObservedJob } from './shared/jobs/lifecycle';
10
+ export { adapters } from './shared/telemetry/adapters';
@@ -0,0 +1,97 @@
1
+ import type { Job, Worker } from 'bullmq';
2
+ import type { Telemetry } from 'franchising/telemetry';
3
+
4
+ function jobAttributes(job: Job | undefined) {
5
+ return {
6
+ queue: job?.queueName ?? 'unknown',
7
+ job: job?.name ?? 'unknown',
8
+ jobId: job?.id ?? 'unknown',
9
+ attempt: job?.attemptsMade ?? 0,
10
+ };
11
+ }
12
+
13
+ /** Tentativas que o job tem, contando a primeira. */
14
+ function maxAttempts(job: Job) {
15
+ return job.opts.attempts ?? 1;
16
+ }
17
+
18
+ /**
19
+ * Processa um job dentro do contexto da telemetria.
20
+ *
21
+ * @remarks
22
+ * O `runJob` abre o span (continuando o trace do produtor quando o payload
23
+ * traz `traceparent`), conta sucesso e erro e mede a duracao por fila
24
+ * (`rock_dependency_*` com `dependency=queue.<fila>`), e reporta a excecao.
25
+ * Aqui entra so o que ele nao cobre: quanto tempo o job esperou na fila antes
26
+ * de um worker pegar, que e o primeiro sinal de fila acumulando.
27
+ */
28
+ export function runObservedJob<Result>(
29
+ telemetry: Telemetry,
30
+ job: Job,
31
+ process: () => Promise<Result>,
32
+ ): Promise<Result> {
33
+ const traceparent = (job.data as { traceparent?: unknown } | undefined)
34
+ ?.traceparent;
35
+
36
+ telemetry.histogram(
37
+ 'rock_job_wait_ms',
38
+ (job.processedOn ?? Date.now()) - job.timestamp,
39
+ { queue: job.queueName },
40
+ );
41
+
42
+ return telemetry.runJob(
43
+ {
44
+ queue: job.queueName,
45
+ job: job.name,
46
+ ...(job.id ? { jobId: job.id } : {}),
47
+ ...(typeof traceparent === 'string' ? { traceparent } : {}),
48
+ },
49
+ process,
50
+ );
51
+ }
52
+
53
+ /**
54
+ * Liga os eventos do `Worker` do BullMQ a logs e metricas.
55
+ *
56
+ * @remarks
57
+ * Falha com retentativa pela frente vira `warn`; o `error` fica para o job
58
+ * que esgotou as tentativas (ou foi descartado com `UnrecoverableError`), que
59
+ * e o que precisa de alguem olhando. Job travado e erro da conexao tambem
60
+ * entram, porque nenhum dos dois passa pelo processador.
61
+ */
62
+ export function observeWorker(worker: Worker, telemetry: Telemetry): void {
63
+ worker.on('failed', (job, error) => {
64
+ const attributes = { ...jobAttributes(job), reason: error.message };
65
+
66
+ const exhausted =
67
+ !job ||
68
+ error.name === 'UnrecoverableError' ||
69
+ job.attemptsMade >= maxAttempts(job);
70
+
71
+ if (!exhausted) {
72
+ telemetry.warn('job.retrying', attributes);
73
+
74
+ telemetry.increment('rock_job_retries_total', 1, {
75
+ queue: attributes.queue,
76
+ });
77
+
78
+ return;
79
+ }
80
+
81
+ telemetry.error('job.exhausted', error, attributes);
82
+
83
+ telemetry.increment('rock_job_exhausted_total', 1, {
84
+ queue: attributes.queue,
85
+ });
86
+ });
87
+
88
+ worker.on('stalled', (jobId) => {
89
+ telemetry.warn('job.stalled', { queue: worker.name, jobId });
90
+
91
+ telemetry.increment('rock_job_stalled_total', 1, { queue: worker.name });
92
+ });
93
+
94
+ worker.on('error', (error) =>
95
+ telemetry.error('worker.error', error, { queue: worker.name }),
96
+ );
97
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Observabilidade da API.
3
+ *
4
+ * @remarks
5
+ * O registro do SDK fica em `./register`, importado primeiro no `main.ts`:
6
+ * aqui so entra o que roda depois do bootstrap.
7
+ */
8
+ export { adapters } from './adapters';
9
+ export { bootstrapFailed, observeProcess } from './bootstrap';
@@ -0,0 +1,12 @@
1
+ import { registerTelemetry } from 'franchising/telemetry/register';
2
+ import { env } from '../../env';
3
+ import { adapters } from './adapters';
4
+
5
+ /*
6
+ * Roda no import, e nao numa funcao chamada depois: a auto-instrumentacao so
7
+ * consegue interceptar o Nest, o driver do banco e os clients HTTP se for
8
+ * registrada antes de esses modulos serem avaliados. Por isso o `main.ts`
9
+ * importa este arquivo antes de qualquer `@nestjs/*`. No dev local a
10
+ * telemetria vem desligada e nada e registrado.
11
+ */
12
+ if (env.TELEMETRY_ENABLED) registerTelemetry({ adapters });
@@ -7,43 +7,7 @@
7
7
  * dos dois lados, um lado renomeia e o outro passa a consumir uma fila vazia
8
8
  * sem erro nenhum.
9
9
  */
10
-
11
- /** Identificador de job estavel, para o mesmo evento nao entrar duas vezes. */
12
- export function jobId(parts: ReadonlyArray<string | number>): string {
13
- /*
14
- * O BullMQ recusa `:` em id customizado — justamente o separador obvio.
15
- * Cada parte vai codificada para que um valor com ponto ou barra nao mude
16
- * o significado do id.
17
- */
18
- return parts.map((part) => encodeURIComponent(String(part))).join('.');
19
- }
20
-
21
- /**
22
- * Prefixo com hashtag por fila.
23
- *
24
- * @remarks
25
- * Os scripts Lua do BullMQ tocam varias chaves de uma vez, e num Redis em modo
26
- * cluster isso so e atomico se as chaves cairem no mesmo slot. A hashtag em
27
- * volta do par prefixo/fila garante isso sem jogar todas as filas no mesmo
28
- * shard.
29
- */
30
- export function queuePrefix(prefix: string, queueName: string): string {
31
- const normalizedPrefix = prefix.trim().replace(/:+$/, '');
32
- const normalizedQueue = queueName.trim();
33
-
34
- if (!(normalizedPrefix && normalizedQueue)) {
35
- throw new Error('QUEUE_PREFIX_AND_NAME_REQUIRED');
36
- }
37
-
38
- return `{${normalizedPrefix}:${normalizedQueue}}`;
39
- }
40
-
41
- /** Politica padrao de retentativa das filas do projeto. */
42
- export const DEFAULT_JOB_OPTIONS = {
43
- attempts: 5,
44
- backoff: { type: 'exponential', delay: 1000 },
45
- removeOnComplete: { age: 3600, count: 1000 },
46
- removeOnFail: { age: 86_400 },
47
- } as const;
48
-
49
- export * from './queues';
10
+ export * from './shared/queue/job-id';
11
+ export * from './shared/queue/names';
12
+ export * from './shared/queue/options';
13
+ export * from './shared/queue/prefix';
@@ -0,0 +1,9 @@
1
+ /** Identificador de job estavel, para o mesmo evento nao entrar duas vezes. */
2
+ export function jobId(parts: ReadonlyArray<string | number>): string {
3
+ /*
4
+ * O BullMQ recusa `:` em id customizado — justamente o separador obvio.
5
+ * Cada parte vai codificada para que um valor com ponto ou barra nao mude
6
+ * o significado do id.
7
+ */
8
+ return parts.map((part) => encodeURIComponent(String(part))).join('.');
9
+ }
@@ -0,0 +1,7 @@
1
+ /** Politica padrao de retentativa das filas do projeto. */
2
+ export const DEFAULT_JOB_OPTIONS = {
3
+ attempts: 5,
4
+ backoff: { type: 'exponential', delay: 1000 },
5
+ removeOnComplete: { age: 3600, count: 1000 },
6
+ removeOnFail: { age: 86_400 },
7
+ } as const;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Prefixo com hashtag por fila.
3
+ *
4
+ * @remarks
5
+ * Os scripts Lua do BullMQ tocam varias chaves de uma vez, e num Redis em modo
6
+ * cluster isso so e atomico se as chaves cairem no mesmo slot. A hashtag em
7
+ * volta do par prefixo/fila garante isso sem jogar todas as filas no mesmo
8
+ * shard.
9
+ */
10
+ export function queuePrefix(prefix: string, queueName: string): string {
11
+ const normalizedPrefix = prefix.trim().replace(/:+$/, '');
12
+ const normalizedQueue = queueName.trim();
13
+
14
+ if (!(normalizedPrefix && normalizedQueue))
15
+ throw new Error('QUEUE_PREFIX_AND_NAME_REQUIRED');
16
+
17
+ return `{${normalizedPrefix}:${normalizedQueue}}`;
18
+ }
@@ -0,0 +1,4 @@
1
+ /** Conexoes Redis do BullMQ, compartilhadas pela API e pelos workers. */
2
+ export * from './shared/errors/failure-reason';
3
+ export * from './shared/redis/connection';
4
+ export type { QueueRedisConnection } from './types/redis/connection';
@@ -0,0 +1,7 @@
1
+ /** Motivo legivel da falha, para o log estruturado. */
2
+ export function failureReason(error: unknown): string {
3
+ if (error instanceof Error)
4
+ return error.message;
5
+
6
+ return typeof error === 'string' ? error : 'unknown';
7
+ }
@@ -1,9 +1,5 @@
1
- import IORedis, { type Redis } from 'ioredis';
2
-
3
- export type QueueRedisConnection = {
4
- client: Redis;
5
- close: () => Promise<void>;
6
- };
1
+ import IORedis from 'ioredis';
2
+ import type { QueueRedisConnection } from '../../types/redis/connection';
7
3
 
8
4
  /*
9
5
  * `maxRetriesPerRequest: null` e exigencia do BullMQ para a conexao que fica
@@ -43,12 +39,3 @@ export function createWorkerRedisConnection(
43
39
  ): QueueRedisConnection {
44
40
  return connect(url, WORKER_OPTIONS);
45
41
  }
46
-
47
- /** Motivo legivel da falha, para o log estruturado. */
48
- export function failureReason(error: unknown): string {
49
- if (error instanceof Error) {
50
- return error.message;
51
- }
52
-
53
- return typeof error === 'string' ? error : 'unknown';
54
- }
@@ -0,0 +1,6 @@
1
+ import type { Redis } from 'ioredis';
2
+
3
+ export type QueueRedisConnection = {
4
+ client: Redis;
5
+ close: () => Promise<void>;
6
+ };
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Dominio de webhooks compartilhado entre a API e o worker `webhooks`.
3
+ *
4
+ * @remarks
5
+ * A API cifra o segredo ao cadastrar o endpoint e o worker decifra para
6
+ * assinar: os dois precisam do mesmo formato, entao ele mora num lugar so.
7
+ */
8
+ export * from './shared/crypto/secret';
9
+ export * from './shared/signing/headers';
10
+ export * from './shared/url/deliverable';
11
+ export type * from './types/webhooks/job';