@entifix/service-shell 0.13.0 → 0.14.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 (73) hide show
  1. package/README.md +7 -7
  2. package/dist/auth/failures.d.ts +0 -12
  3. package/dist/auth/failures.d.ts.map +1 -1
  4. package/dist/auth/failures.js +0 -10
  5. package/dist/auth/failures.js.map +1 -1
  6. package/dist/auth/index.d.ts +0 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js +0 -1
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/auth/require-principal.d.ts +0 -16
  11. package/dist/auth/require-principal.d.ts.map +1 -1
  12. package/dist/auth/require-principal.js +1 -38
  13. package/dist/auth/require-principal.js.map +1 -1
  14. package/dist/auth/require-service-crossing.d.ts +2 -73
  15. package/dist/auth/require-service-crossing.d.ts.map +1 -1
  16. package/dist/auth/require-service-crossing.js +2 -117
  17. package/dist/auth/require-service-crossing.js.map +1 -1
  18. package/dist/auth/shared-token.d.ts +0 -15
  19. package/dist/auth/shared-token.d.ts.map +1 -1
  20. package/dist/auth/shared-token.js +0 -25
  21. package/dist/auth/shared-token.js.map +1 -1
  22. package/dist/index.d.ts +0 -3
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +0 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/load-remote-configuration.d.ts +4 -4
  27. package/dist/load-remote-configuration.d.ts.map +1 -1
  28. package/dist/load-remote-configuration.js +7 -14
  29. package/dist/load-remote-configuration.js.map +1 -1
  30. package/dist/observability.d.ts +2 -2
  31. package/dist/observability.d.ts.map +1 -1
  32. package/dist/observability.js.map +1 -1
  33. package/dist/push/index.d.ts +9 -0
  34. package/dist/push/index.d.ts.map +1 -0
  35. package/dist/push/index.js +9 -0
  36. package/dist/push/index.js.map +1 -0
  37. package/dist/push/server-push.d.ts +82 -0
  38. package/dist/push/server-push.d.ts.map +1 -0
  39. package/dist/push/server-push.js +48 -0
  40. package/dist/push/server-push.js.map +1 -0
  41. package/dist/push/sse.d.ts +62 -0
  42. package/dist/push/sse.d.ts.map +1 -0
  43. package/dist/push/sse.js +120 -0
  44. package/dist/push/sse.js.map +1 -0
  45. package/dist/respond.d.ts +1 -7
  46. package/dist/respond.d.ts.map +1 -1
  47. package/dist/respond.js +1 -8
  48. package/dist/respond.js.map +1 -1
  49. package/package.json +23 -13
  50. package/dist/auth/require-organization.d.ts +0 -32
  51. package/dist/auth/require-organization.d.ts.map +0 -1
  52. package/dist/auth/require-organization.js +0 -52
  53. package/dist/auth/require-organization.js.map +0 -1
  54. package/dist/entity-facet-routes.d.ts +0 -44
  55. package/dist/entity-facet-routes.d.ts.map +0 -1
  56. package/dist/entity-facet-routes.js +0 -70
  57. package/dist/entity-facet-routes.js.map +0 -1
  58. package/dist/entity-metadata-route.d.ts +0 -25
  59. package/dist/entity-metadata-route.d.ts.map +0 -1
  60. package/dist/entity-metadata-route.js +0 -102
  61. package/dist/entity-metadata-route.js.map +0 -1
  62. package/dist/entity-route-guard.d.ts +0 -62
  63. package/dist/entity-route-guard.d.ts.map +0 -1
  64. package/dist/entity-route-guard.js +0 -35
  65. package/dist/entity-route-guard.js.map +0 -1
  66. package/dist/entity-routes.d.ts +0 -76
  67. package/dist/entity-routes.d.ts.map +0 -1
  68. package/dist/entity-routes.js +0 -267
  69. package/dist/entity-routes.js.map +0 -1
  70. package/dist/route-responses.d.ts +0 -44
  71. package/dist/route-responses.d.ts.map +0 -1
  72. package/dist/route-responses.js +0 -104
  73. package/dist/route-responses.js.map +0 -1
