@kairos-es/store-postgres 1.0.0-alpha.3 → 1.0.0-alpha.5

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.
Files changed (91) hide show
  1. package/README.md +61 -29
  2. package/dist/cjs/clients.js +34 -24
  3. package/dist/cjs/clients.js.map +1 -1
  4. package/dist/cjs/config.js +9 -15
  5. package/dist/cjs/config.js.map +1 -1
  6. package/dist/cjs/ensureSchema.js +8 -3
  7. package/dist/cjs/ensureSchema.js.map +1 -1
  8. package/dist/cjs/index.js.map +1 -1
  9. package/dist/cjs/internal/ddl.js +29 -12
  10. package/dist/cjs/internal/ddl.js.map +1 -1
  11. package/dist/cjs/internal/matchSql.js +57 -4
  12. package/dist/cjs/internal/matchSql.js.map +1 -1
  13. package/dist/cjs/internal/readPlan.js +33 -5
  14. package/dist/cjs/internal/readPlan.js.map +1 -1
  15. package/dist/cjs/internal/transport.js +42 -15
  16. package/dist/cjs/internal/transport.js.map +1 -1
  17. package/dist/cjs/store.js +30 -25
  18. package/dist/cjs/store.js.map +1 -1
  19. package/dist/dts-cjs/clients.d.ts +66 -0
  20. package/dist/dts-cjs/clients.d.ts.map +1 -0
  21. package/dist/{dts → dts-cjs}/config.d.ts +9 -19
  22. package/dist/{dts → dts-cjs}/config.d.ts.map +1 -1
  23. package/dist/{dts → dts-cjs}/ensureSchema.d.ts +8 -3
  24. package/dist/dts-cjs/ensureSchema.d.ts.map +1 -0
  25. package/dist/{dts → dts-cjs}/index.d.ts +4 -3
  26. package/dist/dts-cjs/index.d.ts.map +1 -0
  27. package/dist/{dts → dts-cjs}/internal/ddl.d.ts +1 -1
  28. package/dist/{dts → dts-cjs}/internal/ddl.d.ts.map +1 -1
  29. package/dist/{dts → dts-cjs}/internal/matchSql.d.ts +26 -2
  30. package/dist/dts-cjs/internal/matchSql.d.ts.map +1 -0
  31. package/dist/{dts → dts-cjs}/internal/readPlan.d.ts +1 -1
  32. package/dist/{dts → dts-cjs}/internal/readPlan.d.ts.map +1 -1
  33. package/dist/{dts → dts-cjs}/internal/transport.d.ts +34 -19
  34. package/dist/dts-cjs/internal/transport.d.ts.map +1 -0
  35. package/dist/dts-cjs/package.json +3 -0
  36. package/dist/dts-cjs/store.d.ts.map +1 -0
  37. package/dist/dts-esm/clients.d.ts +66 -0
  38. package/dist/dts-esm/clients.d.ts.map +1 -0
  39. package/dist/dts-esm/config.d.ts +48 -0
  40. package/dist/dts-esm/config.d.ts.map +1 -0
  41. package/dist/dts-esm/ensureSchema.d.ts +40 -0
  42. package/dist/dts-esm/ensureSchema.d.ts.map +1 -0
  43. package/dist/dts-esm/index.d.ts +42 -0
  44. package/dist/dts-esm/index.d.ts.map +1 -0
  45. package/dist/dts-esm/internal/ddl.d.ts +174 -0
  46. package/dist/dts-esm/internal/ddl.d.ts.map +1 -0
  47. package/dist/dts-esm/internal/matchSql.d.ts +164 -0
  48. package/dist/dts-esm/internal/matchSql.d.ts.map +1 -0
  49. package/dist/dts-esm/internal/readPlan.d.ts +72 -0
  50. package/dist/dts-esm/internal/readPlan.d.ts.map +1 -0
  51. package/dist/dts-esm/internal/transport.d.ts +131 -0
  52. package/dist/dts-esm/internal/transport.d.ts.map +1 -0
  53. package/dist/dts-esm/package.json +3 -0
  54. package/dist/dts-esm/store.d.ts +17 -0
  55. package/dist/dts-esm/store.d.ts.map +1 -0
  56. package/dist/esm/clients.js +34 -24
  57. package/dist/esm/clients.js.map +1 -1
  58. package/dist/esm/config.js +9 -15
  59. package/dist/esm/config.js.map +1 -1
  60. package/dist/esm/ensureSchema.js +8 -3
  61. package/dist/esm/ensureSchema.js.map +1 -1
  62. package/dist/esm/index.js +4 -3
  63. package/dist/esm/index.js.map +1 -1
  64. package/dist/esm/internal/ddl.js +30 -13
  65. package/dist/esm/internal/ddl.js.map +1 -1
  66. package/dist/esm/internal/matchSql.js +55 -2
  67. package/dist/esm/internal/matchSql.js.map +1 -1
  68. package/dist/esm/internal/readPlan.js +32 -5
  69. package/dist/esm/internal/readPlan.js.map +1 -1
  70. package/dist/esm/internal/transport.js +42 -15
  71. package/dist/esm/internal/transport.js.map +1 -1
  72. package/dist/esm/store.js +30 -25
  73. package/dist/esm/store.js.map +1 -1
  74. package/package.json +13 -11
  75. package/src/clients.ts +43 -31
  76. package/src/config.ts +12 -13
  77. package/src/ensureSchema.ts +8 -3
  78. package/src/index.ts +4 -3
  79. package/src/internal/ddl.ts +33 -13
  80. package/src/internal/matchSql.ts +63 -1
  81. package/src/internal/readPlan.ts +11 -6
  82. package/src/internal/transport.ts +71 -24
  83. package/src/store.ts +35 -28
  84. package/dist/dts/clients.d.ts +0 -34
  85. package/dist/dts/clients.d.ts.map +0 -1
  86. package/dist/dts/ensureSchema.d.ts.map +0 -1
  87. package/dist/dts/index.d.ts.map +0 -1
  88. package/dist/dts/internal/matchSql.d.ts.map +0 -1
  89. package/dist/dts/internal/transport.d.ts.map +0 -1
  90. package/dist/dts/store.d.ts.map +0 -1
  91. /package/dist/{dts → dts-cjs}/store.d.ts +0 -0
