@systemfsoftware/agent-storage-postgres 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/PostgresStorage-D9IqvmQ2.mjs +1860 -0
- package/dist/PostgresStorage-D9IqvmQ2.mjs.map +1 -0
- package/dist/PostgresStorage-zKTn_ufd.d.mts +63 -0
- package/dist/PostgresStorage.d.mts +2 -0
- package/dist/PostgresStorage.mjs +2 -0
- package/dist/PostgresStorageError-DCuaf7EF.mjs +50 -0
- package/dist/PostgresStorageError-DCuaf7EF.mjs.map +1 -0
- package/dist/PostgresStorageError-mnbXuBHP.d.mts +48 -0
- package/dist/PostgresStorageError.d.mts +2 -0
- package/dist/PostgresStorageError.mjs +1 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +3 -0
- package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
- package/package.json +57 -3
- package/src/PostgresStorage.ts +339 -0
- package/src/PostgresStorageError.ts +69 -0
- package/src/index.ts +2 -0
- package/src/internal/layout-expression.ts +209 -0
- package/src/internal/postgres-storage.ts +144 -0
- package/src/internal/storage-layout.ts +1591 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@systemfsoftware/agent-storage-postgres",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Postgres persistence adapters for the Effect Agent durable runtime.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/systemfsoftware/agent.git",
|
|
9
|
+
"directory": "packages/storage-postgres"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": [],
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.mts",
|
|
20
|
+
"default": "./dist/index.mjs"
|
|
21
|
+
},
|
|
22
|
+
"./postgres-storage": {
|
|
23
|
+
"types": "./dist/PostgresStorage.d.mts",
|
|
24
|
+
"default": "./dist/PostgresStorage.mjs"
|
|
25
|
+
},
|
|
26
|
+
"./postgres-storage-error": {
|
|
27
|
+
"types": "./dist/PostgresStorageError.d.mts",
|
|
28
|
+
"default": "./dist/PostgresStorageError.mjs"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public",
|
|
33
|
+
"provenance": true
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"@systemfsoftware/agent": "0.1.0",
|
|
37
|
+
"@systemfsoftware/agent-storage-sql": "0.1.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
41
|
+
"@effect/platform-node": "4.1.5",
|
|
42
|
+
"@effect/sql-pg": "4.1.5",
|
|
43
|
+
"@effect/vitest": "4.1.5",
|
|
44
|
+
"@systemfsoftware/effect-microsandbox": "^6.1.0",
|
|
45
|
+
"@systemfsoftware/effect-readiness": "^1.1.4",
|
|
46
|
+
"effect": "4.1.5",
|
|
47
|
+
"tsdown": "^0.23.0",
|
|
48
|
+
"typescript": "7.0.2",
|
|
49
|
+
"vitest": "5.0.3"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"effect": "^4.1.0"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "tsdown",
|
|
56
|
+
"typecheck": "tsc -b",
|
|
57
|
+
"test": "vitest run --passWithNoTests",
|
|
58
|
+
"check:pack": "pnpm pack --pack-destination .pack && attw .pack/*.tgz --profile esm-only; s=$?; rm -rf .pack; exit $s"
|
|
59
|
+
}
|
|
6
60
|
}
|
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
import { makeSqlActivityStore } from '@systemfsoftware/agent-storage-sql/sql-activity-store'
|
|
2
|
+
import { sqlStorageOwner } from '@systemfsoftware/agent-storage-sql/sql-journal'
|
|
3
|
+
import {
|
|
4
|
+
makeSqlMessageDeliveryStore,
|
|
5
|
+
registerCanonicalMessageWriter,
|
|
6
|
+
} from '@systemfsoftware/agent-storage-sql/sql-message-delivery-store'
|
|
7
|
+
import {
|
|
8
|
+
makeSqlScheduleStore,
|
|
9
|
+
SqlScheduleWriteTransaction,
|
|
10
|
+
} from '@systemfsoftware/agent-storage-sql/sql-schedule-store'
|
|
11
|
+
import { makeSqlTransaction } from '@systemfsoftware/agent-storage-sql/sql-storage'
|
|
12
|
+
import { makeSqlSubmissionLedgerKernel } from '@systemfsoftware/agent-storage-sql/sql-submission-ledger'
|
|
13
|
+
import { makeSqlSubscriptionStore } from '@systemfsoftware/agent-storage-sql/sql-subscription-store'
|
|
14
|
+
import { makeSqlThreadImport } from '@systemfsoftware/agent-storage-sql/sql-thread-import'
|
|
15
|
+
import { makeSqlThreadStoreKernel } from '@systemfsoftware/agent-storage-sql/sql-thread-store'
|
|
16
|
+
import {
|
|
17
|
+
ActivityMutationFailpoint,
|
|
18
|
+
ActivityProcessorStore,
|
|
19
|
+
ActivityStoreError,
|
|
20
|
+
} from '@systemfsoftware/agent/activity-store'
|
|
21
|
+
import { MessageDeliveryStore, type MessageDeliveryStoreLimits } from '@systemfsoftware/agent/message-delivery'
|
|
22
|
+
import { StorageOwner } from '@systemfsoftware/agent/run-storage'
|
|
23
|
+
import { ScheduleStore } from '@systemfsoftware/agent/schedule'
|
|
24
|
+
import { SettlementPublisher } from '@systemfsoftware/agent/settlement-publisher'
|
|
25
|
+
import { LedgerError, SubmissionLedger } from '@systemfsoftware/agent/submission-ledger'
|
|
26
|
+
import { SourcePartition, SubscriptionError, SubscriptionStore } from '@systemfsoftware/agent/subscription'
|
|
27
|
+
import { ThreadImport } from '@systemfsoftware/agent/thread-import'
|
|
28
|
+
import type { ThreadExportRequest } from '@systemfsoftware/agent/thread-store'
|
|
29
|
+
import { ThreadReader, ThreadStore } from '@systemfsoftware/agent/thread-store'
|
|
30
|
+
import { checkExportSource } from '@systemfsoftware/agent/thread-transfer'
|
|
31
|
+
import * as Context from 'effect/Context'
|
|
32
|
+
import * as Effect from 'effect/Effect'
|
|
33
|
+
import * as Layer from 'effect/Layer'
|
|
34
|
+
import * as Schema from 'effect/Schema'
|
|
35
|
+
import * as SqlClient from 'effect/sql/SqlClient'
|
|
36
|
+
|
|
37
|
+
import {
|
|
38
|
+
classifyWriteFailure,
|
|
39
|
+
ensurePostgresSchema,
|
|
40
|
+
initializePostgresStorage,
|
|
41
|
+
makePostgresJournal,
|
|
42
|
+
makeWriteTransaction,
|
|
43
|
+
postgresStorageErrors,
|
|
44
|
+
readPostgresStorageHeader,
|
|
45
|
+
} from './internal/postgres-storage'
|
|
46
|
+
import {
|
|
47
|
+
PostgresStorageError,
|
|
48
|
+
type PostgresStorageFailpointError,
|
|
49
|
+
type PostgresStorageFailpointLocation,
|
|
50
|
+
} from './PostgresStorageError'
|
|
51
|
+
|
|
52
|
+
export { CurrentPostgresStorageVersion } from './internal/postgres-storage'
|
|
53
|
+
|
|
54
|
+
export type PostgresStorageFailpointHandler = (
|
|
55
|
+
location: PostgresStorageFailpointLocation,
|
|
56
|
+
) => Effect.Effect<void, PostgresStorageFailpointError>
|
|
57
|
+
|
|
58
|
+
const Settings = Schema.Struct({
|
|
59
|
+
observationPollInterval: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
60
|
+
lockTimeout: Schema.Int.check(Schema.isGreaterThan(0)),
|
|
61
|
+
verifyOnOpen: Schema.Boolean,
|
|
62
|
+
schema: Schema.NonEmptyString.check(
|
|
63
|
+
Schema.isMaxLength(63),
|
|
64
|
+
Schema.isPattern(/^[a-z_][a-z0-9_]*$/),
|
|
65
|
+
),
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
export interface PostgresStorageOptions {
|
|
69
|
+
/** Namespace for qualified storage tables, created under the owner gate when absent. Defaults to public. */
|
|
70
|
+
readonly schema?: string | undefined
|
|
71
|
+
/** Journal observation polling interval in milliseconds. Defaults to 25. */
|
|
72
|
+
readonly observationPollInterval?: number | undefined
|
|
73
|
+
/** Positive database lock timeout in milliseconds. Defaults to 5,000. */
|
|
74
|
+
readonly lockTimeout?: number | undefined
|
|
75
|
+
/** Audit stored payloads, identities, and batch coverage on open. Defaults to false. */
|
|
76
|
+
readonly verifyOnOpen?: boolean | undefined
|
|
77
|
+
readonly failpoint?: PostgresStorageFailpointHandler | undefined
|
|
78
|
+
readonly activityFailpoint?: ActivityMutationFailpoint['Service']['hit'] | undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const settings = (options: PostgresStorageOptions) =>
|
|
82
|
+
Schema.decodeEffect(Settings)({
|
|
83
|
+
observationPollInterval: options.observationPollInterval ?? 25,
|
|
84
|
+
lockTimeout: options.lockTimeout ?? 5_000,
|
|
85
|
+
verifyOnOpen: options.verifyOnOpen ?? false,
|
|
86
|
+
schema: options.schema ?? 'public',
|
|
87
|
+
}).pipe(
|
|
88
|
+
Effect.mapError((cause) =>
|
|
89
|
+
PostgresStorageError.make({
|
|
90
|
+
cause,
|
|
91
|
+
operation: 'configure Postgres storage',
|
|
92
|
+
message: cause.message,
|
|
93
|
+
})
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
const initialize = Effect.fnUntraced(function*(options: PostgresStorageOptions) {
|
|
98
|
+
const config = yield* settings(options)
|
|
99
|
+
|
|
100
|
+
yield* initializePostgresStorage(config)
|
|
101
|
+
|
|
102
|
+
return config
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
const openJournal = Effect.fnUntraced(function*(options: PostgresStorageOptions) {
|
|
106
|
+
const config = yield* initialize(options)
|
|
107
|
+
const hitFailpoint: PostgresStorageFailpointHandler = options.failpoint ?? (() => Effect.void)
|
|
108
|
+
const journal = yield* makePostgresJournal(config.lockTimeout, hitFailpoint, config.schema)
|
|
109
|
+
|
|
110
|
+
return { config, journal, hitFailpoint }
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
type Journal = Effect.Success<ReturnType<typeof openJournal>>
|
|
114
|
+
|
|
115
|
+
const makeThreadStore = ({ config, journal, hitFailpoint }: Journal) =>
|
|
116
|
+
makeSqlThreadStoreKernel(journal, {
|
|
117
|
+
...config,
|
|
118
|
+
namespace: config.schema,
|
|
119
|
+
errors: postgresStorageErrors,
|
|
120
|
+
hitFailpoint,
|
|
121
|
+
offsetPrefix: 'effect-agent-postgres@1:',
|
|
122
|
+
}).pipe(Effect.map((services) => ({ ...services, owner: journal.owner })))
|
|
123
|
+
|
|
124
|
+
const makeSubmissionLedger = ({ config, journal, hitFailpoint }: Journal) =>
|
|
125
|
+
makeSqlSubmissionLedgerKernel(journal, {
|
|
126
|
+
namespace: config.schema,
|
|
127
|
+
errors: postgresStorageErrors,
|
|
128
|
+
hitFailpoint,
|
|
129
|
+
offsetPrefix: 'effect-agent-postgres@1:',
|
|
130
|
+
sqlFailure: (operation) => (cause) => {
|
|
131
|
+
const internal = classifyWriteFailure(operation)(cause)
|
|
132
|
+
|
|
133
|
+
return LedgerError.make({ operation, message: internal.message, cause: internal })
|
|
134
|
+
},
|
|
135
|
+
}).pipe(Effect.map((services) => ({ ...services, owner: journal.owner })))
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Thread history and submissions over one scoped owner. The application must route each Thread
|
|
139
|
+
* exclusively to this owner; Postgres does not provide distributed ownership or failover here.
|
|
140
|
+
*/
|
|
141
|
+
export const layerWith = (options: PostgresStorageOptions) =>
|
|
142
|
+
ThreadReader.layer().pipe(
|
|
143
|
+
Layer.provideMerge(
|
|
144
|
+
Layer.effectContext(
|
|
145
|
+
Effect.gen(function*() {
|
|
146
|
+
const journal = yield* openJournal(options)
|
|
147
|
+
const threadStore = yield* makeThreadStore(journal)
|
|
148
|
+
const submissionLedger = yield* makeSubmissionLedger(journal)
|
|
149
|
+
|
|
150
|
+
return Context.make(ThreadStore, threadStore.store).pipe(
|
|
151
|
+
Context.add(ThreadImport, threadStore.importer),
|
|
152
|
+
Context.add(SubmissionLedger, submissionLedger.ledger),
|
|
153
|
+
Context.add(SettlementPublisher, submissionLedger.publisher),
|
|
154
|
+
Context.add(StorageOwner, journal.journal.owner),
|
|
155
|
+
)
|
|
156
|
+
}),
|
|
157
|
+
),
|
|
158
|
+
),
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Thread history and submissions with default settings. Requires SqlClient, Digest, and SecureRandom.
|
|
163
|
+
* SQL text parameters, including identities, must exclude NUL and unpaired UTF-16
|
|
164
|
+
* surrogates. Canonical JSON payload strings remain intact through escaped encoding.
|
|
165
|
+
*/
|
|
166
|
+
export const layer = layerWith({})
|
|
167
|
+
|
|
168
|
+
/** Standalone thread history over the application's SqlClient and Digest. */
|
|
169
|
+
export const threadStoreLayer = (options: PostgresStorageOptions = {}) =>
|
|
170
|
+
ThreadReader.layer().pipe(
|
|
171
|
+
Layer.provideMerge(
|
|
172
|
+
Layer.effectContext(
|
|
173
|
+
Effect.flatMap(openJournal(options), makeThreadStore).pipe(
|
|
174
|
+
Effect.map(({ store, importer, owner }) =>
|
|
175
|
+
Context.make(ThreadStore, store).pipe(
|
|
176
|
+
Context.add(ThreadImport, importer),
|
|
177
|
+
Context.add(StorageOwner, owner),
|
|
178
|
+
)
|
|
179
|
+
),
|
|
180
|
+
),
|
|
181
|
+
),
|
|
182
|
+
),
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
/** Export a quiesced current-layout store through a read-only snapshot; never run DDL. */
|
|
186
|
+
export const exportThread = Effect.fn('PostgresStorage.exportThread')(function*(
|
|
187
|
+
request: ThreadExportRequest,
|
|
188
|
+
options: PostgresStorageOptions = {},
|
|
189
|
+
) {
|
|
190
|
+
yield* checkExportSource(request.threadId)
|
|
191
|
+
const config = yield* settings(options)
|
|
192
|
+
const sql = yield* SqlClient.SqlClient
|
|
193
|
+
|
|
194
|
+
return yield* Effect.scoped(
|
|
195
|
+
Effect.gen(function*() {
|
|
196
|
+
const owner = yield* sqlStorageOwner(sql, config.schema)
|
|
197
|
+
|
|
198
|
+
return yield* owner.withMutation(
|
|
199
|
+
makeSqlTransaction(sql, {
|
|
200
|
+
begin: 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY',
|
|
201
|
+
})(
|
|
202
|
+
Effect.gen(function*() {
|
|
203
|
+
yield* readPostgresStorageHeader(config.schema)
|
|
204
|
+
|
|
205
|
+
const transfer = yield* makeSqlThreadImport({
|
|
206
|
+
owner,
|
|
207
|
+
namespace: config.schema,
|
|
208
|
+
offsetPrefix: 'effect-agent-postgres@1:',
|
|
209
|
+
read: (body) => body,
|
|
210
|
+
write: () => Effect.die('A read-only exporter cannot import'),
|
|
211
|
+
})
|
|
212
|
+
|
|
213
|
+
return yield* transfer.export(request)
|
|
214
|
+
}),
|
|
215
|
+
).pipe(
|
|
216
|
+
Effect.catchTag('SqlError', (cause) =>
|
|
217
|
+
PostgresStorageError.make({
|
|
218
|
+
operation: 'export Thread snapshot',
|
|
219
|
+
message: cause.message,
|
|
220
|
+
cause,
|
|
221
|
+
})),
|
|
222
|
+
),
|
|
223
|
+
)
|
|
224
|
+
}),
|
|
225
|
+
)
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
/** Submissions and canonical settlement publication over the application's SqlClient, Digest, and SecureRandom. */
|
|
229
|
+
export const submissionLedgerLayer = (options: PostgresStorageOptions = {}) =>
|
|
230
|
+
Layer.effectContext(
|
|
231
|
+
Effect.flatMap(openJournal(options), makeSubmissionLedger).pipe(
|
|
232
|
+
Effect.map((services) =>
|
|
233
|
+
Context.make(SubmissionLedger, services.ledger).pipe(
|
|
234
|
+
Context.add(SettlementPublisher, services.publisher),
|
|
235
|
+
Context.add(StorageOwner, services.owner),
|
|
236
|
+
)
|
|
237
|
+
),
|
|
238
|
+
),
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
/** Schedules over the application's SqlClient. */
|
|
242
|
+
export const scheduleStoreLayer = (options: PostgresStorageOptions = {}) =>
|
|
243
|
+
Layer.unwrap(
|
|
244
|
+
Effect.gen(function*() {
|
|
245
|
+
const sql = yield* SqlClient.SqlClient
|
|
246
|
+
const config = yield* initialize(options)
|
|
247
|
+
const run = yield* makeWriteTransaction(sql, config.lockTimeout, config.schema)
|
|
248
|
+
|
|
249
|
+
return Layer.effect(ScheduleStore, makeSqlScheduleStore(config.schema)).pipe(
|
|
250
|
+
Layer.provide(Layer.succeed(SqlScheduleWriteTransaction, { run })),
|
|
251
|
+
)
|
|
252
|
+
}),
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
/** Message delivery over the application's SqlClient and Digest, with optional live capacity and payload limits. */
|
|
256
|
+
export const messageDeliveryStoreLayer = (
|
|
257
|
+
options: PostgresStorageOptions & {
|
|
258
|
+
readonly limits?: MessageDeliveryStoreLimits | undefined
|
|
259
|
+
} = {},
|
|
260
|
+
) =>
|
|
261
|
+
Layer.effect(
|
|
262
|
+
MessageDeliveryStore,
|
|
263
|
+
Effect.gen(function*() {
|
|
264
|
+
const sql = yield* SqlClient.SqlClient
|
|
265
|
+
const config = yield* initialize(options)
|
|
266
|
+
|
|
267
|
+
const owner = yield* sqlStorageOwner(sql, config.schema)
|
|
268
|
+
|
|
269
|
+
const store = yield* makeSqlMessageDeliveryStore(owner, options.limits, {
|
|
270
|
+
namespace: config.schema,
|
|
271
|
+
transaction: yield* makeWriteTransaction(sql, config.lockTimeout, config.schema),
|
|
272
|
+
})
|
|
273
|
+
|
|
274
|
+
yield* registerCanonicalMessageWriter(owner, store)
|
|
275
|
+
|
|
276
|
+
return store
|
|
277
|
+
}),
|
|
278
|
+
)
|
|
279
|
+
|
|
280
|
+
/** Subscriptions owned by an explicit partition. Invalid partitions fail before accessing SQL. */
|
|
281
|
+
export const subscriptionStoreLayer = (
|
|
282
|
+
owned: SourcePartition,
|
|
283
|
+
options: PostgresStorageOptions = {},
|
|
284
|
+
) =>
|
|
285
|
+
Layer.effect(
|
|
286
|
+
SubscriptionStore,
|
|
287
|
+
Effect.gen(function*() {
|
|
288
|
+
const partition = yield* Schema.decodeEffect(SourcePartition)(owned).pipe(
|
|
289
|
+
Effect.mapError(() => SubscriptionError.make({ reason: 'validation', code: 'partition' })),
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
const config = yield* initialize(options)
|
|
293
|
+
const sql = yield* SqlClient.SqlClient
|
|
294
|
+
const transaction = yield* makeWriteTransaction(sql, config.lockTimeout, config.schema)
|
|
295
|
+
|
|
296
|
+
// Retention DDL must share the owner gate with format initialization.
|
|
297
|
+
return yield* transaction(
|
|
298
|
+
makeSqlSubscriptionStore(partition, {
|
|
299
|
+
namespace: config.schema,
|
|
300
|
+
transaction,
|
|
301
|
+
maxStoredJsonLength: 16 * 1024 * 1024,
|
|
302
|
+
}),
|
|
303
|
+
).pipe(
|
|
304
|
+
Effect.catchTag('SqlError', () => SubscriptionError.make({ reason: 'storage', code: 'initialize' })),
|
|
305
|
+
)
|
|
306
|
+
}),
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Independent activity progress over one shared SqlClient; does not initialize the Thread journal.
|
|
311
|
+
* Route each activity key to one process. Sessions are local and close with their owning Scope.
|
|
312
|
+
*/
|
|
313
|
+
export const activityStoreLayer = (options: PostgresStorageOptions = {}) =>
|
|
314
|
+
Layer.effect(
|
|
315
|
+
ActivityProcessorStore,
|
|
316
|
+
Effect.gen(function*() {
|
|
317
|
+
const sql = yield* SqlClient.SqlClient
|
|
318
|
+
const config = yield* settings(options)
|
|
319
|
+
|
|
320
|
+
return yield* makeSqlActivityStore(
|
|
321
|
+
yield* makeWriteTransaction(sql, config.lockTimeout, config.schema),
|
|
322
|
+
ensurePostgresSchema(config.schema).pipe(
|
|
323
|
+
Effect.mapError(() =>
|
|
324
|
+
ActivityStoreError.make({
|
|
325
|
+
operation: 'initialize activity schema',
|
|
326
|
+
reason: 'unavailable',
|
|
327
|
+
})
|
|
328
|
+
),
|
|
329
|
+
),
|
|
330
|
+
config.schema,
|
|
331
|
+
)
|
|
332
|
+
}),
|
|
333
|
+
).pipe(
|
|
334
|
+
Layer.provide(
|
|
335
|
+
options.activityFailpoint === undefined
|
|
336
|
+
? ActivityMutationFailpoint.layer
|
|
337
|
+
: Layer.succeed(ActivityMutationFailpoint)({ hit: options.activityFailpoint }),
|
|
338
|
+
),
|
|
339
|
+
)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { SqlStorageFailpointLocation } from '@systemfsoftware/agent-storage-sql/sql-storage-failpoint'
|
|
2
|
+
import * as Schema from 'effect/Schema'
|
|
3
|
+
|
|
4
|
+
/** The database uses an unsupported or inconsistent storage layout or record format. */
|
|
5
|
+
export class PostgresStorageCompatibilityError extends Schema.TaggedError<PostgresStorageCompatibilityError>()(
|
|
6
|
+
'PostgresStorageCompatibilityError',
|
|
7
|
+
{
|
|
8
|
+
actualVersion: Schema.Int,
|
|
9
|
+
message: Schema.String,
|
|
10
|
+
supportedVersion: Schema.Int,
|
|
11
|
+
},
|
|
12
|
+
) {}
|
|
13
|
+
|
|
14
|
+
/** Stored bytes failed the current Schema and cannot be used as recovery truth. */
|
|
15
|
+
export class PostgresStorageCorruptionError extends Schema.TaggedError<PostgresStorageCorruptionError>()(
|
|
16
|
+
'PostgresStorageCorruptionError',
|
|
17
|
+
{
|
|
18
|
+
message: Schema.String,
|
|
19
|
+
rowKey: Schema.String,
|
|
20
|
+
table: Schema.String,
|
|
21
|
+
},
|
|
22
|
+
) {}
|
|
23
|
+
|
|
24
|
+
/** Postgres infrastructure failed while opening or operating the store. */
|
|
25
|
+
export class PostgresStorageError extends Schema.TaggedError<PostgresStorageError>()(
|
|
26
|
+
'PostgresStorageError',
|
|
27
|
+
{
|
|
28
|
+
cause: Schema.optionalKey(Schema.Defect()),
|
|
29
|
+
message: Schema.String,
|
|
30
|
+
operation: Schema.String,
|
|
31
|
+
},
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* A write transaction lost a concurrency race and was rolled back by Postgres: a
|
|
36
|
+
* serialization failure (40001), a deadlock (40P01), or a lock timeout (55P03). The
|
|
37
|
+
* transaction mutated no canonical state and is safe to retry.
|
|
38
|
+
*/
|
|
39
|
+
export class PostgresWriteContention extends Schema.TaggedError<PostgresWriteContention>()(
|
|
40
|
+
'PostgresWriteContention',
|
|
41
|
+
{
|
|
42
|
+
cause: Schema.optionalKey(Schema.Defect()),
|
|
43
|
+
message: Schema.String,
|
|
44
|
+
operation: Schema.String,
|
|
45
|
+
},
|
|
46
|
+
) {}
|
|
47
|
+
|
|
48
|
+
export const PostgresStorageFailpointLocation = SqlStorageFailpointLocation
|
|
49
|
+
|
|
50
|
+
export type PostgresStorageFailpointLocation = typeof PostgresStorageFailpointLocation.Type
|
|
51
|
+
|
|
52
|
+
/** Deterministic test-only fault or pause injected at a Postgres operation boundary. */
|
|
53
|
+
export class PostgresStorageFailpointError extends Schema.TaggedError<PostgresStorageFailpointError>()(
|
|
54
|
+
'PostgresStorageFailpointError',
|
|
55
|
+
{
|
|
56
|
+
location: PostgresStorageFailpointLocation,
|
|
57
|
+
},
|
|
58
|
+
) {
|
|
59
|
+
override get message() {
|
|
60
|
+
return `Injected Postgres storage failure at ${this.location}.`
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Every way opening Postgres storage can fail before it serves a request. */
|
|
65
|
+
export type PostgresStorageInitializationError =
|
|
66
|
+
| PostgresStorageCompatibilityError
|
|
67
|
+
| PostgresStorageCorruptionError
|
|
68
|
+
| PostgresStorageError
|
|
69
|
+
| PostgresWriteContention
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/** Closed expression vocabulary for the frozen Postgres layout. */
|
|
2
|
+
export type LayoutExpression =
|
|
3
|
+
| readonly ['column' | 'text' | 'json' | 'length', string]
|
|
4
|
+
| readonly ['integer', number]
|
|
5
|
+
| readonly ['notNull' | 'null', LayoutExpression]
|
|
6
|
+
| readonly [
|
|
7
|
+
'eq' | 'ne' | 'gt' | 'ge' | 'lt' | 'le' | 'subtract' | 'shift',
|
|
8
|
+
LayoutExpression,
|
|
9
|
+
LayoutExpression,
|
|
10
|
+
]
|
|
11
|
+
| readonly ['in' | 'notIn', LayoutExpression, ReadonlyArray<string | number>]
|
|
12
|
+
| readonly ['and', ReadonlyArray<LayoutExpression>]
|
|
13
|
+
|
|
14
|
+
/** Decode deparser syntax into meaning; unknown tokens/forms fail closed. Never execute it. */
|
|
15
|
+
const readExpressions = (input: string): ReadonlyArray<LayoutExpression> | undefined => {
|
|
16
|
+
if (input.length > 16_384) return undefined
|
|
17
|
+
const tokens: Array<{ kind: string; value: string }> = []
|
|
18
|
+
|
|
19
|
+
const token =
|
|
20
|
+
/\s+|"(?:[^"]|"")*"|'(?:[^']|'')*'|->>|>>|::|<>|[a-z_][a-z_0-9]*|(?:256|[0-9]|[1-4][0-9]|5[0-2])(?![0-9])|>=|<=|[=(),[\]>.<-]/giy
|
|
21
|
+
|
|
22
|
+
while (token.lastIndex < input.length) {
|
|
23
|
+
const match = token.exec(input)?.[0]
|
|
24
|
+
|
|
25
|
+
if (match === undefined || tokens.length >= 512) return undefined
|
|
26
|
+
if (/^\s/.test(match)) continue
|
|
27
|
+
const quote = match[0]
|
|
28
|
+
|
|
29
|
+
tokens.push(
|
|
30
|
+
quote === '"' || quote === "'"
|
|
31
|
+
? { kind: quote, value: match.slice(1, -1).replaceAll(quote + quote, quote) }
|
|
32
|
+
: { kind: 'bare', value: match.toLowerCase() },
|
|
33
|
+
)
|
|
34
|
+
}
|
|
35
|
+
let position = 0
|
|
36
|
+
|
|
37
|
+
const take = (value: string) => {
|
|
38
|
+
if (tokens[position]?.kind !== 'bare' || tokens[position]?.value !== value) return false
|
|
39
|
+
position++
|
|
40
|
+
|
|
41
|
+
return true
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const identifier = (): string | undefined => {
|
|
45
|
+
const next = tokens[position]
|
|
46
|
+
|
|
47
|
+
if (next === undefined || next.kind === "'" || !/^[a-z_][a-z_0-9]*$/i.test(next.value)) {
|
|
48
|
+
return undefined
|
|
49
|
+
}
|
|
50
|
+
position++
|
|
51
|
+
if (!take('.')) return next.value
|
|
52
|
+
const member = identifier()
|
|
53
|
+
|
|
54
|
+
return next.value === 'pg_catalog' && member !== undefined ? `pg_catalog.${member}` : undefined
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const operand = (): LayoutExpression | undefined => {
|
|
58
|
+
let value: LayoutExpression | undefined
|
|
59
|
+
const next = tokens[position]
|
|
60
|
+
|
|
61
|
+
if (take('(')) {
|
|
62
|
+
value = expression()
|
|
63
|
+
if (!take(')')) return undefined
|
|
64
|
+
} else if (next?.kind === "'") {
|
|
65
|
+
position++
|
|
66
|
+
value = ['text', next.value]
|
|
67
|
+
if (take('::')) {
|
|
68
|
+
const type = identifier()
|
|
69
|
+
|
|
70
|
+
if (type !== 'text' && type !== 'pg_catalog.text') return undefined
|
|
71
|
+
}
|
|
72
|
+
} else if (next?.kind === 'bare' && /^(?:256|[0-9]|[1-4][0-9]|5[0-2])$/.test(next.value)) {
|
|
73
|
+
position++
|
|
74
|
+
value = ['integer', Number(next.value)]
|
|
75
|
+
} else {
|
|
76
|
+
const name = identifier()
|
|
77
|
+
|
|
78
|
+
if (name === undefined) return undefined
|
|
79
|
+
if ((name === 'length' || name === 'pg_catalog.length') && take('(')) {
|
|
80
|
+
const column = identifier()
|
|
81
|
+
|
|
82
|
+
if (column === undefined || !take(')')) return undefined
|
|
83
|
+
value = ['length', column]
|
|
84
|
+
} else value = ['column', name]
|
|
85
|
+
}
|
|
86
|
+
if (take('::')) {
|
|
87
|
+
const type = identifier()
|
|
88
|
+
|
|
89
|
+
if (value?.[0] !== 'integer' || (type !== 'bigint' && type !== 'pg_catalog.int8')) {
|
|
90
|
+
return undefined
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (take('->>')) {
|
|
94
|
+
const key = operand()
|
|
95
|
+
|
|
96
|
+
if (value?.[0] !== 'column' || value[1] !== 'read_metadata' || key?.[0] !== 'text') {
|
|
97
|
+
return undefined
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return ['json', key[1]]
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (take('-')) {
|
|
104
|
+
const right = operand()
|
|
105
|
+
|
|
106
|
+
return right === undefined || value === undefined ? undefined : ['subtract', value, right]
|
|
107
|
+
}
|
|
108
|
+
if (take('>>')) {
|
|
109
|
+
const right = operand()
|
|
110
|
+
|
|
111
|
+
return value === undefined || right?.[0] !== 'integer' || right[1] > 52
|
|
112
|
+
? undefined
|
|
113
|
+
: ['shift', value, right]
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return value
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const textList = (array: boolean): ReadonlyArray<string | number> | undefined => {
|
|
120
|
+
if (!take('(')) return undefined
|
|
121
|
+
if (array && (!take('array') || !take('['))) return undefined
|
|
122
|
+
const values: Array<string | number> = []
|
|
123
|
+
|
|
124
|
+
do {
|
|
125
|
+
const item = operand()
|
|
126
|
+
|
|
127
|
+
if (item?.[0] !== 'text' && item?.[0] !== 'integer') return undefined
|
|
128
|
+
values.push(item[1])
|
|
129
|
+
} while (take(','))
|
|
130
|
+
if (array && !take(']')) return undefined
|
|
131
|
+
|
|
132
|
+
return take(')') ? values : undefined
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const comparison = (): LayoutExpression | undefined => {
|
|
136
|
+
const left = operand()
|
|
137
|
+
|
|
138
|
+
if (left === undefined) return undefined
|
|
139
|
+
if (take('is')) {
|
|
140
|
+
const tag = take('not') ? 'notNull' : 'null'
|
|
141
|
+
|
|
142
|
+
return take('null') ? [tag, left] : undefined
|
|
143
|
+
}
|
|
144
|
+
const negated = take('not')
|
|
145
|
+
|
|
146
|
+
if (negated || take('in')) {
|
|
147
|
+
if (negated && !take('in')) return undefined
|
|
148
|
+
const values = textList(false)
|
|
149
|
+
|
|
150
|
+
return values === undefined ? undefined : [negated ? 'notIn' : 'in', left, values]
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const operator = take('=')
|
|
154
|
+
? 'eq'
|
|
155
|
+
: take('<>')
|
|
156
|
+
? 'ne'
|
|
157
|
+
: take('>=')
|
|
158
|
+
? 'ge'
|
|
159
|
+
: take('<=')
|
|
160
|
+
? 'le'
|
|
161
|
+
: take('>')
|
|
162
|
+
? 'gt'
|
|
163
|
+
: take('<')
|
|
164
|
+
? 'lt'
|
|
165
|
+
: undefined
|
|
166
|
+
|
|
167
|
+
if (operator === undefined) return left
|
|
168
|
+
if ((operator === 'eq' && take('any')) || (operator === 'ne' && take('all'))) {
|
|
169
|
+
const values = textList(true)
|
|
170
|
+
|
|
171
|
+
return values === undefined ? undefined : [operator === 'eq' ? 'in' : 'notIn', left, values]
|
|
172
|
+
}
|
|
173
|
+
const right = operand()
|
|
174
|
+
|
|
175
|
+
return right === undefined ? undefined : [operator, left, right]
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const expression = (): LayoutExpression | undefined => {
|
|
179
|
+
const parts: Array<LayoutExpression> = []
|
|
180
|
+
|
|
181
|
+
do {
|
|
182
|
+
const part = comparison()
|
|
183
|
+
|
|
184
|
+
if (part === undefined) return undefined
|
|
185
|
+
parts.push(...(part[0] === 'and' ? part[1] : [part]))
|
|
186
|
+
} while (take('and'))
|
|
187
|
+
|
|
188
|
+
return parts.length === 1 ? parts[0] : ['and', parts]
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const expressions: Array<LayoutExpression> = []
|
|
192
|
+
|
|
193
|
+
do {
|
|
194
|
+
const value = expression()
|
|
195
|
+
|
|
196
|
+
if (value === undefined) return undefined
|
|
197
|
+
expressions.push(value)
|
|
198
|
+
} while (take(','))
|
|
199
|
+
|
|
200
|
+
return position === tokens.length ? expressions : undefined
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export const matchesLayoutExpressions = (
|
|
204
|
+
actual: string | null,
|
|
205
|
+
expected: ReadonlyArray<LayoutExpression>,
|
|
206
|
+
): boolean =>
|
|
207
|
+
actual === null
|
|
208
|
+
? expected.length === 0
|
|
209
|
+
: JSON.stringify(readExpressions(actual)) === JSON.stringify(expected)
|