@entifix/service-shell 0.11.0 → 0.12.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 (82) hide show
  1. package/README.md +1 -4
  2. package/dist/auth/require-organization.d.ts +1 -1
  3. package/dist/auth/require-organization.d.ts.map +1 -1
  4. package/dist/auth/require-organization.js.map +1 -1
  5. package/dist/auth/require-principal.d.ts +9 -55
  6. package/dist/auth/require-principal.d.ts.map +1 -1
  7. package/dist/auth/require-principal.js +15 -13
  8. package/dist/auth/require-principal.js.map +1 -1
  9. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  10. package/dist/auth/require-service-crossing.js +3 -13
  11. package/dist/auth/require-service-crossing.js.map +1 -1
  12. package/dist/auth/shared-token.d.ts +2 -0
  13. package/dist/auth/shared-token.d.ts.map +1 -1
  14. package/dist/auth/shared-token.js +2 -2
  15. package/dist/auth/shared-token.js.map +1 -1
  16. package/dist/auth/verified-context.d.ts +1 -2
  17. package/dist/auth/verified-context.d.ts.map +1 -1
  18. package/dist/auth/verified-context.js.map +1 -1
  19. package/dist/entity-facet-routes.d.ts +2 -2
  20. package/dist/entity-facet-routes.d.ts.map +1 -1
  21. package/dist/entity-facet-routes.js.map +1 -1
  22. package/dist/entity-route-guard.d.ts +2 -2
  23. package/dist/entity-route-guard.d.ts.map +1 -1
  24. package/dist/entity-route-guard.js.map +1 -1
  25. package/dist/entity-routes.d.ts +1 -1
  26. package/dist/entity-routes.d.ts.map +1 -1
  27. package/dist/entity-routes.js.map +1 -1
  28. package/dist/http-api/build-api.d.ts +78 -0
  29. package/dist/http-api/build-api.d.ts.map +1 -0
  30. package/dist/http-api/build-api.js +189 -0
  31. package/dist/http-api/build-api.js.map +1 -0
  32. package/dist/http-api/entity-api.d.ts +69 -0
  33. package/dist/http-api/entity-api.d.ts.map +1 -0
  34. package/dist/http-api/entity-api.js +522 -0
  35. package/dist/http-api/entity-api.js.map +1 -0
  36. package/dist/http-api/guards.d.ts +92 -0
  37. package/dist/http-api/guards.d.ts.map +1 -0
  38. package/dist/http-api/guards.js +131 -0
  39. package/dist/http-api/guards.js.map +1 -0
  40. package/dist/http-api/index.d.ts +6 -0
  41. package/dist/http-api/index.d.ts.map +1 -0
  42. package/dist/http-api/index.js +7 -0
  43. package/dist/http-api/index.js.map +1 -0
  44. package/dist/http-api/problem-codec.d.ts +14 -0
  45. package/dist/http-api/problem-codec.d.ts.map +1 -0
  46. package/dist/http-api/problem-codec.js +26 -0
  47. package/dist/http-api/problem-codec.js.map +1 -0
  48. package/dist/http-api/service-group.d.ts +74 -0
  49. package/dist/http-api/service-group.d.ts.map +1 -0
  50. package/dist/http-api/service-group.js +168 -0
  51. package/dist/http-api/service-group.js.map +1 -0
  52. package/dist/idempotency.d.ts +9 -4
  53. package/dist/idempotency.d.ts.map +1 -1
  54. package/dist/idempotency.js +11 -6
  55. package/dist/idempotency.js.map +1 -1
  56. package/dist/index.d.ts +1 -2
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +1 -2
  59. package/dist/index.js.map +1 -1
  60. package/dist/make-service.d.ts +39 -6
  61. package/dist/make-service.d.ts.map +1 -1
  62. package/dist/make-service.js +54 -16
  63. package/dist/make-service.js.map +1 -1
  64. package/dist/narrowing.d.ts +1 -15
  65. package/dist/narrowing.d.ts.map +1 -1
  66. package/dist/narrowing.js.map +1 -1
  67. package/dist/respond.d.ts +6 -4
  68. package/dist/respond.d.ts.map +1 -1
  69. package/dist/respond.js +11 -7
  70. package/dist/respond.js.map +1 -1
  71. package/dist/serve-test-service.d.ts +2 -1
  72. package/dist/serve-test-service.d.ts.map +1 -1
  73. package/dist/serve-test-service.js.map +1 -1
  74. package/package.json +7 -6
  75. package/dist/health-routes.d.ts +0 -24
  76. package/dist/health-routes.d.ts.map +0 -1
  77. package/dist/health-routes.js +0 -86
  78. package/dist/health-routes.js.map +0 -1
  79. package/dist/service-description-route.d.ts +0 -66
  80. package/dist/service-description-route.d.ts.map +0 -1
  81. package/dist/service-description-route.js +0 -60
  82. package/dist/service-description-route.js.map +0 -1
@@ -6,11 +6,16 @@ export declare const IDEMPOTENT_REPLAY_HEADER = "idempotent-replayed";
6
6
  /** Marks a handler as guarded, for {@link assertRetriedRoutesIdempotent}. */
7
7
  declare const IDEMPOTENT: unique symbol;
8
8
  /**
9
- * The fingerprint of a request body: SHA-256 over its canonical JSON, or over
10
- * the raw text when it is not JSON. It is what tells a retry from a different
11
- * request that reused a key.
9
+ * The fingerprint of a request: SHA-256 over its concrete target and its body
10
+ * as canonical JSON, or as raw text when it is not JSON. It is what tells a
11
+ * retry from a different request that reused a key.
12
+ *
13
+ * The target is the **concrete** method and path, not the route's template:
14
+ * one key reused on `/api/order/o1` and `/api/order/o2` is two requests, and
15
+ * hashing only the template would replay the first order's answer for the
16
+ * second.
12
17
  */
13
- export declare const requestFingerprint: (body: string) => string;
18
+ export declare const requestFingerprint: (target: string, body: string) => string;
14
19
  export interface IdempotencyKeyOptions {
15
20
  /** The route's identity in the dedup key: `POST /api/payment`. */
16
21
  readonly route: string;
@@ -1 +1 @@
1
- {"version":3,"file":"idempotency.d.ts","sourceRoot":"","sources":["../src/idempotency.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mBAAmB,EAAuB,MAAM,mBAAmB,CAAC;AAQ7E,OAAO,EAAE,MAAM,EAAQ,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAIpE,uEAAuE;AACvE,eAAO,MAAM,wBAAwB,wBAAwB,CAAC;AAE9D,6EAA6E;AAC7E,QAAA,MAAM,UAAU,eAAkD,CAAC;AAiBnE;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,GAAI,MAAM,MAAM,KAAG,MAQjD,CAAC;AAgBF,MAAM,WAAW,qBAAqB;IACpC,kEAAkE;IAClE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,MAAM,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CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAC/B,SAAS,qBAAqB,MAC9B,CAAC,EAAE,CAAC,EACH,SAAS,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,CAAC,EAAE,CAAC,CAAC;;CA+CpE,CAAC;AAEJ,yEAAyE;AACzE,eAAO,MAAM,mBAAmB,GAAI,SAAS,OAAO,KAAG,OAGI,CAAC;AAE5D,8DAA8D;AAC9D,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,GACxC,QAAQ,SAAS,YAAY,EAAE,EAC/B,SAAS,SAAS;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EAAE,KACrE,IAcF,CAAC"}
@@ -12,17 +12,22 @@ import { problemResponse } from './respond.js';
12
12
  canonical(value[key])
13
13
  ])) : value;
