@pgxsinkit/pgwasm-c 0.5.2 → 0.6.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,25 +12,25 @@
12
12
  /** The release the files are assets of. */
13
13
  export const ARTEFACT_RELEASE = {
14
14
  repository: "pgxsinkit/pgwasm-postgres",
15
- tag: "18.6.2",
16
- name: "pgwasm-postgres 18.6.2",
17
- commit: "bf7938ad6acd51e1f68a9cb14fee9fea879a3b48",
18
- upstream: { tag: "REL_18_6", commit: "724edf9bde9d356724ad384a2e196edc3c9f80f7" },
19
- dataFormat: 1,
15
+ tag: "19.0.0-rc.1",
16
+ name: "pgwasm-postgres 19.0.0-rc.1",
17
+ commit: "df4458a4fd3c0a546af29eb399bdfaa54eee70dd",
18
+ upstream: { tag: "REL_19_RC1", commit: "0b8bff042a997fe50fcd1c4c83b9ef1cc9ed8a89" },
19
+ dataFormat: 2,
20
20
  builderImage:
21
- "ghcr.io/pgxsinkit/pgwasm-builder@sha256:0c4d5255c5f1824216d1eb347cc231a6f881574c3d5b8172796a8cbe5f9f63c8",
22
- manifestSha256: "571b72a31003f89510f1bcbb37b5f70c142a5271cfdf24b7229423f9975d621d",
21
+ "ghcr.io/pgxsinkit/pgwasm-builder@sha256:cbb378a50de43cd2fbd8718b72ce4c7595ffe421148a3c32435906f096bc5130",
22
+ manifestSha256: "3451d5f8c0cc67c9dc8dd7d69862bebf81c700907f0a7d42860acc7a7548222a",
23
23
  } as const;
24
24
 
25
25
  /** Every pinned file, by its name in `artefacts/` (the release asset of the same name). */
26
26
  export const ARTEFACT_FILES = {
27
- "amcheck.tar.gz": { bytes: 21850, sha256: "6151f1f4ff507dd4401dc3dff9e5ad769727c2eb3d510e9fe75329bf52667c3f" },
28
- "initdb.js": { bytes: 106390, sha256: "a402bd734fda0faf36696b68324471f853d52bd248ab8219893a6344386f6fac" },
29
- "initdb.wasm": { bytes: 298938, sha256: "0fdc9cb46e2efe6dc1fc957c47c0c7364022c98d327eb8072af3f7fb75237d3e" },
30
- "postgres.data": { bytes: 6246509, sha256: "012a2ed052fc0a05d50b9920afb5cb1692b3fbf9e09d486da61e4a59bb8f249a" },
31
- "postgres.js": { bytes: 335115, sha256: "1bfb5740bd836121c0444d058593bbc7fa0de625596214a8e4805414191a23b2" },
32
- "postgres.wasm": { bytes: 9140085, sha256: "f2d217be96e05dd01c02a6b62e89110d3658ac5be6032fe1d28effc9348b15ac" },
33
- "prepopulated.tar.gz": { bytes: 4404457, sha256: "f5228a3690329edf675f630bedad6a4f6196f40c277f34aec3ac4d1ee426e0b3" },
27
+ "amcheck.tar.gz": { bytes: 21881, sha256: "200978d0b73e9d5b254088625f9975a61bbbfd584558d4b53acb8bc667f26a02" },
28
+ "initdb.js": { bytes: 105130, sha256: "cf3fff4109879f3be1ba321f19b126c4f8d518d9909846927d3104b1ec0a8129" },
29
+ "initdb.wasm": { bytes: 308968, sha256: "71b468843c8b75dea04a5c3775606ca8d0612f0d3240953159b44132d29e0015" },
30
+ "postgres.data": { bytes: 6330058, sha256: "be7b9fd708ddffcc627aefaff8fdc35310978d8f274a87046cfd232e306a861b" },
31
+ "postgres.js": { bytes: 336823, sha256: "49f427bd890b89ba5b29cf96e3032dcc13cbaf5aadf62b782290480317ea0178" },
32
+ "postgres.wasm": { bytes: 9451369, sha256: "3caccc979114e3ac7177a77bdc4511dab775738ea397bcdde04e6959ce682eb3" },
33
+ "prepopulated.tar.gz": { bytes: 4443562, sha256: "7542c86ecdb058aa18553087b28ebf155b6270773abfb206ddcb05a446266052" },
34
34
  } as const;