@@ -8,7 +8,7 @@
8
8
  * where transport code lives, and the two per-column type maps (`EventJson`,
9
9
  * `EventRow`) sit next to each other rather than in two files.
10
10
  *
11
- * The 5-column event contract stays single-sourced on `EventColumnName`
11
+ * The event column contract stays single-sourced on `EventColumnName`
12
12
  * (`internal/matchSql.ts`), the one column-NAME descriptor: both type maps here
13
13
  * are mapped types over it, so a column rename in `EVENT_COLUMNS` is a COMPILE
14
14
  * error in this module, never a silent transport drift the lax read boundary
@@ -19,20 +19,21 @@
19
19
  * (`toEventJson`) serialises `data` as base64 text and domain time as an ISO
20
20
  * string, both restored in SQL.
21
21
  */
22
- import type { DcbEvent, Query, SequencedEvent } from '@kairos-es/core';
22
+ import type { DcbEvent, Metadata, Query, SequencedEvent } from '@kairos-es/core';
23
23
  import type { EventColumnName } from './matchSql.js';
24
24
  /**
25
25
  * Serialise a value to a JSON STRING for transport as a `::jsonb`-cast bound
26
26
  * parameter.
27
27
  *
28
- * WHY not `sql.json(value)`: `@effect/sql-pg`'s `json` helper binds the RAW
29
- * value, and node-postgres serialises a JS *array* bound param as a Postgres
30
- * ARRAY literal (`{…}`), not JSON — so `sql.json([...])::jsonb` fails with a
31
- * `22P02` invalid-JSON error (an array literal is not valid JSON). Passing a
32
- * pre-stringified JSON string and casting `::jsonb` sends plain text that
33
- * Postgres parses as JSON, which round-trips reliably for both objects and
34
- * arrays. Kept as a named helper so every JSON-transport call site is consistent
35
- * and the reasoning lives in one place.
28
+ * WHY a string and not `sql.json(value)`: the read plan runs through
29
+ * `sql.unsafe(text, params)` with POSITIONAL parameters, and a positional
30
+ * parameter must be a plain scalar or a flat array of scalars — `@effect/sql-pg`
31
+ * cannot infer a Postgres type for an object or an array of objects, and a
32
+ * `sql.json` fragment is not a value that list can carry. A pre-stringified
33
+ * JSON string binds untyped and the `::jsonb` cast has Postgres parse it, which
34
+ * round-trips reliably for both objects and arrays on the positional path and
35
+ * the tagged-template path alike. Kept as a named helper so every
36
+ * JSON-transport call site is consistent and the reasoning lives in one place.
36
37
  */
37
38
  export declare const jsonbText: (value: unknown) => string;
38
39
  /** The JSON shape of one query item: types OR-filter, tags AND-superset. */
@@ -45,9 +46,11 @@ export declare const toQueryItemsJson: (query: Query) => ReadonlyArray<QueryItem
45
46
  /**
46
47
  * The per-column TS types of the transport JSON shape — one entry per
47
48
  * `EVENT_COLUMNS` name. `data` is base64 TEXT and `occurred_at` an ISO string
48
- * (both restored in SQL: `decode(…, 'base64')` / `timestamptz`); the rest map
49
- * straight across. Kept as a plain map so `EventJson` below is a mapped type over
50
- * the ONE column descriptor rather than a hand-restated column list.
49
+ * (both restored in SQL: `decode(…, 'base64')` / `timestamptz`); `metadata`
50
+ * travels as a nested JSON object, which `jsonb_to_recordset` hands to the
51
+ * insert as `jsonb` untouched; the rest map straight across. Kept as a plain
52
+ * map so `EventJson` below is a mapped type over the ONE column descriptor
53
+ * rather than a hand-restated column list.
51
54
  */
