@streamsy/projection 0.0.0-tegami-trusted-publish-setup → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-2026 Gareth Andrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,6 +1,171 @@
1
- # Placeholder package
2
-
3
- This empty package was published by [Tegami](https://tegami.fuma-nama.dev) to configure npm trusted publishing.
4
-
5
- The real package contents will be published via CI with OIDC.
6
-
1
+ # @streamsy/projection
2
+
3
+ Checkpointed projections over typed Streamsy routes. A constructor defines the
4
+ step. Its `commit:` value defines how results and offsets become durable.
5
+
6
+ ## Constructors
7
+
8
+ | Constructor | Handler | Result | Commit |
9
+ | -------------------------- | ------------------------- | ---------------- | ------------------------------- |
10
+ | `Projection.fold` | `(state, entry, unit)` | Next value | Defaults to `Commit.checkpoint` |
11
+ | `Projection.process` | `(batch, unit, prepared)` | Effect of void | Required |
12
+ | `Projection.emit` | `(entry, unit)` | Output items | Required |
13
+ | `Projection.mapAccum` | `(state, entry, unit)` | `[state, emits]` | Required |
14
+ | `Projection.mapAccumBatch` | `(state, batch, unit)` | `[state, emits]` | Required |
15
+
16
+ Except for `process`, steps return a value or an Effect. A missing output key
17
+ emits nothing. `Projection.each` adapts an entry handler for `process`.
18
+ Batch handlers must give the same final rows for any unit size. In per-entry
19
+ steps, use `unit` for parameters and offsets only.
20
+
21
+ ```ts
22
+ import { Effect, Layer, Schema } from "effect";
23
+ import { MemoryStorage, Streamsy } from "@streamsy/core";
24
+ import { CheckpointStore, Commit, Projection } from "@streamsy/projection";
25
+
26
+ class Numbers extends Streamsy.json<Numbers>()("Example/Numbers", "numbers", {
27
+ params: {},
28
+ schema: Schema.Finite,
29
+ }) {}
30
+ class Doubled extends Streamsy.json<Doubled>()("Example/Doubled", "doubled", {
31
+ params: {},
32
+ schema: Schema.Finite,
33
+ }) {}
34
+ const doubled = Projection.emit({
35
+ id: "doubled",
36
+ params: {},
37
+ inputs: { input: Numbers },
38
+ outputs: { output: Doubled },
39
+ commit: Commit.producer,
40
+ emit: ({ item }) => ({ output: [item * 2] }),
41
+ });
42
+ const host = CheckpointStore.layer.pipe(
43
+ Layer.provideMerge(MemoryStorage.layer(Streamsy.group(Numbers, Doubled))),
44
+ );
45
+ const program = Effect.gen(function* () {
46
+ const numbers = yield* Numbers;
47
+ yield* numbers.create({});
48
+ yield* numbers.append({}, [1, 2, 3]);
49
+ return yield* Projection.run(doubled.at({}));
50
+ });
51
+ await Effect.runPromise(program.pipe(Effect.provide(host)));
52
+ ```
53
+
54
+ ## Commits
55
+
56
+ | Commit | Fits | Guarantee | Services |
57
+ | ------------- | ----------------------------------- | -------------------------------- | -------------------------------- |
58
+ | `checkpoint` | `fold` | Exactly once for the saved value | `CheckpointStore` |
59
+ | `transaction` | All constructors | Exactly once within SQL | `CheckpointStore`, `Transaction` |
60
+ | `producer` | `emit`, `mapAccum`, `mapAccumBatch` | Effectively once for outputs | `CheckpointStore`, output routes |
61
+ | `atLeastOnce` | `process` | At least once | `CheckpointStore` |
62
+
63
+ `Commit.transaction` provides `SqlClient`. Its SQL, same-owner stream appends,
64
+ and checkpoint commit together. External calls are at least once. Memory hosts
65
+ provide no `Transaction`.
66
+
67
+ `Commit.producer` pins ranges and producer sequences. Retries append with the
68
+ same positions; handlers must be deterministic. Foreign outputs must already
69
+ exist. Same-owner outputs can be created automatically. There is no atomicity
70
+ across producer outputs. Chain projections for sinks with different guarantees.
71
+
72
+ `Commit.atLeastOnce` pins before processing, so retries keep `unit.key`.
73
+ `Projection.process` with `Commit.transaction` can use `prepare(batch, unit)`
74
+ outside the transaction. It runs at least once and passes its result to
75
+ `process`. A retry can read new input and change `unit.key`.
76
+
77
+ `Commit.withCompensation(f)` calls `f(result, cause, unit)` after successful
78
+ processing if the commit fails. It is also available as a `.pipe` combinator.
79
+ For durable external delivery, use the [action outbox](https://streamsy.dev/docs/projections/actions).
80
+
81
+ `Commit.make` defines `load`, `apply`, and optional `remove`. Custom Commits
82
+ extend ranges on retry. Never save after a failed handler; compare-and-set on
83
+ `loaded.token`; report `checkpoint / token-conflict` for a moved token; return
84
+ `"0"` for an absent record; and load stored state. The guarantee must describe
85
+ the actual writes. See the [bucket example](https://streamsy.dev/docs/projections/state#custom-commits).
86
+
87
+ ## State and output routes
88
+
89
+ `fold`, `mapAccum`, and `mapAccumBatch` require `state: { schema, initial }`.
90
+ `initial` can depend on decoded parameters. State and offsets share one record.
91
+ `Projection.read(bound)` reads through the Commit's `load` and returns
92
+ `{ state, offsets }`, using `initial` before the first unit.
93
+ `Projection.current(bound)` folds the checkpoint and input tail in memory. It
94
+ takes no lock and writes no checkpoint or outputs. It requires `state:` and
95
+ returns matching state and offsets, including entries appended before the call.
96
+ `mapAccum` and `mapAccumBatch` compute state and discard emitted items.
97
+ `Projection.decide(bound, { input, decide })` requires `state:`, calls `current`,
98
+ decides, and appends to one input with that input's offset as `expectedOffset`. It
99
+ retries on `OffsetMismatch`. See [Read, decide, append](https://streamsy.dev/docs/projections/state#read-decide-append).
100
+
101
+ `Serve.value(schema, effect)` serves values computed with `Projection.read`.
102
+ Before the first saved unit, reads return the declared initial value.
103
+ `Serve.mount(Board, path)` and `Serve.mount(Transitions, path)` mount output routes.
104
+
105
+ Outputs accept routes or fixed addresses, like inputs. `Streamsy.json` accepts
106
+ items. `Streamsy.state` accepts `DurableState.upsert("card", row)` and
107
+ `DurableState.remove("card", key)` from `@streamsy/core`. Each change names its
108
+ collection. Two outputs cannot name the same stream or an input.
109
+
110
+ ## Hosts
111
+
112
+ | Layer | Provides | Requires |
113
+ | ----------------------------- | ---------------------------- | ------------------------------- |
114
+ | `CheckpointStore.layer` | `CheckpointStore` | `CommitBoundary`, owner records |
115
+ | `Transaction.layer` | `Transaction` | `CommitBoundary`, `SqlClient` |
116
+ | `CheckpointStore.layerMemory` | Standalone `CheckpointStore` | Nothing |
117
+
118
+ `CheckpointStore.layer` keeps checkpoints on the owner of the streams. It works
119
+ over every Streamsy storage host: `MemoryStorage.layer`, `BunStorage.layer`, and
120
+ `DurableObjectStorage.layer`. Add `Transaction.layer` on a SQL host for
121
+ `Commit.transaction`. Compose the projection Layers over storage with
122
+ `Layer.provideMerge` and retain one Layer graph for the host lifetime:
123
+
124
+ ```ts
125
+ const host = Layer.mergeAll(CheckpointStore.layer, Transaction.layer).pipe(
126
+ Layer.provideMerge(BunStorage.layer(streams, { client: { filename } })),
127
+ );
128
+ ```
129
+
130
+ `CheckpointStore.layerMemory` is standalone. It keeps checkpoints in the
131
+ process and does not join the stream owner, so processing is at least once. Use
132
+ it for rebuilt values, tests, and a remote host (`RemoteStreams.layer`).
133
+
134
+ SQL hosts keep checkpoints in `streamsy_owner_records`. Older projection tables
135
+ are not migrated or read; projections rebuild from zero.
136
+ Layer authors use `EncodedStore` and `fromStore` from `@streamsy/projection/checkpoint`.
137
+
138
+ ## Run and recover
139
+
140
+ `declaration.at(params)` binds a projection. `pass` runs one unit; `run` continues
141
+ until caught up, closed, or its optional unit limit. `follow` returns a scoped
142
+ fiber and waits for changes, with a default repair interval of 30 seconds. Remote inputs
143
+ work with `follow` and `run`.
144
+
145
+ Use one writer per projection key: one `follow`, or one `run` at a
146
+ time. Schedules must not overlap. A second writer is a deployment fault; a
147
+ moved checkpoint token fails with `token-conflict`. External handlers may have
148
+ already run. Any number of `current` and `decide` calls can run beside the
149
+ follower, including inside a caller transaction. Table and stateless output
150
+ projections are follow-only; wait on their output to see a command.
151
+
152
+ `follow` retries only `storage-failure`: `options.retry` overrides the
153
+ `ProjectionRetry` context reference, whose default is jittered exponential
154
+ backoff from 200 ms, capped at 30 s. `run` does not retry. Handler errors retain
155
+ their types; `ProjectionFault` carries `phase`, `reason`, and `cause`.
156
+
157
+ Records are keyed by `id`, `version`, `generation`, and canonical parameters.
158
+ Use a new generation for changed input identity or state schema. Retain input
159
+ history after the checkpoint, including pinned ranges. Stop the follower first, or use a new generation before
160
+ `Projection.forget(bound)`, which calls the Commit's `remove`. For producer
161
+ outputs, delete output streams first or use a new generation.
162
+
163
+ Without a follower, each `current` replays from the last checkpoint or from
164
+ the start. A continuously growing input can delay it. Fold handlers must be
165
+ replayable and give the same result for any page split.
166
+
167
+ Full reference: [streamsy.dev/docs/projections](https://streamsy.dev/docs/projections).
168
+
169
+ ## License
170
+
171
+ MIT
@@ -0,0 +1,118 @@
1
+ import { Context, Effect, Layer, Option, Schema } from "effect";
2
+ import { CommitBoundary, StreamAddress, Streamsy } from "@streamsy/core";
3
+ import { OwnerRecords } from "@streamsy/core/internal";
4
+ /** Declaration order of the map is the read and item order of every pass. */
5
+ type InputMap = Record<string, Streamsy.Address<unknown, unknown>>;
6
+ type ItemOf<Address> = Address extends StreamAddress.StreamAddress<infer A> ? A : never;
7
+ interface Slice<A> {
8
+ /** Cursor the read started after. Equal to `nextOffset` when the slice is empty. */
9
+ readonly from: string;
10
+ readonly items: ReadonlyArray<A>;
11
+ readonly nextOffset: string;
12
+ readonly upToDate: boolean;
13
+ readonly closed: boolean;
14
+ }
15
+ type Slices<Inputs extends InputMap> = { readonly [K in keyof Inputs]: Slice<ItemOf<Inputs[K]>>; };
16
+ /** One item tagged with its input; `index` is its position in the whole unit. */
17
+ type Entry<Inputs extends InputMap> = { readonly [K in keyof Inputs]: {
18
+ readonly input: K;
19
+ readonly item: ItemOf<Inputs[K]>;
20
+ readonly index: number;
21
+ }; }[keyof Inputs];
22
+ type InputServices<Inputs extends InputMap> = Inputs[keyof Inputs]["stream"]["Identifier"];
23
+ declare const ProjectionFault_base: Schema.Class<ProjectionFault, Schema.TaggedStruct<"ProjectionFault", {
24
+ readonly phase: Schema.Literals<readonly ["load", "read", "pin", "process", "checkpoint"]>;
25
+ readonly reason: Schema.Literals<readonly ["history-unavailable", "identity-mismatch", "invalid-record", "invalid-source", "invalid-options", "invalid-output", "token-conflict", "range-unreproducible", "stale-epoch", "storage-failure", "unsupported-composition"]>;
26
+ readonly input: Schema.optionalKey<Schema.String>;
27
+ readonly message: Schema.String;
28
+ readonly cause: Schema.optionalKey<Schema.Defect>;
29
+ }>, import("effect/Cause").YieldableError>;
30
+ /** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
31
+ declare class ProjectionFault extends ProjectionFault_base {
32
+ get retryable(): boolean;
33
+ }
34
+ declare const Range: Schema.Struct<{
35
+ readonly from: Schema.String;
36
+ readonly nextOffset: Schema.String;
37
+ }>;
38
+ interface Range extends Schema.Schema.Type<typeof Range> {}
39
+ /** `params` holds the decoded values the declaration was bound with. Keys use the encoded strings. */
40
+ interface Unit<P = Record<string, string>> {
41
+ readonly projectionId: string;
42
+ /** The declared version; defaults to 1. */
43
+ readonly version: number;
44
+ readonly generation: number;
45
+ readonly params: P;
46
+ /** Only the inputs that contributed items; a retry reproduces exactly these. */
47
+ readonly ranges: Record<string, Range>;
48
+ readonly key: string;
49
+ }
50
+ declare const CheckpointRecord: Schema.Struct<{
51
+ readonly identity: Schema.Struct<{
52
+ readonly inputs: Schema.$Record<Schema.String, Schema.String>;
53
+ }>;
54
+ /** Input key to accepted offset; the next pass reads after these. */
55
+ readonly inputs: Schema.$Record<Schema.String, Schema.String>;
56
+ readonly pending: Schema.optionalKey<Schema.Struct<{
57
+ readonly ranges: Schema.$Record<Schema.String, Schema.Struct<{
58
+ readonly from: Schema.String;
59
+ readonly nextOffset: Schema.String;
60
+ readonly count: Schema.Finite;
61
+ }>>;
62
+ readonly seqs: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Finite>>;
63
+ }>>;
64
+ readonly state: Schema.optionalKey<Schema.String>;
65
+ readonly adapters: Schema.Struct<{
66
+ readonly outputs: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
67
+ readonly epoch: Schema.Finite;
68
+ readonly nextSeq: Schema.Finite;
69
+ }>>>;
70
+ }>;
71
+ }>;
72
+ interface CheckpointRecord extends Schema.Schema.Type<typeof CheckpointRecord> {}
73
+ interface ProjectionKey {
74
+ readonly id: string;
75
+ readonly version: number;
76
+ readonly generation: number;
77
+ readonly params: Record<string, string>;
78
+ }
79
+ declare const recordKey: (key: ProjectionKey) => string;
80
+ interface Loaded {
81
+ readonly record: Option.Option<CheckpointRecord>;
82
+ readonly token: string;
83
+ }
84
+ interface CheckpointStoreApi {
85
+ readonly load: (key: ProjectionKey) => Effect.Effect<Loaded, ProjectionFault>;
86
+ /** Compare-and-set inside the owner transaction; returns the new token. */
87
+ readonly compareAndSet: (key: ProjectionKey, ifToken: string, record: CheckpointRecord) => Effect.Effect<string, ProjectionFault>;
88
+ /** Deletes the record. Absent keys are ignored. */
89
+ readonly remove: (key: ProjectionKey) => Effect.Effect<void, ProjectionFault>;
90
+ }
91
+ declare const CheckpointStore_base: Context.ServiceClass<CheckpointStore, "@streamsy/projection/CheckpointStore", CheckpointStoreApi>;
92
+ /** Stores each projection's offsets and encoded state in one compare-and-set record. */
93
+ declare class CheckpointStore extends CheckpointStore_base {
94
+ /**
95
+ * Checkpoints on the storage owner, in its transaction. Works over every Streamsy
96
+ * storage host, so checkpoints and streams always share one owner.
97
+ */
98
+ static readonly layer: Layer.Layer<CheckpointStore, never, CommitBoundary | OwnerRecords>;
99
+ /** An independent store for rebuilt values and tests. It shares no owner with streams. */
100
+ static readonly layerMemory: Layer.Layer<CheckpointStore, never, never>;
101
+ }
102
+ /** The encoded seam a checkpoint Layer builds on; both shipped Layers use it. */
103
+ interface EncodedStore {
104
+ readonly read: (key: string) => Effect.Effect<Option.Option<string>, ProjectionFault>;
105
+ readonly write: (key: string, value: string) => Effect.Effect<void, ProjectionFault>;
106
+ readonly remove: (key: string) => Effect.Effect<void, ProjectionFault>;
107
+ readonly withTransaction: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E | ProjectionFault, R>;
108
+ }
109
+ declare const fromStore: (store: EncodedStore) => CheckpointStoreApi;
110
+ /** What the kernel needs to locate a record; every projection value satisfies it. */
111
+ interface Identity {
112
+ readonly id: string;
113
+ readonly version: number;
114
+ readonly generation: number;
115
+ readonly params: Record<string, string>;
116
+ readonly inputs: InputMap;
117
+ }
118
+ export { Slice as _, Identity as a, fromStore as c, Unit as d, ProjectionFault as f, ItemOf as g, InputServices as h, EncodedStore as i, recordKey as l, InputMap as m, CheckpointStore as n, Loaded as o, Entry as p, CheckpointStoreApi as r, ProjectionKey as s, CheckpointRecord as t, Range as u, Slices as v };
@@ -0,0 +1,246 @@
1
+ import { Array, Context, Effect, Layer, Option, Order, Record, Schema, Semaphore } from "effect";
2
+ import { CommitBoundary, ZERO_OFFSET, isStreamsFault } from "@streamsy/core";
3
+ import { OwnerRecords, attachOwner, ownerOf } from "@streamsy/core/internal";
4
+ // src/fault.ts
5
+ /** Phase says where the run stopped; a `checkpoint` failure means processing already completed. */
6
+ var ProjectionFault = class extends Schema.TaggedError()("ProjectionFault", {
7
+ phase: Schema.Literals([
8
+ "load",
9
+ "read",
10
+ "pin",
11
+ "process",
12
+ "checkpoint"
13
+ ]),
14
+ reason: Schema.Literals([
15
+ "history-unavailable",
16
+ "identity-mismatch",
17
+ "invalid-record",
18
+ "invalid-source",
19
+ "invalid-options",
20
+ "invalid-output",
21
+ "token-conflict",
22
+ "range-unreproducible",
23
+ "stale-epoch",
24
+ "storage-failure",
25
+ "unsupported-composition"
26
+ ]),
27
+ input: Schema.optionalKey(Schema.String),
28
+ message: Schema.String,
29
+ cause: Schema.optionalKey(Schema.Defect())
30
+ }) {
31
+ get retryable() {
32
+ return this.reason === "storage-failure" && (!isStreamsFault(this.cause) || this.cause.retryable);
33
+ }
34
+ };
35
+ // src/unit.ts
36
+ /** Length-safe encoding of inert string components; no persistence decoding here. */
37
+ const encodeKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
38
+ const Counter = Schema.Finite.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0));
39
+ Schema.Struct({
40
+ from: Schema.String,
41
+ nextOffset: Schema.String
42
+ });
43
+ /** A range with the item count a retry must reproduce exactly. */
44
+ const PinnedRange = Schema.Struct({
45
+ from: Schema.String,
46
+ nextOffset: Schema.String,
47
+ count: Counter
48
+ });
49
+ /** An outputs unit that was pinned before its append; settled by the next pass. */
50
+ const PendingUnit = Schema.Struct({
51
+ ranges: Schema.Record(Schema.String, PinnedRange),
52
+ seqs: Schema.optionalKey(Schema.Record(Schema.String, Counter))
53
+ });
54
+ /** Deterministic JSON: keys sorted, so equal maps always encode identically. */
55
+ const canonicalParams = (params) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(params), Order.String), (k) => [k, params[k]])));
56
+ const canonicalRanges = (ranges) => JSON.stringify(Record.fromEntries(Array.map(Array.sort(Record.keys(ranges), Order.String), (k) => [k, {
57
+ from: ranges[k]?.from,
58
+ nextOffset: ranges[k]?.nextOffset
59
+ }])));
60
+ /** The key is stable across producer retries; transaction retries may read a longer tail. */
61
+ const unitOf = (projectionId, version, generation, params, ranges) => ({
62
+ projectionId,
63
+ version,
64
+ generation,
65
+ params,
66
+ ranges,
67
+ key: encodeKey([
68
+ projectionId,
69
+ String(generation),
70
+ canonicalParams(params),
71
+ canonicalRanges(ranges)
72
+ ])
73
+ });
74
+ /** The handler view of a kernel unit, with the decoded params. */
75
+ const withParams = (unit, params) => ({
76
+ ...unit,
77
+ params
78
+ });
79
+ // src/checkpoint-store.ts
80
+ const CheckpointRecord = Schema.Struct({
81
+ identity: Schema.Struct({ inputs: Schema.Record(Schema.String, Schema.String) }),
82
+ /** Input key to accepted offset; the next pass reads after these. */
83
+ inputs: Schema.Record(Schema.String, Schema.String),
84
+ pending: Schema.optionalKey(PendingUnit),
85
+ state: Schema.optionalKey(Schema.String),
86
+ adapters: Schema.Struct({ outputs: Schema.optionalKey(Schema.Record(Schema.String, Schema.Struct({
87
+ epoch: Counter,
88
+ nextSeq: Counter
89
+ }))) })
90
+ });
91
+ /** Stored value. The version is the compare-and-set token exposed as a string. */
92
+ const Envelope = Schema.Struct({
93
+ version: Counter,
94
+ record: CheckpointRecord
95
+ });
96
+ const EnvelopeJson = Schema.fromJsonString(Envelope);
97
+ const recordKey = (key) => encodeKey([
98
+ "streamsy.projection.v1",
99
+ key.id,
100
+ String(key.version),
101
+ String(key.generation),
102
+ canonicalParams(key.params)
103
+ ]);
104
+ /** Token "0" means no record is stored yet. */
105
+ const ABSENT_TOKEN = "0";
106
+ const storageFailure = (phase, message) => (cause) => new ProjectionFault({
107
+ phase,
108
+ reason: "storage-failure",
109
+ message,
110
+ cause
111
+ });
112
+ /**
113
+ * SQL storage fails a write with this operation when the transaction read the key as
114
+ * absent and a concurrent save created it first. That save won the compare-and-set.
115
+ */
116
+ const OWNER_RECORD_CONFLICT = "records.conflict";
117
+ /** Stores each projection's offsets and encoded state in one compare-and-set record. */
118
+ var CheckpointStore = class extends Context.Service()("@streamsy/projection/CheckpointStore") {
119
+ /**
120
+ * Checkpoints on the storage owner, in its transaction. Works over every Streamsy
121
+ * storage host, so checkpoints and streams always share one owner.
122
+ */
123
+ static layer = Layer.effect(this, Effect.gen(function* () {
124
+ const boundary = yield* CommitBoundary;
125
+ const records = yield* OwnerRecords;
126
+ const checkpoints = fromStore({
127
+ read: (key) => records.read(key).pipe(Effect.mapError(storageFailure("load", "Cannot read a checkpoint"))),
128
+ write: (key, value) => records.write(key, value).pipe(Effect.mapError((cause) => cause.operation === OWNER_RECORD_CONFLICT ? new ProjectionFault({
129
+ phase: "checkpoint",
130
+ reason: "token-conflict",
131
+ message: "A second writer on the same key likely created the checkpoint first. Use one writer per key: the follower or one run at a time.",
132
+ cause
133
+ }) : storageFailure("checkpoint", "Cannot write a checkpoint")(cause))),
134
+ remove: (key) => records.remove(key).pipe(Effect.mapError(storageFailure("checkpoint", "Cannot delete a checkpoint"))),
135
+ withTransaction: (body) => boundary.withTransaction(body).pipe(Effect.catchTag("SqlError", (cause) => Effect.fail(new ProjectionFault({
136
+ phase: "checkpoint",
137
+ reason: "storage-failure",
138
+ message: "The owner transaction failed",
139
+ cause
140
+ }))))
141
+ });
142
+ attachOwner(checkpoints.load, ownerOf(boundary));
143
+ return checkpoints;
144
+ }));
145
+ /** An independent store for rebuilt values and tests. It shares no owner with streams. */
146
+ static layerMemory = Layer.effect(this, Effect.gen(function* () {
147
+ const records = /* @__PURE__ */ new Map();
148
+ const lock = yield* Semaphore.make(1);
149
+ return fromStore({
150
+ read: (key) => Effect.sync(() => Option.fromUndefinedOr(records.get(key))),
151
+ write: (key, value) => Effect.sync(() => {
152
+ records.set(key, value);
153
+ }),
154
+ remove: (key) => lock.withPermits(1)(Effect.sync(() => {
155
+ records.delete(key);
156
+ })),
157
+ withTransaction: lock.withPermits(1)
158
+ });
159
+ }));
160
+ };
161
+ const fromStore = (store) => {
162
+ const load = Effect.fn("Projection.CheckpointStore.load")(function* (key) {
163
+ const encoded = yield* store.read(recordKey(key));
164
+ if (Option.isNone(encoded)) return {
165
+ record: Option.none(),
166
+ token: ABSENT_TOKEN
167
+ };
168
+ const envelope = yield* Schema.decodeEffect(EnvelopeJson)(encoded.value).pipe(Effect.mapError(() => new ProjectionFault({
169
+ phase: "load",
170
+ reason: "invalid-record",
171
+ message: `Invalid stored record for ${key.id}`
172
+ })));
173
+ return {
174
+ record: Option.some(envelope.record),
175
+ token: String(envelope.version)
176
+ };
177
+ });
178
+ return {
179
+ load,
180
+ compareAndSet: Effect.fn("Projection.CheckpointStore.compareAndSet")(function* (key, ifToken, record) {
181
+ return yield* store.withTransaction(Effect.gen(function* () {
182
+ const current = yield* load(key);
183
+ if (current.token !== ifToken) return yield* new ProjectionFault({
184
+ phase: "checkpoint",
185
+ reason: "token-conflict",
186
+ message: `Record for ${key.id} changed: expected token ${ifToken}, found ${current.token}. A second writer on the same key is the likely cause. Use one writer per key: the follower or one run at a time.`
187
+ });
188
+ const version = Number(ifToken) + 1;
189
+ const encoded = yield* Schema.encodeEffect(EnvelopeJson)({
190
+ version,
191
+ record
192
+ }).pipe(Effect.mapError(() => new ProjectionFault({
193
+ phase: "checkpoint",
194
+ reason: "invalid-record",
195
+ message: `Cannot encode record for ${key.id}`
196
+ })));
197
+ yield* store.write(recordKey(key), encoded);
198
+ return String(version);
199
+ }));
200
+ }),
201
+ remove: (key) => store.remove(recordKey(key))
202
+ };
203
+ };
204
+ const identityOf = (inputs) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, address]) => [name, encodeKey([address.id, address.contentType])]));
205
+ const sameIdentity = (a, b) => {
206
+ const keys = Record.keys(a);
207
+ return keys.length === Record.keys(b).length && Array.every(keys, (k) => a[k] === b[k]);
208
+ };
209
+ /** The stored record, or the unstored initial record for a fresh key. */
210
+ const restore = Effect.fn("Projection.restore")(function* (projection, owner) {
211
+ const loaded = yield* owner.load(projection);
212
+ const identity = { inputs: identityOf(projection.inputs) };
213
+ if (Option.isNone(loaded.record)) return {
214
+ record: {
215
+ identity,
216
+ inputs: Record.fromEntries(Array.map(Record.keys(projection.inputs), (name) => [name, ZERO_OFFSET])),
217
+ adapters: {}
218
+ },
219
+ token: loaded.token,
220
+ loaded
221
+ };
222
+ if (!sameIdentity(loaded.record.value.identity.inputs, identity.inputs)) return yield* new ProjectionFault({
223
+ phase: "load",
224
+ reason: "identity-mismatch",
225
+ message: `Stored inputs differ from the declaration of ${projection.id}`
226
+ });
227
+ for (const name of Record.keys(projection.inputs)) if (loaded.record.value.inputs[name] === void 0) return yield* new ProjectionFault({
228
+ phase: "load",
229
+ reason: "invalid-record",
230
+ input: name,
231
+ message: `Stored record of ${projection.id} has no offset for ${name}`
232
+ });
233
+ return {
234
+ record: loaded.record.value,
235
+ token: loaded.token,
236
+ loaded
237
+ };
238
+ });
239
+ /** Accepted offsets after a unit: every read input moves to its `nextOffset`. */
240
+ const advance = (inputs, ranges) => Record.fromEntries(Array.map(Record.toEntries(inputs), ([name, offset]) => [name, ranges[name]?.nextOffset ?? offset]));
241
+ /** Only the inputs that contributed items; the unit key and any pin come from these. */
242
+ const rangesOf = (slices) => Record.fromEntries(Array.map(Array.filter(Record.toEntries(slices), ([, slice]) => slice.items.length > 0), ([name, slice]) => [name, {
243
+ from: slice.from,
244
+ nextOffset: slice.nextOffset
245
+ }]));
246
+ export { rangesOf as a, canonicalParams as c, ProjectionFault as d, fromStore as i, unitOf as l, CheckpointStore as n, recordKey as o, advance as r, restore as s, CheckpointRecord as t, withParams as u };
@@ -0,0 +1,2 @@
1
+ import { c as fromStore, i as EncodedStore, l as recordKey, n as CheckpointStore, o as Loaded, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord } from "./checkpoint-store-C8KxieX5.js";
2
+ export { CheckpointRecord, CheckpointStore, type CheckpointStoreApi, type EncodedStore, type Loaded, type ProjectionKey, fromStore, recordKey };
@@ -0,0 +1 @@
1
+ export { t as CheckpointRecord, n as CheckpointStore, i as fromStore, o as recordKey } from "./checkpoint-store-CoDWYNbd.js";