@streamsy/projection 0.8.0 → 0.10.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 +26 -7
- package/dist/index.d.ts +125 -7
- package/dist/index.js +391 -19
- package/package.json +13 -13
package/README.md
CHANGED
|
@@ -5,13 +5,13 @@ step. Its `commit:` value defines how results and offsets become durable.
|
|
|
5
5
|
|
|
6
6
|
## Constructors
|
|
7
7
|
|
|
8
|
-
| Constructor | Handler
|
|
9
|
-
| -------------------------- |
|
|
10
|
-
| `Projection.fold` | `(state, entry, unit)`
|
|
11
|
-
| `Projection.process` | `(batch, unit,
|
|
12
|
-
| `Projection.emit` | `(entry, unit)`
|
|
13
|
-
| `Projection.mapAccum` | `(state, entry, unit)`
|
|
14
|
-
| `Projection.mapAccumBatch` | `(state, batch, unit)`
|
|
8
|
+
| Constructor | Handler | Result | Commit |
|
|
9
|
+
| -------------------------- | ------------------------ | ---------------- | ------------------------------- |
|
|
10
|
+
| `Projection.fold` | `(state, entry, unit)` | Next value | Defaults to `Commit.checkpoint` |
|
|
11
|
+
| `Projection.process` | `(batch, unit, context)` | 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
15
|
|
|
16
16
|
Except for `process`, steps return a value or an Effect. A missing output key
|
|
17
17
|
emits nothing. `Projection.each` adapts an entry handler for `process`.
|
|
@@ -108,6 +108,25 @@ items. `Streamsy.state` accepts `DurableState.upsert("card", row)` and
|
|
|
108
108
|
`DurableState.remove("card", key)` from `@streamsy/core`. Each change names its
|
|
109
109
|
collection. Two outputs cannot name the same stream or an input.
|
|
110
110
|
|
|
111
|
+
## State tables
|
|
112
|
+
|
|
113
|
+
`StateTable.define(State)` declares a projection that keeps the rows of a
|
|
114
|
+
`Streamsy.state` stream in SQLite tables beside the stream. Run
|
|
115
|
+
`StateTable.migrate(sql)` at host start and attach the table with
|
|
116
|
+
`Projection.attach(table, { durable: true })`. A bound table reads rows with
|
|
117
|
+
`get`, `getMany` and `list`, each with the offset that the rows reflect.
|
|
118
|
+
`StateTable.rebuild` makes the rows again from the stream alone. The types of
|
|
119
|
+
a declaration and a bound table are `StateTable.Declaration` and
|
|
120
|
+
`StateTable.Bound`.
|
|
121
|
+
|
|
122
|
+
`FoldByKey.process(table, spec)` builds a `Projection.process` handler, under
|
|
123
|
+
`Commit.transaction` with the State stream in `outputs`, that folds records into
|
|
124
|
+
one collection. It reads each key's previous row from the table. `sync` and the
|
|
125
|
+
fold handler fail with `ProjectionFault` for every wire, SQL and schema failure,
|
|
126
|
+
and the handler adds `FoldByKeyError` for a row with the wrong key. A fold's `id`,
|
|
127
|
+
`version` and `generation` are its identity, so a rename is a fold fix. See
|
|
128
|
+
[State tables](https://streamsy.dev/docs/projections/state-table).
|
|
129
|
+
|
|
111
130
|
## Wake streams
|
|
112
131
|
|
|
113
132
|
`Projection.wake` writes a `Streamsy.wake` stream from one source stream. It is
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { _ as Slice, a as Identity, d as Unit, f as ProjectionFault, g as ItemOf, h as InputServices, m as InputMap, n as CheckpointStore, o as Loaded, p as Entry, r as CheckpointStoreApi, s as ProjectionKey, t as CheckpointRecord, u as Range, v as Slices } from "./checkpoint-store-D1saxIIM.js";
|
|
2
2
|
import { Cause, Context, Data, Effect, Layer, Option, Pipeable, Schedule, Schema, Stream } from "effect";
|
|
3
3
|
import { CommitBoundary, Decided, Decision, DurableState, OffsetMismatch, Storage, StreamAddress, StreamId, Streamsy } from "@streamsy/core";
|
|
4
|
-
import { StreamRoute } from "@streamsy/core/protocol";
|
|
5
|
-
import { SqlClient } from "effect/sql";
|
|
4
|
+
import { StreamRoute, Streams } from "@streamsy/core/protocol";
|
|
5
|
+
import { SqlClient, SqlError } from "effect/sql";
|
|
6
6
|
interface RunOptions {
|
|
7
7
|
/** Maximum checkpoint transactions per call; absent means run to completion. */
|
|
8
8
|
readonly limit?: number;
|
|
@@ -177,11 +177,25 @@ declare function fold<C extends StreamRoute.ParamCodecs, I extends Inputs, A, SI
|
|
|
177
177
|
readonly commit?: Committing<Folded<NoInfer<A>>, P, Q>["commit"];
|
|
178
178
|
readonly fold: (state: NoInfer<A>, entry: Entry<Addresses<I>>, unit: Unit<StreamRoute.Params<C>>) => Step<A, E, R>;
|
|
179
179
|
}): StatefulDeclaration<C, I, A, E, R, Folded<A>, P, Q>;
|
|
180
|
+
/** The third argument of `process`. */
|
|
181
|
+
interface ProcessContext<Prepared = void> {
|
|
182
|
+
readonly prepared: Prepared;
|
|
183
|
+
}
|
|
184
|
+
/** The bound address of each declared output, in the context of `prepare` and `process`. */
|
|
185
|
+
interface OutputsContext<O extends RoutedMap> {
|
|
186
|
+
readonly outputs: Addresses<O>;
|
|
187
|
+
}
|
|
180
188
|
/** Run side effects once per unit. prepare runs at least once, outside the transaction. */
|
|
181
|
-
declare function process<C extends StreamRoute.ParamCodecs, I extends Inputs, E = never, R = never, P = never, Q = never, Prepared = void, PE = never, PR = never>(definition: Common<C, I> & Committing<void, P, Q> & {
|
|
189
|
+
declare function process$1<C extends StreamRoute.ParamCodecs, I extends Inputs, E = never, R = never, P = never, Q = never, Prepared = void, PE = never, PR = never>(definition: Common<C, I> & Committing<void, P, Q> & {
|
|
190
|
+
readonly outputs?: never;
|
|
182
191
|
readonly prepare?: (batch: Slices<Addresses<I>>, unit: Unit<StreamRoute.Params<C>>) => Effect.Effect<Prepared, PE, PR>;
|
|
183
|
-
readonly process: (batch: Slices<Addresses<I>>, unit: Unit<StreamRoute.Params<C>>,
|
|
192
|
+
readonly process: (batch: Slices<Addresses<I>>, unit: Unit<StreamRoute.Params<C>>, context: ProcessContext<Prepared>) => Effect.Effect<void, E, R>;
|
|
184
193
|
}): RunningDeclaration<C, I, E | PE, R, void, P, Q | PR>;
|
|
194
|
+
declare function process$1<C extends StreamRoute.ParamCodecs, I extends Inputs, const O extends RoutedMap, E = never, R = never, Q = never, Prepared = void, PE = never, PR = never>(definition: Common<C, I> & Committing<void, SqlClient.SqlClient, Q> & {
|
|
195
|
+
readonly outputs: O & OutputsWithin<C, O>;
|
|
196
|
+
readonly prepare?: (batch: Slices<Addresses<I>>, unit: Unit<StreamRoute.Params<C>>, context: OutputsContext<O>) => Effect.Effect<Prepared, PE, PR>;
|
|
197
|
+
readonly process: (batch: Slices<Addresses<I>>, unit: Unit<StreamRoute.Params<C>>, context: ProcessContext<Prepared> & OutputsContext<O>) => Effect.Effect<void, E, R>;
|
|
198
|
+
}): OutputDeclaration<C, I, O, E | PE, R, void, SqlClient.SqlClient, Q | PR>;
|
|
185
199
|
/** Emit zero or more output items for each input entry, in entry order. */
|
|
186
200
|
declare function emit<C extends StreamRoute.ParamCodecs, I extends Inputs, const O extends RoutedMap, X extends Emits<O>, E = never, R = never, P = never, Q = never>(definition: Common<C, I> & Committing<Emitted<NoInfer<O>>, P, Q> & {
|
|
187
201
|
readonly outputs: O & OutputsWithin<C, O>;
|
|
@@ -280,7 +294,10 @@ interface Attachable<B> {
|
|
|
280
294
|
interface AttachOptions {
|
|
281
295
|
/** Units for each binding in one run. Default 100. */
|
|
282
296
|
readonly limit?: number;
|
|
283
|
-
/**
|
|
297
|
+
/**
|
|
298
|
+
* Retry a failed drain pass, whether it failed with a typed error or a defect.
|
|
299
|
+
* Defaults to capped, jittered exponential backoff.
|
|
300
|
+
*/
|
|
284
301
|
readonly retry?: Schedule.Schedule<unknown>;
|
|
285
302
|
/**
|
|
286
303
|
* Keep a pending mark for each binding in the storage owner, written in the
|
|
@@ -408,11 +425,112 @@ type WakeDeclaration<C extends StreamRoute.ParamCodecs, I extends Input, O exten
|
|
|
408
425
|
*/
|
|
409
426
|
declare function wake<C extends StreamRoute.ParamCodecs, const I extends Input, const O extends WakeOutput>(definition: WakeDefinition<C, I, O>): WakeDeclaration<C, I, O>;
|
|
410
427
|
declare namespace projection_d_exports {
|
|
411
|
-
export { attach$1 as attach, current, decide, each, emit, fold, follow, forget, items, key, mapAccum, mapAccumBatch, pass, process, read, run, wake };
|
|
428
|
+
export { attach$1 as attach, current, decide, each, emit, fold, follow, forget, items, key, mapAccum, mapAccumBatch, pass, process$1 as process, read, run, wake };
|
|
412
429
|
}
|
|
413
430
|
declare const key: (projection: Identity) => ProjectionKey;
|
|
414
431
|
/** Runs each tagged entry in order and discards its success value. */
|
|
415
432
|
declare const each: <Inputs extends InputMap, E, R, P = Record<string, string>>(handle: (entry: Entry<Inputs>, unit: Unit<P>) => Effect.Effect<unknown, E, R>) => ((batch: Slices<Inputs>, unit: Unit<P>) => Effect.Effect<void, E, R>);
|
|
433
|
+
declare namespace state_table_d_exports {
|
|
434
|
+
export { Bound, Declaration$1 as Declaration, ListOptions, define, migrate, rebuild, reset };
|
|
435
|
+
}
|
|
436
|
+
/** Create the SQLite row index at host startup, outside storage migrations. */
|
|
437
|
+
declare const migrate: (sql: SqlClient.SqlClient) => Effect.Effect<void, ProjectionFault | SqlError.SqlError, never>;
|
|
438
|
+
/** Keyset pages are not snapshots. Follow changes from the first page's offset. */
|
|
439
|
+
interface ListOptions {
|
|
440
|
+
readonly after?: string | undefined;
|
|
441
|
+
readonly limit?: number | undefined;
|
|
442
|
+
}
|
|
443
|
+
/** A State stream bound to its params: a bound projection, plus the row reads and `sync`. */
|
|
444
|
+
interface Bound<C extends StreamAddress.Collections, R> {
|
|
445
|
+
readonly id: string;
|
|
446
|
+
readonly version: number;
|
|
447
|
+
readonly generation: number;
|
|
448
|
+
readonly params: Record<string, string>;
|
|
449
|
+
/** The State stream, read as stored JSON text. */
|
|
450
|
+
readonly inputs: {
|
|
451
|
+
readonly state: Streamsy.Address<string, R>;
|
|
452
|
+
};
|
|
453
|
+
readonly commit: typeof transaction;
|
|
454
|
+
readonly process: (batch: Slices<{
|
|
455
|
+
readonly state: Streamsy.Address<string, R>;
|
|
456
|
+
}>) => Effect.Effect<void, ProjectionFault, Transaction | R>;
|
|
457
|
+
/** The row of `key`. `value` is undefined when the row is absent. */
|
|
458
|
+
readonly get: <K extends keyof C & string>(collection: K, key: string) => Effect.Effect<{
|
|
459
|
+
readonly offset: string;
|
|
460
|
+
readonly value: C[K]["schema"]["Type"] | undefined;
|
|
461
|
+
}, Schema.SchemaError | SqlError.SqlError, SqlClient.SqlClient | C[K]["schema"]["DecodingServices"]>;
|
|
462
|
+
/** The rows of `keys` that exist, by key. */
|
|
463
|
+
readonly getMany: <K extends keyof C & string>(collection: K, keys: ReadonlyArray<string>) => Effect.Effect<{
|
|
464
|
+
readonly offset: string;
|
|
465
|
+
readonly rows: ReadonlyMap<string, C[K]["schema"]["Type"]>;
|
|
466
|
+
}, Schema.SchemaError | SqlError.SqlError, SqlClient.SqlClient | C[K]["schema"]["DecodingServices"]>;
|
|
467
|
+
/** The rows in key order. `next` is the last key of a full page. */
|
|
468
|
+
readonly list: <K extends keyof C & string>(collection: K, options?: ListOptions) => Effect.Effect<{
|
|
469
|
+
readonly offset: string;
|
|
470
|
+
readonly rows: ReadonlyArray<{
|
|
471
|
+
readonly key: string;
|
|
472
|
+
readonly value: C[K]["schema"]["Type"];
|
|
473
|
+
}>;
|
|
474
|
+
readonly next: string | undefined;
|
|
475
|
+
}, ProjectionFault | Schema.SchemaError | SqlError.SqlError, SqlClient.SqlClient | C[K]["schema"]["DecodingServices"]>;
|
|
476
|
+
/** The stream offset that the rows reflect. */
|
|
477
|
+
readonly offset: () => Effect.Effect<string, SqlError.SqlError, SqlClient.SqlClient>;
|
|
478
|
+
/** Apply the stream from the head of the table to its tail, in the caller's transaction. */
|
|
479
|
+
readonly sync: () => Effect.Effect<void, ProjectionFault, Transaction | R>;
|
|
480
|
+
}
|
|
481
|
+
/** The declaration of a State table. Runners and `attach` take it like any declaration. */
|
|
482
|
+
interface Declaration$1<Codecs extends StreamRoute.ParamCodecs, C extends StreamAddress.Collections, R> extends Omit<Declaration<Codecs, Bound<C, R>>, "inputs" | "parse"> {
|
|
483
|
+
readonly inputs: {
|
|
484
|
+
readonly state: State<Codecs, C, R>;
|
|
485
|
+
};
|
|
486
|
+
readonly parse: (id: string) => Option.Option<StreamRoute.Params<Codecs>>;
|
|
487
|
+
}
|
|
488
|
+
/** A `Streamsy.state` class with param codecs `Codecs` and collections `C`, served by `R`. */
|
|
489
|
+
type State<Codecs extends StreamRoute.ParamCodecs, C extends StreamAddress.Collections, R> = StreamRoute.StateRoute<StreamRoute.Params<Codecs>, C> & Streamsy.Any & {
|
|
490
|
+
readonly paramCodecs: Codecs;
|
|
491
|
+
readonly at: (params: StreamRoute.Params<Codecs>) => StreamAddress.StateAddress<C> & Streamsy.Address<StreamAddress.CollectionsEvent<C>, R, StreamAddress.CollectionsDecodingServices<C>, StreamAddress.CollectionsEncodingServices<C>>;
|
|
492
|
+
};
|
|
493
|
+
/** A State stream's declaration, kept current by the ordinary projection runners. */
|
|
494
|
+
declare function define<Codecs extends StreamRoute.ParamCodecs, C extends StreamAddress.Collections, R>(state: State<Codecs, C, R>): Declaration$1<Codecs, C, R>;
|
|
495
|
+
/** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
|
|
496
|
+
declare const rebuild: <C extends StreamAddress.Collections, R>(table: Bound<C, R>) => Effect.Effect<void, ProjectionFault, R | Transaction>;
|
|
497
|
+
/** Append a reset to the State stream. The next table run applies it. */
|
|
498
|
+
declare const reset: <C extends StreamAddress.Collections, R>(table: Bound<C, R>) => Effect.Effect<import("@streamsy/core").AppendResult, Streams.AppendFailure<{}>, R>;
|
|
499
|
+
declare const FoldByKeyError_base: Schema.Class<FoldByKeyError, Schema.TaggedStruct<"FoldByKeyError", {
|
|
500
|
+
readonly message: Schema.String;
|
|
501
|
+
}>, import("effect/Cause").YieldableError & {
|
|
502
|
+
readonly brand: unique symbol;
|
|
503
|
+
}>;
|
|
504
|
+
/** A folded row disagreed with the key that was used to load its previous row. */
|
|
505
|
+
export declare class FoldByKeyError extends FoldByKeyError_base {}
|
|
506
|
+
declare namespace fold_by_key_d_exports {
|
|
507
|
+
export { Handler, Remove, process, remove };
|
|
508
|
+
}
|
|
509
|
+
/** Return this from a fold to delete its row. The next record receives undefined. */
|
|
510
|
+
declare const remove: unique symbol;
|
|
511
|
+
type Remove = typeof remove;
|
|
512
|
+
type Output<C extends StreamAddress.Collections, R> = StreamAddress.StateAddress<C> & Streamsy.Address<StreamAddress.CollectionsEvent<C>, R, StreamAddress.CollectionsDecodingServices<C>, StreamAddress.CollectionsEncodingServices<C>>;
|
|
513
|
+
/**
|
|
514
|
+
* A `Projection.process` handler for a declaration that lists the State stream
|
|
515
|
+
* of the table in `outputs`, under the key `O`.
|
|
516
|
+
*/
|
|
517
|
+
type Handler<C extends StreamAddress.Collections, O extends string, I extends InputMap, P, E, R, TR> = (batch: Slices<I>, unit: Unit<P>, context: {
|
|
518
|
+
readonly outputs: Readonly<Record<O, Output<C, TR>>>;
|
|
519
|
+
}) => Effect.Effect<void, E | FoldByKeyError | ProjectionFault, R | TR | SqlClient.SqlClient | Transaction | StreamAddress.CollectionsDecodingServices<C> | StreamAddress.CollectionsEncodingServices<C>>;
|
|
520
|
+
interface Spec<C extends StreamAddress.Collections, K extends keyof C & string, O extends string, A, P, E, R> {
|
|
521
|
+
readonly output: O;
|
|
522
|
+
readonly collection: K;
|
|
523
|
+
readonly key: (record: A, unit: Unit<P>) => string | undefined;
|
|
524
|
+
readonly fold: (previous: C[K]["schema"]["Type"] | undefined, record: A, unit: Unit<P>) => Step<C[K]["schema"]["Type"] | Remove, E, R>;
|
|
525
|
+
}
|
|
526
|
+
type Expanded<C extends StreamAddress.Collections, K extends keyof C & string, O extends string, I extends InputMap, A, P, E, R> = Spec<C, K, O, A, P, E, R> & {
|
|
527
|
+
readonly records: (item: ItemOf<I[keyof I]>, unit: Unit<P>) => ReadonlyArray<A>;
|
|
528
|
+
};
|
|
529
|
+
/** Build a transaction process handler for one collection, grouping records in first-seen order. */
|
|
530
|
+
declare function process<Codecs extends StreamRoute.ParamCodecs, C extends StreamAddress.Collections, TR, K extends keyof C & string, O extends string, I extends InputMap, A, P, E = never, R = never>(table: Declaration$1<Codecs, C, TR>, spec: Expanded<C, K, O, I, A, P, E, R>): Handler<C, O, I, P, E, R, TR>;
|
|
531
|
+
declare function process<Codecs extends StreamRoute.ParamCodecs, C extends StreamAddress.Collections, TR, K extends keyof C & string, O extends string, I extends InputMap, P, E = never, R = never>(table: Declaration$1<Codecs, C, TR>, spec: Spec<C, K, O, ItemOf<I[keyof I]>, P, E, R> & {
|
|
532
|
+
readonly records?: never;
|
|
533
|
+
}): Handler<C, O, I, P, E, R, TR>;
|
|
416
534
|
/** Default retry for following and attached runners; an explicit options.retry takes precedence. */
|
|
417
535
|
export declare const ProjectionRetry: Context.Reference<Schedule.Schedule<unknown, unknown, never, never>>;
|
|
418
536
|
/**
|
|
@@ -439,4 +557,4 @@ declare const attach: <I extends InputMap, E, R, Q, Result, P, OR = never>(proje
|
|
|
439
557
|
export declare const ProjectionWakeup: {
|
|
440
558
|
attach: typeof attach;
|
|
441
559
|
};
|
|
442
|
-
export { type Accumulated, type AttachOptions, type Attachable, CheckpointRecord, CheckpointStore, type CheckpointStoreApi, commit_d_exports as Commit, type CurrentProjection, type DecideSpec, type Declaration, type Emits, type Emitted, type Entry, type Folded, type FollowOptions, type Identity, type Initial, type InputMap, type ItemOf, type Loaded, type Offsets, type OutputBatch, type PassResult, type Progress, projection_d_exports as Projection, ProjectionFault, type ProjectionKey, type Range, type RunOptions, type Slice, type Slices, type Snapshot, type StateDefinition, type StateSchema, type Step, type Unit };
|
|
560
|
+
export { type Accumulated, type AttachOptions, type Attachable, CheckpointRecord, CheckpointStore, type CheckpointStoreApi, commit_d_exports as Commit, type CurrentProjection, type DecideSpec, type Declaration, type Emits, type Emitted, type Entry, fold_by_key_d_exports as FoldByKey, type Folded, type FollowOptions, type Identity, type Initial, type InputMap, type ItemOf, type Loaded, type Offsets, type OutputBatch, type OutputsContext, type PassResult, type ProcessContext, type Progress, projection_d_exports as Projection, ProjectionFault, type ProjectionKey, type Range, type RunOptions, type Slice, type Slices, type Snapshot, type StateDefinition, type StateSchema, state_table_d_exports as StateTable, type Step, type Unit };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
|
|
2
2
|
import { a as rangesOf, c as canonicalParams, d as withParams, f as ProjectionFault, l as terminalOf, n as CheckpointStore, r as advance, s as restore, t as CheckpointRecord, u as unitOf } from "./checkpoint-store-Bm8z-f-l.js";
|
|
3
3
|
import { Array, Cause, Clock, Context, Data, Duration, Effect, Exit, Function, Layer, Option, Pipeable, Predicate, PubSub, Record, Ref, Result, Schedule, Schema, Stream } from "effect";
|
|
4
|
-
import { CommitBoundary, DurableState, Offset, Storage, StreamId, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
4
|
+
import { CommitBoundary, DurableState, Offset, Storage, StreamAddress, StreamId, ZERO_OFFSET, compare, isStreamsFault } from "@streamsy/core";
|
|
5
5
|
import { Streams, StreamsWriter } from "@streamsy/core/protocol";
|
|
6
6
|
import { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, ProjectionMarks, compileSegments, fitKey, isForeignOwner, ownerOf } from "@streamsy/core/internal";
|
|
7
7
|
import { SqlClient } from "effect/sql";
|
|
@@ -288,7 +288,7 @@ const { Folded, Emitted, Accumulated } = Data.taggedEnum();
|
|
|
288
288
|
* and return token "0" for an absent record.
|
|
289
289
|
* load must return the stored state. If run and the write are not atomic,
|
|
290
290
|
* declare at-least-once. The guarantee must describe the actual write. */
|
|
291
|
-
const make = (options) => extend({
|
|
291
|
+
const make$1 = (options) => extend({
|
|
292
292
|
...options,
|
|
293
293
|
[TypeId]: {
|
|
294
294
|
result: () => {},
|
|
@@ -311,7 +311,7 @@ const detailsOf = (pending) => {
|
|
|
311
311
|
};
|
|
312
312
|
};
|
|
313
313
|
const load = (key) => CheckpointStore.use((store) => store.load(key));
|
|
314
|
-
const remove = (key) => CheckpointStore.use((store) => store.remove(key));
|
|
314
|
+
const remove$1 = (key) => CheckpointStore.use((store) => store.remove(key));
|
|
315
315
|
const withState = (next, result) => result !== void 0 && "encoded" in result ? {
|
|
316
316
|
...next,
|
|
317
317
|
state: result.encoded
|
|
@@ -322,11 +322,11 @@ const beforeRecord = (pending) => Option.getOrElse(pending.loaded.record, () =>
|
|
|
322
322
|
}));
|
|
323
323
|
const settle = (pending, result) => CheckpointStore.use((store) => store.compareAndSet(pending.key, pending.loaded.token, withState(pending.next, result))).pipe(Effect.asVoid);
|
|
324
324
|
// src/commit/checkpoint.ts
|
|
325
|
-
const checkpoint = make({
|
|
325
|
+
const checkpoint = make$1({
|
|
326
326
|
name: "checkpoint",
|
|
327
327
|
guarantee: "exactly-once",
|
|
328
328
|
load,
|
|
329
|
-
remove,
|
|
329
|
+
remove: remove$1,
|
|
330
330
|
apply: (pending) => Effect.flatMap(pending.run, (result) => settle(pending, result))
|
|
331
331
|
});
|
|
332
332
|
// src/transaction.ts
|
|
@@ -352,11 +352,11 @@ var Transaction = class extends Context.Service()("@streamsy/projection/Transact
|
|
|
352
352
|
}));
|
|
353
353
|
};
|
|
354
354
|
// src/commit/transaction.ts
|
|
355
|
-
const transaction = withPrepare(make({
|
|
355
|
+
const transaction = withPrepare(make$1({
|
|
356
356
|
name: "transaction",
|
|
357
357
|
guarantee: "exactly-once",
|
|
358
358
|
load,
|
|
359
|
-
remove,
|
|
359
|
+
remove: remove$1,
|
|
360
360
|
apply: (pending) => Effect.gen(function* () {
|
|
361
361
|
const tx = yield* Transaction;
|
|
362
362
|
const store = yield* CheckpointStore;
|
|
@@ -424,10 +424,10 @@ const asPin = (fault) => fault.phase === "checkpoint" && fault.reason === "token
|
|
|
424
424
|
reason: fault.reason,
|
|
425
425
|
message: fault.message
|
|
426
426
|
}) : fault;
|
|
427
|
-
const producer = pin(make({
|
|
427
|
+
const producer = pin(make$1({
|
|
428
428
|
name: "producer",
|
|
429
429
|
guarantee: "effectively-once",
|
|
430
|
-
remove,
|
|
430
|
+
remove: remove$1,
|
|
431
431
|
load: (key) => Effect.gen(function* () {
|
|
432
432
|
const loaded = yield* load(key);
|
|
433
433
|
if (Option.isSome(loaded.record)) {
|
|
@@ -530,11 +530,11 @@ const producer = pin(make({
|
|
|
530
530
|
})
|
|
531
531
|
}));
|
|
532
532
|
// src/commit/at-least-once.ts
|
|
533
|
-
const atLeastOnce = pin(make({
|
|
533
|
+
const atLeastOnce = pin(make$1({
|
|
534
534
|
name: "atLeastOnce",
|
|
535
535
|
guarantee: "at-least-once",
|
|
536
536
|
load,
|
|
537
|
-
remove,
|
|
537
|
+
remove: remove$1,
|
|
538
538
|
apply: (pending) => Effect.gen(function* () {
|
|
539
539
|
const store = yield* CheckpointStore;
|
|
540
540
|
const before = beforeRecord(pending);
|
|
@@ -547,7 +547,7 @@ const atLeastOnce = pin(make({
|
|
|
547
547
|
})
|
|
548
548
|
}));
|
|
549
549
|
// src/commit/compensation.ts
|
|
550
|
-
const withCompensation = Function.dual(2, (self, f) => inherit(self, make({
|
|
550
|
+
const withCompensation = Function.dual(2, (self, f) => inherit(self, make$1({
|
|
551
551
|
...self,
|
|
552
552
|
apply: (pending) => Effect.suspend(() => {
|
|
553
553
|
let completed = Option.none();
|
|
@@ -569,7 +569,7 @@ var commit_exports = /* @__PURE__ */ __exportAll({
|
|
|
569
569
|
TypeId: () => TypeId,
|
|
570
570
|
atLeastOnce: () => atLeastOnce,
|
|
571
571
|
checkpoint: () => checkpoint,
|
|
572
|
-
make: () => make,
|
|
572
|
+
make: () => make$1,
|
|
573
573
|
producer: () => producer,
|
|
574
574
|
transaction: () => transaction,
|
|
575
575
|
withCompensation: () => withCompensation
|
|
@@ -603,7 +603,10 @@ const encodeState = (key, schema, value) => Schema.encodeEffect(Schema.fromJsonS
|
|
|
603
603
|
// src/step.ts
|
|
604
604
|
/** One adapter invocation is one unit. Per-entry variants thread state and preserve order. */
|
|
605
605
|
const adapt = (kind, key, state, streams, handler, batch, unit, encoded, prepared) => Effect.gen(function* () {
|
|
606
|
-
if (kind === "process") return yield* Effect.asVoid(handler(batch, unit,
|
|
606
|
+
if (kind === "process") return yield* Effect.asVoid(handler(batch, unit, {
|
|
607
|
+
prepared,
|
|
608
|
+
outputs: streams
|
|
609
|
+
}));
|
|
607
610
|
let value = state === void 0 ? void 0 : yield* currentState(key, state, encoded);
|
|
608
611
|
const buffers = Record.fromEntries(Array.map(Record.keys(streams), (name) => [name, []]));
|
|
609
612
|
const steps = kind === "mapAccumBatch" ? [batch] : items(batch);
|
|
@@ -684,7 +687,7 @@ const build = (kind, definition) => {
|
|
|
684
687
|
state,
|
|
685
688
|
streams,
|
|
686
689
|
commit,
|
|
687
|
-
prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded)),
|
|
690
|
+
prepare: definition.prepare === void 0 ? void 0 : (batch, unit) => definition.prepare(batch, withParams(unit, decoded), { outputs: streams }),
|
|
688
691
|
process: (batch, unit, encoded, prepared) => adapt(kind, key, state, streams, definition[kind], batch, withParams(unit, decoded), encoded, prepared)
|
|
689
692
|
};
|
|
690
693
|
});
|
|
@@ -694,7 +697,7 @@ function fold(definition) {
|
|
|
694
697
|
return build("fold", definition);
|
|
695
698
|
}
|
|
696
699
|
// src/process.ts
|
|
697
|
-
function process(definition) {
|
|
700
|
+
function process$1(definition) {
|
|
698
701
|
return build("process", definition);
|
|
699
702
|
}
|
|
700
703
|
// src/emit.ts
|
|
@@ -1220,6 +1223,8 @@ const runnerOf = (declaration, options = {}) => {
|
|
|
1220
1223
|
});
|
|
1221
1224
|
};
|
|
1222
1225
|
// src/attach.ts
|
|
1226
|
+
/** A defect of one drain pass, as a failure that the retry schedule sees. */
|
|
1227
|
+
var PassDefect = class extends Schema.TaggedError()("PassDefect", { defect: Schema.Defect() }) {};
|
|
1223
1228
|
/**
|
|
1224
1229
|
* Run a projection whenever a local commit writes one of its inputs. The layer
|
|
1225
1230
|
* subscribes to `Storage.committed` when it is built, so build it with the
|
|
@@ -1251,7 +1256,7 @@ const attach$1 = (projection, options = {}) => {
|
|
|
1251
1256
|
return Layer.effectDiscard(Effect.gen(function* () {
|
|
1252
1257
|
const { wait, drain } = yield* runner;
|
|
1253
1258
|
const retry = options.retry ?? (yield* ProjectionRetry);
|
|
1254
|
-
yield* wait.pipe(Effect.andThen(drain), Effect.tapError((error) => Effect.logError(`Projection.attach ${projection.id} failed`, error)), Effect.retry(retry), Effect.repeat(Schedule.forever), Effect.withSpan("Projection.attach"), Effect.forkScoped);
|
|
1259
|
+
yield* wait.pipe(Effect.andThen(drain), Effect.catchDefect((defect) => Effect.fail(new PassDefect({ defect }))), Effect.tapError((error) => Effect.logError(`Projection.attach ${projection.id} failed`, error)), Effect.retry(retry), Effect.repeat(Schedule.forever), Effect.withSpan("Projection.attach"), Effect.forkScoped);
|
|
1255
1260
|
}));
|
|
1256
1261
|
};
|
|
1257
1262
|
// src/current.ts
|
|
@@ -1393,7 +1398,7 @@ var projection_exports = /* @__PURE__ */ __exportAll({
|
|
|
1393
1398
|
mapAccum: () => mapAccum,
|
|
1394
1399
|
mapAccumBatch: () => mapAccumBatch,
|
|
1395
1400
|
pass: () => pass,
|
|
1396
|
-
process: () => process,
|
|
1401
|
+
process: () => process$1,
|
|
1397
1402
|
read: () => read,
|
|
1398
1403
|
run: () => run,
|
|
1399
1404
|
wake: () => wake
|
|
@@ -1406,6 +1411,373 @@ const key = (projection) => ({
|
|
|
1406
1411
|
});
|
|
1407
1412
|
/** Runs each tagged entry in order and discards its success value. */
|
|
1408
1413
|
const each = (handle) => (batch, unit) => Effect.forEach(items(batch), (entry) => handle(entry, unit), { discard: true });
|
|
1414
|
+
// src/state-table-message.ts
|
|
1415
|
+
const Message = Schema.Union([
|
|
1416
|
+
Schema.Struct({ headers: Schema.Struct({ control: Schema.Literals([
|
|
1417
|
+
"reset",
|
|
1418
|
+
"snapshot-start",
|
|
1419
|
+
"snapshot-end"
|
|
1420
|
+
]) }) }),
|
|
1421
|
+
Schema.Struct({
|
|
1422
|
+
type: Schema.String,
|
|
1423
|
+
key: Schema.String,
|
|
1424
|
+
headers: Schema.Struct({ operation: Schema.Literals([
|
|
1425
|
+
"insert",
|
|
1426
|
+
"update",
|
|
1427
|
+
"upsert"
|
|
1428
|
+
]) }),
|
|
1429
|
+
value: Schema.Unknown
|
|
1430
|
+
}),
|
|
1431
|
+
Schema.Struct({
|
|
1432
|
+
type: Schema.String,
|
|
1433
|
+
key: Schema.String,
|
|
1434
|
+
headers: Schema.Struct({ operation: Schema.Literal("delete") })
|
|
1435
|
+
})
|
|
1436
|
+
]);
|
|
1437
|
+
const Change = Data.taggedEnum();
|
|
1438
|
+
const decode = Schema.decodeEffect(Schema.fromJsonString(Message));
|
|
1439
|
+
/**
|
|
1440
|
+
* Only the protocol envelope is decoded; collection values never pass through a codec.
|
|
1441
|
+
* `JSON.stringify` gives the bytes that storage holds, because core stores each JSON
|
|
1442
|
+
* message as `JSON.stringify` of the parsed item.
|
|
1443
|
+
*/
|
|
1444
|
+
const message = (json) => Effect.map(decode(json), (decoded) => {
|
|
1445
|
+
if (!("type" in decoded)) return Change.Control({ control: decoded.headers.control });
|
|
1446
|
+
return "value" in decoded ? Change.Upsert({
|
|
1447
|
+
collection: decoded.type,
|
|
1448
|
+
key: decoded.key,
|
|
1449
|
+
value: JSON.stringify(decoded.value)
|
|
1450
|
+
}) : Change.Delete({
|
|
1451
|
+
collection: decoded.type,
|
|
1452
|
+
key: decoded.key
|
|
1453
|
+
});
|
|
1454
|
+
});
|
|
1455
|
+
/** The stored message of an upsert whose value is already canonical JSON. */
|
|
1456
|
+
const upsertJson = (collection, key, value) => `{"type":${JSON.stringify(collection)},"key":${JSON.stringify(key)},"value":${value},"headers":{"operation":"upsert"}}`;
|
|
1457
|
+
/** The stored message of a delete. */
|
|
1458
|
+
const deleteJson = (collection, key) => JSON.stringify({
|
|
1459
|
+
type: collection,
|
|
1460
|
+
key,
|
|
1461
|
+
headers: { operation: "delete" }
|
|
1462
|
+
});
|
|
1463
|
+
// src/state-table-rows.ts
|
|
1464
|
+
/** Decode one stored value, which is canonical JSON, with its collection schema. */
|
|
1465
|
+
const decodeRow = (schema, json) => Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema)))(json);
|
|
1466
|
+
/** Encode one row to the canonical JSON that the table stores for it. */
|
|
1467
|
+
const encodeRow = (schema, value) => Schema.encodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema)))(value);
|
|
1468
|
+
/** The stored JSON of each key that has a row. A missing key has no entry. */
|
|
1469
|
+
const storedValues = Effect.fn("StateTable.storedValues")(function* (sql, id, collection, keys) {
|
|
1470
|
+
const values = /* @__PURE__ */ new Map();
|
|
1471
|
+
for (const chunk of Array.chunksOf(keys, 50)) {
|
|
1472
|
+
const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND ${sql.in("row_key", chunk)}`;
|
|
1473
|
+
for (const row of found) values.set(row.row_key, row.value);
|
|
1474
|
+
}
|
|
1475
|
+
return values;
|
|
1476
|
+
});
|
|
1477
|
+
// src/state-table.ts
|
|
1478
|
+
var state_table_exports = /* @__PURE__ */ __exportAll({
|
|
1479
|
+
define: () => define,
|
|
1480
|
+
migrate: () => migrate,
|
|
1481
|
+
rebuild: () => rebuild,
|
|
1482
|
+
reset: () => reset
|
|
1483
|
+
});
|
|
1484
|
+
const empty = {
|
|
1485
|
+
applied_offset: ZERO_OFFSET,
|
|
1486
|
+
epoch: 0,
|
|
1487
|
+
snapshot_open: 0
|
|
1488
|
+
};
|
|
1489
|
+
const head = (sql, id) => Effect.map(sql`SELECT applied_offset, epoch, snapshot_open FROM streamsy_state_heads WHERE stream_id = ${id}`, Array.head);
|
|
1490
|
+
/** The offset that the rows reflect. A table with no head has no rows. */
|
|
1491
|
+
const appliedOffset = (sql, id) => Effect.map(head(sql, id), (stored) => Option.getOrElse(stored, () => empty).applied_offset);
|
|
1492
|
+
const clearRows = (sql, id) => sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}`;
|
|
1493
|
+
const save = (sql, id, state) => sql`INSERT INTO streamsy_state_heads (stream_id, applied_offset, epoch, snapshot_open)
|
|
1494
|
+
VALUES (${id}, ${state.applied_offset}, ${state.epoch}, ${state.snapshot_open})
|
|
1495
|
+
ON CONFLICT (stream_id) DO UPDATE SET applied_offset = excluded.applied_offset,
|
|
1496
|
+
epoch = excluded.epoch, snapshot_open = excluded.snapshot_open`;
|
|
1497
|
+
const sqlFault = (id) => (cause) => new ProjectionFault({
|
|
1498
|
+
phase: "process",
|
|
1499
|
+
reason: "storage-failure",
|
|
1500
|
+
message: `Cannot update the rows of ${id}`,
|
|
1501
|
+
cause
|
|
1502
|
+
});
|
|
1503
|
+
const apply = Effect.fn("StateTable.apply")(function* (sql, id, before, items) {
|
|
1504
|
+
let epoch = before.epoch;
|
|
1505
|
+
let open = before.snapshot_open;
|
|
1506
|
+
for (const item of items) yield* Change.$match(yield* message(item), {
|
|
1507
|
+
Control: ({ control }) => {
|
|
1508
|
+
if (control === "reset") {
|
|
1509
|
+
open = 0;
|
|
1510
|
+
return Effect.asVoid(clearRows(sql, id));
|
|
1511
|
+
}
|
|
1512
|
+
if (control === "snapshot-start") {
|
|
1513
|
+
epoch += 1;
|
|
1514
|
+
open = 1;
|
|
1515
|
+
return Effect.void;
|
|
1516
|
+
}
|
|
1517
|
+
if (open === 0) return Effect.void;
|
|
1518
|
+
open = 0;
|
|
1519
|
+
return Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id} AND epoch < ${epoch}`);
|
|
1520
|
+
},
|
|
1521
|
+
Upsert: ({ collection, key, value }) => Effect.asVoid(sql`INSERT INTO streamsy_state_rows (stream_id, collection, row_key, value, epoch)
|
|
1522
|
+
VALUES (${id}, ${collection}, ${key}, ${value}, ${epoch})
|
|
1523
|
+
ON CONFLICT (stream_id, collection, row_key) DO UPDATE SET value = excluded.value, epoch = excluded.epoch`),
|
|
1524
|
+
Delete: ({ collection, key }) => Effect.asVoid(sql`DELETE FROM streamsy_state_rows WHERE stream_id = ${id}
|
|
1525
|
+
AND collection = ${collection} AND row_key = ${key}`)
|
|
1526
|
+
});
|
|
1527
|
+
return {
|
|
1528
|
+
epoch,
|
|
1529
|
+
snapshot_open: open
|
|
1530
|
+
};
|
|
1531
|
+
}, (effect, _sql, id) => Effect.catchTag(effect, "SchemaError", (cause) => new ProjectionFault({
|
|
1532
|
+
phase: "process",
|
|
1533
|
+
reason: "invalid-record",
|
|
1534
|
+
message: `A stored message of ${id} is not a State message`,
|
|
1535
|
+
cause
|
|
1536
|
+
})));
|
|
1537
|
+
/** Create the SQLite row index at host startup, outside storage migrations. */
|
|
1538
|
+
const migrate = Effect.fn("StateTable.migrate")(function* (sql) {
|
|
1539
|
+
yield* sql.onDialectOrElse({
|
|
1540
|
+
sqlite: () => Effect.void,
|
|
1541
|
+
orElse: () => Effect.fail(new ProjectionFault({
|
|
1542
|
+
phase: "load",
|
|
1543
|
+
reason: "unsupported-composition",
|
|
1544
|
+
message: "StateTable requires SQLite"
|
|
1545
|
+
}))
|
|
1546
|
+
});
|
|
1547
|
+
yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_heads (
|
|
1548
|
+
stream_id TEXT PRIMARY KEY,
|
|
1549
|
+
applied_offset TEXT NOT NULL,
|
|
1550
|
+
epoch INTEGER NOT NULL DEFAULT 0,
|
|
1551
|
+
snapshot_open INTEGER NOT NULL DEFAULT 0
|
|
1552
|
+
) WITHOUT ROWID`;
|
|
1553
|
+
yield* sql`CREATE TABLE IF NOT EXISTS streamsy_state_rows (
|
|
1554
|
+
stream_id TEXT NOT NULL,
|
|
1555
|
+
collection TEXT NOT NULL,
|
|
1556
|
+
row_key TEXT NOT NULL,
|
|
1557
|
+
value TEXT NOT NULL,
|
|
1558
|
+
epoch INTEGER NOT NULL DEFAULT 0,
|
|
1559
|
+
PRIMARY KEY (stream_id, collection, row_key)
|
|
1560
|
+
) WITHOUT ROWID`;
|
|
1561
|
+
});
|
|
1562
|
+
const synchronize = (address) => Effect.gen(function* () {
|
|
1563
|
+
const { sql } = yield* Transaction;
|
|
1564
|
+
const { wire } = yield* address.stream;
|
|
1565
|
+
const unavailable = () => new ProjectionFault({
|
|
1566
|
+
phase: "read",
|
|
1567
|
+
reason: "history-unavailable",
|
|
1568
|
+
message: `Required history of ${address.id} is unavailable`
|
|
1569
|
+
});
|
|
1570
|
+
const storage = (cause) => new ProjectionFault({
|
|
1571
|
+
phase: "read",
|
|
1572
|
+
reason: "storage-failure",
|
|
1573
|
+
message: `Cannot read ${address.id}`,
|
|
1574
|
+
cause
|
|
1575
|
+
});
|
|
1576
|
+
const stored = yield* head(sql, address.id);
|
|
1577
|
+
const tail = yield* wire.head(address.id).pipe(Effect.catchTags({
|
|
1578
|
+
StreamNotFound: unavailable,
|
|
1579
|
+
StreamGone: unavailable,
|
|
1580
|
+
StorageFault: storage,
|
|
1581
|
+
TransportFault: storage
|
|
1582
|
+
}));
|
|
1583
|
+
let state = Option.getOrElse(stored, () => empty);
|
|
1584
|
+
if (Option.isNone(stored) || compare(state.applied_offset, tail.nextOffset) > 0) {
|
|
1585
|
+
yield* clearRows(sql, address.id);
|
|
1586
|
+
state = empty;
|
|
1587
|
+
}
|
|
1588
|
+
while (compare(state.applied_offset, tail.nextOffset) < 0) {
|
|
1589
|
+
const page = yield* wire.read(address.id, { offset: state.applied_offset }).pipe(Effect.catchTags({
|
|
1590
|
+
InvalidReadRequest: (cause) => new ProjectionFault({
|
|
1591
|
+
phase: "read",
|
|
1592
|
+
reason: "invalid-source",
|
|
1593
|
+
message: cause.message,
|
|
1594
|
+
cause
|
|
1595
|
+
}),
|
|
1596
|
+
StreamNotFound: unavailable,
|
|
1597
|
+
StreamGone: unavailable,
|
|
1598
|
+
StorageFault: storage,
|
|
1599
|
+
TransportFault: storage
|
|
1600
|
+
}));
|
|
1601
|
+
if (compare(page.nextOffset, state.applied_offset) <= 0) return yield* unavailable();
|
|
1602
|
+
state = {
|
|
1603
|
+
...yield* apply(sql, address.id, state, Array.map(page.messages, (item) => new TextDecoder().decode(item.data))),
|
|
1604
|
+
applied_offset: page.nextOffset
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
return yield* save(sql, address.id, state);
|
|
1608
|
+
}).pipe(Effect.catchTag("SqlError", sqlFault(address.id)), Effect.asVoid, Effect.withSpan("StateTable.sync"));
|
|
1609
|
+
const applySlice = (address, slice) => Effect.gen(function* () {
|
|
1610
|
+
const { sql } = yield* Transaction;
|
|
1611
|
+
const stored = yield* head(sql, address.id);
|
|
1612
|
+
if (Option.isSome(stored) && stored.value.applied_offset === slice.from || Option.isNone(stored) && slice.from === ZERO_OFFSET) {
|
|
1613
|
+
if (Option.isNone(stored)) yield* clearRows(sql, address.id);
|
|
1614
|
+
const next = yield* apply(sql, address.id, Option.getOrElse(stored, () => empty), slice.items);
|
|
1615
|
+
yield* save(sql, address.id, {
|
|
1616
|
+
...next,
|
|
1617
|
+
applied_offset: slice.nextOffset
|
|
1618
|
+
});
|
|
1619
|
+
} else yield* synchronize(address);
|
|
1620
|
+
}).pipe(Effect.catchTag("SqlError", sqlFault(address.id)), Effect.withSpan("StateTable.applySlice"));
|
|
1621
|
+
const reads = (id, collections) => {
|
|
1622
|
+
const readValue = (collection, json) => {
|
|
1623
|
+
const entry = collections[collection];
|
|
1624
|
+
if (entry === void 0) return Effect.die(/* @__PURE__ */ new RangeError(`Unknown State collection ${collection}`));
|
|
1625
|
+
return decodeRow(entry.schema, json);
|
|
1626
|
+
};
|
|
1627
|
+
return {
|
|
1628
|
+
offset: Effect.fn("StateTable.offset")(function* () {
|
|
1629
|
+
return yield* appliedOffset(yield* SqlClient.SqlClient, id);
|
|
1630
|
+
}),
|
|
1631
|
+
get: Effect.fn("StateTable.get")(function* (collection, key) {
|
|
1632
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1633
|
+
const offset = yield* appliedOffset(sql, id);
|
|
1634
|
+
const row = (yield* sql`SELECT value FROM streamsy_state_rows WHERE stream_id = ${id} AND collection = ${collection} AND row_key = ${key}`)[0];
|
|
1635
|
+
return {
|
|
1636
|
+
offset,
|
|
1637
|
+
value: row === void 0 ? void 0 : yield* readValue(collection, row.value)
|
|
1638
|
+
};
|
|
1639
|
+
}),
|
|
1640
|
+
getMany: Effect.fn("StateTable.getMany")(function* (collection, keys) {
|
|
1641
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1642
|
+
const offset = yield* appliedOffset(sql, id);
|
|
1643
|
+
const rows = /* @__PURE__ */ new Map();
|
|
1644
|
+
for (const [key, value] of yield* storedValues(sql, id, collection, keys)) rows.set(key, yield* readValue(collection, value));
|
|
1645
|
+
return {
|
|
1646
|
+
offset,
|
|
1647
|
+
rows
|
|
1648
|
+
};
|
|
1649
|
+
}),
|
|
1650
|
+
list: Effect.fn("StateTable.list")(function* (collection, options = {}) {
|
|
1651
|
+
if (options.limit !== void 0 && (!Number.isSafeInteger(options.limit) || options.limit <= 0)) return yield* new ProjectionFault({
|
|
1652
|
+
phase: "load",
|
|
1653
|
+
reason: "invalid-options",
|
|
1654
|
+
message: "StateTable list limit must be a positive safe integer"
|
|
1655
|
+
});
|
|
1656
|
+
const sql = yield* SqlClient.SqlClient;
|
|
1657
|
+
const offset = yield* appliedOffset(sql, id);
|
|
1658
|
+
const found = yield* sql`SELECT row_key, value FROM streamsy_state_rows
|
|
1659
|
+
WHERE stream_id = ${id} AND collection = ${collection}
|
|
1660
|
+
${options.after === void 0 ? sql`` : sql`AND row_key > ${options.after}`}
|
|
1661
|
+
ORDER BY row_key ${options.limit === void 0 ? sql`` : sql`LIMIT ${options.limit}`}`;
|
|
1662
|
+
const rows = yield* Effect.forEach(found, (row) => Effect.map(readValue(collection, row.value), (value) => ({
|
|
1663
|
+
key: row.row_key,
|
|
1664
|
+
value
|
|
1665
|
+
})));
|
|
1666
|
+
return {
|
|
1667
|
+
offset,
|
|
1668
|
+
rows,
|
|
1669
|
+
next: options.limit !== void 0 && rows.length === options.limit ? rows[rows.length - 1]?.key : void 0
|
|
1670
|
+
};
|
|
1671
|
+
})
|
|
1672
|
+
};
|
|
1673
|
+
};
|
|
1674
|
+
/** A State stream's declaration, kept current by the ordinary projection runners. */
|
|
1675
|
+
function define(state) {
|
|
1676
|
+
return {
|
|
1677
|
+
...declare({
|
|
1678
|
+
id: `state-table/${state.key}`,
|
|
1679
|
+
params: state.paramCodecs,
|
|
1680
|
+
inputs: {}
|
|
1681
|
+
}, ({ decoded, ...key }) => {
|
|
1682
|
+
const address = state.at(decoded);
|
|
1683
|
+
const raw = Object.assign(StreamAddress.json(address.id, { schema: Schema.String }), {
|
|
1684
|
+
stream: address.stream,
|
|
1685
|
+
codec: Schema.String
|
|
1686
|
+
});
|
|
1687
|
+
return {
|
|
1688
|
+
...key,
|
|
1689
|
+
inputs: { state: raw },
|
|
1690
|
+
commit: transaction,
|
|
1691
|
+
process: (batch) => applySlice(raw, batch.state),
|
|
1692
|
+
...reads(address.id, state.collections),
|
|
1693
|
+
sync: () => synchronize(raw)
|
|
1694
|
+
};
|
|
1695
|
+
}),
|
|
1696
|
+
inputs: { state },
|
|
1697
|
+
parse: state.parse
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
/** Discard the index and replay the State stream atomically, retaining the binding checkpoint. */
|
|
1701
|
+
const rebuild = Effect.fn("StateTable.rebuild")(function* (table) {
|
|
1702
|
+
const tx = yield* Transaction;
|
|
1703
|
+
const id = table.inputs.state.id;
|
|
1704
|
+
yield* tx.withTransaction(clearRows(tx.sql, id).pipe(Effect.andThen(tx.sql`DELETE FROM streamsy_state_heads WHERE stream_id = ${id}`), Effect.catchTag("SqlError", sqlFault(id)), Effect.andThen(table.sync())));
|
|
1705
|
+
});
|
|
1706
|
+
/** Append a reset to the State stream. The next table run applies it. */
|
|
1707
|
+
const reset = Effect.fn("StateTable.reset")(function* (table) {
|
|
1708
|
+
const address = table.inputs.state;
|
|
1709
|
+
const { wire } = yield* address.stream;
|
|
1710
|
+
const state = StreamAddress.state(address.id, { collections: {} });
|
|
1711
|
+
return yield* Streams.append(state, [StreamAddress.reset()]).pipe(Effect.provideService(StreamsWriter, wire));
|
|
1712
|
+
});
|
|
1713
|
+
// src/fold-by-key-error.ts
|
|
1714
|
+
/** A folded row disagreed with the key that was used to load its previous row. */
|
|
1715
|
+
var FoldByKeyError = class extends Schema.TaggedError()("FoldByKeyError", { message: Schema.String }) {};
|
|
1716
|
+
// src/fold-by-key.ts
|
|
1717
|
+
var fold_by_key_exports = /* @__PURE__ */ __exportAll({
|
|
1718
|
+
process: () => process,
|
|
1719
|
+
remove: () => remove
|
|
1720
|
+
});
|
|
1721
|
+
/** Return this from a fold to delete its row. The next record receives undefined. */
|
|
1722
|
+
const remove = Symbol("@streamsy/projection/FoldByKey.remove");
|
|
1723
|
+
const isEffect = (step) => Effect.isEffect(step);
|
|
1724
|
+
const fault = (reason, message) => (cause) => new ProjectionFault({
|
|
1725
|
+
phase: "process",
|
|
1726
|
+
reason,
|
|
1727
|
+
message,
|
|
1728
|
+
cause
|
|
1729
|
+
});
|
|
1730
|
+
const writeFault = (id) => (cause) => fault(isStreamsFault(cause) ? "storage-failure" : "invalid-output", `Cannot write output ${id}`)(cause);
|
|
1731
|
+
const make = (table, spec) => (batch, unit, { outputs }) => Effect.gen(function* () {
|
|
1732
|
+
const output = outputs[spec.output];
|
|
1733
|
+
const collection = output.collections[spec.collection];
|
|
1734
|
+
const params = table.parse(output.id);
|
|
1735
|
+
if (collection === void 0 || Option.isNone(params)) return yield* Effect.die(/* @__PURE__ */ new RangeError(`${table.id} does not index ${spec.collection} of ${output.id}`));
|
|
1736
|
+
const { wire } = yield* output.stream;
|
|
1737
|
+
yield* wire.create(output.id, { contentType: output.contentType }).pipe(Effect.mapError(writeFault(output.id)));
|
|
1738
|
+
yield* table.at(params.value).sync();
|
|
1739
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1740
|
+
for (const { item } of items(batch)) for (const record of spec.records(item, unit)) {
|
|
1741
|
+
const key = spec.key(record, unit);
|
|
1742
|
+
if (key === void 0) continue;
|
|
1743
|
+
const group = groups.get(key);
|
|
1744
|
+
if (group === void 0) groups.set(key, [record]);
|
|
1745
|
+
else group.push(record);
|
|
1746
|
+
}
|
|
1747
|
+
const stored = yield* storedValues(yield* SqlClient.SqlClient, output.id, spec.collection, [...groups.keys()]).pipe(Effect.mapError(fault("storage-failure", `Cannot read the rows of ${output.id}`)));
|
|
1748
|
+
const schema = collection.schema;
|
|
1749
|
+
const changes = [];
|
|
1750
|
+
for (const [key, records] of groups) {
|
|
1751
|
+
const before = stored.get(key);
|
|
1752
|
+
let value = before === void 0 ? void 0 : yield* decodeRow(schema, before).pipe(Effect.mapError(fault("invalid-record", `Row ${key} of ${output.id} does not decode`)));
|
|
1753
|
+
for (const record of records) {
|
|
1754
|
+
const step = spec.fold(value, record, unit);
|
|
1755
|
+
const next = isEffect(step) ? yield* step : step;
|
|
1756
|
+
value = next === remove ? void 0 : next;
|
|
1757
|
+
}
|
|
1758
|
+
if (value === void 0) {
|
|
1759
|
+
if (before !== void 0) changes.push(deleteJson(spec.collection, key));
|
|
1760
|
+
continue;
|
|
1761
|
+
}
|
|
1762
|
+
const field = collection.key;
|
|
1763
|
+
const actual = Predicate.hasProperty(value, field) ? String(value[field]) : "undefined";
|
|
1764
|
+
if (actual !== key) return yield* new FoldByKeyError({ message: `FoldByKey key "${key}" differs from folded row key "${actual}"` });
|
|
1765
|
+
const after = yield* encodeRow(schema, value).pipe(Effect.mapError(fault("invalid-output", `Cannot encode row ${key} of ${output.id}`)));
|
|
1766
|
+
if (after !== before) changes.push(upsertJson(spec.collection, key, after));
|
|
1767
|
+
}
|
|
1768
|
+
if (Array.isReadonlyArrayNonEmpty(changes)) yield* wire.append(output.id, {
|
|
1769
|
+
contentType: output.contentType,
|
|
1770
|
+
data: new TextEncoder().encode(`[${Array.join(changes, ",")}]`)
|
|
1771
|
+
}).pipe(Effect.mapError(writeFault(output.id)));
|
|
1772
|
+
return yield* Effect.void;
|
|
1773
|
+
}).pipe(Effect.withSpan("FoldByKey.process"));
|
|
1774
|
+
function process(table, spec) {
|
|
1775
|
+
if (spec.records !== void 0) return make(table, spec);
|
|
1776
|
+
return make(table, {
|
|
1777
|
+
...spec,
|
|
1778
|
+
records: (item) => [item]
|
|
1779
|
+
});
|
|
1780
|
+
}
|
|
1409
1781
|
// src/wakeup.ts
|
|
1410
1782
|
/**
|
|
1411
1783
|
* Local commits choose bindings; each alarm drains the same runner used by
|
|
@@ -1435,4 +1807,4 @@ const attach = (projection, options = {}) => {
|
|
|
1435
1807
|
});
|
|
1436
1808
|
};
|
|
1437
1809
|
const ProjectionWakeup = { attach };
|
|
1438
|
-
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, Transaction };
|
|
1810
|
+
export { CheckpointRecord, CheckpointStore, commit_exports as Commit, fold_by_key_exports as FoldByKey, FoldByKeyError, HandlerFailed, projection_exports as Projection, ProjectionFault, ProjectionRetry, ProjectionWakeup, state_table_exports as StateTable, Transaction };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@streamsy/projection",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Checkpointed Effect projections over one or more retained streams.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -37,27 +37,27 @@
|
|
|
37
37
|
"test:dialects": "bun --bun vitest run test/sql-dialects.test.ts"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@streamsy/core": "^0.
|
|
40
|
+
"@streamsy/core": "^0.10.0"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@cloudflare/workers-types": "4.20251228.0",
|
|
44
|
-
"@effect/platform-bun": "4.
|
|
45
|
-
"@effect/sql-mysql2": "4.
|
|
46
|
-
"@effect/sql-pg": "4.
|
|
47
|
-
"@effect/sql-sqlite-bun": "4.
|
|
48
|
-
"@effect/sql-sqlite-do": "4.
|
|
49
|
-
"@effect/vitest": "4.
|
|
50
|
-
"@streamsy/outbox": "0.
|
|
51
|
-
"@streamsy/serve": "0.
|
|
52
|
-
"@streamsy/storage": "0.
|
|
44
|
+
"@effect/platform-bun": "4.1.2",
|
|
45
|
+
"@effect/sql-mysql2": "4.1.2",
|
|
46
|
+
"@effect/sql-pg": "4.1.2",
|
|
47
|
+
"@effect/sql-sqlite-bun": "4.1.2",
|
|
48
|
+
"@effect/sql-sqlite-do": "4.1.2",
|
|
49
|
+
"@effect/vitest": "4.1.2",
|
|
50
|
+
"@streamsy/outbox": "0.10.0",
|
|
51
|
+
"@streamsy/serve": "0.10.0",
|
|
52
|
+
"@streamsy/storage": "0.10.0",
|
|
53
53
|
"@types/bun": "^1.4.3",
|
|
54
|
-
"effect": "4.
|
|
54
|
+
"effect": "4.1.2",
|
|
55
55
|
"miniflare": "4.20260730.0",
|
|
56
56
|
"typescript": "^7.0.2",
|
|
57
57
|
"vitest": "5.0.5"
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
|
-
"effect": "^4.
|
|
60
|
+
"effect": "^4.1.2"
|
|
61
61
|
},
|
|
62
62
|
"tsdown": {
|
|
63
63
|
"fixedExtension": false,
|