@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,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The seam between pgwasm and a Postgres build (ADR-0062 decision 3).
|
|
3
|
+
*
|
|
4
|
+
* pgwasm owns everything above the wire protocol once: queries, transactions, notifications, live
|
|
5
|
+
* queries, the persist scheduler, the failure latch, the backup format and the build marker. A build
|
|
6
|
+
* provides a boot in two phases (mount storage, then start Postgres), a byte channel per session, and a
|
|
7
|
+
* record of its capabilities. Anything that differs between builds is a capability; shared code never
|
|
8
|
+
* tests a build's name.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { BaseFilesystem } from "../fs/base-filesystem";
|
|
12
|
+
|
|
13
|
+
/** pgwasm's log level, passed through to the build. */
|
|
14
|
+
export type DebugLevel = 0 | 1 | 2 | 3 | 4 | 5;
|
|
15
|
+
|
|
16
|
+
/** Who a build is. Recorded in every data directory it creates (ADR-0063 decision 1). */
|
|
17
|
+
export interface BuildIdentity {
|
|
18
|
+
/** Stable name, never renamed; the `storage.build` vocabulary: `"c"`, later `"pgrust"`. */
|
|
19
|
+
readonly name: string;
|
|
20
|
+
/** On-disk compatibility version. A data directory opens only under the same name AND format. */
|
|
21
|
+
readonly dataFormat: number;
|
|
22
|
+
/**
|
|
23
|
+
* Whether a data directory WITHOUT a marker is this build's. True for the C build only: every data
|
|
24
|
+
* directory made before builds were marked was made by it (ADR-0063).
|
|
25
|
+
*/
|
|
26
|
+
readonly claimsUnmarkedDirectories: boolean;
|
|
27
|
+
/** Informational release label, never compared. */
|
|
28
|
+
readonly release: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The storage kinds pgwasm knows. A build lists the ones it mounts. */
|
|
32
|
+
export type FilesystemKind = "memory" | "idb" | "file" | "vfs";
|
|
33
|
+
|
|
34
|
+
/** Everything that differs between builds, as data. */
|
|
35
|
+
export interface BuildCapabilities {
|
|
36
|
+
/** How many sessions `openSession()` hands out at once. */
|
|
37
|
+
readonly sessions: number;
|
|
38
|
+
/** Needs a cross-origin-isolated context (SharedArrayBuffer) in a browser. */
|
|
39
|
+
readonly requiresCrossOriginIsolation: boolean;
|
|
40
|
+
/** The storage kinds `boot()` accepts. */
|
|
41
|
+
readonly filesystems: readonly FilesystemKind[];
|
|
42
|
+
/**
|
|
43
|
+
* Whether `exchange()` completes inside the call in this context. A tool that bridges a blocking wasm
|
|
44
|
+
* callback to the wire (pg_dump) needs it.
|
|
45
|
+
*/
|
|
46
|
+
readonly synchronousExchange: boolean;
|
|
47
|
+
/** Whether `COPY … FROM/TO '/dev/blob'` works (the `blob` query option). */
|
|
48
|
+
readonly blobDevice: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Where a data directory lives, as pgwasm resolved it from `dataDir` / `fs`. */
|
|
52
|
+
export type StorageRequest =
|
|
53
|
+
| { readonly kind: "memory" }
|
|
54
|
+
| { readonly kind: "idb"; readonly name: string }
|
|
55
|
+
| { readonly kind: "file"; readonly path: string }
|
|
56
|
+
| { readonly kind: "vfs"; readonly vfs: BaseFilesystem };
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Files a build installs before Postgres starts, shipped by a build package (for example
|
|
60
|
+
* `@pgxsinkit/pgwasm-c/contrib/amcheck`). Pass it in `extensions` like any other extension.
|
|
61
|
+
*/
|
|
62
|
+
export interface ServerExtension {
|
|
63
|
+
readonly kind: "server";
|
|
64
|
+
readonly name: string;
|
|
65
|
+
/** The {@link BuildIdentity.name} it was compiled for; another build refuses it before boot. */
|
|
66
|
+
readonly build: string;
|
|
67
|
+
/** A gzipped tar of the extension's `lib/` and `share/` files. */
|
|
68
|
+
readonly bundle: URL;
|
|
69
|
+
readonly sharedPreloadLibraries?: readonly string[];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* One entry of a data directory. `path` is relative to the data directory with a leading `/`
|
|
74
|
+
* (`/PG_VERSION`, `/base/1/1259`): the layout Store backups have always had.
|
|
75
|
+
*/
|
|
76
|
+
export interface DataDirEntry {
|
|
77
|
+
readonly path: string;
|
|
78
|
+
readonly type: "file" | "directory";
|
|
79
|
+
/** Permission bits. */
|
|
80
|
+
readonly mode: number;
|
|
81
|
+
readonly mtimeSeconds: number;
|
|
82
|
+
/** The file's bytes; empty for a directory. */
|
|
83
|
+
readonly data: Uint8Array;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface BootRequest {
|
|
87
|
+
readonly storage: StorageRequest;
|
|
88
|
+
readonly extensions: readonly ServerExtension[];
|
|
89
|
+
readonly user: string;
|
|
90
|
+
readonly database: string;
|
|
91
|
+
readonly debug: DebugLevel;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A compiled Postgres, as pgwasm drives it. */
|
|
95
|
+
export interface PostgresBuild {
|
|
96
|
+
readonly identity: BuildIdentity;
|
|
97
|
+
readonly capabilities: BuildCapabilities;
|
|
98
|
+
/**
|
|
99
|
+
* Optional: settles once everything a {@link boot} would wait on before its own work is ready (artefacts
|
|
100
|
+
* fetched and compiled ahead, e.g. by a warm started on an earlier screen). A caller that times a boot
|
|
101
|
+
* awaits it first, so the timing measures the boot, never an unfinished warm. Never rejects: a failed
|
|
102
|
+
* warm means the build loads its artefacts itself during the boot.
|
|
103
|
+
*/
|
|
104
|
+
prepare?(): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Boot, phase 1: bring the host up and mount the storage (IndexedDB read in, a filesystem initially
|
|
107
|
+
* synced). When this resolves, Postgres has not run and nothing in the data directory was written.
|
|
108
|
+
*/
|
|
109
|
+
boot(request: BootRequest): Promise<MountedDataDirectory>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Phase 1 of a boot: storage is mounted, Postgres has not started. */
|
|
113
|
+
export interface MountedDataDirectory {
|
|
114
|
+
/** A file in the data directory, or `undefined` when it does not exist. Never writes. */
|
|
115
|
+
readFile(path: string): Promise<Uint8Array | undefined>;
|
|
116
|
+
/** Create a fresh cluster (initdb) in an empty data directory. */
|
|
117
|
+
createCluster(): Promise<void>;
|
|
118
|
+
/** Write a data-directory image into an empty data directory (a restore, a seed). */
|
|
119
|
+
writeEntries(entries: readonly DataDirEntry[]): Promise<void>;
|
|
120
|
+
/** Write one file into the data directory. */
|
|
121
|
+
writeFile(path: string, data: Uint8Array): Promise<void>;
|
|
122
|
+
/** Strictly persist everything written so far. */
|
|
123
|
+
persist(): Promise<void>;
|
|
124
|
+
/** Boot, phase 2: start Postgres. */
|
|
125
|
+
start(options: StartOptions): Promise<RunningPostgres>;
|
|
126
|
+
/** Give up without starting: release the storage (locks, handles) and the host. */
|
|
127
|
+
release(): Promise<void>;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface StartOptions {
|
|
131
|
+
/** Server settings (GUCs), `shared_preload_libraries` already merged. */
|
|
132
|
+
readonly settings: Readonly<Record<string, string>>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Phase 2 of a boot: Postgres is running. */
|
|
136
|
+
export interface RunningPostgres {
|
|
137
|
+
/** A session, already past startup. Calls beyond `capabilities.sessions` reject. */
|
|
138
|
+
openSession(): Promise<WireSession>;
|
|
139
|
+
/**
|
|
140
|
+
* Persist storage after a statement. pgwasm serializes calls and owns the policy: `relaxed` is a
|
|
141
|
+
* background persist whose failure pgwasm latches; `false` is awaited by the statement.
|
|
142
|
+
*/
|
|
143
|
+
persist(relaxed: boolean): Promise<void>;
|
|
144
|
+
/** Walk the data directory for a Store backup. pgwasm holds its query lock around the call. */
|
|
145
|
+
readEntries(): Promise<DataDirEntry[]>;
|
|
146
|
+
/** The `/dev/blob` device, present iff `capabilities.blobDevice`. */
|
|
147
|
+
readonly blob: BlobDevice | undefined;
|
|
148
|
+
/** Stop Postgres cleanly. Never called after a failure. */
|
|
149
|
+
shutdown(): Promise<void>;
|
|
150
|
+
/**
|
|
151
|
+
* Release the storage and the host. Always the last call, after a failure too. `afterFailedBoot` is
|
|
152
|
+
* set when the boot failed after `start()` (a filesystem gets `cleanupFailedInit` instead of `closeFs`).
|
|
153
|
+
*/
|
|
154
|
+
release(options?: { readonly afterFailedBoot?: boolean }): Promise<void>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** One session's byte channel carrying the wire protocol. */
|
|
158
|
+
export interface WireSession {
|
|
159
|
+
/**
|
|
160
|
+
* Send frontend bytes and stream every byte of the COMPLETE reply into `onData`; settle when it is
|
|
161
|
+
* complete. A build on a real wire frames the reply itself (a Flush after a non-terminal message, then
|
|
162
|
+
* read to its terminator). Returns `undefined` when it completed synchronously, which it always does
|
|
163
|
+
* when `capabilities.synchronousExchange`. A chunk is only valid during the callback: copy it to keep
|
|
164
|
+
* it. A throw is a failure of the build, never an SQL error (those arrive in-band as ErrorResponse),
|
|
165
|
+
* and pgwasm fails the instance. A message starting with a 0 byte is a startup packet.
|
|
166
|
+
*/
|
|
167
|
+
exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void | Promise<void>;
|
|
168
|
+
/** Set by pgwasm: backend bytes that arrive between exchanges (another session's NOTIFY). */
|
|
169
|
+
onUnsolicited: ((chunk: Uint8Array) => void) | undefined;
|
|
170
|
+
close(): Promise<void>;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The `COPY … '/dev/blob'` device. */
|
|
174
|
+
export interface BlobDevice {
|
|
175
|
+
/** What `COPY … FROM '/dev/blob'` reads, or `undefined` to clear it. */
|
|
176
|
+
setReadSource(data: Uint8Array | undefined): void;
|
|
177
|
+
/** What `COPY … TO '/dev/blob'` wrote since the last call, or `undefined` when nothing was. */
|
|
178
|
+
takeWritten(): Uint8Array<ArrayBuffer>[] | undefined;
|
|
179
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
/**
|
|
5
|
+
* Store backups: a data directory as a tarball (ADR-0035). pgwasm owns the format so every build
|
|
6
|
+
* produces the same artefact: ustar, entry names relative to the data directory with a leading `/`,
|
|
7
|
+
* a directory before its contents, optionally gzipped. Backups written by earlier releases restore.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { DataDirEntry } from "../build/seam";
|
|
11
|
+
import { BackupFormatError } from "../errors";
|
|
12
|
+
import type { DumpCompression } from "../interface";
|
|
13
|
+
import { gunzipIfCompressed, gzip } from "../tar/gzip";
|
|
14
|
+
import { readTar, TarFormatError, writeTar, type TarEntry } from "../tar/tar";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Normalize a backup member's name to a data-directory path: a leading `/`, no trailing `/`, no empty,
|
|
18
|
+
* `.` or `..` segments. A name that would leave the data directory is refused.
|
|
19
|
+
*/
|
|
20
|
+
export function normalizeDataDirPath(name: string): string {
|
|
21
|
+
const segments = name.split("/").filter((segment) => segment !== "" && segment !== ".");
|
|
22
|
+
if (segments.includes("..")) {
|
|
23
|
+
throw new BackupFormatError(`the backup member "${name}" points outside the data directory`);
|
|
24
|
+
}
|
|
25
|
+
return `/${segments.join("/")}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Read a Store backup (gzipped or not, whatever its MIME type or name says) into entries. */
|
|
29
|
+
export async function readDataDirArchive(archive: Blob): Promise<DataDirEntry[]> {
|
|
30
|
+
const bytes = await gunzipIfCompressed(new Uint8Array(await archive.arrayBuffer()));
|
|
31
|
+
let members: TarEntry[];
|
|
32
|
+
try {
|
|
33
|
+
members = readTar(bytes);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (error instanceof TarFormatError) {
|
|
36
|
+
throw new BackupFormatError(`the Store backup is not a readable tarball: ${error.message}`, { cause: error });
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
const entries: DataDirEntry[] = [];
|
|
41
|
+
for (const entry of members) {
|
|
42
|
+
const path = normalizeDataDirPath(entry.name);
|
|
43
|
+
if (path === "/") continue;
|
|
44
|
+
entries.push({ path, type: entry.type, mode: entry.mode, mtimeSeconds: entry.mtimeSeconds, data: entry.data });
|
|
45
|
+
}
|
|
46
|
+
return entries;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Write entries as a Store backup `File`, named `<baseName>.tar` or `<baseName>.tar.gz`. */
|
|
50
|
+
export async function writeDataDirArchive(
|
|
51
|
+
entries: readonly DataDirEntry[],
|
|
52
|
+
baseName: string,
|
|
53
|
+
compression: DumpCompression = "auto",
|
|
54
|
+
): Promise<File> {
|
|
55
|
+
const tarball = writeTar(
|
|
56
|
+
entries.map((entry) => ({
|
|
57
|
+
name: entry.path,
|
|
58
|
+
type: entry.type,
|
|
59
|
+
mode: entry.mode,
|
|
60
|
+
mtimeSeconds: entry.mtimeSeconds,
|
|
61
|
+
data: entry.data,
|
|
62
|
+
})),
|
|
63
|
+
);
|
|
64
|
+
if (compression === "none") {
|
|
65
|
+
return new File([tarball.slice()], `${baseName}.tar`, { type: "application/x-tar" });
|
|
66
|
+
}
|
|
67
|
+
return new File([await gzip(tarball)], `${baseName}.tar.gz`, { type: "application/x-gzip" });
|
|
68
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire-level access to a pgwasm instance, kept off its public type. `@pgxsinkit/pgwasm/protocol` and the
|
|
3
|
+
* `live` extension reach it through this registry; pgwasm is bundled with code splitting, so every
|
|
4
|
+
* entry point shares this one module and its map.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { BuildCapabilities } from "../build/seam";
|
|
8
|
+
import type { BackendMessage, NoticeMessage } from "../protocol/wire/messages";
|
|
9
|
+
|
|
10
|
+
export interface ExecProtocolOptions {
|
|
11
|
+
/** Persist storage after the message, as a statement does. Defaults to `true`. */
|
|
12
|
+
readonly persist?: boolean;
|
|
13
|
+
/** Throw the first ErrorResponse. Defaults to `true`. */
|
|
14
|
+
readonly throwOnError?: boolean;
|
|
15
|
+
readonly onNotice?: (notice: NoticeMessage) => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ExecProtocolStreamOptions {
|
|
19
|
+
/** Persist storage after the message. Defaults to `true`. */
|
|
20
|
+
readonly persist?: boolean;
|
|
21
|
+
/** Every backend byte, as it arrives. A chunk is only valid during the call: copy it to keep it. */
|
|
22
|
+
readonly onRawData: (data: Uint8Array) => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ExecProtocolResult {
|
|
26
|
+
readonly messages: BackendMessage[];
|
|
27
|
+
readonly data: Uint8Array;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What `protocol(pg)` returns. */
|
|
31
|
+
export interface PgwasmProtocol {
|
|
32
|
+
/** Run frontend message bytes; the parsed backend messages and the raw reply. */
|
|
33
|
+
execProtocol(message: Uint8Array, options?: ExecProtocolOptions): Promise<ExecProtocolResult>;
|
|
34
|
+
/** Run frontend message bytes; the parsed backend messages only. */
|
|
35
|
+
execProtocolStream(message: Uint8Array, options?: ExecProtocolOptions): Promise<BackendMessage[]>;
|
|
36
|
+
/** Run frontend message bytes; the raw reply. Notifications and errors are still dispatched. */
|
|
37
|
+
execProtocolRaw(message: Uint8Array, options?: Pick<ExecProtocolOptions, "persist">): Promise<Uint8Array>;
|
|
38
|
+
/**
|
|
39
|
+
* Run frontend message bytes and stream the raw reply. When nothing is pending and the build has
|
|
40
|
+
* `synchronousExchange`, the whole reply is delivered before this call returns its promise — what a
|
|
41
|
+
* tool driving it from inside a blocking wasm callback (pg_dump) needs.
|
|
42
|
+
*/
|
|
43
|
+
execProtocolRawStream(message: Uint8Array, options: ExecProtocolStreamOptions): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Run `fn` with the database's session to itself, for a tool whose exchanges must not interleave with
|
|
46
|
+
* anything else (pg_dump). It waits for, then holds, the locks a `transaction()` holds, and the query
|
|
47
|
+
* lock: no query, exec, transaction, listen, live-query refresh or Store backup of this database runs
|
|
48
|
+
* until `fn` settles.
|
|
49
|
+
*
|
|
50
|
+
* What `fn` sends with the `execProtocol*` methods is its own responsibility: no transaction is begun
|
|
51
|
+
* or ended around it, and a message is persisted only as its options say. Inside `fn`, use only these
|
|
52
|
+
* wire methods: the database's query methods wait for the locks `fn` holds, so awaiting one deadlocks.
|
|
53
|
+
*/
|
|
54
|
+
runExclusiveSession<T>(fn: () => Promise<T>): Promise<T>;
|
|
55
|
+
/** The build's capabilities, e.g. to check `synchronousExchange` before relying on it. */
|
|
56
|
+
readonly capabilities: BuildCapabilities;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const registry = new WeakMap<object, PgwasmProtocol>();
|
|
60
|
+
|
|
61
|
+
export function registerProtocolAccess(pg: object, access: PgwasmProtocol): void {
|
|
62
|
+
registry.set(pg, access);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The wire-level access of a pgwasm instance. Throws for anything else. */
|
|
66
|
+
export function protocolAccessOf(pg: object): PgwasmProtocol {
|
|
67
|
+
const access = registry.get(pg);
|
|
68
|
+
if (access === undefined) {
|
|
69
|
+
throw new TypeError("Not a pgwasm instance (created by createPgwasm).");
|
|
70
|
+
}
|
|
71
|
+
return access;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The strict sync of a database whose data directory is an OPFS-repacked store, registered by
|
|
76
|
+
* `createOpfsPgwasm` and run by `strictSync(pg)` from `@pgxsinkit/pgwasm/opfs`.
|
|
77
|
+
*/
|
|
78
|
+
const strictSyncs = new WeakMap<object, () => void>();
|
|
79
|
+
|
|
80
|
+
export function registerStrictSync(pg: object, strictSync: () => void): void {
|
|
81
|
+
strictSyncs.set(pg, strictSync);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The registered strict sync of `pg`, or `undefined` when it has none (not an OPFS-repacked store). */
|
|
85
|
+
export function strictSyncOf(pg: object): (() => void) | undefined {
|
|
86
|
+
return strictSyncs.get(pg);
|
|
87
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The build marker (ADR-0063 decision 1, build permanence).
|
|
3
|
+
*
|
|
4
|
+
* pgwasm records the Postgres build in every data directory it creates, as the file `PGWASM_BUILD` in
|
|
5
|
+
* the data directory itself (next to `PG_VERSION`), so it works on every storage and travels inside
|
|
6
|
+
* every Store backup. Its content is one line of JSON:
|
|
7
|
+
*
|
|
8
|
+
* {"pgwasm":1,"build":"c","dataFormat":1}
|
|
9
|
+
*
|
|
10
|
+
* `pgwasm` is the marker's own format version; a newer one than this release knows is unreadable
|
|
11
|
+
* (fail closed). A directory without a marker predates marking: it is the C build's, which the build
|
|
12
|
+
* says through `claimsUnmarkedDirectories` rather than shared code naming a build. Existing unmarked
|
|
13
|
+
* directories are never backfilled; only a directory pgwasm creates gets a marker.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type { BuildIdentity, DataDirEntry } from "../build/seam";
|
|
17
|
+
import { BuildMarkerUnreadableError, BuildMismatchError, DataFormatMismatchError, type RecordedBuild } from "../errors";
|
|
18
|
+
|
|
19
|
+
/** The marker's path inside the data directory. */
|
|
20
|
+
export const BUILD_MARKER_PATH = "/PGWASM_BUILD";
|
|
21
|
+
/** Postgres' own version file: its presence means the directory holds a cluster. */
|
|
22
|
+
export const PG_VERSION_PATH = "/PG_VERSION";
|
|
23
|
+
|
|
24
|
+
const MARKER_FORMAT = 1;
|
|
25
|
+
|
|
26
|
+
const encoder = new TextEncoder();
|
|
27
|
+
const decoder = new TextDecoder();
|
|
28
|
+
|
|
29
|
+
/** The marker's bytes for a build. */
|
|
30
|
+
export function encodeBuildMarker(build: BuildIdentity): Uint8Array {
|
|
31
|
+
return encoder.encode(
|
|
32
|
+
`${JSON.stringify({ pgwasm: MARKER_FORMAT, build: build.name, dataFormat: build.dataFormat })}\n`,
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Parse a marker; throws {@link BuildMarkerUnreadableError} for anything but a valid one. */
|
|
37
|
+
export function decodeBuildMarker(bytes: Uint8Array): { build: string; dataFormat: number } {
|
|
38
|
+
const raw = decoder.decode(bytes);
|
|
39
|
+
let parsed: unknown;
|
|
40
|
+
try {
|
|
41
|
+
parsed = JSON.parse(raw);
|
|
42
|
+
} catch {
|
|
43
|
+
throw new BuildMarkerUnreadableError(raw, "not JSON");
|
|
44
|
+
}
|
|
45
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
46
|
+
throw new BuildMarkerUnreadableError(raw, "not a JSON object");
|
|
47
|
+
}
|
|
48
|
+
const { pgwasm, build, dataFormat } = parsed as Record<string, unknown>;
|
|
49
|
+
if (typeof pgwasm !== "number" || !Number.isInteger(pgwasm) || pgwasm < 1) {
|
|
50
|
+
throw new BuildMarkerUnreadableError(raw, "no marker format version");
|
|
51
|
+
}
|
|
52
|
+
if (pgwasm > MARKER_FORMAT) {
|
|
53
|
+
throw new BuildMarkerUnreadableError(raw, `marker format ${pgwasm} is newer than this pgwasm reads`);
|
|
54
|
+
}
|
|
55
|
+
if (typeof build !== "string" || build === "") {
|
|
56
|
+
throw new BuildMarkerUnreadableError(raw, "no build name");
|
|
57
|
+
}
|
|
58
|
+
if (typeof dataFormat !== "number" || !Number.isInteger(dataFormat) || dataFormat < 1) {
|
|
59
|
+
throw new BuildMarkerUnreadableError(raw, "no data format");
|
|
60
|
+
}
|
|
61
|
+
return { build, dataFormat };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Check what a data directory or backup records against the build about to open it. `marker` is the
|
|
66
|
+
* marker's bytes (absent when there is none); `hasCluster` is whether `PG_VERSION` exists. Throws the
|
|
67
|
+
* typed refusal when the build may not open it.
|
|
68
|
+
*/
|
|
69
|
+
export function checkBuildMarker(
|
|
70
|
+
build: BuildIdentity,
|
|
71
|
+
marker: Uint8Array | undefined,
|
|
72
|
+
hasCluster: boolean,
|
|
73
|
+
source: "data-directory" | "backup",
|
|
74
|
+
): void {
|
|
75
|
+
if (marker === undefined) {
|
|
76
|
+
if (hasCluster && !build.claimsUnmarkedDirectories) {
|
|
77
|
+
throw new BuildMismatchError(build, "unmarked", source);
|
|
78
|
+
}
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const recorded = decodeBuildMarker(marker);
|
|
82
|
+
if (recorded.build !== build.name) {
|
|
83
|
+
const found: RecordedBuild = recorded;
|
|
84
|
+
throw new BuildMismatchError(build, found, source);
|
|
85
|
+
}
|
|
86
|
+
if (recorded.dataFormat !== build.dataFormat) {
|
|
87
|
+
throw new DataFormatMismatchError(build, recorded.dataFormat, source);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The marker entry of a data-directory image, if it has one. */
|
|
92
|
+
export function findEntry(entries: readonly DataDirEntry[], path: string): DataDirEntry | undefined {
|
|
93
|
+
return entries.find((entry) => entry.path === path && entry.type === "file");
|
|
94
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A FIFO async mutex: `runExclusive` runs its callback once every earlier one has settled. Not
|
|
3
|
+
* re-entrant — a callback that waits on the same mutex deadlocks, as with any mutex.
|
|
4
|
+
*/
|
|
5
|
+
export class Mutex {
|
|
6
|
+
#tail: Promise<void> = Promise.resolve();
|
|
7
|
+
|
|
8
|
+
runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {
|
|
9
|
+
const run = this.#tail.then(fn);
|
|
10
|
+
this.#tail = run.then(
|
|
11
|
+
() => undefined,
|
|
12
|
+
() => undefined,
|
|
13
|
+
);
|
|
14
|
+
return run;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
/**
|
|
5
|
+
* The name Postgres stores for an identifier: a quoted one keeps its case (quotes removed), an
|
|
6
|
+
* unquoted one is folded to lower case. Used to key notification listeners the way Postgres names
|
|
7
|
+
* the channel.
|
|
8
|
+
*/
|
|
9
|
+
export function toPostgresName(input: string): string {
|
|
10
|
+
if (input.startsWith('"') && input.endsWith('"') && input.length >= 2) {
|
|
11
|
+
return input.slice(1, -1);
|
|
12
|
+
}
|
|
13
|
+
return input.toLowerCase();
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Quote an identifier for SQL: wrap in double quotes, doubling any inside. */
|
|
17
|
+
export function quoteIdentifier(name: string): string {
|
|
18
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A random 32-character hex id, for the names of temporary objects. */
|
|
22
|
+
export function randomId(): string {
|
|
23
|
+
const bytes = new Uint8Array(16);
|
|
24
|
+
crypto.getRandomValues(bytes);
|
|
25
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
26
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
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 { QueryOptions, Results, Row } from "../interface";
|
|
5
|
+
import {
|
|
6
|
+
CommandCompleteMessage,
|
|
7
|
+
DataRowMessage,
|
|
8
|
+
ParameterDescriptionMessage,
|
|
9
|
+
RowDescriptionMessage,
|
|
10
|
+
type BackendMessage,
|
|
11
|
+
} from "../protocol/wire/messages";
|
|
12
|
+
import { parseType, type Parser } from "../types";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Turn the backend messages of a simple or extended query into result sets, one per statement
|
|
16
|
+
* (https://www.postgresql.org/docs/current/protocol-flow.html).
|
|
17
|
+
*/
|
|
18
|
+
export function parseResults(
|
|
19
|
+
messages: readonly BackendMessage[],
|
|
20
|
+
defaultParsers: Readonly<Record<number | string, Parser>>,
|
|
21
|
+
options?: QueryOptions,
|
|
22
|
+
blob?: Blob,
|
|
23
|
+
): Results<unknown>[] {
|
|
24
|
+
const resultSets: Results<unknown>[] = [];
|
|
25
|
+
let current: Results<unknown> = { rows: [], fields: [] };
|
|
26
|
+
let affectedRows = 0;
|
|
27
|
+
const parsers = { ...defaultParsers, ...options?.parsers };
|
|
28
|
+
|
|
29
|
+
for (const message of messages) {
|
|
30
|
+
if (message instanceof RowDescriptionMessage) {
|
|
31
|
+
current.fields = message.fields.map((field) => ({ name: field.name, dataTypeID: field.dataTypeID }));
|
|
32
|
+
} else if (message instanceof DataRowMessage) {
|
|
33
|
+
const fields = current.fields;
|
|
34
|
+
const typeOf = (index: number) => fields[index]?.dataTypeID ?? 0;
|
|
35
|
+
if (options?.rowMode === "array") {
|
|
36
|
+
current.rows.push(message.fields.map((value, index) => parseType(value, typeOf(index), parsers)));
|
|
37
|
+
} else {
|
|
38
|
+
const row: Row = {};
|
|
39
|
+
message.fields.forEach((value, index) => {
|
|
40
|
+
row[fields[index]?.name ?? String(index)] = parseType(value, typeOf(index), parsers);
|
|
41
|
+
});
|
|
42
|
+
current.rows.push(row);
|
|
43
|
+
}
|
|
44
|
+
} else if (message instanceof CommandCompleteMessage) {
|
|
45
|
+
// A tag that carries a row count ends in it ("SELECT 2", "UPDATE 3", "INSERT 0 5"); the rest end
|
|
46
|
+
// in a word ("CREATE TABLE").
|
|
47
|
+
const parts = message.text.split(" ");
|
|
48
|
+
const command = parts[0] ?? "";
|
|
49
|
+
const rowCount = Number.parseInt(parts[parts.length - 1] ?? "", 10);
|
|
50
|
+
switch (command) {
|
|
51
|
+
case "INSERT":
|
|
52
|
+
case "UPDATE":
|
|
53
|
+
case "DELETE":
|
|
54
|
+
case "COPY":
|
|
55
|
+
case "MERGE":
|
|
56
|
+
affectedRows += rowCount;
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
const result: Results<unknown> = { ...current, command, affectedRows };
|
|
60
|
+
if (!Number.isNaN(rowCount)) result.rowCount = rowCount;
|
|
61
|
+
if (blob) result.blob = blob;
|
|
62
|
+
resultSets.push(result);
|
|
63
|
+
current = { rows: [], fields: [] };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (resultSets.length === 0) {
|
|
68
|
+
resultSets.push({ affectedRows: 0, rows: [], fields: [] });
|
|
69
|
+
}
|
|
70
|
+
return resultSets;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The parameter type OIDs from a Describe(statement) reply, when it has them. */
|
|
74
|
+
export function parseDescribeStatementResults(messages: readonly BackendMessage[]): number[] {
|
|
75
|
+
const message = messages.find(
|
|
76
|
+
(msg): msg is ParameterDescriptionMessage => msg instanceof ParameterDescriptionMessage,
|
|
77
|
+
);
|
|
78
|
+
return message ? message.dataTypeIDs : [];
|
|
79
|
+
}
|