14
14
  /**
15
- * The fingerprint of a request body: SHA-256 over its canonical JSON, or over
16
- * the raw text when it is not JSON. It is what tells a retry from a different
17
- * request that reused a key.
18
- */ export const requestFingerprint = (body)=>{
15
+ * The fingerprint of a request: SHA-256 over its concrete target and its body
16
+ * as canonical JSON, or as raw text when it is not JSON. It is what tells a
17
+ * retry from a different request that reused a key.
18
+ *
19
+ * The target is the **concrete** method and path, not the route's template:
20
+ * one key reused on `/api/order/o1` and `/api/order/o2` is two requests, and
21
+ * hashing only the template would replay the first order's answer for the
22
+ * second.
23
+ */ export const requestFingerprint = (target, body)=>{
19
24
  let text = body;
20
25
  try {
21
26
  text = JSON.stringify(canonical(JSON.parse(body)));
22
27
  } catch (unused) {
23
28
  // Not JSON: the bytes are the request.
24
29
  }
25
- return createHash('sha256').update(text).digest('hex');
30
+ return createHash('sha256').update(`${target}\n${text}`).digest('hex');
26
31
  };
27
32
  /** A response as it can be stored; `undefined` for a body that cannot be replayed. */ const storable = (response)=>{
28
33
  const { body } = response;
@@ -59,7 +64,7 @@ import { problemResponse } from './respond.js';
59
64
  // A body that cannot be read cannot be fingerprinted: that failure is the
60
65
  // transport's, and it travels as one.
61
66
  const body = yield* request.text;
62
- const fingerprint = requestFingerprint(body);
67
+ const fingerprint = requestFingerprint(`${request.method} ${request.url.split('?')[0]}`, body);
63
68
  const dedupKey = `${options.caller}|${options.route}|${key}`;
64
69
  const store = yield* IdempotencyStoreTag;
65
70
  const claim = yield* store.claim(dedupKey, fingerprint);
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/idempotency.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport { IdempotencyStoreTag, type StoredResponse } from '@entifix/business';\nimport {\n IDEMPOTENCY_KEY_HEADER,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n parseIdempotencyKey,\n} from '@entifix/core';\nimport { Effect, Exit } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { problemResponse } from './respond.js';\n\n/** Set on a response replayed from the store, so a caller can tell. */\nexport const IDEMPOTENT_REPLAY_HEADER = 'idempotent-replayed';\n\n/** Marks a handler as guarded, for {@link assertRetriedRoutesIdempotent}. */\nconst IDEMPOTENT = Symbol.for('@entifix/service-shell/idempotent');\n\n/** Sorted keys at every depth, so two equal bodies hash equally whatever their key order. */\nconst canonical = (value: unknown): unknown =>\n Array.isArray(value)\n ? value.map(canonical)\n : value !== null && typeof value === 'object'\n ? Object.fromEntries(\n Object.keys(value)\n .sort()\n .map(key => [\n key,\n canonical((value as Record<string, unknown>)[key]),\n ]),\n )\n : value;\n\n/**\n * The fingerprint of a request body: SHA-256 over its canonical JSON, or over\n * the raw text when it is not JSON. It is what tells a retry from a different\n * request that reused a key.\n */\nexport const requestFingerprint = (body: string): string => {\n let text = body;\n try {\n text = JSON.stringify(canonical(JSON.parse(body)));\n } catch {\n // Not JSON: the bytes are the request.\n }\n return createHash('sha256').update(text).digest('hex');\n};\n\n/** A response as it can be stored; `undefined` for a body that cannot be replayed. */\nconst storable = (\n response: HttpServerResponse.HttpServerResponse,\n): StoredResponse | undefined => {\n const { body } = response;\n if (body._tag === 'Empty') return { status: response.status, body: '' };\n if (body._tag !== 'Uint8Array') return undefined;\n return {\n status: response.status,\n contentType: body.contentType,\n body: new TextDecoder().decode(body.body),\n };\n};\n\nexport interface IdempotencyKeyOptions {\n /** The route's identity in the dedup key: `POST /api/payment`. */\n readonly route: string;\n /**\n * Who is calling: the principal's id on a session route, the crossing caller\n * on a participant route. Two callers choosing one key never collide.\n */\n readonly caller: string;\n}\n\n/**\n * Makes a write route idempotent on its `Idempotency-Key`\n * (draft-ietf-httpapi-idempotency-key-header), with the store the composition\n * root provides as {@link IdempotencyStoreTag}.\n *\n * - no key, or one that is not an RFC 9651 String → `400 idempotencyKeyMissing`;\n * - a key in use with another body → `422 idempotencyKeyReused`;\n * - a key whose first request has not finished → `409 idempotencyKeyInFlight`;\n * - a key whose first request finished → that response, replayed.\n *\n * An answer — any response below `500` — is remembered. A `5xx`, a failure or a\n * defect gives the key back, because none of them is an answer and the retry\n * the key exists for must be allowed to try again.\n */\nexport const requireIdempotencyKey =\n (options: IdempotencyKeyOptions) =>\n <E, R>(\n handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n ) => {\n const guarded = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const key = parseIdempotencyKey(request.headers[IDEMPOTENCY_KEY_HEADER]);\n if (key === undefined)\n return problemResponse(new IdempotencyKeyMissing());\n\n // The body is cached by the request, so the handler reads it again.\n // A body that cannot be read cannot be fingerprinted: that failure is the\n // transport's, and it travels as one.\n const body = yield* request.text;\n const fingerprint = requestFingerprint(body);\n const dedupKey = `${options.caller}|${options.route}|${key}`;\n const store = yield* IdempotencyStoreTag;\n\n const claim = yield* store.claim(dedupKey, fingerprint);\n if (claim._tag === 'existing') {\n const { record } = claim;\n if (record.fingerprint !== fingerprint)\n return problemResponse(new IdempotencyKeyReused());\n if (record.state === 'inFlight' || record.response === undefined)\n return problemResponse(new IdempotencyKeyInFlight());\n return HttpServerResponse.text(record.response.body, {\n status: record.response.status,\n ...(record.response.contentType === undefined\n ? {}\n : { contentType: record.response.contentType }),\n headers: { [IDEMPOTENT_REPLAY_HEADER]: 'true' },\n });\n }\n\n const exit = yield* Effect.exit(handler);\n if (Exit.isSuccess(exit)) {\n const stored = storable(exit.value);\n yield* stored === undefined || stored.status >= 500\n ? store.release(dedupKey)\n : store.complete(dedupKey, stored);\n return exit.value;\n }\n yield* store.release(dedupKey);\n return yield* exit;\n });\n return Object.assign(guarded, { [IDEMPOTENT]: true as const });\n };\n\n/** Whether a handler was built through {@link requireIdempotencyKey}. */\nexport const isIdempotentHandler = (handler: unknown): boolean =>\n typeof handler === 'object' &&\n handler !== null &&\n (handler as Record<symbol, unknown>)[IDEMPOTENT] === true;\n\n/** One route a service mounts, as the mount check sees it. */\nexport interface MountedRoute {\n readonly method: string;\n readonly path: string;\n readonly handler: unknown;\n}\n\n/**\n * Fails the build — throws at mount — when a route a flow Activity retries is\n * not guarded by {@link requireIdempotencyKey}. A retried write without a key\n * is a write that runs twice; finding that out from a duplicate capture is the\n * outcome this check exists to prevent.\n */\nexport const assertRetriedRoutesIdempotent = (\n routes: readonly MountedRoute[],\n retried: readonly { readonly method: string; readonly path: string }[],\n): void => {\n const unguarded = retried.filter(target => {\n const route = routes.find(\n candidate =>\n candidate.method.toUpperCase() === target.method.toUpperCase() &&\n candidate.path === target.path,\n );\n return route === undefined || !isIdempotentHandler(route.handler);\n });\n if (unguarded.length > 0)\n throw new Error(\n 'these routes are retried by a flow and are not idempotent on an Idempotency-Key: ' +\n unguarded.map(route => `${route.method} ${route.path}`).join(', '),\n );\n};\n"],"names":["createHash","IdempotencyStoreTag","IDEMPOTENCY_KEY_HEADER","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","parseIdempotencyKey","Effect","Exit","HttpServerRequest","HttpServerResponse","problemResponse","IDEMPOTENT_REPLAY_HEADER","IDEMPOTENT","Symbol","for","canonical","value","Array","isArray","map","Object","fromEntries","keys","sort","key","requestFingerprint","body","text","JSON","stringify","parse","update","digest","storable","response","_tag","status","undefined","contentType","TextDecoder","decode","requireIdempotencyKey","options","handler","guarded","gen","request","headers","fingerprint","dedupKey","caller","route","store","claim","record","state","exit","isSuccess","stored","release","complete","assign","isIdempotentHandler","assertRetriedRoutesIdempotent","routes","retried","unguarded","filter","target","find","candidate","method","toUpperCase","path","length","Error","join"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SAASC,mBAAmB,QAA6B,oBAAoB;AAC7E,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EACpBC,mBAAmB,QACd,gBAAgB;AACvB,SAASC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AACtC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE,SAASC,eAAe,QAAQ,eAAe;AAE/C,qEAAqE,GACrE,OAAO,MAAMC,2BAA2B,sBAAsB;AAE9D,2EAA2E,GAC3E,MAAMC,aAAaC,OAAOC,GAAG,CAAC;AAE9B,2FAA2F,GAC3F,MAAMC,YAAY,CAACC,QACjBC,MAAMC,OAAO,CAACF,SACVA,MAAMG,GAAG,CAACJ,aACVC,UAAU,QAAQ,OAAOA,UAAU,WACjCI,OAAOC,WAAW,CAChBD,OAAOE,IAAI,CAACN,OACTO,IAAI,GACJJ,GAAG,CAACK,CAAAA,MAAO;YACVA;YACAT,UAAU,AAACC,KAAiC,CAACQ,IAAI;SAClD,KAELR;AAER;;;;CAIC,GACD,OAAO,MAAMS,q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,UAAUG,IAAI,KAAKL,OAAOK,IAAI;QAElC,OAAOtB,UAAUd,aAAa,CAACyB,oBAAoBX,MAAMR,OAAO;IAClE;IACA,IAAIuB,UAAUQ,MAAM,GAAG,GACrB,MAAM,IAAIC,MACR,sFACET,UAAU/C,GAAG,CAACgC,CAAAA,QAAS,GAAGA,MAAMoB,MAAM,CAAC,CAAC,EAAEpB,MAAMsB,IAAI,EAAE,EAAEG,IAAI,CAAC;AAErE,EAAE"}
1
+ {"version":3,"sources":["../src/idempotency.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport { IdempotencyStoreTag, type StoredResponse } from '@entifix/business';\nimport {\n IDEMPOTENCY_KEY_HEADER,\n IdempotencyKeyInFlight,\n IdempotencyKeyMissing,\n IdempotencyKeyReused,\n parseIdempotencyKey,\n} from '@entifix/core';\nimport { Effect, Exit } from 'effect';\nimport { HttpServerRequest, HttpServerResponse } from 'effect/http';\n\nimport { problemResponse } from './respond.js';\n\n/** Set on a response replayed from the store, so a caller can tell. */\nexport const IDEMPOTENT_REPLAY_HEADER = 'idempotent-replayed';\n\n/** Marks a handler as guarded, for {@link assertRetriedRoutesIdempotent}. */\nconst IDEMPOTENT = Symbol.for('@entifix/service-shell/idempotent');\n\n/** Sorted keys at every depth, so two equal bodies hash equally whatever their key order. */\nconst canonical = (value: unknown): unknown =>\n Array.isArray(value)\n ? value.map(canonical)\n : value !== null && typeof value === 'object'\n ? Object.fromEntries(\n Object.keys(value)\n .sort()\n .map(key => [\n key,\n canonical((value as Record<string, unknown>)[key]),\n ]),\n )\n : value;\n\n/**\n * The fingerprint of a request: SHA-256 over its concrete target and its body\n * as canonical JSON, or as raw text when it is not JSON. It is what tells a\n * retry from a different request that reused a key.\n *\n * The target is the **concrete** method and path, not the route's template:\n * one key reused on `/api/order/o1` and `/api/order/o2` is two requests, and\n * hashing only the template would replay the first order's answer for the\n * second.\n */\nexport const requestFingerprint = (target: string, body: string): string => {\n let text = body;\n try {\n text = JSON.stringify(canonical(JSON.parse(body)));\n } catch {\n // Not JSON: the bytes are the request.\n }\n return createHash('sha256').update(`${target}\\n${text}`).digest('hex');\n};\n\n/** A response as it can be stored; `undefined` for a body that cannot be replayed. */\nconst storable = (\n response: HttpServerResponse.HttpServerResponse,\n): StoredResponse | undefined => {\n const { body } = response;\n if (body._tag === 'Empty') return { status: response.status, body: '' };\n if (body._tag !== 'Uint8Array') return undefined;\n return {\n status: response.status,\n contentType: body.contentType,\n body: new TextDecoder().decode(body.body),\n };\n};\n\nexport interface IdempotencyKeyOptions {\n /** The route's identity in the dedup key: `POST /api/payment`. */\n readonly route: string;\n /**\n * Who is calling: the principal's id on a session route, the crossing caller\n * on a participant route. Two callers choosing one key never collide.\n */\n readonly caller: string;\n}\n\n/**\n * Makes a write route idempotent on its `Idempotency-Key`\n * (draft-ietf-httpapi-idempotency-key-header), with the store the composition\n * root provides as {@link IdempotencyStoreTag}.\n *\n * - no key, or one that is not an RFC 9651 String → `400 idempotencyKeyMissing`;\n * - a key in use with another body → `422 idempotencyKeyReused`;\n * - a key whose first request has not finished → `409 idempotencyKeyInFlight`;\n * - a key whose first request finished → that response, replayed.\n *\n * An answer — any response below `500` — is remembered. A `5xx`, a failure or a\n * defect gives the key back, because none of them is an answer and the retry\n * the key exists for must be allowed to try again.\n */\nexport const requireIdempotencyKey =\n (options: IdempotencyKeyOptions) =>\n <E, R>(\n handler: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n ) => {\n const guarded = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const key = parseIdempotencyKey(request.headers[IDEMPOTENCY_KEY_HEADER]);\n if (key === undefined)\n return problemResponse(new IdempotencyKeyMissing());\n\n // The body is cached by the request, so the handler reads it again.\n // A body that cannot be read cannot be fingerprinted: that failure is the\n // transport's, and it travels as one.\n const body = yield* request.text;\n const fingerprint = requestFingerprint(\n `${request.method} ${request.url.split('?')[0]}`,\n body,\n );\n const dedupKey = `${options.caller}|${options.route}|${key}`;\n const store = yield* IdempotencyStoreTag;\n\n const claim = yield* store.claim(dedupKey, fingerprint);\n if (claim._tag === 'existing') {\n const { record } = claim;\n if (record.fingerprint !== fingerprint)\n return problemResponse(new IdempotencyKeyReused());\n if (record.state === 'inFlight' || record.response === undefined)\n return problemResponse(new IdempotencyKeyInFlight());\n return HttpServerResponse.text(record.response.body, {\n status: record.response.status,\n ...(record.response.contentType === undefined\n ? {}\n : { contentType: record.response.contentType }),\n headers: { [IDEMPOTENT_REPLAY_HEADER]: 'true' },\n });\n }\n\n const exit = yield* Effect.exit(handler);\n if (Exit.isSuccess(exit)) {\n const stored = storable(exit.value);\n yield* stored === undefined || stored.status >= 500\n ? store.release(dedupKey)\n : store.complete(dedupKey, stored);\n return exit.value;\n }\n yield* store.release(dedupKey);\n return yield* exit;\n });\n return Object.assign(guarded, { [IDEMPOTENT]: true as const });\n };\n\n/** Whether a handler was built through {@link requireIdempotencyKey}. */\nexport const isIdempotentHandler = (handler: unknown): boolean =>\n typeof handler === 'object' &&\n handler !== null &&\n (handler as Record<symbol, unknown>)[IDEMPOTENT] === true;\n\n/** One route a service mounts, as the mount check sees it. */\nexport interface MountedRoute {\n readonly method: string;\n readonly path: string;\n readonly handler: unknown;\n}\n\n/**\n * Fails the build — throws at mount — when a route a flow Activity retries is\n * not guarded by {@link requireIdempotencyKey}. A retried write without a key\n * is a write that runs twice; finding that out from a duplicate capture is the\n * outcome this check exists to prevent.\n */\nexport const assertRetriedRoutesIdempotent = (\n routes: readonly MountedRoute[],\n retried: readonly { readonly method: string; readonly path: string }[],\n): void => {\n const unguarded = retried.filter(target => {\n const route = routes.find(\n candidate =>\n candidate.method.toUpperCase() === target.method.toUpperCase() &&\n candidate.path === target.path,\n );\n return route === undefined || !isIdempotentHandler(route.handler);\n });\n if (unguarded.length > 0)\n throw new Error(\n 'these routes are retried by a flow and are not idempotent on an Idempotency-Key: ' +\n unguarded.map(route => `${route.method} ${route.path}`).join(', '),\n );\n};\n"],"names":["createHash","IdempotencyStoreTag","IDEMPOTENCY_KEY_HEADER","IdempotencyKeyInFlight","IdempotencyKeyMissing","IdempotencyKeyReused","parseIdempotencyKey","Effect","Exit","HttpServerRequest","HttpServerResponse","problemResponse","IDEMPOTENT_REPLAY_HEADER","IDEMPOTENT","Symbol","for","canonical","value","Array","isArray","map","Object","fromEntries","keys","sort","key","requestFingerprint","target","body","text","JSON","stringify","parse","update","digest","storable","response","_tag","status","undefined","contentType","TextDecoder","decode","requireIdempotencyKey","options","handler","guarded","gen","request","headers","fingerprint","method","url","split","dedupKey","caller","route","store","claim","record","state","exit","isSuccess","stored","release","complete","assign","isIdempotentHandler","assertRetriedRoutesIdempotent","routes","retried","unguarded","filter","find","candidate","toUpperCase","path","length","Error","join"],"mappings":";AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,SAASC,mBAAmB,QAA6B,oBAAoB;AAC7E,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,qBAAqB,EACrBC,oBAAoB,EACpBC,mBAAmB,QACd,gBAAgB;AACvB,SAASC,MAAM,EAAEC,IAAI,QAAQ,SAAS;AACtC,SAASC,iBAAiB,EAAEC,kBAAkB,QAAQ,cAAc;AAEpE,SAASC,eAAe,QAAQ,eAAe;AAE/C,qEAAqE,GACrE,OAAO,MAAMC,2BAA2B,sBAAsB;AAE9D,2EAA2E,GAC3E,MAAMC,aAAaC,OAAOC,GAAG,CAAC;AAE9B,2FAA2F,GAC3F,MAAMC,YAAY,CAACC,QACjBC,MAAMC,OAAO,CAACF,SACVA,MAAMG,GAAG,CAACJ,aACVC,UAAU,QAAQ,OAAOA,UAAU,WACjCI,OAAOC,WAAW,CAChBD,OAAOE,IAAI,CAACN,OACTO,IAAI,GACJJ,GAAG,CAACK,CAAAA,MAAO;YACVA;YACAT,UAAU,AAACC,KAAiC,CAACQ,IAAI;SAClD,KAELR;AAER;;;;;;;;;CASC,GACD,OAAO,MAAMS,qBAAqB,CAACC,QAAgBC;IACjD,IAAIC,OAAOD;IACX,IAAI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AAOI,IAAI,CACvBC,CAAAA,YACEA,UAAUvB,MAAM,CAACwB,WAAW,OAAOhD,OAAOwB,MAAM,CAACwB,WAAW,MAC5DD,UAAUE,IAAI,KAAKjD,OAAOiD,IAAI;QAElC,OAAOpB,UAAUjB,aAAa,CAAC4B,oBAAoBX,MAAMX,OAAO;IAClE;IACA,IAAI0B,UAAUM,MAAM,GAAG,GACrB,MAAM,IAAIC,MACR,sFACEP,UAAUnD,GAAG,CAACoC,CAAAA,QAAS,GAAGA,MAAML,MAAM,CAAC,CAAC,EAAEK,MAAMoB,IAAI,EAAE,EAAEG,IAAI,CAAC;AAErE,EAAE"}
package/dist/index.d.ts CHANGED
@@ -2,12 +2,11 @@ export * from './auth/index.js';
2
2
  export * from './entity-facet-routes.js';
3
3
  export * from './entity-metadata-route.js';
4
4
  export * from './entity-routes.js';
5
- export * from './health-routes.js';
5
+ export * from './http-api/index.js';
6
6
  export * from './idempotency.js';
7
7
  export * from './metadata-composition.js';
8
8
  export * from './narrowing.js';
9
9
  export * from './redact-configuration.js';
10
10
  export * from './respond.js';
11
- export * from './service-description-route.js';
12
11
  export * from './sse.js';
13
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,gCAAgC,CAAC;AAC/C,cAAc,UAAU,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC"}
package/dist/index.js CHANGED
@@ -2,13 +2,12 @@ export * from './auth/index.js';
2
2
  export * from './entity-facet-routes.js';
3
3
  export * from './entity-metadata-route.js';
4
4
  export * from './entity-routes.js';
5
- export * from './health-routes.js';
5
+ export * from './http-api/index.js';
6
6
  export * from './idempotency.js';
7
7
  export * from './metadata-composition.js';
8
8
  export * from './narrowing.js';
9
9
  export * from './redact-configuration.js';
10
10
  export * from './respond.js';
11
- export * from './service-description-route.js';
12
11
  export * from './sse.js';
13
12
 
14
13
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './auth/index.js';\nexport * from './entity-facet-routes.js';\nexport * from './entity-metadata-route.js';\nexport * from './entity-routes.js';\nexport * from './health-routes.js';\nexport * from './idempotency.js';\nexport * from './metadata-composition.js';\nexport * from './narrowing.js';\nexport * from './redact-configuration.js';\nexport * from './respond.js';\nexport * from './service-description-route.js';\nexport * from './sse.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,2BAA2B;AACzC,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,mBAAmB;AACjC,cAAc,4BAA4B;AAC1C,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B;AAC1C,cAAc,eAAe;AAC7B,cAAc,iCAAiC;AAC/C,cAAc,WAAW"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './auth/index.js';\nexport * from './entity-facet-routes.js';\nexport * from './entity-metadata-route.js';\nexport * from './entity-routes.js';\nexport * from './http-api/index.js';\nexport * from './idempotency.js';\nexport * from './metadata-composition.js';\nexport * from './narrowing.js';\nexport * from './redact-configuration.js';\nexport * from './respond.js';\nexport * from './sse.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB;AAChC,cAAc,2BAA2B;AACzC,cAAc,6BAA6B;AAC3C,cAAc,qBAAqB;AACnC,cAAc,sBAAsB;AACpC,cAAc,mBAAmB;AACjC,cAAc,4BAA4B;AAC1C,cAAc,iBAAiB;AAC/B,cAAc,4BAA4B;AAC1C,cAAc,eAAe;AAC7B,cAAc,WAAW"}
@@ -2,6 +2,9 @@ import { HealthRegistryTag, type ShutdownRegistry, ShutdownRegistryTag, WiringRe
2
2
  import { Layer } from 'effect';
3
3
  import { HttpRouter } from 'effect/http';
4
4
  import type { SharedToken } from './auth/shared-token.js';
5
+ import { type AnyEndpointGroup, type ServedRequirements } from './http-api/build-api.js';
6
+ import { FleetTokenTag } from './http-api/guards.js';
7
+ import { type FailurePolicy } from './respond.js';
5
8
  /**
6
9
  * A service's routes: `HttpRouter.add` / `HttpRouter.addAll` layers, merged
7
10
  * with `Layer.mergeAll`. Its requirements carry, as `HttpRouter` request
@@ -27,7 +30,7 @@ export type ServiceRegistries = HealthRegistryTag | ShutdownRegistryTag | Wiring
27
30
  * skeleton every `*-service` composes; the HTTP server, logging,
28
31
  * `/api/health`, and graceful shutdown live here so services stay thin.
29
32
  */
30
- export interface ServiceDefinition<RRoutes> {
33
+ export interface ServiceDefinition<RRoutes, Groups extends ReadonlyArray<AnyEndpointGroup> = readonly []> {
31
34
  /** Service name, surfaced on `/api/health`. */
32
35
  readonly name: string;
33
36
  /** Port to bind. Convention: 310N for domain services, 319x for platform. */
@@ -50,8 +53,19 @@ export interface ServiceDefinition<RRoutes> {
50
53
  * has, and an unguarded reconnaissance map is worse than none.
51
54
  */
52
55
  readonly description?: SharedToken;
53
- /** The service's routes; their requirements are satisfied by `appLayer`. */
54
- readonly router: ServiceRoutes<RRoutes>;
56
+ /**
57
+ * The service's endpoints, served as one `HttpApi` beside the health and
58
+ * description endpoints every service has
59
+ * ([ADR 0020](../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
60
+ */
61
+ readonly endpoints?: Groups;
62
+ /** The status and log table the endpoints answer by. */
63
+ readonly policy?: FailurePolicy;
64
+ /**
65
+ * Routes that are not endpoints — a held-open stream, which an `HttpApi`
66
+ * does not describe. Their requirements are satisfied by `appLayer`.
67
+ */
68
+ readonly router?: ServiceRoutes<RRoutes>;
55
69
  /**
56
70
  * Composition root providing everything `router` requires.
57
71
  *
@@ -62,7 +76,7 @@ export interface ServiceDefinition<RRoutes> {
62
76
  * provided here, once, so the probes, the bus, the drain and the routes that
63
77
  * read them share one apiece.
64
78
  */
65
- readonly appLayer: Layer.Layer<RoutesRequirements<RRoutes>, never, ServiceRegistries>;
79
+ readonly appLayer: Layer.Layer<RoutesRequirements<RRoutes> | Exclude<ServedRequirements<Groups>, FleetTokenTag>, never, ServiceRegistries>;
66
80
  }
67
81
  /**
68
82
  * The service as a `Layer`: `/api/health` mounted, `router` served over an
@@ -80,7 +94,7 @@ export interface ServiceDefinition<RRoutes> {
80
94
  * only a real process boot has a SIGTERM to latch, and an in-process e2e boot
81
95
  * that installed one would leave a process listener per service it started.
82
96
  */
83
- export declare const makeServerLayer: <RRoutes>(def: ServiceDefinition<RRoutes>, port?: number, shutdown?: ShutdownRegistry) => Layer.Layer<Layer.Success<Layer.Layer<never, import("effect/http/HttpServerError").ServeError, Exclude<Exclude<HealthRegistryTag, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<ShutdownRegistryTag, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<WiringRegistryTag, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<import("effect/http/HttpServer").HttpServer, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<Exclude<HttpRouter.Request.Without<RRoutes>, HttpRouter.HttpRouter>, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<Exclude<Exclude<HttpRouter.Request.Only<"Requires", RRoutes>, HttpRouter.GlobalProvided>, HttpRouter.HttpRouter>, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<Exclude<Exclude<HttpRouter.Request.Only<"GlobalRequires", RRoutes>, HttpRouter.GlobalProvided>, HttpRouter.HttpRouter>, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator>>>, Layer.Error<Layer.Layer<never, import("effect/http/HttpServerError").ServeError, Exclude<Exclude<HealthRegistryTag, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<ShutdownRegistryTag, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<WiringRegistryTag, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<import("effect/http/HttpServer").HttpServer, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<Exclude<HttpRouter.Request.Without<RRoutes>, HttpRouter.HttpRouter>, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<Exclude<Exclude<HttpRouter.Request.Only<"Requires", RRoutes>, HttpRouter.GlobalProvided>, HttpRouter.HttpRouter>, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator> | Exclude<Exclude<Exclude<Exclude<HttpRouter.Request.Only<"GlobalRequires", RRoutes>, HttpRouter.GlobalProvided>, HttpRouter.HttpRouter>, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes>>, import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/Etag").Generator>>>>;
97
+ export declare const makeServerLayer: <RRoutes, const Groups extends ReadonlyArray<AnyEndpointGroup> = readonly []>(def: ServiceDefinition<RRoutes, Groups>, port?: number, shutdown?: ShutdownRegistry) => Layer.Layer<Layer.Success<Layer.Layer<never, import("effect/http/HttpServerError").ServeError, Exclude<Exclude<any, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes> | Exclude<Groups[number] extends infer T ? T extends Groups[number] ? T extends import("./index.js").EndpointGroup<infer Endpoint extends import("@entifix/core").AnyEndpoint, infer R> ? Exclude<R, import("./index.js").ProvidedToHandlers> | import("./index.js").GuardServices<Endpoint["guard"]["kind"]> | import("./index.js").IdempotencyServices<Endpoint["idempotent"]> : never : never : never, FleetTokenTag>>, import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices>>>, Layer.Error<Layer.Layer<never, import("effect/http/HttpServerError").ServeError, Exclude<Exclude<any, HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag | RoutesRequirements<RRoutes> | Exclude<Groups[number] extends infer T_1 ? T_1 extends Groups[number] ? T_1 extends import("./index.js").EndpointGroup<infer Endpoint extends import("@entifix/core").AnyEndpoint, infer R> ? Exclude<R, import("./index.js").ProvidedToHandlers> | import("./index.js").GuardServices<Endpoint["guard"]["kind"]> | import("./index.js").IdempotencyServices<Endpoint["idempotent"]> : never : never : never, FleetTokenTag>>, import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpServer").HttpServer | import("@effect/platform-node/NodeServices").NodeServices>>>>;
84
98
  /**
85
99
  * Boot an Effect service: build {@link makeServerLayer} and launch it under
86
100
  * `runMain` (SIGINT/SIGTERM interrupt the fiber, so Layer finalizers — the
@@ -97,5 +111,24 @@ export declare const makeServerLayer: <RRoutes>(def: ServiceDefinition<RRoutes>,
97
111
  * be: Kubernetes runs it before it sends SIGTERM, and this repo declares no
98
112
  * Deployment for a service. It lands with the first one.
99
113
  */
100
- export declare const makeService: <RRoutes>(def: ServiceDefinition<RRoutes>) => void;
114
+ export declare const makeService: <RRoutes, const Groups extends ReadonlyArray<AnyEndpointGroup> = readonly []>(def: ServiceDefinition<RRoutes, Groups>) => void;
115
+ /**
116
+ * A process that serves nothing over HTTP: its work reaches it through a
117
+ * datastore it shares with a service — a second runner of a flow engine,
118
+ * whose shards are assigned in the database the first one registered in.
119
+ */
120
+ export interface WorkerDefinition<A> {
121
+ /**
122
+ * Composition root. It may require the same three registries a service's
123
+ * `appLayer` may, provided here once each, so a client's probe, the bus's
124
+ * wiring and the drain behave as they would in a service.
125
+ */
126
+ readonly appLayer: Layer.Layer<A, never, ServiceRegistries>;
127
+ }
128
+ /**
129
+ * Boot a worker: `appLayer` under the registries and the shutdown drain a
130
+ * service has, launched under `runMain` with the same signal handling as
131
+ * {@link makeService}, and no HTTP server.
132
+ */
133
+ export declare const makeWorker: <A>(def: WorkerDefinition<A>) => void;
101
134
  //# sourceMappingURL=make-service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"make-service.d.ts","sourceRoot":"","sources":["../src/make-service.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,iBAAiB,EAEjB,KAAK,gBAAgB,EACrB,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAU,KAAK,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAK1D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MAAM,WAAW,gBAAgB,CAAC,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,iBAAiB,CAAC,CAAC;CAC7D;AAED;;;;GAIG;AACH,eAAO,MAAM,UAAU,GAAI,CAAC,EAAE,KAAK,gBAAgB,CAAC,CAAC,CAAC,KAAG,IAQxD,CAAC"}
@@ -3,9 +3,26 @@ import { NodeHttpServer, NodeRuntime } from '@effect/platform-node';
3
3
  import { HealthRegistryLayer, makeShutdownRegistry, ShutdownRegistryTag, WiringRegistryLayer } from '@entifix/business';
4
4
  import { Effect, Layer } from 'effect';
5
5
  import { HttpRouter } from 'effect/http';
6
- import { healthRoutes } from './health-routes.js';
6
+ import { buildApi, endpointsOf, serveApi } from './http-api/build-api.js';
7
+ import { FleetTokenTag } from './http-api/guards.js';
8
+ import { serviceGroup } from './http-api/service-group.js';
7
9
  import { logMechanismOutcome, problemNet } from './respond.js';
8
- import { serviceDescriptionRoute } from './service-description-route.js';
10
+ /**
11
+ * `appLayer` under the registries every process shares and the drain that
12
+ * shuts it down — one assembly, so a service and a worker cannot drift apart
13
+ * on either.
14
+ *
15
+ * `provideMerge` (not `provide`) so the registries the client layers
16
+ * registered into are the same instances the readiness and description routes
17
+ * read.
18
+ *
19
+ * The graceful shutdown, and its **position** is the mechanism. Build order is
20
+ * `appLayer` → the drain → whatever is built on top, so release order is the
21
+ * reverse: the drain runs after the server has stopped taking requests and
22
+ * *before* the connections it needs are closed. A signal handler could not
23
+ * give that ordering — `runMain` interrupts the fiber on SIGTERM, and a
24
+ * handler racing that interrupt would drain against a closing client.
25
+ */ const underRegistries = (appLayer, shutdown)=>Layer.provideMerge(Layer.effectDiscard(Effect.acquireRelease(Effect.void, ()=>shutdown.drain)), appLayer.pipe(Layer.provideMerge(Layer.mergeAll(HealthRegistryLayer, WiringRegistryLayer, Layer.succeed(ShutdownRegistryTag, shutdown)))));
9
26
  /**
10
27
  * The service as a `Layer`: `/api/health` mounted, `router` served over an
11
28
  * `@effect/platform-node` HTTP server with request logging, `appLayer`
@@ -22,30 +39,41 @@ import { serviceDescriptionRoute } from './service-description-route.js';
22
39
  * only a real process boot has a SIGTERM to latch, and an in-process e2e boot
23
40
  * that installed one would leave a process listener per service it started.
24
41
  */ export const makeServerLayer = (def, port = def.port, shutdown = makeShutdownRegistry().registry)=>{
25
- const routes = Layer.mergeAll(def.router, healthRoutes(def.name), def.description === undefined ? Layer.empty : serviceDescriptionRoute(def.name, def.slices, def.description), // Permissive CORS (frontends call these services cross-origin from their
42
+ var _def_endpoints, _def_router;
43
+ const hosted = (_def_endpoints = def.endpoints) != null ? _def_endpoints : [];
44
+ const fleetGuarded = hosted.flatMap((group)=>group.endpoints.filter(({ descriptor })=>descriptor.guard.kind === 'fleet'));
45
+ if (fleetGuarded.length > 0 && def.description === undefined) throw new Error(`'${def.name}' serves ${fleetGuarded.map(({ descriptor })=>`${descriptor.method} ${descriptor.path}`).join(', ')} behind the fleet token and names no \`description\` to check it against`);
46
+ const base = serviceGroup({
47
+ service: def.name,
48
+ slices: def.slices,
49
+ described: def.description !== undefined,
50
+ endpoints: ()=>endpointsOf(groups),
51
+ api: ()=>api
52
+ });
53
+ const groups = [
54
+ base,
55
+ ...hosted
56
+ ];
57
+ const options = def.policy === undefined ? {} : {
58
+ policy: def.policy
59
+ };
60
+ // One API per service: one encoder, one guard implementation, one OpenAPI.
61
+ const api = buildApi(def.name, groups, options);
62
+ const served = serveApi(api, groups, options).pipe(Layer.provide(def.description === undefined ? Layer.empty : Layer.succeed(FleetTokenTag, def.description)));
63
+ const routes = Layer.mergeAll(served, (_def_router = def.router) != null ? _def_router : Layer.empty, // Permissive CORS (frontends call these services cross-origin from their
26
64
  // dev ports). Tighten per-environment later.
27
65
  HttpRouter.cors(), // The last net: a defect no route answered is still a problem body.
28
66
  problemNet);
29
- // `provideMerge` (not `provide`) so the registries the client layers
30
- // registered into are the same instances the readiness and description routes
31
- // read.
32
- const appLayer = def.appLayer.pipe(Layer.provideMerge(Layer.mergeAll(HealthRegistryLayer, WiringRegistryLayer, Layer.succeed(ShutdownRegistryTag, shutdown))));
33
- // The graceful shutdown, and its **position** is the mechanism.
34
- // Build order is `appLayer` → this → `serve`, so release order is the
35
- // reverse: the drain runs after the server has stopped taking requests and
36
- // *before* the connections it needs are closed. A signal handler could not
37
- // give that ordering — `runMain` interrupts the fiber on SIGTERM, and a
38
- // handler racing that interrupt would drain against a closing client.
39
- const drained = Layer.provideMerge(Layer.effectDiscard(Effect.acquireRelease(Effect.void, ()=>shutdown.drain)), appLayer);
67
+ const drained = underRegistries(def.appLayer, shutdown);
40
68
  // `HttpRouter.serve` logs every request unless told not to, which is the
41
69
  // request logging `HttpMiddleware.logger` used to add here.
42
- const served = HttpRouter.serve(routes).pipe(Layer.provide(drained), Layer.provide(NodeHttpServer.layer(()=>createServer(), {
70
+ const server = HttpRouter.serve(routes).pipe(Layer.provide(drained), Layer.provide(NodeHttpServer.layer(()=>createServer(), {
43
71
  port
44
72
  })));
45
73
  // `ServiceDefinition` already proved `appLayer` covers what the routes need;
46
74
  // TypeScript cannot carry that proof through `Exclude` on a type parameter,
47
75
  // so the closed requirement set is stated here rather than re-derived.
48
- return served;
76
+ return server;
49
77
  };
50
78
  /**
51
79
  * Boot an Effect service: build {@link makeServerLayer} and launch it under
@@ -68,5 +96,15 @@ import { serviceDescriptionRoute } from './service-description-route.js';
68
96
  process.once('SIGINT', shutdown.begin);
69
97
  NodeRuntime.runMain(Layer.launch(makeServerLayer(def, def.port, shutdown.registry)));
70
98
  };
99
+ /**
100
+ * Boot a worker: `appLayer` under the registries and the shutdown drain a
101
+ * service has, launched under `runMain` with the same signal handling as
102
+ * {@link makeService}, and no HTTP server.
103
+ */ export const makeWorker = (def)=>{
104
+ const shutdown = makeShutdownRegistry(logMechanismOutcome);
105
+ process.once('SIGTERM', shutdown.begin);
106
+ process.once('SIGINT', shutdown.begin);
107
+ NodeRuntime.runMain(Layer.launch(underRegistries(def.appLayer, shutdown.registry)));
108
+ };
71
109
 
72
110
  //# sourceMappingURL=make-service.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/make-service.ts"],"sourcesContent":["import { createServer } from 'node:http';\n\nimport { NodeHttpServer, NodeRuntime } from '@effect/platform-node';\nimport {\n HealthRegistryLayer,\n HealthRegistryTag,\n makeShutdownRegistry,\n type ShutdownRegistry,\n ShutdownRegistryTag,\n WiringRegistryLayer,\n WiringRegistryTag,\n} from '@entifix/business';\nimport { Effect, Layer } from 'effect';\nimport { HttpRouter } from 'effect/http';\n\nimport type { SharedToken } from './auth/shared-token.js';\nimport { healthRoutes } from './health-routes.js';\nimport { logMechanismOutcome, problemNet } from './respond.js';\nimport { serviceDescriptionRoute } from './service-description-route.js';\n\n/**\n * A service's routes: `HttpRouter.add` / `HttpRouter.addAll` layers, merged\n * with `Layer.mergeAll`. Its requirements carry, as `HttpRouter` request\n * markers, the domain services the handlers need.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ServiceRoutes<R = any> = Layer.Layer<never, never, R>;\n\n/**\n * What a service's `appLayer` must provide for routes requiring `R`: the\n * services their handlers read per request, plus anything building the route\n * layers themselves needs.\n */\nexport type RoutesRequirements<R> =\n | HttpRouter.Request.Only<'Requires', R>\n | HttpRouter.Request.Without<Exclude<R, HttpRouter.HttpRouter>>;\n\n/** The registries {@link makeServerLayer} provides to every `appLayer`. */\nexport type ServiceRegistries =\n HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag;\n\n/**\n * Definition of an Effect-native backend service.\n *\n * `router` carries the service's routes and, in its requirements, the exact set\n * of domain services those routes need. `appLayer` must provide them — the\n * composition root. Because the requirements are tracked in the type, a\n * missing dependency is a COMPILE error at `makeService`, not a runtime\n * surprise: the launched layer must require nothing. This is the uniform\n * skeleton every `*-service` composes; the HTTP server, logging,\n * `/api/health`, and graceful shutdown live here so services stay thin.\n */\nexport interface ServiceDefinition<RRoutes> {\n /** Service name, surfaced on `/api/health`. */\n readonly name: string;\n /** Port to bind. Convention: 310N for domain services, 319x for platform. */\n readonly port: number;\n /**\n * The slices this process hosts, by their `tools/slices/` name.\n *\n * It cannot be derived. `EventSourceTag` names only the *emitting* slice, and\n * one deployment may host several, and a host that co-deploys two slices in\n * one process names both. A host that registers its deployments can check\n * each name against that register, so a wrong one fails the diff rather than\n * quietly mislabelling the fleet.\n */\n readonly slices: readonly string[];\n /**\n * The token that gates `GET /api/$service`, the service's wiring document.\n *\n * Optional, and **absent means the route is not mounted** rather than served\n * open: the document names every store, exchange and upstream the service\n * has, and an unguarded reconnaissance map is worse than none.\n */\n readonly description?: SharedToken;\n /** The service's routes; their requirements are satisfied by `appLayer`. */\n readonly router: ServiceRoutes<RRoutes>;\n /**\n * Composition root providing everything `router` requires.\n *\n * It may also *require* {@link HealthRegistryTag} — that is how a client\n * layer's readiness probe registers itself — {@link WiringRegistryTag}, which\n * is how the bus records what it bound, and {@link ShutdownRegistryTag},\n * which is how it registers what draining it means. All three instances are\n * provided here, once, so the probes, the bus, the drain and the routes that\n * read them share one apiece.\n */\n readonly appLayer: Layer.Layer<\n RoutesRequirements<RRoutes>,\n never,\n ServiceRegistries\n >;\n}\n\n/**\n * The service as a `Layer`: `/api/health` mounted, `router` served over an\n * `@effect/platform-node` HTTP server with request logging, `appLayer`\n * provided.\n *\n * Split out of {@link makeService} so the same wiring can be launched more than\n * one way. `makeService` runs it under `runMain` for production; the e2e mock\n * profile launches it in-process on an ephemeral port (see `serveTestService`).\n * Sharing this function is the point — a second assembly of router + health +\n * middleware would let the thing under test drift from the thing that ships.\n *\n * `port` overrides `def.port`, which is what an in-process boot needs.\n * `shutdown` overrides the registry, which is what {@link makeService} needs:\n * only a real process boot has a SIGTERM to latch, and an in-process e2e boot\n * that installed one would leave a process listener per service it started.\n */\nexport const makeServerLayer = <RRoutes>(\n def: ServiceDefinition<RRoutes>,\n port: number = def.port,\n shutdown: ShutdownRegistry = makeShutdownRegistry().registry,\n) => {\n const routes = Layer.mergeAll(\n def.router,\n healthRoutes(def.name),\n def.description === undefined\n ? Layer.empty\n : serviceDescriptionRoute(def.name, def.slices, def.description),\n // Permissive CORS (frontends call these services cross-origin from their\n // dev ports). Tighten per-environment later.\n HttpRouter.cors(),\n // The last net: a defect no route answered is still a problem body.\n problemNet,\n );\n\n // `provideMerge` (not `provide`) so the registries the client layers\n // registered into are the same instances the readiness and description routes\n // read.\n const appLayer = def.appLayer.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n HealthRegistryLayer,\n WiringRegistryLayer,\n Layer.succeed(ShutdownRegistryTag, shutdown),\n ),\n ),\n );\n\n // The graceful shutdown, and its **position** is the mechanism.\n // Build order is `appLayer` → this → `serve`, so release order is the\n // reverse: the drain runs after the server has stopped taking requests and\n // *before* the connections it needs are closed. A signal handler could not\n // give that ordering — `runMain` interrupts the fiber on SIGTERM, and a\n // handler racing that interrupt would drain against a closing client.\n const drained = Layer.provideMerge(\n Layer.effectDiscard(\n Effect.acquireRelease(Effect.void, () => shutdown.drain),\n ),\n appLayer,\n );\n\n // `HttpRouter.serve` logs every request unless told not to, which is the\n // request logging `HttpMiddleware.logger` used to add here.\n const served = HttpRouter.serve(routes).pipe(\n Layer.provide(drained),\n Layer.provide(NodeHttpServer.layer(() => createServer(), { port })),\n );\n // `ServiceDefinition` already proved `appLayer` covers what the routes need;\n // TypeScript cannot carry that proof through `Exclude` on a type parameter,\n // so the closed requirement set is stated here rather than re-derived.\n return served as Layer.Layer<\n Layer.Success<typeof served>,\n Layer.Error<typeof served>\n >;\n};\n\n/**\n * Boot an Effect service: build {@link makeServerLayer} and launch it under\n * `runMain` (SIGINT/SIGTERM interrupt the fiber, so Layer finalizers — the\n * shutdown drain, then the db pools — release deterministically).\n *\n * The signal listeners here do **one** thing: flip the readiness latch, in the\n * same tick `runMain`'s own listener starts the interrupt, so\n * `GET /api/health/ready` stops claiming to be ready immediately rather than\n * when the finalizers get around to running. The draining itself is the\n * finalizer's, because only layer ordering can guarantee the connections are\n * still open while it happens.\n *\n * A `preStop` grace period is **not** here and could not\n * be: Kubernetes runs it before it sends SIGTERM, and this repo declares no\n * Deployment for a service. It lands with the first one.\n */\nexport const makeService = <RRoutes>(def: ServiceDefinition<RRoutes>): void => {\n const shutdown = makeShutdownRegistry(logMechanismOutcome);\n process.once('SIGTERM', shutdown.begin);\n process.once('SIGINT', shutdown.begin);\n\n NodeRuntime.runMain(\n Layer.launch(makeServerLayer(def, def.port, shutdown.registry)),\n );\n};\n"],"names":["createServer","NodeHttpServer","NodeRuntime","HealthRegistryLayer","makeShutdownRegistry","ShutdownRegistryTag","WiringRegistryLayer","Effect","Layer","HttpRouter","healthRoutes","logMechanismOutcome","problemNet","serviceDescriptionRoute","makeServerLayer","def","port","shutdown","registry","routes","mergeAll","router","name","description","undefined","empty","slices","cors","appLayer","pipe","provideMerge","succeed","drained","effectDiscard","acquireRelease","void","drain","served","serve","provide","layer","makeService","process","once","begin","runMain","launch"],"mappings":"AAAA,SAASA,YAAY,QAAQ,YAAY;AAEzC,SAASC,cAAc,EAAEC,WAAW,QAAQ,wBAAwB;AACpE,SACEC,mBAAmB,EAEnBC,oBAAoB,EAEpBC,mBAAmB,EACnBC,mBAAmB,QAEd,oBAAoB;AAC3B,SAASC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AACvC,SAASC,UAAU,QAAQ,cAAc;AAGzC,SAASC,YAAY,QAAQ,qBAAqB;AAClD,SAASC,mBAAmB,EAAEC,UAAU,QAAQ,eAAe;AAC/D,SAASC,uBAAuB,QAAQ,iCAAiC;AA4EzE;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMC,kBAAkB,CAC7BC,KACAC,OAAeD,IAAIC,IAAI,EACvBC,WAA6Bb,uBAAuBc,QAAQ;IAE5D,MAAMC,SAASX,MAAMY,QAAQ,CAC3BL,IAAIM,MAAM,EACVX,aAAaK,IAAIO,IAAI,GACrBP,IAAIQ,WAAW,KAAKC,YAChBhB,MAAMiB,KAAK,GACXZ,wBAAwBE,IAAIO,IAAI,EAAEP,IAAIW,MAAM,EAAEX,IAAIQ,WAAW,GACjE,yEAAyE;IACzE,6CAA6C;IAC7Cd,WAAWkB,IAAI,IACf,oEAAoE;IACpEf;IAGF,qEAAqE;IACrE,8EAA8E;IAC9E,QAAQ;IACR,MAAMgB,WAAWb,IAAIa,QAAQ,CAACC,IAAI,CAChCrB,MAAMsB,YAAY,CAChBtB,MAAMY,QAAQ,CACZjB,qBACAG,qBACAE,MAAMuB,OAAO,CAAC1B,qBAAqBY;IAKzC,gEAAgE;IAChE,sEAAsE;IACtE,2EAA2E;IAC3E,2EAA2E;IAC3E,wEAAwE;IACxE,sEAAsE;IACtE,MAAMe,UAAUxB,MAAMsB,YAAY,CAChCtB,MAAMyB,aAAa,CACjB1B,OAAO2B,cAAc,CAAC3B,OAAO4B,IAAI,EAAE,IAAMlB,SAASmB,KAAK,IAEzDR;IAGF,yEAAyE;IACzE,4DAA4D;IAC5D,MAAMS,SAAS5B,WAAW6B,KAAK,CAACnB,QAAQU,IAAI,CAC1CrB,MAAM+B,OAAO,CAACP,UACdxB,MAAM+B,OAAO,CAACtC,eAAeuC,KAAK,CAAC,IAAMxC,gBAAgB;QAAEgB;IAAK;IAElE,6EAA6E;IAC7E,4EAA4E;IAC5E,uEAAuE;IACvE,OAAOqB;AAIT,EAAE;AAEF;;;;;;;;;;;;;;;CAeC,GACD,OAAO,MAAMI,cAAc,CAAU1B;IACnC,MAAME,WAAWb,qBAAqBO;IACtC+B,QAAQC,IAAI,CAAC,WAAW1B,SAAS2B,KAAK;IACtCF,QAAQC,IAAI,CAAC,UAAU1B,SAAS2B,KAAK;IAErC1C,YAAY2C,OAAO,CACjBrC,MAAMsC,MAAM,CAAChC,gBAAgBC,KAAKA,IAAIC,IAAI,EAAEC,SAASC,QAAQ;AAEjE,EAAE"}
1
+ {"version":3,"sources":["../src/make-service.ts"],"sourcesContent":["import { createServer } from 'node:http';\n\nimport { NodeHttpServer, NodeRuntime } from '@effect/platform-node';\nimport {\n HealthRegistryLayer,\n HealthRegistryTag,\n makeShutdownRegistry,\n type ShutdownRegistry,\n ShutdownRegistryTag,\n WiringRegistryLayer,\n WiringRegistryTag,\n} from '@entifix/business';\nimport { Effect, Layer } from 'effect';\nimport { HttpRouter } from 'effect/http';\n\nimport type { SharedToken } from './auth/shared-token.js';\nimport {\n type AnyEndpointGroup,\n buildApi,\n endpointsOf,\n serveApi,\n type ServedRequirements,\n} from './http-api/build-api.js';\nimport { FleetTokenTag } from './http-api/guards.js';\nimport { serviceGroup } from './http-api/service-group.js';\nimport {\n type FailurePolicy,\n logMechanismOutcome,\n problemNet,\n} from './respond.js';\n\n/**\n * A service's routes: `HttpRouter.add` / `HttpRouter.addAll` layers, merged\n * with `Layer.mergeAll`. Its requirements carry, as `HttpRouter` request\n * markers, the domain services the handlers need.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type ServiceRoutes<R = any> = Layer.Layer<never, never, R>;\n\n/**\n * What a service's `appLayer` must provide for routes requiring `R`: the\n * services their handlers read per request, plus anything building the route\n * layers themselves needs.\n */\nexport type RoutesRequirements<R> =\n | HttpRouter.Request.Only<'Requires', R>\n | HttpRouter.Request.Without<Exclude<R, HttpRouter.HttpRouter>>;\n\n/** The registries {@link makeServerLayer} provides to every `appLayer`. */\nexport type ServiceRegistries =\n HealthRegistryTag | ShutdownRegistryTag | WiringRegistryTag;\n\n/**\n * Definition of an Effect-native backend service.\n *\n * `router` carries the service's routes and, in its requirements, the exact set\n * of domain services those routes need. `appLayer` must provide them — the\n * composition root. Because the requirements are tracked in the type, a\n * missing dependency is a COMPILE error at `makeService`, not a runtime\n * surprise: the launched layer must require nothing. This is the uniform\n * skeleton every `*-service` composes; the HTTP server, logging,\n * `/api/health`, and graceful shutdown live here so services stay thin.\n */\nexport interface ServiceDefinition<\n RRoutes,\n Groups extends ReadonlyArray<AnyEndpointGroup> = readonly [],\n> {\n /** Service name, surfaced on `/api/health`. */\n readonly name: string;\n /** Port to bind. Convention: 310N for domain services, 319x for platform. */\n readonly port: number;\n /**\n * The slices this process hosts, by their `tools/slices/` name.\n *\n * It cannot be derived. `EventSourceTag` names only the *emitting* slice, and\n * one deployment may host several, and a host that co-deploys two slices in\n * one process names both. A host that registers its deployments can check\n * each name against that register, so a wrong one fails the diff rather than\n * quietly mislabelling the fleet.\n */\n readonly slices: readonly string[];\n /**\n * The token that gates `GET /api/$service`, the service's wiring document.\n *\n * Optional, and **absent means the route is not mounted** rather than served\n * open: the document names every store, exchange and upstream the service\n * has, and an unguarded reconnaissance map is worse than none.\n */\n readonly description?: SharedToken;\n /**\n * The service's endpoints, served as one `HttpApi` beside the health and\n * description endpoints every service has\n * ([ADR 0020](../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).\n */\n readonly endpoints?: Groups;\n /** The status and log table the endpoints answer by. */\n readonly policy?: FailurePolicy;\n /**\n * Routes that are not endpoints — a held-open stream, which an `HttpApi`\n * does not describe. Their requirements are satisfied by `appLayer`.\n */\n readonly router?: ServiceRoutes<RRoutes>;\n /**\n * Composition root providing everything `router` requires.\n *\n * It may also *require* {@link HealthRegistryTag} — that is how a client\n * layer's readiness probe registers itself — {@link WiringRegistryTag}, which\n * is how the bus records what it bound, and {@link ShutdownRegistryTag},\n * which is how it registers what draining it means. All three instances are\n * provided here, once, so the probes, the bus, the drain and the routes that\n * read them share one apiece.\n */\n readonly appLayer: Layer.Layer<\n | RoutesRequirements<RRoutes>\n // The fleet token is `description`'s, provided here — never the host's.\n | Exclude<ServedRequirements<Groups>, FleetTokenTag>,\n never,\n ServiceRegistries\n >;\n}\n\n/**\n * `appLayer` under the registries every process shares and the drain that\n * shuts it down — one assembly, so a service and a worker cannot drift apart\n * on either.\n *\n * `provideMerge` (not `provide`) so the registries the client layers\n * registered into are the same instances the readiness and description routes\n * read.\n *\n * The graceful shutdown, and its **position** is the mechanism. Build order is\n * `appLayer` → the drain → whatever is built on top, so release order is the\n * reverse: the drain runs after the server has stopped taking requests and\n * *before* the connections it needs are closed. A signal handler could not\n * give that ordering — `runMain` interrupts the fiber on SIGTERM, and a\n * handler racing that interrupt would drain against a closing client.\n */\nconst underRegistries = <A>(\n appLayer: Layer.Layer<A, never, ServiceRegistries>,\n shutdown: ShutdownRegistry,\n) =>\n Layer.provideMerge(\n Layer.effectDiscard(\n Effect.acquireRelease(Effect.void, () => shutdown.drain),\n ),\n appLayer.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n HealthRegistryLayer,\n WiringRegistryLayer,\n Layer.succeed(ShutdownRegistryTag, shutdown),\n ),\n ),\n ),\n );\n\n/**\n * The service as a `Layer`: `/api/health` mounted, `router` served over an\n * `@effect/platform-node` HTTP server with request logging, `appLayer`\n * provided.\n *\n * Split out of {@link makeService} so the same wiring can be launched more than\n * one way. `makeService` runs it under `runMain` for production; the e2e mock\n * profile launches it in-process on an ephemeral port (see `serveTestService`).\n * Sharing this function is the point — a second assembly of router + health +\n * middleware would let the thing under test drift from the thing that ships.\n *\n * `port` overrides `def.port`, which is what an in-process boot needs.\n * `shutdown` overrides the registry, which is what {@link makeService} needs:\n * only a real process boot has a SIGTERM to latch, and an in-process e2e boot\n * that installed one would leave a process listener per service it started.\n */\nexport const makeServerLayer = <\n RRoutes,\n const Groups extends ReadonlyArray<AnyEndpointGroup> = readonly [],\n>(\n def: ServiceDefinition<RRoutes, Groups>,\n port: number = def.port,\n shutdown: ShutdownRegistry = makeShutdownRegistry().registry,\n) => {\n const hosted = def.endpoints ?? [];\n const fleetGuarded = hosted.flatMap(group =>\n group.endpoints.filter(\n ({ descriptor }) => descriptor.guard.kind === 'fleet',\n ),\n );\n if (fleetGuarded.length > 0 && def.description === undefined)\n throw new Error(\n `'${def.name}' serves ${fleetGuarded\n .map(({ descriptor }) => `${descriptor.method} ${descriptor.path}`)\n .join(\n ', ',\n )} behind the fleet token and names no \\`description\\` to check it against`,\n );\n const base = serviceGroup({\n service: def.name,\n slices: def.slices,\n described: def.description !== undefined,\n endpoints: () => endpointsOf(groups),\n api: () => api,\n });\n const groups: ReadonlyArray<AnyEndpointGroup> = [base, ...hosted];\n const options = def.policy === undefined ? {} : { policy: def.policy };\n // One API per service: one encoder, one guard implementation, one OpenAPI.\n const api = buildApi(def.name, groups, options);\n const served = serveApi(api, groups, options).pipe(\n Layer.provide(\n def.description === undefined\n ? Layer.empty\n : Layer.succeed(FleetTokenTag, def.description),\n ),\n );\n\n const routes = Layer.mergeAll(\n served,\n def.router ?? Layer.empty,\n // Permissive CORS (frontends call these services cross-origin from their\n // dev ports). Tighten per-environment later.\n HttpRouter.cors(),\n // The last net: a defect no route answered is still a problem body.\n problemNet,\n );\n\n const drained = underRegistries(def.appLayer, shutdown);\n\n // `HttpRouter.serve` logs every request unless told not to, which is the\n // request logging `HttpMiddleware.logger` used to add here.\n const server = HttpRouter.serve(routes as ServiceRoutes).pipe(\n Layer.provide(drained),\n Layer.provide(NodeHttpServer.layer(() => createServer(), { port })),\n );\n // `ServiceDefinition` already proved `appLayer` covers what the routes need;\n // TypeScript cannot carry that proof through `Exclude` on a type parameter,\n // so the closed requirement set is stated here rather than re-derived.\n return server as Layer.Layer<\n Layer.Success<typeof server>,\n Layer.Error<typeof server>\n >;\n};\n\n/**\n * Boot an Effect service: build {@link makeServerLayer} and launch it under\n * `runMain` (SIGINT/SIGTERM interrupt the fiber, so Layer finalizers — the\n * shutdown drain, then the db pools — release deterministically).\n *\n * The signal listeners here do **one** thing: flip the readiness latch, in the\n * same tick `runMain`'s own listener starts the interrupt, so\n * `GET /api/health/ready` stops claiming to be ready immediately rather than\n * when the finalizers get around to running. The draining itself is the\n * finalizer's, because only layer ordering can guarantee the connections are\n * still open while it happens.\n *\n * A `preStop` grace period is **not** here and could not\n * be: Kubernetes runs it before it sends SIGTERM, and this repo declares no\n * Deployment for a service. It lands with the first one.\n */\nexport const makeService = <\n RRoutes,\n const Groups extends ReadonlyArray<AnyEndpointGroup> = readonly [],\n>(\n def: ServiceDefinition<RRoutes, Groups>,\n): void => {\n const shutdown = makeShutdownRegistry(logMechanismOutcome);\n process.once('SIGTERM', shutdown.begin);\n process.once('SIGINT', shutdown.begin);\n\n NodeRuntime.runMain(\n Layer.launch(makeServerLayer(def, def.port, shutdown.registry)),\n );\n};\n\n/**\n * A process that serves nothing over HTTP: its work reaches it through a\n * datastore it shares with a service — a second runner of a flow engine,\n * whose shards are assigned in the database the first one registered in.\n */\nexport interface WorkerDefinition<A> {\n /**\n * Composition root. It may require the same three registries a service's\n * `appLayer` may, provided here once each, so a client's probe, the bus's\n * wiring and the drain behave as they would in a service.\n */\n readonly appLayer: Layer.Layer<A, never, ServiceRegistries>;\n}\n\n/**\n * Boot a worker: `appLayer` under the registries and the shutdown drain a\n * service has, launched under `runMain` with the same signal handling as\n * {@link makeService}, and no HTTP server.\n */\nexport const makeWorker = <A>(def: WorkerDefinition<A>): void => {\n const shutdown = makeShutdownRegistry(logMechanismOutcome);\n process.once('SIGTERM', shutdown.begin);\n process.once('SIGINT', shutdown.begin);\n\n NodeRuntime.runMain(\n Layer.launch(underRegistries(def.appLayer, shutdown.registry)),\n );\n};\n"],"names":["createServer","NodeHttpServer","NodeRuntime","HealthRegistryLayer","makeShutdownRegistry","ShutdownRegistryTag","WiringRegistryLayer","Effect","Layer","HttpRouter","buildApi","endpointsOf","serveApi","FleetTokenTag","serviceGroup","logMechanismOutcome","problemNet","underRegistries","appLayer","shutdown","provideMerge","effectDiscard","acquireRelease","void","drain","pipe","mergeAll","succeed","makeServerLayer","def","port","registry","hosted","endpoints","fleetGuarded","flatMap","group","filter","descriptor","guard","kind","length","description","undefined","Error","name","map","method","path","join","base","service","slices","described","groups","api","options","policy","served","provide","empty","routes","router","cors","drained","server","serve","layer","makeService","process","once","begin","runMain","launch","makeWorker"],"mappings":"AAAA,SAASA,YAAY,QAAQ,YAAY;AAEzC,SAASC,cAAc,EAAEC,WAAW,QAAQ,wBAAwB;AACpE,SACEC,mBAAmB,EAEnBC,oBAAoB,EAEpBC,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IAAI,CAAC,UAAUnD,SAASoD,KAAK;IAErCrE,YAAYsE,OAAO,CACjBhE,MAAMiE,MAAM,CAAC7C,gBAAgBC,KAAKA,IAAIC,IAAI,EAAEX,SAASY,QAAQ;AAEjE,EAAE;AAgBF;;;;CAIC,GACD,OAAO,MAAM2C,aAAa,CAAI7C;IAC5B,MAAMV,WAAWf,qBAAqBW;IACtCsD,QAAQC,IAAI,CAAC,WAAWnD,SAASoD,KAAK;IACtCF,QAAQC,IAAI,CAAC,UAAUnD,SAASoD,KAAK;IAErCrE,YAAYsE,OAAO,CACjBhE,MAAMiE,MAAM,CAACxD,gBAAgBY,IAAIX,QAAQ,EAAEC,SAASY,QAAQ;AAEhE,EAAE"}
@@ -1,19 +1,5 @@
1
- import { type ResolutionRule, type VerifiedContext } from '@entifix/business';
1
+ import { type Narrowing, type NarrowingRules, type VerifiedContext } from '@entifix/business';
2
2
  import type { Entity, EntityId, EntityLoadRequest, FilterGroup } from '@entifix/core';
3
- /**
4
- * Which records of an entity a caller may see: every one, none, or those a
5
- * filter keeps ([ADR 0015](../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).
6
- * A filter is conjoined onto the load request, so a query string can only
7
- * narrow it further and no `or` in it can escape.
8
- */
9
- export type Narrowing<T extends Entity> = 'unscoped' | 'nothing' | FilterGroup<T>;
10
- /**
11
- * A read's narrowing as ordered resolver rules over the verified context: the
12
- * first variant the caller is entitled to and whose predicate holds builds the
13
- * narrowing. A caller no rule matches sees **nothing** — the direction a
14
- * missing rule must fail in.
15
- */
16
- export type NarrowingRules<T extends Entity> = readonly ResolutionRule<(context: VerifiedContext) => Narrowing<T>>[];
17
3
  /** The narrowing `rules` choose for `context`. */
18
4
  export declare const narrowingFor: <T extends Entity>(rules: NarrowingRules<T>, context: VerifiedContext) => Narrowing<T>;
19
5
  /** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */
@@ -1 +1 @@
1
- {"version":3,"file":"narrowing.d.ts","sourceRoot":"","sources":["../src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,WAAW,EACZ,MAAM,eAAe,CAAC;AAEvB,kDAAkD;AAClD,eAAO,MAAM,YAAY,GAAI,CAAC,SAAS,MAAM,EAC3C,OAAO,cAAc,CAAC,CAAC,CAAC,EACxB,SAAS,eAAe,KACvB,SAAS,CAAC,CAAC,CAMb,CAAC;AAEF,sFAAsF;AACtF,eAAO,MAAM,iBAAiB,GAAI,CAAC,SAAS,MAAM,EAChD,SAAS,iBAAiB,CAAC,CAAC,CAAC,EAC7B,WAAW,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,KAC1C,iBAAiB,CAAC,CAAC,CAGoD,CAAC;AAE3E;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,MAAM,EAClD,WAAW,WAAW,CAAC,CAAC,CAAC,EACzB,IAAI,QAAQ,KACX,iBAAiB,CAAC,CAAC,CAGiB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/narrowing.ts"],"sourcesContent":["import {\n dryRun,\n type ResolutionRule,\n type VerifiedContext,\n} from '@entifix/business';\nimport type {\n Entity,\n EntityId,\n EntityLoadRequest,\n FilterGroup,\n} from '@entifix/core';\n\n/**\n * Which records of an entity a caller may see: every one, none, or those a\n * filter keeps ([ADR 0015](../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).\n * A filter is conjoined onto the load request, so a query string can only\n * narrow it further and no `or` in it can escape.\n */\nexport type Narrowing<T extends Entity> =\n 'unscoped' | 'nothing' | FilterGroup<T>;\n\n/**\n * A read's narrowing as ordered resolver rules over the verified context: the\n * first variant the caller is entitled to and whose predicate holds builds the\n * narrowing. A caller no rule matches sees **nothing** — the direction a\n * missing rule must fail in.\n */\nexport type NarrowingRules<T extends Entity> = readonly ResolutionRule<\n (context: VerifiedContext) => Narrowing<T>\n>[];\n\n/** The narrowing `rules` choose for `context`. */\nexport const narrowingFor = <T extends Entity>(\n rules: NarrowingRules<T>,\n context: VerifiedContext,\n): Narrowing<T> => {\n const chosen = dryRun(rules, context);\n if (chosen === undefined) return 'nothing';\n // `dryRun` answers the index of a rule it found, so the rule is there.\n const rule = rules[chosen.rule] as NarrowingRules<T>[number];\n return rule.variant.impl(context);\n};\n\n/** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */\nexport const narrowLoadRequest = <T extends Entity>(\n request: EntityLoadRequest<T>,\n narrowing: Exclude<Narrowing<T>, 'nothing'>,\n): EntityLoadRequest<T> =>\n narrowing === 'unscoped'\n ? request\n : { ...request, filtering: [...(request.filtering ?? []), narrowing] };\n\n/**\n * The by-id read under a narrowing: a load of the narrowing plus id equality,\n * so a record out of the caller's sight answers exactly as an absent one does,\n * and the list and the read can never disagree about which records those are.\n */\nexport const narrowedByIdRequest = <T extends Entity>(\n narrowing: FilterGroup<T>,\n id: EntityId,\n): EntityLoadRequest<T> =>\n ({\n filtering: [narrowing, { property: 'id', operator: 'eq', value: id }],\n }) as unknown as EntityLoadRequest<T>;\n"],"names":["dryRun","narrowingFor","rules","context","chosen","undefined","rule","variant","impl","narrowLoadRequest","request","narrowing","filtering","narrowedByIdRequest","id","property","operator","value"],"mappings":";AAAA,SACEA,MAAM,QAGD,oBAAoB;AA2B3B,gDAAgD,GAChD,OAAO,MAAMC,eAAe,CAC1BC,OACAC;IAEA,MAAMC,SAASJ,OAAOE,OAAOC;IAC7B,IAAIC,WAAWC,WAAW,OAAO;IACjC,uEAAuE;IACvE,MAAMC,OAAOJ,KAAK,CAACE,OAAOE,IAAI,CAAC;IAC/B,OAAOA,KAAKC,OAAO,CAACC,IAAI,CAACL;AAC3B,EAAE;AAEF,oFAAoF,GACpF,OAAO,MAAMM,oBAAoB,CAC/BC,SACAC;QAIkCD;WAFlCC,cAAc,aACVD,UACA,aAAKA;QAASE,WAAW;gBAAKF,qBAAAA,QAAQE,SAAS,YAAjBF,qBAAqB,EAAE;YAAGC;SAAU;;EAAG;AAE3E;;;;CAIC,GACD,OAAO,MAAME,sBAAsB,CACjCF,WACAG,KAEC,CAAA;QACCF,WAAW;YAACD;YAAW;gBAAEI,UAAU;gBAAMC,UAAU;gBAAMC,OAAOH;YAAG;SAAE;IACvE,CAAA,EAAsC"}
1
+ {"version":3,"sources":["../src/narrowing.ts"],"sourcesContent":["import {\n dryRun,\n type Narrowing,\n type NarrowingRules,\n type VerifiedContext,\n} from '@entifix/business';\nimport type {\n Entity,\n EntityId,\n EntityLoadRequest,\n FilterGroup,\n} from '@entifix/core';\n\n/** The narrowing `rules` choose for `context`. */\nexport const narrowingFor = <T extends Entity>(\n rules: NarrowingRules<T>,\n context: VerifiedContext,\n): Narrowing<T> => {\n const chosen = dryRun(rules, context);\n if (chosen === undefined) return 'nothing';\n // `dryRun` answers the index of a rule it found, so the rule is there.\n const rule = rules[chosen.rule] as NarrowingRules<T>[number];\n return rule.variant.impl(context);\n};\n\n/** Conjoins a filter narrowing onto a load request; `unscoped` leaves it as it is. */\nexport const narrowLoadRequest = <T extends Entity>(\n request: EntityLoadRequest<T>,\n narrowing: Exclude<Narrowing<T>, 'nothing'>,\n): EntityLoadRequest<T> =>\n narrowing === 'unscoped'\n ? request\n : { ...request, filtering: [...(request.filtering ?? []), narrowing] };\n\n/**\n * The by-id read under a narrowing: a load of the narrowing plus id equality,\n * so a record out of the caller's sight answers exactly as an absent one does,\n * and the list and the read can never disagree about which records those are.\n */\nexport const narrowedByIdRequest = <T extends Entity>(\n narrowing: FilterGroup<T>,\n id: EntityId,\n): EntityLoadRequest<T> =>\n ({\n filtering: [narrowing, { property: 'id', operator: 'eq', value: id }],\n }) as unknown as EntityLoadRequest<T>;\n"],"names":["dryRun","narrowingFor","rules","context","chosen","undefined","rule","variant","impl","narrowLoadRequest","request","narrowing","filtering","narrowedByIdRequest","id","property","operator","value"],"mappings":";AAAA,SACEA,MAAM,QAID,oBAAoB;AAQ3B,gDAAgD,GAChD,OAAO,MAAMC,eAAe,CAC1BC,OACAC;IAEA,MAAMC,SAASJ,OAAOE,OAAOC;IAC7B,IAAIC,WAAWC,WAAW,OAAO;IACjC,uEAAuE;IACvE,MAAMC,OAAOJ,KAAK,CAACE,OAAOE,IAAI,CAAC;IAC/B,OAAOA,KAAKC,OAAO,CAACC,IAAI,CAACL;AAC3B,EAAE;AAEF,oFAAoF,GACpF,OAAO,MAAMM,oBAAoB,CAC/BC,SACAC;QAIkCD;WAFlCC,cAAc,aACVD,UACA,aAAKA;QAASE,WAAW;gBAAKF,qBAAAA,QAAQE,SAAS,YAAjBF,qBAAqB,EAAE;YAAGC;SAAU;;EAAG;AAE3E;;;;CAIC,GACD,OAAO,MAAME,sBAAsB,CACjCF,WACAG,KAEC,CAAA;QACCF,WAAW;YAACD;YAAW;gBAAEI,UAAU;gBAAMC,UAAU;gBAAMC,OAAOH;YAAG;SAAE;IACvE,CAAA,EAAsC"}
package/dist/respond.d.ts CHANGED
@@ -64,10 +64,12 @@ export declare const respond: <E extends RouteFailure, R>(effect: Effect.Effect<
64
64
  */
65
65
  export declare const mountRoutes: <const Routes extends ReadonlyArray<HttpRouter.Route<RouteFailure, any>>>(routes: Routes, policy?: FailurePolicy) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request.From<"Requires", Exclude<HttpRouter.Route.Context<{ readonly [K in keyof Routes]: HttpRouter.Route<never, HttpRouter.Route.Context<Routes[K]>>; }[number]>, HttpRouter.Provided>> | HttpRouter.Request.From<"Error", HttpRouter.Route.Error<{ readonly [K in keyof Routes]: HttpRouter.Route<never, HttpRouter.Route.Context<Routes[K]>>; }[number]>>>;
66
66
  /**
67
- * The router's last net: a defect that escaped every route — one not mounted
68
- * through {@link mountRoutes}, or one thrown while a response was being
69
- * written — answers the same opaque `500` problem. It catches defects only,
70
- * never the whole cause, so an interruption still interrupts.
67
+ * The router's last net. A path no route matches answers a `404` problem
68
+ * rather than an empty body, and a defect that escaped every route — one not
69
+ * mounted through {@link mountRoutes}, or one thrown while a response was
70
+ * being written — answers the same opaque `500` problem. It catches those two
71
+ * and nothing else, never the whole cause, so an interruption still
72
+ * interrupts.
71
73
  */
72
74
  export declare const problemNet: import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter>;
73
75
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"respond.d.ts","sourceRoot":"","sources":["../src/respond.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,eAAe,EAKrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAgB,MAAM,EAAU,MAAM,QAAQ,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAqB,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEhD;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GAAG,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC;AAEnE;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;IACnE,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACrD,QAAQ,CAAC,gBAAgB,EAAE,QAAQ,CAAC,MAAM,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC,CAAC;IACvE,QAAQ,CAAC,WAAW,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC;CAC1D;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,EAAE,aA+BlC,CAAC;AAEF,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;IACnE,QAAQ,CAAC,SAAS,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,E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;;;GAKG;AACH,eAAO,MAAM,OAAO,GAAI,CAAC,SAAS,YAAY,EAAE,CAAC,EAC/C,QAAQ,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,CAAC,EAAE,CAAC,CAAC,EAClE,SAAQ,aAAoC,KAC3C,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,kBAAkB,EAAE,KAAK,EAAE,CAAC,CAQ7D,CAAC;AAEJ;;;;GAIG;AACH,eAAO,MAAM,WAAW,GAEtB,KAAK,CAAC,MAAM,SAAS,aAAa,CAAC,UAAU,CAAC,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC,EAEvE,QAAQ,MAAM,EACd,SAAQ,aAAoC,yJAa9B,CAAC,yLAAD,CAAC,6FAKd,CAAC;AAEJ;;;;;;;GAOG;AACH,eAAO,MAAM,UAAU,mEAiBtB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;CACnC;AAED,wEAAwE;AACxE,eAAO,MAAM,wBAAwB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAOvE,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,gBAAgB,KACxB,MAAM,CAAC,MAAM,CAAC,IAAI,CAUpB,CAAC"}
package/dist/respond.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { _ as _extends } from "@swc/helpers/_/_extends";
2
2
  import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
3
- import { DEADLINE_HEADER, deadlineFromHeader, DeadlineTag, Internal, isFailure, PROBLEM_CONTENT_TYPE, problemOf } from '@entifix/core';
3
+ import { DEADLINE_HEADER, deadlineFromHeader, DeadlineTag, Internal, isFailure, NotFound, PROBLEM_CONTENT_TYPE, problemOf } from '@entifix/core';
4
4
  import { Cause, Clock, Effect, Option } from 'effect';
5
- import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
5
+ import { HttpRouter, HttpServerError, HttpServerRequest, HttpServerResponse } from 'effect/http';
6
6
  /**
7
7
  * The defaults: the category table's statuses, business failures at `Debug`
8
8
  * because an answer is not an incident, the transient technical categories at
@@ -139,11 +139,15 @@ const answerFailure = (failure, policy)=>Effect.gen(function*() {
139
139
  uninterruptible: route.uninterruptible
140
140
  })));
141
141
  /**
142
- * The router's last net: a defect that escaped every route — one not mounted
143
- * through {@link mountRoutes}, or one thrown while a response was being
144
- * written — answers the same opaque `500` problem. It catches defects only,
145
- * never the whole cause, so an interruption still interrupts.
146
- */ export const problemNet = HttpRouter.middleware((effect)=>effect.pipe(Effect.catchDefect(answerDefect)), {
142
+ * The router's last net. A path no route matches answers a `404` problem
143
+ * rather than an empty body, and a defect that escaped every route — one not
144
+ * mounted through {@link mountRoutes}, or one thrown while a response was
145
+ * being written — answers the same opaque `500` problem. It catches those two
146
+ * and nothing else, never the whole cause, so an interruption still
147
+ * interrupts.
148
+ */ export const problemNet = HttpRouter.middleware((effect)=>effect.pipe(Effect.catchIf((error)=>HttpServerError.isHttpServerError(error) && error.reason._tag === 'RouteNotFound', ()=>Effect.map(currentInstance, (instance)=>problemResponse(new NotFound({}), defaultFailurePolicy, {
149
+ instance
150
+ }))), Effect.catchDefect(answerDefect)), {
147
151
  global: true
148
152
  });
149
153
  /** The level each outcome is logged at; anything unnamed is `Debug`. */ export const MECHANISM_OUTCOME_LEVELS = {