@entifix/service-shell 0.17.0 → 0.18.1
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.
- package/dist/push/sse.d.ts.map +1 -1
- package/dist/push/sse.js +13 -1
- package/dist/push/sse.js.map +1 -1
- package/package.json +7 -7
package/dist/push/sse.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/push/sse.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../src/push/sse.ts"],"names":[],"mappings":"AAEA,OAAO,EAGL,QAAQ,EACR,MAAM,EAEN,MAAM,EAGN,KAAK,KAAK,EAEX,MAAM,QAAQ,CAAC;AAChB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EACL,KAAK,cAAc,EAEnB,aAAa,EACd,MAAM,kBAAkB,CAAC;AAE1B;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,mBAAuB,CAAC;AAEnD,MAAM,WAAW,YAAY;IAC3B;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,EAAE;QAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACjE,0EAA0E;IAC1E,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,iEAAiE;IACjE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;CAChC;AAED,MAAM,WAAW,iBAAkB,SAAQ,cAAc;IACvD;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,OAAO;IACtB,oDAAoD;IACpD,QAAQ,CAAC,OAAO,EAAE,CAChB,UAAU,EAAE,iBAAiB,KAC1B,kBAAkB,CAAC,kBAAkB,CAAC;CAC5C;AAED,6CAA6C;AAC7C,eAAO,MAAM,eAAe,sBAE1B,CAAC;AACH,eAAO,MAAM,UAAU,wBAErB,CAAC;AACH,eAAO,MAAM,UAAU,wBAErB,CAAC;AACH,eAAO,MAAM,WAAW,wBAEtB,CAAC;AACH,eAAO,MAAM,UAAU,wBAErB,CAAC;AACH,eAAO,MAAM,eAAe,wBAG3B,CAAC;AA6BF;;;;;;;GAOG;AACH,eAAO,MAAM,WAAW,GAAI,qDAKzB,YAAY,KAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,GAAG,KAAK,CAAC,KAAK,CA+JvE,CAAC"}
|
package/dist/push/sse.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { ShutdownRegistryTag } from '@entifix/business';
|
|
1
2
|
import { encodeEvent } from '@entifix/core';
|
|
2
|
-
import { Clock, Deferred, Duration, Effect, Exit, Metric, Ref, Stream } from 'effect';
|
|
3
|
+
import { Clock, Deferred, Duration, Effect, Exit, Metric, Option, Ref, Stream } from 'effect';
|
|
3
4
|
import { HttpServerResponse } from 'effect/http';
|
|
4
5
|
import { ServerPushTag } from './server-push.js';
|
|
5
6
|
/**
|
|
@@ -63,6 +64,17 @@ const frameOf = (message)=>message._tag === 'event' ? eventFrame(message.event,
|
|
|
63
64
|
discard: true
|
|
64
65
|
})), Effect.timeoutOption(Duration.millis(drainWindowMs)));
|
|
65
66
|
});
|
|
67
|
+
// …and before that, on the signal itself. The server's close waits for
|
|
68
|
+
// every open response and a stream never finishes by itself, so a drain
|
|
69
|
+
// left to the finalizer above ran only after the server had given up on
|
|
70
|
+
// the streams, twenty seconds on, and cut them without the `retry:` that
|
|
71
|
+
// spreads their reconnect (#492). Told here, each one ends at once.
|
|
72
|
+
const shutdown = yield* Effect.serviceOption(ShutdownRegistryTag);
|
|
73
|
+
if (Option.isSome(shutdown)) {
|
|
74
|
+
yield* Effect.forkScoped(shutdown.value.whenTerminating.pipe(Effect.andThen(Effect.suspend(()=>Effect.forEach(Array.from(live.keys()), (drain)=>Deferred.succeed(drain, undefined), {
|
|
75
|
+
discard: true
|
|
76
|
+
})))));
|
|
77
|
+
}
|
|
66
78
|
const frames = (connection)=>Stream.unwrap(Effect.gen(function*() {
|
|
67
79
|
const drain = yield* Deferred.make();
|
|
68
80
|
const done = yield* Deferred.make();
|
package/dist/push/sse.js.map
CHANGED
|
@@ -1 +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;IACpEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMI,cAAcb,OAAOW,OAAO,CAAC,8BAA8B;IACtEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMK,aAAad,OAAOW,OAAO,CAAC,6BAA6B;IACpEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMM,kBAAkBf,OAAOW,OAAO,CAC3C,kCACA;IAAEF,aAAa;AAAoD,GACnE;AAEF,MAAMO,UAAU,IAAIC;AAEpB,4EAA4E;AAC5E,6DAA6D;AAC7D,MAAMC,aAAa,CACjBC,OACAC,SAEAtB,OAAOuB,IAAI,CAAC3B,YAAYyB,QAAQG,IAAI,CAClCxB,OAAOyB,OAAO,CAACC,CAAAA,UACbzB,KAAK0B,SAAS,CAACD,WACX1B,OAAO4B,OAAO,CACZ,CAA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AO,CAACmD,SAASgB,CAAAA,SAAUzF,IAAIsE,GAAG,CAACH,QAAQsB;gBAGpD,MAAMC,OAAOzF,OAAOgE,MAAM,CACxBpE,OAAO8F,GAAG,CAAC3F,IAAI4F,GAAG,CAACzB,SAASsB,CAAAA;oBAC1B,OAAQA;wBACN,KAAK;4BACH,OAAOxF,OAAO4F,UAAU,CACtBhG,OAAOkC,EAAE,CACPhC,OAAOiC,MAAM,CAACnB,YAAY,IAC1B;wBAGN,KAAK;4BACH,OAAOZ,OAAO4F,UAAU,CACtBhG,OAAOkC,EAAE,CACPhC,OAAOiC,MAAM,CAACpB,aAAa,IAC3B,CAAC,OAAO,EAAEmC,QAAQ,IAAI,CAAC;wBAG7B;4BACE,OAAO9C,OAAO6F,KAAK;oBACvB;gBACF;gBAGF,OAAO7F,OAAO8F,QAAQ,CACpB9F,OAAOmF,MAAM,CAACG,SAASG,OACvB7F,OAAOmG,OAAO,CAAC;oBACbnD,KAAKoD,MAAM,CAACzC;oBACZ,OAAO3D,OAAOqG,GAAG,CAAC;wBAChBnG,OAAOiC,MAAM,CAACrB,YAAY;wBAC1BZ,OAAOiC,MAAM,CAAC1B,iBAAiBuC,KAAK0B,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"}
|
|
1
|
+
{"version":3,"sources":["../../src/push/sse.ts"],"sourcesContent":["import { ShutdownRegistryTag } from '@entifix/business';\nimport { type DomainEvent, encodeEvent } from '@entifix/core';\nimport {\n Clock,\n Deferred,\n Duration,\n Effect,\n Exit,\n Metric,\n Option,\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 // …and before that, on the signal itself. The server's close waits for\n // every open response and a stream never finishes by itself, so a drain\n // left to the finalizer above ran only after the server had given up on\n // the streams, twenty seconds on, and cut them without the `retry:` that\n // spreads their reconnect (#492). Told here, each one ends at once.\n const shutdown = yield* Effect.serviceOption(ShutdownRegistryTag);\n if (Option.isSome(shutdown)) {\n yield* Effect.forkScoped(\n shutdown.value.whenTerminating.pipe(\n Effect.andThen(\n Effect.suspend(() =>\n Effect.forEach(\n Array.from(live.keys()),\n drain => Deferred.succeed(drain, undefined),\n { discard: true },\n ),\n ),\n ),\n ),\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":["ShutdownRegistryTag","encodeEvent","Clock","Deferred","Duration","Effect","Exit","Metric","Option","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","shutdown","serviceOption","isSome","forkScoped","whenTerminating","suspend","keys","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","delete","all","respond","stream","encode","contentType","headers"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,oBAAoB;AACxD,SAA2BC,WAAW,QAAQ,gBAAgB;AAC9D,SACEC,KAAK,EACLC,QAAQ,EACRC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,MAAM,EACNC,GAAG,EAEHC,MAAM,QACD,SAAS;AAChB,SAASC,kBAAkB,QAAQ,cAAc;AAEjD,SAGEC,aAAa,QACR,mBAAmB;AAE1B;;;;;;;CAOC,GACD,OAAO,MAAMC,iBAAiBT,SAASU,OAAO,CAAC,IAAI;AAqCnD,2CAA2C,GAC3C,OAAO,MAAMC,kBAAkBR,OAAOS,KAAK,CAAC,4BAA4B;IACtEC,aAAa;AACf,GAAG;AACH,OAAO,MAAMC,aAAaX,OAAOY,OAAO,CAAC,6BAA6B;IACpEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMG,aAAab,OAAOY,OAAO,CAAC,6BAA6B;IACpEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMI,cAAcd,OAAOY,OAAO,CAAC,8BAA8B;IACtEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMK,aAAaf,OAAOY,OAAO,CAAC,6BAA6B;IACpEF,aAAa;AACf,GAAG;AACH,OAAO,MAAMM,kBAAkBhB,OAAOY,OAAO,CAC3C,kCACA;IAAEF,aAAa;AAAoD,GACnE;AAEF,MAAMO,UAAU,IAAIC;AAEpB,4EAA4E;AAC5E,6DAA6D;AAC7D,MAAMC,aAAa,CACjBC,OACAC,SAEAvB,OAAOwB,IAAI,CAAC5B,YAAY0B,QAAQG,IAAI,CAClCzB,OAAO0B,OAAO,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M,CAAC1B,iBAAiBuC,KAAKiC,IAAI;wBACxCpF,SAAS+B,OAAO,CAACkC,MAAM1B;qBACxB;gBACH;YAEJ;QAGJ,OAAO;YACLwE,SAASlC,CAAAA,aACPrE,mBAAmBwG,MAAM,CACvBzG,OAAOiG,GAAG,CAAC5B,OAAOC,aAAagB,CAAAA,QAASxE,QAAQ4F,MAAM,CAACpB,SACvD;oBACEqB,aAAa;oBACbC,SAAS;wBACP,gEAAgE;wBAChE,aAAa;wBACb,iBAAiB;wBACjBtC,YAAY;wBACZ,4DAA4D;wBAC5D,2BAA2B;wBAC3B,qBAAqB;oBACvB;gBACF;QAEN;IACF,GAAG"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@entifix/service-shell",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.1",
|
|
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": {
|
|
@@ -76,10 +76,10 @@
|
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
78
|
"@swc/helpers": "0.5.23",
|
|
79
|
-
"@entifix/authz": "0.
|
|
80
|
-
"@entifix/business": "0.
|
|
81
|
-
"@entifix/core": "0.
|
|
82
|
-
"@entifix/tooling": "0.
|
|
79
|
+
"@entifix/authz": "0.18.1",
|
|
80
|
+
"@entifix/business": "0.18.1",
|
|
81
|
+
"@entifix/core": "0.18.1",
|
|
82
|
+
"@entifix/tooling": "0.18.1"
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
85
|
"@effect/opentelemetry": "4.0.7",
|
|
@@ -91,8 +91,8 @@
|
|
|
91
91
|
"@opentelemetry/sdk-metrics": "2.12.0",
|
|
92
92
|
"@opentelemetry/sdk-trace-base": "2.12.0",
|
|
93
93
|
"effect": "4.0.7",
|
|
94
|
-
"@entifix/rest": "0.
|
|
95
|
-
"@entifix/testing-unit": "0.
|
|
94
|
+
"@entifix/rest": "0.18.1",
|
|
95
|
+
"@entifix/testing-unit": "0.18.1"
|
|
96
96
|
},
|
|
97
97
|
"peerDependencies": {
|
|
98
98
|
"@effect/opentelemetry": "^4.0.7",
|