@photon-grove/evt 0.1.1 → 0.1.2
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 +39 -4
- package/dist/aggregate.d.ts +26 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js.map +1 -1
- package/dist/dynamodb/index.d.ts +1 -0
- package/dist/dynamodb/index.d.ts.map +1 -1
- package/dist/dynamodb/index.js +1 -0
- package/dist/dynamodb/index.js.map +1 -1
- package/dist/dynamodb/repository.d.ts.map +1 -1
- package/dist/dynamodb/repository.js +24 -7
- package/dist/dynamodb/repository.js.map +1 -1
- package/dist/dynamodb/requests.d.ts +5 -2
- package/dist/dynamodb/requests.d.ts.map +1 -1
- package/dist/dynamodb/requests.js +19 -4
- package/dist/dynamodb/requests.js.map +1 -1
- package/dist/dynamodb/views.d.ts +18 -0
- package/dist/dynamodb/views.d.ts.map +1 -0
- package/dist/dynamodb/views.js +56 -0
- package/dist/dynamodb/views.js.map +1 -0
- package/dist/errors.d.ts +14 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/postgres/client.d.ts +32 -0
- package/dist/postgres/client.d.ts.map +1 -0
- package/dist/postgres/client.js +4 -0
- package/dist/postgres/client.js.map +1 -0
- package/dist/postgres/index.d.ts +4 -0
- package/dist/postgres/index.d.ts.map +1 -0
- package/dist/postgres/index.js +6 -0
- package/dist/postgres/index.js.map +1 -0
- package/dist/postgres/repository.d.ts +55 -0
- package/dist/postgres/repository.d.ts.map +1 -0
- package/dist/postgres/repository.js +527 -0
- package/dist/postgres/repository.js.map +1 -0
- package/dist/postgres/schema.d.ts +81 -0
- package/dist/postgres/schema.d.ts.map +1 -0
- package/dist/postgres/schema.js +233 -0
- package/dist/postgres/schema.js.map +1 -0
- package/dist/repository.d.ts +26 -6
- package/dist/repository.d.ts.map +1 -1
- package/dist/repository.js +21 -5
- package/dist/repository.js.map +1 -1
- package/dist/store.d.ts +4 -2
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +31 -6
- package/dist/store.js.map +1 -1
- package/package.json +5 -1
- package/src/aggregate.ts +28 -0
- package/src/dynamodb/index.ts +1 -0
- package/src/dynamodb/repository.ts +29 -6
- package/src/dynamodb/requests.ts +24 -4
- package/src/dynamodb/views.ts +67 -0
- package/src/errors.ts +23 -0
- package/src/index.ts +4 -0
- package/src/postgres/client.ts +37 -0
- package/src/postgres/index.ts +23 -0
- package/src/postgres/repository.ts +773 -0
- package/src/postgres/schema.ts +286 -0
- package/src/repository.ts +52 -7
- package/src/store.ts +58 -8
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
// The PostgreSQL layout of an event log, independent of any driver (storage format, "PostgreSQL"):
|
|
2
|
+
// the table names a store is configured with, the engine relations derived from them, and the
|
|
3
|
+
// idempotent DDL that Go's EnsureSchema and Rust's ensure_schema run.
|
|
4
|
+
|
|
5
|
+
import {EvtError} from '../errors.js'
|
|
6
|
+
|
|
7
|
+
/** The default events table. */
|
|
8
|
+
export const DEFAULT_EVENTS_TABLE = 'evt_events'
|
|
9
|
+
|
|
10
|
+
/** The default snapshots table. */
|
|
11
|
+
export const DEFAULT_SNAPSHOTS_TABLE = 'evt_snapshots'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The infix the engine relations derive from the events table name with, such as
|
|
15
|
+
* `evt_events__evt_features`. A configured table name may not contain it, in any case, so one
|
|
16
|
+
* log's tables can never equal another log's derived relation.
|
|
17
|
+
*/
|
|
18
|
+
export const RESERVED_INFIX = '__evt_'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The longest events table name, in bytes. Its longest derived relation,
|
|
22
|
+
* `{events}__evt_rebuild_generation_pkey`, then fills PostgreSQL's 63-byte identifier limit.
|
|
23
|
+
*/
|
|
24
|
+
export const MAX_EVENTS_TABLE_NAME_BYTES = 63 - '__evt_rebuild_generation_pkey'.length
|
|
25
|
+
|
|
26
|
+
/** The longest snapshots table name, in bytes, which leaves room for its `_pkey` index. */
|
|
27
|
+
export const MAX_SNAPSHOTS_TABLE_NAME_BYTES = 63 - '_pkey'.length
|
|
28
|
+
|
|
29
|
+
// Only pgTables can make a PgTables, so the names the DDL interpolates are always validated.
|
|
30
|
+
declare const validated: unique symbol
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* An event log's two configured tables, validated and folded to lower case. Only
|
|
34
|
+
* {@link pgTables} makes one.
|
|
35
|
+
*/
|
|
36
|
+
export interface PgTables {
|
|
37
|
+
readonly events: string
|
|
38
|
+
readonly snapshots: string
|
|
39
|
+
readonly [validated]: true
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
43
|
+
|
|
44
|
+
// PostgreSQL's reserved keywords (pg_get_keywords() categories R and T), which can't be unquoted
|
|
45
|
+
// table names. The same list as Go's and Rust's.
|
|
46
|
+
const RESERVED_KEYWORDS = new Set(
|
|
47
|
+
`all analyse analyze and any array as asc asymmetric authorization binary both case cast check
|
|
48
|
+
collate collation column concurrently constraint create cross current_catalog current_date
|
|
49
|
+
current_role current_schema current_time current_timestamp current_user default deferrable desc
|
|
50
|
+
distinct do else end except false fetch for foreign freeze from full grant group having ilike in
|
|
51
|
+
initially inner intersect into is isnull join lateral leading left like limit localtime
|
|
52
|
+
localtimestamp natural not notnull null offset on only or order outer overlaps placing primary
|
|
53
|
+
references returning right select session_user similar some symmetric system_user table
|
|
54
|
+
tablesample then to trailing true union unique user using variadic verbose when where window
|
|
55
|
+
with`.split(/\s+/),
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Validates an event log's table names and folds them to lower case, as PostgreSQL folds unquoted
|
|
60
|
+
* identifiers. Each must be a plain identifier that isn't a reserved keyword, within its length
|
|
61
|
+
* limit, without the {@link RESERVED_INFIX}, and no two relations the schema creates may share a
|
|
62
|
+
* name. A name that breaks a rule fails with `invalidArgument`, as Go and Rust refuse it at
|
|
63
|
+
* construction.
|
|
64
|
+
*/
|
|
65
|
+
export function pgTables(
|
|
66
|
+
events: string = DEFAULT_EVENTS_TABLE,
|
|
67
|
+
snapshots: string = DEFAULT_SNAPSHOTS_TABLE,
|
|
68
|
+
): PgTables {
|
|
69
|
+
for (const [name, limit] of [
|
|
70
|
+
[events, MAX_EVENTS_TABLE_NAME_BYTES],
|
|
71
|
+
[snapshots, MAX_SNAPSHOTS_TABLE_NAME_BYTES],
|
|
72
|
+
] as const) {
|
|
73
|
+
if (!validIdentifier(name, limit)) {
|
|
74
|
+
throw invalidConfig(`invalid table name ${JSON.stringify(name)}`)
|
|
75
|
+
}
|
|
76
|
+
if (name.toLowerCase().includes(RESERVED_INFIX)) {
|
|
77
|
+
throw invalidConfig(
|
|
78
|
+
`table name ${JSON.stringify(name)} must not contain the reserved infix ` +
|
|
79
|
+
JSON.stringify(RESERVED_INFIX),
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const tables = {events: events.toLowerCase(), snapshots: snapshots.toLowerCase()} as PgTables
|
|
85
|
+
const shared = sharedRelation(tables)
|
|
86
|
+
if (shared !== null) {
|
|
87
|
+
throw invalidConfig(
|
|
88
|
+
`tables ${JSON.stringify(events)} and ${JSON.stringify(snapshots)} would both use the ` +
|
|
89
|
+
`name ${JSON.stringify(shared)}`,
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return tables
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The command-outcomes table: `evt_events` yields `evt_events__evt_command_outcomes`. */
|
|
97
|
+
export function outcomesTable(tables: PgTables): string {
|
|
98
|
+
return derived(tables.events, 'command_outcomes')
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The feature-marker table: `evt_events` yields `evt_events__evt_features`. */
|
|
102
|
+
export function featuresTable(tables: PgTables): string {
|
|
103
|
+
return derived(tables.events, 'features')
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The rebuild-lock table: `evt_events` yields `evt_events__evt_rebuild_lock`. */
|
|
107
|
+
export function rebuildLockTable(tables: PgTables): string {
|
|
108
|
+
return derived(tables.events, 'rebuild_lock')
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The rebuild-generation table: `evt_events` yields `evt_events__evt_rebuild_generation`. */
|
|
112
|
+
export function rebuildGenerationTable(tables: PgTables): string {
|
|
113
|
+
return derived(tables.events, 'rebuild_generation')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The stream-heads table: `evt_events` yields `evt_events__evt_stream_heads`. */
|
|
117
|
+
export function streamHeadsTable(tables: PgTables): string {
|
|
118
|
+
return derived(tables.events, 'stream_heads')
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The entity-type index of the events table: `evt_events__evt_entity_type_idx`. */
|
|
122
|
+
export function entityTypeIndex(tables: PgTables): string {
|
|
123
|
+
return derived(tables.events, 'entity_type_idx')
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The idempotent DDL of an event log, byte for byte the DDL Go's `EnsureSchema` and Rust's
|
|
128
|
+
* `ensure_schema` run: the events and snapshots tables, the entity-type index (dropping its
|
|
129
|
+
* pre-v0.9 name), and the command-outcome, feature-marker, rebuild-fence and stream-heads tables.
|
|
130
|
+
* Run it inside one transaction, after {@link SCHEMA_LOCK} with the events table name, as Go and
|
|
131
|
+
* Rust do.
|
|
132
|
+
*/
|
|
133
|
+
export function schemaDdl(tables: PgTables): string {
|
|
134
|
+
const {events, snapshots} = tables
|
|
135
|
+
|
|
136
|
+
return `
|
|
137
|
+
CREATE TABLE IF NOT EXISTS ${events} (
|
|
138
|
+
entity_id text NOT NULL,
|
|
139
|
+
sequence bigint NOT NULL,
|
|
140
|
+
event_id text NOT NULL,
|
|
141
|
+
event_type text NOT NULL,
|
|
142
|
+
version bigint NOT NULL,
|
|
143
|
+
entity_type text NOT NULL,
|
|
144
|
+
payload bytea NOT NULL,
|
|
145
|
+
metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
|
|
146
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
147
|
+
PRIMARY KEY (entity_id, sequence)
|
|
148
|
+
);
|
|
149
|
+
CREATE INDEX IF NOT EXISTS ${entityTypeIndex(tables)} ON ${events} (entity_type);
|
|
150
|
+
DO $$
|
|
151
|
+
BEGIN
|
|
152
|
+
IF EXISTS (
|
|
153
|
+
SELECT 1 FROM pg_index
|
|
154
|
+
WHERE indexrelid = to_regclass('${events}_entity_type_idx')
|
|
155
|
+
AND indrelid = '${events}'::regclass
|
|
156
|
+
) THEN
|
|
157
|
+
DROP INDEX ${events}_entity_type_idx;
|
|
158
|
+
END IF;
|
|
159
|
+
END $$;
|
|
160
|
+
|
|
161
|
+
CREATE TABLE IF NOT EXISTS ${snapshots} (
|
|
162
|
+
entity_id text PRIMARY KEY,
|
|
163
|
+
entity_type text NOT NULL,
|
|
164
|
+
sequence bigint NOT NULL,
|
|
165
|
+
event_sequence bigint NOT NULL,
|
|
166
|
+
payload bytea NOT NULL,
|
|
167
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
CREATE TABLE IF NOT EXISTS ${outcomesTable(tables)} (
|
|
171
|
+
command_id text PRIMARY KEY,
|
|
172
|
+
status text NOT NULL CHECK (status IN ('accepted', 'rejected')),
|
|
173
|
+
digest text NOT NULL,
|
|
174
|
+
response bytea,
|
|
175
|
+
events jsonb NOT NULL DEFAULT '[]'::jsonb,
|
|
176
|
+
rejection jsonb,
|
|
177
|
+
code text,
|
|
178
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
179
|
+
CHECK ((status = 'rejected' AND rejection IS NOT NULL AND code IS NOT NULL)
|
|
180
|
+
OR (status = 'accepted' AND rejection IS NULL AND code IS NULL))
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
CREATE TABLE IF NOT EXISTS ${featuresTable(tables)} (
|
|
184
|
+
id integer PRIMARY KEY,
|
|
185
|
+
version bigint NOT NULL,
|
|
186
|
+
features text NOT NULL,
|
|
187
|
+
history_dependent text NOT NULL DEFAULT '[]',
|
|
188
|
+
retention text NOT NULL DEFAULT '[]'
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
CREATE TABLE IF NOT EXISTS ${rebuildLockTable(tables)} (
|
|
192
|
+
id integer PRIMARY KEY,
|
|
193
|
+
owner text NOT NULL,
|
|
194
|
+
generation bigint NOT NULL,
|
|
195
|
+
lease_expires_at timestamptz NOT NULL
|
|
196
|
+
);
|
|
197
|
+
|
|
198
|
+
CREATE TABLE IF NOT EXISTS ${rebuildGenerationTable(tables)} (
|
|
199
|
+
id integer PRIMARY KEY,
|
|
200
|
+
value bigint NOT NULL,
|
|
201
|
+
force_released boolean NOT NULL DEFAULT false
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
CREATE TABLE IF NOT EXISTS ${streamHeadsTable(tables)} (
|
|
205
|
+
entity_id text PRIMARY KEY,
|
|
206
|
+
entity_type text NOT NULL,
|
|
207
|
+
head bigint NOT NULL CHECK (head >= 1)
|
|
208
|
+
);
|
|
209
|
+
`
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Serializes schema changes across processes, in every language: `IF NOT EXISTS` alone can still
|
|
214
|
+
* race in PostgreSQL's catalogs. `$1` is the events table name.
|
|
215
|
+
*/
|
|
216
|
+
export const SCHEMA_LOCK = 'SELECT pg_advisory_xact_lock(1702261762, hashtext($1))'
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The per-entity transaction lock every commit and snapshot write takes, `$1` being the entity
|
|
220
|
+
* ID. Go and Rust run this exact statement, so writers in every language exclude each other.
|
|
221
|
+
*/
|
|
222
|
+
export const ENTITY_LOCK = 'SELECT pg_advisory_xact_lock(1702261760, hashtext($1))'
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* The shared engine-row lock a commit takes and holds to `COMMIT`, `$1` being a key from
|
|
226
|
+
* {@link featuresLockKey} or {@link rebuildLockKey}. Commits don't serialize against each other.
|
|
227
|
+
*/
|
|
228
|
+
export const ENGINE_LOCK_SHARED = 'SELECT pg_advisory_xact_lock_shared(1702261761, hashtext($1))'
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* The exclusive engine-row lock a declaration or a rebuild lifecycle step takes for its short
|
|
232
|
+
* transaction, so it never slips between a commit's check and its `COMMIT`.
|
|
233
|
+
*/
|
|
234
|
+
export const ENGINE_LOCK_EXCLUSIVE = 'SELECT pg_advisory_xact_lock(1702261761, hashtext($1))'
|
|
235
|
+
|
|
236
|
+
/** The feature marker's engine-row lock key: `{events}:features`. */
|
|
237
|
+
export function featuresLockKey(tables: PgTables): string {
|
|
238
|
+
return `${tables.events}:features`
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** The rebuild fence's engine-row lock key: `{events}:rebuild`. */
|
|
242
|
+
export function rebuildLockKey(tables: PgTables): string {
|
|
243
|
+
return `${tables.events}:rebuild`
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function derived(events: string, suffix: string): string {
|
|
247
|
+
return `${events}${RESERVED_INFIX}${suffix}`
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// A valid identifier is ASCII, so its length is its byte count and folding it changes only A-Z.
|
|
251
|
+
// The type check refuses a non-string passed from JavaScript, which the pattern would coerce.
|
|
252
|
+
function validIdentifier(name: unknown, limit: number): name is string {
|
|
253
|
+
return (
|
|
254
|
+
typeof name === 'string' &&
|
|
255
|
+
name.length <= limit &&
|
|
256
|
+
IDENTIFIER.test(name) &&
|
|
257
|
+
!RESERVED_KEYWORDS.has(name.toLowerCase())
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// A name two relations of the schema would share, or null, with the names already folded to lower
|
|
262
|
+
// case. CREATE TABLE IF NOT EXISTS would otherwise skip a table whose name an index already took.
|
|
263
|
+
function sharedRelation(tables: PgTables): string | null {
|
|
264
|
+
const {events, snapshots} = tables
|
|
265
|
+
const derivedTables = [
|
|
266
|
+
outcomesTable(tables),
|
|
267
|
+
featuresTable(tables),
|
|
268
|
+
rebuildLockTable(tables),
|
|
269
|
+
rebuildGenerationTable(tables),
|
|
270
|
+
streamHeadsTable(tables),
|
|
271
|
+
]
|
|
272
|
+
const relations = [
|
|
273
|
+
events,
|
|
274
|
+
`${events}_pkey`,
|
|
275
|
+
entityTypeIndex(tables),
|
|
276
|
+
...derivedTables.flatMap((table) => [table, `${table}_pkey`]),
|
|
277
|
+
snapshots,
|
|
278
|
+
`${snapshots}_pkey`,
|
|
279
|
+
]
|
|
280
|
+
|
|
281
|
+
return relations.find((relation, index) => relations.indexOf(relation) !== index) ?? null
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function invalidConfig(message: string): EvtError {
|
|
285
|
+
return new EvtError('invalidArgument', `postgres: ${message}`)
|
|
286
|
+
}
|
package/src/repository.ts
CHANGED
|
@@ -4,7 +4,12 @@
|
|
|
4
4
|
import {headActionSize, headUpdate} from './dynamodb/head.js'
|
|
5
5
|
import {eventItem, itemSize, snapshotItem} from './dynamodb/item.js'
|
|
6
6
|
import {FEATURES_PK, REBUILD_LOCK_PK} from './dynamodb/marker.js'
|
|
7
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
CommitTooLargeError,
|
|
9
|
+
EvtError,
|
|
10
|
+
ProjectorOnlyCommitError,
|
|
11
|
+
ReservedEntityIdError,
|
|
12
|
+
} from './errors.js'
|
|
8
13
|
import {type SerializedEvent, type SerializedSnapshot, eventId} from './event.js'
|
|
9
14
|
import {MAX_COMMIT_ITEM_BYTES} from './snapshots.js'
|
|
10
15
|
|
|
@@ -17,9 +22,24 @@ export interface NewSnapshot {
|
|
|
17
22
|
payload: Uint8Array
|
|
18
23
|
}
|
|
19
24
|
|
|
25
|
+
/**
|
|
26
|
+
* Operations a projector adds to a commit, for the backend it names to write in the commit's own
|
|
27
|
+
* transaction (Go's transaction groups). The DynamoDB repository writes `dynamodb` groups, whose
|
|
28
|
+
* operations are `TransactWriteItems` actions. The in-memory repository budgets every group and
|
|
29
|
+
* writes none, as Go's does, so code with projectors runs on it unchanged.
|
|
30
|
+
*/
|
|
31
|
+
export interface ProjectorGroup {
|
|
32
|
+
/** The backend whose transaction carries the operations, such as `dynamodb`. */
|
|
33
|
+
readonly backend: string
|
|
34
|
+
/** The operations, in the order they're written. */
|
|
35
|
+
readonly operations: readonly unknown[]
|
|
36
|
+
/** Each operation's size in the commit budget, as DynamoDB counts it. */
|
|
37
|
+
readonly sizes: readonly number[]
|
|
38
|
+
}
|
|
39
|
+
|
|
20
40
|
/**
|
|
21
41
|
* Everything a repository writes atomically for one command. A commit with no events is a no-op,
|
|
22
|
-
* and its snapshot is ignored.
|
|
42
|
+
* and its snapshot is ignored, unless it carries projector operations: then it's refused.
|
|
23
43
|
*/
|
|
24
44
|
export interface Commit {
|
|
25
45
|
/** The stream the events are appended to. */
|
|
@@ -28,6 +48,8 @@ export interface Commit {
|
|
|
28
48
|
events: SerializedEvent[]
|
|
29
49
|
/** The snapshot to write, when the commit reaches a snapshot boundary. */
|
|
30
50
|
snapshot?: NewSnapshot | null | undefined
|
|
51
|
+
/** The operations the aggregate's projectors add, written first, in order. */
|
|
52
|
+
projections?: readonly ProjectorGroup[] | null | undefined
|
|
31
53
|
}
|
|
32
54
|
|
|
33
55
|
/** Options every repository call takes. */
|
|
@@ -53,7 +75,9 @@ export interface CallOptions {
|
|
|
53
75
|
* {@link StreamHeadDriftError}, ranked above a gap and any other conflict;
|
|
54
76
|
* - refuse a commit's snapshot whose sequence isn't the stored snapshot's plus one (1 with none
|
|
55
77
|
* stored) with a {@link ConflictError};
|
|
56
|
-
* - write a commit's events, head and snapshot atomically, or nothing
|
|
78
|
+
* - write a commit's events, head and snapshot atomically, or nothing, with the projector
|
|
79
|
+
* operations it writes (a backend writes only its own groups), and refuse projector operations
|
|
80
|
+
* without events with a {@link ProjectorOnlyCommitError};
|
|
57
81
|
* - refuse an entity ID in a reserved namespace on every write path, before any request;
|
|
58
82
|
* - refuse every write (a commit, a snapshot write, compaction) to a store whose feature manifest
|
|
59
83
|
* declares a pair this package doesn't model, with an {@link UnsupportedFeatureError}, and to
|
|
@@ -147,11 +171,27 @@ export function checkNotReserved(entityId: string): void {
|
|
|
147
171
|
* Checks that a commit's events can be stored as written: each belongs to the commit's entity and
|
|
148
172
|
* has the ID `{entityId}:{sequence}`, they share one entity type, the first sequence is at least
|
|
149
173
|
* 1, and the sequences are contiguous. A snapshot must have the events' entity type and a
|
|
150
|
-
* sequence of at least 1
|
|
174
|
+
* sequence of at least 1, and each projector group a size per operation. A commit with no events
|
|
175
|
+
* is valid, and its snapshot isn't checked, but its projector operations are refused.
|
|
151
176
|
*/
|
|
152
177
|
export function validateCommit(commit: Commit): void {
|
|
178
|
+
let operations = 0
|
|
179
|
+
for (const group of commit.projections ?? []) {
|
|
180
|
+
if (group.sizes.length !== group.operations.length) {
|
|
181
|
+
throw invalidCommit(
|
|
182
|
+
`a ${group.backend} projector group has ${group.operations.length} operations but ` +
|
|
183
|
+
`${group.sizes.length} sizes`,
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
operations += group.operations.length
|
|
187
|
+
}
|
|
188
|
+
|
|
153
189
|
const [first] = commit.events
|
|
154
190
|
if (first === undefined) {
|
|
191
|
+
if (operations > 0) {
|
|
192
|
+
throw new ProjectorOnlyCommitError(operations)
|
|
193
|
+
}
|
|
194
|
+
|
|
155
195
|
return
|
|
156
196
|
}
|
|
157
197
|
|
|
@@ -207,9 +247,10 @@ export function validateCommit(commit: Commit): void {
|
|
|
207
247
|
|
|
208
248
|
/**
|
|
209
249
|
* The size of each action a commit's transaction carries, in order: the feature-marker and
|
|
210
|
-
* rebuild-lock checks, then the stream's head update, its event puts,
|
|
211
|
-
* it writes one. `ttl` gives the expiry an entity type's items carry, if
|
|
212
|
-
* backend budgets a commit by these sizes, so an oversized commit fails the
|
|
250
|
+
* rebuild-lock checks, the projector operations, then the stream's head update, its event puts,
|
|
251
|
+
* and its snapshot put when it writes one. `ttl` gives the expiry an entity type's items carry, if
|
|
252
|
+
* it's retained. Every backend budgets a commit by these sizes, so an oversized commit fails the
|
|
253
|
+
* same way on each.
|
|
213
254
|
*/
|
|
214
255
|
export function commitSizes(
|
|
215
256
|
commit: Commit,
|
|
@@ -217,6 +258,10 @@ export function commitSizes(
|
|
|
217
258
|
): number[] {
|
|
218
259
|
// The control rows every commit checks: the feature marker and the rebuild lock.
|
|
219
260
|
const sizes = [controlCheckSize(FEATURES_PK), controlCheckSize(REBUILD_LOCK_PK)]
|
|
261
|
+
for (const group of commit.projections ?? []) {
|
|
262
|
+
sizes.push(...group.sizes)
|
|
263
|
+
}
|
|
264
|
+
|
|
220
265
|
const first = commit.events[0]
|
|
221
266
|
const last = commit.events.at(-1)
|
|
222
267
|
if (first === undefined || last === undefined) {
|
package/src/store.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
type Aggregate,
|
|
6
6
|
type EventDefinitions,
|
|
7
7
|
type EventOf,
|
|
8
|
+
type Projection,
|
|
8
9
|
type Rejection,
|
|
9
10
|
encodeEventData,
|
|
10
11
|
replayEvent,
|
|
@@ -13,7 +14,7 @@ import {commitIds} from './commit-id.js'
|
|
|
13
14
|
import {EvtError, SequenceGapError, SnapshotError, isConflict, isRetryable} from './errors.js'
|
|
14
15
|
import {type SerializedEvent, eventId} from './event.js'
|
|
15
16
|
import {type Metadata, emptyMetadata} from './metadata.js'
|
|
16
|
-
import type {CallOptions, NewSnapshot, Repository} from './repository.js'
|
|
17
|
+
import type {CallOptions, NewSnapshot, ProjectorGroup, Repository} from './repository.js'
|
|
17
18
|
import {
|
|
18
19
|
DEFAULT_RETRY_POLICY,
|
|
19
20
|
type RetryPolicy,
|
|
@@ -146,8 +147,10 @@ export class Store {
|
|
|
146
147
|
|
|
147
148
|
/**
|
|
148
149
|
* Loads the aggregate, runs the command, and commits its events, with a snapshot when the
|
|
149
|
-
* commit reaches the snapshot interval
|
|
150
|
-
* is left out, so the commit still succeeds and
|
|
150
|
+
* commit reaches the snapshot interval, and the aggregate's projector operations. A snapshot
|
|
151
|
+
* whose item is over the per-item commit budget is left out, so the commit still succeeds and
|
|
152
|
+
* later loads replay from the one before, but a projector's own items are budgeted as they are:
|
|
153
|
+
* a view row of a state that large fails the commit.
|
|
151
154
|
*
|
|
152
155
|
* A command ID already carried by an event folded in since the latest snapshot makes the
|
|
153
156
|
* command a `duplicate`, and the handler doesn't run. A conflict with another writer throws;
|
|
@@ -175,8 +178,13 @@ export class Store {
|
|
|
175
178
|
return {kind: 'committed', state: loaded, events: []}
|
|
176
179
|
}
|
|
177
180
|
|
|
178
|
-
const {state, events, snapshot} = this.#stage(
|
|
179
|
-
|
|
181
|
+
const {state, events, snapshot, projections} = this.#stage(
|
|
182
|
+
aggregate,
|
|
183
|
+
loaded,
|
|
184
|
+
decision.events,
|
|
185
|
+
metadata,
|
|
186
|
+
)
|
|
187
|
+
await this.repository.commit({entityId, events, snapshot, projections}, options)
|
|
180
188
|
|
|
181
189
|
return {kind: 'committed', state, events}
|
|
182
190
|
}
|
|
@@ -262,14 +270,19 @@ export class Store {
|
|
|
262
270
|
return {entityId, state, sequence, snapshotSequence, seenCommandIds}
|
|
263
271
|
}
|
|
264
272
|
|
|
265
|
-
// Applies the decided events, and builds the stored events
|
|
266
|
-
//
|
|
273
|
+
// Applies the decided events, and builds the stored events, the snapshot the policy calls for,
|
|
274
|
+
// and the projectors' operations. The state is only used once the commit succeeds.
|
|
267
275
|
#stage<S, C, D extends EventDefinitions>(
|
|
268
276
|
aggregate: Aggregate<S, C, D>,
|
|
269
277
|
loaded: Loaded<S>,
|
|
270
278
|
decided: readonly EventOf<D>[],
|
|
271
279
|
metadata: Metadata,
|
|
272
|
-
): {
|
|
280
|
+
): {
|
|
281
|
+
state: Loaded<S>
|
|
282
|
+
events: SerializedEvent[]
|
|
283
|
+
snapshot: NewSnapshot | null
|
|
284
|
+
projections: ProjectorGroup[]
|
|
285
|
+
} {
|
|
273
286
|
const entityId = loaded.entityId
|
|
274
287
|
let sequence = loaded.sequence
|
|
275
288
|
let state = loaded.state
|
|
@@ -329,9 +342,46 @@ export class Store {
|
|
|
329
342
|
},
|
|
330
343
|
events,
|
|
331
344
|
snapshot,
|
|
345
|
+
projections: this.#project(aggregate, entityId, state, events, snapshot),
|
|
332
346
|
}
|
|
333
347
|
}
|
|
334
348
|
|
|
349
|
+
// The operations the aggregate's projectors add to the commit, in declaration order.
|
|
350
|
+
#project<S, C, D extends EventDefinitions>(
|
|
351
|
+
aggregate: Aggregate<S, C, D>,
|
|
352
|
+
entityId: string,
|
|
353
|
+
state: S,
|
|
354
|
+
events: SerializedEvent[],
|
|
355
|
+
snapshot: NewSnapshot | null,
|
|
356
|
+
): ProjectorGroup[] {
|
|
357
|
+
const projectors = aggregate.projectors ?? []
|
|
358
|
+
if (projectors.length === 0) {
|
|
359
|
+
return []
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Each projector gets its own frozen copy of the events, their metadata and every byte array,
|
|
363
|
+
// so none can change what another one sees, or what the commit writes.
|
|
364
|
+
const encodedState = snapshot?.payload ?? aggregate.state.encode(state)
|
|
365
|
+
const detached = (): Projection<S> =>
|
|
366
|
+
Object.freeze({
|
|
367
|
+
entityType: aggregate.type,
|
|
368
|
+
entityId,
|
|
369
|
+
state,
|
|
370
|
+
encodedState: encodedState.slice(),
|
|
371
|
+
events: Object.freeze(
|
|
372
|
+
events.map((event) =>
|
|
373
|
+
Object.freeze({
|
|
374
|
+
...event,
|
|
375
|
+
payload: event.payload && event.payload.slice(),
|
|
376
|
+
metadata: Object.freeze(copyMetadata(event.metadata)),
|
|
377
|
+
}),
|
|
378
|
+
),
|
|
379
|
+
),
|
|
380
|
+
})
|
|
381
|
+
|
|
382
|
+
return projectors.flatMap((projector) => projector.project(detached()) ?? [])
|
|
383
|
+
}
|
|
384
|
+
|
|
335
385
|
// The command's metadata with the store's region and the clock's timestamp where it has none,
|
|
336
386
|
// and the commit ID the engine stamps: the command ID, else the caller's, else a generated one.
|
|
337
387
|
// Field by field, so a field an untyped caller set to undefined is empty too, and every key is
|