@streamsy/core 0.15.0 → 0.17.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.
@@ -1,8 +1,10 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamBusy, D as OffsetMismatch, E as NotSupported, F as StreamsReader, I as StreamsWriter, K as TransportFault, M as StreamGone, N as StreamNotFound, O as ProducerGap, S as InvalidCreateRequest, T as InvalidReadRequest, _ as CreateResult, b as ForkSourceNotFound, g as AppendResult, j as StreamClosed, k as StaleEpoch, n as bind, rt as StreamId, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict } from "../streamsy-HKC10a_V.js";
3
- import { n as validateCreateOptions } from "../create-validation-DzLxKiux.js";
4
- import { Array, Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
2
+ import { A as ProducerGap, C as InvalidAppendRequest, D as InvalidReadRequest, E as InvalidForkRequest, F as StreamNotFound, H as isValid, K as Offset, L as StreamsReader, M as StreamBusy, N as StreamClosed, O as NotSupported, P as StreamGone, Q as StreamId, R as StreamsWriter, S as ForkSourceNotFound, b as AppendConflict, j as StaleEpoch, k as OffsetMismatch, n as bind, v as AppendResult, w as InvalidCreateRequest, x as CreateConflict, y as CreateResult } from "../streamsy-DiAjZWlT.js";
3
+ import { F as TransportFault } from "../read-message-DP1UpEFl.js";
4
+ import { n as validateCreateOptions } from "../create-validation-NKP81BC0.js";
5
+ import { Array, Context, DateTime, Effect, Exit, Fiber, Layer, Option, Pull, Schema, Scope, Semaphore, Stream } from "effect";
5
6
  import { HttpClient, HttpClientRequest } from "effect/http";
7
+ import { Sse } from "effect/encoding";
6
8
  // src/remote/request.ts
7
9
  function requests(options) {
8
10
  const base = new URL(options.baseUrl);
@@ -30,7 +32,7 @@ function requests(options) {
30
32
  readNext: (id, input) => {
31
33
  const params = {
32
34
  offset: input.offset,
33
- live: "long-poll"
35
+ live: options.live ?? "long-poll"
34
36
  };
35
37
  if (input.cursor !== void 0) params.cursor = input.cursor;
36
38
  return HttpClientRequest.setUrlParams(make("GET", id), params);
@@ -71,7 +73,6 @@ function requests(options) {
71
73
  * a field the direct Layer returns, the decoder reports what the wire has.
72
74
  */
73
75
  const INTEGER = /^(0|[1-9]\d*)$/;
74
- const OFFSET = /^\d{16}_\d{16}$/;
75
76
  const CONTENT_TYPE = /^[^\s/;]+\/[^\s;]+(?:;.*)?$/;
76
77
  const failure = (operation, reason, message, cause, status) => status === void 0 ? new TransportFault({
77
78
  operation,
@@ -98,7 +99,7 @@ const cursor = (response) => header(response, "stream-cursor") ?? "";
98
99
  const optionalOffset = (operation, response) => {
99
100
  const value = header(response, "stream-next-offset");
100
101
  if (value === void 0) return Effect.as(Effect.void, void 0);
101
- if (!OFFSET.test(value)) return Effect.fail(failure(operation, "response", `Invalid stream-next-offset header: ${value}`, void 0, response.status));
102
+ if (!isValid(value)) return Effect.fail(failure(operation, "response", `Invalid stream-next-offset header: ${value}`, void 0, response.status));
102
103
  return Effect.succeed(value);
103
104
  };
104
105
  const offset = (operation, response) => optionalOffset(operation, response).pipe(Effect.filterOrFail((value) => value !== void 0, () => failure(operation, "response", "Missing stream-next-offset header", void 0, response.status)));
@@ -141,10 +142,12 @@ const unexpected = (operation, response) => bodyText(operation, response).pipe(E
141
142
  */
142
143
  const readMessages = (operation, response, bytes) => {
143
144
  if (bytes.byteLength === 0) return Effect.succeed([]);
144
- return contentType(operation, response).pipe(Effect.flatMap((value) => {
145
- if (value.split(";")[0]?.trim().toLowerCase() === "application/json") return text(operation, bytes).pipe(Effect.flatMap((decoded) => jsonMessages(operation, decoded)));
146
- return Effect.succeed([{ data: bytes }]);
147
- }));
145
+ return contentType(operation, response).pipe(Effect.flatMap((value) => decodeMessages(operation, value, bytes)));
146
+ };
147
+ const decodeMessages = (operation, mediaType, bytes) => {
148
+ if (bytes.byteLength === 0) return Effect.succeed([]);
149
+ if (mediaType.split(";")[0]?.trim().toLowerCase() === "application/json") return text(operation, bytes).pipe(Effect.flatMap((decoded) => jsonMessages(operation, decoded)));
150
+ return Effect.succeed([{ data: bytes }]);
148
151
  };
149
152
  const jsonArray = Schema.fromJsonString(Schema.Array(Schema.Unknown));
150
153
  const jsonMessages = (operation, decoded) => Schema.decodeEffect(jsonArray)(decoded).pipe(Effect.mapError((cause) => failure(operation, "decode", "Read body is not a JSON array", cause)), Effect.map((items) => Array.map(items, (item) => ({ data: new TextEncoder().encode(JSON.stringify(item)) }))));
@@ -159,13 +162,13 @@ const head = (operation, response, context) => Effect.gen(function* () {
159
162
  if (response.status === 410) return yield* new StreamGone({ id: context.id });
160
163
  if (response.status !== 200) return yield* unexpected(operation, response);
161
164
  const contentType$2 = yield* contentType(operation, response);
162
- const nextOffset = yield* offset(operation, response);
165
+ const offset$2 = yield* offset(operation, response);
163
166
  const ttlSeconds = yield* integer(operation, "stream-ttl", header(response, "stream-ttl"));
164
167
  const expiresAt = header(response, "stream-expires-at");
165
168
  if (expiresAt !== void 0 && Option.isNone(DateTime.make(expiresAt))) return yield* failure(operation, "response", `Invalid stream-expires-at header: ${expiresAt}`, void 0, response.status);
166
169
  return {
167
170
  contentType: contentType$2,
168
- nextOffset,
171
+ offset: offset$2,
169
172
  ttlSeconds,
170
173
  expiresAt,
171
174
  closed: yield* closedHeader(operation, response)
@@ -175,7 +178,7 @@ const create = (operation, response, context) => Effect.gen(function* () {
175
178
  if (response.status === 200 || response.status === 201) {
176
179
  const contentType$1 = yield* contentType(operation, response);
177
180
  const fields = {
178
- nextOffset: yield* offset(operation, response),
181
+ offset: yield* offset(operation, response),
179
182
  contentType: contentType$1,
180
183
  closed: yield* closedHeader(operation, response)
181
184
  };
@@ -257,6 +260,8 @@ const append = (operation, response, context) => Effect.gen(function* () {
257
260
  if (response.status === 409) return yield* appendConflict(operation, response, context);
258
261
  return yield* unexpected(operation, response);
259
262
  });
263
+ /** A missing or unknown `stream-conflict-reason` gives no reason. */
264
+ const conflictReason = (value) => value === "sequence" || value === "content-type" ? value : void 0;
260
265
  const appendConflict = (operation, response, context) => Effect.gen(function* () {
261
266
  const expectedSeq = yield* integer(operation, "producer-expected-seq", header(response, "producer-expected-seq"));
262
267
  const receivedSeq = yield* integer(operation, "producer-received-seq", header(response, "producer-received-seq"));
@@ -276,9 +281,15 @@ const appendConflict = (operation, response, context) => Effect.gen(function* ()
276
281
  expected: context.expectedOffset,
277
282
  actual: offset
278
283
  });
279
- return yield* new AppendConflict({
284
+ const reason = conflictReason(header(response, "stream-conflict-reason"));
285
+ const message = yield* bodyText(operation, response);
286
+ return yield* reason === void 0 ? new AppendConflict({
280
287
  id: context.id,
281
- message: yield* bodyText(operation, response)
288
+ message
289
+ }) : new AppendConflict({
290
+ id: context.id,
291
+ reason,
292
+ message
282
293
  });
283
294
  });
284
295
  const read = (operation, response, context) => Effect.gen(function* () {
@@ -345,13 +356,120 @@ const remove = (operation, response, context) => Effect.gen(function* () {
345
356
  if (response.status === 503) return yield* new StreamBusy({ id: context.id });
346
357
  return yield* unexpected(operation, response);
347
358
  });
359
+ // src/remote/sse-response.ts
360
+ const operation = "readNext";
361
+ const control = Schema.fromJsonString(Schema.Struct({
362
+ streamNextOffset: Offset,
363
+ streamCursor: Schema.optionalKey(Schema.String),
364
+ streamClosed: Schema.optionalKey(Schema.Boolean),
365
+ upToDate: Schema.optionalKey(Schema.Boolean)
366
+ }));
367
+ const encoder = new TextEncoder();
368
+ const isTransportFault = Schema.is(TransportFault);
369
+ const sseContentType = (contentType) => contentType.split(";")[0]?.trim().toLowerCase() === "text/event-stream";
370
+ const batches = (response, contentType) => Effect.gen(function* () {
371
+ const encoding = header(response, "stream-sse-data-encoding");
372
+ if (encoding !== void 0 && encoding.toLowerCase() !== "base64") return yield* failure(operation, "response", `Unsupported SSE data encoding: ${encoding}`);
373
+ const bytes = (data) => encoding === void 0 ? Effect.succeed(encoder.encode(data)) : Schema.decodeEffect(Schema.Uint8ArrayFromBase64)(data).pipe(Effect.mapError((cause) => failure(operation, "decode", "Invalid base64 in SSE data", cause)));
374
+ return { pull: (yield* response.stream.pipe(Stream.mapError((cause) => failure(operation, "request", "Cannot read SSE response body", cause)), Stream.decodeText(), Stream.pipeThroughChannel(Sse.decode({ maxEventSize: Infinity })), Stream.mapError((cause) => isTransportFault(cause) ? cause : failure(operation, "decode", "Invalid SSE response body", cause)), Stream.mapAccum(() => [], (data, event) => {
375
+ if (event.event === "control") return [[], [{
376
+ data,
377
+ control: event.data
378
+ }]];
379
+ if (event.event === "data") data.push(event.data);
380
+ return [data, []];
381
+ }), Stream.rechunk(1), Stream.mapEffect((frame) => Effect.gen(function* () {
382
+ const position = yield* Schema.decodeEffect(control)(frame.control).pipe(Effect.mapError((cause) => failure(operation, "decode", "Invalid SSE control", cause)));
383
+ const messages = yield* Effect.forEach(frame.data, (data) => bytes(data).pipe(Effect.flatMap((body) => decodeMessages(operation, contentType, body)))).pipe(Effect.map(Array.flatten));
384
+ const closed = position.streamClosed === true;
385
+ return {
386
+ contentType,
387
+ messages,
388
+ timedOut: frame.data.length === 0,
389
+ nextOffset: position.streamNextOffset,
390
+ cursor: position.streamCursor ?? "",
391
+ upToDate: closed || position.upToDate === true,
392
+ closed
393
+ };
394
+ })), Stream.toPull)).pipe(Pull.catchDone(() => Effect.fail(failure(operation, "request", "SSE response ended before the next control"))), Effect.map(([batch]) => batch)) };
395
+ });
396
+ // src/remote/sse.ts
397
+ const idleTimeout = "30 seconds";
398
+ const discard = (slot) => Effect.suspend(() => {
399
+ const connection = slot.connection;
400
+ slot.connection = void 0;
401
+ return connection === void 0 ? Effect.void : Scope.close(connection.scope, Exit.void);
402
+ });
403
+ /** Serialize pulls by stream. A caller at a different position gets a fresh connection. */
404
+ const sseReadNext = (owner, open) => {
405
+ const slots = /* @__PURE__ */ new Map();
406
+ const acquire = (id) => Effect.gen(function* () {
407
+ let slot = slots.get(id);
408
+ if (slot === void 0) {
409
+ slot = {
410
+ lock: Semaphore.makeUnsafe(1),
411
+ users: 0
412
+ };
413
+ slots.set(id, slot);
414
+ }
415
+ slot.users += 1;
416
+ const idle = slot.idle;
417
+ slot.idle = void 0;
418
+ if (idle?.fiber !== void 0) yield* Fiber.interrupt(idle.fiber);
419
+ return slot;
420
+ });
421
+ const release = (id, slot) => Effect.gen(function* () {
422
+ slot.users -= 1;
423
+ if (slot.users > 0) return;
424
+ if (slot.connection === void 0) {
425
+ slots.delete(id);
426
+ return;
427
+ }
428
+ const idle = {};
429
+ slot.idle = idle;
430
+ idle.fiber = yield* Effect.sleep(idleTimeout).pipe(Effect.andThen(Effect.suspend(() => {
431
+ if (slot.idle !== idle) return Effect.void;
432
+ slots.delete(id);
433
+ return discard(slot);
434
+ })), Effect.forkIn(owner, { uninterruptible: false }));
435
+ });
436
+ const fresh = (id, input, slot) => Effect.gen(function* () {
437
+ const connection = yield* Scope.fork(owner).pipe(Effect.map((scope) => ({
438
+ scope,
439
+ ...input
440
+ })), Effect.tap((opened) => Effect.sync(() => {
441
+ slot.connection = opened;
442
+ })), Effect.uninterruptible);
443
+ const opened = yield* open(id, input).pipe(Effect.provideService(Scope.Scope, connection.scope));
444
+ if (!("pull" in opened)) return opened;
445
+ connection.pull = opened.pull;
446
+ return yield* opened.pull;
447
+ });
448
+ const read = (id, input, slot) => Effect.gen(function* () {
449
+ const connection = slot.connection;
450
+ if (connection?.pull !== void 0 && connection.offset === input.offset && (input.cursor === void 0 || connection.cursor === input.cursor)) {
451
+ const batch = yield* connection.pull.pipe(Effect.catchTag("TransportFault", (fault) => fault.isRetryable ? Effect.void : Effect.fail(fault)));
452
+ if (batch !== void 0) return batch;
453
+ }
454
+ yield* discard(slot);
455
+ return yield* fresh(id, input, slot);
456
+ }).pipe(Effect.onExit((exit) => {
457
+ const connection = slot.connection;
458
+ if (Exit.isFailure(exit) || exit.value.closed || connection?.pull === void 0) return discard(slot);
459
+ return Effect.sync(() => {
460
+ connection.offset = exit.value.nextOffset;
461
+ connection.cursor = exit.value.cursor;
462
+ });
463
+ }));
464
+ return (id, input) => Effect.acquireUseRelease(acquire(id), (slot) => slot.lock.withPermit(read(id, input, slot)), (slot) => release(id, slot));
465
+ };
348
466
  // src/remote/streams.ts
349
467
  var streams_exports = /* @__PURE__ */ __exportAll({
350
468
  TransportFault: () => TransportFault,
351
469
  layer: () => layer,
352
470
  layerProtocol: () => layerProtocol
353
471
  });
354
- /** Generic reader and writer over HTTP for the protocol tier. HttpClient and the calling fiber own request lifetimes. */
472
+ /** Generic reader and writer over HTTP for the protocol tier. */
355
473
  const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
356
474
  const client = HttpClient.withScope(yield* HttpClient.HttpClient);
357
475
  const owner = yield* Scope.Scope;
@@ -364,7 +482,8 @@ const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
364
482
  cause
365
483
  })
366
484
  });
367
- const execute = (operation, make, decode) => Effect.gen(function* () {
485
+ const owned = (body) => body.pipe(Effect.forkIn(owner), Effect.flatMap((fiber) => Fiber.join(fiber).pipe(Effect.ensuring(Fiber.interrupt(fiber)))));
486
+ const send = (operation, make) => Effect.gen(function* () {
368
487
  const input = yield* Effect.try({
369
488
  try: make,
370
489
  catch: (cause) => new TransportFault({
@@ -374,23 +493,34 @@ const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
374
493
  cause
375
494
  })
376
495
  });
377
- return yield* decode(operation, yield* client.execute(input).pipe(Effect.mapError((cause) => new TransportFault({
496
+ return yield* client.execute(input).pipe(Effect.mapError((cause) => new TransportFault({
378
497
  operation,
379
498
  reason: "request",
380
499
  message: "HTTP request failed",
381
500
  cause
382
- }))));
383
- }).pipe(Effect.scoped, Effect.forkIn(owner), Effect.flatMap((fiber) => Fiber.join(fiber).pipe(Effect.ensuring(Fiber.interrupt(fiber)))));
501
+ })));
502
+ });
503
+ const execute = (operation, make, decode) => owned(Effect.scoped(send(operation, make).pipe(Effect.flatMap((response) => decode(operation, response)))));
504
+ const head$1 = (id) => execute("head", () => request.head(id), (operation, response) => head(operation, response, { id }));
505
+ const decodeNext = (response, id) => Effect.gen(function* () {
506
+ const originalType = response.status === 204 && header(response, "content-type") === void 0 ? (yield* head$1(id)).contentType : void 0;
507
+ return yield* readNext("readNext", response, {
508
+ id,
509
+ contentType: originalType
510
+ });
511
+ });
512
+ const sse = options.live === "sse" ? sseReadNext(owner, (id, input) => Effect.gen(function* () {
513
+ const response = yield* send("readNext", () => request.readNext(id, input));
514
+ if (response.status !== 200) return yield* decodeNext(response, id);
515
+ const mediaType = yield* contentType("readNext", response);
516
+ if (!sseContentType(mediaType)) return yield* failure("readNext", "response", `Expected an SSE response, received ${mediaType}`);
517
+ const meta = yield* head$1(id);
518
+ return yield* batches(response, meta.contentType);
519
+ })) : void 0;
384
520
  const reader = {
385
- head: (id) => execute("head", () => request.head(id), (operation, response) => head(operation, response, { id })),
521
+ head: head$1,
386
522
  read: (id, input) => execute("read", () => request.read(id, input), (operation, response) => read(operation, response, { id })),
387
- readNext: (id, input) => execute("readNext", () => request.readNext(id, input), (operation, response) => Effect.gen(function* () {
388
- const contentType = response.status === 204 && header(response, "content-type") === void 0 ? (yield* reader.head(id)).contentType : void 0;
389
- return yield* readNext(operation, response, {
390
- id,
391
- contentType
392
- });
393
- }))
523
+ readNext: (id, input) => sse === void 0 ? execute("readNext", () => request.readNext(id, input), (_, response) => decodeNext(response, id)) : owned(sse(id, input))
394
524
  };
395
525
  return Context.make(StreamsReader, reader).pipe(Context.add(StreamsWriter, {
396
526
  create: (id, input) => validateCreateOptions(id, input).pipe(Effect.andThen(execute("create", () => request.create(id, input), (operation, response) => create(operation, response, {