52
55
  interface EventJsonColumns {
53
56
  readonly type: string;
@@ -55,6 +58,7 @@ interface EventJsonColumns {
55
58
  readonly tags: ReadonlyArray<string>;
56
59
  readonly uuid: string;
57
60
  readonly occurred_at: string;
61
+ readonly metadata: Metadata;
58
62
  }
59
63
  /**
60
64
  * The JSON shape of one event as sent to the append functions, as a mapped type
@@ -72,8 +76,12 @@ export type EventJson = {
72
76
  export declare const toEventJson: (event: DcbEvent) => EventJson;
73
77
  /**
74
78
  * The per-column TS types of a raw driver row — one entry per `EVENT_COLUMNS`
75
- * name. These are node-postgres's decoded JS types: `data` a `Buffer` (or null
76
- * for a payload-less event), `occurred_at` a JS `Date`, `tags` a `string[]`. `id`
79
+ * name. These are the JS types `@effect/sql-pg`'s default binary codecs decode
80
+ * to: `data` a `Uint8Array` (or null for a payload-less event), `occurred_at` a
81
+ * JS `Date`, `tags` a `string[]`, `metadata` whatever the driver parses a
82
+ * `jsonb` value into — declared
83
+ * `unknown`, because `jsonb` is the one column here whose SQL type does not
84
+ * fix its JS shape, and `metadataFrom` below is where it is checked. `id`
77
85
  * (the `bigserial` position) is NOT here — it is prepended by the read projection
78
86
  * and absent from the events recordset, so it sits outside the shared descriptor.
79
87
  */
@@ -83,23 +91,30 @@ interface EventRowColumns {
83
91
  readonly tags: ReadonlyArray<string>;
84
92
  readonly uuid: string;
85
93
  readonly occurred_at: Date;
94
+ readonly metadata: unknown;
86
95
  }
87
96
  /**
88
- * A raw row from the main table as node-postgres returns it, as `id` plus a
97
+ * A raw row from the main table as the driver returns it, as `id` plus a
89
98
  * mapped type over the shared `EventColumnName` descriptor. `id` is `int8`, which
90
- * the driver hands back as a decimal STRING (JS `number` is unsafe past 2^53).
99
+ * the driver's default codec hands back as a `bigint` (JS `number` is unsafe past
100
+ * 2^53). `rowToSequenced` still passes it through `BigInt(…)`, so a client
101
+ * configured with its own `int8` codec that yields the decimal string instead
102
+ * still mints a real `bigint` position.
91
103
  * The payload columns cannot drift from the read projection: a rename in
92
104
  * `EVENT_COLUMNS` breaks this mapped type.
93
105
  */
94
106
  export type EventRow = {
95
- readonly id: string;
107
+ readonly id: bigint | string;
96
108
  } & {
97
109
  readonly [K in EventColumnName]: EventRowColumns[K];
98
110
  };
99
111
  /**
100
112
  * Map a raw main-table row to a core `SequencedEvent`. `data` NULL → empty bytes
101
113
  * (a payload-less event round-trips to a zero-length `Uint8Array`); `occurred_at`
102
- * Date → `DateTime.Utc`; `id` string → branded `Position`.
114
+ * Date → `DateTime.Utc`; `id` → branded `Position`; `metadata` through
115
+ * `metadataFrom`. The column is `NOT NULL DEFAULT '{}'`, so there is no absent
116
+ * case to reconcile: an event appended with an empty bag reads back as `{}` on
117
+ * this engine exactly as on the in-memory oracle.
103
118
  *
104
119
  * The branded scalars (`type`, `tags`, `uuid`, `position`) are minted by trusted
105
120
  * `as`-cast, NOT by re-running `EventType.make` / `Tag.make` etc. This is
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/internal/transport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EACV,QAAQ,EACR,QAAQ,EAER,KAAK,EACL,cAAc,EACf,MAAM,iBAAiB,CAAA;AAGxB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,SAAS,GAAI,OAAO,OAAO,KAAG,MAA+B,CAAA;AAE1E,4EAA4E;AAC5E,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC,CAAA;IACrC,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC,MAAM,CAAC,CAAA;CACrC;AAED,mEAAmE;AACnE,eAAO,MAAM,gBAAgB,GAAI,OAAO,KAAK,KAAG,aAAa,CAAC,aAAa,CAItE,CAAA;AAEL;;;;;;;;GAQG;AACH,UAAU,gBAAgB;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IAC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AGL,aAAa,EAQd,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAA6B,KAAK,EAAsB,MAAM,QAAQ,CAAA;AAE7E,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,WAAW,CAAA;AAC1D,OAAO,EAA6B,KAAK,mBAAmB,EAAE,MAAM,UAAU,CAAA;AA2U9E;;;;;;;;;;GAUG;AACH,eAAO,MAAM,KAAK,GAChB,SAAQ,mBAAwB,KAC/B,KAAK,CAAC,KAAK,CAAC,aAAa,EAAE,KAAK,EAAE,cAAc,GAAG,cAAc,CASnE,CAAA"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The TWO store-owned Postgres clients — the "Neon trap" mitigation (ADR-0002).
3
+ *
4
+ * `@effect/sql-pg` exposes a single `PgClient` (and `SqlClient`) service; a
5
+ * `PgClient.layer` claims BOTH. If we built two `PgClient.layer`s they would
6
+ * collide on that one key — the second would shadow the first. So instead we
7
+ * define two DISTINCT `Context.Service`s, each HOLDING a `PgClient` value:
8
+ *
9
+ * - `PgClientPooled` — the pooled client used for reads, the append function,
10
+ * and `notify`. Its statements borrow a connection from the client's pool per
11
+ * query.
12
+ * - `PgClientDirect` — a client used ONLY by `subscribe`'s `listen`. Its
13
+ * built-in `listen` RESERVES a connection from that client's own pool and
14
+ * holds it for the life of the subscription, so the listening session lives
15
+ * on whatever host the client was configured with. On a Neon POOLED endpoint
16
+ * (`…-pooler…`) that session is a PgBouncer front-door connection, which
17
+ * SILENTLY DROPS `LISTEN`/`NOTIFY` — the subscription would simply never
18
+ * wake. Pointing `PgClientDirect` at Neon's DIRECT (non-pooler) endpoint fixes
19
+ * it. `subscribe` is the ONLY method that touches `PgClientDirect`.
20
+ *
21
+ * Because each live subscription holds one of `PgClientDirect`'s pooled
22
+ * connections until it closes, that client's `maxConnections` is also the number
23
+ * of subscriptions that can be listening at once. A subscription past it waits
24
+ * for a connection on its wake fibre only — delivery still proceeds at the poll
25
+ * rate meanwhile (see `store.ts`) — so size the direct client for the expected
26
+ * subscriber count rather than for query throughput.
27
+ *
28
+ * For a plain (non-Neon) Postgres both services point at the same URL; the split
29
+ * costs nothing there. The two-service design is what makes the Neon fix a
30
+ * deployment-time wiring choice rather than a code change.
31
+ */
32
+ import { PgClient } from '@effect/sql-pg';
33
+ import { Context, Layer } from 'effect';
34
+ import type { SqlError } from 'effect/sql';
35
+ declare const PgClientPooled_base: Context.ServiceClass<PgClientPooled, "@kairos-es/store-postgres/PgClientPooled", PgClient.PgClient>;
36
+ /**
37
+ * The pooled client service: reads, the append function, and `notify`. Holds a
38
+ * `PgClient` value rather than being a `PgClient.layer`, so it never collides
39
+ * with the direct client on the shared `PgClient`/`SqlClient` key.
40
+ */
41
+ export declare class PgClientPooled extends PgClientPooled_base {
42
+ }
43
+ declare const PgClientDirect_base: Context.ServiceClass<PgClientDirect, "@kairos-es/store-postgres/PgClientDirect", PgClient.PgClient>;
44
+ /**
45
+ * The direct (non-pooler) client service: the `subscribe` listener ONLY. Point
46
+ * this at a direct endpoint on Neon so `LISTEN`/`NOTIFY` is not dropped by the
47
+ * pooler.
48
+ */
49
+ export declare class PgClientDirect extends PgClientDirect_base {
50
+ }
51
+ /**
52
+ * Build a `PgClientPooled` layer from a `PgClient` pool config. We construct the
53
+ * client via `PgClient.make` (scoped) and place it in our OWN service, then
54
+ * provide `Reactivity.layer` (which `PgClient.make` requires) — exactly what the
55
+ * built-in `PgClient.layer` does internally, minus the collision-prone claim on
56
+ * the shared `PgClient` key.
57
+ */
58
+ export declare const pooledLayer: (config: PgClient.PgPoolConfig) => Layer.Layer<PgClientPooled, SqlError.SqlError>;
59
+ /**
60
+ * Build a `PgClientDirect` layer from a `PgClient` pool config. Same construction as
61
+ * `pooledLayer`; the two differ only in which endpoint the caller points them
62
+ * at (and that only matters on Neon).
63
+ */
64
+ export declare const directLayer: (config: PgClient.PgPoolConfig) => Layer.Layer<PgClientDirect, SqlError.SqlError>;
65
+ export {};
66
+ //# sourceMappingURL=clients.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../src/clients.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAA;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;;AAE1C;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,mBAGW;CAAG;;AAElD;;;;GAIG;AACH,qBAAa,cAAe,SAAQ,mBAGW;CAAG;AAElD;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,QAAQ,CAAC,YAAY,KAC5B,KAAK,CAAC,KAAK,CAAC,cAAc,EAAE,QAAQ,CAAC,QAAQ,CAG7C,CAAA;AAEH;;;;GAIG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,QAAQ,CAAC,YAAY,KAC5B,KAAK,CAAC,KAAK,CAAC,cAAc,EAAE,QAAQ,CAAC,QAAQ,CAG7C,CAAA"}
@@ -0,0 +1,48 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * Configuration for a Postgres store instance.
4
+ *
5
+ * - `schema` — the Postgres schema that owns the store's objects (default
6
+ * `public`). `ensureSchema` creates it defensively.
7
+ * - `tablePrefix` — the base name for the store's tables/indexes/functions
8
+ * (default `dcb_events`). Two stores with different prefixes (or schemas)
9
+ * cohabit one database without interference.
10
+ * - `lockTimeout` — seconds passed to `set_config('lock_timeout', …, true)`
11
+ * inside every append, bounding how long a blocked writer waits on the
12
+ * exclusive lock. `0` (the default) means wait indefinitely — parity with the
13
+ * in-memory semaphore's unbounded wait, so the shared contract suite behaves
14
+ * identically across engines. A non-zero timeout that fires (`55P03`) is a
15
+ * Postgres-only outcome surfaced OFF the shared `append` contract (a defect),
16
+ * never as `AppendConditionFailed` — the in-memory oracle cannot produce it.
17
+ * - `pollInterval` — MILLISECONDS a live `subscribe` waits for a NOTIFY wake
18
+ * before re-reading from its cursor anyway, defaulting to core's
19
+ * `DEFAULT_POLL_INTERVAL_MILLIS`. Because this engine HAS a wake source, the
20
+ * value bounds worst-case live-tail latency rather than being it — only a
21
+ * subscriber no NOTIFY reaches waits the whole interval; lower it (e.g. in tests)
22
+ * to poll faster. See `packages/core/src/SubscribeMachine.ts` for what the poll
23
+ * guarantees and what a wake source is for.
24
+ * - `catchUpPageSize` — the `subscribe` reconcile page size, defaulting to core's
25
+ * `DEFAULT_CATCH_UP_PAGE_SIZE`: how many events a single catch-up/live read
26
+ * fetches before looping.
27
+ */
28
+ export declare const PostgresStoreConfig: Schema.Struct<{
29
+ readonly pollInterval: Schema.optionalKey<Schema.Number>;
30
+ readonly catchUpPageSize: Schema.optionalKey<Schema.Int>;
31
+ readonly schema: Schema.optionalKey<Schema.String>;
32
+ readonly tablePrefix: Schema.optionalKey<Schema.String>;
33
+ readonly lockTimeout: Schema.optionalKey<Schema.Number>;
34
+ }>;
35
+ export type PostgresStoreConfig = typeof PostgresStoreConfig.Type;
36
+ /**
37
+ * Decode an unknown value into a validated `PostgresStoreConfig`, throwing a
38
+ * `SchemaError` on any violation. Used by `layer`/`ensureSchema` so a bad config
39
+ * fails at construction time.
40
+ */
41
+ export declare const decodePostgresStoreConfig: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => {
42
+ readonly schema?: string;
43
+ readonly tablePrefix?: string;
44
+ readonly lockTimeout?: number;
45
+ readonly pollInterval?: number;
46
+ readonly catchUpPageSize?: number;
47
+ };
48
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAiB/B;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,mBAAmB;;;;;;EAiB/B,CAAA;AACD,MAAM,MAAM,mBAAmB,GAAG,OAAO,mBAAmB,CAAC,IAAI,CAAA;AAEjE;;;;GAIG;AACH,eAAO,MAAM,yBAAyB;;;;;;CACS,CAAA"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `ensureSchema` — the idempotent DDL migration building block (ADR-0002).
3
+ *
4
+ * This is deliberately NOT a migrator. It is a single `Effect<void, SqlError,
5
+ * SqlClient>` that creates (or refreshes) every object a store owns: both
6
+ * tables, both indexes, and both plpgsql functions. It requires the GENERIC
7
+ * `SqlClient` service — NOT `PgClientPooled` — precisely so a consumer can drop it
8
+ * straight into THEIR OWN migrator, e.g.:
9
+ *
10
+ * ```ts
11
+ * Migrator.fromRecord({
12
+ * '0001_kairos_store_dcb_events': ensureSchema(config),
13
+ * })
14
+ * ```
15
+ *
16
+ * or simply run it once at boot. We ship no `FileSystem`/`Path`/`ChildProcess`
17
+ * dependency and no `PgMigrator`; migration ORCHESTRATION belongs to the
18
+ * consumer, this package only provides the idempotent PAYLOAD.
19
+ *
20
+ * Idempotence: every statement is `CREATE … IF NOT EXISTS` or `CREATE OR REPLACE
21
+ * FUNCTION`, so re-running it is safe. It is NOT a no-op across versions: a
22
+ * re-run replaces the append functions with this version's, and does NOT alter
23
+ * an existing table, so a column a newer version adds must be added by hand
24
+ * before the re-run (the release notes give the statement). A store whose
25
+ * table gained a column but whose functions were never replaced keeps writing
26
+ * through the old ones, which do not know the column. Names come from
27
+ * `sql(identifier)` (via the pre-quoted builder in `internal/ddl.ts`); the DDL
28
+ * bodies carry no bound values (pure schema), and the append functions keep
29
+ * their runtime VALUES as bound parameters, never interpolated.
30
+ */
31
+ import { Effect } from 'effect';
32
+ import { SqlClient, type SqlError } from 'effect/sql';
33
+ import { type PostgresStoreConfig } from './config.js';
34
+ /**
35
+ * Produce the migration payload for `config`. Resolves the object names once and
36
+ * runs the ordered idempotent DDL against whatever `SqlClient` the caller's
37
+ * migrator (or boot code) provides.
38
+ */
39
+ export declare const ensureSchema: (config: PostgresStoreConfig) => Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient>;
40
+ //# sourceMappingURL=ensureSchema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ensureSchema.d.ts","sourceRoot":"","sources":["../../src/ensureSchema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,EAAE,SAAS,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAA;AACrD,OAAO,EAA6B,KAAK,mBAAmB,EAAE,MAAM,UAAU,CAAA;AAG9E;;;;GAIG;AACH,eAAO,MAAM,YAAY,GACvB,QAAQ,mBAAmB,KAC1B,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC,SAAS,CAQzD,CAAA"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @kairos-es/store-postgres — the Postgres `DcbEventStore` backend.
3
+ *
4
+ * A single store is one `{ schema, tablePrefix }` naming pair (`PostgresStoreConfig`);
5
+ * every object it owns is derived from that pair, so multiple isolated stores
6
+ * cohabit one database. The engine is the two-table B-tree + exclusive-lock
7
+ * conditional append of ADR-0002, with JSON transport and a two-client Layer to
8
+ * survive Neon's pooled LISTEN/NOTIFY drop.
9
+ *
10
+ * Wiring, end to end:
11
+ *
12
+ * ```ts
13
+ * import { PgClient } from '@effect/sql-pg'
14
+ * import {
15
+ * ensureSchema,
16
+ * layer,
17
+ * pooledLayer,
18
+ * directLayer,
19
+ * } from '@kairos-es/store-postgres'
20
+ *
21
+ * const config = { schema: 'public', tablePrefix: 'dcb_events' }
22
+ *
23
+ * // 1. Register `ensureSchema(config)` in YOUR migrator (or run it at boot).
24
+ * // 2. Provide the two clients (same URL off Neon; a direct endpoint for
25
+ * // `directLayer` on Neon), then the store layer over them.
26
+ * const clients = Layer.merge(
27
+ * pooledLayer({ url: Redacted.make(poolUrl) }),
28
+ * directLayer({ url: Redacted.make(directUrl) }),
29
+ * )
30
+ * const store = layer(config).pipe(Layer.provide(clients))
31
+ * ```
32
+ *
33
+ * The store `layer` performs NO DDL: it depends only on the two client services
34
+ * and assumes `ensureSchema` has run. `ensureSchema` requires the generic
35
+ * `SqlClient` service so it slots into any migrator; the runtime uses the
36
+ * store-owned services.
37
+ */
38
+ export { directLayer, PgClientDirect, PgClientPooled, pooledLayer, } from './clients.js';
39
+ export type { PostgresStoreConfig } from './config.js';
40
+ export { ensureSchema } from './ensureSchema.js';
41
+ export { layer } from './store.js';
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,OAAO,EACL,WAAW,EACX,cAAc,EACd,cAAc,EACd,WAAW,GACZ,MAAM,WAAW,CAAA;AAClB,YAAY,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAA;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA"}
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Internal DDL and object-naming for the Postgres `DcbEventStore` backend.
3
+ *
4
+ * This module is the single source of truth for every object name a store owns
5
+ * and for the plpgsql function bodies. It is deliberately factored apart from
6
+ * the public engine so that:
7
+ *
8
+ * 1. names are derived ONCE, from `{ schema, tablePrefix }`, and reused by both
9
+ * `ensureSchema` (DDL) and the runtime (`append`/`read`/`subscribe`), so the
10
+ * migration and the queries can never disagree about what a table is called;
11
+ * 2. the append-function body is assembled from COMPOSABLE parts — in
12
+ * particular the `LOCK TABLE … IN EXCLUSIVE MODE` clause is an omittable
13
+ * fragment — so a test can `CREATE OR REPLACE` a deliberately-LOCKLESS twin of
14
+ * the append function to prove the shared contract suite actually detects a
15
+ * non-serialising store. The production Layer never exposes a lockless option;
16
+ * the seam lives here, in an internal module, reachable only from the test
17
+ * graph.
18
+ *
19
+ * WHY names are never string-concatenated: every identifier flows through
20
+ * `sql(identifier)`, which quotes and dot-splits safely, so a hostile or merely
21
+ * awkward `schema`/`tablePrefix` cannot inject SQL or collide with a reserved
22
+ * word. The plpgsql *bodies*, which must embed the resolved names as literal
23
+ * text inside a `CREATE FUNCTION … $$ … $$` string, use the SAME quoting via a
24
+ * small `quoteQualified` helper so the body text matches what `sql(identifier)`
25
+ * would emit; VALUES stay bound parameters (`sql.unsafe` with `params`) and are
26
+ * never interpolated.
27
+ */
28
+ import type { SqlClient, Statement } from 'effect/sql';
29
+ /**
30
+ * A store is one physical `{ schema, tablePrefix }` pair. Every object it owns
31
+ * (both tables, both indexes, both functions, and the NOTIFY channel) is derived
32
+ * from this pair, so one prefix is one completely isolated store: its own
33
+ * bigserial sequence, its own exclusive-lock scope, its own wake channel.
34
+ */
35
+ export interface ResolvedNames {
36
+ readonly schema: string;
37
+ readonly tablePrefix: string;
38
+ /** `<schema>.<prefix>` — the main event table. */
39
+ readonly mainTable: string;
40
+ /** `<schema>.<prefix>_tags` — the junction tag table. */
41
+ readonly tagTable: string;
42
+ /** `<prefix>_idx_id_type` — the covering unique index on the main table. */
43
+ readonly mainIndex: string;
44
+ /** `<prefix>_idx_tag_main_id` — the composite B-tree on the tag table. */
45
+ readonly tagIndex: string;
46
+ /** `<schema>.<prefix>_append` — the conditional (lock → check → insert → notify) function. */
47
+ readonly appendFn: string;
48
+ /**
49
+ * `<schema>.<prefix>_append_unconditional` — the check-free insert twin. It takes
50
+ * the SAME exclusive lock as the conditional one, which is what discharges the
51
+ * subscribe machine's ascending-commit-order precondition on this engine;
52
+ * `unconditionalAppendBody` owns why a lock-free twin would not.
53
+ */
54
+ readonly appendUnconditionalFn: string;
55
+ /**
56
+ * The `LISTEN`/`NOTIFY` channel: the fully-qualified events-table name with
57
+ * dots replaced by `_`. A channel is a single unqualified identifier, so the
58
+ * schema is folded into the name to keep two stores in different schemas but
59
+ * with the same prefix from sharing a channel.
60
+ */
61
+ readonly channel: string;
62
+ }
63
+ /** Default schema when the config omits one. */
64
+ export declare const DEFAULT_SCHEMA = "public";
65
+ /** Default table prefix when the config omits one. */
66
+ export declare const DEFAULT_TABLE_PREFIX = "dcb_events";
67
+ /**
68
+ * The first derived identifier that exceeds 63 bytes, as a human-readable
69
+ * message, or `undefined` when every name fits. Shared by `resolveNames` (which
70
+ * throws) and the `PostgresStoreConfig` schema filter (which fails validation),
71
+ * so the byte bound is enforced identically at both the name-derivation and the
72
+ * config-decode boundary.
73
+ */
74
+ export declare const oversizedIdentifier: (config: {
75
+ readonly schema?: string;
76
+ readonly tablePrefix?: string;
77
+ }) => string | undefined;
78
+ /**
79
+ * Derive every owned object name from `{ schema, tablePrefix }`. The index and
80
+ * function *base* names are unqualified prefixes (`<prefix>_…`) because an index
81
+ * name is scoped to its table's schema and a function is created in `<schema>`;
82
+ * the tables and functions carry the schema explicitly so `sql(identifier)`
83
+ * dot-splits them.
84
+ *
85
+ * Throws at construction if any derived identifier would be silently truncated
86
+ * (see `oversizedIdentifier` / `MAX_IDENTIFIER_BYTES`) — a loud failure at the
87
+ * single choke point beats an invisible index-skip or channel collision later.
88
+ */
89
+ export declare const resolveNames: (config: {
90
+ readonly schema?: string;
91
+ readonly tablePrefix?: string;
92
+ }) => ResolvedNames;
93
+ /**
94
+ * Quote a possibly-qualified identifier for embedding inside a plpgsql body as
95
+ * literal text. Splits on `.` and double-quotes each atom, mirroring what
96
+ * `sql(identifier)` emits, so the body's table references and the runtime's
97
+ * `sql(identifier)` references resolve to exactly the same object. Any embedded
98
+ * `"` is doubled per SQL identifier-quoting rules.
99
+ */
100
+ export declare const quoteQualified: (name: string) => string;
101
+ /**
102
+ * The named body-fragment seams, replacing positional boolean flags — the old
103
+ * `unconditionalAppendBody(names, true, false)` was boolean-blind. Both knobs
104
+ * default to the production configuration (locked + notifying); a test twin
105
+ * overrides one field BY NAME. This is the union of both knobs; each body `Pick`s
106
+ * only the ones it actually varies — the conditional body always notifies, so it
107
+ * never took `notify`.
108
+ *
109
+ * - `lock` — include the `LOCK TABLE … IN EXCLUSIVE MODE` clause (default true).
110
+ * BOTH twins vary it: the test-only lockless twins pass `false` to prove the
111
+ * lock is load-bearing (the conditional path's lockless meta-test and the
112
+ * unconditional commit-order repro).
113
+ * - `notify` — include the `pg_notify` wake (default true). ONLY the unconditional
114
+ * twin varies it: the poll-only delivery test passes `false` to prove the
115
+ * periodic poll, not NOTIFY, is the delivery guarantee.
116
+ */
117
+ export interface AppendBodyOptions {
118
+ readonly lock?: boolean;
119
+ readonly notify?: boolean;
120
+ }
121
+ /**
122
+ * Which append function to (re)create, plus the body-fragment seams. `kind`
123
+ * selects the conditional (guarded) or unconditional (check-free) twin — fixing
124
+ * the function NAME and SIGNATURE — and the seams default to the production
125
+ * configuration.
126
+ *
127
+ * A DISCRIMINATED union, not `extends AppendBodyOptions`, so the seams a `kind`
128
+ * cannot vary are un-expressible: the conditional twin exposes only `lock` (it
129
+ * always notifies), so `{ kind: 'conditional', notify: false }` is a compile error
130
+ * rather than a silently-ignored dead option.
131
+ */
132
+ export type AppendFunctionOptions = ({
133
+ readonly kind: 'conditional';
134
+ } & Pick<AppendBodyOptions, 'lock'>) | ({
135
+ readonly kind: 'unconditional';
136
+ } & AppendBodyOptions);
137
+ /**
138
+ * Build ONE complete `CREATE OR REPLACE FUNCTION … RETURNS SETOF bigint LANGUAGE
139
+ * plpgsql AS $kairos$…$kairos$` statement for an append function. This is the
140
+ * single source of the wrapper — its qualified name, argument SIGNATURE, and
141
+ * `$kairos$`-delimited body — consumed by `ddlStatements` (production, both twins)
142
+ * AND by the test installers that `CREATE OR REPLACE` a lockless / notify-
143
+ * suppressed twin over their own prefix.
144
+ *
145
+ * WHY one builder: `ddlStatements` plus three test twins previously hand-restated
146
+ * this wrapper, several with string-INTERPOLATED identifiers this module's own
147
+ * doctrine forbids (`"${schema}"."${prefix}_append"` rather than
148
+ * `quoteQualified(names.appendFn)`). A drift in the SIGNATURE across those copies
149
+ * is a silent footgun: `CREATE OR REPLACE` with a changed argument list creates a
150
+ * new OVERLOAD instead of replacing, leaving the original production function live
151
+ * under test. Single-sourcing name + signature makes a twin unable to diverge —
152
+ * a twin `CREATE OR REPLACE`s exactly the function `ddlStatements` created.
153
+ */
154
+ export declare const appendFunctionStatement: (names: ResolvedNames, options: AppendFunctionOptions) => string;
155
+ /**
156
+ * The full ordered list of idempotent DDL statements that create/refresh a
157
+ * store's objects. Each entry is a `sql.unsafe` statement string; VALUES are not
158
+ * involved (pure DDL), and every identifier is pre-quoted via `quoteQualified`
159
+ * to match the runtime's `sql(identifier)` resolution.
160
+ *
161
+ * Ordering matters: tables before their indexes and before the tag table's FK,
162
+ * functions last (they reference the tables). Everything is `IF NOT EXISTS` /
163
+ * `CREATE OR REPLACE`, so re-running is a no-op — the migration payload is safe
164
+ * to register in any migrator or to run directly.
165
+ */
166
+ export declare const ddlStatements: (names: ResolvedNames) => ReadonlyArray<string>;
167
+ /**
168
+ * Run the ordered DDL against the generic `SqlClient`. Kept here (not in the
169
+ * public `ensureSchema`) so the same builder feeds both the public migration
170
+ * payload and any internal test setup. Each statement is a separate `sql.unsafe`
171
+ * call so a driver that rejects multi-statement strings still works.
172
+ */
173
+ export declare const runDdl: (sql: SqlClient.SqlClient, names: ResolvedNames) => ReadonlyArray<Statement.Statement<unknown>>;
174
+ //# sourceMappingURL=ddl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ddl.d.ts","sourceRoot":"","sources":["../../../src/internal/ddl.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAWtD;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB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