@@ -0,0 +1,120 @@
1
+ import { encodeEvent } from '@entifix/core';
2
+ import { Clock, Deferred, Duration, Effect, Exit, Metric, Ref, Stream } from 'effect';
3
+ import { HttpServerResponse } from 'effect/http';
4
+ import { ServerPushTag } from './server-push.js';
5
+ /**
6
+ * How often an idle push connection sends a comment frame.
7
+ *
8
+ * 15 s sits under the common 30 s idle timeout with room for one lost frame.
9
+ * An edge in front of the stream must hold an idle connection for more than
10
+ * twice this, or it closes healthy streams
11
+ * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).
12
+ */ export const PUSH_HEARTBEAT = Duration.seconds(15);
13
+ /** Open push connections on this process. */ export const pushConnections = Metric.gauge('entifix_push_connections', {
14
+ description: 'Open server-push connections.'
15
+ });
16
+ export const pushOpened = Metric.counter('entifix_push_opened_total', {
17
+ description: 'Server-push connections opened.'
18
+ });
19
+ export const pushClosed = Metric.counter('entifix_push_closed_total', {
20
+ description: 'Server-push connections closed, for any reason.'
21
+ });
22
+ export const pushDrained = Metric.counter('entifix_push_drained_total', {
23
+ description: 'Server-push connections closed by a drain on shutdown.'
24
+ });
25
+ export const pushReauth = Metric.counter('entifix_push_reauth_total', {
26
+ description: 'Server-push connections asked to reauthenticate before exp.'
27
+ });
28
+ export const pushUnencodable = Metric.counter('entifix_push_unencodable_total', {
29
+ description: 'Pushed events dropped because they do not encode.'
30
+ });
31
+ const encoder = new TextEncoder();
32
+ // `data` is `{ topics, envelope }`: the topics of this connection the event
33
+ // matched, and the event as its registered codec encodes it.
34
+ const eventFrame = (event, topics)=>Effect.exit(encodeEvent(event)).pipe(Effect.flatMap((encoded)=>Exit.isSuccess(encoded) ? Effect.succeed(`id: ${event.id}\ndata: ${JSON.stringify({
35
+ topics,
36
+ envelope: encoded.value
37
+ })}\n\n`) : Effect.as(Metric.update(pushUnencodable, 1), undefined)));
38
+ const frameOf = (message)=>message._tag === 'event' ? eventFrame(message.event, message.topics) : Effect.succeed(`event: resync\ndata: ${JSON.stringify({
39
+ topics: message.topics
40
+ })}\n\n`);
41
+ /**
42
+ * The SSE adapter of the push port.
43
+ *
44
+ * Every connection opens with its own randomized `retry:`, sends a comment
45
+ * every {@link PUSH_HEARTBEAT}, asks for a reauth at `exp − margin` and closes
46
+ * cleanly instead of failing a reconnect with a 401, and is drained — a fresh
47
+ * `retry:` and then EOF — when this adapter's scope closes.
48
+ */ export const makeSsePush = ({ retryMs, reauthMarginMs, drainWindowMs = 5000, random = Math.random })=>Effect.gen(function*() {
49
+ const push = yield* ServerPushTag;
50
+ // Each open connection's drain signal, and what it completes once its last
51
+ // frame is out.
52
+ const live = new Map();
53
+ const retry = ()=>Math.round(retryMs.min + random() * (retryMs.max - retryMs.min));
54
+ // Drain on shutdown: every connection still open is told to come back
55
+ // later, at its own randomized interval, and then ends. The finalizer waits
56
+ // for those last frames — up to the window — because the hub the
57
+ // connections read from closes right after it.
58
+ yield* Effect.addFinalizer(()=>{
59
+ const open = Array.from(live);
60
+ return Effect.forEach(open, ([drain])=>Deferred.succeed(drain, undefined), {
61
+ discard: true
62
+ }).pipe(Effect.andThen(Effect.forEach(open, ([, done])=>Deferred.await(done), {
63
+ discard: true
64
+ })), Effect.timeoutOption(Duration.millis(drainWindowMs)));
65
+ });
66
+ const frames = (connection)=>Stream.unwrap(Effect.gen(function*() {
67
+ const drain = yield* Deferred.make();
68
+ const done = yield* Deferred.make();
69
+ const ending = yield* Ref.make(undefined);
70
+ const now = yield* Clock.currentTimeMillis;
71
+ live.set(drain, done);
72
+ yield* Metric.update(pushOpened, 1);
73
+ yield* Metric.update(pushConnections, live.size);
74
+ const drained = Effect.as(Deferred.await(drain), 'drain');
75
+ const closing = connection.expiresAt === undefined ? drained : Effect.raceFirst(Effect.as(Effect.sleep(Duration.millis(Math.max(0, connection.expiresAt * 1000 - reauthMarginMs - now))), 'reauth'), drained);
76
+ const messages = Stream.filter(Stream.mapEffect(push.open(connection), frameOf), (frame)=>frame !== undefined);
77
+ const heartbeat = Stream.fromEffectRepeat(Effect.as(Effect.sleep(PUSH_HEARTBEAT), ': heartbeat\n\n'));
78
+ // The opening frame is sent at once: a chunked response writes its
79
+ // headers with its first chunk, so a quiet stream would otherwise
80
+ // leave the browser in `CONNECTING`.
81
+ const body = Stream.concat(Stream.make(`retry: ${retry()}\n: open\n\n`), Stream.merge(messages, heartbeat, {
82
+ haltStrategy: 'left'
83
+ }));
84
+ const bounded = Stream.interruptWhen(body, Effect.flatMap(closing, (reason)=>Ref.set(ending, reason)));
85
+ const last = Stream.unwrap(Effect.map(Ref.get(ending), (reason)=>{
86
+ switch(reason){
87
+ case 'reauth':
88
+ return Stream.fromEffect(Effect.as(Metric.update(pushReauth, 1), 'event: reauth\ndata: {}\n\n'));
89
+ case 'drain':
90
+ return Stream.fromEffect(Effect.as(Metric.update(pushDrained, 1), `retry: ${retry()}\n\n`));
91
+ default:
92
+ return Stream.empty;
93
+ }
94
+ }));
95
+ return Stream.ensuring(Stream.concat(bounded, last), Effect.suspend(()=>{
96
+ live.delete(drain);
97
+ return Effect.all([
98
+ Metric.update(pushClosed, 1),
99
+ Metric.update(pushConnections, live.size),
100
+ Deferred.succeed(done, undefined)
101
+ ]);
102
+ }));
103
+ }));
104
+ return {
105
+ respond: (connection)=>HttpServerResponse.stream(Stream.map(frames(connection), (frame)=>encoder.encode(frame)), {
106
+ contentType: 'text/event-stream',
107
+ headers: {
108
+ // Scoped to one principal: a cached stream is served to whoever
109
+ // asks next.
110
+ 'cache-control': 'no-store',
111
+ connection: 'keep-alive',
112
+ // A buffering proxy would hold every frame until the stream
113
+ // ends — that is, forever.
114
+ 'x-accel-buffering': 'no'
115
+ }
116
+ })
117
+ };
118
+ });
119
+
120
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/push/sse.ts"],"sourcesContent":["import { type DomainEvent, encodeEvent } from '@entifix/core';\nimport {\n Clock,\n Deferred,\n Duration,\n Effect,\n Exit,\n Metric,\n Ref,\n type Scope,\n Stream,\n} from 'effect';\nimport { HttpServerResponse } from 'effect/http';\n\nimport {\n type PushConnection,\n type PushMessage,\n ServerPushTag,\n} from './server-push.js';\n\n/**\n * How often an idle push connection sends a comment frame.\n *\n * 15 s sits under the common 30 s idle timeout with room for one lost frame.\n * An edge in front of the stream must hold an idle connection for more than\n * twice this, or it closes healthy streams\n * ([ADR 0021](../../../../../docs/adr/0021-server-push-and-the-multiplexed-channel.md)).\n */\nexport const PUSH_HEARTBEAT = Duration.seconds(15);\n\nexport interface SsePushDials {\n /**\n * The range a connection's `retry:` is drawn from, in milliseconds.\n *\n * Drawn per connection, so a redeploy that closes every stream at once does\n * not have every browser reconnect in the same instant.\n */\n readonly retryMs: { readonly min: number; readonly max: number };\n /** How long before the token's `exp` the connection asks for a reauth. */\n readonly reauthMarginMs: number;\n /**\n * How long a shutdown waits for its drained connections to send their last\n * frame, in milliseconds. Defaults to 5 000.\n */\n readonly drainWindowMs?: number;\n /** Injectable for tests; `[0, 1)`, defaults to `Math.random`. */\n readonly random?: () => number;\n}\n\nexport interface SsePushConnection extends PushConnection {\n /**\n * Unix seconds at which the credential that opened the stream expires — the\n * verified token's `exp`. Omitted for a connection with no expiring\n * credential, such as one opened with flow capabilities only.\n */\n readonly expiresAt?: number;\n}\n\nexport interface SsePush {\n /** Serves one connection as `text/event-stream`. */\n readonly respond: (\n connection: SsePushConnection,\n ) => HttpServerResponse.HttpServerResponse;\n}\n\n/** Open push connections on this process. */\nexport const pushConnections = Metric.gauge('entifix_push_connections', {\n description: 'Open server-push connections.',\n});\nexport const pushOpened = Metric.counter('entifix_push_opened_total', {\n description: 'Server-push connections opened.',\n});\nexport const pushClosed = Metric.counter('entifix_push_closed_total', {\n description: 'Server-push connections closed, for any reason.',\n});\nexport const pushDrained = Metric.counter('entifix_push_drained_total', {\n description: 'Server-push connections closed by a drain on shutdown.',\n});\nexport const pushReauth = Metric.counter('entifix_push_reauth_total', {\n description: 'Server-push connections asked to reauthenticate before exp.',\n});\nexport const pushUnencodable = Metric.counter(\n 'entifix_push_unencodable_total',\n { description: 'Pushed events dropped because they do not encode.' },\n);\n\nconst encoder = new TextEncoder();\n\n// `data` is `{ topics, envelope }`: the topics of this connection the event\n// matched, and the event as its registered codec encodes it.\nconst eventFrame = (\n event: DomainEvent,\n topics: readonly string[],\n): Effect.Effect<string | undefined> =>\n Effect.exit(encodeEvent(event)).pipe(\n Effect.flatMap(encoded =>\n Exit.isSuccess(encoded)\n ? Effect.succeed(\n `id: ${event.id}\\ndata: ${JSON.stringify({ topics, envelope: encoded.value })}\\n\\n`,\n )\n : Effect.as(Metric.update(pushUnencodable, 1), undefined),\n ),\n );\n\nconst frameOf = (message: PushMessage): Effect.Effect<string | undefined> =>\n message._tag === 'event'\n ? eventFrame(message.event, message.topics)\n : Effect.succeed(\n `event: resync\\ndata: ${JSON.stringify({ topics: message.topics })}\\n\\n`,\n );\n\ntype Ending = 'reauth' | 'drain';\n\n/**\n * The SSE adapter of the push port.\n *\n * Every connection opens with its own randomized `retry:`, sends a comment\n * every {@link PUSH_HEARTBEAT}, asks for a reauth at `exp − margin` and closes\n * cleanly instead of failing a reconnect with a 401, and is drained — a fresh\n * `retry:` and then EOF — when this adapter's scope closes.\n */\nexport const makeSsePush = ({\n retryMs,\n reauthMarginMs,\n drainWindowMs = 5_000,\n random = Math.random,\n}: SsePushDials): Effect.Effect<SsePush, never, ServerPushTag | Scope.Scope> =>\n Effect.gen(function* () {\n const push = yield* ServerPushTag;\n // Each open connection's drain signal, and what it completes once its last\n // frame is out.\n const live = new Map<Deferred.Deferred<void>, Deferred.Deferred<void>>();\n\n const retry = () =>\n Math.round(retryMs.min + random() * (retryMs.max - retryMs.min));\n\n // Drain on shutdown: every connection still open is told to come back\n // later, at its own randomized interval, and then ends. The finalizer waits\n // for those last frames — up to the window — because the hub the\n // connections read from closes right after it.\n yield* Effect.addFinalizer(() => {\n const open = Array.from(live);\n return Effect.forEach(\n open,\n ([drain]) => Deferred.succeed(drain, undefined),\n { discard: true },\n ).pipe(\n Effect.andThen(\n Effect.forEach(open, ([, done]) => Deferred.await(done), {\n discard: true,\n }),\n ),\n Effect.timeoutOption(Duration.millis(drainWindowMs)),\n );\n });\n\n const frames = (connection: SsePushConnection) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const drain = yield* Deferred.make<void>();\n const done = yield* Deferred.make<void>();\n const ending = yield* Ref.make<Ending | undefined>(undefined);\n const now = yield* Clock.currentTimeMillis;\n\n live.set(drain, done);\n yield* Metric.update(pushOpened, 1);\n yield* Metric.update(pushConnections, live.size);\n\n const drained = Effect.as(Deferred.await(drain), 'drain' as const);\n const closing: Effect.Effect<Ending> =\n connection.expiresAt === undefined\n ? drained\n : Effect.raceFirst(\n Effect.as(\n Effect.sleep(\n Duration.millis(\n Math.max(\n 0,\n connection.expiresAt * 1000 - reauthMarginMs - now,\n ),\n ),\n ),\n 'reauth' as const,\n ),\n drained,\n );\n\n const messages = Stream.filter(\n Stream.mapEffect(push.open(connection), frameOf),\n (frame): frame is string => frame !== undefined,\n );\n const heartbeat = Stream.fromEffectRepeat(\n Effect.as(Effect.sleep(PUSH_HEARTBEAT), ': heartbeat\\n\\n'),\n );\n\n // The opening frame is sent at once: a chunked response writes its\n // headers with its first chunk, so a quiet stream would otherwise\n // leave the browser in `CONNECTING`.\n const body = Stream.concat(\n Stream.make(`retry: ${retry()}\\n: open\\n\\n`),\n Stream.merge(messages, heartbeat, { haltStrategy: 'left' }),\n );\n\n const bounded = Stream.interruptWhen(\n body,\n Effect.flatMap(closing, reason => Ref.set(ending, reason)),\n );\n\n const last = Stream.unwrap(\n Effect.map(Ref.get(ending), reason => {\n switch (reason) {\n case 'reauth':\n return Stream.fromEffect(\n Effect.as(\n Metric.update(pushReauth, 1),\n 'event: reauth\\ndata: {}\\n\\n',\n ),\n );\n case 'drain':\n return Stream.fromEffect(\n Effect.as(\n Metric.update(pushDrained, 1),\n `retry: ${retry()}\\n\\n`,\n ),\n );\n default:\n return Stream.empty;\n }\n }),\n );\n\n return Stream.ensuring(\n Stream.concat(bounded, last),\n Effect.suspend(() => {\n live.delete(drain);\n return Effect.all([\n Metric.update(pushClosed, 1),\n Metric.update(pushConnections, live.size),\n Deferred.succeed(done, undefined),\n ]);\n }),\n );\n }),\n );\n\n return {\n respond: connection =>\n HttpServerResponse.stream(\n Stream.map(frames(connection), frame => encoder.encode(frame)),\n {\n contentType: 'text/event-stream',\n headers: {\n // Scoped to one principal: a cached stream is served to whoever\n // asks next.\n 'cache-control': 'no-store',\n connection: 'keep-alive',\n // A buffering proxy would hold every frame until the stream\n // ends — that is, forever.\n 'x-accel-buffering': 'no',\n },\n },\n ),\n };\n });\n"],"names":["encodeEvent","Clock","Deferred","Duration","Effect","Exit","Metric","Ref","Stream","HttpServerResponse","ServerPushTag","PUSH_HEARTBEAT","seconds","pushConnections","gauge","description","pushOpened","counter","pushClosed","pushDrained","pushReauth","pushUnencodable","encoder","TextEncoder","eventFrame","event","topics","exit","pipe","flatMap","encoded","isSuccess","succeed","id","JSON","stringify","envelope","value","as","update","undefined","frameOf","message","_tag","makeSsePush","retryMs","reauthMarginMs","drainWindowMs","random","Math","gen","push","live","Map","retry","round","min","max","addFinalizer","open","Array","from","forEach","drain","discard","andThen","done","await","timeoutOption","millis","frames","connection","unwrap","make","ending","now","currentTimeMillis","set","size","drained","closing","expiresAt","raceFirst","sleep","messages","filter","mapEffect","frame","heartbeat","fromEffectRepeat","body","concat","merge","haltStrategy","bounded","interruptWhen","reason","last","map","get","fromEffect","empty","ensuring","suspend","delete","all","respond","stream","encode","contentType","headers"],"mappings":"AAAA,SAA2BA,WAAW,QAAQ,gBAAgB;AAC9D,SACEC,KAAK,EACLC,QAAQ,EACRC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,GAAG,EAEHC,MAAM,QACD,SAAS;AAChB,SAASC,kBAAkB,QAAQ,cAAc;AAEjD,SAGEC,aAAa,QACR,mBAAmB;AAE1B;;;;;;;CAOC,GACD,OAAO,MAAMC,iBAAiBR,SAASS,OAAO,CAAC,IAAI;AAqCnD,2CAA2C,GAC3C,OAAO,MAAMC,kBAAkBP,OAAOQ,KAAK,CAAC,4BAA4B;IACtEC,aAAa;AACf,GAAG;AACH,OAAO,MAAMC,aAAaV,OAAOW,OAAO,CAAC,6BAA6B;IACpEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMG,aAAaZ,OAAOW,OAAO,CAAC,6BAA6B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K0B,IAAI;wBACxC5E,SAAS8B,OAAO,CAACkC,MAAM1B;qBACxB;gBACH;YAEJ;QAGJ,OAAO;YACLkE,SAASnC,CAAAA,aACP9D,mBAAmBkG,MAAM,CACvBnG,OAAO0F,GAAG,CAAC5B,OAAOC,aAAagB,CAAAA,QAASjE,QAAQsF,MAAM,CAACrB,SACvD;oBACEsB,aAAa;oBACbC,SAAS;wBACP,gEAAgE;wBAChE,aAAa;wBACb,iBAAiB;wBACjBvC,YAAY;wBACZ,4DAA4D;wBAC5D,2BAA2B;wBAC3B,qBAAqB;oBACvB;gBACF;QAEN;IACF,GAAG"}
package/dist/respond.d.ts CHANGED
@@ -57,16 +57,10 @@ export declare const problemResponse: (failure: EntifixFailure, policy?: Failure
57
57
  * away has nobody to answer.
58
58
  */
59
59
  export declare const respond: <E extends RouteFailure, R>(effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>, policy?: FailurePolicy) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, R>;
60
- /**
61
- * Mounts a set of routes with every handler wrapped in {@link respond}, once,
62
- * at the composition root. A route whose handler fails with anything but a
63
- * {@link RouteFailure} does not compile here.
64
- */
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
60
  /**
67
61
  * The router's last net. A path no route matches answers a `404` problem
68
62
  * 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
63
+ * wrapped in {@link respond}, or one thrown while a response was
70
64
  * being written — answers the same opaque `500` problem. It catches those two
71
65
  * and nothing else, never the whole cause, so an interruption still
72
66
  * interrupts.
@@ -1 +1 @@
1
- {"version":3,"file":"respond.d.ts","sourceRoot":"","sources":["../src/respond.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,eAAe,EAMrB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAgB,MAAM,EAAU,MAAM,QAAQ,CAAC;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EACL,UAAU,EAGV,kBAAkB,EACnB,MAAM,aAAa,CAAC;AACrB,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,EAAE,MAAM,CAAC,CA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AAO,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;;;;;;;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
@@ -131,17 +131,10 @@ const answerFailure = (failure, policy)=>Effect.gen(function*() {
131
131
  * an opaque `500`. Interruption is left alone — a request whose client went
132
132
  * away has nobody to answer.
133
133
  */ export const respond = (effect, policy = defaultFailurePolicy)=>withRequestDeadline(effect).pipe(Effect.catch((failure)=>isFailure(failure) ? answerFailure(failure, policy) : answerDefect(failure)), Effect.catchDefect(answerDefect));
134
- /**
135
- * Mounts a set of routes with every handler wrapped in {@link respond}, once,
136
- * at the composition root. A route whose handler fails with anything but a
137
- * {@link RouteFailure} does not compile here.
138
- */ export const mountRoutes = (routes, policy = defaultFailurePolicy)=>HttpRouter.addAll(routes.map((route)=>HttpRouter.route(route.method, route.path, respond(route.handler, policy), {
139
- uninterruptible: route.uninterruptible
140
- })));
141
134
  /**
142
135
  * The router's last net. A path no route matches answers a `404` problem
143
136
  * 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
137
+ * wrapped in {@link respond}, or one thrown while a response was
145
138
  * being written — answers the same opaque `500` problem. It catches those two
146
139
  * and nothing else, never the whole cause, so an interruption still
147
140
  * interrupts.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/respond.ts"],"sourcesContent":["import {\n DEADLINE_HEADER,\n deadlineFromHeader,\n DeadlineTag,\n type EntifixFailure,\n type FailureCategory,\n Internal,\n isFailure,\n NotFound,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Cause, Clock, Effect, Option } from 'effect';\nimport type { HttpBody } from 'effect/http';\nimport {\n HttpRouter,\n HttpServerError,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/http';\nimport type { Severity } from 'effect/LogLevel';\n\n/**\n * What a mounted handler may fail with: a categorised failure, or the\n * response body failing to encode. Anything else — a plain `Error`, a string —\n * does not compile at the mount, which is the point: a failure the shell cannot\n * categorise is one it cannot answer honestly\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n */\nexport type RouteFailure = EntifixFailure | HttpBody.HttpBodyError;\n\n/**\n * How a host answers and logs its failures: the status a category answers with\n * and the level it is logged at, each overridable per tag.\n *\n * The composition root owns it. A cell never decides a status, a retry or a\n * log line; it fails, and the shell's policy says what that means.\n */\nexport interface FailurePolicy {\n readonly categoryStatus: Readonly<Record<FailureCategory, number>>;\n readonly tagStatus: Readonly<Record<string, number>>;\n readonly categoryLogLevel: Readonly<Record<FailureCategory, Severity>>;\n readonly tagLogLevel: Readonly<Record<string, Severity>>;\n}\n\n/**\n * The defaults: the category table's statuses, business failures at `Debug`\n * because an answer is not an incident, the transient technical categories at\n * `Warn`, and what is broken — a peer speaking nonsense, a bug — at `Error`.\n */\nexport const defaultFailurePolicy: FailurePolicy = {\n categoryStatus: {\n invalid: 400,\n unauthenticated: 401,\n forbidden: 403,\n notFound: 404,\n conflict: 409,\n declined: 422,\n contention: 409,\n exhausted: 429,\n unavailable: 503,\n timeout: 504,\n protocol: 502,\n internal: 500,\n },\n tagStatus: {},\n categoryLogLevel: {\n invalid: 'Debug',\n unauthenticated: 'Debug',\n forbidden: 'Debug',\n notFound: 'Debug',\n conflict: 'Debug',\n declined: 'Debug',\n contention: 'Warn',\n exhausted: 'Warn',\n unavailable: 'Warn',\n timeout: 'Warn',\n protocol: 'Error',\n internal: 'Error',\n },\n tagLogLevel: {},\n};\n\nexport interface FailurePolicyOverrides {\n readonly categoryStatus?: Partial<Record<FailureCategory, number>>;\n readonly tagStatus?: Readonly<Record<string, number>>;\n readonly categoryLogLevel?: Partial<Record<FailureCategory, Severity>>;\n readonly tagLogLevel?: Readonly<Record<string, Severity>>;\n}\n\n/** A policy with some of its entries replaced — how a slice extends the fleet's. */\nexport const extendFailurePolicy = (\n base: FailurePolicy,\n overrides: FailurePolicyOverrides,\n): FailurePolicy => ({\n categoryStatus: { ...base.categoryStatus, ...overrides.categoryStatus },\n tagStatus: { ...base.tagStatus, ...overrides.tagStatus },\n categoryLogLevel: {\n ...base.categoryLogLevel,\n ...overrides.categoryLogLevel,\n },\n tagLogLevel: { ...base.tagLogLevel, ...overrides.tagLogLevel },\n});\n\nexport const statusFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failure._tag] ?? policy.categoryStatus[failure.category];\n\nexport const logLevelFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): Severity =>\n policy.tagLogLevel[failure._tag] ?? policy.categoryLogLevel[failure.category];\n\nexport interface ProblemResponseOptions {\n readonly traceId?: string | undefined;\n readonly instance?: string | undefined;\n}\n\nconst retryAfterOf = (failure: EntifixFailure): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' ? seconds : undefined;\n};\n\n/**\n * The `application/problem+json` answer to a failure, with the policy's\n * status. Built synchronously — the body is already plain data — so it cannot\n * itself fail to encode.\n */\nexport const problemResponse = (\n failure: EntifixFailure,\n policy: FailurePolicy = defaultFailurePolicy,\n options: ProblemResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const status = statusFor(failure, policy);\n const retryAfter = retryAfterOf(failure);\n return HttpServerResponse.text(\n JSON.stringify(\n problemOf(failure, {\n status,\n ...(options.traceId === undefined ? {} : { traceId: options.traceId }),\n ...(options.instance === undefined\n ? {}\n : { instance: options.instance }),\n }),\n ),\n {\n status,\n contentType: PROBLEM_CONTENT_TYPE,\n ...(retryAfter === undefined\n ? {}\n : { headers: { 'retry-after': String(retryAfter) } }),\n },\n );\n};\n\n/** The current span's trace id, when a span is open. */\nconst currentTraceId: Effect.Effect<string | undefined> = Effect.option(\n Effect.currentSpan,\n).pipe(\n Effect.map(span => Option.getOrUndefined(Option.map(span, s => s.traceId))),\n);\n\n/** The path being answered, when a request is in scope. */\nconst currentInstance: Effect.Effect<string | undefined> = Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n).pipe(\n Effect.map(request =>\n Option.getOrUndefined(Option.map(request, r => r.url.split('?')[0])),\n ),\n);\n\nconst answerFailure = (failure: EntifixFailure, policy: FailurePolicy) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logWithLevel(logLevelFor(failure, policy))(\n 'request failed',\n ).pipe(\n Effect.annotateLogs({\n code: failure.code,\n category: failure.category,\n tag: failure._tag,\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(failure, policy, { traceId, instance });\n });\n\n/**\n * The opaque `500` for anything nobody categorised. The defect is logged in\n * full here, where it was caught; the body carries the trace id to find that\n * line by, and nothing of the defect itself.\n */\nconst answerDefect = (defect: unknown) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logError('request defect').pipe(\n Effect.annotateLogs({\n code: 'internal',\n category: 'internal',\n cause: Cause.pretty(Cause.die(defect)),\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(new Internal(), defaultFailurePolicy, {\n traceId,\n instance,\n });\n });\n\n/**\n * The request's deadline, when its caller sent one, provided to the handler\n * so a retry below it never starts past it and an outbound call forwards what\n * is left ([ADR 0014](../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst withRequestDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n );\n const now = yield* Clock.currentTimeMillis;\n const deadline = Option.isSome(request)\n ? deadlineFromHeader(request.value.headers[DEADLINE_HEADER], now)\n : undefined;\n return yield* deadline === undefined\n ? effect\n : Effect.provideService(effect, DeadlineTag, deadline);\n });\n\n/**\n * The terminal reaction: every failure answered as a problem body with the\n * policy's status and logged at the policy's level, every defect answered as\n * an opaque `500`. Interruption is left alone — a request whose client went\n * away has nobody to answer.\n */\nexport const respond = <E extends RouteFailure, R>(\n effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n policy: FailurePolicy = defaultFailurePolicy,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n withRequestDeadline(effect).pipe(\n Effect.catch((failure: E) =>\n isFailure(failure)\n ? answerFailure(failure, policy)\n : answerDefect(failure),\n ),\n Effect.catchDefect(answerDefect),\n );\n\n/**\n * Mounts a set of routes with every handler wrapped in {@link respond}, once,\n * at the composition root. A route whose handler fails with anything but a\n * {@link RouteFailure} does not compile here.\n */\nexport const mountRoutes = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const Routes extends ReadonlyArray<HttpRouter.Route<RouteFailure, any>>,\n>(\n routes: Routes,\n policy: FailurePolicy = defaultFailurePolicy,\n) =>\n HttpRouter.addAll(\n routes.map(route =>\n HttpRouter.route(\n route.method,\n route.path,\n respond(route.handler, policy),\n {\n uninterruptible: route.uninterruptible,\n },\n ),\n ) as unknown as {\n readonly [K in keyof Routes]: HttpRouter.Route<\n never,\n HttpRouter.Route.Context<Routes[K]>\n >;\n },\n );\n\n/**\n * The router's last net. A path no route matches answers a `404` problem\n * rather than an empty body, and a defect that escaped every route — one not\n * mounted through {@link mountRoutes}, or one thrown while a response was\n * being written — answers the same opaque `500` problem. It catches those two\n * and nothing else, never the whole cause, so an interruption still\n * interrupts.\n */\nexport const problemNet = HttpRouter.middleware(\n effect =>\n effect.pipe(\n Effect.catchIf(\n (error: unknown) =>\n HttpServerError.isHttpServerError(error) &&\n error.reason._tag === 'RouteNotFound',\n () =>\n Effect.map(currentInstance, instance =>\n problemResponse(new NotFound({}), defaultFailurePolicy, {\n instance,\n }),\n ),\n ),\n Effect.catchDefect(answerDefect),\n ),\n { global: true },\n);\n\n/**\n * What a mechanism reports instead of logging — a relay pass, a shutdown drain\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n * Structural, so the shell can log an outcome from a package it does not\n * depend on.\n */\nexport interface MechanismOutcome {\n readonly _tag: string;\n readonly failure?: unknown;\n readonly [field: string]: unknown;\n}\n\n/** The level each outcome is logged at; anything unnamed is `Debug`. */\nexport const MECHANISM_OUTCOME_LEVELS: Readonly<Record<string, Severity>> = {\n quarantined: 'Error',\n sweepFailed: 'Error',\n hookFailed: 'Error',\n drainFailed: 'Warn',\n draining: 'Info',\n drained: 'Debug',\n};\n\n/**\n * The fork site's logger for a mechanism's outcomes: the level from the\n * outcome's tag, the outcome's own fields as annotations, and a typed\n * failure's code and category beside them — never `String(error)`.\n */\nexport const logMechanismOutcome = (\n outcome: MechanismOutcome,\n): Effect.Effect<void> => {\n const { _tag, failure, ...fields } = outcome;\n const typed = isFailure(failure)\n ? { code: failure.code, category: failure.category, tag: failure._tag }\n : failure === undefined\n ? {}\n : { code: 'internal', category: 'internal' };\n return Effect.logWithLevel(MECHANISM_OUTCOME_LEVELS[_tag] ?? 'Debug')(\n _tag,\n ).pipe(Effect.annotateLogs({ ...fields, ...typed }));\n};\n"],"names":["DEADLINE_HEADER","deadlineFromHeader","DeadlineTag","Internal","isFailure","NotFound","PROBLEM_CONTENT_TYPE","problemOf","Cause","Clock","Effect","Option","HttpRouter","HttpServerError","HttpServerRequest","HttpServerResponse","defaultFailurePolicy","categoryStatus","invalid","unauthenticated","forbidden","notFound","conflict","declined","contention","exhausted","unavailable","timeout","protocol","internal","tagStatus","categoryLogLevel","tagLogLevel","extendFailurePolicy","base","overrides","statusFor","failure","policy","_tag","category","logLevelFor","retryAfterOf","seconds","retryAfterSeconds","undefined","problemResponse","options","status","retryAfter","text","JSON","stringify","traceId","instance","contentType","headers","String","currentTraceId","option","currentSpan","pipe","map","span","getOrUndefined","s","currentInstance","serviceOption","request","r","url","split","answerFailure","gen","logWithLevel","annotateLogs","code","tag","answerDefect","defect","logError","cause","pretty","die","withRequestDeadline","effect","now","currentTimeMillis","deadline","isSome","value","provideService","respond","catch","catchDefect","mountRoutes","routes","addAll","route","method","path","handler","uninterruptible","problemNet","middleware","catchIf","error","isHttpServerError","reason","global","MECHANISM_OUTCOME_LEVELS","quarantined","sweepFailed","hookFailed","drainFailed","draining","drained","logMechanismOutcome","outcome","fields","typed"],"mappings":";;AAAA,SACEA,eAAe,EACfC,kBAAkB,EAClBC,WAAW,EAGXC,QAAQ,EACRC,SAAS,EACTC,QAAQ,EACRC,oBAAoB,EACpBC,SAAS,QACJ,gBAAgB;AACvB,SAASC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAEtD,SACEC,UAAU,EACVC,eAAe,EACfC,iBAAiB,EACjBC,kBAAkB,QACb,cAAc;AA0BrB;;;;CAIC,GACD,OAAO,MAAMC,uBAAsC;IACjDC,gBAAgB;QACdC,SAAS;QACTC,iBAAiB;QACjBC,WAAW;QACXC,UAAU;QACVC,UAAU;QACVC,UAAU;QACVC,YAAY;QACZC,WAAW;QACXC,aAAa;QACbC,SAAS;QACTC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YACEgE,iBAAiBJ,MAAMI,eAAe;QACxC,KAQJ;AAEJ;;;;;;;CAOC,GACD,OAAO,MAAMC,aAAa3F,WAAW4F,UAAU,CAC7CnB,CAAAA,SACEA,OAAOxB,IAAI,CACTnD,OAAO+F,OAAO,CACZ,CAACC,QACC7F,gBAAgB8F,iBAAiB,CAACD,UAClCA,MAAME,MAAM,CAACrE,IAAI,KAAK,iBACxB,IACE7B,OAAOoD,GAAG,CAACI,iBAAiBZ,CAAAA,WAC1BR,gBAAgB,IAAIzC,SAAS,CAAC,IAAIW,sBAAsB;gBACtDsC;YACF,MAGN5C,OAAOoF,WAAW,CAAChB,gBAEvB;IAAE+B,QAAQ;AAAK,GACf;AAcF,sEAAsE,GACtE,OAAO,MAAMC,2BAA+D;IAC1EC,aAAa;IACbC,aAAa;IACbC,YAAY;IACZC,aAAa;IACbC,UAAU;IACVC,SAAS;AACX,EAAE;AAEF;;;;CAIC,GACD,OAAO,MAAMC,sBAAsB,CACjCC;QAQ2BR;IAN3B,MAAM,EAAEvE,IAAI,EAAEF,OAAO,EAAa,GAAGiF,SAAXC,0CAAWD;;;;IACrC,MAAME,QAAQpH,UAAUiC,WACpB;QAAEuC,MAAMvC,QAAQuC,IAAI;QAAEpC,UAAUH,QAAQG,QAAQ;QAAEqC,KAAKxC,QAAQE,IAAI;IAAC,IACpEF,YAAYQ,YACV,CAAC,IACD;QAAE+B,MAAM;QAAYpC,UAAU;IAAW;IAC/C,OAAO9B,OAAOgE,YAAY,EAACoC,iCAAAA,wBAAwB,CAACvE,KAAK,YAA9BuE,iCAAkC,SAC3DvE,MACAsB,IAAI,CAACnD,OAAOiE,YAAY,CAAC,aAAK4C,QAAWC;AAC7C,EAAE"}
1
+ {"version":3,"sources":["../src/respond.ts"],"sourcesContent":["import {\n DEADLINE_HEADER,\n deadlineFromHeader,\n DeadlineTag,\n type EntifixFailure,\n type FailureCategory,\n Internal,\n isFailure,\n NotFound,\n PROBLEM_CONTENT_TYPE,\n problemOf,\n} from '@entifix/core';\nimport { Cause, Clock, Effect, Option } from 'effect';\nimport type { HttpBody } from 'effect/http';\nimport {\n HttpRouter,\n HttpServerError,\n HttpServerRequest,\n HttpServerResponse,\n} from 'effect/http';\nimport type { Severity } from 'effect/LogLevel';\n\n/**\n * What a mounted handler may fail with: a categorised failure, or the\n * response body failing to encode. Anything else — a plain `Error`, a string —\n * does not compile at the mount, which is the point: a failure the shell cannot\n * categorise is one it cannot answer honestly\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n */\nexport type RouteFailure = EntifixFailure | HttpBody.HttpBodyError;\n\n/**\n * How a host answers and logs its failures: the status a category answers with\n * and the level it is logged at, each overridable per tag.\n *\n * The composition root owns it. A cell never decides a status, a retry or a\n * log line; it fails, and the shell's policy says what that means.\n */\nexport interface FailurePolicy {\n readonly categoryStatus: Readonly<Record<FailureCategory, number>>;\n readonly tagStatus: Readonly<Record<string, number>>;\n readonly categoryLogLevel: Readonly<Record<FailureCategory, Severity>>;\n readonly tagLogLevel: Readonly<Record<string, Severity>>;\n}\n\n/**\n * The defaults: the category table's statuses, business failures at `Debug`\n * because an answer is not an incident, the transient technical categories at\n * `Warn`, and what is broken — a peer speaking nonsense, a bug — at `Error`.\n */\nexport const defaultFailurePolicy: FailurePolicy = {\n categoryStatus: {\n invalid: 400,\n unauthenticated: 401,\n forbidden: 403,\n notFound: 404,\n conflict: 409,\n declined: 422,\n contention: 409,\n exhausted: 429,\n unavailable: 503,\n timeout: 504,\n protocol: 502,\n internal: 500,\n },\n tagStatus: {},\n categoryLogLevel: {\n invalid: 'Debug',\n unauthenticated: 'Debug',\n forbidden: 'Debug',\n notFound: 'Debug',\n conflict: 'Debug',\n declined: 'Debug',\n contention: 'Warn',\n exhausted: 'Warn',\n unavailable: 'Warn',\n timeout: 'Warn',\n protocol: 'Error',\n internal: 'Error',\n },\n tagLogLevel: {},\n};\n\nexport interface FailurePolicyOverrides {\n readonly categoryStatus?: Partial<Record<FailureCategory, number>>;\n readonly tagStatus?: Readonly<Record<string, number>>;\n readonly categoryLogLevel?: Partial<Record<FailureCategory, Severity>>;\n readonly tagLogLevel?: Readonly<Record<string, Severity>>;\n}\n\n/** A policy with some of its entries replaced — how a slice extends the fleet's. */\nexport const extendFailurePolicy = (\n base: FailurePolicy,\n overrides: FailurePolicyOverrides,\n): FailurePolicy => ({\n categoryStatus: { ...base.categoryStatus, ...overrides.categoryStatus },\n tagStatus: { ...base.tagStatus, ...overrides.tagStatus },\n categoryLogLevel: {\n ...base.categoryLogLevel,\n ...overrides.categoryLogLevel,\n },\n tagLogLevel: { ...base.tagLogLevel, ...overrides.tagLogLevel },\n});\n\nexport const statusFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): number =>\n policy.tagStatus[failure._tag] ?? policy.categoryStatus[failure.category];\n\nexport const logLevelFor = (\n failure: EntifixFailure,\n policy: FailurePolicy,\n): Severity =>\n policy.tagLogLevel[failure._tag] ?? policy.categoryLogLevel[failure.category];\n\nexport interface ProblemResponseOptions {\n readonly traceId?: string | undefined;\n readonly instance?: string | undefined;\n}\n\nconst retryAfterOf = (failure: EntifixFailure): number | undefined => {\n const seconds = (failure as { readonly retryAfterSeconds?: unknown })\n .retryAfterSeconds;\n return typeof seconds === 'number' ? seconds : undefined;\n};\n\n/**\n * The `application/problem+json` answer to a failure, with the policy's\n * status. Built synchronously — the body is already plain data — so it cannot\n * itself fail to encode.\n */\nexport const problemResponse = (\n failure: EntifixFailure,\n policy: FailurePolicy = defaultFailurePolicy,\n options: ProblemResponseOptions = {},\n): HttpServerResponse.HttpServerResponse => {\n const status = statusFor(failure, policy);\n const retryAfter = retryAfterOf(failure);\n return HttpServerResponse.text(\n JSON.stringify(\n problemOf(failure, {\n status,\n ...(options.traceId === undefined ? {} : { traceId: options.traceId }),\n ...(options.instance === undefined\n ? {}\n : { instance: options.instance }),\n }),\n ),\n {\n status,\n contentType: PROBLEM_CONTENT_TYPE,\n ...(retryAfter === undefined\n ? {}\n : { headers: { 'retry-after': String(retryAfter) } }),\n },\n );\n};\n\n/** The current span's trace id, when a span is open. */\nconst currentTraceId: Effect.Effect<string | undefined> = Effect.option(\n Effect.currentSpan,\n).pipe(\n Effect.map(span => Option.getOrUndefined(Option.map(span, s => s.traceId))),\n);\n\n/** The path being answered, when a request is in scope. */\nconst currentInstance: Effect.Effect<string | undefined> = Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n).pipe(\n Effect.map(request =>\n Option.getOrUndefined(Option.map(request, r => r.url.split('?')[0])),\n ),\n);\n\nconst answerFailure = (failure: EntifixFailure, policy: FailurePolicy) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logWithLevel(logLevelFor(failure, policy))(\n 'request failed',\n ).pipe(\n Effect.annotateLogs({\n code: failure.code,\n category: failure.category,\n tag: failure._tag,\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(failure, policy, { traceId, instance });\n });\n\n/**\n * The opaque `500` for anything nobody categorised. The defect is logged in\n * full here, where it was caught; the body carries the trace id to find that\n * line by, and nothing of the defect itself.\n */\nconst answerDefect = (defect: unknown) =>\n Effect.gen(function* () {\n const traceId = yield* currentTraceId;\n const instance = yield* currentInstance;\n yield* Effect.logError('request defect').pipe(\n Effect.annotateLogs({\n code: 'internal',\n category: 'internal',\n cause: Cause.pretty(Cause.die(defect)),\n ...(traceId === undefined ? {} : { traceId }),\n }),\n );\n return problemResponse(new Internal(), defaultFailurePolicy, {\n traceId,\n instance,\n });\n });\n\n/**\n * The request's deadline, when its caller sent one, provided to the handler\n * so a retry below it never starts past it and an outbound call forwards what\n * is left ([ADR 0014](../../../../docs/adr/0014-retry-once-at-the-layer-above-under-a-budget.md)).\n */\nconst withRequestDeadline = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n Effect.gen(function* () {\n const request = yield* Effect.serviceOption(\n HttpServerRequest.HttpServerRequest,\n );\n const now = yield* Clock.currentTimeMillis;\n const deadline = Option.isSome(request)\n ? deadlineFromHeader(request.value.headers[DEADLINE_HEADER], now)\n : undefined;\n return yield* deadline === undefined\n ? effect\n : Effect.provideService(effect, DeadlineTag, deadline);\n });\n\n/**\n * The terminal reaction: every failure answered as a problem body with the\n * policy's status and logged at the policy's level, every defect answered as\n * an opaque `500`. Interruption is left alone — a request whose client went\n * away has nobody to answer.\n */\nexport const respond = <E extends RouteFailure, R>(\n effect: Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,\n policy: FailurePolicy = defaultFailurePolicy,\n): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R> =>\n withRequestDeadline(effect).pipe(\n Effect.catch((failure: E) =>\n isFailure(failure)\n ? answerFailure(failure, policy)\n : answerDefect(failure),\n ),\n Effect.catchDefect(answerDefect),\n );\n\n/**\n * The router's last net. A path no route matches answers a `404` problem\n * rather than an empty body, and a defect that escaped every route — one not\n * wrapped in {@link respond}, or one thrown while a response was\n * being written — answers the same opaque `500` problem. It catches those two\n * and nothing else, never the whole cause, so an interruption still\n * interrupts.\n */\nexport const problemNet = HttpRouter.middleware(\n effect =>\n effect.pipe(\n Effect.catchIf(\n (error: unknown) =>\n HttpServerError.isHttpServerError(error) &&\n error.reason._tag === 'RouteNotFound',\n () =>\n Effect.map(currentInstance, instance =>\n problemResponse(new NotFound({}), defaultFailurePolicy, {\n instance,\n }),\n ),\n ),\n Effect.catchDefect(answerDefect),\n ),\n { global: true },\n);\n\n/**\n * What a mechanism reports instead of logging — a relay pass, a shutdown drain\n * ([ADR 0013](../../../../docs/adr/0013-failures-are-typed-values-decided-at-the-shell.md)).\n * Structural, so the shell can log an outcome from a package it does not\n * depend on.\n */\nexport interface MechanismOutcome {\n readonly _tag: string;\n readonly failure?: unknown;\n readonly [field: string]: unknown;\n}\n\n/** The level each outcome is logged at; anything unnamed is `Debug`. */\nexport const MECHANISM_OUTCOME_LEVELS: Readonly<Record<string, Severity>> = {\n quarantined: 'Error',\n sweepFailed: 'Error',\n hookFailed: 'Error',\n drainFailed: 'Warn',\n draining: 'Info',\n drained: 'Debug',\n};\n\n/**\n * The fork site's logger for a mechanism's outcomes: the level from the\n * outcome's tag, the outcome's own fields as annotations, and a typed\n * failure's code and category beside them — never `String(error)`.\n */\nexport const logMechanismOutcome = (\n outcome: MechanismOutcome,\n): Effect.Effect<void> => {\n const { _tag, failure, ...fields } = outcome;\n const typed = isFailure(failure)\n ? { code: failure.code, category: failure.category, tag: failure._tag }\n : failure === undefined\n ? {}\n : { code: 'internal', category: 'internal' };\n return Effect.logWithLevel(MECHANISM_OUTCOME_LEVELS[_tag] ?? 'Debug')(\n _tag,\n ).pipe(Effect.annotateLogs({ ...fields, ...typed }));\n};\n"],"names":["DEADLINE_HEADER","deadlineFromHeader","DeadlineTag","Internal","isFailure","NotFound","PROBLEM_CONTENT_TYPE","problemOf","Cause","Clock","Effect","Option","HttpRouter","HttpServerError","HttpServerRequest","HttpServerResponse","defaultFailurePolicy","categoryStatus","invalid","unauthenticated","forbidden","notFound","conflict","declined","contention","exhausted","unavailable","timeout","protocol","internal","tagStatus","categoryLogLevel","tagLogLevel","extendFailurePolicy","base","overrides","statusFor","failure","policy","_tag","category","logLevelFor","retryAfterOf","seconds","retryAfterSeconds","undefined","problemResponse","options","status","retryAfter","text","JSON","stringify","traceId","instance","contentType","headers","String","currentTraceId","option","currentSpan","pipe","map","span","getOrUndefined","s","currentInstance","serviceOption","request","r","url","split","answerFailure","gen","logWithLevel","annotateLogs","code","tag","answerDefect","defect","logError","cause","pretty","die","withRequestDeadline","effect","now","currentTimeMillis","deadline","isSome","value","provideService","respond","catch","catchDefect","problemNet","middleware","catchIf","error","isHttpServerError","reason","global","MECHANISM_OUTCOME_LEVELS","quarantined","sweepFailed","hookFailed","drainFailed","draining","drained","logMechanismOutcome","outcome","fields","typed"],"mappings":";;AAAA,SACEA,eAAe,EACfC,kBAAkB,EAClBC,WAAW,EAGXC,QAAQ,EACRC,SAAS,EACTC,QAAQ,EACRC,oBAAoB,EACpBC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14.0",
4
4
  "description": "Effect HTTP service skeleton: server layer, health and metadata routes, permission guards, remote configuration and OpenTelemetry.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,6 +37,16 @@
37
37
  "import": "./dist/observability.js",
38
38
  "default": "./dist/observability.js"
39
39
  },
40
+ "./push": {
41
+ "types": "./dist/push/index.d.ts",
42
+ "import": "./dist/push/index.js",
43
+ "default": "./dist/push/index.js"
44
+ },
45
+ "./push/sse": {
46
+ "types": "./dist/push/sse.d.ts",
47
+ "import": "./dist/push/sse.js",
48
+ "default": "./dist/push/sse.js"
49
+ },
40
50
  "./testing": {
41
51
  "types": "./dist/testing.d.ts",
42
52
  "import": "./dist/testing.js",
@@ -66,34 +76,34 @@
66
76
  },
67
77
  "dependencies": {
68
78
  "@swc/helpers": "0.5.23",
69
- "@entifix/authz": "0.13.0",
70
- "@entifix/business": "0.13.0",
71
- "@entifix/core": "0.13.0",
72
- "@entifix/tooling": "0.13.0"
79
+ "@entifix/authz": "0.14.0",
80
+ "@entifix/business": "0.14.0",
81
+ "@entifix/core": "0.14.0",
82
+ "@entifix/tooling": "0.14.0"
73
83
  },
74
84
  "devDependencies": {
75
- "@effect/opentelemetry": "4.0.6",
76
- "@effect/platform-node": "4.0.6",
85
+ "@effect/opentelemetry": "4.0.7",
86
+ "@effect/platform-node": "4.0.7",
77
87
  "@opentelemetry/api": "1.9.1",
78
88
  "@opentelemetry/context-async-hooks": "2.12.0",
79
89
  "@opentelemetry/exporter-metrics-otlp-http": "0.223.0",
80
90
  "@opentelemetry/exporter-trace-otlp-http": "0.223.0",
81
91
  "@opentelemetry/sdk-metrics": "2.12.0",
82
92
  "@opentelemetry/sdk-trace-base": "2.12.0",
83
- "effect": "4.0.6",
84
- "@entifix/rest": "0.13.0",
85
- "@entifix/testing-unit": "0.13.0"
93
+ "effect": "4.0.7",
94
+ "@entifix/rest": "0.14.0",
95
+ "@entifix/testing-unit": "0.14.0"
86
96
  },
87
97
  "peerDependencies": {
88
- "@effect/opentelemetry": "^4.0.6",
89
- "@effect/platform-node": "^4.0.6",
98
+ "@effect/opentelemetry": "^4.0.7",
99
+ "@effect/platform-node": "^4.0.7",
90
100
  "@opentelemetry/api": ">=1.9 <2",
91
101
  "@opentelemetry/context-async-hooks": ">=2.12 <3",
92
102
  "@opentelemetry/exporter-metrics-otlp-http": ">=0.223 <0.224",
93
103
  "@opentelemetry/exporter-trace-otlp-http": ">=0.223 <0.224",
94
104
  "@opentelemetry/sdk-metrics": ">=2.12 <3",
95
105
  "@opentelemetry/sdk-trace-base": ">=2.12 <3",
96
- "effect": "^4.0.6"
106
+ "effect": "^4.0.7"
97
107
  },
98
108
  "peerDependenciesMeta": {
99
109
  "@effect/opentelemetry": {
@@ -1,32 +0,0 @@
1
- import type { Permission } from '@entifix/authz';
2
- import type { RequestPrincipal } from '@entifix/business';
3
- import { Effect } from 'effect';
4
- /**
5
- * Guard a **tenant-plane** handler: authenticate, check the permission, and
6
- * require that the session names an organization.
7
- *
8
- * **This is the first of exactly two ways a request resolves the organization
9
- * it acts for, and the only *user-facing* one**.
10
- * The second is {@link requireServiceCrossing}: an explicit `organizationId`
11
- * presented with a service token *and* a narrow route permission, for a
12
- * platform-plane caller acting for an organization it was handed rather than one
13
- * it picked.
14
- *
15
- * There is no third path, no fallback and no operator branch. A request
16
- * satisfying neither guard never reaches a tenant handle at all, which is what
17
- * keeps the most sensitive capability in the system from being the *absence* of
18
- * a condition.
19
- *
20
- * The organization is handed to the handler so it can resolve its own storage
21
- * through a `TenantDatabaseResolver`. Resolution happens **inside the request**
22
- * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would
23
- * rebuild the pool per request.
24
- *
25
- * Here the value comes from the verified token and nowhere else. A route
26
- * parameter or a body field naming an organization would be caller-controlled,
27
- * which is the whole failure this guard exists to prevent — and is exactly why
28
- * the other path honours a caller-named organization only *after* the caller has
29
- * proved it is the fleet.
30
- */
31
- export declare const requireOrganization: (permission: Permission) => <A, E, R>(use: (organizationId: string, principal: RequestPrincipal) => Effect.Effect<A, E, R>) => Effect.Effect<import("effect/http/HttpServerResponse").HttpServerResponse | A, E, import("@entifix/business").TokenServiceTag | import("@entifix/authz").PolicyDecisionTag | import("effect/http/HttpServerRequest").HttpServerRequest | R>;
32
- //# sourceMappingURL=require-organization.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"require-organization.d.ts","sourceRoot":"","sources":["../../src/auth/require-organization.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAkBhC;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,eAAO,MAAM,mBAAmB,GAC7B,YAAY,UAAU,MACtB,CAAC,EAAE,CAAC,EAAE,CAAC,EACN,KAAK,CACH,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,gBAAgB,KACxB,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,gPAa1B,CAAC"}
@@ -1,52 +0,0 @@
1
- import { Effect } from 'effect';
2
- import { NoActiveOrganization, refuse } from './failures.js';
3
- import { requirePermission } from './require-principal.js';
4
- /**
5
- * `409` rather than `403`: the caller is authenticated and permitted, but the
6
- * session names no organization, so there is no storage to read. An operator
7
- * hits this by design — crossing into a tenant is an explicit, audited
8
- * act-as-organization re-mint, never a widening of the default —
9
- * and a member of several organizations hits it before choosing one. The `code`
10
- * is a key in the shared `errors` catalog, so a client renders "select an
11
- * organization" instead of "forbidden" — a claim a host has to check its
12
- * catalog against, because for a while it was simply false and the code
13
- * reached the browser as its own literal text.
14
- */ const noOrganization = refuse(new NoActiveOrganization());
15
- /**
16
- * Guard a **tenant-plane** handler: authenticate, check the permission, and
17
- * require that the session names an organization.
18
- *
19
- * **This is the first of exactly two ways a request resolves the organization
20
- * it acts for, and the only *user-facing* one**.
21
- * The second is {@link requireServiceCrossing}: an explicit `organizationId`
22
- * presented with a service token *and* a narrow route permission, for a
23
- * platform-plane caller acting for an organization it was handed rather than one
24
- * it picked.
25
- *
26
- * There is no third path, no fallback and no operator branch. A request
27
- * satisfying neither guard never reaches a tenant handle at all, which is what
28
- * keeps the most sensitive capability in the system from being the *absence* of
29
- * a condition.
30
- *
31
- * The organization is handed to the handler so it can resolve its own storage
32
- * through a `TenantDatabaseResolver`. Resolution happens **inside the request**
33
- * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would
34
- * rebuild the pool per request.
35
- *
36
- * Here the value comes from the verified token and nowhere else. A route
37
- * parameter or a body field naming an organization would be caller-controlled,
38
- * which is the whole failure this guard exists to prevent — and is exactly why
39
- * the other path honours a caller-named organization only *after* the caller has
40
- * proved it is the fleet.
41
- */ export const requireOrganization = (permission)=>(use)=>requirePermission(permission)((principal)=>// `Effect.gen` rather than a ternary: the two branches have different
42
- // success types, and a conditional expression would unify them against
43
- // the first one instead of widening. `requirePrincipal` yields for the
44
- // same reason.
45
- Effect.gen(function*() {
46
- if (principal.organizationId === undefined) {
47
- return yield* noOrganization;
48
- }
49
- return yield* use(principal.organizationId, principal);
50
- }));
51
-
52
- //# sourceMappingURL=require-organization.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/auth/require-organization.ts"],"sourcesContent":["import type { Permission } from '@entifix/authz';\nimport type { RequestPrincipal } from '@entifix/business';\nimport { Effect } from 'effect';\n\nimport { NoActiveOrganization, refuse } from './failures.js';\nimport { requirePermission } from './require-principal.js';\n\n/**\n * `409` rather than `403`: the caller is authenticated and permitted, but the\n * session names no organization, so there is no storage to read. An operator\n * hits this by design — crossing into a tenant is an explicit, audited\n * act-as-organization re-mint, never a widening of the default —\n * and a member of several organizations hits it before choosing one. The `code`\n * is a key in the shared `errors` catalog, so a client renders \"select an\n * organization\" instead of \"forbidden\" — a claim a host has to check its\n * catalog against, because for a while it was simply false and the code\n * reached the browser as its own literal text.\n */\nconst noOrganization = refuse(new NoActiveOrganization());\n\n/**\n * Guard a **tenant-plane** handler: authenticate, check the permission, and\n * require that the session names an organization.\n *\n * **This is the first of exactly two ways a request resolves the organization\n * it acts for, and the only *user-facing* one**.\n * The second is {@link requireServiceCrossing}: an explicit `organizationId`\n * presented with a service token *and* a narrow route permission, for a\n * platform-plane caller acting for an organization it was handed rather than one\n * it picked.\n *\n * There is no third path, no fallback and no operator branch. A request\n * satisfying neither guard never reaches a tenant handle at all, which is what\n * keeps the most sensitive capability in the system from being the *absence* of\n * a condition.\n *\n * The organization is handed to the handler so it can resolve its own storage\n * through a `TenantDatabaseResolver`. Resolution happens **inside the request**\n * — the connection pool is a boot-time `Layer`, and a per-request `Layer` would\n * rebuild the pool per request.\n *\n * Here the value comes from the verified token and nowhere else. A route\n * parameter or a body field naming an organization would be caller-controlled,\n * which is the whole failure this guard exists to prevent — and is exactly why\n * the other path honours a caller-named organization only *after* the caller has\n * proved it is the fleet.\n */\nexport const requireOrganization =\n (permission: Permission) =>\n <A, E, R>(\n use: (\n organizationId: string,\n principal: RequestPrincipal,\n ) => Effect.Effect<A, E, R>,\n ) =>\n requirePermission(permission)(principal =>\n // `Effect.gen` rather than a ternary: the two branches have different\n // success types, and a conditional expression would unify them against\n // the first one instead of widening. `requirePrincipal` yields for the\n // same reason.\n Effect.gen(function* () {\n if (principal.organizationId === undefined) {\n return yield* noOrganization;\n }\n return yield* use(principal.organizationId, principal);\n }),\n );\n"],"names":["Effect","NoActiveOrganization","refuse","requirePermission","noOrganization","requireOrganization","permission","use","principal","gen","organizationId","undefined"],"mappings":"AAEA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAASC,oBAAoB,EAAEC,MAAM,QAAQ,gBAAgB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAyB;AAE3D;;;;;;;;;;CAUC,GACD,MAAMC,iBAAiBF,OAAO,IAAID;AAElC;;;;;;;;;;;;;;;;;;;;;;;;;;CA0BC,GACD,OAAO,MAAMI,sBACX,CAACC,aACD,CACEC,MAKAJ,kBAAkBG,YAAYE,CAAAA,YAC5B,sEAAsE;YACtE,uEAAuE;YACvE,uEAAuE;YACvE,eAAe;YACfR,OAAOS,GAAG,CAAC;gBACT,IAAID,UAAUE,cAAc,KAAKC,WAAW;oBAC1C,OAAO,OAAOP;gBAChB;gBACA,OAAO,OAAOG,IAAIC,UAAUE,cAAc,EAAEF;YAC9C,IACA"}
@@ -1,44 +0,0 @@
1
- import type { NarrowingRules } from '@entifix/business';
2
- import { EntityFacetCounterFactoryTag } from '@entifix/business';
3
- import { type Entity, type EntityConstructor } from '@entifix/core';
4
- import { Effect } from 'effect';
5
- import { HttpRouter } from 'effect/http';
6
- import { type EntityReadScope, type EntityRouteContext, type EntityRouteGuard } from './entity-route-guard.js';
7
- import { type FailurePolicy } from './respond.js';
8
- export interface EntityFacetRoutesOptions<T extends Entity, R, G extends EntityRouteGuard = EntityRouteGuard> {
9
- /** Who may count: the guard the entity's `list` has, as a rule. */
10
- readonly guard: G;
11
- /** Defaults to `/api/<entity key>`; the route is `<basePath>/$facets`. */
12
- readonly basePath?: `/${string}`;
13
- /**
14
- * Narrows the counts to the records this caller may see — the same scope
15
- * the entity's `list` takes, so a count never reveals a record the list
16
- * would not.
17
- */
18
- readonly scope?: (context: EntityRouteContext) => Effect.Effect<EntityReadScope<T>, never, R>;
19
- /**
20
- * The same narrowing the entity's `list` takes, as resolver rules — so a
21
- * count equals the narrowed list. Replaces `scope`; naming both throws.
22
- */
23
- readonly narrowing?: NarrowingRules<T>;
24
- /** How the count's failures are answered and logged. */
25
- readonly policy?: FailurePolicy;
26
- }
27
- /**
28
- * `GET <base>/$facets` — how many of the entity's records hold each value of
29
- * each `facet` member, each under its own `rsql.<member>` filtering — bound to
30
- * storage through the host's {@link EntityFacetCounterFactoryTag}.
31
- *
32
- * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it
33
- * is the one route set that requires a counter: a host that mounts it without
34
- * binding one fails to compile, and a host that never counts binds nothing.
35
- *
36
- * The query is parsed against the entity's metadata, so only a `filterable`
37
- * member is counted and every malformed request is a `400`. A scope is
38
- * **conjoined into every facet's filtering**, never substituted, so no query
39
- * string can count past it; `'none'` answers every member empty.
40
- */
41
- export declare const makeEntityFacetRoutes: <T extends Entity, R = never, const G extends EntityRouteGuard = never>(entityConstructor: EntityConstructor<T>, options: EntityFacetRoutesOptions<T, R, G>) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", import("@entifix/business").TokenServiceTag> | HttpRouter.Request<"Requires", EntityFacetCounterFactoryTag> | HttpRouter.Request<"Requires", import("@entifix/authz").PolicyDecisionTag> | HttpRouter.Request.From<"Requires", Exclude<Exclude<R, HttpRouter.Provided>, HttpRouter.Provided>> | HttpRouter.Request.From<"Requires", Exclude<Exclude<G extends {
42
- readonly kind: "crossing";
43
- } ? import("@entifix/authz").ServiceCrossingPolicyTag | import("./index.js").ServiceCrossingTokenTag : never, HttpRouter.Provided>, HttpRouter.Provided>>>;
44
- //# sourceMappingURL=entity-facet-routes.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"entity-facet-routes.d.ts","sourceRoot":"","sources":["../src/entity-facet-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAa,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EACL,4BAA4B,EAG7B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,KAAK,MAAM,EACX,KAAK,iBAAiB,EAMvB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,EAAE,UAAU,EAAyC,MAAM,aAAa,CAAC;AAEhF,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAGtB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,cAAc,CAAC;AAGtB,MAAM,WAAW,wBAAwB,CACvC,CAAC,SAAS,MAAM,EAChB,CAAC,EACD,CAAC,SAAS,gBAAgB,GAAG,gBAAgB;IAE7C,mEAAmE;IACnE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAClB,0EAA0E;IAC1E,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,MAAM,EAAE,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,CACf,OAAO,EAAE,kBAAkB,KACxB,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IACjD;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC;IACvC,wDAAwD;IACxD,QAAQ,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC;CACjC;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAChC,CAAC,SAAS,MAAM,EAChB,CAAC,GAAG,KAAK,EAGT,KAAK,CAAC,CAAC,SAAS,gBAAgB,GAAG,KAAK,EAExC,mBAAmB,iBAAiB,CAAC,CAAC,CAAC,EACvC,SAAS,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;;0JAyF3C,CAAC"}
@@ -1,70 +0,0 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { EntityFacetCounterFactoryTag, EntityFacetCounterTag, facetCountsUCFactory } from '@entifix/business';
3
- import { envelopeEntityName, makeEntityFacetsEnvelope, parseFacetQueryParams } from '@entifix/core';
4
- import { Effect } from 'effect';
5
- import { HttpRouter, HttpServerRequest, HttpServerResponse } from 'effect/http';
6
- import { guardRoute } from './entity-route-guard.js';
7
- import { narrowingFor } from './narrowing.js';
8
- import { defaultFailurePolicy, respond } from './respond.js';
9
- import { legacyAnswer } from './route-responses.js';
10
- /**
11
- * `GET <base>/$facets` — how many of the entity's records hold each value of
12
- * each `facet` member, each under its own `rsql.<member>` filtering — bound to
13
- * storage through the host's {@link EntityFacetCounterFactoryTag}.
14
- *
15
- * A route of its own beside `makeEntityRoutes` rather than a sixth verb, so it
16
- * is the one route set that requires a counter: a host that mounts it without
17
- * binding one fails to compile, and a host that never counts binds nothing.
18
- *
19
- * The query is parsed against the entity's metadata, so only a `filterable`
20
- * member is counted and every malformed request is a `400`. A scope is
21
- * **conjoined into every facet's filtering**, never substituted, so no query
22
- * string can count past it; `'none'` answers every member empty.
23
- */ export const makeEntityFacetRoutes = (entityConstructor, options)=>{
24
- var _options_basePath, _options_policy;
25
- const base = (_options_basePath = options.basePath) != null ? _options_basePath : `/api/${envelopeEntityName(entityConstructor)}`;
26
- const readQueries = Effect.gen(function*() {
27
- const request = yield* HttpServerRequest.HttpServerRequest;
28
- const search = new URL(request.url, 'http://localhost').searchParams;
29
- return yield* Effect.try({
30
- try: ()=>parseFacetQueryParams(entityConstructor, search),
31
- catch: (error)=>error
32
- });
33
- });
34
- const narrowed = (queries, narrowing)=>narrowing === 'unscoped' ? queries : queries.map((query)=>{
35
- var _query_filtering;
36
- return _extends({}, query, {
37
- filtering: [
38
- ...(_query_filtering = query.filtering) != null ? _query_filtering : [],
39
- narrowing
40
- ]
41
- });
42
- });
43
- if (options.narrowing !== undefined && options.scope !== undefined) throw new Error(`the facet route for '${envelopeEntityName(entityConstructor)}' names both ` + '`narrowing` and `scope`; `narrowing` replaces `scope`, so name one.');
44
- /** A scope, as the narrowing this route applies. */ const asNarrowing = (scope)=>scope === 'all' ? 'unscoped' : scope === 'none' ? 'nothing' : scope.filter;
45
- const count = (context)=>Effect.gen(function*() {
46
- const queries = yield* readQueries;
47
- const narrowing = options.narrowing !== undefined && context.verified !== undefined ? narrowingFor(options.narrowing, context.verified) : asNarrowing(options.scope ? yield* options.scope(context) : 'all');
48
- if (narrowing === 'nothing') {
49
- // Still parsed: whether a query is well-formed must not depend on who
50
- // asked.
51
- const empty = Object.fromEntries(queries.map(({ member })=>[
52
- member,
53
- []
54
- ]));
55
- return yield* HttpServerResponse.json(makeEntityFacetsEnvelope(entityConstructor, empty));
56
- }
57
- const factory = yield* EntityFacetCounterFactoryTag;
58
- const counter = yield* factory.for(entityConstructor, _extends({}, context.organizationId === undefined ? {} : {
59
- organizationId: context.organizationId
60
- }));
61
- const counts = yield* facetCountsUCFactory(narrowed(queries, narrowing)).pipe(Effect.provideService(EntityFacetCounterTag, counter));
62
- return yield* HttpServerResponse.json(makeEntityFacetsEnvelope(entityConstructor, counts));
63
- }).pipe(Effect.catch(legacyAnswer('invalidQuery')));
64
- const handler = respond(guardRoute(entityConstructor, options.guard, 'read', count), (_options_policy = options.policy) != null ? _options_policy : defaultFailurePolicy);
65
- return HttpRouter.addAll([
66
- HttpRouter.route('GET', `${base}/$facets`, handler)
67
- ]);
68
- };
69
-
70
- //# sourceMappingURL=entity-facet-routes.js.map