35
35
 
36
36
  export type ArtefactName = keyof typeof ARTEFACT_FILES;
package/src/build.ts CHANGED
@@ -24,16 +24,18 @@ import { fetchExtensionBundle, installExtensionFiles } from "./host/extensions";
24
24
  import { runInitdb } from "./host/initdb";
25
25
  import { mountFor, type StorageMount } from "./host/mounts";
26
26
  import { DEFAULT_START_PARAMS, PostgresInstance } from "./host/postgres-instance";
27
+ import { checkPostgresVersion } from "./postgres-version";
27
28
 
28
29
  /**
29
30
  * The C build's identity, recorded in every data directory it creates (ADR-0063). Its release and data
30
31
  * format are the pinned pgwasm-postgres release's (`bun run pgwasm:pin` writes both; ADR-0064): the
31
- * release is the build's name in version(), and `pgwasm:pin` refuses a release of another data format.
32
+ * release is the build's name in version(). Changing formats is an explicit fresh-store adoption;
33
+ * existing directories and backups still have to match this build's format and PostgreSQL major.
32
34
  */
33
35
  export const C_BUILD_IDENTITY: BuildIdentity = {
34
36
  name: "c",
35
37
  dataFormat: ARTEFACT_RELEASE.dataFormat,
36
- // Every data directory made before builds were recorded was made by this build.
38
+ // Unmarked directories are the C build's only when their PG_VERSION also matches (checked below).
37
39
  claimsUnmarkedDirectories: true,
38
40
  release: ARTEFACT_RELEASE.name,
39
41
  };
@@ -158,7 +160,13 @@ class CMountedDataDirectory implements MountedDataDirectory {
158
160
  }
159
161
 
