franchising 0.0.0-stage → 0.1.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 (227) hide show
  1. package/LICENSE +61 -0
  2. package/README.md +88 -2
  3. package/dist/accounts-B4bnTXUd.js +242 -0
  4. package/dist/accounts-B4bnTXUd.js.map +1 -0
  5. package/dist/accounts-TyMPSHM0.cjs +313 -0
  6. package/dist/accounts-TyMPSHM0.cjs.map +1 -0
  7. package/dist/adapters-DM59AJfR.d.cts +216 -0
  8. package/dist/adapters-DM59AJfR.d.ts +216 -0
  9. package/dist/cli/template-assets/api/src/errors/codes.ts +17 -0
  10. package/dist/cli/template-assets/api/src/errors/index.ts +16 -0
  11. package/dist/cli/template-assets/api/src/filters/exception.ts +53 -0
  12. package/dist/cli/template-assets/api/src/main.ts +189 -0
  13. package/dist/cli/template-assets/api/src/modules/health/controller.ts +23 -0
  14. package/dist/cli/template-assets/api/src/modules/health/dto/response.dto.ts +23 -0
  15. package/dist/cli/template-assets/api/src/modules/health/module.ts +12 -0
  16. package/dist/cli/template-assets/api/src/modules/health/service.ts +54 -0
  17. package/dist/cli/template-assets/api/src/modules/messaging/module.ts +7 -0
  18. package/dist/cli/template-assets/api/src/modules/messaging/service.ts +74 -0
  19. package/dist/cli/template-assets/api/src/shared/exceptions.ts +40 -0
  20. package/dist/cli/template-assets/api/src/shared/response.ts +31 -0
  21. package/dist/cli/template-assets/api/src/telemetry.ts +59 -0
  22. package/dist/cli/template-assets/api/src/types.ts +8 -0
  23. package/dist/cli/template-assets/cloudflare/cache.service.ts +23 -0
  24. package/dist/cli/template-assets/cloudflare/queue.service.ts +22 -0
  25. package/dist/cli/template-assets/cloudflare/worker.ts +33 -0
  26. package/dist/cli/template-assets/packages/jobs/src/index.ts +49 -0
  27. package/dist/cli/template-assets/packages/queue-runtime/src/index.ts +54 -0
  28. package/dist/cli/template-assets/root/dot-dockerignore +11 -0
  29. package/dist/cli/template-assets/root/dot-editorconfig +13 -0
  30. package/dist/cli/template-assets/root/dot-oxfmtrc.json +9 -0
  31. package/dist/cli/template-assets/root/dot-oxlintrc.json +47 -0
  32. package/dist/cli/template-assets/root/lefthook.yml +18 -0
  33. package/dist/cli/template-assets/web/postcss.config.mjs +9 -0
  34. package/dist/cli/template-assets/web/src/app/(app)/dashboard/page.tsx +5 -0
  35. package/dist/cli/template-assets/web/src/app/(app)/layout.tsx +25 -0
  36. package/dist/cli/template-assets/web/src/app/(auth)/login/page.tsx +75 -0
  37. package/dist/cli/template-assets/web/src/app/globals.css +48 -0
  38. package/dist/cli/template-assets/web/src/app/layout.tsx +30 -0
  39. package/dist/cli/template-assets/web/src/app/page.tsx +20 -0
  40. package/dist/cli/template-assets/web/src/components/overview/overview-panel.tsx +27 -0
  41. package/dist/cli/template-assets/web/src/components/shell/app-shell.tsx +37 -0
  42. package/dist/cli/template-assets/web/src/components/shell/providers.tsx +22 -0
  43. package/dist/cli/template-assets/web/src/lib/api-client.ts +57 -0
  44. package/dist/cli/template-assets/web/src/lib/auth-client.ts +15 -0
  45. package/dist/cli/template-assets/web/src/lib/server-auth.ts +38 -0
  46. package/dist/cli/template-assets/web/src/types/api.ts +18 -0
  47. package/dist/cli/template-assets/worker/src/app.module.ts +5 -0
  48. package/dist/cli/template-assets/worker/src/env.ts +8 -0
  49. package/dist/cli/template-assets/worker/src/main.ts +25 -0
  50. package/dist/cli/template-assets/worker/src/modules/queue/config.ts +16 -0
  51. package/dist/cli/template-assets/worker/src/modules/queue/module.ts +11 -0
  52. package/dist/cli/template-assets/worker/src/modules/queue/processor.ts +105 -0
  53. package/dist/cli/template-assets/worker/src/modules/queue/repository.ts +16 -0
  54. package/dist/cli/template-assets/worker/src/modules/queue/retry.ts +17 -0
  55. package/dist/cli/template-assets/worker/test/retry.test.ts.tpl +12 -0
  56. package/dist/cli/template-assets/worker-messaging/jobs-messaging.ts +12 -0
  57. package/dist/cli/template-assets/worker-messaging/messaging-api-service.ts +39 -0
  58. package/dist/cli/template-assets/worker-messaging/src/env.ts +14 -0
  59. package/dist/cli/template-assets/worker-messaging/src/modules/messaging/service.ts +59 -0
  60. package/dist/cli/template-assets/worker-messaging/src/modules/queue/module.ts +8 -0
  61. package/dist/cli/template-assets/worker-messaging/src/modules/queue/processor.ts +113 -0
  62. package/dist/cli.js +1218 -0
  63. package/dist/cn-BVOnrSza.js +1 -0
  64. package/dist/constants-C4iP0--i.js +38 -0
  65. package/dist/constants-C4iP0--i.js.map +1 -0
  66. package/dist/constants-rCR-LNSN.cjs +91 -0
  67. package/dist/constants-rCR-LNSN.cjs.map +1 -0
  68. package/dist/decorate-BR5FVX5x.js +14 -0
  69. package/dist/decorate-R-oqksAh.cjs +25 -0
  70. package/dist/decorateParam-BFJPEGKJ.cjs +13 -0
  71. package/dist/decorateParam-CKE7_J1s.js +8 -0
  72. package/dist/define-adapter-Cc0QrfKt.cjs +16 -0
  73. package/dist/define-adapter-Cc0QrfKt.cjs.map +1 -0
  74. package/dist/define-adapter-DRcXno3j.js +11 -0
  75. package/dist/define-adapter-DRcXno3j.js.map +1 -0
  76. package/dist/dispatcher-BsD7cO2w.cjs +84 -0
  77. package/dist/dispatcher-BsD7cO2w.cjs.map +1 -0
  78. package/dist/dispatcher-DA_l1Vkv.js +73 -0
  79. package/dist/dispatcher-DA_l1Vkv.js.map +1 -0
  80. package/dist/errors-DxHoXrLd.d.cts +46 -0
  81. package/dist/errors-DxHoXrLd.d.ts +46 -0
  82. package/dist/http/index.cjs +440 -0
  83. package/dist/http/index.cjs.map +1 -0
  84. package/dist/http/index.d.cts +257 -0
  85. package/dist/http/index.d.ts +257 -0
  86. package/dist/http/index.js +400 -0
  87. package/dist/http/index.js.map +1 -0
  88. package/dist/http/swagger.cjs +122 -0
  89. package/dist/http/swagger.cjs.map +1 -0
  90. package/dist/http/swagger.d.cts +59 -0
  91. package/dist/http/swagger.d.ts +59 -0
  92. package/dist/http/swagger.js +117 -0
  93. package/dist/http/swagger.js.map +1 -0
  94. package/dist/index-B3UOHsA9.d.ts +679 -0
  95. package/dist/index-Bdl0AiNM.d.ts +1262 -0
  96. package/dist/index-By8b4ksT.d.ts +25 -0
  97. package/dist/index-C1KmT8dQ.d.ts +174 -0
  98. package/dist/index-CYT1PFzo.d.cts +679 -0
  99. package/dist/index-Cj-10Q5F.d.cts +174 -0
  100. package/dist/index-DDSaLjXV.d.cts +25 -0
  101. package/dist/index-FTrYdHfq.d.cts +1262 -0
  102. package/dist/index.cjs +1 -0
  103. package/dist/index.d.cts +4 -0
  104. package/dist/index.d.ts +4 -0
  105. package/dist/index.js +1 -0
  106. package/dist/label-BqmJoVE-.cjs +1 -0
  107. package/dist/label-XeChe1Bu.js +1 -0
  108. package/dist/messaging/index.cjs +1 -0
  109. package/dist/messaging/index.d.cts +1775 -0
  110. package/dist/messaging/index.d.ts +1775 -0
  111. package/dist/messaging/index.js +1 -0
  112. package/dist/misc-BpM_lMTx.js +1 -0
  113. package/dist/misc-DkqJOm1V.cjs +1 -0
  114. package/dist/operational-CnxdBwVG.d.cts +13 -0
  115. package/dist/operational-CnxdBwVG.d.ts +13 -0
  116. package/dist/redaction-DhuHTlHA.js +124 -0
  117. package/dist/redaction-DhuHTlHA.js.map +1 -0
  118. package/dist/redaction-uRIQbTwZ.cjs +171 -0
  119. package/dist/redaction-uRIQbTwZ.cjs.map +1 -0
  120. package/dist/rolldown-runtime-auK_WOaK.cjs +1 -0
  121. package/dist/rolldown-runtime-xuxB8TGW.cjs +32 -0
  122. package/dist/runtime-C95UYYLb.cjs +111 -0
  123. package/dist/runtime-C95UYYLb.cjs.map +1 -0
  124. package/dist/runtime-DG2oBFYw.js +88 -0
  125. package/dist/runtime-DG2oBFYw.js.map +1 -0
  126. package/dist/skills-C1uwr9Pp.js +4 -0
  127. package/dist/skills-DuE-XnBp.js +1 -0
  128. package/dist/sso/client.cjs +37 -0
  129. package/dist/sso/client.cjs.map +1 -0
  130. package/dist/sso/client.d.cts +90 -0
  131. package/dist/sso/client.d.ts +90 -0
  132. package/dist/sso/client.js +36 -0
  133. package/dist/sso/client.js.map +1 -0
  134. package/dist/sso/index.cjs +833 -0
  135. package/dist/sso/index.cjs.map +1 -0
  136. package/dist/sso/index.d.cts +3 -0
  137. package/dist/sso/index.d.ts +3 -0
  138. package/dist/sso/index.js +821 -0
  139. package/dist/sso/index.js.map +1 -0
  140. package/dist/sso/nestjs.cjs +169 -0
  141. package/dist/sso/nestjs.cjs.map +1 -0
  142. package/dist/sso/nestjs.d.cts +92 -0
  143. package/dist/sso/nestjs.d.ts +92 -0
  144. package/dist/sso/nestjs.js +151 -0
  145. package/dist/sso/nestjs.js.map +1 -0
  146. package/dist/sso/resource.cjs +124 -0
  147. package/dist/sso/resource.cjs.map +1 -0
  148. package/dist/sso/resource.d.cts +3 -0
  149. package/dist/sso/resource.d.ts +3 -0
  150. package/dist/sso/resource.js +114 -0
  151. package/dist/sso/resource.js.map +1 -0
  152. package/dist/status-CRvlFPIs.js +13 -0
  153. package/dist/status-CRvlFPIs.js.map +1 -0
  154. package/dist/status-DtK6OHtj.cjs +24 -0
  155. package/dist/status-DtK6OHtj.cjs.map +1 -0
  156. package/dist/team-CJVAg4HH.d.cts +157 -0
  157. package/dist/team-CJVAg4HH.d.ts +157 -0
  158. package/dist/telemetry/adapters.cjs +6 -0
  159. package/dist/telemetry/adapters.d.cts +3 -0
  160. package/dist/telemetry/adapters.d.ts +3 -0
  161. package/dist/telemetry/adapters.js +4 -0
  162. package/dist/telemetry/betterstack.cjs +74 -0
  163. package/dist/telemetry/betterstack.cjs.map +1 -0
  164. package/dist/telemetry/betterstack.d.cts +12 -0
  165. package/dist/telemetry/betterstack.d.ts +12 -0
  166. package/dist/telemetry/betterstack.js +71 -0
  167. package/dist/telemetry/betterstack.js.map +1 -0
  168. package/dist/telemetry/index.cjs +1237 -0
  169. package/dist/telemetry/index.cjs.map +1 -0
  170. package/dist/telemetry/index.d.cts +114 -0
  171. package/dist/telemetry/index.d.ts +114 -0
  172. package/dist/telemetry/index.js +1205 -0
  173. package/dist/telemetry/index.js.map +1 -0
  174. package/dist/telemetry/posthog.cjs +72 -0
  175. package/dist/telemetry/posthog.cjs.map +1 -0
  176. package/dist/telemetry/posthog.d.cts +10 -0
  177. package/dist/telemetry/posthog.d.ts +10 -0
  178. package/dist/telemetry/posthog.js +71 -0
  179. package/dist/telemetry/posthog.js.map +1 -0
  180. package/dist/telemetry/register.cjs +6 -0
  181. package/dist/telemetry/register.d.cts +14 -0
  182. package/dist/telemetry/register.d.ts +14 -0
  183. package/dist/telemetry/register.js +3 -0
  184. package/dist/telemetry/testing.cjs +54 -0
  185. package/dist/telemetry/testing.cjs.map +1 -0
  186. package/dist/telemetry/testing.d.cts +15 -0
  187. package/dist/telemetry/testing.d.ts +15 -0
  188. package/dist/telemetry/testing.js +52 -0
  189. package/dist/telemetry/testing.js.map +1 -0
  190. package/dist/telemetry.mock-BSsx7L6S.cjs +45 -0
  191. package/dist/telemetry.mock-BSsx7L6S.cjs.map +1 -0
  192. package/dist/telemetry.mock-BZRpy63c.js +40 -0
  193. package/dist/telemetry.mock-BZRpy63c.js.map +1 -0
  194. package/dist/telemetry.mock-C1wXuf-M.d.cts +4 -0
  195. package/dist/telemetry.mock-CdaxofJ7.d.ts +4 -0
  196. package/dist/ui/chart.cjs +6 -0
  197. package/dist/ui/chart.d.cts +34 -0
  198. package/dist/ui/chart.d.ts +34 -0
  199. package/dist/ui/chart.js +6 -0
  200. package/dist/ui/form.cjs +1 -0
  201. package/dist/ui/form.d.cts +23 -0
  202. package/dist/ui/form.d.ts +23 -0
  203. package/dist/ui/form.js +1 -0
  204. package/dist/ui/hooks.cjs +1 -0
  205. package/dist/ui/hooks.d.cts +66 -0
  206. package/dist/ui/hooks.d.ts +66 -0
  207. package/dist/ui/hooks.js +1 -0
  208. package/dist/ui/index.cjs +1 -0
  209. package/dist/ui/index.d.cts +3 -0
  210. package/dist/ui/index.d.ts +3 -0
  211. package/dist/ui/index.js +1 -0
  212. package/dist/ui/styles.css +2 -0
  213. package/dist/ui/utils.cjs +1 -0
  214. package/dist/ui/utils.d.cts +199 -0
  215. package/dist/ui/utils.d.ts +199 -0
  216. package/dist/ui/utils.js +1 -0
  217. package/dist/use-mobile-BbeIMRgE.cjs +1 -0
  218. package/dist/use-mobile-Cdd4Lp7p.js +1 -0
  219. package/dist/use-mobile-ecpyXWz3.d.cts +10 -0
  220. package/dist/use-mobile-ecpyXWz3.d.ts +10 -0
  221. package/dist/verifier-BIBtPCVi.cjs +119 -0
  222. package/dist/verifier-BIBtPCVi.cjs.map +1 -0
  223. package/dist/verifier-DNdy5Ynw.js +90 -0
  224. package/dist/verifier-DNdy5Ynw.js.map +1 -0
  225. package/dist/version-CPunTYCY.js +1 -0
  226. package/dist/version-CfUi3iAV.cjs +1 -0
  227. package/package.json +523 -5
