@streamsy/core 0.6.0 → 0.8.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.
- package/README.md +4 -4
- package/dist/create-validation-Dwx1OQAN.js +53 -0
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.js +2 -2
- package/dist/{http-B10ao6xE.js → http-CwDadGy6.js} +2 -2
- package/dist/{index-p68har8W.d.ts → index-DzptR3sL.d.ts} +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -5
- package/dist/internal/index.d.ts +15 -2
- package/dist/internal/index.js +27 -2
- package/dist/{layer-8Y1cg6UL.js → layer-B1JEYOZb.js} +13 -31
- package/dist/{layer-DQZj5tXr.js → layer-VOzdazlb.js} +86 -5
- package/dist/{program-CYtMjdvD.js → program-DPq8FYrT.js} +2 -1
- package/dist/{owner-records-H7VEuBpy.d.ts → projection-marks-OtKtjFLH.d.ts} +76 -2
- package/dist/projection-marks-RqurLPLA.js +24 -0
- package/dist/protocol/index.d.ts +2 -2
- package/dist/protocol/index.js +3 -3
- package/dist/remote/index.d.ts +2 -2
- package/dist/remote/index.js +10 -5
- package/dist/{streamsy-D9OCCdw0.js → streamsy-BWX6z980.js} +6 -1
- package/dist/testing/index.d.ts +6 -3
- package/dist/testing/index.js +159 -6
- package/package.json +1 -1
- package/dist/owner-records-C0p8jeC1.js +0 -4
package/README.md
CHANGED
|
@@ -283,10 +283,10 @@ read notification source. Custom storage adapters must provide `committed`.
|
|
|
283
283
|
## Documentation
|
|
284
284
|
|
|
285
285
|
- [Declare streams](https://streamsy.dev/docs/streams/declare)
|
|
286
|
-
- [
|
|
287
|
-
- [
|
|
288
|
-
- [
|
|
289
|
-
- [Write a storage adapter](https://streamsy.dev/docs/
|
|
286
|
+
- [Choose storage](https://streamsy.dev/docs/storage)
|
|
287
|
+
- [Expose the stream protocol](https://streamsy.dev/docs/servers/protocol)
|
|
288
|
+
- [Connect to a remote server](https://streamsy.dev/docs/servers/remote)
|
|
289
|
+
- [Write a storage adapter](https://streamsy.dev/docs/storage/adapter)
|
|
290
290
|
|
|
291
291
|
Source: https://github.com/gingerhendrix/streamsy
|
|
292
292
|
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { S as InvalidCreateRequest } from "./streamsy-BWX6z980.js";
|
|
2
|
+
import { Array, DateTime, Effect, Option, Result } from "effect";
|
|
3
|
+
// src/policy/message-framer.ts
|
|
4
|
+
/**
|
|
5
|
+
* Body framing for the durable streams protocol.
|
|
6
|
+
*
|
|
7
|
+
* Responsibilities:
|
|
8
|
+
*
|
|
9
|
+
* - Non-JSON content types pass the original bytes through as a single
|
|
10
|
+
* message.
|
|
11
|
+
* - JSON content types are decoded and re-encoded:
|
|
12
|
+
* - JSON object input becomes one canonical `JSON.stringify(parsed)` message.
|
|
13
|
+
* - JSON array input produces one message per item.
|
|
14
|
+
* - Empty JSON array produces zero messages.
|
|
15
|
+
* - The JSON branch is selected by `contentType.toLowerCase().startsWith("application/json")`,
|
|
16
|
+
* without parameter stripping.
|
|
17
|
+
* - Invalid JSON propagates the underlying `JSON.parse` error.
|
|
18
|
+
*
|
|
19
|
+
* Used by `AppendService`, `CreateStreamService`, and `ForkPlanBuilder` before
|
|
20
|
+
* incoming request bodies are persisted as stored messages.
|
|
21
|
+
*/
|
|
22
|
+
function frameMessages(data, contentType) {
|
|
23
|
+
if (!contentType.toLowerCase().startsWith("application/json")) return [data];
|
|
24
|
+
const parsed = JSON.parse(new TextDecoder().decode(data));
|
|
25
|
+
if (Array.isArray(parsed)) return parsed.length === 0 ? [] : Array.map(parsed, (item) => new TextEncoder().encode(JSON.stringify(item)));
|
|
26
|
+
return [new TextEncoder().encode(JSON.stringify(parsed))];
|
|
27
|
+
}
|
|
28
|
+
// src/policy/create-validation.ts
|
|
29
|
+
/** Validate expiry before either transport accesses a stream. */
|
|
30
|
+
const validateCreateOptions = Effect.fn("Create.validateOptions")(function* (id, options = {}) {
|
|
31
|
+
if (options.ttlSeconds !== void 0 && options.expiresAt !== void 0) return yield* new InvalidCreateRequest({
|
|
32
|
+
id,
|
|
33
|
+
message: "Cannot specify both Stream-TTL and Stream-Expires-At"
|
|
34
|
+
});
|
|
35
|
+
if (options.expiresAt !== void 0 && Option.isNone(DateTime.make(options.expiresAt))) return yield* new InvalidCreateRequest({
|
|
36
|
+
id,
|
|
37
|
+
message: "Invalid Stream-Expires-At format"
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
/** Create bodies use typed JSON failures without changing append framing. */
|
|
41
|
+
function frameCreateMessages(id, data, contentType) {
|
|
42
|
+
return Result.try({
|
|
43
|
+
try: () => data === void 0 ? [] : frameMessages(data, contentType),
|
|
44
|
+
catch: (error) => {
|
|
45
|
+
if (error instanceof SyntaxError) return new InvalidCreateRequest({
|
|
46
|
+
id,
|
|
47
|
+
message: "Invalid JSON"
|
|
48
|
+
});
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export { validateCreateOptions as n, frameMessages as r, frameCreateMessages as t };
|
package/dist/http/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { H as HttpOptions, U as app, V as streamPath, a as securityHeaders, c as read, d as routes, i as layerShutdownSignal, l as Access, n as ShutdownSignal, o as ReadOptions, r as ShutdownSignalService, s as checkReadOptions, u as RoutesOptions } from "../index-
|
|
1
|
+
import { H as HttpOptions, U as app, V as streamPath, a as securityHeaders, c as read, d as routes, i as layerShutdownSignal, l as Access, n as ShutdownSignal, o as ReadOptions, r as ShutdownSignalService, s as checkReadOptions, u as RoutesOptions } from "../index-DzptR3sL.js";
|
|
2
2
|
export { type Access, type HttpOptions, type ReadOptions, type RoutesOptions, ShutdownSignal, type ShutdownSignalService, app, checkReadOptions, layerShutdownSignal, read, routes, securityHeaders, streamPath };
|
package/dist/http/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as ShutdownSignal, c as streamPath, l as securityHeaders, n as checkReadOptions, o as layerShutdownSignal, r as read, t as app } from "../program-
|
|
2
|
-
import { n as routes } from "../http-
|
|
1
|
+
import { a as ShutdownSignal, c as streamPath, l as securityHeaders, n as checkReadOptions, o as layerShutdownSignal, r as read, t as app } from "../program-DPq8FYrT.js";
|
|
2
|
+
import { n as routes } from "../http-CwDadGy6.js";
|
|
3
3
|
export { ShutdownSignal, app, checkReadOptions, layerShutdownSignal, read, routes, securityHeaders, streamPath };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { F as
|
|
3
|
-
import { a as ShutdownSignal, c as streamPath, i as requestUrl, l as securityHeaders, n as checkReadOptions, o as layerShutdownSignal, r as read, s as discardRequestBody, t as app } from "./program-
|
|
2
|
+
import { F as StreamsReader, I as StreamsWriter, i as checkStreams } from "./streamsy-BWX6z980.js";
|
|
3
|
+
import { a as ShutdownSignal, c as streamPath, i as requestUrl, l as securityHeaders, n as checkReadOptions, o as layerShutdownSignal, r as read, s as discardRequestBody, t as app } from "./program-DPq8FYrT.js";
|
|
4
4
|
import { Array, Effect, Option } from "effect";
|
|
5
5
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
6
6
|
// src/http/routes.ts
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as ReadNextResult, B as HeadError, C as StreamsReader, Ct as EncodeFault, D as CreateResult, E as AppendResult, Et as TransportFault, F as AppendErrorFor, G as InvalidReadRequest, K as NotSupported, N as AppendConflict, O as HeadResult, Q as RemoveError, R as CreateError, S as Reader, St as DecodeFault, T as Writer, Tt as StreamsFault, Z as ReadNextError, a as CommitHooks, at as AppendCallOptions, c as OwnerRecords, ct as ReadNextOptions, et as StreamBusy, lt as ReadOptions$1, n as ProjectionMarks, nt as StreamGone, q as OffsetMismatch, rt as StreamNotFound, st as ProducerOptions, tt as StreamClosed, u as Storage, ut as CreateOptions, w as StreamsWriter, wt as StorageFault, yt as StreamId } from "./projection-marks-OtKtjFLH.js";
|
|
2
2
|
import { Array, Context, Data, Duration, Effect, Function, Layer, Option, Schedule, Schema, Stream } from "effect";
|
|
3
3
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
4
4
|
import { SqlError } from "effect/sql";
|
|
@@ -249,9 +249,9 @@ declare namespace streams_d_exports$1 {
|
|
|
249
249
|
/** Options for `layer` and `layerProtocol`. */
|
|
250
250
|
interface Options extends MemoryOptions, ProtocolOptions {}
|
|
251
251
|
/** Generic reader and writer over memory storage, for protocol tools. */
|
|
252
|
-
declare const layerProtocol: (options?: Options) => Layer.Layer<CommitBoundary | OwnerRecords | Storage | StreamsReader | StreamsWriter, never, never>;
|
|
252
|
+
declare const layerProtocol: (options?: Options) => Layer.Layer<CommitBoundary | CommitHooks | OwnerRecords | ProjectionMarks | Storage | StreamsReader | StreamsWriter, never, never>;
|
|
253
253
|
/** Memory host. Streams and their feeds share the exposed storage boundary. */
|
|
254
|
-
declare function layer<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options?: Options): Layer.Layer<Storage | CommitBoundary | OwnerRecords | Host<Group<Keys>>>;
|
|
254
|
+
declare function layer<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options?: Options): Layer.Layer<Storage | CommitBoundary | OwnerRecords | CommitHooks | ProjectionMarks | Host<Group<Keys>>>;
|
|
255
255
|
declare namespace durable_state_d_exports {
|
|
256
256
|
export { Change, ChangeHeaders, Delete, Entry, Materialized, Rows, Upsert, changes, materialize, materialized, remove$1 as remove, upsert };
|
|
257
257
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { A as durable_state_d_exports, B as address_d_exports, C as FollowFailure, E as RemoveFailure, F as CommitBoundary, I as CommitBoundaryApi, L as ZERO_OFFSET, O as streamsy_d_exports, R as compare, S as Folded, T as ReadFailure, _ as Collected, b as Decided, g as Batch, h as AppendFailure, j as streams_d_exports, k as producer_d_exports, t as index_d_exports, v as CreateFailure, w as HeadFailure, x as Decision, y as DecideSpec } from "./index-
|
|
3
|
-
export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, type Batch, ChangeSnapshot, type Collected, CommitBoundary, type CommitBoundaryApi, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, Storage, StorageCapabilities, StorageFault, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
|
|
1
|
+
import { $ as StaleEpoch, A as ReadNextResult, B as HeadError, Ct as EncodeFault, D as CreateResult, Dt as isRetryableFault, E as AppendResult, Et as TransportFault, F as AppendErrorFor, G as InvalidReadRequest, H as InvalidCreateRequest, I as CreateConflict, J as ProducerGap, K as NotSupported, L as CreateConflictReason, M as AppendBaseError, N as AppendConflict, O as HeadResult, Ot as isStreamsFault, P as AppendError, Q as RemoveError, R as CreateError, St as DecodeFault, Tt as StreamsFault, U as InvalidEpochSeq, V as InvalidAppendRequest, W as InvalidForkRequest, X as ReadError, Y as ProtocolError, Z as ReadNextError, _ as OperationResult, _t as StoredMessage, at as AppendCallOptions, b as ProducerPrecondition, bt as StreamLifecycle, ct as ReadNextOptions, d as StorageShape, dt as ChangeSnapshot, et as StreamBusy, f as Mutation, ft as MessageWindow, g as Operation, gt as RecordPatch, h as Mutations, ht as ProducerState, it as isProtocolError, j as ReadResult, k as ReadMessage, lt as ReadOptions, m as MutationRejected, mt as ProducerId, nt as StreamGone, ot as AppendOptions, p as MutationApplied, pt as Offset, q as OffsetMismatch, rt as StreamNotFound, st as ProducerOptions, tt as StreamClosed, u as Storage, ut as CreateOptions, v as OperationResults, vt as StreamConfig, wt as StorageFault, x as StorageCapabilities, xt as StreamRecord, y as Operations, yt as StreamId, z as ForkSourceNotFound } from "./projection-marks-OtKtjFLH.js";
|
|
2
|
+
import { A as durable_state_d_exports, B as address_d_exports, C as FollowFailure, E as RemoveFailure, F as CommitBoundary, I as CommitBoundaryApi, L as ZERO_OFFSET, O as streamsy_d_exports, R as compare, S as Folded, T as ReadFailure, _ as Collected, b as Decided, g as Batch, h as AppendFailure, j as streams_d_exports, k as producer_d_exports, t as index_d_exports, v as CreateFailure, w as HeadFailure, x as Decision, y as DecideSpec } from "./index-DzptR3sL.js";
|
|
3
|
+
export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, type Batch, ChangeSnapshot, type Collected, CommitBoundary, type CommitBoundaryApi, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, Storage, StorageCapabilities, StorageFault, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { $ as
|
|
3
|
-
import { n as CommitBoundary, t as layer$1 } from "./layer-
|
|
4
|
-
import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$2, u as Operations } from "./layer-
|
|
5
|
-
import { t as http_exports } from "./http-
|
|
2
|
+
import { $ as ProducerState, A as StreamBusy, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, G as StreamsFault, H as DecodeFault, J as isStreamsFault, K as TransportFault, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, P as isProtocolError, Q as ProducerId, R as ZERO_OFFSET, S as InvalidCreateRequest, T as InvalidReadRequest, U as EncodeFault, W as StorageFault, X as MessageWindow, Y as ChangeSnapshot, Z as Offset, _ as CreateResult, a as custom, at as StreamRecord, b as ForkSourceNotFound, c as state, d as address_exports, et as RecordPatch, f as isControl, g as AppendResult, h as stateControl, it as StreamLifecycle, j as StreamClosed, k as StaleEpoch, m as stateChange, n as bind, nt as StreamConfig, o as group, p as isUpsert, q as isRetryableFault, r as bytes, rt as StreamId, s as json, t as Wildcard, tt as StoredMessage, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-BWX6z980.js";
|
|
3
|
+
import { n as CommitBoundary, t as layer$1 } from "./layer-VOzdazlb.js";
|
|
4
|
+
import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$2, u as Operations } from "./layer-B1JEYOZb.js";
|
|
5
|
+
import { t as http_exports } from "./http-CwDadGy6.js";
|
|
6
6
|
import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
|
|
7
7
|
// src/storage/capabilities.ts
|
|
8
8
|
const StorageCapabilities = Schema.Struct({
|
|
@@ -344,4 +344,4 @@ var streamsy_exports = /* @__PURE__ */ __exportAll({
|
|
|
344
344
|
wakeActions: () => wakeActions,
|
|
345
345
|
wakeCollections: () => wakeCollections
|
|
346
346
|
});
|
|
347
|
-
export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, Storage, StorageCapabilities, StorageFault, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
|
|
347
|
+
export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, Storage, StorageCapabilities, StorageFault, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
|
package/dist/internal/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as CommitHooks, c as OwnerRecords, i as CommitHook, l as OwnerRecordsApi, n as ProjectionMarks, o as CommitHooksApi, r as ProjectionMarksApi, s as commitHookRegistry, t as PendingMark } from "../projection-marks-OtKtjFLH.js";
|
|
2
2
|
import { Context, Effect } from "effect";
|
|
3
3
|
/** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
|
|
4
4
|
declare const ForeignOwnerType: unique symbol;
|
|
@@ -17,6 +17,19 @@ type Owner = object;
|
|
|
17
17
|
export declare const attachOwner: <A extends object>(value: A, owner: Owner) => A;
|
|
18
18
|
export declare const ownerOf: (value: object) => Owner;
|
|
19
19
|
export declare const CurrentOwner: Context.Reference<object | undefined>;
|
|
20
|
+
/**
|
|
21
|
+
* The MySQL producer key holds a stream id and at most this many producer id
|
|
22
|
+
* code points, so every storage dialect enforces it. Projections that build
|
|
23
|
+
* their own producer ids keep them within it.
|
|
24
|
+
*/
|
|
25
|
+
export declare const MAX_PRODUCER_ID_LENGTH = 255;
|
|
26
|
+
/**
|
|
27
|
+
* Fits `key` into `limit` code points. A key within the limit is returned as it is, so
|
|
28
|
+
* keys that storage already holds keep working. A longer key becomes the first code
|
|
29
|
+
* points of `readable`, then `#` and the SHA-256 hex of the full key. The result is at
|
|
30
|
+
* most `limit` code points, and exactly `limit` when `readable` is at least as long.
|
|
31
|
+
*/
|
|
32
|
+
export declare const fitKey: (key: string, limit: number, readable?: string) => Effect.Effect<string>;
|
|
20
33
|
/**
|
|
21
34
|
* Compile output shared by `StreamRoute` and stream validation.
|
|
22
35
|
*
|
|
@@ -40,4 +53,4 @@ interface TemplateGrammar<Template extends string = string> {
|
|
|
40
53
|
readonly names: ReadonlyArray<string>;
|
|
41
54
|
}
|
|
42
55
|
export declare function compileSegments<const Template extends string>(template: Template): TemplateGrammar<Template>;
|
|
43
|
-
export { OwnerRecords, type OwnerRecordsApi };
|
|
56
|
+
export { type CommitHook, CommitHooks, type CommitHooksApi, OwnerRecords, type OwnerRecordsApi, type PendingMark, ProjectionMarks, type ProjectionMarksApi, commitHookRegistry };
|
package/dist/internal/index.js
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
1
|
import { a as attachOwner, c as isForeignOwner, i as CurrentOwner, l as ownerOf, t as compileSegments } from "../route-internal-DNL0oGTN.js";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { i as OwnerRecords, n as CommitHooks, r as commitHookRegistry, t as ProjectionMarks } from "../projection-marks-RqurLPLA.js";
|
|
3
|
+
import { Array, Effect } from "effect";
|
|
4
|
+
// src/internal/limits.ts
|
|
5
|
+
/**
|
|
6
|
+
* The MySQL producer key holds a stream id and at most this many producer id
|
|
7
|
+
* code points, so every storage dialect enforces it. Projections that build
|
|
8
|
+
* their own producer ids keep them within it.
|
|
9
|
+
*/
|
|
10
|
+
const MAX_PRODUCER_ID_LENGTH = 255;
|
|
11
|
+
// src/internal/fit-key.ts
|
|
12
|
+
/** `#` and the 64 hex digits of a SHA-256 end a hashed key. */
|
|
13
|
+
const DIGEST_LENGTH = 65;
|
|
14
|
+
const codePoints = (value) => [...value];
|
|
15
|
+
/** WebCrypto is the SHA-256 that Bun, Node, workerd and browsers all provide. */
|
|
16
|
+
const sha256Hex = (value) => Effect.promise(() => globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))).pipe(Effect.map((digest) => Array.join(Array.map(Array.fromIterable(new Uint8Array(digest)), (byte) => byte.toString(16).padStart(2, "0")), "")));
|
|
17
|
+
/**
|
|
18
|
+
* Fits `key` into `limit` code points. A key within the limit is returned as it is, so
|
|
19
|
+
* keys that storage already holds keep working. A longer key becomes the first code
|
|
20
|
+
* points of `readable`, then `#` and the SHA-256 hex of the full key. The result is at
|
|
21
|
+
* most `limit` code points, and exactly `limit` when `readable` is at least as long.
|
|
22
|
+
*/
|
|
23
|
+
const fitKey = (key, limit, readable = key) => {
|
|
24
|
+
if (codePoints(key).length <= limit) return Effect.succeed(key);
|
|
25
|
+
const prefix = Array.join(Array.take(codePoints(readable), limit - DIGEST_LENGTH), "");
|
|
26
|
+
return Effect.map(sha256Hex(key), (digest) => `${prefix}#${digest}`);
|
|
27
|
+
};
|
|
28
|
+
export { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OwnerRecords, ProjectionMarks, attachOwner, commitHookRegistry, compileSegments, fitKey, isForeignOwner, ownerOf };
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { $ as
|
|
2
|
+
import { $ as ProducerState, A as StreamBusy, B as isValid, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, F as StreamsReader, I as StreamsWriter, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, Q as ProducerId, R as ZERO_OFFSET, T as InvalidReadRequest, V as next, Z as Offset, _ as CreateResult, at as StreamRecord, b as ForkSourceNotFound, et as RecordPatch, g as AppendResult, j as StreamClosed, k as StaleEpoch, n as bind, rt as StreamId, tt as StoredMessage, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-BWX6z980.js";
|
|
3
3
|
import { o as attachStorage } from "./route-internal-DNL0oGTN.js";
|
|
4
|
+
import { n as validateCreateOptions, r as frameMessages, t as frameCreateMessages } from "./create-validation-Dwx1OQAN.js";
|
|
4
5
|
import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
|
|
5
|
-
import { Array, Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Schema, Stream } from "effect";
|
|
6
|
+
import { Array, Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Result, Schema, Stream } from "effect";
|
|
6
7
|
// src/storage/mutation.ts
|
|
7
8
|
const ProducerPrecondition = Schema.Struct({
|
|
8
9
|
producerId: ProducerId,
|
|
@@ -105,31 +106,6 @@ function isExpired(record, now) {
|
|
|
105
106
|
const at = record.lifecycle.expiresAtMs;
|
|
106
107
|
return at !== void 0 && at <= now;
|
|
107
108
|
}
|
|
108
|
-
// src/policy/message-framer.ts
|
|
109
|
-
/**
|
|
110
|
-
* Body framing for the durable streams protocol.
|
|
111
|
-
*
|
|
112
|
-
* Responsibilities:
|
|
113
|
-
*
|
|
114
|
-
* - Non-JSON content types pass the original bytes through as a single
|
|
115
|
-
* message.
|
|
116
|
-
* - JSON content types are decoded and re-encoded:
|
|
117
|
-
* - JSON object input becomes one canonical `JSON.stringify(parsed)` message.
|
|
118
|
-
* - JSON array input produces one message per item.
|
|
119
|
-
* - Empty JSON array produces zero messages.
|
|
120
|
-
* - The JSON branch is selected by `contentType.toLowerCase().startsWith("application/json")`,
|
|
121
|
-
* without parameter stripping.
|
|
122
|
-
* - Invalid JSON propagates the underlying `JSON.parse` error.
|
|
123
|
-
*
|
|
124
|
-
* Used by `AppendService`, `CreateStreamService`, and `ForkPlanBuilder` before
|
|
125
|
-
* incoming request bodies are persisted as stored messages.
|
|
126
|
-
*/
|
|
127
|
-
function frameMessages(data, contentType) {
|
|
128
|
-
if (!contentType.toLowerCase().startsWith("application/json")) return [data];
|
|
129
|
-
const parsed = JSON.parse(new TextDecoder().decode(data));
|
|
130
|
-
if (Array.isArray(parsed)) return parsed.length === 0 ? [] : Array.map(parsed, (item) => new TextEncoder().encode(JSON.stringify(item)));
|
|
131
|
-
return [new TextEncoder().encode(JSON.stringify(parsed))];
|
|
132
|
-
}
|
|
133
109
|
// src/policy/fork-plan-builder.ts
|
|
134
110
|
/** Fork-side validation and plan building. */
|
|
135
111
|
const ForkBuildResult = Data.taggedEnum();
|
|
@@ -188,7 +164,12 @@ var ForkPlanBuilder = class {
|
|
|
188
164
|
...options,
|
|
189
165
|
...expiry
|
|
190
166
|
}, fork);
|
|
191
|
-
const
|
|
167
|
+
const framed = frameCreateMessages(targetId, options.initialData, contentType);
|
|
168
|
+
if (Result.isFailure(framed)) return ForkBuildResult.Rejected({ error: new InvalidForkRequest({
|
|
169
|
+
id: targetId,
|
|
170
|
+
message: framed.failure.message
|
|
171
|
+
}) });
|
|
172
|
+
const initialMessages = this.initialMessages([...prefix.messages, ...framed.success], baseRecord.currentOffset);
|
|
192
173
|
const child = this.withInitialTail(baseRecord, initialMessages);
|
|
193
174
|
const plan = Operations.Create({
|
|
194
175
|
record: child,
|
|
@@ -226,8 +207,7 @@ var ForkPlanBuilder = class {
|
|
|
226
207
|
if (subOffset > first.data.byteLength) return ForkPrefix.Invalid({ errorMessage: "Stream-Fork-Sub-Offset exceeds source message length" });
|
|
227
208
|
return ForkPrefix.Prefix({ messages: [first.data.subarray(0, subOffset)] });
|
|
228
209
|
}
|
|
229
|
-
initialMessages(
|
|
230
|
-
const framed = [...prefix, ...initialData ? frameMessages(initialData, contentType) : []];
|
|
210
|
+
initialMessages(framed, previousOffset) {
|
|
231
211
|
let offset = previousOffset;
|
|
232
212
|
const now = this.deps.clock.now();
|
|
233
213
|
return Array.map(framed, (data) => {
|
|
@@ -328,6 +308,7 @@ const existingResult = Effect.fn("Protocol.existingResult")(function* (record, o
|
|
|
328
308
|
});
|
|
329
309
|
});
|
|
330
310
|
const create = Effect.fn("Protocol.create")(function* (storage, id, options = {}) {
|
|
311
|
+
yield* validateCreateOptions(id, options);
|
|
331
312
|
if (options.forkedFrom !== void 0 && storage.capabilities.fork === "none") return yield* new NotSupported({
|
|
332
313
|
id,
|
|
333
314
|
feature: "fork"
|
|
@@ -358,7 +339,8 @@ const create = Effect.fn("Protocol.create")(function* (storage, id, options = {}
|
|
|
358
339
|
const type = options.contentType ?? "application/octet-stream";
|
|
359
340
|
const record = newRecord(id, type, options, now);
|
|
360
341
|
let offset = record.currentOffset;
|
|
361
|
-
const
|
|
342
|
+
const framed = yield* Effect.fromResult(frameCreateMessages(id, options.initialData, type));
|
|
343
|
+
const initialMessages = Array.map(framed, (data) => ({
|
|
362
344
|
data,
|
|
363
345
|
offset: offset = next(offset),
|
|
364
346
|
timestamp: now
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-
|
|
1
|
+
import { L as Storage, R as ZERO_OFFSET } from "./streamsy-BWX6z980.js";
|
|
2
|
+
import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-B1JEYOZb.js";
|
|
3
3
|
import { a as attachOwner, l as ownerOf } from "./route-internal-DNL0oGTN.js";
|
|
4
|
-
import {
|
|
4
|
+
import { i as OwnerRecords, n as CommitHooks, r as commitHookRegistry, t as ProjectionMarks } from "./projection-marks-RqurLPLA.js";
|
|
5
5
|
import { Array, Context, Effect, Layer, Option, Order, Predicate, PubSub, Queue, Schedule, Semaphore, Stream } from "effect";
|
|
6
6
|
// src/storage/commit-boundary.ts
|
|
7
7
|
/** The transaction of the storage owner. Every Streamsy storage host provides it. */
|
|
@@ -142,12 +142,73 @@ const createNotifier = Effect.gen(function* () {
|
|
|
142
142
|
})
|
|
143
143
|
};
|
|
144
144
|
});
|
|
145
|
+
// src/storage/memory/marks.ts
|
|
146
|
+
/** A private transaction draft of the marks. */
|
|
147
|
+
const copyMarks = (marks) => new Map(Array.map([...marks], ([projection, rows]) => [projection, new Map(rows)]));
|
|
148
|
+
const rowsOf = (marks, projection) => {
|
|
149
|
+
const found = marks.get(projection);
|
|
150
|
+
if (found !== void 0) return found;
|
|
151
|
+
const rows = /* @__PURE__ */ new Map();
|
|
152
|
+
marks.set(projection, rows);
|
|
153
|
+
return rows;
|
|
154
|
+
};
|
|
155
|
+
const byDue = Order.mapInput(Order.Tuple([Order.Number, Order.String]), (mark) => [mark.dueAt, mark.params]);
|
|
156
|
+
const mark = (marks, projection, params) => {
|
|
157
|
+
const rows = rowsOf(marks, projection);
|
|
158
|
+
for (const value of params) {
|
|
159
|
+
const found = rows.get(value);
|
|
160
|
+
rows.set(value, found === void 0 ? {
|
|
161
|
+
params: value,
|
|
162
|
+
seq: 1,
|
|
163
|
+
attempts: 0,
|
|
164
|
+
dueAt: 0
|
|
165
|
+
} : {
|
|
166
|
+
...found,
|
|
167
|
+
seq: found.seq + 1
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const nextDue = (marks, projection) => {
|
|
172
|
+
let earliest;
|
|
173
|
+
for (const row of marks.get(projection)?.values() ?? []) earliest = earliest === void 0 ? row.dueAt : Math.min(earliest, row.dueAt);
|
|
174
|
+
return Option.fromUndefinedOr(earliest);
|
|
175
|
+
};
|
|
176
|
+
const due = (marks, projection, now, limit) => Array.sort(Array.filter([...marks.get(projection)?.values() ?? []], (row) => row.dueAt <= now), byDue).slice(0, limit);
|
|
177
|
+
const read = (marks, projection, params) => {
|
|
178
|
+
const rows = marks.get(projection);
|
|
179
|
+
const found = /* @__PURE__ */ new Map();
|
|
180
|
+
for (const value of params) {
|
|
181
|
+
const row = rows?.get(value);
|
|
182
|
+
if (row !== void 0) found.set(value, row);
|
|
183
|
+
}
|
|
184
|
+
return found;
|
|
185
|
+
};
|
|
186
|
+
const clear = (marks, projection, params, seq) => {
|
|
187
|
+
const rows = marks.get(projection);
|
|
188
|
+
if (rows?.get(params)?.seq === seq) rows.delete(params);
|
|
189
|
+
};
|
|
190
|
+
const remove = (marks, projection, params) => {
|
|
191
|
+
marks.get(projection)?.delete(params);
|
|
192
|
+
};
|
|
193
|
+
const defer = (marks, projection, params, attempts, dueAt) => {
|
|
194
|
+
const rows = rowsOf(marks, projection);
|
|
195
|
+
const found = rows.get(params);
|
|
196
|
+
rows.set(params, {
|
|
197
|
+
params,
|
|
198
|
+
seq: found?.seq ?? 1,
|
|
199
|
+
attempts,
|
|
200
|
+
dueAt
|
|
201
|
+
});
|
|
202
|
+
};
|
|
203
|
+
const deferred = (marks, projection) => Array.filter([...marks.get(projection)?.values() ?? []], (row) => row.attempts > 0).length;
|
|
145
204
|
// src/storage/memory/boundary.ts
|
|
146
205
|
var ActiveDraft = class extends Context.Service()("@streamsy/core/internal/MemoryActiveDraft") {};
|
|
147
206
|
const makeBoundary = (committed, publish) => Effect.gen(function* () {
|
|
148
207
|
const owner = {};
|
|
149
208
|
const lock = yield* Semaphore.make(1);
|
|
150
209
|
let committedRecords = /* @__PURE__ */ new Map();
|
|
210
|
+
let committedMarks = /* @__PURE__ */ new Map();
|
|
211
|
+
const hooks = commitHookRegistry();
|
|
151
212
|
const current = Effect.flatMap(Effect.serviceOption(ActiveDraft), (draft) => Effect.withFiber((fiber) => {
|
|
152
213
|
if (Option.isSome(draft) && (draft.value.owner !== owner || !draft.value.active || draft.value.fiberId !== fiber.id)) return Effect.die(/* @__PURE__ */ new Error("Memory boundary requires the active owner fiber"));
|
|
153
214
|
return Effect.succeed(draft);
|
|
@@ -160,13 +221,16 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
|
|
|
160
221
|
fiberId: fiber.id,
|
|
161
222
|
state: copyState(committed),
|
|
162
223
|
records: new Map(committedRecords),
|
|
224
|
+
marks: copyMarks(committedMarks),
|
|
163
225
|
ids: /* @__PURE__ */ new Set(),
|
|
164
226
|
active: true,
|
|
165
227
|
changed: false
|
|
166
228
|
};
|
|
167
|
-
|
|
229
|
+
const withHooks = body.pipe(Effect.tap(() => Effect.orDie(hooks.run(draft.ids))), Effect.provideService(ActiveDraft, draft));
|
|
230
|
+
return Effect.uninterruptibleMask((restore) => restore(withHooks).pipe(Effect.tap(() => Effect.sync(() => {
|
|
168
231
|
Object.assign(committed, draft.state);
|
|
169
232
|
committedRecords = draft.records;
|
|
233
|
+
committedMarks = draft.marks;
|
|
170
234
|
}).pipe(Effect.andThen(Effect.suspend(() => draft.changed ? publish(draft.ids) : Effect.void)))), Effect.ensuring(Effect.sync(() => {
|
|
171
235
|
draft.active = false;
|
|
172
236
|
}))));
|
|
@@ -190,9 +254,26 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
|
|
|
190
254
|
draft.value.records.set(key, encoded);
|
|
191
255
|
}))
|
|
192
256
|
});
|
|
257
|
+
const readMarks = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.marks : committedMarks));
|
|
258
|
+
const writeMarks = (f) => withTransaction(Effect.map(current, (draft) => {
|
|
259
|
+
if (Option.isNone(draft)) throw new Error("Memory mark write requires an owner");
|
|
260
|
+
f(draft.value.marks);
|
|
261
|
+
}));
|
|
262
|
+
const marks = ProjectionMarks.of({
|
|
263
|
+
mark: (projection, params) => writeMarks((table) => mark(table, projection, params)),
|
|
264
|
+
nextDue: (projection) => readMarks((table) => nextDue(table, projection)),
|
|
265
|
+
due: (projection, now, limit) => readMarks((table) => due(table, projection, now, limit)),
|
|
266
|
+
read: (projection, params) => readMarks((table) => read(table, projection, params)),
|
|
267
|
+
clear: (projection, params, seq) => writeMarks((table) => clear(table, projection, params, seq)),
|
|
268
|
+
remove: (projection, params) => writeMarks((table) => remove(table, projection, params)),
|
|
269
|
+
defer: (projection, params, attempts, dueAt) => writeMarks((table) => defer(table, projection, params, attempts, dueAt)),
|
|
270
|
+
deferred: (projection) => readMarks((table) => deferred(table, projection))
|
|
271
|
+
});
|
|
193
272
|
return {
|
|
194
273
|
boundary: attachOwner(boundary, owner),
|
|
274
|
+
marks: attachOwner(marks, owner),
|
|
195
275
|
records: attachOwner(records, owner),
|
|
276
|
+
hooks: attachOwner(CommitHooks.of({ beforeCommit: hooks.beforeCommit }), owner),
|
|
196
277
|
withTransaction,
|
|
197
278
|
access,
|
|
198
279
|
changed
|
|
@@ -339,6 +420,6 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
|
|
|
339
420
|
committed: PubSub.subscribe(feed),
|
|
340
421
|
nextExpiry: owner.access((state) => Option.fromUndefinedOr(state.deadlines[0]).pipe(Option.map((deadline) => ({ ...deadline }))))
|
|
341
422
|
});
|
|
342
|
-
return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records));
|
|
423
|
+
return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records), Context.add(CommitHooks, owner.hooks), Context.add(ProjectionMarks, owner.marks));
|
|
343
424
|
}));
|
|
344
425
|
export { CommitBoundary as n, layer as t };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { F as
|
|
2
|
+
import { B as isValid, F as StreamsReader, I as StreamsWriter, P as isProtocolError, _ as CreateResult, g as AppendResult, rt as StreamId } from "./streamsy-BWX6z980.js";
|
|
3
3
|
import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
|
|
4
4
|
import { Array, Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Record, Ref, Schedule, Stream } from "effect";
|
|
5
5
|
import { HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
@@ -683,6 +683,7 @@ function protocolErrorResponse(error, context) {
|
|
|
683
683
|
AppendConflict: conflict,
|
|
684
684
|
InvalidReadRequest: badRequest,
|
|
685
685
|
InvalidForkRequest: badRequest,
|
|
686
|
+
InvalidCreateRequest: badRequest,
|
|
686
687
|
InvalidAppendRequest: badRequest,
|
|
687
688
|
StreamClosed: ({ offset }) => responses$1.empty(409, {
|
|
688
689
|
"stream-closed": "true",
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Context, Data, Effect, Option, PubSub, Schema, Scope, Stream } from "effect";
|
|
2
|
+
import { SqlError } from "effect/sql";
|
|
2
3
|
declare const StorageFault_base: Schema.Class<StorageFault, Schema.TaggedStruct<"StorageFault", {
|
|
3
4
|
readonly operation: Schema.String;
|
|
4
5
|
readonly message: Schema.String;
|
|
@@ -235,6 +236,11 @@ declare const InvalidAppendRequest_base: Schema.Class<InvalidAppendRequest, Sche
|
|
|
235
236
|
readonly message: Schema.String;
|
|
236
237
|
}>, import("effect/Cause").YieldableError>;
|
|
237
238
|
declare class InvalidAppendRequest extends InvalidAppendRequest_base {}
|
|
239
|
+
declare const InvalidCreateRequest_base: Schema.Class<InvalidCreateRequest, Schema.TaggedStruct<"InvalidCreateRequest", {
|
|
240
|
+
readonly id: Schema.brand<Schema.String, "StreamId">;
|
|
241
|
+
readonly message: Schema.String;
|
|
242
|
+
}>, import("effect/Cause").YieldableError>;
|
|
243
|
+
declare class InvalidCreateRequest extends InvalidCreateRequest_base {}
|
|
238
244
|
declare const CreateConflict_base: Schema.Class<CreateConflict, Schema.TaggedStruct<"CreateConflict", {
|
|
239
245
|
readonly id: Schema.brand<Schema.String, "StreamId">;
|
|
240
246
|
readonly reason: Schema.optionalKey<Schema.Literals<readonly ["config-mismatch", "soft-deleted", "fork-content-type", "fork-source-soft-deleted"]>>;
|
|
@@ -269,7 +275,7 @@ declare const InvalidReadRequest_base: Schema.Class<InvalidReadRequest, Schema.T
|
|
|
269
275
|
declare class InvalidReadRequest extends InvalidReadRequest_base {}
|
|
270
276
|
type ReadError = StreamNotFound | StreamGone | InvalidReadRequest;
|
|
271
277
|
type ReadNextError = ReadError | NotSupported;
|
|
272
|
-
type CreateError = CreateConflict | ForkSourceNotFound | InvalidForkRequest | NotSupported;
|
|
278
|
+
type CreateError = CreateConflict | InvalidCreateRequest | ForkSourceNotFound | InvalidForkRequest | NotSupported;
|
|
273
279
|
/**
|
|
274
280
|
* Append rejections that any call can get, whatever its options. The memory and
|
|
275
281
|
* storage hosts never answer `NotSupported`; the remote client does when the server
|
|
@@ -2947,4 +2953,72 @@ interface OwnerRecordsApi {
|
|
|
2947
2953
|
}
|
|
2948
2954
|
declare const OwnerRecords_base: Context.ServiceClass<OwnerRecords, "@streamsy/core/internal/OwnerRecords", OwnerRecordsApi>;
|
|
2949
2955
|
declare class OwnerRecords extends OwnerRecords_base {}
|
|
2950
|
-
|
|
2956
|
+
/**
|
|
2957
|
+
* Work that joins an owned transaction just before it commits. It receives the
|
|
2958
|
+
* stream ids that the transaction created, appended to or deleted.
|
|
2959
|
+
*/
|
|
2960
|
+
type CommitHook = (ids: ReadonlySet<StreamId>) => Effect.Effect<void, SqlError.SqlError>;
|
|
2961
|
+
/**
|
|
2962
|
+
* Commit hooks on the storage owner, for the durable projection marks.
|
|
2963
|
+
*
|
|
2964
|
+
* A hook runs inside each later owned transaction that wrote at least one stream
|
|
2965
|
+
* id, after the body and before COMMIT. Statements in the hook join the
|
|
2966
|
+
* transaction, and a hook failure rolls the transaction back. A SQL host treats
|
|
2967
|
+
* a hook failure like a body failure, so a retryable `SqlError` replays the
|
|
2968
|
+
* whole transaction, hook included. The memory host turns a hook failure into a
|
|
2969
|
+
* defect. A hook must not write streams: its ids would not reach other hooks.
|
|
2970
|
+
*/
|
|
2971
|
+
interface CommitHooksApi {
|
|
2972
|
+
/** Register `hook` until the scope closes. */
|
|
2973
|
+
readonly beforeCommit: (hook: CommitHook) => Effect.Effect<void, never, Scope.Scope>;
|
|
2974
|
+
}
|
|
2975
|
+
declare const CommitHooks_base: Context.ServiceClass<CommitHooks, "@streamsy/core/internal/CommitHooks", CommitHooksApi>;
|
|
2976
|
+
declare class CommitHooks extends CommitHooks_base {}
|
|
2977
|
+
/** Shared registry for storage boundaries: register in a scope, run in order. */
|
|
2978
|
+
declare const commitHookRegistry: () => {
|
|
2979
|
+
beforeCommit: (hook: CommitHook) => Effect.Effect<void, never, Scope.Scope>;
|
|
2980
|
+
run: (ids: ReadonlySet<StreamId>) => Effect.Effect<void, SqlError.SqlError>;
|
|
2981
|
+
};
|
|
2982
|
+
/** One pending mark: a binding whose input has commits that may not have run. */
|
|
2983
|
+
interface PendingMark {
|
|
2984
|
+
/** The binding's canonical params, as `canonicalParams` encodes them. */
|
|
2985
|
+
readonly params: string;
|
|
2986
|
+
/** Raised by every mark. A clear only deletes the row when its `seq` still matches. */
|
|
2987
|
+
readonly seq: number;
|
|
2988
|
+
/** Failed runs since the last success. A mark keeps it. */
|
|
2989
|
+
readonly attempts: number;
|
|
2990
|
+
/** Epoch ms. 0 means due now. */
|
|
2991
|
+
readonly dueAt: number;
|
|
2992
|
+
}
|
|
2993
|
+
/**
|
|
2994
|
+
* Durable pending marks on the storage owner, for attached projections.
|
|
2995
|
+
*
|
|
2996
|
+
* A mark is keyed by projection id and canonical params. Version and generation
|
|
2997
|
+
* are left out, so a deploy that raises the version picks up the old marks.
|
|
2998
|
+
*/
|
|
2999
|
+
interface ProjectionMarksApi {
|
|
3000
|
+
/**
|
|
3001
|
+
* Insert a mark for each binding, or raise its `seq`. A raise keeps
|
|
3002
|
+
* `attempts` and `dueAt`, so a write does not reset a binding's backoff.
|
|
3003
|
+
* Call it inside a commit hook. It joins the transaction and fails like the
|
|
3004
|
+
* transaction's own statements.
|
|
3005
|
+
*/
|
|
3006
|
+
readonly mark: (projection: string, params: ReadonlyArray<string>) => Effect.Effect<void, SqlError.SqlError>;
|
|
3007
|
+
/** The earliest `dueAt` of the projection's marks. */
|
|
3008
|
+
readonly nextDue: (projection: string) => Effect.Effect<Option.Option<number>, StorageFault>;
|
|
3009
|
+
/** Up to `limit` marks with `dueAt <= now`, earliest first. */
|
|
3010
|
+
readonly due: (projection: string, now: number, limit: number) => Effect.Effect<ReadonlyArray<PendingMark>, StorageFault>;
|
|
3011
|
+
/** The marks of these bindings that exist, keyed by params. */
|
|
3012
|
+
readonly read: (projection: string, params: ReadonlyArray<string>) => Effect.Effect<ReadonlyMap<string, PendingMark>, StorageFault>;
|
|
3013
|
+
/** Delete the mark if its `seq` still equals `seq`. A later mark keeps the row. */
|
|
3014
|
+
readonly clear: (projection: string, params: string, seq: number) => Effect.Effect<void, StorageFault>;
|
|
3015
|
+
/** Delete the mark whatever its `seq`. */
|
|
3016
|
+
readonly remove: (projection: string, params: string) => Effect.Effect<void, StorageFault>;
|
|
3017
|
+
/** Set `attempts` and `dueAt`, and insert the mark if it is absent. */
|
|
3018
|
+
readonly defer: (projection: string, params: string, attempts: number, dueAt: number) => Effect.Effect<void, StorageFault>;
|
|
3019
|
+
/** The number of the projection's marks with at least one failed attempt. */
|
|
3020
|
+
readonly deferred: (projection: string) => Effect.Effect<number, StorageFault>;
|
|
3021
|
+
}
|
|
3022
|
+
declare const ProjectionMarks_base: Context.ServiceClass<ProjectionMarks, "@streamsy/core/internal/ProjectionMarks", ProjectionMarksApi>;
|
|
3023
|
+
declare class ProjectionMarks extends ProjectionMarks_base {}
|
|
3024
|
+
export { StaleEpoch as $, ReadNextResult as A, HeadError as B, StreamsReader as C, EncodeFault as Ct, CreateResult as D, isRetryableFault as Dt, AppendResult as E, TransportFault as Et, AppendErrorFor as F, InvalidReadRequest as G, InvalidCreateRequest as H, CreateConflict as I, ProducerGap as J, NotSupported as K, CreateConflictReason as L, AppendBaseError as M, AppendConflict as N, HeadResult as O, isStreamsFault as Ot, AppendError as P, RemoveError as Q, CreateError as R, Reader as S, DecodeFault as St, Writer as T, StreamsFault as Tt, InvalidEpochSeq as U, InvalidAppendRequest as V, InvalidForkRequest as W, ReadError as X, ProtocolError as Y, ReadNextError as Z, OperationResult as _, StoredMessage as _t, CommitHooks as a, AppendCallOptions as at, ProducerPrecondition as b, StreamLifecycle as bt, OwnerRecords as c, ReadNextOptions as ct, StorageShape as d, ChangeSnapshot as dt, StreamBusy as et, Mutation as f, MessageWindow as ft, Operation as g, RecordPatch as gt, Mutations as h, ProducerState as ht, CommitHook as i, isProtocolError as it, ReadResult as j, ReadMessage as k, OwnerRecordsApi as l, ReadOptions as lt, MutationRejected as m, ProducerId as mt, ProjectionMarks as n, StreamGone as nt, CommitHooksApi as o, AppendOptions as ot, MutationApplied as p, Offset as pt, OffsetMismatch as q, ProjectionMarksApi as r, StreamNotFound as rt, commitHookRegistry as s, ProducerOptions as st, PendingMark as t, StreamClosed as tt, Storage as u, CreateOptions as ut, OperationResults as v, StreamConfig as vt, StreamsWriter as w, StorageFault as wt, StorageCapabilities as x, StreamRecord as xt, Operations as y, StreamId as yt, ForkSourceNotFound as z };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { Context, Effect } from "effect";
|
|
2
|
+
// src/internal/owner-records.ts
|
|
3
|
+
var OwnerRecords = class extends Context.Service()("@streamsy/core/internal/OwnerRecords") {};
|
|
4
|
+
// src/internal/commit-hooks.ts
|
|
5
|
+
var CommitHooks = class extends Context.Service()("@streamsy/core/internal/CommitHooks") {};
|
|
6
|
+
/** Shared registry for storage boundaries: register in a scope, run in order. */
|
|
7
|
+
const commitHookRegistry = () => {
|
|
8
|
+
const hooks = /* @__PURE__ */ new Set();
|
|
9
|
+
const beforeCommit = (hook) => Effect.acquireRelease(Effect.sync(() => {
|
|
10
|
+
const entry = { hook };
|
|
11
|
+
hooks.add(entry);
|
|
12
|
+
return entry;
|
|
13
|
+
}), (entry) => Effect.sync(() => {
|
|
14
|
+
hooks.delete(entry);
|
|
15
|
+
})).pipe(Effect.asVoid);
|
|
16
|
+
const run = (ids) => ids.size === 0 || hooks.size === 0 ? Effect.void : Effect.forEach([...hooks], (entry) => entry.hook(ids), { discard: true });
|
|
17
|
+
return {
|
|
18
|
+
beforeCommit,
|
|
19
|
+
run
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
// src/internal/projection-marks.ts
|
|
23
|
+
var ProjectionMarks = class extends Context.Service()("@streamsy/core/internal/ProjectionMarks") {};
|
|
24
|
+
export { OwnerRecords as i, CommitHooks as n, commitHookRegistry as r, ProjectionMarks as t };
|
package/dist/protocol/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-
|
|
1
|
+
import { C as StreamsReader, S as Reader, T as Writer, w as StreamsWriter } from "../projection-marks-OtKtjFLH.js";
|
|
2
|
+
import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-DzptR3sL.js";
|
|
3
3
|
import { HttpRouter } from "effect/http";
|
|
4
4
|
/** Raw protocol route for adapters and wire conformance tests. */
|
|
5
5
|
export declare const routes: (options?: Omit<RoutesOptions, "access">) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", StreamsReader> | HttpRouter.Request<"Requires", StreamsWriter>>;
|
package/dist/protocol/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { F as
|
|
2
|
-
import { n as layer_exports } from "../layer-
|
|
3
|
-
import { t as app } from "../program-
|
|
1
|
+
import { F as StreamsReader, I as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-BWX6z980.js";
|
|
2
|
+
import { n as layer_exports } from "../layer-B1JEYOZb.js";
|
|
3
|
+
import { t as app } from "../program-DPq8FYrT.js";
|
|
4
4
|
import { HttpRouter } from "effect/http";
|
|
5
5
|
// src/protocol/routes.ts
|
|
6
6
|
/** Raw protocol route for adapters and wire conformance tests. */
|
package/dist/remote/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { f as Any, m as Identifiers, p as Group } from "../index-
|
|
1
|
+
import { C as StreamsReader, Et as TransportFault, w as StreamsWriter } from "../projection-marks-OtKtjFLH.js";
|
|
2
|
+
import { f as Any, m as Identifiers, p as Group } from "../index-DzptR3sL.js";
|
|
3
3
|
import { Layer } from "effect";
|
|
4
4
|
import { HttpClient, HttpClientRequest } from "effect/http";
|
|
5
5
|
interface Options {
|
package/dist/remote/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "../rolldown-runtime-D8jQpDG7.js";
|
|
2
|
-
import { A as
|
|
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-BWX6z980.js";
|
|
3
|
+
import { n as validateCreateOptions } from "../create-validation-Dwx1OQAN.js";
|
|
3
4
|
import { Array, Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
|
|
4
5
|
import { HttpClient, HttpClientRequest } from "effect/http";
|
|
5
6
|
// src/remote/request.ts
|
|
@@ -187,6 +188,10 @@ const create = (operation, response, context) => Effect.gen(function* () {
|
|
|
187
188
|
feature
|
|
188
189
|
});
|
|
189
190
|
const message = emptyToUndefined(yield* bodyText(operation, response));
|
|
191
|
+
if (context.source === void 0) return yield* new InvalidCreateRequest({
|
|
192
|
+
id: context.id,
|
|
193
|
+
message: message ?? "Invalid create parameters"
|
|
194
|
+
});
|
|
190
195
|
return yield* new InvalidForkRequest({
|
|
191
196
|
id: context.id,
|
|
192
197
|
message: message ?? "Invalid fork parameters"
|
|
@@ -388,17 +393,17 @@ const layerProtocol = (options) => Layer.effectContext(Effect.gen(function* () {
|
|
|
388
393
|
}))
|
|
389
394
|
};
|
|
390
395
|
return Context.make(StreamsReader, reader).pipe(Context.add(StreamsWriter, {
|
|
391
|
-
create: (id, input) => execute("create", () => request.create(id, input), (operation, response) => create(operation, response, {
|
|
396
|
+
create: (id, input) => validateCreateOptions(id, input).pipe(Effect.andThen(execute("create", () => request.create(id, input), (operation, response) => create(operation, response, {
|
|
392
397
|
id,
|
|
393
398
|
source: input?.forkedFrom === void 0 ? void 0 : StreamId.make(input.forkedFrom)
|
|
394
|
-
})),
|
|
395
|
-
fork: (id, source, input) => execute("create", () => request.create(id, {
|
|
399
|
+
})))),
|
|
400
|
+
fork: (id, source, input) => validateCreateOptions(id, input).pipe(Effect.andThen(execute("create", () => request.create(id, {
|
|
396
401
|
...input,
|
|
397
402
|
forkedFrom: source
|
|
398
403
|
}), (operation, response) => create(operation, response, {
|
|
399
404
|
id,
|
|
400
405
|
source
|
|
401
|
-
})),
|
|
406
|
+
})))),
|
|
402
407
|
append: (id, input) => {
|
|
403
408
|
if (input.expectedOffset !== void 0 && options.capabilities?.expectedOffset !== true) return Effect.fail(new NotSupported({
|
|
404
409
|
id,
|
|
@@ -184,6 +184,10 @@ var InvalidAppendRequest = class extends Schema.TaggedError()("InvalidAppendRequ
|
|
|
184
184
|
id: StreamId,
|
|
185
185
|
message: Schema.String
|
|
186
186
|
}) {};
|
|
187
|
+
var InvalidCreateRequest = class extends Schema.TaggedError()("InvalidCreateRequest", {
|
|
188
|
+
id: StreamId,
|
|
189
|
+
message: Schema.String
|
|
190
|
+
}) {};
|
|
187
191
|
var CreateConflict = class extends Schema.TaggedError()("CreateConflict", {
|
|
188
192
|
id: StreamId,
|
|
189
193
|
reason: Schema.optionalKey(Schema.Literals([
|
|
@@ -231,6 +235,7 @@ const protocolErrorTags = {
|
|
|
231
235
|
ProducerGap: true,
|
|
232
236
|
InvalidEpochSeq: true,
|
|
233
237
|
InvalidAppendRequest: true,
|
|
238
|
+
InvalidCreateRequest: true,
|
|
234
239
|
CreateConflict: true,
|
|
235
240
|
ForkSourceNotFound: true,
|
|
236
241
|
InvalidForkRequest: true,
|
|
@@ -788,4 +793,4 @@ function group(...keys) {
|
|
|
788
793
|
checkStreams(keys);
|
|
789
794
|
return Object.freeze({ streams: Object.freeze(keys) });
|
|
790
795
|
}
|
|
791
|
-
export {
|
|
796
|
+
export { ProducerState as $, StreamBusy as A, isValid as B, InvalidEpochSeq as C, OffsetMismatch as D, NotSupported as E, StreamsReader as F, StreamsFault as G, DecodeFault as H, StreamsWriter as I, isStreamsFault as J, TransportFault as K, Storage as L, StreamGone as M, StreamNotFound as N, ProducerGap as O, isProtocolError as P, ProducerId as Q, ZERO_OFFSET as R, InvalidCreateRequest as S, InvalidReadRequest as T, EncodeFault as U, next as V, StorageFault as W, MessageWindow as X, ChangeSnapshot as Y, Offset as Z, CreateResult as _, custom as a, StreamRecord as at, ForkSourceNotFound as b, state as c, address_exports as d, RecordPatch as et, isControl as f, AppendResult as g, stateControl as h, checkStreams as i, StreamLifecycle as it, StreamClosed as j, StaleEpoch as k, streams_exports as l, stateChange as m, bind as n, StreamConfig as nt, group as o, isUpsert as p, isRetryableFault as q, bytes as r, StreamId as rt, json as s, Wildcard as t, StoredMessage as tt, route_exports as u, AppendConflict as v, InvalidForkRequest as w, InvalidAppendRequest as x, CreateConflict as y, compare as z };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { M as MemoryOptions, N as ProtocolOptions } from "../index-
|
|
1
|
+
import { C as StreamsReader, dt as ChangeSnapshot, u as Storage, w as StreamsWriter, x as StorageCapabilities, yt as StreamId } from "../projection-marks-OtKtjFLH.js";
|
|
2
|
+
import { M as MemoryOptions, N as ProtocolOptions } from "../index-DzptR3sL.js";
|
|
3
3
|
import { Context, Effect, Layer } from "effect";
|
|
4
4
|
interface StorageContractOptions {
|
|
5
5
|
readonly name: string;
|
|
6
6
|
readonly layer: Layer.Layer<Storage>;
|
|
7
7
|
readonly expected: StorageCapabilities;
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* The Layer also provides `CommitBoundary`, and the internal owner records,
|
|
10
|
+
* commit hooks and projection marks that projections need.
|
|
11
|
+
*/
|
|
9
12
|
readonly ownerRecords?: boolean;
|
|
10
13
|
}
|
|
11
14
|
export declare const StorageContract: {
|
package/dist/testing/index.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as CommitBoundary, t as layer } from "../layer-
|
|
3
|
-
import { a as MutationRejected, t as layer$1 } from "../layer-
|
|
4
|
-
import {
|
|
5
|
-
import { Array, Cause, Context, Deferred, Effect, Exit, Fiber, Layer, Match, Option, Predicate, PubSub, Queue, Record, Ref, Scope, Stream } from "effect";
|
|
1
|
+
import { L as Storage, Q as ProducerId, R as ZERO_OFFSET, V as next, W as StorageFault, rt as StreamId } from "../streamsy-BWX6z980.js";
|
|
2
|
+
import { n as CommitBoundary, t as layer } from "../layer-VOzdazlb.js";
|
|
3
|
+
import { a as MutationRejected, t as layer$1 } from "../layer-B1JEYOZb.js";
|
|
4
|
+
import { i as OwnerRecords, n as CommitHooks, t as ProjectionMarks } from "../projection-marks-RqurLPLA.js";
|
|
5
|
+
import { Array, Cause, Context, Deferred, Effect, Exit, Fiber, Layer, Match, Option, Order, Predicate, PubSub, Queue, Record, Ref, Scope, Stream } from "effect";
|
|
6
|
+
import { SqlError } from "effect/sql";
|
|
6
7
|
import { describe, expect, it } from "vitest";
|
|
7
8
|
import { TestClock } from "effect/testing";
|
|
8
9
|
// src/testing/storage-contract.ts
|
|
10
|
+
/** Executable Bun edge: a fresh scoped Layer and virtual clock for every case. */
|
|
9
11
|
const id = StreamId.make("s");
|
|
10
12
|
const child = StreamId.make("child");
|
|
11
13
|
const producerId = ProducerId.make("p");
|
|
@@ -130,7 +132,9 @@ const StorageContract = {
|
|
|
130
132
|
const context = yield* Layer.build(options.layer);
|
|
131
133
|
yield* body({
|
|
132
134
|
boundary: Option.getOrThrow(Context.getOption(context, CommitBoundary)),
|
|
133
|
-
records: Option.getOrThrow(Context.getOption(context, OwnerRecords))
|
|
135
|
+
records: Option.getOrThrow(Context.getOption(context, OwnerRecords)),
|
|
136
|
+
hooks: Option.getOrThrow(Context.getOption(context, CommitHooks)),
|
|
137
|
+
marks: Option.getOrThrow(Context.getOption(context, ProjectionMarks))
|
|
134
138
|
}).pipe(Effect.provide(context));
|
|
135
139
|
}).pipe(Effect.scoped, Effect.runPromiseExit)).resolves.toMatchObject({ _tag: "Success" }));
|
|
136
140
|
};
|
|
@@ -175,6 +179,155 @@ const StorageContract = {
|
|
|
175
179
|
}));
|
|
176
180
|
expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([[id, other]]);
|
|
177
181
|
}));
|
|
182
|
+
recordsTest("R4 owner record keys of any length stay distinct, inside and outside a transaction", ({ boundary, records }) => Effect.gen(function* () {
|
|
183
|
+
const shared = "k".repeat(600);
|
|
184
|
+
const first = `${shared}-first`;
|
|
185
|
+
const second = `${shared}-second`;
|
|
186
|
+
yield* records.write(first, "1");
|
|
187
|
+
yield* boundary.withTransaction(Effect.gen(function* () {
|
|
188
|
+
expect(yield* records.read(second)).toEqual(Option.none());
|
|
189
|
+
yield* records.write(second, "2");
|
|
190
|
+
}));
|
|
191
|
+
expect(yield* records.read(first)).toEqual(Option.some("1"));
|
|
192
|
+
expect(yield* records.read(second)).toEqual(Option.some("2"));
|
|
193
|
+
yield* records.remove(first);
|
|
194
|
+
expect(yield* records.read(first)).toEqual(Option.none());
|
|
195
|
+
expect(yield* records.read(second)).toEqual(Option.some("2"));
|
|
196
|
+
}));
|
|
197
|
+
recordsTest("R5 commit hooks see the ids of create, append, delete and expiry before the commit", ({ boundary, hooks, records }) => Effect.gen(function* () {
|
|
198
|
+
const committed = yield* (yield* Storage).committed;
|
|
199
|
+
const seen = [];
|
|
200
|
+
const published = [];
|
|
201
|
+
const expiring = StreamId.make("expiring");
|
|
202
|
+
const scope = yield* Scope.fork(yield* Scope.Scope);
|
|
203
|
+
yield* hooks.beforeCommit((ids) => Effect.gen(function* () {
|
|
204
|
+
published.push(...yield* PubSub.takeUpTo(committed, Infinity));
|
|
205
|
+
expect(published).toHaveLength(seen.length);
|
|
206
|
+
seen.push([...ids]);
|
|
207
|
+
})).pipe(Scope.provide(scope));
|
|
208
|
+
yield* mutate(create());
|
|
209
|
+
yield* mutate(append());
|
|
210
|
+
expect(Exit.isFailure(yield* Effect.exit(mutate(create())))).toBe(true);
|
|
211
|
+
yield* mutate(remove());
|
|
212
|
+
yield* mutate(create({
|
|
213
|
+
...record(expiring),
|
|
214
|
+
lifecycle: {
|
|
215
|
+
closed: false,
|
|
216
|
+
softDeleted: false,
|
|
217
|
+
expiresAtMs: 100
|
|
218
|
+
}
|
|
219
|
+
}));
|
|
220
|
+
yield* mutate({
|
|
221
|
+
_tag: "Delete",
|
|
222
|
+
streamId: expiring,
|
|
223
|
+
reason: "expiry",
|
|
224
|
+
expectedExpiresAtMs: 100
|
|
225
|
+
});
|
|
226
|
+
yield* boundary.withTransaction(records.write("only-records", "1"));
|
|
227
|
+
expect(seen).toEqual([
|
|
228
|
+
[id],
|
|
229
|
+
[id],
|
|
230
|
+
[id],
|
|
231
|
+
[expiring],
|
|
232
|
+
[expiring]
|
|
233
|
+
]);
|
|
234
|
+
const other = StreamId.make("other");
|
|
235
|
+
yield* boundary.withTransaction(Effect.andThen(mutate(create(record(other))), mutate(create(record(child)))));
|
|
236
|
+
expect(seen[5]).toEqual([other, child]);
|
|
237
|
+
yield* Scope.close(scope, Exit.void);
|
|
238
|
+
yield* mutate(remove(other));
|
|
239
|
+
expect(seen).toHaveLength(6);
|
|
240
|
+
}));
|
|
241
|
+
recordsTest("R6 a hook's writes join the transaction and a hook failure rolls the write back", ({ hooks, records }) => Effect.gen(function* () {
|
|
242
|
+
const storage = yield* Storage;
|
|
243
|
+
let fail = false;
|
|
244
|
+
yield* hooks.beforeCommit((ids) => fail ? Effect.fail(new SqlError.SqlError({ reason: new SqlError.UnknownError({
|
|
245
|
+
cause: "hook",
|
|
246
|
+
message: "hook failed"
|
|
247
|
+
}) })) : Effect.orDie(records.write("hooked", Array.join([...ids], ","))));
|
|
248
|
+
yield* mutate(create());
|
|
249
|
+
expect(yield* records.read("hooked")).toEqual(Option.some(id));
|
|
250
|
+
fail = true;
|
|
251
|
+
const committed = yield* storage.committed;
|
|
252
|
+
expect(Exit.isFailure(yield* Effect.exit(mutate(append())))).toBe(true);
|
|
253
|
+
expect((yield* current).currentOffset).toBe(ZERO_OFFSET);
|
|
254
|
+
expect(yield* PubSub.takeUpTo(committed, Infinity)).toEqual([]);
|
|
255
|
+
}));
|
|
256
|
+
recordsTest("R7 projection marks raise seq, clear by seq, defer, and list due marks in order", ({ marks }) => Effect.gen(function* () {
|
|
257
|
+
expect(yield* marks.nextDue("p")).toEqual(Option.none());
|
|
258
|
+
yield* Effect.orDie(marks.mark("p", ["a", "b"]));
|
|
259
|
+
yield* Effect.orDie(marks.mark("p", ["a"]));
|
|
260
|
+
yield* Effect.orDie(marks.mark("q", ["a"]));
|
|
261
|
+
const read = yield* marks.read("p", [
|
|
262
|
+
"a",
|
|
263
|
+
"b",
|
|
264
|
+
"absent"
|
|
265
|
+
]);
|
|
266
|
+
expect(Array.sort([...read.keys()], Order.String)).toEqual(["a", "b"]);
|
|
267
|
+
expect(read.get("a")).toEqual({
|
|
268
|
+
params: "a",
|
|
269
|
+
seq: 2,
|
|
270
|
+
attempts: 0,
|
|
271
|
+
dueAt: 0
|
|
272
|
+
});
|
|
273
|
+
expect(read.get("b")).toEqual({
|
|
274
|
+
params: "b",
|
|
275
|
+
seq: 1,
|
|
276
|
+
attempts: 0,
|
|
277
|
+
dueAt: 0
|
|
278
|
+
});
|
|
279
|
+
expect(yield* marks.nextDue("p")).toEqual(Option.some(0));
|
|
280
|
+
yield* marks.clear("p", "a", 1);
|
|
281
|
+
expect((yield* marks.read("p", ["a"])).get("a")?.seq).toBe(2);
|
|
282
|
+
yield* marks.clear("p", "a", 2);
|
|
283
|
+
expect((yield* marks.read("p", ["a"])).size).toBe(0);
|
|
284
|
+
expect((yield* marks.read("q", ["a"])).get("a")?.seq).toBe(1);
|
|
285
|
+
yield* marks.defer("p", "b", 1, 5e3);
|
|
286
|
+
yield* Effect.orDie(marks.mark("p", ["b"]));
|
|
287
|
+
expect((yield* marks.read("p", ["b"])).get("b")).toEqual({
|
|
288
|
+
params: "b",
|
|
289
|
+
seq: 2,
|
|
290
|
+
attempts: 1,
|
|
291
|
+
dueAt: 5e3
|
|
292
|
+
});
|
|
293
|
+
expect(yield* marks.deferred("p")).toBe(1);
|
|
294
|
+
expect(yield* marks.nextDue("p")).toEqual(Option.some(5e3));
|
|
295
|
+
yield* marks.defer("p", "c", 2, 3e3);
|
|
296
|
+
expect(yield* marks.deferred("p")).toBe(2);
|
|
297
|
+
yield* Effect.orDie(marks.mark("p", ["e", "d"]));
|
|
298
|
+
expect(Array.map(yield* marks.due("p", 4e3, 10), (row) => row.params)).toEqual([
|
|
299
|
+
"d",
|
|
300
|
+
"e",
|
|
301
|
+
"c"
|
|
302
|
+
]);
|
|
303
|
+
expect(Array.map(yield* marks.due("p", 1e4, 2), (row) => row.params)).toEqual(["d", "e"]);
|
|
304
|
+
expect(Array.map(yield* marks.due("p", 1e4, 10), (row) => row.params)).toEqual([
|
|
305
|
+
"d",
|
|
306
|
+
"e",
|
|
307
|
+
"c",
|
|
308
|
+
"b"
|
|
309
|
+
]);
|
|
310
|
+
yield* marks.remove("p", "b");
|
|
311
|
+
yield* marks.remove("p", "absent");
|
|
312
|
+
expect(yield* marks.deferred("p")).toBe(1);
|
|
313
|
+
const many = Array.makeBy(150, (index) => `m${String(index).padStart(3, "0")}`);
|
|
314
|
+
yield* Effect.orDie(marks.mark("many", many));
|
|
315
|
+
yield* Effect.orDie(marks.mark("many", many));
|
|
316
|
+
const all = yield* marks.read("many", many);
|
|
317
|
+
expect(all.size).toBe(150);
|
|
318
|
+
expect(Array.every([...all.values()], (row) => row.seq === 2)).toBe(true);
|
|
319
|
+
expect(yield* marks.due("many", 0, 1e3)).toHaveLength(150);
|
|
320
|
+
}));
|
|
321
|
+
recordsTest("R8 marks written by a commit hook commit and roll back with the write", ({ boundary, hooks, marks }) => Effect.gen(function* () {
|
|
322
|
+
yield* hooks.beforeCommit((ids) => marks.mark("p", [...ids]));
|
|
323
|
+
yield* mutate(create());
|
|
324
|
+
expect((yield* marks.read("p", [id])).get(id)?.seq).toBe(1);
|
|
325
|
+
const failed = yield* Effect.exit(boundary.withTransaction(Effect.andThen(mutate(append()), Effect.fail("rollback"))));
|
|
326
|
+
expect(Exit.isFailure(failed)).toBe(true);
|
|
327
|
+
expect((yield* marks.read("p", [id])).get(id)?.seq).toBe(1);
|
|
328
|
+
yield* mutate(append());
|
|
329
|
+
expect((yield* marks.read("p", [id])).get(id)?.seq).toBe(2);
|
|
330
|
+
}));
|
|
178
331
|
test("01 Append advances tail and folds close atomically", Effect.gen(function* () {
|
|
179
332
|
yield* mutate(create());
|
|
180
333
|
applied(yield* mutate(append({ patch: {
|
package/package.json
CHANGED