@pgxsinkit/pgwasm 0.5.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/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +111 -0
- package/README.md +56 -0
- package/dist/build/index.d.ts +8 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +21 -0
- package/dist/build/index.js.map +9 -0
- package/dist/build/seam.d.ts +174 -0
- package/dist/build/seam.d.ts.map +1 -0
- package/dist/chunk-0w227vw2.js +233 -0
- package/dist/chunk-0w227vw2.js.map +11 -0
- package/dist/chunk-74gcrk47.js +563 -0
- package/dist/chunk-74gcrk47.js.map +14 -0
- package/dist/chunk-at1py5s5.js +373 -0
- package/dist/chunk-at1py5s5.js.map +12 -0
- package/dist/chunk-cpsnmzrf.js +126 -0
- package/dist/chunk-cpsnmzrf.js.map +10 -0
- package/dist/chunk-d82gg1hx.js +306 -0
- package/dist/chunk-d82gg1hx.js.map +10 -0
- package/dist/chunk-gjf102c9.js +1005 -0
- package/dist/chunk-gjf102c9.js.map +16 -0
- package/dist/chunk-kb3rsr7n.js +19 -0
- package/dist/chunk-kb3rsr7n.js.map +9 -0
- package/dist/chunk-tdvrvgt5.js +83 -0
- package/dist/chunk-tdvrvgt5.js.map +11 -0
- package/dist/chunk-z0c40tja.js +50 -0
- package/dist/chunk-z0c40tja.js.map +10 -0
- package/dist/core/data-dir-archive.d.ts +17 -0
- package/dist/core/data-dir-archive.d.ts.map +1 -0
- package/dist/core/internals.d.ts +59 -0
- package/dist/core/internals.d.ts.map +1 -0
- package/dist/core/marker.d.ts +35 -0
- package/dist/core/marker.d.ts.map +1 -0
- package/dist/core/mutex.d.ts +9 -0
- package/dist/core/mutex.d.ts.map +1 -0
- package/dist/core/names.d.ts +11 -0
- package/dist/core/names.d.ts.map +1 -0
- package/dist/core/parse.d.ts +11 -0
- package/dist/core/parse.d.ts.map +1 -0
- package/dist/core/pgwasm.d.ts +53 -0
- package/dist/core/pgwasm.d.ts.map +1 -0
- package/dist/core/storage.d.ts +14 -0
- package/dist/core/storage.d.ts.map +1 -0
- package/dist/create.d.ts +10 -0
- package/dist/create.d.ts.map +1 -0
- package/dist/drizzle/codecs.d.ts +9 -0
- package/dist/drizzle/codecs.d.ts.map +1 -0
- package/dist/drizzle/driver.d.ts +50 -0
- package/dist/drizzle/driver.d.ts.map +1 -0
- package/dist/drizzle/index.d.ts +4 -0
- package/dist/drizzle/index.d.ts.map +1 -0
- package/dist/drizzle/index.js +261 -0
- package/dist/drizzle/index.js.map +12 -0
- package/dist/drizzle/session.d.ts +39 -0
- package/dist/drizzle/session.d.ts.map +1 -0
- package/dist/errors.d.ts +115 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/fs/base-filesystem.d.ts +118 -0
- package/dist/fs/base-filesystem.d.ts.map +1 -0
- package/dist/fs/index.d.ts +2 -0
- package/dist/fs/index.d.ts.map +1 -0
- package/dist/fs/index.js +11 -0
- package/dist/fs/index.js.map +9 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +53 -0
- package/dist/index.js.map +9 -0
- package/dist/interface.d.ts +165 -0
- package/dist/interface.d.ts.map +1 -0
- package/dist/live/debounce-mutex.d.ts +6 -0
- package/dist/live/debounce-mutex.d.ts.map +1 -0
- package/dist/live/format-query.d.ts +8 -0
- package/dist/live/format-query.d.ts.map +1 -0
- package/dist/live/index.d.ts +9 -0
- package/dist/live/index.d.ts.map +1 -0
- package/dist/live/index.js +601 -0
- package/dist/live/index.js.map +12 -0
- package/dist/live/interface.d.ts +86 -0
- package/dist/live/interface.d.ts.map +1 -0
- package/dist/opfs/broker/client.d.ts +163 -0
- package/dist/opfs/broker/client.d.ts.map +1 -0
- package/dist/opfs/broker/protocol.d.ts +326 -0
- package/dist/opfs/broker/protocol.d.ts.map +1 -0
- package/dist/opfs/broker/server.d.ts +84 -0
- package/dist/opfs/broker/server.d.ts.map +1 -0
- package/dist/opfs/core/checksum.d.ts +3 -0
- package/dist/opfs/core/checksum.d.ts.map +1 -0
- package/dist/opfs/core/codec.d.ts +73 -0
- package/dist/opfs/core/codec.d.ts.map +1 -0
- package/dist/opfs/core/errors.d.ts +80 -0
- package/dist/opfs/core/errors.d.ts.map +1 -0
- package/dist/opfs/core/limits.d.ts +35 -0
- package/dist/opfs/core/limits.d.ts.map +1 -0
- package/dist/opfs/core/memory-port.d.ts +51 -0
- package/dist/opfs/core/memory-port.d.ts.map +1 -0
- package/dist/opfs/core/metadata-store.d.ts +19 -0
- package/dist/opfs/core/metadata-store.d.ts.map +1 -0
- package/dist/opfs/core/mounted-vfs.d.ts +119 -0
- package/dist/opfs/core/mounted-vfs.d.ts.map +1 -0
- package/dist/opfs/core/path.d.ts +14 -0
- package/dist/opfs/core/path.d.ts.map +1 -0
- package/dist/opfs/core/port.d.ts +30 -0
- package/dist/opfs/core/port.d.ts.map +1 -0
- package/dist/opfs/core/repacked-vfs.d.ts +138 -0
- package/dist/opfs/core/repacked-vfs.d.ts.map +1 -0
- package/dist/opfs/core/state-machine.d.ts +296 -0
- package/dist/opfs/core/state-machine.d.ts.map +1 -0
- package/dist/opfs/create.d.ts +50 -0
- package/dist/opfs/create.d.ts.map +1 -0
- package/dist/opfs/file-port.d.ts +14 -0
- package/dist/opfs/file-port.d.ts.map +1 -0
- package/dist/opfs/index.d.ts +37 -0
- package/dist/opfs/index.d.ts.map +1 -0
- package/dist/opfs/index.js +6671 -0
- package/dist/opfs/index.js.map +28 -0
- package/dist/opfs/opfs-port.d.ts +34 -0
- package/dist/opfs/opfs-port.d.ts.map +1 -0
- package/dist/opfs/opfs-repacked-fs.d.ts +55 -0
- package/dist/opfs/opfs-repacked-fs.d.ts.map +1 -0
- package/dist/opfs/wasi/preview1.d.ts +228 -0
- package/dist/opfs/wasi/preview1.d.ts.map +1 -0
- package/dist/protocol/index.d.ts +15 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +23 -0
- package/dist/protocol/index.js.map +10 -0
- package/dist/protocol/wire/buffer-reader.d.ts +13 -0
- package/dist/protocol/wire/buffer-reader.d.ts.map +1 -0
- package/dist/protocol/wire/buffer-writer.d.ts +12 -0
- package/dist/protocol/wire/buffer-writer.d.ts.map +1 -0
- package/dist/protocol/wire/index.d.ts +5 -0
- package/dist/protocol/wire/index.d.ts.map +1 -0
- package/dist/protocol/wire/messages.d.ts +194 -0
- package/dist/protocol/wire/messages.d.ts.map +1 -0
- package/dist/protocol/wire/parser.d.ts +12 -0
- package/dist/protocol/wire/parser.d.ts.map +1 -0
- package/dist/protocol/wire/serializer.d.ts +61 -0
- package/dist/protocol/wire/serializer.d.ts.map +1 -0
- package/dist/protocol/wire/string-utils.d.ts +6 -0
- package/dist/protocol/wire/string-utils.d.ts.map +1 -0
- package/dist/protocol/wire/types.d.ts +7 -0
- package/dist/protocol/wire/types.d.ts.map +1 -0
- package/dist/tar/gzip.d.ts +7 -0
- package/dist/tar/gzip.d.ts.map +1 -0
- package/dist/tar/tar.d.ts +39 -0
- package/dist/tar/tar.d.ts.map +1 -0
- package/dist/templating.d.ts +42 -0
- package/dist/templating.d.ts.map +1 -0
- package/dist/types.d.ts +76 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +69 -0
- package/skills/opfs/SKILL.md +138 -0
- package/src/build/index.ts +23 -0
- package/src/build/seam.ts +179 -0
- package/src/core/data-dir-archive.ts +68 -0
- package/src/core/internals.ts +87 -0
- package/src/core/marker.ts +94 -0
- package/src/core/mutex.ts +16 -0
- package/src/core/names.ts +26 -0
- package/src/core/parse.ts +79 -0
- package/src/core/pgwasm.ts +876 -0
- package/src/core/storage.ts +70 -0
- package/src/create.ts +134 -0
- package/src/drizzle/codecs.ts +114 -0
- package/src/drizzle/driver.ts +141 -0
- package/src/drizzle/index.ts +15 -0
- package/src/drizzle/session.ts +133 -0
- package/src/errors.ts +201 -0
- package/src/fs/base-filesystem.ts +149 -0
- package/src/fs/index.ts +7 -0
- package/src/index.ts +44 -0
- package/src/interface.ts +186 -0
- package/src/live/debounce-mutex.ts +45 -0
- package/src/live/format-query.ts +47 -0
- package/src/live/index.ts +707 -0
- package/src/live/interface.ts +109 -0
- package/src/opfs/broker/client.ts +482 -0
- package/src/opfs/broker/protocol.ts +624 -0
- package/src/opfs/broker/server.ts +522 -0
- package/src/opfs/core/checksum.ts +85 -0
- package/src/opfs/core/codec.ts +1051 -0
- package/src/opfs/core/errors.ts +134 -0
- package/src/opfs/core/limits.ts +68 -0
- package/src/opfs/core/memory-port.ts +459 -0
- package/src/opfs/core/metadata-store.ts +512 -0
- package/src/opfs/core/mounted-vfs.ts +407 -0
- package/src/opfs/core/path.ts +82 -0
- package/src/opfs/core/port.ts +114 -0
- package/src/opfs/core/repacked-vfs.ts +1464 -0
- package/src/opfs/core/state-machine.ts +1699 -0
- package/src/opfs/create.ts +125 -0
- package/src/opfs/file-port.ts +183 -0
- package/src/opfs/index.ts +113 -0
- package/src/opfs/opfs-port.ts +90 -0
- package/src/opfs/opfs-repacked-fs.ts +210 -0
- package/src/opfs/wasi/preview1.ts +1016 -0
- package/src/protocol/index.ts +24 -0
- package/src/protocol/wire/buffer-reader.ts +60 -0
- package/src/protocol/wire/buffer-writer.ts +93 -0
- package/src/protocol/wire/index.ts +15 -0
- package/src/protocol/wire/messages.ts +332 -0
- package/src/protocol/wire/parser.ts +373 -0
- package/src/protocol/wire/serializer.ts +233 -0
- package/src/protocol/wire/string-utils.ts +18 -0
- package/src/protocol/wire/types.ts +12 -0
- package/src/tar/gzip.ts +36 -0
- package/src/tar/tar.ts +253 -0
- package/src/templating.ts +103 -0
- package/src/types.ts +283 -0
|
@@ -0,0 +1,876 @@
|
|
|
1
|
+
// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
|
|
2
|
+
// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
BuildCapabilities,
|
|
6
|
+
BuildIdentity,
|
|
7
|
+
DataDirEntry,
|
|
8
|
+
DebugLevel,
|
|
9
|
+
PostgresBuild,
|
|
10
|
+
RunningPostgres,
|
|
11
|
+
ServerExtension,
|
|
12
|
+
StorageRequest,
|
|
13
|
+
WireSession,
|
|
14
|
+
} from "../build/seam";
|
|
15
|
+
import {
|
|
16
|
+
DataDirExistsError,
|
|
17
|
+
makeQueryError,
|
|
18
|
+
PgwasmClosedError,
|
|
19
|
+
PgwasmError,
|
|
20
|
+
PgwasmFailedError,
|
|
21
|
+
UnsupportedFeatureError,
|
|
22
|
+
} from "../errors";
|
|
23
|
+
import type {
|
|
24
|
+
DumpCompression,
|
|
25
|
+
Extension,
|
|
26
|
+
ParserOptions,
|
|
27
|
+
Pgwasm,
|
|
28
|
+
QueryOptions,
|
|
29
|
+
Results,
|
|
30
|
+
SerializerOptions,
|
|
31
|
+
StorageDescription,
|
|
32
|
+
Transaction,
|
|
33
|
+
} from "../interface";
|
|
34
|
+
import {
|
|
35
|
+
DatabaseError,
|
|
36
|
+
NoticeMessage,
|
|
37
|
+
NotificationResponseMessage,
|
|
38
|
+
type BackendMessage,
|
|
39
|
+
} from "../protocol/wire/messages";
|
|
40
|
+
import { Parser as WireParser } from "../protocol/wire/parser";
|
|
41
|
+
import { serialize } from "../protocol/wire/serializer";
|
|
42
|
+
import { query as queryTemplate } from "../templating";
|
|
43
|
+
import {
|
|
44
|
+
arrayParser,
|
|
45
|
+
arraySerializer,
|
|
46
|
+
parsers as defaultParsers,
|
|
47
|
+
serializers as defaultSerializers,
|
|
48
|
+
toText,
|
|
49
|
+
type Parser,
|
|
50
|
+
type Serializer,
|
|
51
|
+
} from "../types";
|
|
52
|
+
import { writeDataDirArchive } from "./data-dir-archive";
|
|
53
|
+
import {
|
|
54
|
+
type ExecProtocolOptions,
|
|
55
|
+
type ExecProtocolResult,
|
|
56
|
+
type ExecProtocolStreamOptions,
|
|
57
|
+
registerProtocolAccess,
|
|
58
|
+
} from "./internals";
|
|
59
|
+
import { BUILD_MARKER_PATH, checkBuildMarker, encodeBuildMarker, PG_VERSION_PATH } from "./marker";
|
|
60
|
+
import { Mutex } from "./mutex";
|
|
61
|
+
import { quoteIdentifier, toPostgresName } from "./names";
|
|
62
|
+
import { parseDescribeStatementResults, parseResults } from "./parse";
|
|
63
|
+
import { backupBaseName, describeStorage } from "./storage";
|
|
64
|
+
|
|
65
|
+
/** Everything `createPgwasm` resolved and validated before booting. */
|
|
66
|
+
export interface BootPlan {
|
|
67
|
+
readonly build: PostgresBuild;
|
|
68
|
+
readonly storage: StorageRequest;
|
|
69
|
+
readonly serverExtensions: readonly ServerExtension[];
|
|
70
|
+
readonly clientExtensions: readonly (readonly [key: string, extension: Extension])[];
|
|
71
|
+
/** A Store backup's entries to create the data directory from, marker included. */
|
|
72
|
+
readonly restore: readonly DataDirEntry[] | undefined;
|
|
73
|
+
readonly settings: Readonly<Record<string, string>>;
|
|
74
|
+
readonly user: string;
|
|
75
|
+
readonly database: string;
|
|
76
|
+
readonly username: string | undefined;
|
|
77
|
+
readonly debug: DebugLevel;
|
|
78
|
+
readonly relaxedDurability: boolean;
|
|
79
|
+
readonly parsers: ParserOptions | undefined;
|
|
80
|
+
readonly serializers: SerializerOptions | undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface CurrentQuery {
|
|
84
|
+
results: BackendMessage[];
|
|
85
|
+
throwOnError: boolean;
|
|
86
|
+
onNotice: ((notice: NoticeMessage) => void) | undefined;
|
|
87
|
+
databaseError: DatabaseError | null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function newQuery(throwOnError = false, onNotice?: (notice: NoticeMessage) => void): CurrentQuery {
|
|
91
|
+
return { results: [], throwOnError, onNotice, databaseError: null };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function describeException(error: unknown): string {
|
|
95
|
+
if (typeof error === "object" && error !== null && "message" in error) {
|
|
96
|
+
const { name, message } = error as { name?: unknown; message?: unknown };
|
|
97
|
+
return `${typeof name === "string" ? name : "Error"}: ${String(message)}`;
|
|
98
|
+
}
|
|
99
|
+
return String(error);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function concatChunks(chunks: readonly Uint8Array[]): Uint8Array {
|
|
103
|
+
if (chunks.length === 1) return chunks[0] ?? new Uint8Array(0);
|
|
104
|
+
const total = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
|
|
105
|
+
const out = new Uint8Array(total);
|
|
106
|
+
let offset = 0;
|
|
107
|
+
for (const chunk of chunks) {
|
|
108
|
+
out.set(chunk, offset);
|
|
109
|
+
offset += chunk.byteLength;
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A running database over a Postgres build. Everything above the wire protocol lives here, once for
|
|
116
|
+
* every build: queries and transactions, the persist scheduler and its latch, the failure latch,
|
|
117
|
+
* notifications, array types, backups and the build marker.
|
|
118
|
+
*/
|
|
119
|
+
export class PgwasmInstance implements Pgwasm {
|
|
120
|
+
readonly build: BuildIdentity;
|
|
121
|
+
readonly storage: StorageDescription;
|
|
122
|
+
readonly debug: DebugLevel;
|
|
123
|
+
readonly waitReady: Promise<void>;
|
|
124
|
+
|
|
125
|
+
readonly #capabilities: BuildCapabilities;
|
|
126
|
+
readonly #relaxedDurability: boolean;
|
|
127
|
+
#resolveReady: () => void = () => undefined;
|
|
128
|
+
#rejectReady: (error: unknown) => void = () => undefined;
|
|
129
|
+
|
|
130
|
+
#ready = false;
|
|
131
|
+
#closing = false;
|
|
132
|
+
#closed = false;
|
|
133
|
+
// Set when the build failed underneath a statement: every later statement throws it (see #fail).
|
|
134
|
+
#failure: { error: PgwasmFailedError } | undefined;
|
|
135
|
+
// A background (relaxed) persist that failed: the next statement reports it.
|
|
136
|
+
#persistFailure: { error: unknown } | undefined;
|
|
137
|
+
#persistScheduled = false;
|
|
138
|
+
|
|
139
|
+
readonly #queryMutex = new Mutex();
|
|
140
|
+
readonly #transactionMutex = new Mutex();
|
|
141
|
+
readonly #listenMutex = new Mutex();
|
|
142
|
+
readonly #persistMutex = new Mutex();
|
|
143
|
+
|
|
144
|
+
#running: RunningPostgres | undefined;
|
|
145
|
+
#session: WireSession | undefined;
|
|
146
|
+
readonly #extensionsClose: (() => Promise<void>)[] = [];
|
|
147
|
+
|
|
148
|
+
#parser = new WireParser();
|
|
149
|
+
readonly #unsolicitedParser = new WireParser();
|
|
150
|
+
#currentQuery: CurrentQuery = newQuery();
|
|
151
|
+
|
|
152
|
+
readonly #notifyListeners = new Map<string, Set<(payload: string) => void>>();
|
|
153
|
+
readonly #globalNotifyListeners = new Set<(channel: string, payload: string) => void>();
|
|
154
|
+
|
|
155
|
+
readonly #parsers: Record<number | string, Parser>;
|
|
156
|
+
readonly #serializers: Record<number | string, Serializer>;
|
|
157
|
+
#arrayTypesInitialized = false;
|
|
158
|
+
#inTransaction = false;
|
|
159
|
+
|
|
160
|
+
constructor(plan: BootPlan) {
|
|
161
|
+
this.build = plan.build.identity;
|
|
162
|
+
this.#capabilities = plan.build.capabilities;
|
|
163
|
+
this.storage = describeStorage(plan.storage);
|
|
164
|
+
this.debug = plan.debug;
|
|
165
|
+
this.#relaxedDurability = plan.relaxedDurability;
|
|
166
|
+
this.#parsers = { ...defaultParsers, ...plan.parsers };
|
|
167
|
+
this.#serializers = { ...defaultSerializers, ...plan.serializers };
|
|
168
|
+
this.waitReady = new Promise<void>((resolve, reject) => {
|
|
169
|
+
this.#resolveReady = resolve;
|
|
170
|
+
this.#rejectReady = reject;
|
|
171
|
+
});
|
|
172
|
+
// A failed boot is reported by createPgwasm; the rejection here must not also surface unhandled.
|
|
173
|
+
this.waitReady.catch(() => undefined);
|
|
174
|
+
registerProtocolAccess(this, {
|
|
175
|
+
execProtocol: (message, options) => this.#execProtocol(message, options),
|
|
176
|
+
execProtocolStream: (message, options) => this.#execProtocolStream(message, options),
|
|
177
|
+
execProtocolRaw: (message, options) => this.#execProtocolRaw(message, options),
|
|
178
|
+
execProtocolRawStream: (message, options) => this.#execProtocolRawStream(message, options),
|
|
179
|
+
runExclusiveSession: (fn) => this.#runExclusiveSession(fn),
|
|
180
|
+
capabilities: this.#capabilities,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ─── boot ────────────────────────────────────────────────────────────────────
|
|
185
|
+
|
|
186
|
+
/** Boot the build, check the build marker, create or restore the data directory, and start. */
|
|
187
|
+
async boot(plan: BootPlan): Promise<void> {
|
|
188
|
+
try {
|
|
189
|
+
await this.#boot(plan);
|
|
190
|
+
this.#resolveReady();
|
|
191
|
+
} catch (error) {
|
|
192
|
+
this.#rejectReady(error);
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async #boot(plan: BootPlan): Promise<void> {
|
|
198
|
+
const inits: (() => Promise<void>)[] = [];
|
|
199
|
+
for (const [key, extension] of plan.clientExtensions) {
|
|
200
|
+
const result = await extension.setup(this);
|
|
201
|
+
if (result.namespace !== undefined) {
|
|
202
|
+
if (key in this) {
|
|
203
|
+
throw new PgwasmError(`The extension key "${key}" collides with a pgwasm member; use another key.`);
|
|
204
|
+
}
|
|
205
|
+
Object.defineProperty(this, key, { value: result.namespace, enumerable: true });
|
|
206
|
+
}
|
|
207
|
+
if (result.init) inits.push(result.init);
|
|
208
|
+
if (result.close) this.#extensionsClose.push(result.close);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const identity = plan.build.identity;
|
|
212
|
+
const mounted = await plan.build.boot({
|
|
213
|
+
storage: plan.storage,
|
|
214
|
+
extensions: plan.serverExtensions,
|
|
215
|
+
user: plan.user,
|
|
216
|
+
database: plan.database,
|
|
217
|
+
debug: plan.debug,
|
|
218
|
+
});
|
|
219
|
+
let running: RunningPostgres;
|
|
220
|
+
try {
|
|
221
|
+
// Build permanence (ADR-0063): refuse another build's directory before anything is written.
|
|
222
|
+
const marker = await mounted.readFile(BUILD_MARKER_PATH);
|
|
223
|
+
const hasCluster = (await mounted.readFile(PG_VERSION_PATH)) !== undefined;
|
|
224
|
+
checkBuildMarker(identity, marker, hasCluster, "data-directory");
|
|
225
|
+
if (plan.restore !== undefined) {
|
|
226
|
+
if (hasCluster) throw new DataDirExistsError();
|
|
227
|
+
this.#log("pgwasm: creating the data directory from a Store backup");
|
|
228
|
+
await mounted.writeEntries(plan.restore);
|
|
229
|
+
await mounted.persist();
|
|
230
|
+
} else if (!hasCluster) {
|
|
231
|
+
this.#log("pgwasm: no database in the data directory, creating one");
|
|
232
|
+
await mounted.createCluster();
|
|
233
|
+
if (marker === undefined) await mounted.writeFile(BUILD_MARKER_PATH, encodeBuildMarker(identity));
|
|
234
|
+
await mounted.persist();
|
|
235
|
+
}
|
|
236
|
+
running = await mounted.start({ settings: plan.settings });
|
|
237
|
+
} catch (error) {
|
|
238
|
+
try {
|
|
239
|
+
await mounted.release();
|
|
240
|
+
} catch {
|
|
241
|
+
// The boot already failed; its first cause is what the caller needs.
|
|
242
|
+
}
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
this.#running = running;
|
|
247
|
+
try {
|
|
248
|
+
const session = await running.openSession();
|
|
249
|
+
session.onUnsolicited = (chunk) => this.#handleUnsolicited(chunk);
|
|
250
|
+
this.#session = session;
|
|
251
|
+
this.#ready = true;
|
|
252
|
+
if (plan.username !== undefined) {
|
|
253
|
+
await this.exec(`SET ROLE ${quoteIdentifier(plan.username)}`);
|
|
254
|
+
}
|
|
255
|
+
await this.#initArrayTypes();
|
|
256
|
+
for (const init of inits) {
|
|
257
|
+
await init();
|
|
258
|
+
}
|
|
259
|
+
} catch (error) {
|
|
260
|
+
this.#ready = false;
|
|
261
|
+
this.#closed = true;
|
|
262
|
+
try {
|
|
263
|
+
// A background persist a statement of the boot started (an extension's init) must settle first:
|
|
264
|
+
// releasing tears its storage down under it.
|
|
265
|
+
await this.#persistMutex.runExclusive(async () => {});
|
|
266
|
+
await running.release({ afterFailedBoot: true });
|
|
267
|
+
} catch {
|
|
268
|
+
// Preserve the error that made the boot fail.
|
|
269
|
+
}
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ─── state ───────────────────────────────────────────────────────────────────
|
|
275
|
+
|
|
276
|
+
get ready(): boolean {
|
|
277
|
+
return this.#ready && !this.#closing && !this.#closed && this.#failure === undefined;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
get closed(): boolean {
|
|
281
|
+
return this.#closed;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async #checkReady(): Promise<void> {
|
|
285
|
+
if (this.#closing) throw new PgwasmClosedError("closing");
|
|
286
|
+
if (this.#closed) throw new PgwasmClosedError("closed");
|
|
287
|
+
if (!this.#ready) await this.waitReady;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
#checkOpenState(): void {
|
|
291
|
+
if (this.#closing) throw new PgwasmClosedError("closing");
|
|
292
|
+
if (this.#closed) throw new PgwasmClosedError("closed");
|
|
293
|
+
if (this.#failure) throw this.#failure.error;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
#checkPersistLatch(): void {
|
|
297
|
+
if (this.#persistFailure) throw this.#persistFailure.error;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Latch the instance as failed and return the error the failing statement and every later one
|
|
302
|
+
* throw. It names the exception and, when Postgres reported an error first (a PANIC does, before it
|
|
303
|
+
* aborts), that error.
|
|
304
|
+
*/
|
|
305
|
+
#fail(cause: unknown): PgwasmFailedError {
|
|
306
|
+
if (this.#failure) return this.#failure.error;
|
|
307
|
+
const reported = this.#currentQuery.databaseError;
|
|
308
|
+
const error = new PgwasmFailedError(
|
|
309
|
+
"pgwasm failed and must be closed: " +
|
|
310
|
+
(reported
|
|
311
|
+
? `Postgres reported ${reported.severity ?? "an error"}: ${reported.message}; the build then threw `
|
|
312
|
+
: "the build threw ") +
|
|
313
|
+
describeException(cause),
|
|
314
|
+
{ cause },
|
|
315
|
+
);
|
|
316
|
+
this.#failure = { error };
|
|
317
|
+
return error;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
#log(...args: unknown[]): void {
|
|
321
|
+
if (this.debug > 0) console.log(...args);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// ─── the wire ────────────────────────────────────────────────────────────────
|
|
325
|
+
|
|
326
|
+
#exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void | Promise<void> {
|
|
327
|
+
this.#checkOpenState();
|
|
328
|
+
const session = this.#session;
|
|
329
|
+
if (session === undefined) throw new PgwasmClosedError("closed");
|
|
330
|
+
let pending: void | Promise<void>;
|
|
331
|
+
try {
|
|
332
|
+
pending = session.exchange(message, onData);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
throw this.#fail(error);
|
|
335
|
+
}
|
|
336
|
+
if (pending === undefined) return;
|
|
337
|
+
return pending.then(undefined, (error: unknown) => {
|
|
338
|
+
throw this.#fail(error);
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
#parseChunk(chunk: Uint8Array): void {
|
|
343
|
+
this.#parser.parse(chunk, (message) => {
|
|
344
|
+
const handled = this.#handleMessage(message);
|
|
345
|
+
if (handled) this.#currentQuery.results.push(handled);
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
#handleUnsolicited(chunk: Uint8Array): void {
|
|
350
|
+
this.#unsolicitedParser.parse(chunk, (message) => {
|
|
351
|
+
if (message instanceof NotificationResponseMessage) this.#dispatchNotification(message);
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
#handleMessage(message: BackendMessage): BackendMessage | null {
|
|
356
|
+
// Once a statement reported an error, the rest of its reply only needs acknowledging.
|
|
357
|
+
if (this.#currentQuery.databaseError) return null;
|
|
358
|
+
if (message instanceof DatabaseError) {
|
|
359
|
+
if (this.#currentQuery.throwOnError) this.#currentQuery.databaseError = message;
|
|
360
|
+
} else if (message instanceof NoticeMessage) {
|
|
361
|
+
if (this.debug > 0) console.warn(message);
|
|
362
|
+
this.#currentQuery.onNotice?.(message);
|
|
363
|
+
} else if (message instanceof NotificationResponseMessage) {
|
|
364
|
+
this.#dispatchNotification(message);
|
|
365
|
+
}
|
|
366
|
+
return message;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
#dispatchNotification(message: NotificationResponseMessage): void {
|
|
370
|
+
// Callbacks run after the synchronous code that received the notification.
|
|
371
|
+
const listeners = this.#notifyListeners.get(message.channel);
|
|
372
|
+
if (listeners) {
|
|
373
|
+
for (const callback of listeners) queueMicrotask(() => callback(message.payload));
|
|
374
|
+
}
|
|
375
|
+
for (const callback of this.#globalNotifyListeners) {
|
|
376
|
+
queueMicrotask(() => callback(message.channel, message.payload));
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async #execProtocolRaw(message: Uint8Array, { persist = true }: Pick<ExecProtocolOptions, "persist"> = {}) {
|
|
381
|
+
// Checks only (no await) before the exchange, so a build that exchanges synchronously delivers the
|
|
382
|
+
// reply inside this call's synchronous prefix.
|
|
383
|
+
this.#checkPersistLatch();
|
|
384
|
+
const chunks: Uint8Array[] = [];
|
|
385
|
+
const pending = this.#exchange(message, (chunk) => {
|
|
386
|
+
chunks.push(chunk.slice());
|
|
387
|
+
this.#parseChunk(chunk);
|
|
388
|
+
});
|
|
389
|
+
if (pending !== undefined) await pending;
|
|
390
|
+
if (persist) await this.#persistAfterStatement();
|
|
391
|
+
return concatChunks(chunks);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
async #execProtocolRawStream(
|
|
395
|
+
message: Uint8Array,
|
|
396
|
+
{ persist = true, onRawData }: ExecProtocolStreamOptions,
|
|
397
|
+
): Promise<void> {
|
|
398
|
+
// Same synchronous-prefix contract as #execProtocolRaw: pg_dump's write callback drives this from
|
|
399
|
+
// inside a blocking wasm call and reads the reply back before it returns.
|
|
400
|
+
this.#checkPersistLatch();
|
|
401
|
+
const pending = this.#exchange(message, onRawData);
|
|
402
|
+
if (pending !== undefined) await pending;
|
|
403
|
+
if (persist) await this.#persistAfterStatement();
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async #execProtocol(
|
|
407
|
+
message: Uint8Array,
|
|
408
|
+
{ persist = true, throwOnError = true, onNotice }: ExecProtocolOptions = {},
|
|
409
|
+
): Promise<ExecProtocolResult> {
|
|
410
|
+
this.#currentQuery = newQuery(throwOnError, onNotice);
|
|
411
|
+
try {
|
|
412
|
+
const data = await this.#execProtocolRaw(message, { persist });
|
|
413
|
+
const databaseError = this.#currentQuery.databaseError;
|
|
414
|
+
const result = { messages: this.#currentQuery.results, data };
|
|
415
|
+
if (throwOnError && databaseError) {
|
|
416
|
+
this.#parser = new WireParser();
|
|
417
|
+
throw databaseError;
|
|
418
|
+
}
|
|
419
|
+
return result;
|
|
420
|
+
} finally {
|
|
421
|
+
this.#currentQuery = newQuery();
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
async #execProtocolStream(
|
|
426
|
+
message: Uint8Array,
|
|
427
|
+
{ persist = true, throwOnError = true, onNotice }: ExecProtocolOptions = {},
|
|
428
|
+
): Promise<BackendMessage[]> {
|
|
429
|
+
this.#currentQuery = newQuery(throwOnError, onNotice);
|
|
430
|
+
try {
|
|
431
|
+
this.#checkPersistLatch();
|
|
432
|
+
const pending = this.#exchange(message, (chunk) => this.#parseChunk(chunk));
|
|
433
|
+
if (pending !== undefined) await pending;
|
|
434
|
+
if (persist) await this.#persistAfterStatement();
|
|
435
|
+
const databaseError = this.#currentQuery.databaseError;
|
|
436
|
+
const results = this.#currentQuery.results;
|
|
437
|
+
if (throwOnError && databaseError) {
|
|
438
|
+
this.#parser = new WireParser();
|
|
439
|
+
throw databaseError;
|
|
440
|
+
}
|
|
441
|
+
return results;
|
|
442
|
+
} finally {
|
|
443
|
+
this.#currentQuery = newQuery();
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ─── durability ──────────────────────────────────────────────────────────────
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Persist storage after a statement. Awaited by default; with `relaxedDurability` it runs in the
|
|
451
|
+
* background and a failure is latched for the next statement. An awaited failure is not latched: the
|
|
452
|
+
* caller already has it, and a filesystem with its own failure policy decides what later calls see.
|
|
453
|
+
*/
|
|
454
|
+
async #persistAfterStatement(): Promise<void> {
|
|
455
|
+
this.#checkOpenState();
|
|
456
|
+
this.#checkPersistLatch();
|
|
457
|
+
const running = this.#running;
|
|
458
|
+
if (running === undefined || this.#persistScheduled) return;
|
|
459
|
+
this.#persistScheduled = true;
|
|
460
|
+
const run = () =>
|
|
461
|
+
this.#persistMutex.runExclusive(async () => {
|
|
462
|
+
this.#persistScheduled = false;
|
|
463
|
+
await running.persist(this.#relaxedDurability);
|
|
464
|
+
});
|
|
465
|
+
if (this.#relaxedDurability) {
|
|
466
|
+
run().catch((error: unknown) => {
|
|
467
|
+
this.#persistFailure ??= { error };
|
|
468
|
+
});
|
|
469
|
+
} else {
|
|
470
|
+
await run();
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// ─── queries ─────────────────────────────────────────────────────────────────
|
|
475
|
+
|
|
476
|
+
#runExclusiveQuery<T>(fn: () => Promise<T>): Promise<T> {
|
|
477
|
+
return this.#queryMutex.runExclusive(async () => {
|
|
478
|
+
this.#checkPersistLatch();
|
|
479
|
+
return await fn();
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
async #execNoPersist(message: Uint8Array, options?: QueryOptions): Promise<BackendMessage[]> {
|
|
484
|
+
return await this.#execProtocolStream(message, {
|
|
485
|
+
persist: false,
|
|
486
|
+
...(options?.onNotice ? { onNotice: options.onNotice } : {}),
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
async #handleBlob(blob: Blob | undefined): Promise<void> {
|
|
491
|
+
const device = this.#running?.blob;
|
|
492
|
+
if (blob === undefined) {
|
|
493
|
+
device?.setReadSource(undefined);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (device === undefined) {
|
|
497
|
+
throw new UnsupportedFeatureError(
|
|
498
|
+
`The "${this.build.name}" Postgres build has no /dev/blob device, so the \`blob\` query option is not available.`,
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
device.setReadSource(new Uint8Array(await blob.arrayBuffer()));
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
#cleanupBlob(): void {
|
|
505
|
+
this.#running?.blob?.setReadSource(undefined);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
#takeWrittenBlob(): Blob | undefined {
|
|
509
|
+
const chunks = this.#running?.blob?.takeWritten();
|
|
510
|
+
return chunks === undefined ? undefined : new Blob(chunks);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
#serializeParams(
|
|
514
|
+
params: readonly unknown[],
|
|
515
|
+
dataTypeIDs: readonly number[],
|
|
516
|
+
options?: QueryOptions,
|
|
517
|
+
): (string | null)[] {
|
|
518
|
+
return params.map((param, index) => {
|
|
519
|
+
if (param === null || param === undefined) return null;
|
|
520
|
+
const oid = dataTypeIDs[index] ?? 0;
|
|
521
|
+
const serializer = options?.serializers?.[oid] ?? this.#serializers[oid];
|
|
522
|
+
return serializer ? serializer(param) : toText(param);
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
async #runQuery<T>(sql: string, params: readonly unknown[] = [], options?: QueryOptions): Promise<Results<T>> {
|
|
527
|
+
return await this.#runExclusiveQuery(async () => {
|
|
528
|
+
this.#log("runQuery", sql, params, options);
|
|
529
|
+
await this.#handleBlob(options?.blob);
|
|
530
|
+
let results: BackendMessage[] = [];
|
|
531
|
+
try {
|
|
532
|
+
const parsed = await this.#execNoPersist(
|
|
533
|
+
serialize.parse({ text: sql, ...(options?.paramTypes ? { types: options.paramTypes } : {}) }),
|
|
534
|
+
options,
|
|
535
|
+
);
|
|
536
|
+
const dataTypeIDs = parseDescribeStatementResults(
|
|
537
|
+
await this.#execNoPersist(serialize.describe({ type: "S" }), options),
|
|
538
|
+
);
|
|
539
|
+
const values = this.#serializeParams(params, dataTypeIDs, options);
|
|
540
|
+
results = [
|
|
541
|
+
...parsed,
|
|
542
|
+
...(await this.#execNoPersist(serialize.bind({ values }), options)),
|
|
543
|
+
...(await this.#execNoPersist(serialize.describe({ type: "P" }), options)),
|
|
544
|
+
...(await this.#execNoPersist(serialize.execute({}), options)),
|
|
545
|
+
];
|
|
546
|
+
} catch (error) {
|
|
547
|
+
if (error instanceof DatabaseError) {
|
|
548
|
+
throw makeQueryError({ error, query: sql, params, options });
|
|
549
|
+
}
|
|
550
|
+
throw error;
|
|
551
|
+
} finally {
|
|
552
|
+
results.push(...(await this.#execNoPersist(serialize.sync(), options)));
|
|
553
|
+
}
|
|
554
|
+
this.#cleanupBlob();
|
|
555
|
+
if (!this.#inTransaction) await this.#persistAfterStatement();
|
|
556
|
+
const blob = this.#takeWrittenBlob();
|
|
557
|
+
// The row type is the caller's assertion, as with any driver.
|
|
558
|
+
return parseResults(results, this.#parsers, options, blob)[0] as Results<T>;
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async #runExec(sql: string, options?: QueryOptions): Promise<Results[]> {
|
|
563
|
+
return await this.#runExclusiveQuery(async () => {
|
|
564
|
+
this.#log("runExec", sql, options);
|
|
565
|
+
await this.#handleBlob(options?.blob);
|
|
566
|
+
let results: BackendMessage[] = [];
|
|
567
|
+
try {
|
|
568
|
+
results = await this.#execNoPersist(serialize.query(sql), options);
|
|
569
|
+
} catch (error) {
|
|
570
|
+
if (error instanceof DatabaseError) {
|
|
571
|
+
throw makeQueryError({ error, query: sql, params: undefined, options });
|
|
572
|
+
}
|
|
573
|
+
throw error;
|
|
574
|
+
} finally {
|
|
575
|
+
results.push(...(await this.#execNoPersist(serialize.sync(), options)));
|
|
576
|
+
}
|
|
577
|
+
this.#cleanupBlob();
|
|
578
|
+
if (!this.#inTransaction) await this.#persistAfterStatement();
|
|
579
|
+
const blob = this.#takeWrittenBlob();
|
|
580
|
+
return parseResults(results, this.#parsers, options, blob) as Results[];
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
async query<T = Record<string, unknown>>(
|
|
585
|
+
sql: string,
|
|
586
|
+
params?: readonly unknown[],
|
|
587
|
+
options?: QueryOptions,
|
|
588
|
+
): Promise<Results<T>> {
|
|
589
|
+
await this.#checkReady();
|
|
590
|
+
// One statement at a time, never inside another caller's transaction.
|
|
591
|
+
return await this.#transactionMutex.runExclusive(() => this.#runQuery<T>(sql, params, options));
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
async sql<T = Record<string, unknown>>(sqlStrings: TemplateStringsArray, ...params: unknown[]): Promise<Results<T>> {
|
|
595
|
+
const { query, params: actualParams } = queryTemplate(sqlStrings, ...params);
|
|
596
|
+
return await this.query<T>(query, actualParams);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async exec(sql: string, options?: QueryOptions): Promise<Results[]> {
|
|
600
|
+
await this.#checkReady();
|
|
601
|
+
return await this.#transactionMutex.runExclusive(() => this.#runExec(sql, options));
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
async transaction<T>(callback: (tx: Transaction) => Promise<T>): Promise<T> {
|
|
605
|
+
await this.#checkReady();
|
|
606
|
+
return await this.#transactionMutex.runExclusive(async () => {
|
|
607
|
+
await this.#runExec("BEGIN");
|
|
608
|
+
this.#inTransaction = true;
|
|
609
|
+
|
|
610
|
+
// A transaction handle throws once its transaction has ended.
|
|
611
|
+
let closed = false;
|
|
612
|
+
const checkClosed = () => {
|
|
613
|
+
if (closed) throw new PgwasmError("Transaction is closed");
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
const tx: Transaction = {
|
|
617
|
+
query: async <R>(sql: string, params?: readonly unknown[], options?: QueryOptions) => {
|
|
618
|
+
checkClosed();
|
|
619
|
+
return await this.#runQuery<R>(sql, params, options);
|
|
620
|
+
},
|
|
621
|
+
sql: async <R>(sqlStrings: TemplateStringsArray, ...params: unknown[]) => {
|
|
622
|
+
checkClosed();
|
|
623
|
+
const { query, params: actualParams } = queryTemplate(sqlStrings, ...params);
|
|
624
|
+
return await this.#runQuery<R>(query, actualParams);
|
|
625
|
+
},
|
|
626
|
+
exec: async (sql: string, options?: QueryOptions) => {
|
|
627
|
+
checkClosed();
|
|
628
|
+
return await this.#runExec(sql, options);
|
|
629
|
+
},
|
|
630
|
+
rollback: async () => {
|
|
631
|
+
checkClosed();
|
|
632
|
+
await this.#runExec("ROLLBACK");
|
|
633
|
+
closed = true;
|
|
634
|
+
},
|
|
635
|
+
listen: async (channel: string, callback: (payload: string) => void) => {
|
|
636
|
+
checkClosed();
|
|
637
|
+
return await this.listen(channel, callback, tx);
|
|
638
|
+
},
|
|
639
|
+
get closed() {
|
|
640
|
+
return closed;
|
|
641
|
+
},
|
|
642
|
+
};
|
|
643
|
+
|
|
644
|
+
try {
|
|
645
|
+
const result = await callback(tx);
|
|
646
|
+
// Leave the in-transaction state before the terminal statement, so COMMIT persists like any
|
|
647
|
+
// top-level statement instead of waiting for some later query.
|
|
648
|
+
this.#inTransaction = false;
|
|
649
|
+
if (!closed) {
|
|
650
|
+
closed = true;
|
|
651
|
+
await this.#runExec("COMMIT");
|
|
652
|
+
} else {
|
|
653
|
+
// An explicit tx.rollback() ran inside the transaction; persist its outcome now.
|
|
654
|
+
await this.#persistAfterStatement();
|
|
655
|
+
}
|
|
656
|
+
return result;
|
|
657
|
+
} catch (error) {
|
|
658
|
+
this.#inTransaction = false;
|
|
659
|
+
if (!closed) {
|
|
660
|
+
closed = true;
|
|
661
|
+
await this.#runExec("ROLLBACK");
|
|
662
|
+
} else {
|
|
663
|
+
// The transaction ended without reaching a persist: an explicit rollback, or a COMMIT that
|
|
664
|
+
// threw. End at a persist boundary anyway, but never mask the original error with a persist
|
|
665
|
+
// failure; a failing storage reports again on the next statement.
|
|
666
|
+
try {
|
|
667
|
+
await this.#persistAfterStatement();
|
|
668
|
+
} catch {
|
|
669
|
+
// the original error takes precedence
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
throw error;
|
|
673
|
+
}
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
async runExclusive<T>(fn: () => Promise<T>): Promise<T> {
|
|
678
|
+
return await this.#runExclusiveQuery(fn);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** `/protocol`'s exclusive session: the transaction lock, then the query lock, for `fn`'s whole run. */
|
|
682
|
+
async #runExclusiveSession<T>(fn: () => Promise<T>): Promise<T> {
|
|
683
|
+
await this.#checkReady();
|
|
684
|
+
return await this.#transactionMutex.runExclusive(() =>
|
|
685
|
+
this.#queryMutex.runExclusive(async () => {
|
|
686
|
+
this.#checkOpenState();
|
|
687
|
+
this.#checkPersistLatch();
|
|
688
|
+
return await fn();
|
|
689
|
+
}),
|
|
690
|
+
);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ─── array types ─────────────────────────────────────────────────────────────
|
|
694
|
+
|
|
695
|
+
async #initArrayTypes({ force = false } = {}): Promise<void> {
|
|
696
|
+
if (this.#arrayTypesInitialized && !force) return;
|
|
697
|
+
this.#arrayTypesInitialized = true;
|
|
698
|
+
const types = await this.query<{ oid: number; typarray: number }>(`
|
|
699
|
+
SELECT b.oid, b.typarray
|
|
700
|
+
FROM pg_catalog.pg_type a
|
|
701
|
+
LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem
|
|
702
|
+
WHERE a.typcategory = 'A'
|
|
703
|
+
GROUP BY b.oid, b.typarray
|
|
704
|
+
ORDER BY b.oid
|
|
705
|
+
`);
|
|
706
|
+
for (const type of types.rows) {
|
|
707
|
+
this.#serializers[type.typarray] = (value) => arraySerializer(value, this.#serializers[type.oid], type.typarray);
|
|
708
|
+
this.#parsers[type.typarray] = (value) => arrayParser(value, this.#parsers[type.oid], type.typarray);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
async refreshArrayTypes(): Promise<void> {
|
|
713
|
+
await this.#initArrayTypes({ force: true });
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// ─── notifications ───────────────────────────────────────────────────────────
|
|
717
|
+
|
|
718
|
+
// Lock order: the transaction lock, then the listen lock, then the query lock. A transaction's
|
|
719
|
+
// tx.listen() runs with the transaction lock already held, so a top-level listen must take the
|
|
720
|
+
// transaction lock before the listen lock too, or each would hold the lock the other waits for.
|
|
721
|
+
|
|
722
|
+
async listen(
|
|
723
|
+
channel: string,
|
|
724
|
+
callback: (payload: string) => void,
|
|
725
|
+
tx?: Transaction,
|
|
726
|
+
): Promise<(tx?: Transaction) => Promise<void>> {
|
|
727
|
+
return await this.#withListenLocks(tx, (exec) => this.#subscribe(channel, callback, exec));
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async unlisten(channel: string, callback?: (payload: string) => void, tx?: Transaction): Promise<void> {
|
|
731
|
+
await this.#withListenLocks(tx, (exec) => this.#unsubscribe(channel, callback, exec));
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
async #withListenLocks<T>(
|
|
735
|
+
tx: Transaction | undefined,
|
|
736
|
+
fn: (exec: (sql: string) => Promise<unknown>) => Promise<T>,
|
|
737
|
+
): Promise<T> {
|
|
738
|
+
if (tx) return await this.#listenMutex.runExclusive(() => fn((sql) => tx.exec(sql)));
|
|
739
|
+
await this.#checkReady();
|
|
740
|
+
return await this.#transactionMutex.runExclusive(() =>
|
|
741
|
+
this.#listenMutex.runExclusive(() => fn((sql) => this.#runExec(sql))),
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
async #subscribe(
|
|
746
|
+
channel: string,
|
|
747
|
+
callback: (payload: string) => void,
|
|
748
|
+
exec: (sql: string) => Promise<unknown>,
|
|
749
|
+
): Promise<(tx?: Transaction) => Promise<void>> {
|
|
750
|
+
const pgChannel = toPostgresName(channel);
|
|
751
|
+
let listeners = this.#notifyListeners.get(pgChannel);
|
|
752
|
+
if (!listeners) {
|
|
753
|
+
listeners = new Set();
|
|
754
|
+
this.#notifyListeners.set(pgChannel, listeners);
|
|
755
|
+
}
|
|
756
|
+
listeners.add(callback);
|
|
757
|
+
try {
|
|
758
|
+
await exec(`LISTEN ${channel}`);
|
|
759
|
+
} catch (error) {
|
|
760
|
+
listeners.delete(callback);
|
|
761
|
+
if (listeners.size === 0) this.#notifyListeners.delete(pgChannel);
|
|
762
|
+
throw error;
|
|
763
|
+
}
|
|
764
|
+
// By the channel as the caller wrote it: unlisten() normalises it the same way listen() did.
|
|
765
|
+
return async (unlistenTx?: Transaction) => {
|
|
766
|
+
await this.unlisten(channel, callback, unlistenTx);
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
async #unsubscribe(
|
|
771
|
+
channel: string,
|
|
772
|
+
callback: ((payload: string) => void) | undefined,
|
|
773
|
+
exec: (sql: string) => Promise<unknown>,
|
|
774
|
+
): Promise<void> {
|
|
775
|
+
const pgChannel = toPostgresName(channel);
|
|
776
|
+
const cleanUp = async () => {
|
|
777
|
+
await exec(`UNLISTEN ${channel}`);
|
|
778
|
+
// Another caller may have subscribed while UNLISTEN ran.
|
|
779
|
+
if (this.#notifyListeners.get(pgChannel)?.size === 0) this.#notifyListeners.delete(pgChannel);
|
|
780
|
+
};
|
|
781
|
+
if (callback) {
|
|
782
|
+
this.#notifyListeners.get(pgChannel)?.delete(callback);
|
|
783
|
+
if (this.#notifyListeners.get(pgChannel)?.size === 0) await cleanUp();
|
|
784
|
+
} else {
|
|
785
|
+
await cleanUp();
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
onNotification(callback: (channel: string, payload: string) => void): () => void {
|
|
790
|
+
this.#globalNotifyListeners.add(callback);
|
|
791
|
+
return () => {
|
|
792
|
+
this.#globalNotifyListeners.delete(callback);
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// ─── backups ─────────────────────────────────────────────────────────────────
|
|
797
|
+
|
|
798
|
+
/**
|
|
799
|
+
* A Store backup. It reads the data directory under the query lock, so no statement runs during the
|
|
800
|
+
* read; do not call it from inside `runExclusive`.
|
|
801
|
+
*/
|
|
802
|
+
async dumpDataDir(compression?: DumpCompression): Promise<File> {
|
|
803
|
+
await this.#checkReady();
|
|
804
|
+
const running = this.#running;
|
|
805
|
+
if (running === undefined) throw new PgwasmClosedError("closed");
|
|
806
|
+
const entries = await this.#queryMutex.runExclusive(async () => {
|
|
807
|
+
this.#checkOpenState();
|
|
808
|
+
return await running.readEntries();
|
|
809
|
+
});
|
|
810
|
+
return await writeDataDirArchive(entries, backupBaseName(this.storage), compression);
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// ─── close ───────────────────────────────────────────────────────────────────
|
|
814
|
+
|
|
815
|
+
async close(): Promise<void> {
|
|
816
|
+
await this.#checkReady();
|
|
817
|
+
this.#closing = true;
|
|
818
|
+
// After a failure the build is in an unknown state: running its shutdown or persisting what it left
|
|
819
|
+
// would build on it. Close then only releases resources, and reports the failure it closed on.
|
|
820
|
+
const failure = this.#failure;
|
|
821
|
+
const running = this.#running;
|
|
822
|
+
const session = this.#session;
|
|
823
|
+
let closeFailure: { error: unknown } | undefined;
|
|
824
|
+
let finalPersistFailure: { error: unknown } | undefined;
|
|
825
|
+
try {
|
|
826
|
+
await this.#transactionMutex.runExclusive(() =>
|
|
827
|
+
this.#queryMutex.runExclusive(async () => {
|
|
828
|
+
for (const closeFn of this.#extensionsClose) {
|
|
829
|
+
try {
|
|
830
|
+
await closeFn();
|
|
831
|
+
} catch (error) {
|
|
832
|
+
closeFailure ??= { error };
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
if (failure || running === undefined) return;
|
|
836
|
+
try {
|
|
837
|
+
await session?.close();
|
|
838
|
+
await running.shutdown();
|
|
839
|
+
} catch (error) {
|
|
840
|
+
closeFailure ??= { error };
|
|
841
|
+
}
|
|
842
|
+
// Persist shutdown's writes strictly. A successful final persist also recovers a prior
|
|
843
|
+
// background failure.
|
|
844
|
+
try {
|
|
845
|
+
await this.#persistMutex.runExclusive(() => running.persist(false));
|
|
846
|
+
this.#persistFailure = undefined;
|
|
847
|
+
} catch (error) {
|
|
848
|
+
finalPersistFailure = { error };
|
|
849
|
+
this.#persistFailure = { error };
|
|
850
|
+
}
|
|
851
|
+
}),
|
|
852
|
+
);
|
|
853
|
+
} finally {
|
|
854
|
+
try {
|
|
855
|
+
// A background persist may still be running: a close after a failure skips the final persist
|
|
856
|
+
// that would otherwise queue behind it. Releasing tears its storage down under it, so wait first.
|
|
857
|
+
await this.#persistMutex.runExclusive(async () => {});
|
|
858
|
+
// Release even when shutdown or persisting failed, so exclusive storage ownership is released.
|
|
859
|
+
await running?.release();
|
|
860
|
+
} finally {
|
|
861
|
+
this.#closed = true;
|
|
862
|
+
this.#closing = false;
|
|
863
|
+
this.#ready = false;
|
|
864
|
+
this.#session = undefined;
|
|
865
|
+
this.#running = undefined;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
if (failure) throw failure.error;
|
|
869
|
+
if (finalPersistFailure) throw finalPersistFailure.error;
|
|
870
|
+
if (closeFailure) throw closeFailure.error;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
async [Symbol.asyncDispose](): Promise<void> {
|
|
874
|
+
await this.close();
|
|
875
|
+
}
|
|
876
|
+
}
|