@streamsy/core 0.2.1 → 0.5.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.
@@ -0,0 +1,797 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
+ import { A as StreamsReader, F as isValid, Q as StreamId, f as AppendResult, j as StreamsWriter, k as isProtocolError, p as CreateResult } from "./streamsy-DJMArv09.js";
3
+ import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
4
+ import { Array, Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Record, Ref, Schedule, Stream } from "effect";
5
+ import { HttpServerRequest, HttpServerResponse } from "effect/http";
6
+ // src/http/responses.ts
7
+ var responses_exports = /* @__PURE__ */ __exportAll({
8
+ badRequest: () => badRequest$1,
9
+ cacheControlForVisibility: () => cacheControlForVisibility,
10
+ conflict: () => conflict$1,
11
+ empty: () => empty,
12
+ fromWeb: () => fromWeb,
13
+ gone: () => gone,
14
+ internalError: () => internalError,
15
+ invalidJson: () => invalidJson,
16
+ methodNotAllowed: () => methodNotAllowed,
17
+ noStore: () => noStore,
18
+ notFound: () => notFound,
19
+ payloadTooLarge: () => payloadTooLarge,
20
+ text: () => text
21
+ });
22
+ /**
23
+ * Response factory for the HTTP layer.
24
+ *
25
+ * Centralizes security headers and the small set of plain text/empty
26
+ * responses that recur across handlers (400/404/410/413/etc.). Method-
27
+ * specific result mapping (append producer-state shaping, create conflict
28
+ * mapping, catch-up ETag responses) stays in the owning service.
29
+ */
30
+ const CACHE_CONTROL_NO_STORE = "no-store";
31
+ const CACHE_CONTROL_PUBLIC = "public, max-age=60, stale-while-revalidate=300";
32
+ const CACHE_CONTROL_PRIVATE = "private, max-age=60, stale-while-revalidate=300";
33
+ function cacheControlForVisibility(visibility) {
34
+ return visibility === "public" ? CACHE_CONTROL_PUBLIC : CACHE_CONTROL_PRIVATE;
35
+ }
36
+ function noStore(response) {
37
+ const headers = new Headers(response.headers);
38
+ headers.set("cache-control", CACHE_CONTROL_NO_STORE);
39
+ return new Response(response.body, {
40
+ status: response.status,
41
+ statusText: response.statusText,
42
+ headers
43
+ });
44
+ }
45
+ function text(message, status, headers) {
46
+ return new Response(message, {
47
+ status,
48
+ headers
49
+ });
50
+ }
51
+ function empty(status, headers) {
52
+ return new Response(null, {
53
+ status,
54
+ headers
55
+ });
56
+ }
57
+ function badRequest$1(message) {
58
+ return new Response(message, { status: 400 });
59
+ }
60
+ function notFound(message = "Stream not found") {
61
+ return new Response(message, { status: 404 });
62
+ }
63
+ function gone(message = "Stream is soft-deleted") {
64
+ return new Response(message, { status: 410 });
65
+ }
66
+ function conflict$1(message, headers) {
67
+ return new Response(message, {
68
+ status: 409,
69
+ headers
70
+ });
71
+ }
72
+ function payloadTooLarge() {
73
+ return new Response("Payload too large", { status: 413 });
74
+ }
75
+ function invalidJson() {
76
+ return new Response("Invalid JSON", { status: 400 });
77
+ }
78
+ function methodNotAllowed() {
79
+ return new Response("Method not allowed", { status: 405 });
80
+ }
81
+ function internalError() {
82
+ return new Response("Internal server error", { status: 500 });
83
+ }
84
+ /** Preserve the protocol's frozen byte and content-type conventions at one boundary. */
85
+ function fromWeb(response) {
86
+ return HttpServerResponse.raw(response, {
87
+ status: response.status,
88
+ statusText: response.statusText,
89
+ headers: Record.fromEntries(response.headers)
90
+ });
91
+ }
92
+ // src/http/security-headers.ts
93
+ /** Shared protocol and host security headers. */
94
+ const securityHeaders = Object.freeze({
95
+ "x-content-type-options": "nosniff",
96
+ "cross-origin-resource-policy": "cross-origin"
97
+ });
98
+ // src/http/stream-path-service.ts
99
+ /** Prefix helpers shared by protocol and host routers. */
100
+ const streamPath = (pathPrefix = "/") => {
101
+ const prefix = pathPrefix.endsWith("/") ? pathPrefix : `${pathPrefix}/`;
102
+ const regex = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
103
+ const strip = (pathname) => pathname.replace(regex, "");
104
+ return {
105
+ requiredPathPattern: () => `${prefix}{path}`,
106
+ strip,
107
+ canonicalizeForkSource: (source) => regex.test(source) ? strip(source) : source.replace(/^\//, "")
108
+ };
109
+ };
110
+ // src/http/request-body-reader.ts
111
+ const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody")(function* (request) {
112
+ return yield* request.arrayBuffer.pipe(Effect.map((data) => data.byteLength > maxMessageSize ? {
113
+ ok: false,
114
+ response: payloadTooLarge()
115
+ } : {
116
+ ok: true,
117
+ data: new Uint8Array(data),
118
+ byteLength: data.byteLength
119
+ }), Effect.orElseSucceed(() => ({
120
+ ok: false,
121
+ response: payloadTooLarge()
122
+ })));
123
+ }) });
124
+ // src/http/request-body-discard.ts
125
+ /**
126
+ * Consumes an unread request body before an early rejection.
127
+ *
128
+ * An HTTP/1.1 host can only reuse a connection when the request body was read
129
+ * to its end. A body that is dropped or cancelled counts as unread, so the host
130
+ * closes the connection after the response, and a client that reuses the pooled
131
+ * connection at that moment sees a socket close. Under workerd this showed up
132
+ * as the conformance case that sends four rejected appends back to back.
133
+ *
134
+ * The body is read through the Effect stream and discarded chunk by chunk, so
135
+ * nothing is buffered. An absent body fails the stream and a locked body
136
+ * defects on `getReader`; both are ignored because the rejection response is
137
+ * the outcome that matters.
138
+ */
139
+ const discardRequestBody = (request) => Stream.runDrain(request.stream).pipe(Effect.ignoreCause);
140
+ // src/http/create.ts
141
+ const responses$4 = responses_exports;
142
+ function parseHeaders$1(request, path) {
143
+ const rawContentType = request.headers.get("content-type");
144
+ const ttlHeader = request.headers.get("stream-ttl");
145
+ const expiresAtHeader = request.headers.get("stream-expires-at");
146
+ const forkedFromHeader = request.headers.get("stream-forked-from");
147
+ const forkOffsetHeader = request.headers.get("stream-fork-offset");
148
+ const forkSubOffsetHeader = request.headers.get("stream-fork-sub-offset");
149
+ if (ttlHeader && !/^(0|[1-9]\d*)$/.test(ttlHeader)) return {
150
+ ok: false,
151
+ response: responses$4.badRequest("Invalid Stream-TTL format")
152
+ };
153
+ if (ttlHeader && expiresAtHeader) return {
154
+ ok: false,
155
+ response: responses$4.badRequest("Cannot specify both Stream-TTL and Stream-Expires-At")
156
+ };
157
+ if (expiresAtHeader && Option.isNone(DateTime.make(expiresAtHeader))) return {
158
+ ok: false,
159
+ response: responses$4.badRequest("Invalid Stream-Expires-At format")
160
+ };
161
+ if (forkOffsetHeader && !forkedFromHeader) return {
162
+ ok: false,
163
+ response: responses$4.badRequest("Stream-Fork-Offset requires Stream-Forked-From")
164
+ };
165
+ if (forkSubOffsetHeader !== null) {
166
+ if (!forkedFromHeader) return {
167
+ ok: false,
168
+ response: responses$4.badRequest("Stream-Fork-Sub-Offset requires Stream-Forked-From")
169
+ };
170
+ if (!/^(0|[1-9]\d*)$/.test(forkSubOffsetHeader)) return {
171
+ ok: false,
172
+ response: responses$4.badRequest("Invalid Stream-Fork-Sub-Offset format")
173
+ };
174
+ if (parseInt(forkSubOffsetHeader, 10) > 0 && !forkOffsetHeader) return {
175
+ ok: false,
176
+ response: responses$4.badRequest("Stream-Fork-Sub-Offset greater than zero requires Stream-Fork-Offset")
177
+ };
178
+ }
179
+ return {
180
+ ok: true,
181
+ contentType: rawContentType ?? (!!forkedFromHeader ? void 0 : "application/octet-stream"),
182
+ ttlSeconds: ttlHeader ? parseInt(ttlHeader, 10) : void 0,
183
+ expiresAt: expiresAtHeader ?? void 0,
184
+ wantClosed: request.headers.get("stream-closed")?.toLowerCase() === "true",
185
+ forkedFromStreamId: forkedFromHeader ? path.canonicalizeForkSource(forkedFromHeader) : void 0,
186
+ forkOffset: forkOffsetHeader ?? void 0,
187
+ forkSubOffset: forkSubOffsetHeader !== null ? parseInt(forkSubOffsetHeader, 10) : void 0
188
+ };
189
+ }
190
+ function normalizeInitialData(data, contentType) {
191
+ let effectiveInitialData = data.byteLength > 0 ? data : void 0;
192
+ if (effectiveInitialData && contentType?.toLowerCase().startsWith("application/json")) try {
193
+ const parsed = JSON.parse(new TextDecoder().decode(effectiveInitialData));
194
+ if (Array.isArray(parsed) && parsed.length === 0) effectiveInitialData = void 0;
195
+ } catch (error) {
196
+ if (error instanceof SyntaxError) return {
197
+ ok: false,
198
+ response: responses$4.invalidJson()
199
+ };
200
+ throw error;
201
+ }
202
+ return {
203
+ ok: true,
204
+ initialData: effectiveInitialData
205
+ };
206
+ }
207
+ function toResponse$1(result, location) {
208
+ const created = CreateResult.$is("Created")(result);
209
+ const headers = new Headers({
210
+ "content-type": result.contentType,
211
+ "stream-next-offset": result.nextOffset
212
+ });
213
+ if (created) headers.set("location", location);
214
+ if (result.closed) headers.set("stream-closed", "true");
215
+ return responses$4.empty(created ? 201 : 200, headers);
216
+ }
217
+ // src/http/producer-header-parser.ts
218
+ var producer_header_parser_exports = /* @__PURE__ */ __exportAll({ parse: () => parse });
219
+ const MAX_SAFE_PRODUCER_INT = Number.MAX_SAFE_INTEGER;
220
+ const NON_NEGATIVE_INT_RE = /^(0|[1-9]\d*)$/;
221
+ function parse(request) {
222
+ const id = request.headers.get("producer-id");
223
+ const epoch = request.headers.get("producer-epoch");
224
+ const seq = request.headers.get("producer-seq");
225
+ const present = Array.filter([
226
+ id,
227
+ epoch,
228
+ seq
229
+ ], (v) => v !== null).length;
230
+ if (present === 0) return { kind: "absent" };
231
+ if (present !== 3 || id === null || epoch === null || seq === null) return { kind: "invalid" };
232
+ if (id.length === 0) return { kind: "invalid" };
233
+ const parsedEpoch = parseInt$1(epoch);
234
+ const parsedSeq = parseInt$1(seq);
235
+ if (parsedEpoch === null || parsedSeq === null) return { kind: "invalid" };
236
+ return {
237
+ kind: "ok",
238
+ producer: {
239
+ producerId: id,
240
+ producerEpoch: parsedEpoch,
241
+ producerSeq: parsedSeq
242
+ }
243
+ };
244
+ }
245
+ function parseInt$1(raw) {
246
+ if (!NON_NEGATIVE_INT_RE.test(raw)) return null;
247
+ const n = Number(raw);
248
+ if (!Number.isFinite(n) || n > MAX_SAFE_PRODUCER_INT) return null;
249
+ return n;
250
+ }
251
+ // src/http/append.ts
252
+ const producerParser = producer_header_parser_exports;
253
+ const responses$3 = responses_exports;
254
+ function parseHeaders(request) {
255
+ const producerHeaders = producerParser.parse(request);
256
+ if (producerHeaders.kind === "invalid") return {
257
+ ok: false,
258
+ response: responses$3.badRequest("Invalid producer headers")
259
+ };
260
+ const expectedOffset = request.headers.get("stream-expected-offset") ?? void 0;
261
+ if (expectedOffset !== void 0 && !isValid(expectedOffset)) return {
262
+ ok: false,
263
+ response: responses$3.badRequest("Invalid expected offset")
264
+ };
265
+ return {
266
+ ok: true,
267
+ contentType: request.headers.get("content-type"),
268
+ seq: request.headers.get("stream-seq") ?? void 0,
269
+ wantClose: request.headers.get("stream-closed")?.toLowerCase() === "true",
270
+ expectedOffset,
271
+ producerHeaders
272
+ };
273
+ }
274
+ function toResponse(result, producerHeaders, isEmpty) {
275
+ return AppendResult.$match(result, {
276
+ Duplicate: (duplicate) => {
277
+ const headers = new Headers({
278
+ "stream-next-offset": duplicate.offset,
279
+ "producer-epoch": String(duplicate.producerEpoch),
280
+ "producer-seq": String(duplicate.producerSeq)
281
+ });
282
+ if (duplicate.closed) headers.set("stream-closed", "true");
283
+ return responses$3.empty(204, headers);
284
+ },
285
+ Appended: (appended) => {
286
+ const headers = new Headers({ "stream-next-offset": appended.offset });
287
+ if (appended.closed) headers.set("stream-closed", "true");
288
+ if (appended.producerEpoch !== void 0) headers.set("producer-epoch", String(appended.producerEpoch));
289
+ if (appended.producerSeq !== void 0) headers.set("producer-seq", String(appended.producerSeq));
290
+ return responses$3.empty(producerHeaders.kind === "ok" && !isEmpty ? 200 : 204, headers);
291
+ }
292
+ });
293
+ }
294
+ // src/http/etag-builder.ts
295
+ var etag_builder_exports = /* @__PURE__ */ __exportAll({ forCatchUp: () => forCatchUp });
296
+ function forCatchUp(pathname, startOffset, nextOffset, closed) {
297
+ const closedSuffix = closed ? ":c" : "";
298
+ return `"${btoa(pathname)}:${startOffset}:${nextOffset}${closedSuffix}"`;
299
+ }
300
+ // src/http/bytes.ts
301
+ /**
302
+ * Cross-runtime byte normalization for HTTP bodies.
303
+ *
304
+ * `Uint8Array.prototype.buffer` is typed `ArrayBufferLike`, which also admits a
305
+ * `SharedArrayBuffer`. `BodyInit` accepts only a real `ArrayBuffer`, and a view
306
+ * may cover just part of its backing buffer, so neither the buffer identity nor
307
+ * its element type can be assumed. These helpers establish both with runtime
308
+ * checks instead of an assertion.
309
+ */
310
+ /**
311
+ * Returns an `ArrayBuffer` holding exactly the bytes of `view`.
312
+ *
313
+ * When the view already owns its whole backing `ArrayBuffer` the buffer is
314
+ * returned as-is (no copy), which is the common case for freshly concatenated
315
+ * bodies. Otherwise — a partial view, or a `SharedArrayBuffer` backing — the
316
+ * bytes are copied into a fresh, exactly sized `ArrayBuffer`.
317
+ */
318
+ function toArrayBuffer(view) {
319
+ const { buffer, byteOffset, byteLength } = view;
320
+ if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) return buffer;
321
+ const copy = new ArrayBuffer(byteLength);
322
+ new Uint8Array(copy).set(view);
323
+ return copy;
324
+ }
325
+ function isReferenceValue(candidate) {
326
+ return candidate !== null && Object(candidate) === candidate;
327
+ }
328
+ function isCallable(candidate) {
329
+ if (!isReferenceValue(candidate)) return false;
330
+ try {
331
+ Function.prototype.toString.call(candidate);
332
+ return true;
333
+ } catch {
334
+ return false;
335
+ }
336
+ }
337
+ function isNodeBufferGlobal(candidate) {
338
+ return isReferenceValue(candidate) && isCallable(candidate) && "from" in candidate && isCallable(candidate.from);
339
+ }
340
+ function parseBase64Encoder(result) {
341
+ const { value } = result;
342
+ if (!isReferenceValue(value)) return void 0;
343
+ let owner = value;
344
+ while (owner !== null) {
345
+ const descriptor = Object.getOwnPropertyDescriptor(owner, "toString");
346
+ if (descriptor !== void 0) {
347
+ const method = "value" in descriptor ? descriptor.value : descriptor.get?.call(value);
348
+ return isCallable(method) ? (encoding) => method.call(value, encoding) : void 0;
349
+ }
350
+ owner = Object.getPrototypeOf(owner);
351
+ }
352
+ }
353
+ function nodeBufferBase64(bytes) {
354
+ if (!("Buffer" in globalThis)) return void 0;
355
+ const bufferGlobal = globalThis.Buffer;
356
+ if (!isReferenceValue(bufferGlobal) || !isNodeBufferGlobal(bufferGlobal)) return void 0;
357
+ const encode = parseBase64Encoder({ value: bufferGlobal.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) });
358
+ if (encode === void 0) return void 0;
359
+ const encoded = encode("base64");
360
+ if (encoded === null || encoded === void 0 || isReferenceValue(encoded) || Object.getPrototypeOf(Object(encoded)) !== String.prototype) return;
361
+ return String.prototype.valueOf.call(encoded);
362
+ }
363
+ // src/http/message-body-codec.ts
364
+ var message_body_codec_exports = /* @__PURE__ */ __exportAll({
365
+ bytesToBase64: () => bytesToBase64,
366
+ concatBytes: () => concatBytes,
367
+ emptyBodyForContentType: () => emptyBodyForContentType,
368
+ encodeHttpBody: () => encodeHttpBody
369
+ });
370
+ const decoder$1 = new TextDecoder();
371
+ function encodeHttpBody(messages, contentType) {
372
+ const lower = contentType.toLowerCase();
373
+ if (lower.startsWith("application/json")) {
374
+ const items = Array.map(messages, (msg) => decoder$1.decode(msg.data));
375
+ return `[${Array.join(items, ",")}]`;
376
+ }
377
+ if (lower.startsWith("text/")) return Array.join(Array.map(messages, (msg) => decoder$1.decode(msg.data)), "");
378
+ return toArrayBuffer(concatBytes(messages));
379
+ }
380
+ function emptyBodyForContentType(contentType) {
381
+ return contentType.toLowerCase().startsWith("application/json") ? "[]" : "";
382
+ }
383
+ function concatBytes(messages) {
384
+ const totalLength = Array.reduce(messages, 0, (acc, msg) => acc + msg.data.length);
385
+ const combined = new Uint8Array(totalLength);
386
+ let pos = 0;
387
+ for (const msg of messages) {
388
+ combined.set(msg.data, pos);
389
+ pos += msg.data.length;
390
+ }
391
+ return combined;
392
+ }
393
+ function bytesToBase64(bytes) {
394
+ const viaBuffer = nodeBufferBase64(bytes);
395
+ if (viaBuffer !== void 0) return viaBuffer;
396
+ let binary = "";
397
+ const chunk = 32768;
398
+ for (let i = 0; i < bytes.length; i += chunk) binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
399
+ return btoa(binary);
400
+ }
401
+ // src/http/read-query-parser.ts
402
+ const readQueryParser = (isValidOffset) => ({ parse(url) {
403
+ const offset = url.searchParams.get("offset") ?? void 0;
404
+ const liveParam = url.searchParams.get("live");
405
+ const cursor = url.searchParams.get("cursor") ?? void 0;
406
+ const live = liveParam === "long-poll" || liveParam === "sse" ? liveParam : void 0;
407
+ if (offset !== void 0 && offset !== "-1" && offset !== "now" && !isValidOffset(offset)) return {
408
+ ok: false,
409
+ response: new Response("Invalid offset format", { status: 400 })
410
+ };
411
+ if (cursor !== void 0 && (!/^(0|[1-9]\d*)$/.test(cursor) || !Number.isSafeInteger(Number(cursor)) || Number(cursor) > Number.MAX_SAFE_INTEGER - 180)) return {
412
+ ok: false,
413
+ response: new Response("Invalid cursor", { status: 400 })
414
+ };
415
+ return {
416
+ ok: true,
417
+ offset,
418
+ live,
419
+ cursor
420
+ };
421
+ } });
422
+ // src/http/sse-event-encoder.ts
423
+ var sse_event_encoder_exports = /* @__PURE__ */ __exportAll({
424
+ controlEvent: () => controlEvent,
425
+ dataEvent: () => dataEvent
426
+ });
427
+ const encoder = new TextEncoder();
428
+ const decoder = new TextDecoder();
429
+ function dataEvent(messages, options) {
430
+ const chunks = [encode("event: data\n")];
431
+ if (options.useBase64) {
432
+ const combined = concatBytes(messages);
433
+ chunks.push(encode(`data:${bytesToBase64(combined)}\n`));
434
+ } else if (options.isJson) {
435
+ const items = Array.map(messages, (msg) => decoder.decode(msg.data));
436
+ chunks.push(encode("data:[\n"));
437
+ for (let i = 0; i < items.length; i++) {
438
+ const suffix = i < items.length - 1 ? "," : "";
439
+ chunks.push(encode(`data:${items[i]}${suffix}\n`));
440
+ }
441
+ chunks.push(encode("data:]\n"));
442
+ } else {
443
+ const text = Array.join(Array.map(messages, (msg) => decoder.decode(msg.data)), "");
444
+ for (const line of text.split(/\r\n|\r|\n/)) chunks.push(encode(`data:${line}\n`));
445
+ }
446
+ chunks.push(encode("\n"));
447
+ return chunks;
448
+ }
449
+ function controlEvent(data) {
450
+ return encode(`event: control\ndata:${JSON.stringify(data)}\n\n`);
451
+ }
452
+ function encode(value) {
453
+ return encoder.encode(value);
454
+ }
455
+ // src/http/sse.ts
456
+ const events = sse_event_encoder_exports;
457
+ /** Each connection's deadline is `deadlineMs` scaled by a factor from 0.9 to 1.1. */
458
+ const DEADLINE_JITTER = .1;
459
+ /**
460
+ * Spread `deadlineMs` by up to `DEADLINE_JITTER` either way, from one draw `r`
461
+ * in [0, 1). Connections opened together then do not all close together.
462
+ */
463
+ function jitterDeadline(deadlineMs, r) {
464
+ return Math.round(deadlineMs * (.9 + 2 * DEADLINE_JITTER * r));
465
+ }
466
+ /** Pull-based batches are unbounded in message count, like readNext and toolkit follow. */
467
+ function sse(reader, id, contentType, offset, cursor, deadlineMs = 6e4, signal) {
468
+ const encoding = {
469
+ isJson: contentType.toLowerCase().startsWith("application/json"),
470
+ isText: contentType.toLowerCase().startsWith("text/"),
471
+ useBase64: false
472
+ };
473
+ encoding.useBase64 = !encoding.isJson && !encoding.isText;
474
+ const frames = Stream.suspend(() => {
475
+ let initial = true;
476
+ let currentOffset = offset;
477
+ let currentCursor = cursor;
478
+ return Stream.fromEffectRepeat(Effect.gen(function* () {
479
+ const result = initial ? yield* reader.read(id, { offset: currentOffset }).pipe(Effect.map((batch) => ({
480
+ ...batch,
481
+ cursor: void 0
482
+ }))) : yield* reader.readNext(id, {
483
+ offset: currentOffset,
484
+ cursor: currentCursor
485
+ });
486
+ if (initial) {
487
+ const now = yield* Clock.currentTimeMillis;
488
+ const random = yield* Random.next;
489
+ currentCursor = generateCursor({ now: () => now }, currentCursor, () => random);
490
+ } else if (result.cursor !== void 0) currentCursor = result.cursor;
491
+ initial = false;
492
+ currentOffset = result.nextOffset;
493
+ const chunks = result.messages.length ? events.dataEvent(result.messages, encoding) : [];
494
+ const control = result.closed ? {
495
+ streamNextOffset: currentOffset,
496
+ streamClosed: true
497
+ } : {
498
+ streamNextOffset: currentOffset,
499
+ streamCursor: currentCursor
500
+ };
501
+ if (!result.closed && result.upToDate) control.upToDate = true;
502
+ chunks.push(events.controlEvent(control));
503
+ return {
504
+ frames: [concatBytes(Array.map(chunks, (data) => ({ data })))],
505
+ done: result.closed
506
+ };
507
+ }).pipe(Effect.catchTags({
508
+ StreamNotFound: () => Effect.succeed({
509
+ frames: [],
510
+ done: true
511
+ }),
512
+ StreamGone: () => Effect.succeed({
513
+ frames: [],
514
+ done: true
515
+ }),
516
+ NotSupported: () => Effect.succeed({
517
+ frames: [],
518
+ done: true
519
+ })
520
+ }))).pipe(Stream.takeUntil((batch) => batch.done), Stream.flatMap((batch) => Stream.fromIterable(batch.frames)), Stream.merge(Stream.fromEffect(Random.next.pipe(Effect.flatMap((r) => Effect.sleep(jitterDeadline(deadlineMs, r))))).pipe(Stream.drain), { haltStrategy: "either" }), Stream.merge(Stream.fromEffect(signal?.draining ?? Effect.never).pipe(Stream.drain), { haltStrategy: "either" }));
521
+ });
522
+ const headers = new Headers({
523
+ "content-type": "text/event-stream",
524
+ "cache-control": "no-cache",
525
+ connection: "keep-alive"
526
+ });
527
+ if (encoding.useBase64) headers.set("stream-sse-data-encoding", "base64");
528
+ const body = signal === void 0 ? frames : signal.trackStream(frames);
529
+ return HttpServerResponse.stream(body, { headers: Record.fromEntries(headers) });
530
+ }
531
+ // src/http/shutdown-signal.ts
532
+ var ShutdownSignal = class extends Context.Service()("@streamsy/core/ShutdownSignal") {};
533
+ /** How often `drain` checks the live-read count. */
534
+ const POLL = Schedule.spaced("5 millis");
535
+ const makeShutdownSignal = Effect.gen(function* () {
536
+ const started = yield* Deferred.make();
537
+ const count = yield* Ref.make(0);
538
+ const enter = Ref.update(count, (n) => n + 1);
539
+ const leave = Ref.update(count, (n) => n - 1);
540
+ return ShutdownSignal.of({
541
+ draining: Deferred.await(started),
542
+ track: (effect) => Effect.acquireUseRelease(enter, () => effect, () => leave),
543
+ trackStream: (stream) => Stream.unwrap(Effect.acquireRelease(enter, () => leave).pipe(Effect.as(stream))),
544
+ drain: (timeout) => Deferred.succeed(started, void 0).pipe(Effect.andThen(Ref.get(count).pipe(Effect.repeat({
545
+ until: (n) => n === 0,
546
+ schedule: POLL
547
+ }))), Effect.timeoutOption(timeout), Effect.asVoid),
548
+ active: Ref.get(count)
549
+ });
550
+ });
551
+ /** A fresh signal. Provide it to the routes and call `drain` before they close. */
552
+ const layerShutdownSignal = Layer.effect(ShutdownSignal, makeShutdownSignal);
553
+ // src/http/read.ts
554
+ const responses$2 = responses_exports;
555
+ const bodyCodec = message_body_codec_exports;
556
+ const etags = etag_builder_exports;
557
+ const queryParser = readQueryParser(isValid);
558
+ /**
559
+ * The reply a parked long poll gives when the host drains: no messages, the
560
+ * requested offset, and a fresh cursor. The HTTP layer turns it into the same
561
+ * `204` as a long-poll timeout, so a client reconnects as it always does. The
562
+ * next read, on this host or the next one, returns anything that arrived.
563
+ */
564
+ const drainReply = Effect.fn("Http.drainReply")(function* (reader, id, offset, cursor) {
565
+ const head = yield* reader.head(id);
566
+ const now = yield* Clock.currentTimeMillis;
567
+ const random = yield* Random.next;
568
+ return {
569
+ contentType: head.contentType,
570
+ messages: [],
571
+ nextOffset: offset === "now" ? head.nextOffset : offset,
572
+ upToDate: true,
573
+ closed: false,
574
+ timedOut: true,
575
+ cursor: generateCursor({ now: () => now }, cursor, () => random)
576
+ };
577
+ });
578
+ /** Park on `readNext` until data, timeout, or the host's drain signal. */
579
+ const longPoll = (reader, id, offset, cursor, signal) => {
580
+ const wait = reader.readNext(id, {
581
+ offset,
582
+ cursor
583
+ });
584
+ if (Option.isNone(signal)) return wait;
585
+ const drained = signal.value.draining.pipe(Effect.andThen(drainReply(reader, id, offset, cursor)));
586
+ return signal.value.track(Effect.raceFirst(wait, drained));
587
+ };
588
+ const read$1 = Effect.fn("Http.read")(function* (reader, id, url, requestHeaders, cacheControl, sseDeadlineMs) {
589
+ const query = queryParser.parse(url);
590
+ if (!query.ok) return query.response;
591
+ const offset = query.offset;
592
+ if (offset === "now" && !query.live) {
593
+ const result = yield* reader.read(id, { offset: "now" });
594
+ const headers = new Headers({
595
+ "content-type": result.contentType,
596
+ "stream-next-offset": result.nextOffset,
597
+ "stream-up-to-date": "true",
598
+ "cache-control": "no-store"
599
+ });
600
+ if (result.closed) headers.set("stream-closed", "true");
601
+ return new Response(bodyCodec.emptyBodyForContentType(result.contentType), { headers });
602
+ }
603
+ if (query.live && !offset) return responses$2.badRequest("offset required for live modes");
604
+ const signal = yield* Effect.serviceOption(ShutdownSignal);
605
+ if (query.live === "sse" && offset) {
606
+ const meta = yield* reader.head(id);
607
+ return sse(reader, id, meta.contentType, offset === "now" ? meta.nextOffset : offset, query.cursor, sseDeadlineMs, Option.getOrUndefined(signal));
608
+ }
609
+ const live = query.live === "long-poll" && offset !== void 0;
610
+ const result = live && offset !== void 0 ? yield* longPoll(reader, id, offset, query.cursor, signal) : yield* reader.read(id, { offset }).pipe(Effect.map((batch) => ({
611
+ ...batch,
612
+ cursor: void 0
613
+ })));
614
+ const headers = new Headers({ "stream-next-offset": result.nextOffset });
615
+ if (result.closed) headers.set("stream-closed", "true");
616
+ if (live || result.upToDate) headers.set("stream-up-to-date", "true");
617
+ if (live && !result.closed && result.cursor !== void 0) headers.set("stream-cursor", result.cursor);
618
+ if (live && result.messages.length === 0) {
619
+ headers.set("cache-control", "no-store");
620
+ return responses$2.empty(204, headers);
621
+ }
622
+ const etag = etags.forCatchUp(url.pathname, offset ?? "-1", result.nextOffset, result.closed);
623
+ const literalNow = live && query.offset === "now";
624
+ headers.set("cache-control", literalNow ? "no-store" : cacheControl);
625
+ if (!literalNow) {
626
+ if (requestHeaders.get("if-none-match") === etag) return responses$2.empty(304, {
627
+ etag,
628
+ "cache-control": cacheControl
629
+ });
630
+ headers.set("etag", etag);
631
+ }
632
+ headers.set("content-type", result.contentType);
633
+ return new Response(bodyCodec.encodeHttpBody(result.messages, result.contentType), { headers });
634
+ });
635
+ // src/http/route.ts
636
+ /** Preserve the Web request origin; Effect 4.0.1 toURL otherwise reconstructs it from Host. */
637
+ function requestUrl(request) {
638
+ return URL.parse(request.originalUrl) ?? Option.getOrUndefined(HttpServerRequest.toURL(request));
639
+ }
640
+ // src/http/read-program.ts
641
+ /** @internal Shared construction-time validation for HTTP read routes. */
642
+ function checkReadOptions(options) {
643
+ if (options.sseDeadlineMs !== void 0 && (!Number.isFinite(options.sseDeadlineMs) || options.sseDeadlineMs <= 0)) throw new RangeError("sseDeadlineMs must be positive");
644
+ }
645
+ /** Read an already resolved id using the protocol's HTTP framing and live modes. */
646
+ function read(id, options = {}) {
647
+ checkReadOptions(options);
648
+ return Effect.gen(function* () {
649
+ const request = yield* HttpServerRequest.HttpServerRequest;
650
+ const reader = yield* StreamsReader;
651
+ const url = requestUrl(request);
652
+ if (!url) return HttpServerResponse.text("Invalid request URL", { status: 400 });
653
+ if (request.method === "HEAD") {
654
+ const meta = yield* reader.head(id);
655
+ const headers = new Headers({
656
+ "content-type": meta.contentType,
657
+ "stream-next-offset": meta.nextOffset,
658
+ "cache-control": "no-store"
659
+ });
660
+ if (meta.closed) headers.set("stream-closed", "true");
661
+ if (meta.ttlSeconds) headers.set("stream-ttl", String(meta.ttlSeconds));
662
+ if (meta.expiresAt) headers.set("stream-expires-at", meta.expiresAt);
663
+ return HttpServerResponse.empty({
664
+ status: 200,
665
+ headers: Record.fromEntries(headers)
666
+ });
667
+ }
668
+ const response = yield* read$1(reader, id, url, new Headers(request.headers), cacheControlForVisibility(options.cacheVisibility ?? "private"), options.sseDeadlineMs);
669
+ return response instanceof Response ? fromWeb(response) : response;
670
+ }).pipe(Effect.map(HttpServerResponse.setHeaders(securityHeaders)));
671
+ }
672
+ // src/http/protocol-error-response.ts
673
+ const responses$1 = responses_exports;
674
+ const conflict = ({ message }) => responses$1.conflict(message);
675
+ const badRequest = ({ message }) => responses$1.badRequest(message);
676
+ /** The sole protocol rejection mapping at the HTTP edge. */
677
+ function protocolErrorResponse(error, context) {
678
+ return Match.valueTags(error, {
679
+ StreamNotFound: () => context.method === "HEAD" ? responses$1.noStore(responses$1.notFound()) : responses$1.notFound(),
680
+ StreamGone: () => context.method === "HEAD" ? responses$1.noStore(responses$1.gone()) : responses$1.gone(),
681
+ ForkSourceNotFound: ({ source }) => responses$1.notFound(`Source stream not found: ${source}`),
682
+ CreateConflict: conflict,
683
+ AppendConflict: conflict,
684
+ InvalidReadRequest: badRequest,
685
+ InvalidForkRequest: badRequest,
686
+ InvalidAppendRequest: badRequest,
687
+ StreamClosed: ({ offset }) => responses$1.empty(409, {
688
+ "stream-closed": "true",
689
+ "stream-next-offset": offset
690
+ }),
691
+ OffsetMismatch: ({ actual }) => responses$1.conflict("Expected offset mismatch", { "stream-next-offset": actual }),
692
+ StreamBusy: () => responses$1.text("Stream busy, retry later", 503),
693
+ StaleEpoch: ({ currentEpoch }) => responses$1.text("Stale producer epoch", 403, { "producer-epoch": String(currentEpoch) }),
694
+ ProducerGap: ({ expectedSeq, receivedSeq }) => responses$1.conflict("Producer sequence gap", {
695
+ "producer-expected-seq": String(expectedSeq),
696
+ "producer-received-seq": String(receivedSeq)
697
+ }),
698
+ InvalidEpochSeq: () => responses$1.badRequest("New epoch must start at seq=0"),
699
+ NotSupported: ({ feature }) => new Response(`Feature not supported: ${feature}`, {
700
+ status: 400,
701
+ headers: { "stream-not-supported": feature }
702
+ })
703
+ });
704
+ }
705
+ // src/http/program.ts
706
+ const responses = responses_exports;
707
+ const failure = (error) => Effect.map(HttpServerRequest.HttpServerRequest, (request) => protocolErrorResponse(error, { method: request.method }));
708
+ /**
709
+ * The public HTTP program. It is the whole application an Effect host serves.
710
+ *
711
+ * Its success type is `HttpServerResponse` alone, its error channel is closed,
712
+ * and it requires exactly `HttpServerRequest | StreamsReader | StreamsWriter`.
713
+ * Those three facts are what let a host type it as an Alchemy `HttpEffect` and
714
+ * what let one composition serve several backends.
715
+ */
716
+ function app(options = {}) {
717
+ checkReadOptions(options);
718
+ const path = streamPath(options.pathPrefix ?? "/");
719
+ const bodyReader = requestBodyReader(options.maxMessageSize ?? 1048576);
720
+ return Effect.gen(function* () {
721
+ const request = yield* HttpServerRequest.HttpServerRequest;
722
+ const writer = yield* StreamsWriter;
723
+ const url = requestUrl(request);
724
+ if (!url) return responses.badRequest("Invalid request URL");
725
+ const stripped = path.strip(url.pathname);
726
+ if (!stripped || stripped === url.pathname) return responses.badRequest(`Stream path required: ${path.requiredPathPattern()}`);
727
+ const id = StreamId.make(stripped);
728
+ const headers = new Headers(request.headers);
729
+ if (request.method === "PUT") {
730
+ const parsed = parseHeaders$1({ headers }, path);
731
+ if (!parsed.ok) return parsed.response;
732
+ const body = yield* bodyReader.read(request);
733
+ if (!body.ok) return body.response;
734
+ const normalized = normalizeInitialData(body.data, parsed.contentType);
735
+ if (!normalized.ok) return normalized.response;
736
+ return toResponse$1(yield* writer.create(id, {
737
+ contentType: parsed.contentType,
738
+ ttlSeconds: parsed.ttlSeconds,
739
+ expiresAt: parsed.expiresAt,
740
+ initialData: normalized.initialData,
741
+ closed: parsed.wantClosed,
742
+ forkedFrom: parsed.forkedFromStreamId,
743
+ forkOffset: parsed.forkOffset,
744
+ forkSubOffset: parsed.forkSubOffset
745
+ }), url.href);
746
+ }
747
+ if (request.method === "OPTIONS") return responses.empty(204, {
748
+ "access-control-allow-origin": "*",
749
+ "access-control-allow-methods": "GET, HEAD, PUT, POST, DELETE, OPTIONS",
750
+ "access-control-allow-headers": "Authorization, Content-Type, If-None-Match, Producer-Id, Producer-Epoch, Producer-Seq, Stream-Closed, Stream-Expected-Offset, Stream-Seq, Stream-TTL, Stream-Expires-At",
751
+ "access-control-max-age": "86400"
752
+ });
753
+ if (![
754
+ "POST",
755
+ "GET",
756
+ "HEAD",
757
+ "DELETE"
758
+ ].includes(request.method)) return responses.methodNotAllowed();
759
+ switch (request.method) {
760
+ case "POST": {
761
+ const parsed = parseHeaders({ headers });
762
+ if (!parsed.ok) {
763
+ yield* discardRequestBody(request);
764
+ return parsed.response;
765
+ }
766
+ const body = yield* bodyReader.read(request);
767
+ if (!body.ok) return body.response;
768
+ const isEmpty = body.byteLength === 0;
769
+ if (isEmpty && !parsed.wantClose) return responses.badRequest("Empty body not allowed");
770
+ if (!parsed.contentType && !isEmpty) return responses.badRequest("Content-Type required");
771
+ const normalized = normalizeInitialData(body.data, parsed.contentType ?? void 0);
772
+ if (!normalized.ok) return normalized.response;
773
+ return toResponse(yield* writer.append(id, {
774
+ data: body.data,
775
+ contentType: parsed.contentType ?? "application/octet-stream",
776
+ seq: parsed.seq,
777
+ producer: parsed.producerHeaders.kind === "ok" ? parsed.producerHeaders.producer : void 0,
778
+ close: parsed.wantClose,
779
+ expectedOffset: parsed.expectedOffset
780
+ }), parsed.producerHeaders, isEmpty);
781
+ }
782
+ case "GET":
783
+ case "HEAD": return yield* read(id, options);
784
+ case "DELETE":
785
+ yield* writer.remove(id);
786
+ return responses.empty(204);
787
+ default: return responses.methodNotAllowed();
788
+ }
789
+ }).pipe(Effect.catchIf(isProtocolError, failure), Effect.catchTags({
790
+ StorageFault: () => Effect.succeed(responses.internalError()),
791
+ TransportFault: () => Effect.succeed(responses.internalError())
792
+ }), Effect.map((response) => {
793
+ const result = response instanceof Response ? responses.fromWeb(response) : response;
794
+ return HttpServerResponse.setHeaders(result, securityHeaders);
795
+ }));
796
+ }
797
+ export { ShutdownSignal as a, streamPath as c, requestUrl as i, securityHeaders as l, checkReadOptions as n, layerShutdownSignal as o, read as r, discardRequestBody as s, app as t };