@systemfsoftware/agent-storage-postgres 0.0.0-stage → 0.1.0-beta.192

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.
@@ -0,0 +1,144 @@
1
+ import { makeSqlJournal, sqlStorageOwner } from '@systemfsoftware/agent-storage-sql/sql-journal'
2
+ import {
3
+ type CorruptionErrorFields,
4
+ makeSqlQuery,
5
+ makeSqlTransaction,
6
+ type StorageErrorFields,
7
+ } from '@systemfsoftware/agent-storage-sql/sql-storage'
8
+ import * as Effect from 'effect/Effect'
9
+ import * as Schema from 'effect/Schema'
10
+ import * as SqlClient from 'effect/sql/SqlClient'
11
+ import * as SqlError from 'effect/sql/SqlError'
12
+
13
+ import {
14
+ PostgresStorageCorruptionError,
15
+ PostgresStorageError,
16
+ type PostgresStorageFailpointError,
17
+ type PostgresStorageFailpointLocation,
18
+ PostgresWriteContention,
19
+ } from '../PostgresStorageError'
20
+ import { applyPostgresLayout, inspectPostgresStorage } from './storage-layout'
21
+
22
+ export { CurrentPostgresStorageVersion, readPostgresStorageHeader } from './storage-layout'
23
+
24
+ const storageError = (operation: string) => (cause: SqlError.SqlError) =>
25
+ PostgresStorageError.make({ operation, cause, message: cause.message })
26
+
27
+ export const classifyWriteFailure =
28
+ (operation: string) => (cause: SqlError.SqlError): PostgresStorageError | PostgresWriteContention =>
29
+ cause.reason._tag === 'SerializationError' ||
30
+ cause.reason._tag === 'DeadlockError' ||
31
+ cause.reason._tag === 'LockTimeoutError'
32
+ ? PostgresWriteContention.make({
33
+ operation,
34
+ cause,
35
+ message: `Postgres reported a transient transaction conflict; ${operation} is safe to retry.`,
36
+ })
37
+ : storageError(operation)(cause)
38
+
39
+ /**
40
+ * Applications route each Thread to one scoped owner. This local gate is shared by all ports
41
+ * using the same client/namespace; it is not a distributed lock or failover protocol.
42
+ */
43
+ export const makeWriteTransaction = Effect.fnUntraced(function*(
44
+ sql: SqlClient.SqlClient,
45
+ lockTimeout: number,
46
+ namespace: string,
47
+ ) {
48
+ const owner = yield* sqlStorageOwner(sql, namespace)
49
+
50
+ const transaction = makeSqlTransaction(sql, {
51
+ begin: 'BEGIN ISOLATION LEVEL READ COMMITTED',
52
+ prelude: sql`SELECT set_config('lock_timeout', ${`${lockTimeout}ms`}, true)`.withoutTransform,
53
+ })
54
+
55
+ return <A, E, R>(body: Effect.Effect<A, E, R>) => owner.withMutation(transaction(body))
56
+ })
57
+
58
+ /** Every page of a multi-query export observes the same snapshot without creating write authority. */
59
+ const withReadTransaction = (sql: SqlClient.SqlClient) =>
60
+ makeSqlTransaction(sql, { begin: 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY' })
61
+
62
+ /** Run while holding the owner transaction, including when this schema does not yet exist. */
63
+ export const ensurePostgresSchema = Effect.fnUntraced(function*(schema: string) {
64
+ const sql = yield* SqlClient.SqlClient
65
+ const { execute } = yield* makeSqlQuery()
66
+
67
+ const existing = yield* execute(sql`SELECT 1 FROM pg_namespace WHERE nspname = ${schema}`)
68
+
69
+ // Even IF NOT EXISTS requires database-wide CREATE permission.
70
+ if (existing.length === 0) {
71
+ yield* execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql(schema)}`)
72
+ }
73
+ })
74
+
75
+ export const postgresStorageErrors = {
76
+ storage: (fields: StorageErrorFields) => PostgresStorageError.make(fields),
77
+ corruption: (fields: CorruptionErrorFields) => PostgresStorageCorruptionError.make(fields),
78
+ isCorruption: Schema.is(PostgresStorageCorruptionError),
79
+ }
80
+
81
+ const isTransactionFailure = Schema.is(
82
+ Schema.Union([PostgresStorageError, PostgresWriteContention]),
83
+ )
84
+
85
+ /** Inspect under the owner gate before any DDL; current headers commit together. */
86
+ export const initializePostgresStorage = Effect.fn('PostgresStorage.initializeLayout')(function*({
87
+ lockTimeout,
88
+ schema,
89
+ }: {
90
+ readonly lockTimeout: number
91
+ readonly schema: string
92
+ }) {
93
+ const sql = yield* SqlClient.SqlClient
94
+
95
+ const write = yield* makeWriteTransaction(sql, lockTimeout, schema)
96
+
97
+ yield* write(
98
+ Effect.gen(function*() {
99
+ const header = yield* inspectPostgresStorage(schema, true)
100
+
101
+ if (header === undefined) yield* ensurePostgresSchema(schema)
102
+ yield* applyPostgresLayout(schema, header)
103
+ }),
104
+ ).pipe(
105
+ Effect.catchTag('SqlError', (error) => Effect.fail(classifyWriteFailure('initialize storage')(error))),
106
+ )
107
+ })
108
+
109
+ /** Bind shared journal operations without repeating format initialization. */
110
+ export const makePostgresJournal = Effect.fnUntraced(function*(
111
+ lockTimeout: number,
112
+ hitFailpoint: (
113
+ location: PostgresStorageFailpointLocation,
114
+ ) => Effect.Effect<void, PostgresStorageFailpointError>,
115
+ namespace: string,
116
+ ) {
117
+ const sql = yield* SqlClient.SqlClient
118
+ const write = yield* makeWriteTransaction(sql, lockTimeout, namespace)
119
+ const read = withReadTransaction(sql)
120
+
121
+ return yield* makeSqlJournal({
122
+ namespace,
123
+ errors: postgresStorageErrors,
124
+ hitFailpoint,
125
+ transactions: {
126
+ withWriteTransaction: (operation) => <A, E, R>(body: Effect.Effect<A, E, R>) =>
127
+ write(body).pipe(
128
+ Effect.mapError((error) => {
129
+ if (SqlError.isSqlError(error)) return classifyWriteFailure(operation)(error)
130
+ if (Schema.is(PostgresStorageError)(error) && SqlError.isSqlError(error.cause)) {
131
+ return classifyWriteFailure(error.operation)(error.cause)
132
+ }
133
+
134
+ return error
135
+ }),
136
+ ),
137
+ withReadTransaction: (operation) => <A, E, R>(body: Effect.Effect<A, E, R>) =>
138
+ read(body).pipe(
139
+ Effect.mapError((error) => SqlError.isSqlError(error) ? storageError(operation)(error) : error),
140
+ ),
141
+ isTransactionFailure,
142
+ },
143
+ })
144
+ })