@@ -0,0 +1,37 @@
1
+ 'use client';
2
+
3
+ import { SidebarInset, SidebarNav, type SidebarNavGroup, SidebarProvider } from 'franchising/ui';
4
+ import Link from 'next/link';
5
+ import { usePathname } from 'next/navigation';
6
+ import type { ReactNode } from 'react';
7
+
8
+ const groups: SidebarNavGroup[] = [
9
+ {
10
+ label: 'Geral',
11
+ items: [{ href: '/dashboard', label: 'Painel' }],
12
+ },
13
+ ];
14
+
15
+ /**
16
+ * Enquadramento das telas autenticadas.
17
+ *
18
+ * @remarks
19
+ * Fica no cliente porque a barra lateral do franchising/ui usa contexto do React.
20
+ * O layout em `app/` continua no servidor: e la que a sessao e lida e o
21
+ * redirecionamento acontece, antes de qualquer render.
22
+ */
23
+ export function AppShell({ children }: { children: ReactNode }) {
24
+ const pathname = usePathname();
25
+
26
+ return (
27
+ <SidebarProvider>
28
+ <SidebarNav
29
+ groups={groups}
30
+ activeHref={pathname}
31
+ /* A lib nao importa `next/*`: o link do framework entra por prop. */
32
+ linkComponent={Link}
33
+ />
34
+ <SidebarInset>{children}</SidebarInset>
35
+ </SidebarProvider>
36
+ );
37
+ }
@@ -0,0 +1,22 @@
1
+ 'use client';
2
+
3
+ import { Toaster, TooltipProvider } from 'franchising/ui';
4
+ import type { ReactNode } from 'react';
5
+
6
+ /**
7
+ * Fronteira de cliente da app.
8
+ *
9
+ * @remarks
10
+ * Os componentes do franchising/ui usam contexto do React, que so existe no
11
+ * cliente. O layout raiz e um componente de servidor, entao renderiza-los
12
+ * direto la quebra o build com `createContext is not a function`. Este arquivo
13
+ * e a fronteira: tudo que precisa de contexto entra aqui.
14
+ */
15
+ export function Providers({ children }: { children: ReactNode }) {
16
+ return (
17
+ <TooltipProvider>
18
+ {children}
19
+ <Toaster />
20
+ </TooltipProvider>
21
+ );
22
+ }
@@ -0,0 +1,57 @@
1
+ import { env } from '@/env';
2
+ import type { ApiEnvelope } from '@/types/api';
3
+
4
+ /**
5
+ * Erro vindo da API, ja com o codigo estavel do contrato.
6
+ *
7
+ * @remarks
8
+ * A tela ramifica por `code`, nunca por `message`: mensagem e texto de
9
+ * interface e muda sem aviso.
10
+ */
11
+ export class ApiClientError extends Error {
12
+ constructor(
13
+ readonly code: string,
14
+ message: string,
15
+ readonly status: number,
16
+ readonly errors?: unknown,
17
+ ) {
18
+ super(message);
19
+ this.name = 'ApiClientError';
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Cliente da API.
25
+ *
26
+ * @remarks
27
+ * `credentials: 'include'` porque a sessao do Better Auth viaja em cookie; sem
28
+ * isso toda chamada autenticada volta 401 no navegador.
29
+ */
30
+ export async function apiFetch<Data>(
31
+ path: string,
32
+ init?: RequestInit,
33
+ ): Promise<Data> {
34
+ const response = await fetch(`${env.NEXT_PUBLIC_API_URL}${path}`, {
35
+ ...init,
36
+ credentials: 'include',
37
+ headers: {
38
+ 'content-type': 'application/json',
39
+ ...init?.headers,
40
+ },
41
+ });
42
+
43
+ const payload = (await response
44
+ .json()
45
+ .catch(() => null)) as ApiEnvelope<Data> | null;
46
+
47
+ if (!response.ok || !payload?.ok) {
48
+ throw new ApiClientError(
49
+ payload && !payload.ok ? payload.code : 'INTERNAL_ERROR',
50
+ payload && !payload.ok ? payload.message : 'Request failed.',
51
+ response.status,
52
+ payload && !payload.ok ? payload.errors : undefined,
53
+ );
54
+ }
55
+
56
+ return payload.data;
57
+ }
@@ -0,0 +1,15 @@
1
+ 'use client';
2
+
3
+ import { createAuthClient } from 'better-auth/react';
4
+ __ROCK_AUTH_CLIENT_IMPORTS__
5
+ import { env } from '@/env';
6
+
7
+ export const authClient = createAuthClient({
8
+ baseURL: env.NEXT_PUBLIC_AUTH_URL,
9
+ /* A API versiona por URI, entao o Better Auth nao mora em `/auth`. */
10
+ basePath: '/api/auth',
11
+ fetchOptions: { credentials: 'include' },
12
+ plugins: [
13
+ __ROCK_AUTH_CLIENT_PLUGINS__
14
+ ],
15
+ });
@@ -0,0 +1,38 @@
1
+ import { headers } from 'next/headers';
2
+ import { env } from '@/env';
3
+ import type { AuthSession } from '@/types/api';
4
+
5
+ /**
6
+ * Le a sessao no servidor repassando o cookie da requisicao.
7
+ *
8
+ * @remarks
9
+ * Devolve `null` em qualquer falha, inclusive de rede: quem chama e o layout
10
+ * autenticado, e ali "nao sei" e "nao autenticado" levam ao mesmo lugar.
11
+ * Estourar aqui trocaria o redirecionamento por um 500.
12
+ */
13
+ export async function getSession(): Promise<AuthSession | null> {
14
+ const cookie = (await headers()).get('cookie');
15
+
16
+ try {
17
+ const response = await fetch(
18
+ `${env.NEXT_PUBLIC_AUTH_URL}/api/auth/get-session`,
19
+ {
20
+ cache: 'no-store',
21
+ /*
22
+ * A chave so entra quando ha cookie: com
23
+ * `exactOptionalPropertyTypes`, passar `undefined` nao equivale
24
+ * a omitir.
25
+ */
26
+ ...(cookie ? { headers: { cookie } } : {}),
27
+ },
28
+ );
29
+
30
+ if (!response.ok) {
31
+ return null;
32
+ }
33
+
34
+ return (await response.json()) as AuthSession | null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
@@ -0,0 +1,18 @@
1
+ export type ApiSuccess<Data> = {
2
+ ok: true;
3
+ data: Data;
4
+ };
5
+
6
+ export type ApiFailure = {
7
+ ok: false;
8
+ code: string;
9
+ message: string;
10
+ errors?: unknown;
11
+ };
12
+
13
+ /** Envelope unico da API: o campo `ok` decide qual lado ler. */
14
+ export type ApiEnvelope<Data> = ApiSuccess<Data> | ApiFailure;
15
+
16
+ export type AuthSession = {
17
+ user: { id: string; name: string; email: string };
18
+ };
@@ -0,0 +1,5 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { __ROCK_WORKER_CLASS__Module } from './modules/queue/module';
3
+
4
+ @Module({ imports: [__ROCK_WORKER_CLASS__Module] })
5
+ export class AppModule {}
@@ -0,0 +1,8 @@
1
+ import 'dotenv/config';
2
+ import { cleanEnv, num, str } from 'envalid';
3
+
4
+ export const env = cleanEnv(process.env, {
5
+ QUEUE_REDIS_URL: str({ default: 'redis://localhost:6379' }),
6
+ QUEUE_PREFIX: str({ default: '__ROCK_PROJECT_SLUG__' }),
7
+ __ROCK_WORKER_CONCURRENCY_ENV__: num({ default: 5 }),
8
+ });
@@ -0,0 +1,25 @@
1
+ import 'reflect-metadata';
2
+ import { Logger } from '@nestjs/common';
3
+ import { NestFactory } from '@nestjs/core';
4
+ import { AppModule } from './app.module';
5
+
6
+ /*
7
+ * Contexto de aplicacao, e nao servidor HTTP: o worker consome fila e nao
8
+ * escuta porta. `enableShutdownHooks` e o que permite o processor fechar as
9
+ * conexoes antes do processo morrer, para um job em andamento nao ficar preso.
10
+ */
11
+ async function bootstrap(): Promise<void> {
12
+ const app = await NestFactory.createApplicationContext(AppModule);
13
+ app.enableShutdownHooks();
14
+ }
15
+
16
+ void bootstrap().catch((error: unknown) => {
17
+ Logger.error(
18
+ error instanceof Error
19
+ ? error.message
20
+ : 'Falha ao iniciar o worker __ROCK_WORKER_NAME__.',
21
+ undefined,
22
+ 'Bootstrap',
23
+ );
24
+ process.exitCode = 1;
25
+ });
@@ -0,0 +1,16 @@
1
+ /*
2
+ * Limites de execucao da fila. Ficam fora do processor porque o teste de
3
+ * retentativa precisa deles sem subir o worker inteiro.
4
+ */
5
+
6
+ /** Quanto tempo um job pode segurar o lock antes de ser considerado travado. */
7
+ export const LOCK_DURATION_MS = 60_000;
8
+
9
+ /** Intervalo entre varreduras por jobs travados. */
10
+ export const STALLED_INTERVAL_MS = 30_000;
11
+
12
+ /** Quantas vezes um job pode travar antes de falhar de vez. */
13
+ export const MAX_STALLED_COUNT = 2;
14
+
15
+ /** Teto de jobs por segundo, para nao afogar o servico de destino. */
16
+ export const RATE_LIMIT_PER_SECOND = 20;
@@ -0,0 +1,11 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { __ROCK_WORKER_CLASS__Processor } from './processor';
3
+ import { __ROCK_WORKER_CLASS__Repository } from './repository';
4
+
5
+ @Module({
6
+ providers: [
7
+ __ROCK_WORKER_CLASS__Repository,
8
+ __ROCK_WORKER_CLASS__Processor,
9
+ ],
10
+ })
11
+ export class __ROCK_WORKER_CLASS__Module {}
@@ -0,0 +1,105 @@
1
+ import {
2
+ Injectable,
3
+ Logger,
4
+ type OnModuleDestroy,
5
+ type OnModuleInit,
6
+ } from '@nestjs/common';
7
+ import { UnrecoverableError, Worker } from 'bullmq';
8
+ import {
9
+ createWorkerRedisConnection,
10
+ failureReason,
11
+ type QueueRedisConnection,
12
+ } from '__ROCK_SCOPE__/queue-runtime';
13
+ import { __ROCK_WORKER_QUEUE_CONST__, queuePrefix } from '__ROCK_SCOPE__/jobs';
14
+ import { env } from '../../env';
15
+ import {
16
+ LOCK_DURATION_MS,
17
+ MAX_STALLED_COUNT,
18
+ RATE_LIMIT_PER_SECOND,
19
+ STALLED_INTERVAL_MS,
20
+ } from './config';
21
+ import { __ROCK_WORKER_CLASS__Repository } from './repository';
22
+ import { isRetryable } from './retry';
23
+
24
+ /**
25
+ * Consumidor da fila `__ROCK_WORKER_QUEUE__`.
26
+ *
27
+ * @remarks
28
+ * O `Worker` do BullMQ e criado no ciclo de vida do Nest em vez de vir de um
29
+ * modulo pronto: assim a conexao com o Redis e fechada no shutdown, e um job
30
+ * em andamento termina antes do processo sair.
31
+ */
32
+ @Injectable()
33
+ export class __ROCK_WORKER_CLASS__Processor
34
+ implements OnModuleInit, OnModuleDestroy
35
+ {
36
+ private readonly logger = new Logger(__ROCK_WORKER_CLASS__Processor.name);
37
+ private worker?: Worker;
38
+ private connection?: QueueRedisConnection;
39
+
40
+ constructor(
41
+ private readonly repository: __ROCK_WORKER_CLASS__Repository,
42
+ ) {}
43
+
44
+ onModuleInit(): void {
45
+ this.connection = createWorkerRedisConnection(env.QUEUE_REDIS_URL);
46
+ this.worker = new Worker(
47
+ __ROCK_WORKER_QUEUE_CONST__,
48
+ (job) => this.process(job),
49
+ {
50
+ connection: this.connection.client,
51
+ prefix: queuePrefix(
52
+ env.QUEUE_PREFIX,
53
+ __ROCK_WORKER_QUEUE_CONST__,
54
+ ),
55
+ concurrency: env.__ROCK_WORKER_CONCURRENCY_ENV__,
56
+ limiter: { max: RATE_LIMIT_PER_SECOND, duration: 1000 },
57
+ lockDuration: LOCK_DURATION_MS,
58
+ stalledInterval: STALLED_INTERVAL_MS,
59
+ maxStalledCount: MAX_STALLED_COUNT,
60
+ },
61
+ );
62
+
63
+ this.worker.on('failed', (job, error) => {
64
+ this.logger.error(
65
+ JSON.stringify({
66
+ event: '__ROCK_WORKER_QUEUE__.failed',
67
+ jobId: job?.id,
68
+ attempts: job?.attemptsMade,
69
+ reason: failureReason(error),
70
+ }),
71
+ );
72
+ });
73
+
74
+ this.worker.on('error', (error) => {
75
+ this.logger.error(
76
+ JSON.stringify({
77
+ event: '__ROCK_WORKER_QUEUE__.error',
78
+ reason: failureReason(error),
79
+ }),
80
+ );
81
+ });
82
+ }
83
+
84
+ async onModuleDestroy(): Promise<void> {
85
+ await this.worker?.close();
86
+ await this.connection?.close();
87
+ }
88
+
89
+ private async process(job: { id?: string; data: unknown }): Promise<void> {
90
+ try {
91
+ // TODO: tratar o job. `job.data` chega como enviado pelo produtor.
92
+ await this.repository.markProcessed(job.id ?? 'unknown');
93
+ } catch (error) {
94
+ /*
95
+ * `UnrecoverableError` tira o job da fila na hora. Sem isso um
96
+ * payload invalido ficaria repetindo ate esgotar as tentativas.
97
+ */
98
+ if (!isRetryable(error)) {
99
+ throw new UnrecoverableError(failureReason(error));
100
+ }
101
+
102
+ throw error;
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,16 @@
1
+ import { Injectable } from '@nestjs/common';
2
+
3
+ /**
4
+ * Acesso a dados do worker.
5
+ *
6
+ * @remarks
7
+ * O processor nao fala com o banco direto: isolar a leitura e a escrita aqui
8
+ * deixa o processor testavel sem subir Postgres.
9
+ */
10
+ @Injectable()
11
+ export class __ROCK_WORKER_CLASS__Repository {
12
+ async markProcessed(jobId: string): Promise<void> {
13
+ // TODO: registrar a conclusao do job na sua tabela.
14
+ await Promise.resolve(jobId);
15
+ }
16
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Decide se vale tentar o job de novo.
3
+ *
4
+ * @remarks
5
+ * Erro de rede ou indisponibilidade tende a passar sozinho, entao vale
6
+ * retentar. Erro de payload invalido nao muda com o tempo: retentar so queima
7
+ * as tentativas e atrasa a ida para a fila de falhas.
8
+ */
9
+ export function isRetryable(error: unknown): boolean {
10
+ if (error instanceof TypeError) {
11
+ return false;
12
+ }
13
+
14
+ const code = (error as { code?: string } | undefined)?.code;
15
+
16
+ return code !== 'VALIDATION_FAILED';
17
+ }
@@ -0,0 +1,12 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { isRetryable } from '../src/modules/queue/retry';
3
+
4
+ describe('isRetryable', () => {
5
+ it('retenta falha transitoria', () => {
6
+ expect(isRetryable(new Error('ECONNRESET'))).toBe(true);
7
+ });
8
+
9
+ it('nao retenta payload invalido', () => {
10
+ expect(isRetryable(Object.assign(new Error('bad'), { code: 'VALIDATION_FAILED' }))).toBe(false);
11
+ });
12
+ });
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Contrato do job de e-mail.
3
+ *
4
+ * @remarks
5
+ * A API publica e o worker `messaging` consome o mesmo tipo: mudar um campo de
6
+ * um lado quebra o build do outro, em vez de virar e-mail vazio em producao.
7
+ */
8
+ export type SendEmailJob = {
9
+ to: string;
10
+ subject: string;
11
+ html: string;
12
+ };
@@ -0,0 +1,39 @@
1
+ import { Injectable, type OnModuleDestroy } from '@nestjs/common';
2
+ import { Queue } from 'bullmq';
3
+ import {
4
+ DEFAULT_JOB_OPTIONS,
5
+ MESSAGING_QUEUE_NAME,
6
+ queuePrefix,
7
+ type SendEmailJob,
8
+ } from '__ROCK_SCOPE__/jobs';
9
+ import { createProducerRedisConnection } from '__ROCK_SCOPE__/queue-runtime';
10
+ import { env } from '../../env';
11
+
12
+ /**
13
+ * Publica e-mails na fila do worker `messaging`.
14
+ *
15
+ * @remarks
16
+ * A API nao fala com o provedor: enfileira e responde. O envio, as
17
+ * retentativas e a credencial da plataforma Messaging ficam em
18
+ * `apps/workers/messaging`, entao uma lentidao no provedor nao segura a
19
+ * requisicao de quem pediu o e-mail.
20
+ */
21
+ @Injectable()
22
+ export class MessagingService implements OnModuleDestroy {
23
+ private readonly connection = createProducerRedisConnection(env.REDIS_URL);
24
+
25
+ private readonly queue = new Queue<SendEmailJob>(MESSAGING_QUEUE_NAME, {
26
+ connection: this.connection.client,
27
+ prefix: queuePrefix(env.QUEUE_PREFIX, MESSAGING_QUEUE_NAME),
28
+ defaultJobOptions: DEFAULT_JOB_OPTIONS,
29
+ });
30
+
31
+ async sendEmail(input: SendEmailJob): Promise<void> {
32
+ await this.queue.add('send-email', input);
33
+ }
34
+
35
+ async onModuleDestroy(): Promise<void> {
36
+ await this.queue.close();
37
+ await this.connection.close();
38
+ }
39
+ }
@@ -0,0 +1,14 @@
1
+ import 'dotenv/config';
2
+ import { cleanEnv, num, str } from 'envalid';
3
+
4
+ export const env = cleanEnv(process.env, {
5
+ NODE_ENV: str({
6
+ choices: ['development', 'test', 'production'],
7
+ default: 'development',
8
+ }),
9
+ QUEUE_REDIS_URL: str({ default: 'redis://localhost:6379' }),
10
+ QUEUE_PREFIX: str({ default: '__ROCK_PROJECT_SLUG__' }),
11
+ MESSAGING_CONCURRENCY: num({ default: 5 }),
12
+ MESSAGING_API_KEY: str({ default: '' }),
13
+ MESSAGING_FROM: str({ default: 'nao-responda@rockfeller.com.br' }),
14
+ });
@@ -0,0 +1,59 @@
1
+ import { Injectable, Logger } from '@nestjs/common';
2
+ import { Messaging } from 'franchising/messaging';
3
+ import type { SendEmailJob } from '__ROCK_SCOPE__/jobs';
4
+ import { env } from '../../env';
5
+
6
+ /**
7
+ * Envio de e-mail pela plataforma Messaging.
8
+ *
9
+ * @remarks
10
+ * Todo e-mail transacional sai por aqui, e nao por um provedor configurado
11
+ * direto na app: remetente, dominio e politica de retentativa ficam num lugar
12
+ * so, e trocar de provedor nao encosta neste projeto.
13
+ *
14
+ * O SDK nao lanca por erro de API: devolve `{ data, error }`. Aqui o erro
15
+ * vira excecao para o BullMQ tentar o job de novo.
16
+ */
17
+ @Injectable()
18
+ export class MessagingService {
19
+ private readonly logger = new Logger(MessagingService.name);
20
+
21
+ private readonly client = env.MESSAGING_API_KEY
22
+ ? new Messaging({ secret: env.MESSAGING_API_KEY })
23
+ : undefined;
24
+
25
+ async sendEmail(input: SendEmailJob): Promise<void> {
26
+ if (!this.client) {
27
+ /*
28
+ * Sem credencial em producao o job falha e aparece no log. Em
29
+ * desenvolvimento o conteudo vai para o console, para testar links
30
+ * de login e redefinicao sem conta na plataforma.
31
+ */
32
+ if (env.NODE_ENV === 'production') {
33
+ throw new Error('MESSAGING_API_KEY_REQUIRED');
34
+ }
35
+
36
+ this.logger.warn(
37
+ JSON.stringify({
38
+ event: 'email.skipped',
39
+ reason: 'MESSAGING_API_KEY ausente',
40
+ subject: input.subject,
41
+ html: input.html,
42
+ }),
43
+ );
44
+
45
+ return;
46
+ }
47
+
48
+ const { error } = await this.client.emails.send({
49
+ to: input.to,
50
+ from: env.MESSAGING_FROM,
51
+ subject: input.subject,
52
+ html: input.html,
53
+ });
54
+
55
+ if (error) {
56
+ throw new Error(`EMAIL_SEND_FAILED: ${error.code}`);
57
+ }
58
+ }
59
+ }
@@ -0,0 +1,8 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { MessagingService } from '../messaging/service';
3
+ import { MessagingProcessor } from './processor';
4
+
5
+ @Module({
6
+ providers: [MessagingService, MessagingProcessor],
7
+ })
8
+ export class MessagingModule {}
@@ -0,0 +1,113 @@
1
+ import {
2
+ Injectable,
3
+ Logger,
4
+ type OnModuleDestroy,
5
+ type OnModuleInit,
6
+ } from '@nestjs/common';
7
+ import { UnrecoverableError, Worker } from 'bullmq';
8
+ import {
9
+ createWorkerRedisConnection,
10
+ failureReason,
11
+ type QueueRedisConnection,
12
+ } from '__ROCK_SCOPE__/queue-runtime';
13
+ import {
14
+ MESSAGING_QUEUE_NAME,
15
+ queuePrefix,
16
+ type SendEmailJob,
17
+ } from '__ROCK_SCOPE__/jobs';
18
+ import { env } from '../../env';
19
+ import { MessagingService } from '../messaging/service';
20
+ import {
21
+ LOCK_DURATION_MS,
22
+ MAX_STALLED_COUNT,
23
+ RATE_LIMIT_PER_SECOND,
24
+ STALLED_INTERVAL_MS,
25
+ } from './config';
26
+ import { isRetryable } from './retry';
27
+
28
+ /** Payload malformado nao melhora com retentativa: falha de vez. */
29
+ function parseSendEmailJob(data: unknown): SendEmailJob {
30
+ const job = data as Partial<SendEmailJob> | undefined;
31
+
32
+ if (
33
+ typeof job?.to !== 'string' ||
34
+ typeof job.subject !== 'string' ||
35
+ typeof job.html !== 'string'
36
+ ) {
37
+ throw new TypeError('INVALID_EMAIL_JOB');
38
+ }
39
+
40
+ return { to: job.to, subject: job.subject, html: job.html };
41
+ }
42
+
43
+ /**
44
+ * Consumidor da fila `messaging`.
45
+ *
46
+ * @remarks
47
+ * A API so publica o e-mail; o envio, as retentativas e a credencial da
48
+ * plataforma Messaging ficam aqui. O `Worker` do BullMQ nasce no ciclo de vida
49
+ * do Nest para que a conexao com o Redis feche no shutdown e um envio em
50
+ * andamento termine antes do processo sair.
51
+ */
52
+ @Injectable()
53
+ export class MessagingProcessor implements OnModuleInit, OnModuleDestroy {
54
+ private readonly logger = new Logger(MessagingProcessor.name);
55
+ private worker?: Worker;
56
+ private connection?: QueueRedisConnection;
57
+
58
+ constructor(private readonly messaging: MessagingService) {}
59
+
60
+ onModuleInit(): void {
61
+ this.connection = createWorkerRedisConnection(env.QUEUE_REDIS_URL);
62
+ this.worker = new Worker(
63
+ MESSAGING_QUEUE_NAME,
64
+ (job) => this.process(job),
65
+ {
66
+ connection: this.connection.client,
67
+ prefix: queuePrefix(env.QUEUE_PREFIX, MESSAGING_QUEUE_NAME),
68
+ concurrency: env.MESSAGING_CONCURRENCY,
69
+ limiter: { max: RATE_LIMIT_PER_SECOND, duration: 1000 },
70
+ lockDuration: LOCK_DURATION_MS,
71
+ stalledInterval: STALLED_INTERVAL_MS,
72
+ maxStalledCount: MAX_STALLED_COUNT,
73
+ },
74
+ );
75
+
76
+ this.worker.on('failed', (job, error) => {
77
+ this.logger.error(
78
+ JSON.stringify({
79
+ event: 'messaging.failed',
80
+ jobId: job?.id,
81
+ attempts: job?.attemptsMade,
82
+ reason: failureReason(error),
83
+ }),
84
+ );
85
+ });
86
+
87
+ this.worker.on('error', (error) => {
88
+ this.logger.error(
89
+ JSON.stringify({
90
+ event: 'messaging.error',
91
+ reason: failureReason(error),
92
+ }),
93
+ );
94
+ });
95
+ }
96
+
97
+ async onModuleDestroy(): Promise<void> {
98
+ await this.worker?.close();
99
+ await this.connection?.close();
100
+ }
101
+
102
+ private async process(job: { data: unknown }): Promise<void> {
103
+ try {
104
+ await this.messaging.sendEmail(parseSendEmailJob(job.data));
105
+ } catch (error) {
106
+ if (!isRetryable(error)) {
107
+ throw new UnrecoverableError(failureReason(error));
108
+ }
109
+
110
+ throw error;
111
+ }
112
+ }
113
+ }