@livestore/common 0.5.0-dev.1 → 0.5.1
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/dist/.tsbuildinfo +1 -1
- package/dist/ClientSessionLeaderThreadProxy.d.ts +89 -7
- package/dist/ClientSessionLeaderThreadProxy.d.ts.map +1 -1
- package/dist/ClientSessionLeaderThreadProxy.js +11 -0
- package/dist/ClientSessionLeaderThreadProxy.js.map +1 -1
- package/dist/EventlogSqliteDb.d.ts +10 -0
- package/dist/EventlogSqliteDb.d.ts.map +1 -0
- package/dist/EventlogSqliteDb.js +7 -0
- package/dist/EventlogSqliteDb.js.map +1 -0
- package/dist/MaterializationJournal.d.ts +9 -14
- package/dist/MaterializationJournal.d.ts.map +1 -1
- package/dist/MaterializationJournal.js +79 -50
- package/dist/MaterializationJournal.js.map +1 -1
- package/dist/StateHead.d.ts +4 -6
- package/dist/StateHead.d.ts.map +1 -1
- package/dist/StateHead.js +5 -3
- package/dist/StateHead.js.map +1 -1
- package/dist/StateSqliteDb.d.ts +10 -0
- package/dist/StateSqliteDb.d.ts.map +1 -0
- package/dist/StateSqliteDb.js +7 -0
- package/dist/StateSqliteDb.js.map +1 -0
- package/dist/adapter-types.d.ts +3 -2
- package/dist/adapter-types.d.ts.map +1 -1
- package/dist/adapter-types.js.map +1 -1
- package/dist/devtools/devtools-messages-leader.d.ts +120 -6
- package/dist/devtools/devtools-messages-leader.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/leader-thread/LeaderPersistence.d.ts +65 -0
- package/dist/leader-thread/LeaderPersistence.d.ts.map +1 -0
- package/dist/leader-thread/LeaderPersistence.js +127 -0
- package/dist/leader-thread/LeaderPersistence.js.map +1 -0
- package/dist/leader-thread/LeaderSyncProcessor.d.ts +26 -126
- package/dist/leader-thread/LeaderSyncProcessor.d.ts.map +1 -1
- package/dist/leader-thread/LeaderSyncProcessor.js +830 -658
- package/dist/leader-thread/LeaderSyncProcessor.js.map +1 -1
- package/dist/leader-thread/connection.js +8 -3
- package/dist/leader-thread/connection.js.map +1 -1
- package/dist/leader-thread/eventlog.d.ts +24 -9
- package/dist/leader-thread/eventlog.d.ts.map +1 -1
- package/dist/leader-thread/eventlog.js +34 -28
- package/dist/leader-thread/eventlog.js.map +1 -1
- package/dist/leader-thread/leader-worker-devtools.d.ts +3 -1
- package/dist/leader-thread/leader-worker-devtools.d.ts.map +1 -1
- package/dist/leader-thread/leader-worker-devtools.js +45 -3
- package/dist/leader-thread/leader-worker-devtools.js.map +1 -1
- package/dist/leader-thread/make-leader-thread-layer.d.ts +7 -5
- package/dist/leader-thread/make-leader-thread-layer.d.ts.map +1 -1
- package/dist/leader-thread/make-leader-thread-layer.js +12 -13
- package/dist/leader-thread/make-leader-thread-layer.js.map +1 -1
- package/dist/leader-thread/materialize-event.d.ts +5 -11
- package/dist/leader-thread/materialize-event.d.ts.map +1 -1
- package/dist/leader-thread/materialize-event.js +38 -86
- package/dist/leader-thread/materialize-event.js.map +1 -1
- package/dist/leader-thread/mod.d.ts +1 -0
- package/dist/leader-thread/mod.d.ts.map +1 -1
- package/dist/leader-thread/mod.js +1 -0
- package/dist/leader-thread/mod.js.map +1 -1
- package/dist/leader-thread/recreate-db.d.ts +5 -5
- package/dist/leader-thread/recreate-db.d.ts.map +1 -1
- package/dist/leader-thread/recreate-db.js +3 -2
- package/dist/leader-thread/recreate-db.js.map +1 -1
- package/dist/leader-thread/shutdown-channel.d.ts +2 -1
- package/dist/leader-thread/shutdown-channel.d.ts.map +1 -1
- package/dist/leader-thread/shutdown-channel.js +8 -1
- package/dist/leader-thread/shutdown-channel.js.map +1 -1
- package/dist/leader-thread/types.d.ts +5 -11
- package/dist/leader-thread/types.d.ts.map +1 -1
- package/dist/leader-thread/types.js.map +1 -1
- package/dist/rematerialize-from-eventlog.d.ts +2 -2
- package/dist/rematerialize-from-eventlog.d.ts.map +1 -1
- package/dist/rematerialize-from-eventlog.js +4 -2
- package/dist/rematerialize-from-eventlog.js.map +1 -1
- package/dist/schema/LiveStoreEvent/client.d.ts +19 -64
- package/dist/schema/LiveStoreEvent/client.d.ts.map +1 -1
- package/dist/schema/LiveStoreEvent/client.js +28 -102
- package/dist/schema/LiveStoreEvent/client.js.map +1 -1
- package/dist/schema/LiveStoreEvent/client.test.js +5 -11
- package/dist/schema/LiveStoreEvent/client.test.js.map +1 -1
- package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js +8 -1
- package/dist/schema/state/sqlite/db-schema/ast/fingerprint.js.map +1 -1
- package/dist/schema/state/sqlite/db-schema/ast/fingerprint.test.js +2 -2
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts +6 -1
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.d.ts.map +1 -1
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js +9 -5
- package/dist/schema/state/sqlite/db-schema/has-json-string-encoding.js.map +1 -1
- package/dist/schema/state/sqlite/system-tables/state-tables.d.ts +8 -139
- package/dist/schema/state/sqlite/system-tables/state-tables.d.ts.map +1 -1
- package/dist/schema/state/sqlite/system-tables/state-tables.js +11 -20
- package/dist/schema/state/sqlite/system-tables/state-tables.js.map +1 -1
- package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js +1 -1
- package/dist/schema-management/__tests__/migrations-autoincrement-quoting.test.js.map +1 -1
- package/dist/sqlite-types.d.ts +1 -1
- package/dist/sqlite-types.d.ts.map +1 -1
- package/dist/sync/ClientSessionSyncProcessor.d.ts +42 -69
- package/dist/sync/ClientSessionSyncProcessor.d.ts.map +1 -1
- package/dist/sync/ClientSessionSyncProcessor.js +611 -291
- package/dist/sync/ClientSessionSyncProcessor.js.map +1 -1
- package/dist/sync/syncstate.d.ts +407 -27
- package/dist/sync/syncstate.d.ts.map +1 -1
- package/dist/sync/syncstate.js +26 -19
- package/dist/sync/syncstate.js.map +1 -1
- package/dist/sync/syncstate.test.js +25 -5
- package/dist/sync/syncstate.test.js.map +1 -1
- package/package.json +18 -18
- package/src/ClientSessionLeaderThreadProxy.ts +16 -7
- package/src/EventlogSqliteDb.ts +11 -0
- package/src/MaterializationJournal.ts +106 -77
- package/src/StateHead.ts +6 -7
- package/src/StateSqliteDb.ts +9 -0
- package/src/adapter-types.ts +9 -2
- package/src/index.ts +2 -0
- package/src/leader-thread/LeaderPersistence.ts +244 -0
- package/src/leader-thread/LeaderSyncProcessor.ts +1099 -1011
- package/src/leader-thread/connection.ts +9 -3
- package/src/leader-thread/eventlog.ts +54 -39
- package/src/leader-thread/leader-worker-devtools.ts +73 -4
- package/src/leader-thread/make-leader-thread-layer.ts +24 -21
- package/src/leader-thread/materialize-event.ts +47 -119
- package/src/leader-thread/mod.ts +1 -0
- package/src/leader-thread/recreate-db.ts +9 -6
- package/src/leader-thread/shutdown-channel.ts +8 -1
- package/src/leader-thread/types.ts +6 -8
- package/src/rematerialize-from-eventlog.ts +3 -3
- package/src/schema/LiveStoreEvent/client.test.ts +7 -12
- package/src/schema/LiveStoreEvent/client.ts +38 -122
- package/src/schema/state/sqlite/db-schema/ast/fingerprint.test.ts +2 -2
- package/src/schema/state/sqlite/db-schema/ast/fingerprint.ts +8 -1
- package/src/schema/state/sqlite/db-schema/has-json-string-encoding.ts +11 -7
- package/src/schema/state/sqlite/system-tables/state-tables.ts +13 -26
- package/src/schema-management/__tests__/migrations-autoincrement-quoting.test.ts +1 -1
- package/src/sqlite-types.ts +1 -1
- package/src/sync/ClientSessionSyncProcessor.ts +809 -456
- package/src/sync/syncstate.test.ts +32 -9
- package/src/sync/syncstate.ts +41 -29
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Predicate, ReadonlyArray, Schema } from '@livestore/utils/effect'
|
|
2
2
|
|
|
3
|
-
import { SqliteError
|
|
3
|
+
import { SqliteError } from './adapter-types.ts'
|
|
4
4
|
import { execSql, execSqlPrepared } from './leader-thread/connection.ts'
|
|
5
5
|
import * as EventSequenceNumber from './schema/EventSequenceNumber/mod.ts'
|
|
6
6
|
import { SystemTables } from './schema/mod.ts'
|
|
7
|
-
import {
|
|
7
|
+
import { insertRowPrepared } from './sql-queries/index.ts'
|
|
8
8
|
import * as SqliteDbHelper from './sqlite-db-helper.ts'
|
|
9
|
+
import * as StateSqliteDb from './StateSqliteDb.ts'
|
|
9
10
|
import { prepareBindValues, sql } from './util.ts'
|
|
10
11
|
|
|
11
12
|
export const TypeId = '~@livestore/common/MaterializationJournal' as const
|
|
@@ -25,16 +26,18 @@ export class MaterializationJournalError extends Schema.TaggedError<Materializat
|
|
|
25
26
|
readonly [MaterializationJournalErrorTypeId] = MaterializationJournalErrorTypeId
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
export type MaterializationChangeset = { _tag: 'changeset'; data: Uint8Array<ArrayBuffer> } | { _tag: 'no-op' }
|
|
29
|
-
|
|
30
29
|
export type MaterializationRecord = {
|
|
31
30
|
key: EventSequenceNumber.Client.Composite
|
|
32
|
-
|
|
31
|
+
/** Changes recorded while materializing the event, or `null` when materialization did not change state. */
|
|
32
|
+
changeset: Uint8Array<ArrayBuffer> | null
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
export interface Service {
|
|
36
36
|
readonly [TypeId]: TypeId
|
|
37
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* Stores a materialization record, replacing any record at the same key. Runs inside the caller's savepoint or
|
|
39
|
+
* transaction, which every materialization already opens, so the replacement is atomic with the materialization.
|
|
40
|
+
*/
|
|
38
41
|
record: (record: MaterializationRecord) => Effect.Effect<void, MaterializationJournalError>
|
|
39
42
|
/** Reverts the keyed materializations in reverse order, then discards their records. */
|
|
40
43
|
rollback: (
|
|
@@ -48,16 +51,12 @@ export class MaterializationJournal extends Context.Service<MaterializationJourn
|
|
|
48
51
|
'@livestore/common/MaterializationJournal',
|
|
49
52
|
) {}
|
|
50
53
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
+
export const make = Effect.gen(function* () {
|
|
55
|
+
const dbState = yield* StateSqliteDb.StateSqliteDb
|
|
54
56
|
|
|
55
|
-
|
|
57
|
+
/** Runs inside `rollback`'s savepoint, which keeps a multi-chunk delete atomic. */
|
|
56
58
|
const deleteByKeys = Effect.fnUntraced(function* (keys: ReadonlyArray<EventSequenceNumber.Client.Composite>) {
|
|
57
|
-
|
|
58
|
-
const keyChunks = ReadonlyArray.chunksOf(100)(keys)
|
|
59
|
-
|
|
60
|
-
for (const keyChunk of keyChunks) {
|
|
59
|
+
for (const keyChunk of chunkKeys(keys)) {
|
|
61
60
|
const placeholders = keyChunk.map(() => '(?, ?, ?)').join(', ')
|
|
62
61
|
const bindValues = keyChunk.flatMap((key) => [key.global, key.client, key.rebaseGeneration])
|
|
63
62
|
const statement = sql`DELETE FROM ${SystemTables.MATERIALIZATION_JOURNAL_META_TABLE}
|
|
@@ -65,79 +64,89 @@ export const make = ({ dbState }: Options) => {
|
|
|
65
64
|
|
|
66
65
|
yield* execSqlPrepared(dbState, statement, prepareBindValues(bindValues, statement))
|
|
67
66
|
}
|
|
68
|
-
}
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
/** Reads the records of `keys`, chunked like `deleteByKeys`. */
|
|
70
|
+
const selectChangesets = Effect.fnUntraced(function* (keys: ReadonlyArray<EventSequenceNumber.Client.Composite>) {
|
|
71
|
+
const changesets = new Map<string, Uint8Array<ArrayBuffer> | null>()
|
|
72
|
+
for (const keyChunk of chunkKeys(keys)) {
|
|
73
|
+
const placeholders = keyChunk.map(() => '(?, ?, ?)').join(', ')
|
|
74
|
+
const bindValues = keyChunk.flatMap((key) => [key.global, key.client, key.rebaseGeneration])
|
|
75
|
+
const statement = sql`SELECT seqNumGlobal, seqNumClient, seqNumRebaseGeneration, changeset
|
|
76
|
+
FROM ${SystemTables.MATERIALIZATION_JOURNAL_META_TABLE}
|
|
77
|
+
WHERE (seqNumGlobal, seqNumClient, seqNumRebaseGeneration) IN (${placeholders})`
|
|
78
|
+
const preparedBindValues = prepareBindValues(bindValues, statement)
|
|
79
|
+
const rows = yield* Effect.try({
|
|
80
|
+
try: () => dbState.select<SystemTables.MaterializationJournalMetaRow>(statement, preparedBindValues),
|
|
81
|
+
catch: (cause) => new SqliteError({ cause, query: { sql: statement, bindValues: preparedBindValues } }),
|
|
82
|
+
})
|
|
83
|
+
for (const row of rows) {
|
|
84
|
+
changesets.set(
|
|
85
|
+
journalKey({
|
|
86
|
+
global: row.seqNumGlobal,
|
|
87
|
+
client: row.seqNumClient,
|
|
88
|
+
rebaseGeneration: row.seqNumRebaseGeneration,
|
|
89
|
+
}),
|
|
90
|
+
row.changeset,
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return changesets
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
// `record` runs for every materialized event, including every event a rebase replays, so its statements are built
|
|
98
|
+
// once and run without a span each. The materialization that records them carries the trace.
|
|
99
|
+
const insertStatement = insertRowPrepared({
|
|
100
|
+
tableName: SystemTables.MATERIALIZATION_JOURNAL_META_TABLE,
|
|
101
|
+
columns: SystemTables.materializationJournalMetaTable.sqliteDef.columns,
|
|
102
|
+
})
|
|
103
|
+
const deleteRecordStatement = sql`DELETE FROM ${SystemTables.MATERIALIZATION_JOURNAL_META_TABLE}
|
|
104
|
+
WHERE seqNumGlobal = $seqNumGlobal AND seqNumClient = $seqNumClient AND seqNumRebaseGeneration = $seqNumRebaseGeneration`
|
|
69
105
|
|
|
70
106
|
return MaterializationJournal.of({
|
|
71
107
|
[TypeId]: TypeId,
|
|
72
|
-
record:
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
// Generate the parameterized INSERT statement
|
|
77
|
-
const [statement, bindValues] = insertRow({
|
|
78
|
-
tableName: SystemTables.MATERIALIZATION_JOURNAL_META_TABLE,
|
|
79
|
-
columns: SystemTables.materializationJournalMetaTable.sqliteDef.columns,
|
|
80
|
-
values: {
|
|
108
|
+
record: (record) =>
|
|
109
|
+
Effect.try({
|
|
110
|
+
try: () => {
|
|
111
|
+
const bindValues = {
|
|
81
112
|
seqNumGlobal: record.key.global,
|
|
82
113
|
seqNumClient: record.key.client,
|
|
83
114
|
seqNumRebaseGeneration: record.key.rebaseGeneration,
|
|
84
|
-
changeset: record.changeset
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
115
|
+
changeset: record.changeset,
|
|
116
|
+
}
|
|
117
|
+
for (const statement of [deleteRecordStatement, insertStatement]) {
|
|
118
|
+
const preparedBindValues = prepareBindValues(bindValues, statement)
|
|
119
|
+
try {
|
|
120
|
+
dbState.execute(statement, preparedBindValues)
|
|
121
|
+
} catch (cause) {
|
|
122
|
+
throw new SqliteError({ cause, query: { sql: statement, bindValues: preparedBindValues } })
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
catch: (cause) => new MaterializationJournalError({ method: 'record', cause }),
|
|
127
|
+
}),
|
|
95
128
|
rollback: Effect.fnUntraced(
|
|
96
129
|
function* (keys: ReadonlyArray<EventSequenceNumber.Client.Composite>) {
|
|
97
130
|
const sortedKeys = keys.toSorted((a, b) => EventSequenceNumber.Client.compare(b, a))
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
},
|
|
109
|
-
limit: 1,
|
|
131
|
+
const changesetsByKey = yield* selectChangesets(sortedKeys)
|
|
132
|
+
const rollbackChangesets: Array<Uint8Array<ArrayBuffer> | null> = []
|
|
133
|
+
for (const key of sortedKeys) {
|
|
134
|
+
const changeset = changesetsByKey.get(journalKey(key))
|
|
135
|
+
if (changeset === undefined) {
|
|
136
|
+
return yield* new MaterializationJournalError({
|
|
137
|
+
method: 'rollback',
|
|
138
|
+
cause: new Error(
|
|
139
|
+
`Missing materialization journal record for ${EventSequenceNumber.Client.toString(key)}`,
|
|
140
|
+
),
|
|
110
141
|
})
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
catch: (cause) => new SqliteError({ cause, query: { sql: statement, bindValues: preparedBindValues } }),
|
|
115
|
-
})
|
|
116
|
-
|
|
117
|
-
if (row === undefined) {
|
|
118
|
-
return yield* new MaterializationJournalError({
|
|
119
|
-
method: 'rollback',
|
|
120
|
-
cause: new Error(
|
|
121
|
-
`Missing materialization journal record for ${EventSequenceNumber.Client.toString(key)}`,
|
|
122
|
-
),
|
|
123
|
-
})
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
return {
|
|
127
|
-
key,
|
|
128
|
-
changeset:
|
|
129
|
-
row.changeset === null
|
|
130
|
-
? { _tag: 'no-op' as const }
|
|
131
|
-
: { _tag: 'changeset' as const, data: row.changeset },
|
|
132
|
-
}
|
|
133
|
-
}),
|
|
134
|
-
)
|
|
142
|
+
}
|
|
143
|
+
rollbackChangesets.push(changeset)
|
|
144
|
+
}
|
|
135
145
|
|
|
136
|
-
for (const
|
|
137
|
-
if (
|
|
138
|
-
const data = record.changeset.data
|
|
146
|
+
for (const changeset of rollbackChangesets) {
|
|
147
|
+
if (changeset !== null) {
|
|
139
148
|
yield* Effect.try({
|
|
140
|
-
try: () => dbState.makeChangeset(
|
|
149
|
+
try: () => dbState.makeChangeset(changeset).invert().apply(),
|
|
141
150
|
catch: (cause) => new SqliteError({ cause }),
|
|
142
151
|
})
|
|
143
152
|
}
|
|
@@ -169,9 +178,9 @@ export const make = ({ dbState }: Options) => {
|
|
|
169
178
|
Effect.mapError((cause) => new MaterializationJournalError({ method: 'discardUpTo', cause })),
|
|
170
179
|
),
|
|
171
180
|
})
|
|
172
|
-
}
|
|
181
|
+
})
|
|
173
182
|
|
|
174
|
-
export const layer =
|
|
183
|
+
export const layer = Layer.effect(MaterializationJournal, make)
|
|
175
184
|
|
|
176
185
|
export const layerTest = Layer.succeed(
|
|
177
186
|
MaterializationJournal,
|
|
@@ -182,3 +191,23 @@ export const layerTest = Layer.succeed(
|
|
|
182
191
|
discardUpTo: () => Effect.void,
|
|
183
192
|
}),
|
|
184
193
|
)
|
|
194
|
+
|
|
195
|
+
const journalKey = (key: { global: number; client: number; rebaseGeneration: number }) =>
|
|
196
|
+
`${key.global},${key.client},${key.rebaseGeneration}`
|
|
197
|
+
|
|
198
|
+
/** Keys per statement: three bound parameters each, well below SQLite's limit of 999. */
|
|
199
|
+
const KEY_CHUNK_SIZE = 100
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Splits keys into chunks of exactly KEY_CHUNK_SIZE, padding the last chunk by repeating its final key. Every
|
|
203
|
+
* statement then has the same SQL, so the connection prepares and caches one statement instead of one per chunk
|
|
204
|
+
* length. A repeated key in an `IN` list matches the same row and changes no result.
|
|
205
|
+
*/
|
|
206
|
+
const chunkKeys = (
|
|
207
|
+
keys: ReadonlyArray<EventSequenceNumber.Client.Composite>,
|
|
208
|
+
): ReadonlyArray<ReadonlyArray<EventSequenceNumber.Client.Composite>> =>
|
|
209
|
+
ReadonlyArray.chunksOf(KEY_CHUNK_SIZE)(keys).map((chunk) =>
|
|
210
|
+
chunk.length === KEY_CHUNK_SIZE
|
|
211
|
+
? chunk
|
|
212
|
+
: [...chunk, ...Array.from({ length: KEY_CHUNK_SIZE - chunk.length }, () => chunk.at(-1)!)],
|
|
213
|
+
)
|
package/src/StateHead.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { Context, Effect, Layer } from '@livestore/utils/effect'
|
|
2
2
|
|
|
3
|
-
import type {
|
|
3
|
+
import type { SqliteError } from './adapter-types.ts'
|
|
4
4
|
import { execSql, selectSql } from './leader-thread/connection.ts'
|
|
5
5
|
import * as EventSequenceNumber from './schema/EventSequenceNumber/mod.ts'
|
|
6
6
|
import { SystemTables } from './schema/mod.ts'
|
|
7
7
|
import { findManyRows, insertRow } from './sql-queries/index.ts'
|
|
8
|
+
import * as StateSqliteDb from './StateSqliteDb.ts'
|
|
8
9
|
|
|
9
10
|
export const TypeId = '~@livestore/common/StateHead' as const
|
|
10
11
|
export type TypeId = typeof TypeId
|
|
@@ -24,11 +25,9 @@ export interface Service {
|
|
|
24
25
|
|
|
25
26
|
export class StateHead extends Context.Service<StateHead, Service>()('@livestore/common/StateHead') {}
|
|
26
27
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
28
|
+
export const make = Effect.gen(function* () {
|
|
29
|
+
const dbState = yield* StateSqliteDb.StateSqliteDb
|
|
30
30
|
|
|
31
|
-
export const make = ({ dbState }: Options) => {
|
|
32
31
|
return StateHead.of({
|
|
33
32
|
[TypeId]: TypeId,
|
|
34
33
|
set: (head) => {
|
|
@@ -66,9 +65,9 @@ export const make = ({ dbState }: Options) => {
|
|
|
66
65
|
)
|
|
67
66
|
}),
|
|
68
67
|
})
|
|
69
|
-
}
|
|
68
|
+
})
|
|
70
69
|
|
|
71
|
-
export const layer =
|
|
70
|
+
export const layer = Layer.effect(StateHead, make)
|
|
72
71
|
|
|
73
72
|
export const layerTest = Layer.succeed(
|
|
74
73
|
StateHead,
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Context, Layer } from '@livestore/utils/effect'
|
|
2
|
+
|
|
3
|
+
import type { SqliteDb } from './sqlite-types.ts'
|
|
4
|
+
|
|
5
|
+
/** The SQLite database containing LiveStore's materialized state. */
|
|
6
|
+
export class StateSqliteDb extends Context.Service<StateSqliteDb, SqliteDb>()('@livestore/common/StateSqliteDb') {}
|
|
7
|
+
|
|
8
|
+
/** Provides a materialized-state database under its role-specific service identity. */
|
|
9
|
+
export const layer = (db: SqliteDb) => Layer.succeed(StateSqliteDb, db)
|
package/src/adapter-types.ts
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
import type { ClientSessionLeaderThreadProxy } from './ClientSessionLeaderThreadProxy.ts'
|
|
13
13
|
import type * as Devtools from './devtools/mod.ts'
|
|
14
14
|
import type { IntentionalShutdownCause, MaterializeError, UnknownError } from './errors.ts'
|
|
15
|
+
import type * as MaterializationJournal from './MaterializationJournal.ts'
|
|
15
16
|
import type { LiveStoreSchema } from './schema/mod.ts'
|
|
16
17
|
import type { SqliteDb } from './sqlite-types.ts'
|
|
17
18
|
import type { BackendIdMismatchError } from './sync/index.ts'
|
|
@@ -35,7 +36,10 @@ export interface ClientSession {
|
|
|
35
36
|
/** Status info whether current session is leader or not */
|
|
36
37
|
lockStatus: SubscriptionRef.SubscriptionRef<LockStatus>
|
|
37
38
|
shutdown: (
|
|
38
|
-
cause: Exit.Exit<
|
|
39
|
+
cause: Exit.Exit<
|
|
40
|
+
IntentionalShutdownCause,
|
|
41
|
+
UnknownError | MaterializeError | MaterializationJournal.MaterializationJournalError | BackendIdMismatchError
|
|
42
|
+
>,
|
|
39
43
|
) => Effect.Effect<void>
|
|
40
44
|
/** A proxy API to communicate with the leader thread */
|
|
41
45
|
leaderThread: ClientSessionLeaderThreadProxy
|
|
@@ -133,7 +137,10 @@ export interface AdapterArgs {
|
|
|
133
137
|
debugInstanceId: string
|
|
134
138
|
bootStatusQueue: Queue.Queue<BootStatus>
|
|
135
139
|
shutdown: (
|
|
136
|
-
exit: Exit.Exit<
|
|
140
|
+
exit: Exit.Exit<
|
|
141
|
+
IntentionalShutdownCause,
|
|
142
|
+
UnknownError | MaterializeError | MaterializationJournal.MaterializationJournalError | BackendIdMismatchError
|
|
143
|
+
>,
|
|
137
144
|
) => Effect.Effect<void>
|
|
138
145
|
connectDevtoolsToStore: ConnectDevtoolsToStore
|
|
139
146
|
/**
|
package/src/index.ts
CHANGED
|
@@ -2,6 +2,7 @@ export * from './adapter-types.ts'
|
|
|
2
2
|
export * from './bounded-collections.ts'
|
|
3
3
|
export * from './debug-info.ts'
|
|
4
4
|
export * as Devtools from './devtools/mod.ts'
|
|
5
|
+
export * as EventlogSqliteDb from './EventlogSqliteDb.ts'
|
|
5
6
|
export * from './leader-thread/RejectedPushError.ts'
|
|
6
7
|
export * as LogConfig from './logging.ts'
|
|
7
8
|
export * from './make-client-session.ts'
|
|
@@ -18,6 +19,7 @@ export {
|
|
|
18
19
|
type BindableWithSessionIdSymbol,
|
|
19
20
|
} from './session-id-symbol.ts'
|
|
20
21
|
export * as SqliteDbHelper from './sqlite-db-helper.ts'
|
|
22
|
+
export * as StateSqliteDb from './StateSqliteDb.ts'
|
|
21
23
|
export * as StateHead from './StateHead.ts'
|
|
22
24
|
export * from './sync/index.ts'
|
|
23
25
|
export * as SyncState from './sync/syncstate.ts'
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { Schema } from '@livestore/utils/effect'
|
|
2
|
+
import { Context, Effect, Option } from '@livestore/utils/effect'
|
|
3
|
+
|
|
4
|
+
import { MaterializeError, SqliteError, type SqliteDb } from '../adapter-types.ts'
|
|
5
|
+
import * as EventlogSqliteDb from '../EventlogSqliteDb.ts'
|
|
6
|
+
import * as MaterializationJournal from '../MaterializationJournal.ts'
|
|
7
|
+
import { EventSequenceNumber, LiveStoreEvent } from '../schema/mod.ts'
|
|
8
|
+
import * as StateHead from '../StateHead.ts'
|
|
9
|
+
import * as StateSqliteDb from '../StateSqliteDb.ts'
|
|
10
|
+
import * as Eventlog from './eventlog.ts'
|
|
11
|
+
import type { MaterializeEvent } from './types.ts'
|
|
12
|
+
|
|
13
|
+
export const TypeId = '~@livestore/common/LeaderPersistence' as const
|
|
14
|
+
export type TypeId = typeof TypeId
|
|
15
|
+
|
|
16
|
+
export interface LocalPersistPlan {
|
|
17
|
+
readonly events: ReadonlyArray<LiveStoreEvent.Client.Encoded>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface PulledEvent {
|
|
21
|
+
readonly event: LiveStoreEvent.Client.Encoded
|
|
22
|
+
readonly syncMetadata: Option.Option<Schema.Json>
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface UpstreamPersistPlan {
|
|
26
|
+
/** The events received in the backend chunk, including metadata used to confirm pending events. */
|
|
27
|
+
readonly pulledEvents: ReadonlyArray<PulledEvent>
|
|
28
|
+
/** The merged events to materialize, including any locally rebased pending suffix. */
|
|
29
|
+
readonly events: ReadonlyArray<LiveStoreEvent.Client.Encoded>
|
|
30
|
+
readonly rollbackEvents: ReadonlyArray<LiveStoreEvent.Client.Encoded>
|
|
31
|
+
readonly confirmedEvents: ReadonlyArray<LiveStoreEvent.Client.Encoded>
|
|
32
|
+
readonly backendHead: EventSequenceNumber.Client.Composite
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface LocalPersistReceipt {
|
|
36
|
+
readonly _tag: 'local-persist'
|
|
37
|
+
readonly persistedEvents: ReadonlyArray<LiveStoreEvent.Client.Encoded>
|
|
38
|
+
readonly materializerHashes: ReadonlyArray<LiveStoreEvent.Client.MaterializerHash>
|
|
39
|
+
readonly stateHead: EventSequenceNumber.Client.Composite
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface UpstreamPersistReceipt {
|
|
43
|
+
readonly _tag: 'upstream-persist'
|
|
44
|
+
readonly persistedEvents: ReadonlyArray<LiveStoreEvent.Client.Encoded>
|
|
45
|
+
readonly materializerHashes: ReadonlyArray<LiveStoreEvent.Client.MaterializerHash>
|
|
46
|
+
readonly rolledBackEventNums: ReadonlyArray<EventSequenceNumber.Client.Composite>
|
|
47
|
+
readonly stateHead: EventSequenceNumber.Client.Composite
|
|
48
|
+
readonly backendHead: EventSequenceNumber.Client.Composite
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type PersistError = MaterializeError | MaterializationJournal.MaterializationJournalError
|
|
52
|
+
|
|
53
|
+
export interface Service {
|
|
54
|
+
readonly [TypeId]: TypeId
|
|
55
|
+
readonly persistLocal: (plan: LocalPersistPlan) => Effect.Effect<LocalPersistReceipt, PersistError>
|
|
56
|
+
readonly persistUpstream: (plan: UpstreamPersistPlan) => Effect.Effect<UpstreamPersistReceipt, PersistError>
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Durable SQLite boundary for leader-sync transitions: rollback, materialization, journal maintenance, eventlog writes
|
|
61
|
+
* and head updates. Queues, retries, publication and acknowledgements stay in `LeaderSyncProcessor`, which publishes
|
|
62
|
+
* only what a successful receipt reports.
|
|
63
|
+
*/
|
|
64
|
+
export class LeaderPersistence extends Context.Service<LeaderPersistence, Service>()(
|
|
65
|
+
'@livestore/common/LeaderPersistence',
|
|
66
|
+
) {}
|
|
67
|
+
|
|
68
|
+
export const make = ({ materializeEvent }: { materializeEvent: MaterializeEvent }) =>
|
|
69
|
+
Effect.gen(function* () {
|
|
70
|
+
const dbState = yield* StateSqliteDb.StateSqliteDb
|
|
71
|
+
const dbEventlog = yield* EventlogSqliteDb.EventlogSqliteDb
|
|
72
|
+
const materializationJournal = yield* MaterializationJournal.MaterializationJournal
|
|
73
|
+
const stateHead = yield* StateHead.StateHead
|
|
74
|
+
|
|
75
|
+
const materializeEvents = (
|
|
76
|
+
events: ReadonlyArray<LiveStoreEvent.Client.Encoded>,
|
|
77
|
+
pulledEvents: ReadonlyArray<PulledEvent> = [],
|
|
78
|
+
) =>
|
|
79
|
+
Effect.forEach(events, (event) =>
|
|
80
|
+
Effect.gen(function* () {
|
|
81
|
+
const syncMetadata =
|
|
82
|
+
pulledEvents.find(({ event: pulledEvent }) =>
|
|
83
|
+
EventSequenceNumber.Client.isEqual(event.seqNum, pulledEvent.seqNum),
|
|
84
|
+
)?.syncMetadata ?? Option.none()
|
|
85
|
+
const { hash } = yield* materializeEvent(event, { syncMetadata })
|
|
86
|
+
return LiveStoreEvent.Client.MaterializerHash.make({ eventNum: event.seqNum, hash })
|
|
87
|
+
}),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
const persistLocal: Service['persistLocal'] = ({ events }) =>
|
|
91
|
+
withCoordinatedTransactions(
|
|
92
|
+
{ dbState, dbEventlog },
|
|
93
|
+
Effect.gen(function* () {
|
|
94
|
+
const materializerHashes = yield* materializeEvents(events)
|
|
95
|
+
const persistedStateHead = yield* stateHead.get.pipe(
|
|
96
|
+
Effect.mapError((cause) => MaterializeError.make({ cause })),
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
_tag: 'local-persist' as const,
|
|
101
|
+
persistedEvents: events,
|
|
102
|
+
materializerHashes,
|
|
103
|
+
stateHead: persistedStateHead,
|
|
104
|
+
}
|
|
105
|
+
}),
|
|
106
|
+
).pipe(
|
|
107
|
+
Effect.withSpan('@livestore/common:LeaderPersistence:persistLocal', {
|
|
108
|
+
attributes: { batchSize: events.length },
|
|
109
|
+
}),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
const persistUpstream: Service['persistUpstream'] = (plan) =>
|
|
113
|
+
withCoordinatedTransactions(
|
|
114
|
+
{ dbState, dbEventlog },
|
|
115
|
+
Effect.gen(function* () {
|
|
116
|
+
const rollbackEventNums = plan.rollbackEvents.map((event) => event.seqNum)
|
|
117
|
+
|
|
118
|
+
if (rollbackEventNums.length > 0) {
|
|
119
|
+
// A rebase first restores the old materialized state, then removes the events that no longer belong
|
|
120
|
+
// in the eventlog. The replacement events can then be applied from the restored head.
|
|
121
|
+
const headAfterRollback = plan.rollbackEvents[0]!.parentSeqNum
|
|
122
|
+
yield* materializationJournal.rollback(rollbackEventNums)
|
|
123
|
+
yield* stateHead.set(headAfterRollback).pipe(Effect.mapError((cause) => MaterializeError.make({ cause })))
|
|
124
|
+
yield* Eventlog.deleteEvents(dbEventlog, rollbackEventNums).pipe(
|
|
125
|
+
Effect.mapError((cause) => MaterializeError.make({ cause })),
|
|
126
|
+
)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const materializerHashes = yield* materializeEvents(plan.events, plan.pulledEvents)
|
|
130
|
+
|
|
131
|
+
if (plan.confirmedEvents.length > 0) {
|
|
132
|
+
// Confirmed local events are already materialized. We only add the metadata learned from the backend.
|
|
133
|
+
const confirmedPulledEvents = plan.pulledEvents.filter(({ event }) =>
|
|
134
|
+
plan.confirmedEvents.some((confirmedEvent) =>
|
|
135
|
+
isSameSequencePosition(event.seqNum, confirmedEvent.seqNum),
|
|
136
|
+
),
|
|
137
|
+
)
|
|
138
|
+
yield* Eventlog.updateSyncMetadataForDb(dbEventlog, confirmedPulledEvents).pipe(
|
|
139
|
+
Effect.mapError((cause) => MaterializeError.make({ cause })),
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Once the backend has reached this head, journal entries before it are no longer needed for a future rebase.
|
|
144
|
+
yield* materializationJournal.discardUpTo(plan.backendHead)
|
|
145
|
+
|
|
146
|
+
// The backend head and the corresponding event inserts share this eventlog transaction.
|
|
147
|
+
yield* updateBackendHead(dbEventlog, plan.backendHead)
|
|
148
|
+
|
|
149
|
+
const persistedStateHead = yield* stateHead.get.pipe(
|
|
150
|
+
Effect.mapError((cause) => MaterializeError.make({ cause })),
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
_tag: 'upstream-persist' as const,
|
|
155
|
+
persistedEvents: plan.events,
|
|
156
|
+
materializerHashes,
|
|
157
|
+
rolledBackEventNums: rollbackEventNums,
|
|
158
|
+
stateHead: persistedStateHead,
|
|
159
|
+
backendHead: plan.backendHead,
|
|
160
|
+
}
|
|
161
|
+
}),
|
|
162
|
+
).pipe(
|
|
163
|
+
Effect.withSpan('@livestore/common:LeaderPersistence:persistUpstream', {
|
|
164
|
+
attributes: {
|
|
165
|
+
batchSize: plan.events.length,
|
|
166
|
+
rollbackCount: plan.rollbackEvents.length,
|
|
167
|
+
confirmedCount: plan.confirmedEvents.length,
|
|
168
|
+
},
|
|
169
|
+
}),
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
return LeaderPersistence.of({ [TypeId]: TypeId, persistLocal, persistUpstream })
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Parent linkage identifies a position in the event chain. Rebase generation describes the version of optimistic
|
|
177
|
+
* history, which the backend does not preserve, so it is not part of position identity.
|
|
178
|
+
*/
|
|
179
|
+
export const isSameSequencePosition = (
|
|
180
|
+
left: EventSequenceNumber.Client.Composite,
|
|
181
|
+
right: EventSequenceNumber.Client.Composite,
|
|
182
|
+
) => left.global === right.global && left.client === right.client
|
|
183
|
+
|
|
184
|
+
const withCoordinatedTransactions = <A, E, R>(
|
|
185
|
+
{ dbState, dbEventlog }: { dbState: SqliteDb; dbEventlog: SqliteDb },
|
|
186
|
+
effect: Effect.Effect<A, E, R>,
|
|
187
|
+
): Effect.Effect<A, E | MaterializeError, R> => {
|
|
188
|
+
// These flags let cleanup roll back whichever transaction was actually opened or left behind by a failed commit.
|
|
189
|
+
let stateTransactionOpen = false
|
|
190
|
+
let eventlogTransactionOpen = false
|
|
191
|
+
|
|
192
|
+
const rollbackOpenTransactions = Effect.gen(function* () {
|
|
193
|
+
if (eventlogTransactionOpen === true) {
|
|
194
|
+
yield* executeTransactionStatement(dbEventlog, 'ROLLBACK').pipe(Effect.ignore)
|
|
195
|
+
eventlogTransactionOpen = false
|
|
196
|
+
}
|
|
197
|
+
if (stateTransactionOpen === true) {
|
|
198
|
+
yield* executeTransactionStatement(dbState, 'ROLLBACK').pipe(Effect.ignore)
|
|
199
|
+
stateTransactionOpen = false
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
return Effect.gen(function* () {
|
|
204
|
+
yield* executeTransactionStatement(dbState, 'BEGIN TRANSACTION')
|
|
205
|
+
stateTransactionOpen = true
|
|
206
|
+
yield* executeTransactionStatement(dbEventlog, 'BEGIN TRANSACTION')
|
|
207
|
+
eventlogTransactionOpen = true
|
|
208
|
+
|
|
209
|
+
const result = yield* effect
|
|
210
|
+
|
|
211
|
+
// SQLite cannot atomically commit independent databases. Commit state first so a failed state
|
|
212
|
+
// commit never publishes an eventlog head that claims the state transition is durable.
|
|
213
|
+
yield* executeTransactionStatement(dbState, 'COMMIT')
|
|
214
|
+
stateTransactionOpen = false
|
|
215
|
+
yield* executeTransactionStatement(dbEventlog, 'COMMIT')
|
|
216
|
+
eventlogTransactionOpen = false
|
|
217
|
+
|
|
218
|
+
return result
|
|
219
|
+
}).pipe(
|
|
220
|
+
Effect.ensuring(rollbackOpenTransactions),
|
|
221
|
+
// Do not allow cancellation between the two commits and the cleanup that follows a failure.
|
|
222
|
+
Effect.uninterruptible,
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const executeTransactionStatement = (db: SqliteDb, statement: 'BEGIN TRANSACTION' | 'COMMIT' | 'ROLLBACK') =>
|
|
227
|
+
Effect.try({
|
|
228
|
+
try: () => db.execute(statement),
|
|
229
|
+
catch: (cause) =>
|
|
230
|
+
MaterializeError.make({
|
|
231
|
+
cause: new SqliteError({ cause, query: { sql: statement, bindValues: [] } }),
|
|
232
|
+
note: `Leader sync transaction failed during ${statement}`,
|
|
233
|
+
}),
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
const updateBackendHead = (dbEventlog: SqliteDb, head: EventSequenceNumber.Client.Composite) =>
|
|
237
|
+
Effect.try({
|
|
238
|
+
try: () => Eventlog.updateBackendHead(dbEventlog, head),
|
|
239
|
+
catch: (cause) =>
|
|
240
|
+
MaterializeError.make({
|
|
241
|
+
cause: new SqliteError({ cause }),
|
|
242
|
+
note: 'Failed to persist the leader sync backend head',
|
|
243
|
+
}),
|
|
244
|
+
})
|