160
162
  async readFile(path: string): Promise<Uint8Array | undefined> {
161
- return readDataDirFile(this.#FS, path);
163
+ const bytes = readDataDirFile(this.#FS, path);
164
+ // Shared boot checks a marked directory's build/format itself. Old unmarked directories have no
165
+ // such guard, so refuse another PostgreSQL major before they can reach startup or any write.
166
+ if (path === "/PG_VERSION" && bytes !== undefined && readDataDirFile(this.#FS, "/PGWASM_BUILD") === undefined) {
167
+ checkPostgresVersion(bytes);
168
+ }
169
+ return bytes;
162
170
  }
163
171
 
164
172
  async createCluster(): Promise<void> {
@@ -191,6 +199,11 @@ class CMountedDataDirectory implements MountedDataDirectory {
191
199
  }
192
200
 
193
201
  async writeEntries(entries: readonly DataDirEntry[]): Promise<void> {
202
+ // A legacy backup can have no build marker. Check its PostgreSQL version before writing even its
203
+ // first member: NODEFS writes immediately, and a later startup refusal cannot undo a partial restore.
204
+ const versions = entries.filter((entry) => entry.path === "/PG_VERSION" && entry.type === "file");
205
+ if (versions.length === 0) checkPostgresVersion(undefined);
206
+ for (const version of versions) checkPostgresVersion(version.data);
194
207
  writeDataDirEntries(this.#FS, entries);
195
208
  }
196
209
 
@@ -203,6 +216,7 @@ class CMountedDataDirectory implements MountedDataDirectory {
203
216
  }
204
217
 
205
218
  async start(options: StartOptions): Promise<RunningPostgres> {
219
+ checkPostgresVersion(readDataDirFile(this.#FS, "/PG_VERSION"));
206
220
  const log = (...args: unknown[]) => {
207
221
  if (this.#request.debug > 0) console.log(...args);
208
222
  };
@@ -235,9 +249,9 @@ export function createCBuild(options: CBuildOptions = {}): PostgresBuild {
235
249
  /**
236
250
  * @internal A C build on the given artefacts, recording the given identity: what {@link createCBuild}
237
251
  * builds on the pinned release's. Not exported from the package; the IndexedDB browser lane reaches it
238
- * from source to boot an earlier release's glue and files, so the stores that release wrote can be opened
239
- * by the current build (tests/e2e/pgwasm-idb/continuity-builds.ts). That list starts empty at 18.6.2: its
240
- * filesystem root changed, so no earlier release's stores open under it; 18.6.2 is the first entry.
252
+ * from source to boot earlier compatible releases' glue and files, then checks that the current build
253
+ * can reopen their stores (tests/e2e/pgwasm-idb/continuity-builds.ts). PG19's format-2 list starts empty:
254
+ * format-1 PG18 stores are explicitly refused, and future entries must preserve the PG19 host ABI too.
241
255
  */
242
256
  export function createCBuildFrom(
243
257
  identity: BuildIdentity,
@@ -124,27 +124,27 @@ export interface EmscriptenModuleBase {
124
124
  stringToUTF8OnStack(value: string): number;
125
125
  _fopen(path: number, mode: number): number;
126
126
  _fclose(stream: number): number;
127
- _pgl_set_system_fn(fn: number): void;
128
- _pgl_set_popen_fn(fn: number): void;
129
- _pgl_set_pclose_fn(fn: number): void;
130
- _pgl_freopen(path: number, mode: number, stream: number): number;
127
+ _pgwasm_set_system_fn(fn: number): void;
128
+ _pgwasm_set_popen_fn(fn: number): void;
129
+ _pgwasm_set_pclose_fn(fn: number): void;
130
+ _pgwasm_freopen(path: number, mode: number, stream: number): number;
131
131
  }
132
132
 
133
133
  /** The Postgres module (`postgres.js`). */
134
134
  export interface PostgresModule extends EmscriptenModuleBase {
135
135
  readonly PROXYFS: EmscriptenFilesystemType;
136
- _pgl_set_rw_cbs(readCallback: number, writeCallback: number): void;
137
- _pgl_pq_flush(): void;
138
- _pgl_setPGliteActive(value: number): number;
139
- _pgl_startPGlite(): void;
140
- _pgl_getMyProcPort(): number;
141
- _pgl_sendConnData(): void;
142
- _pgl_run_atexit_funcs(): void;
143
- _pgl_setPGliteExitStatus(status: number): number;
136
+ _pgwasm_set_rw_cbs(readCallback: number, writeCallback: number): void;
137
+ _pgwasm_pq_flush(): void;
138
+ _pgwasm_setPostgresActive(value: number): number;
139
+ _pgwasm_startPostgres(): void;
140
+ _pgwasm_getMyProcPort(): number;
141
+ _pgwasm_sendConnData(): void;
142
+ _pgwasm_run_atexit_funcs(): void;
143
+ _pgwasm_setPostgresExitStatus(status: number): number;
144
144
  _PostgresMainLoopOnce(): void;
145
145
  _PostgresMainLongJmp(): void;
146
146
  _PostgresSendReadyForQueryIfNecessary(): void;
147
- _ProcessStartupPacket(port: number, sslDone: boolean, gssDone: boolean): number;
147
+ _ProcessStartupPacket(port: number): number;
148
148
  _pq_buffer_remaining_data(): number;
149
149
  _emscripten_force_exit(status: number): void;
150
150
  }
@@ -120,17 +120,19 @@ export async function runInitdb({
120
120
  env["HOME"] = "/home/postgres";
121
121
  env["USER"] = "postgres";
122
122
  env["LOGNAME"] = "postgres";
123
+ // initdb writes the cluster's timezone defaults; match the backend even on a non-UTC host.
124
+ env["TZ"] = "UTC";
123
125
  env["ICU_DATA"] = ICU_DATA_PATH;
124
126
  },
125
127
  (module) => {
126
128
  module.onRuntimeInitialized = () => {
127
- module._pgl_set_system_fn(
129
+ module._pgwasm_set_system_fn(
128
130
  module.addFunction((command: number) => {
129
131
  postgresArgs = commandArgs(module, command);
130
132
  return callPgMain(postgresArgs);
131
133
  }, "pi"),
132
134
  );
133
- module._pgl_set_popen_fn(
135
+ module._pgwasm_set_popen_fn(
134
136
  module.addFunction((command: number, mode: number) => {
135
137
  const openMode = module.UTF8ToString(mode);
136
138
  postgresArgs = commandArgs(module, command);
@@ -145,7 +147,7 @@ export async function runInitdb({
145
147
  throw new Error(`Unexpected popen mode ${openMode}`);
146
148
  }, "ppi"),
147
149
  );
148
- module._pgl_set_pclose_fn(
150
+ module._pgwasm_set_pclose_fn(
149
151
  module.addFunction((stream: number) => {
150
152
  if (stream === initdbStdinFd || stream === initdbStdoutFd) {
151
153
  // A popen in "w" mode runs postgres' main once initdb has written its input.
@@ -159,8 +161,8 @@ export async function runInitdb({
159
161
  }, "pi"),
160
162
  );
161
163
  // The backend reads initdb's output and writes initdb's input through two files.
162
- pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDIN_PATH), pg.stringToUTF8OnStack("r"), 0);
163
- pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDOUT_PATH), pg.stringToUTF8OnStack("w"), 1);
164
+ pg._pgwasm_freopen(pg.stringToUTF8OnStack(PG_STDIN_PATH), pg.stringToUTF8OnStack("r"), 0);
165
+ pg._pgwasm_freopen(pg.stringToUTF8OnStack(PG_STDOUT_PATH), pg.stringToUTF8OnStack("w"), 1);
164
166
  initdbStdinFd = module._fopen(module.stringToUTF8OnStack(PG_STDOUT_PATH), module.stringToUTF8OnStack("r"));
165
167
  initdbStdoutFd = module._fopen(module.stringToUTF8OnStack(PG_STDIN_PATH), module.stringToUTF8OnStack("w"));
166
168
  };
@@ -8,9 +8,9 @@ import type { EmscriptenStream, ModuleOverrides, PostgresModule } from "./emscri
8
8
  import { preservingExitCode } from "./exit-code";
9
9
  import { ICU_DATA_PATH, INITDB_EXE_PATH, LOCALE_LIST_PATH, PGDATA, POSTGRES_EXE_PATH } from "./paths";
10
10
 
11
- /** Postgres' error longjmp, intercepted by the host: keep in sync with pglitec.c's POSTGRES_MAIN_LONGJMP. */
11
+ /** Postgres' error longjmp, intercepted by the host: keep in sync with pgwasmc.c's POSTGRES_MAIN_LONGJMP. */
12
12
  const POSTGRES_MAIN_LONGJMP = 100;
13
- /** The exit status single-user mode reports when it started and stays alive: the C build's `PGLITE_EXIT_ALIVE`. */
13
+ /** The exit status single-user mode reports when it started and stays alive: the C build's `PGWASM_EXIT_ALIVE`. */
14
14
  const PGWASM_EXIT_ALIVE = 99;
15
15
  const INITIAL_MEMORY_PAGES = 2048;
16
16
  const MAXIMUM_MEMORY_PAGES = 32768;
@@ -42,7 +42,7 @@ export const DEFAULT_START_PARAMS: readonly string[] = [
42
42
  /**
43
43
  * Whether `error` is one of the exceptions the Emscripten runtime throws on purpose to unwind the wasm
44
44
  * stack back to the main loop, which handles them:
45
- * - `'unwind'` from emscripten_exit_with_live_runtime(): how pgl_longjmp (pglitec.c) delivers Postgres'
45
+ * - `'unwind'` from emscripten_exit_with_live_runtime(): how pgwasm_longjmp (pgwasmc.c) delivers Postgres'
46
46
  * siglongjmp to its main-loop error handler, and how a Terminate message ends the loop;
47
47
  * - what an emscripten-mode longjmp throws, should one pass every invoke_* frame: an instance of the
48
48
  * glue's (unexported) `EmscriptenSjLj` class on Emscripten 6.0.10 (pgwasm-postgres 18.6.1 onwards), a
@@ -264,19 +264,19 @@ export class PostgresInstance {
264
264
  #onRuntimeInitialized(): void {
265
265
  const mod = this.module;
266
266
  // system() never runs a command: it is logged and fails.
267
- mod._pgl_set_system_fn(
267
+ mod._pgwasm_set_system_fn(
268
268
  this.#addFunction((command: number) => {
269
269
  this.#log(`Postgres tried to execute ${mod.UTF8ToString(command)}, returning 1.`);
270
270
  return 1;
271
271
  }, "pi"),
272
272
  );
273
- mod._pgl_set_popen_fn(
273
+ mod._pgwasm_set_popen_fn(
274
274
  this.#addFunction((command: number, mode: number) => {
275
275
  this.#externalCommandStream = this.#handleExternalCommand(mod.UTF8ToString(command), mod.UTF8ToString(mode));
276
276
  return this.#externalCommandStream;
277
277
  }, "ppp"),
278
278
  );
279
- mod._pgl_set_pclose_fn(
279
+ mod._pgwasm_set_pclose_fn(
280
280
  this.#addFunction((stream: number) => {
281
281
  if (stream !== this.#externalCommandStream) throw new Error(`Unhandled pclose ${stream}`);
282
282
  mod._fclose(stream);
@@ -295,7 +295,7 @@ export class PostgresInstance {
295
295
  this.#readOffset += length;
296
296
  return length;
297
297
  }, "iii");
298
- mod._pgl_set_rw_cbs(read, write);
298
+ mod._pgwasm_set_rw_cbs(read, write);
299
299
  }
300
300
 
301
301
  #handleExternalCommand(command: string, mode: string): number {
@@ -359,16 +359,16 @@ export class PostgresInstance {
359
359
  /** Start Postgres in single-user mode on the data directory. */
360
360
  startSingleMode(startParams: readonly string[]): void {
361
361
  const mod = this.module;
362
- mod._pgl_setPGliteActive(1);
362
+ mod._pgwasm_setPostgresActive(1);
363
363
  this.callMain([...startParams, "-D", PGDATA, mod.ENV["PGDATABASE"] ?? "postgres"]);
364
- const exitStatus = mod._pgl_setPGliteExitStatus(-3);
364
+ const exitStatus = mod._pgwasm_setPostgresExitStatus(-3);
365
365
  if (exitStatus !== PGWASM_EXIT_ALIVE) {
366
366
  const output = this.#stderr.join("\n").trim();
367
367
  throw new Error(
368
368
  `Postgres failed to start (single-user mode exit status ${exitStatus})${output ? `:\n${output}` : ""}`,
369
369
  );
370
370
  }
371
- mod._pgl_startPGlite();
371
+ mod._pgwasm_startPostgres();
372
372
  }
373
373
 
374
374
  /**
@@ -422,11 +422,11 @@ export class PostgresInstance {
422
422
 
423
423
  #processStartupPacket(): void {
424
424
  const mod = this.module;
425
- const result = this.#call(() => mod._ProcessStartupPacket(mod._pgl_getMyProcPort(), true, true));
425
+ const result = this.#call(() => mod._ProcessStartupPacket(mod._pgwasm_getMyProcPort()));
426
426
  if (result !== 0) throw new Error("Cannot process the startup packet");
427
427
  this.#call(() => {
428
- mod._pgl_sendConnData();
429
- mod._pgl_pq_flush();
428
+ mod._pgwasm_sendConnData();
429
+ mod._pgwasm_pq_flush();
430
430
  });
431
431
  }
432
432
 
@@ -443,7 +443,7 @@ export class PostgresInstance {
443
443
  // every frame it abandoned (see ShadowStack).
444
444
  this.#stack.restore(stack);
445
445
  if (!isEmscriptenUnwind(error)) throw error;
446
- if (mod._pgl_setPGliteExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {
446
+ if (mod._pgwasm_setPostgresExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {
447
447
  // Postgres raised an error: its siglongjmp into main was intercepted, and its error handling
448
448
  // runs here before the loop resumes with the rest of the batch.
449
449
  this.#call(() => mod._PostgresMainLongJmp());
@@ -452,7 +452,7 @@ export class PostgresInstance {
452
452
  }
453
453
  this.#call(() => {
454
454
  mod._PostgresSendReadyForQueryIfNecessary();
455
- mod._pgl_pq_flush();
455
+ mod._pgwasm_pq_flush();
456
456
  });
457
457
  } catch (error) {
458
458
  this.#failed = true;
@@ -465,8 +465,8 @@ export class PostgresInstance {
465
465
  const mod = this.module;
466
466
  try {
467
467
  preservingExitCode(() => {
468
- mod._pgl_setPGliteActive(0);
469
- this.#call(() => mod._pgl_run_atexit_funcs());
468
+ mod._pgwasm_setPostgresActive(0);
469
+ this.#call(() => mod._pgwasm_run_atexit_funcs());
470
470
  });
471
471
  } catch (error) {
472
472
  const exit = error as { name?: unknown; status?: unknown };
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { cBuildArtefacts } from "./artefacts";
2
2
  export { C_BUILD_IDENTITY, cBuild, createCBuild, type CBuildAssets, type CBuildOptions } from "./build";
3
3
  export { idbDatabaseName } from "./host/mounts/idb";
4
+ export { PostgresVersionMismatchError } from "./postgres-version";
@@ -0,0 +1,34 @@
1
+ import { PgwasmError } from "@pgxsinkit/pgwasm";
2
+
3
+ import { ARTEFACT_RELEASE } from "./artefact-pins";
4
+
5
+ /** PostgreSQL's major data-directory version, independent of pgwasm's build-marker format. */
6
+ export const C_POSTGRES_MAJOR = /^REL_(\d+)_/.exec(ARTEFACT_RELEASE.upstream.tag)?.[1];
7
+
8
+ /** The C host cannot open this PostgreSQL major; retrying cannot make the directory compatible. */
9
+ export class PostgresVersionMismatchError extends PgwasmError {
10
+ override name = "PostgresVersionMismatchError";
11
+ readonly expected: string;
12
+ readonly found: string | undefined;
13
+ /** Structured fields retained alongside the stable error name by the worker bridge. */
14
+ readonly detail: { readonly expected: string; readonly found: string | undefined };
15
+
16
+ constructor(expected: string, found: string | undefined) {
17
+ super(
18
+ `This C build requires PostgreSQL ${expected}, but the data directory's PG_VERSION is ` +
19
+ `${found === undefined ? "missing" : JSON.stringify(found)}. Use a separately named fresh PostgreSQL ${expected} store; ` +
20
+ "the existing directory is not migrated or replaced.",
21
+ );
22
+ this.expected = expected;
23
+ this.found = found;
24
+ this.detail = { expected, found };
25
+ }
26
+ }
27
+
28
+ /** Refuse another major before the C host writes a restored image or starts a mounted cluster. */
29
+ export function checkPostgresVersion(bytes: Uint8Array | undefined): void {
30
+ if (C_POSTGRES_MAJOR === undefined) throw new Error("The pinned C build has no PostgreSQL major version.");
31
+ const found = bytes === undefined ? undefined : new TextDecoder().decode(bytes).trim();
32
+ if (found === C_POSTGRES_MAJOR) return;
33
+ throw new PostgresVersionMismatchError(C_POSTGRES_MAJOR, found);
34
+ }