@hulla/db-postgres 0.3.2 → 0.3.4
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/README.md +6 -2
- package/dist/host-configuration.d.ts +9 -0
- package/dist/host-configuration.js +51 -0
- package/dist/index.js +1 -1
- package/dist/local-connection.d.ts +8 -0
- package/dist/local-connection.js +45 -0
- package/dist/native.d.ts +3 -0
- package/dist/native.js +44 -0
- package/dist/prepared-schema.d.ts +6 -0
- package/dist/prepared-schema.js +34 -0
- package/dist/serve.d.ts +2 -0
- package/dist/serve.js +37 -0
- package/dist/server-database.d.ts +32 -0
- package/dist/server-database.js +411 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +2 -0
- package/dist/service.d.ts +16 -0
- package/dist/service.js +200 -0
- package/package.json +21 -2
package/README.md
CHANGED
|
@@ -28,5 +28,9 @@ the adapter never starts a PostgreSQL server. Generation prepares server-only
|
|
|
28
28
|
settings without opening the instance, and evaluates environment URLs at hosting
|
|
29
29
|
time. Deploy the generated directory along with the application.
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
31
|
+
The package manager installs the matching native bridge, service and handler
|
|
32
|
+
executables as an optional dependency. Keep optional dependencies enabled
|
|
33
|
+
when installing for the deployment target.
|
|
34
|
+
Run `hulla-db-serve db/server.ts` to serve prepared artifacts in production.
|
|
35
|
+
Generation and local provisioning use the separate `@hulla/db-cli` package.
|
|
36
|
+
See the [deployment guide](https://github.com/hulladev/db/blob/main/docs/deployment.md).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type DatabaseConfig } from '@hulla/db/config';
|
|
2
|
+
/** Prepared settings evaluate runtime URLs without opening the application's instance. */
|
|
3
|
+
export declare function loadHostConfiguration(configPath: string): Promise<{
|
|
4
|
+
config: DatabaseConfig;
|
|
5
|
+
schemaPath: string;
|
|
6
|
+
schema: import("@hulla/db").SchemaDefinition<Readonly<Record<string, import("@hulla/db/schema").TableShape>>>;
|
|
7
|
+
directory: string;
|
|
8
|
+
prepared: boolean;
|
|
9
|
+
}>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { readFile } from 'node:fs/promises';
|
|
10
|
+
import { dirname, resolve } from 'node:path';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { defineConfig } from '@hulla/db/config';
|
|
13
|
+
import { exportedDatabase, exportedSchema } from '@hulla/db/internal/codegen';
|
|
14
|
+
import { preparedSchema } from './prepared-schema.js';
|
|
15
|
+
async function preparedHost(path) {
|
|
16
|
+
const prepared = await preparedSchema(path, 'postgres');
|
|
17
|
+
if (!prepared)
|
|
18
|
+
return undefined;
|
|
19
|
+
const host = resolve(prepared.directory, '_host.js');
|
|
20
|
+
const contents = await readFile(host, 'utf8').catch((error) => {
|
|
21
|
+
if (error.code === 'ENOENT')
|
|
22
|
+
throw new Error('Missing database host settings; run hulla-db generate before hosting this entrypoint');
|
|
23
|
+
throw error;
|
|
24
|
+
});
|
|
25
|
+
if (!contents.startsWith('// Generated by @hulla/db. Do not edit.\n'))
|
|
26
|
+
throw new TypeError('Expected generated database host settings');
|
|
27
|
+
const database = exportedDatabase(await import(__rewriteRelativeImportExtension(pathToFileURL(host).href)));
|
|
28
|
+
if (database.engine.name !== 'postgres')
|
|
29
|
+
throw new TypeError(`This host requires a postgres database; received ${database.engine.name}`);
|
|
30
|
+
return { ...prepared, connection: database.connection };
|
|
31
|
+
}
|
|
32
|
+
/** Prepared settings evaluate runtime URLs without opening the application's instance. */
|
|
33
|
+
export async function loadHostConfiguration(configPath) {
|
|
34
|
+
const path = resolve(configPath);
|
|
35
|
+
const direct = await preparedHost(path);
|
|
36
|
+
if (direct)
|
|
37
|
+
return {
|
|
38
|
+
config: defineConfig({ database: { server: direct.connection } }),
|
|
39
|
+
schemaPath: path, schema: direct.schema, directory: direct.directory, prepared: true,
|
|
40
|
+
};
|
|
41
|
+
const config = defineConfig((await import(__rewriteRelativeImportExtension(pathToFileURL(path).href))).default);
|
|
42
|
+
const schemaPath = resolve(dirname(path), config.schema ?? 'db/schema.ts');
|
|
43
|
+
const prepared = await preparedHost(schemaPath);
|
|
44
|
+
const settings = prepared ? defineConfig({ ...config, database: { ...config.database, server: { ...prepared.connection, ...config.database.server } } }) : config;
|
|
45
|
+
return {
|
|
46
|
+
config: settings, schemaPath,
|
|
47
|
+
schema: prepared?.schema ?? exportedSchema(await import(__rewriteRelativeImportExtension(pathToFileURL(schemaPath).href)), 'postgres'),
|
|
48
|
+
directory: prepared?.directory ?? resolve(dirname(schemaPath), '_generated'),
|
|
49
|
+
prepared: !!prepared,
|
|
50
|
+
};
|
|
51
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { postgresFactory } from "./descriptor.js";
|
|
2
2
|
export const postgres = postgresFactory(async (schema, settings, initialize) => {
|
|
3
|
-
const runtime = await import("
|
|
3
|
+
const runtime = await import("./server-database.js");
|
|
4
4
|
const connection = runtime.resolvePostgresConnection(settings);
|
|
5
5
|
if (initialize)
|
|
6
6
|
await runtime.initializeDatabase(schema, connection);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { DatabaseConnection, DatabaseSettings } from "@hulla/db/config";
|
|
2
|
+
/** Explicit settings win over the environment, including an invalid/empty URL. */
|
|
3
|
+
export declare function resolvePostgresConnection(connection: {
|
|
4
|
+
readonly url?: string | undefined;
|
|
5
|
+
readonly namespace?: string;
|
|
6
|
+
}): DatabaseConnection;
|
|
7
|
+
/** Imported by generated Node/Bun applications; file access must stay portable. */
|
|
8
|
+
export declare function resolveDatabaseConnection(connection: DatabaseSettings, configPath: string | URL): DatabaseConnection;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
/** Explicit settings win over the environment, including an invalid/empty URL. */
|
|
5
|
+
export function resolvePostgresConnection(connection) {
|
|
6
|
+
const url = connection.url === undefined ? process.env.DATABASE_URL : connection.url;
|
|
7
|
+
if (url === undefined)
|
|
8
|
+
throw new Error("No PostgreSQL connection. Run hulla-db dev for managed development, or supply url / DATABASE_URL.");
|
|
9
|
+
try {
|
|
10
|
+
if (typeof url !== "string" || !url.trim())
|
|
11
|
+
throw new Error();
|
|
12
|
+
const parsed = new URL(url);
|
|
13
|
+
if (!["postgres:", "postgresql:"].includes(parsed.protocol))
|
|
14
|
+
throw new Error();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new TypeError("Invalid PostgreSQL connection URL");
|
|
18
|
+
}
|
|
19
|
+
return { url, ...(connection.namespace === undefined ? {} : { namespace: connection.namespace }) };
|
|
20
|
+
}
|
|
21
|
+
/** Imported by generated Node/Bun applications; file access must stay portable. */
|
|
22
|
+
export function resolveDatabaseConnection(connection, configPath) {
|
|
23
|
+
let url = connection.url ?? process.env.DATABASE_URL;
|
|
24
|
+
if (url === undefined) {
|
|
25
|
+
if (process.env.NODE_ENV === "production")
|
|
26
|
+
throw new Error("Production requires database.server.url or DATABASE_URL.");
|
|
27
|
+
const path = typeof configPath === "string" ? configPath : fileURLToPath(configPath);
|
|
28
|
+
try {
|
|
29
|
+
url = JSON.parse(readFileSync(resolve(dirname(path), ".hulla/local.json"), "utf8")).url;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw new Error("No database connection. Run hulla-db dev for local development, or configure database.server.url / DATABASE_URL.");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// Validate persisted state and environment input just like authored settings.
|
|
36
|
+
try {
|
|
37
|
+
const parsed = new URL(url);
|
|
38
|
+
if (!["postgres:", "postgresql:"].includes(parsed.protocol))
|
|
39
|
+
throw new Error();
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new Error("Invalid database connection. Configure a PostgreSQL URL or recreate local development storage explicitly.");
|
|
43
|
+
}
|
|
44
|
+
return { url: url, ...(connection.namespace === undefined ? {} : { namespace: connection.namespace }) };
|
|
45
|
+
}
|
package/dist/native.d.ts
ADDED
package/dist/native.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
const require = createRequire(import.meta.url);
|
|
5
|
+
// Literal resolutions keep executable files visible to server file tracing.
|
|
6
|
+
const assets = {
|
|
7
|
+
"darwin-arm64": {
|
|
8
|
+
bridge: () => require.resolve("@hulla/db-postgres-darwin-arm64/hulladb-bridge"),
|
|
9
|
+
service: () => require.resolve("@hulla/db-postgres-darwin-arm64/hulladb-service"),
|
|
10
|
+
js: () => require.resolve("@hulla/db-postgres-darwin-arm64/hulladb-js"),
|
|
11
|
+
},
|
|
12
|
+
"linux-x64": {
|
|
13
|
+
bridge: () => require.resolve("@hulla/db-postgres-linux-x64/hulladb-bridge"),
|
|
14
|
+
service: () => require.resolve("@hulla/db-postgres-linux-x64/hulladb-service"),
|
|
15
|
+
js: () => require.resolve("@hulla/db-postgres-linux-x64/hulladb-js"),
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
export function resolveNativeExecutable(kind) {
|
|
19
|
+
const variable = { bridge: "HULLADB_ENGINE", service: "HULLADB_SERVICE", js: "HULLADB_JS" }[kind];
|
|
20
|
+
const override = process.env[variable];
|
|
21
|
+
if (override)
|
|
22
|
+
return override;
|
|
23
|
+
const platform = `${process.platform}-${process.arch}`;
|
|
24
|
+
if (import.meta.url.endsWith("/src/native.ts")) {
|
|
25
|
+
for (const path of [`../native/${platform}/hulladb-${kind}`, `../../../target/debug/hulladb-${kind}`]) {
|
|
26
|
+
const development = new URL(path, import.meta.url);
|
|
27
|
+
if (existsSync(development))
|
|
28
|
+
return fileURLToPath(development);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const locate = assets[platform]?.[kind];
|
|
32
|
+
if (locate) {
|
|
33
|
+
try {
|
|
34
|
+
const path = locate();
|
|
35
|
+
if (existsSync(path))
|
|
36
|
+
return path;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
if (error.code !== "MODULE_NOT_FOUND")
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
throw new Error(`No packaged hulladb-${kind} executable for ${platform}. Install @hulla/db-postgres with optional dependencies on the deployment target, or set ${variable} to a compatible executable.`);
|
|
44
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type SchemaDefinition } from '@hulla/db/schema';
|
|
2
|
+
/** Prepared hosting reads generated metadata, never the application's eager bootstrap. */
|
|
3
|
+
export declare function preparedSchema(entrypoint: string, expectedEngine?: string): Promise<{
|
|
4
|
+
schema: SchemaDefinition;
|
|
5
|
+
directory: string;
|
|
6
|
+
} | undefined>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { basename, dirname, extname, resolve } from 'node:path';
|
|
10
|
+
import { readFile } from 'node:fs/promises';
|
|
11
|
+
import { pathToFileURL } from 'node:url';
|
|
12
|
+
import { isDefinedSchema } from '@hulla/db/schema';
|
|
13
|
+
/** Prepared hosting reads generated metadata, never the application's eager bootstrap. */
|
|
14
|
+
export async function preparedSchema(entrypoint, expectedEngine) {
|
|
15
|
+
const directory = resolve(dirname(entrypoint), '_generated', basename(entrypoint, extname(entrypoint)));
|
|
16
|
+
const path = resolve(directory, '_source.js');
|
|
17
|
+
let contents;
|
|
18
|
+
try {
|
|
19
|
+
contents = await readFile(path, 'utf8');
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error.code === 'ENOENT')
|
|
23
|
+
return undefined;
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
if (!contents.startsWith('// Generated by @hulla/db. Do not edit.\n'))
|
|
27
|
+
throw new TypeError('Expected generated database source metadata');
|
|
28
|
+
const metadata = await import(__rewriteRelativeImportExtension(pathToFileURL(path).href));
|
|
29
|
+
if (!isDefinedSchema(metadata.default?.schema) || typeof metadata.engine !== 'string')
|
|
30
|
+
throw new TypeError('Invalid generated database source metadata; regenerate the database entrypoint');
|
|
31
|
+
if (expectedEngine && metadata.engine !== expectedEngine)
|
|
32
|
+
throw new TypeError(`This host requires a ${expectedEngine} database; received ${metadata.engine}`);
|
|
33
|
+
return { schema: metadata.default.schema, directory };
|
|
34
|
+
}
|
package/dist/serve.d.ts
ADDED
package/dist/serve.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { startService } from "./service.js";
|
|
3
|
+
async function serve(config) {
|
|
4
|
+
let service;
|
|
5
|
+
let stopping = false;
|
|
6
|
+
const stop = () => { stopping = true; void service?.close().catch(() => { }); };
|
|
7
|
+
process.on("SIGINT", stop);
|
|
8
|
+
process.on("SIGTERM", stop);
|
|
9
|
+
try {
|
|
10
|
+
service = await startService(config);
|
|
11
|
+
if (!stopping)
|
|
12
|
+
console.log(`Database service listening at ${service.url}`);
|
|
13
|
+
else
|
|
14
|
+
await service.close();
|
|
15
|
+
await service.closed;
|
|
16
|
+
}
|
|
17
|
+
finally {
|
|
18
|
+
process.off("SIGINT", stop);
|
|
19
|
+
process.off("SIGTERM", stop);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const [config = "db.config.ts", ...args] = process.argv.slice(2);
|
|
23
|
+
if (config === "--help" || config === "-h")
|
|
24
|
+
console.log("Usage: hulla-db-serve [entrypoint]");
|
|
25
|
+
else if (config.startsWith("-") || args.length) {
|
|
26
|
+
console.error("Usage: hulla-db-serve [entrypoint]");
|
|
27
|
+
process.exitCode = 1;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
try {
|
|
31
|
+
await serve(config);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
console.error(error instanceof Error ? error.message : "Database service failed");
|
|
35
|
+
process.exitCode = 1;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type InvocationLimits, type DatabaseConnection } from "@hulla/db/config";
|
|
2
|
+
import type { WriteDatabase } from "@hulla/db";
|
|
3
|
+
import type { SchemaDefinition } from "@hulla/db/schema";
|
|
4
|
+
export { resolvePostgresConnection } from "./local-connection.ts";
|
|
5
|
+
export interface TransactionOptions {
|
|
6
|
+
readonly retries?: number;
|
|
7
|
+
}
|
|
8
|
+
export interface Database<S extends SchemaDefinition> extends WriteDatabase<S> {
|
|
9
|
+
transaction<T>(handler: (tx: WriteDatabase<S>) => T | PromiseLike<T>, options?: TransactionOptions): Promise<T>;
|
|
10
|
+
close(): Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
/** Internal factory called by the generated server entrypoint. Importing is inert. */
|
|
13
|
+
export declare function createDatabase<S extends SchemaDefinition>(schema: S, connection: DatabaseConnection, overrides?: InvocationLimits): Database<S>;
|
|
14
|
+
/** Explicit CLI provisioning. Importing a server database never calls this. */
|
|
15
|
+
export declare function initializeDatabase(schema: SchemaDefinition, connection: DatabaseConnection): Promise<void>;
|
|
16
|
+
export type SchemaChange = {
|
|
17
|
+
readonly kind: "add_table" | "reorder_fields";
|
|
18
|
+
readonly table: string;
|
|
19
|
+
} | {
|
|
20
|
+
readonly kind: "add_field" | "add_reference";
|
|
21
|
+
readonly table: string;
|
|
22
|
+
readonly field: string;
|
|
23
|
+
};
|
|
24
|
+
export type MigrationPlan = {
|
|
25
|
+
readonly source: string;
|
|
26
|
+
readonly changes: readonly SchemaChange[];
|
|
27
|
+
};
|
|
28
|
+
/** Apply supported upgrades using a provisioning connection. Set check to inspect
|
|
29
|
+
* without changing storage. Owned local development uses this same transaction. */
|
|
30
|
+
export declare function migrateDatabase(schema: SchemaDefinition, connection: DatabaseConnection, options?: {
|
|
31
|
+
readonly check?: boolean;
|
|
32
|
+
}): Promise<MigrationPlan>;
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { resolveNativeExecutable } from "./native.js";
|
|
4
|
+
import { defineConfig, resolveLimits } from "@hulla/db/config";
|
|
5
|
+
import { transactionDatabase, schemaDescriptor, registerStorageExecution } from "@hulla/db/internal/engine";
|
|
6
|
+
import { DatabaseError } from "@hulla/db";
|
|
7
|
+
export { resolvePostgresConnection } from "./local-connection.js";
|
|
8
|
+
const transactionScope = new AsyncLocalStorage();
|
|
9
|
+
const retryable = new WeakSet();
|
|
10
|
+
const idleMilliseconds = 10_000;
|
|
11
|
+
const maxWaiting = 64;
|
|
12
|
+
const failure = (code, message) => new DatabaseError({ code, message });
|
|
13
|
+
/** Private process protocol. It is never exposed over the application's network. */
|
|
14
|
+
class Bridge {
|
|
15
|
+
child;
|
|
16
|
+
stopped = new AbortController();
|
|
17
|
+
exited;
|
|
18
|
+
#killTimer;
|
|
19
|
+
#buffer = Buffer.alloc(0);
|
|
20
|
+
#pending;
|
|
21
|
+
idleSince = 0;
|
|
22
|
+
idleTimer;
|
|
23
|
+
dead = false;
|
|
24
|
+
inTransaction = false;
|
|
25
|
+
#committing = false;
|
|
26
|
+
limits;
|
|
27
|
+
maxFrame;
|
|
28
|
+
constructor(limits = resolveLimits()) {
|
|
29
|
+
this.limits = limits;
|
|
30
|
+
this.maxFrame = Math.max(limits.inputBytes, limits.outputBytes, limits.readBytes) + 2 * 1024 * 1024;
|
|
31
|
+
const engine = resolveNativeExecutable("bridge");
|
|
32
|
+
this.child = spawn(engine, [], { stdio: ["pipe", "pipe", "pipe"], env: {} });
|
|
33
|
+
this.exited = new Promise(resolve => this.child.once("close", () => {
|
|
34
|
+
clearTimeout(this.#killTimer);
|
|
35
|
+
resolve();
|
|
36
|
+
}));
|
|
37
|
+
// The native bridge sanitizes protocol errors. Never echo driver stderr,
|
|
38
|
+
// which may contain connection or operator details.
|
|
39
|
+
let diagnostics = "";
|
|
40
|
+
this.child.stderr.on("data", (chunk) => {
|
|
41
|
+
diagnostics += chunk.toString("utf8");
|
|
42
|
+
const lines = diagnostics.split("\n");
|
|
43
|
+
diagnostics = lines.pop().slice(-4096);
|
|
44
|
+
for (const line of lines)
|
|
45
|
+
if (line.startsWith("[hulla/db] "))
|
|
46
|
+
console.warn(line);
|
|
47
|
+
});
|
|
48
|
+
this.child.on("error", () => this.destroy(failure("engine_unavailable", "Cannot start the database engine; install/build hulladb-bridge or set HULLADB_ENGINE")));
|
|
49
|
+
this.child.on("exit", () => this.destroy());
|
|
50
|
+
this.child.stdin.on("error", () => this.destroy());
|
|
51
|
+
this.child.stdout.on("data", (chunk) => {
|
|
52
|
+
this.#buffer = Buffer.concat([this.#buffer, chunk]);
|
|
53
|
+
if (this.#buffer.length > this.maxFrame) {
|
|
54
|
+
this.destroy(failure("execution_limit", "Database response exceeds the transport budget"));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
let newline;
|
|
58
|
+
while ((newline = this.#buffer.indexOf(10)) !== -1) {
|
|
59
|
+
const line = this.#buffer.subarray(0, newline);
|
|
60
|
+
this.#buffer = this.#buffer.subarray(newline + 1);
|
|
61
|
+
const pending = this.#pending;
|
|
62
|
+
if (!pending) {
|
|
63
|
+
this.destroy();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
this.#pending = undefined;
|
|
67
|
+
clearTimeout(pending.timer);
|
|
68
|
+
try {
|
|
69
|
+
const value = JSON.parse(line.toString("utf8"));
|
|
70
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
71
|
+
throw new Error();
|
|
72
|
+
pending.resolve(value);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
pending.reject(this.protocolFailure("Invalid database engine response"));
|
|
76
|
+
this.destroy();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
protocolFailure(message) {
|
|
83
|
+
return this.#committing
|
|
84
|
+
? failure("commit_outcome_unknown", "Commit confirmation was lost; the transaction may have committed")
|
|
85
|
+
: failure("engine_protocol", message);
|
|
86
|
+
}
|
|
87
|
+
destroy(error) {
|
|
88
|
+
if (this.dead)
|
|
89
|
+
return;
|
|
90
|
+
this.dead = true;
|
|
91
|
+
clearTimeout(this.idleTimer);
|
|
92
|
+
const pending = this.#pending;
|
|
93
|
+
this.#pending = undefined;
|
|
94
|
+
if (pending) {
|
|
95
|
+
clearTimeout(pending.timer);
|
|
96
|
+
pending.reject(this.#committing ? this.protocolFailure("") : error ?? failure("engine_disconnected", "Database engine disconnected"));
|
|
97
|
+
}
|
|
98
|
+
this.stopped.abort(error ?? failure("engine_disconnected", "Database engine disconnected"));
|
|
99
|
+
this.child.kill();
|
|
100
|
+
if (this.child.exitCode === null && this.child.signalCode === null) {
|
|
101
|
+
this.#killTimer = setTimeout(() => this.child.kill("SIGKILL"), 2000);
|
|
102
|
+
this.#killTimer.unref();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async command(frame, expected) {
|
|
106
|
+
if (this.dead)
|
|
107
|
+
throw failure("engine_disconnected", "Database engine is closed");
|
|
108
|
+
if (this.#pending)
|
|
109
|
+
throw failure("engine_protocol", "Concurrent engine command");
|
|
110
|
+
const encoded = JSON.stringify(frame) + "\n";
|
|
111
|
+
if (Buffer.byteLength(encoded) > this.maxFrame)
|
|
112
|
+
throw failure("execution_limit", "Database request exceeds the transport budget");
|
|
113
|
+
this.#committing = frame.type === "commit" || (frame.type === "init" && frame.migration === true);
|
|
114
|
+
const response = await new Promise((resolve, reject) => {
|
|
115
|
+
const timer = setTimeout(() => this.destroy(failure(this.#committing ? "commit_outcome_unknown" : "engine_timeout", "Database engine did not respond in time")), this.limits.executionMs + 1000);
|
|
116
|
+
this.#pending = { resolve, reject, timer };
|
|
117
|
+
this.child.stdin.write(encoded);
|
|
118
|
+
});
|
|
119
|
+
if (response.type === "error") {
|
|
120
|
+
if (this.#committing && response.rolledBack !== true) {
|
|
121
|
+
const error = this.protocolFailure("");
|
|
122
|
+
this.destroy();
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
this.#committing = false;
|
|
126
|
+
const info = response.error;
|
|
127
|
+
const error = failure(typeof info?.code === "string" ? info.code : "database_failed", typeof info?.message === "string" ? info.message : "Database operation failed");
|
|
128
|
+
this.inTransaction = false;
|
|
129
|
+
if (response.rolledBack === true && error.code === "serialization_conflict")
|
|
130
|
+
retryable.add(error);
|
|
131
|
+
if (response.rolledBack !== true)
|
|
132
|
+
this.destroy();
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
if (response.type !== expected) {
|
|
136
|
+
const error = this.protocolFailure("Unexpected database engine response");
|
|
137
|
+
this.destroy();
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
this.#committing = false;
|
|
141
|
+
if (expected === "begun")
|
|
142
|
+
this.inTransaction = true;
|
|
143
|
+
if (expected === "committed" || expected === "rolled_back")
|
|
144
|
+
this.inTransaction = false;
|
|
145
|
+
return response;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Internal factory called by the generated server entrypoint. Importing is inert. */
|
|
149
|
+
export function createDatabase(schema, connection, overrides) {
|
|
150
|
+
const config = defineConfig({ database: { server: connection } }).database.server;
|
|
151
|
+
const limits = resolveLimits(overrides);
|
|
152
|
+
const descriptor = schemaDescriptor(schema);
|
|
153
|
+
const idle = [], sessions = new Set();
|
|
154
|
+
const waiters = [];
|
|
155
|
+
let available = 4, closed = false;
|
|
156
|
+
const assertRoot = () => {
|
|
157
|
+
if (closed)
|
|
158
|
+
throw failure("database_closed", "Database is closed");
|
|
159
|
+
if (transactionScope.getStore())
|
|
160
|
+
throw failure("transaction_scope", "Use the supplied tx inside a transaction, not the root database");
|
|
161
|
+
};
|
|
162
|
+
const releasePermit = () => {
|
|
163
|
+
const next = waiters.shift();
|
|
164
|
+
if (next)
|
|
165
|
+
next.resolve();
|
|
166
|
+
else
|
|
167
|
+
available++;
|
|
168
|
+
};
|
|
169
|
+
async function retire(session) {
|
|
170
|
+
session.destroy();
|
|
171
|
+
await session.exited;
|
|
172
|
+
sessions.delete(session);
|
|
173
|
+
}
|
|
174
|
+
async function begin(session, writable) {
|
|
175
|
+
const deadline = setTimeout(() => session.destroy(failure("transaction_timeout", "Database transaction exceeded its execution deadline")), limits.executionMs);
|
|
176
|
+
try {
|
|
177
|
+
await session.command({ type: "begin", mode: writable ? "write" : "read" }, "begun");
|
|
178
|
+
return { session, deadline };
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
clearTimeout(deadline);
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
async function acquire(writable) {
|
|
186
|
+
if (available > 0)
|
|
187
|
+
available--;
|
|
188
|
+
else {
|
|
189
|
+
if (waiters.length >= maxWaiting)
|
|
190
|
+
throw failure("capacity", "Database connection queue is full");
|
|
191
|
+
await new Promise((resolve, reject) => {
|
|
192
|
+
const waiter = {
|
|
193
|
+
resolve: () => { clearTimeout(timer); resolve(); },
|
|
194
|
+
reject: (error) => { clearTimeout(timer); reject(error); },
|
|
195
|
+
};
|
|
196
|
+
const timer = setTimeout(() => {
|
|
197
|
+
const index = waiters.indexOf(waiter);
|
|
198
|
+
if (index !== -1)
|
|
199
|
+
waiters.splice(index, 1);
|
|
200
|
+
reject(failure("database_timeout", "Timed out waiting for a database connection"));
|
|
201
|
+
}, limits.executionMs);
|
|
202
|
+
waiters.push(waiter);
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
try {
|
|
206
|
+
if (closed)
|
|
207
|
+
throw failure("database_closed", "Database is closed");
|
|
208
|
+
let session;
|
|
209
|
+
while ((session = idle.pop())) {
|
|
210
|
+
clearTimeout(session.idleTimer);
|
|
211
|
+
if (!session.dead && Date.now() - session.idleSince < idleMilliseconds) {
|
|
212
|
+
// BEGIN checks the connection and scope before any application work can run.
|
|
213
|
+
try {
|
|
214
|
+
return await begin(session, writable);
|
|
215
|
+
}
|
|
216
|
+
catch { /* Retire the failed lease and try another before entering the callback. */ }
|
|
217
|
+
}
|
|
218
|
+
await retire(session);
|
|
219
|
+
}
|
|
220
|
+
if (closed)
|
|
221
|
+
throw failure("database_closed", "Database is closed");
|
|
222
|
+
session = new Bridge(limits);
|
|
223
|
+
sessions.add(session);
|
|
224
|
+
try {
|
|
225
|
+
await session.command({ type: "init", url: config.url, namespace: config.namespace ?? "hulla", schema: descriptor, limits, development: process.env.NODE_ENV !== "production" }, "ready");
|
|
226
|
+
return await begin(session, writable);
|
|
227
|
+
}
|
|
228
|
+
catch (error) {
|
|
229
|
+
await retire(session);
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
releasePermit();
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function release(session) {
|
|
239
|
+
if (!closed && !session.dead) {
|
|
240
|
+
session.idleSince = Date.now();
|
|
241
|
+
idle.push(session);
|
|
242
|
+
session.idleTimer = setTimeout(() => {
|
|
243
|
+
const index = idle.indexOf(session);
|
|
244
|
+
if (index === -1)
|
|
245
|
+
return;
|
|
246
|
+
idle.splice(index, 1);
|
|
247
|
+
session.destroy();
|
|
248
|
+
void session.exited.then(() => sessions.delete(session));
|
|
249
|
+
}, idleMilliseconds);
|
|
250
|
+
session.idleTimer.unref();
|
|
251
|
+
}
|
|
252
|
+
else
|
|
253
|
+
await retire(session);
|
|
254
|
+
releasePermit();
|
|
255
|
+
}
|
|
256
|
+
async function execute(writable, handler, scoped) {
|
|
257
|
+
assertRoot();
|
|
258
|
+
const { session, deadline } = await acquire(writable);
|
|
259
|
+
let active = true, pending = 0, sequence = 0;
|
|
260
|
+
const token = {};
|
|
261
|
+
let tail = Promise.resolve();
|
|
262
|
+
let statementError;
|
|
263
|
+
let statementFailed = false;
|
|
264
|
+
const request = (operation, validate) => {
|
|
265
|
+
if (!active || closed)
|
|
266
|
+
return Promise.reject(failure("transaction_closed", "Transaction handle is no longer active"));
|
|
267
|
+
if (scoped && transactionScope.getStore() !== token)
|
|
268
|
+
return Promise.reject(failure("transaction_scope", "Use the transaction handle only inside its callback"));
|
|
269
|
+
if (pending >= maxWaiting) {
|
|
270
|
+
statementError = failure("capacity", "Too many queued operations in one transaction");
|
|
271
|
+
statementFailed = true;
|
|
272
|
+
return Promise.reject(statementError);
|
|
273
|
+
}
|
|
274
|
+
pending++;
|
|
275
|
+
const result = tail.then(async () => {
|
|
276
|
+
if (!active || closed)
|
|
277
|
+
throw failure("transaction_closed", "Transaction handle is no longer active");
|
|
278
|
+
const id = ++sequence;
|
|
279
|
+
const response = await session.command({ type: "operation", id, operation }, "operation_result");
|
|
280
|
+
if (response.id !== id) {
|
|
281
|
+
session.destroy();
|
|
282
|
+
throw failure("engine_protocol", "Database operation response does not match its request");
|
|
283
|
+
}
|
|
284
|
+
// Validation belongs to the statement's queue entry, before commit. Its
|
|
285
|
+
// failure poisons the transaction even if the application catches it.
|
|
286
|
+
validate?.(response.result);
|
|
287
|
+
return response.result;
|
|
288
|
+
}).catch(error => { statementError = error; statementFailed = true; throw error; }).finally(() => { pending--; });
|
|
289
|
+
tail = result;
|
|
290
|
+
void result.catch(() => { });
|
|
291
|
+
return result;
|
|
292
|
+
};
|
|
293
|
+
try {
|
|
294
|
+
const tx = transactionDatabase(schema, writable, request);
|
|
295
|
+
const signal = session.stopped.signal;
|
|
296
|
+
let stopped;
|
|
297
|
+
let result;
|
|
298
|
+
try {
|
|
299
|
+
signal.throwIfAborted();
|
|
300
|
+
result = await Promise.race([
|
|
301
|
+
Promise.resolve().then(() => { signal.throwIfAborted(); return transactionScope.run(token, () => handler(tx, request)); }),
|
|
302
|
+
new Promise((_, reject) => {
|
|
303
|
+
stopped = () => reject(signal.reason);
|
|
304
|
+
signal.addEventListener("abort", stopped, { once: true });
|
|
305
|
+
}),
|
|
306
|
+
]);
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
if (stopped)
|
|
310
|
+
signal.removeEventListener("abort", stopped);
|
|
311
|
+
}
|
|
312
|
+
active = false;
|
|
313
|
+
if (pending) {
|
|
314
|
+
session.destroy();
|
|
315
|
+
throw failure("unawaited_operations", "Await all database operations before returning from a transaction");
|
|
316
|
+
}
|
|
317
|
+
if (statementFailed)
|
|
318
|
+
throw statementError;
|
|
319
|
+
await session.command({ type: "commit" }, "committed");
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
active = false;
|
|
324
|
+
if (pending)
|
|
325
|
+
session.destroy();
|
|
326
|
+
if (session.inTransaction && !session.dead) {
|
|
327
|
+
try {
|
|
328
|
+
await session.command({ type: "rollback" }, "rolled_back");
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
session.destroy();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
throw error;
|
|
335
|
+
}
|
|
336
|
+
finally {
|
|
337
|
+
clearTimeout(deadline);
|
|
338
|
+
active = false;
|
|
339
|
+
await release(session);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
const request = (operation, validate) => execute(!["select", "paginate", "aggregate"].includes(operation.method), (_tx, request) => request(operation, validate), false);
|
|
343
|
+
const root = transactionDatabase(schema, true, request);
|
|
344
|
+
const database = Object.freeze({
|
|
345
|
+
...root,
|
|
346
|
+
async transaction(handler, options = {}) {
|
|
347
|
+
assertRoot();
|
|
348
|
+
if (typeof handler !== "function" || typeof options !== "object" || options === null
|
|
349
|
+
|| Reflect.ownKeys(options).some(key => key !== "retries")
|
|
350
|
+
|| !Number.isInteger(options.retries ?? 0) || (options.retries ?? 0) < 0 || (options.retries ?? 0) > 100)
|
|
351
|
+
throw new TypeError("Invalid transaction options");
|
|
352
|
+
for (let attempt = 0;; attempt++) {
|
|
353
|
+
try {
|
|
354
|
+
return await execute(true, handler, true);
|
|
355
|
+
}
|
|
356
|
+
catch (error) {
|
|
357
|
+
if (!(error instanceof DatabaseError) || !retryable.has(error) || attempt >= (options.retries ?? 0))
|
|
358
|
+
throw error;
|
|
359
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(5 * 2 ** attempt, 100) * Math.random()));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
async close() {
|
|
364
|
+
if (transactionScope.getStore())
|
|
365
|
+
throw failure("transaction_scope", "Close the database outside its transaction callback");
|
|
366
|
+
if (closed)
|
|
367
|
+
return;
|
|
368
|
+
closed = true;
|
|
369
|
+
for (const waiter of waiters.splice(0))
|
|
370
|
+
waiter.reject(failure("database_closed", "Database is closed"));
|
|
371
|
+
const exiting = [...sessions].map(session => {
|
|
372
|
+
session.destroy(failure("database_closed", "Database is closed"));
|
|
373
|
+
return session.exited;
|
|
374
|
+
});
|
|
375
|
+
idle.length = 0;
|
|
376
|
+
sessions.clear();
|
|
377
|
+
await Promise.all(exiting);
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
registerStorageExecution(database, request);
|
|
381
|
+
return database;
|
|
382
|
+
}
|
|
383
|
+
/** Explicit CLI provisioning. Importing a server database never calls this. */
|
|
384
|
+
export async function initializeDatabase(schema, connection) {
|
|
385
|
+
const config = defineConfig({ database: { server: connection } }).database.server;
|
|
386
|
+
const session = new Bridge();
|
|
387
|
+
try {
|
|
388
|
+
await session.command({ type: "init", url: config.url, namespace: config.namespace ?? "hulla", schema: schemaDescriptor(schema), initialize: true }, "ready");
|
|
389
|
+
}
|
|
390
|
+
finally {
|
|
391
|
+
session.destroy();
|
|
392
|
+
await session.exited;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
/** Apply supported upgrades using a provisioning connection. Set check to inspect
|
|
396
|
+
* without changing storage. Owned local development uses this same transaction. */
|
|
397
|
+
export async function migrateDatabase(schema, connection, options = {}) {
|
|
398
|
+
const config = defineConfig({ database: { server: connection } }).database.server;
|
|
399
|
+
const session = new Bridge(resolveLimits({ executionMs: 60_000 }));
|
|
400
|
+
try {
|
|
401
|
+
const response = await session.command({ type: "init", url: config.url, namespace: config.namespace ?? "hulla", schema: schemaDescriptor(schema), migration: !options.check }, "ready");
|
|
402
|
+
const plan = response.migration;
|
|
403
|
+
if (!plan || typeof plan.source !== "string" || !Array.isArray(plan.changes))
|
|
404
|
+
throw failure("engine_protocol", "Invalid database migration response");
|
|
405
|
+
return plan;
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
session.destroy();
|
|
409
|
+
await session.exited;
|
|
410
|
+
}
|
|
411
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createDatabase, initializeDatabase, migrateDatabase } from "./server-database.ts";
|
|
2
|
+
export type { Database, TransactionOptions } from "./server-database.ts";
|
|
3
|
+
export type { MigrationPlan, SchemaChange } from "./server-database.ts";
|
|
4
|
+
export { resolveDatabaseConnection } from "./local-connection.ts";
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { VerifyIdentity } from "@hulla/db/config";
|
|
2
|
+
/** Private bridge context. Only a trusted verifier result can reach this function. */
|
|
3
|
+
export declare function verifyServiceIdentity(verify: VerifyIdentity | undefined, headers: Headers): Promise<{
|
|
4
|
+
principal: string;
|
|
5
|
+
authorizationScope: string;
|
|
6
|
+
identity: unknown;
|
|
7
|
+
}>;
|
|
8
|
+
/** Runtime-only launcher. The native host owns HTTP/SSE, transactions and revalidation. */
|
|
9
|
+
export declare function startService(configPath: string, address?: {
|
|
10
|
+
readonly host: string;
|
|
11
|
+
readonly port: number;
|
|
12
|
+
}): Promise<{
|
|
13
|
+
url: string;
|
|
14
|
+
close(): Promise<void>;
|
|
15
|
+
closed: Promise<void>;
|
|
16
|
+
}>;
|
package/dist/service.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { access, readFile } from "node:fs/promises";
|
|
4
|
+
import { constants } from "node:fs";
|
|
5
|
+
import { resolve } from "node:path";
|
|
6
|
+
import { resolveNativeExecutable } from "./native.js";
|
|
7
|
+
import { schemaDescriptor } from "@hulla/db/internal/engine";
|
|
8
|
+
import { resolveDatabaseConnection } from "./local-connection.js";
|
|
9
|
+
import { loadHostConfiguration } from "./host-configuration.js";
|
|
10
|
+
class VerificationTimeout extends Error {
|
|
11
|
+
}
|
|
12
|
+
function canonical(value, depth = 0) {
|
|
13
|
+
if (depth > 64)
|
|
14
|
+
throw new TypeError("Identity nesting exceeds the supported depth");
|
|
15
|
+
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
16
|
+
return value;
|
|
17
|
+
if (typeof value === "number" && Number.isFinite(value))
|
|
18
|
+
return value;
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return value.map(item => canonical(item, depth + 1));
|
|
21
|
+
if (typeof value === "object" && value !== null && [Object.prototype, null].includes(Object.getPrototypeOf(value))) {
|
|
22
|
+
const result = Object.create(null);
|
|
23
|
+
for (const key of Reflect.ownKeys(value).sort()) {
|
|
24
|
+
if (typeof key !== "string")
|
|
25
|
+
throw new TypeError("Identity must be JSON data");
|
|
26
|
+
result[key] = canonical(value[key], depth + 1);
|
|
27
|
+
}
|
|
28
|
+
return result;
|
|
29
|
+
}
|
|
30
|
+
throw new TypeError("Identity must be JSON data");
|
|
31
|
+
}
|
|
32
|
+
function identityId(value) {
|
|
33
|
+
const hex = createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 32);
|
|
34
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
35
|
+
}
|
|
36
|
+
/** Private bridge context. Only a trusted verifier result can reach this function. */
|
|
37
|
+
export async function verifyServiceIdentity(verify, headers) {
|
|
38
|
+
let timer;
|
|
39
|
+
let verified;
|
|
40
|
+
try {
|
|
41
|
+
verified = verify ? await Promise.race([
|
|
42
|
+
Promise.resolve().then(() => verify(headers)),
|
|
43
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new VerificationTimeout("Authentication verification timed out")), 5000); }),
|
|
44
|
+
]) : null;
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
}
|
|
49
|
+
if (verified !== null && (typeof verified !== "object" || typeof verified.key !== "string" || !verified.key.trim() || verified.key.length > 1024))
|
|
50
|
+
throw new TypeError("Auth verifier must return a key and JSON identity, or null");
|
|
51
|
+
const identity = verified === null ? null : canonical(verified.identity);
|
|
52
|
+
if (Buffer.byteLength(JSON.stringify(identity)) > 1024 * 1024)
|
|
53
|
+
throw new TypeError("Verified identity exceeds the transport budget");
|
|
54
|
+
const principal = verified === null ? ["anonymous"] : ["authenticated", verified.key];
|
|
55
|
+
return { principal: identityId(principal), authorizationScope: identityId([principal, identity]), identity };
|
|
56
|
+
}
|
|
57
|
+
/** Runtime-only launcher. The native host owns HTTP/SSE, transactions and revalidation. */
|
|
58
|
+
export async function startService(configPath, address) {
|
|
59
|
+
const { config, schema, directory: generated, prepared } = await loadHostConfiguration(configPath);
|
|
60
|
+
const connection = resolveDatabaseConnection(config.database.server, resolve(configPath));
|
|
61
|
+
const bundle = resolve(generated, prepared ? "_worker.js" : "worker.js");
|
|
62
|
+
let manifest;
|
|
63
|
+
try {
|
|
64
|
+
manifest = await readFile(resolve(generated, prepared ? "functions.json" : "client/functions.json"), "utf8");
|
|
65
|
+
await access(bundle, constants.R_OK);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
throw new Error("Cannot read generated service artifacts; run hulla-db generate with Bun before serve and include the generated directory in your deployment");
|
|
69
|
+
}
|
|
70
|
+
const executable = resolveNativeExecutable("service");
|
|
71
|
+
const child = spawn(executable, [], { stdio: ["pipe", "pipe", "pipe"], env: {} });
|
|
72
|
+
const childExit = new Promise(resolve => child.once("close", () => resolve()));
|
|
73
|
+
let diagnostics = "";
|
|
74
|
+
child.stderr.on("data", (chunk) => {
|
|
75
|
+
diagnostics += chunk.toString("utf8");
|
|
76
|
+
const lines = diagnostics.split("\n");
|
|
77
|
+
diagnostics = lines.pop().slice(-4096);
|
|
78
|
+
for (const line of lines)
|
|
79
|
+
if (line.startsWith("[hulla/db] "))
|
|
80
|
+
console.warn(line);
|
|
81
|
+
});
|
|
82
|
+
let buffer = Buffer.alloc(0), stopping = false, settled = false, pendingAuth = 0;
|
|
83
|
+
let ready, startupFailed;
|
|
84
|
+
const startup = new Promise((resolve, reject) => { ready = resolve; startupFailed = reject; });
|
|
85
|
+
let exited, failed;
|
|
86
|
+
const closed = new Promise((resolve, reject) => { exited = resolve; failed = reject; });
|
|
87
|
+
void closed.catch(() => { });
|
|
88
|
+
const fail = (message) => {
|
|
89
|
+
const error = new Error(message);
|
|
90
|
+
if (message === "browser service address is already in use")
|
|
91
|
+
Object.assign(error, { code: "EADDRINUSE" });
|
|
92
|
+
startupFailed(error);
|
|
93
|
+
failed(error);
|
|
94
|
+
child.kill();
|
|
95
|
+
};
|
|
96
|
+
const send = (frame) => { if (!stopping && !child.stdin.destroyed)
|
|
97
|
+
child.stdin.write(JSON.stringify(frame) + "\n"); };
|
|
98
|
+
child.on("error", () => fail("Cannot start hulladb-service; build the native service or set HULLADB_SERVICE"));
|
|
99
|
+
child.stdin.on("error", () => { if (!stopping)
|
|
100
|
+
fail("Database service disconnected"); });
|
|
101
|
+
child.on("exit", code => {
|
|
102
|
+
settled = true;
|
|
103
|
+
startupFailed(new Error("Database service exited before startup completed"));
|
|
104
|
+
if (stopping || code === 0)
|
|
105
|
+
exited();
|
|
106
|
+
else
|
|
107
|
+
failed(new Error("Database service stopped unexpectedly"));
|
|
108
|
+
});
|
|
109
|
+
child.stdout.on("data", (chunk) => {
|
|
110
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
111
|
+
if (buffer.length > 66 * 1024 * 1024) {
|
|
112
|
+
fail("Database service frame exceeds its transport budget");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
let newline;
|
|
116
|
+
while ((newline = buffer.indexOf(10)) !== -1) {
|
|
117
|
+
const line = buffer.subarray(0, newline);
|
|
118
|
+
buffer = buffer.subarray(newline + 1);
|
|
119
|
+
let frame;
|
|
120
|
+
try {
|
|
121
|
+
frame = JSON.parse(line.toString("utf8"));
|
|
122
|
+
if (!frame || typeof frame !== "object")
|
|
123
|
+
throw new Error();
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
fail("Invalid database service response");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (frame.type === "ready" && typeof frame.url === "string")
|
|
130
|
+
ready(frame.url);
|
|
131
|
+
else if (frame.type === "authenticate" && Number.isSafeInteger(frame.id) && Array.isArray(frame.headers)) {
|
|
132
|
+
const { id, headers } = frame;
|
|
133
|
+
if (pendingAuth >= 64) {
|
|
134
|
+
send({ type: "authenticated", id, context: null, unavailable: true });
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
pendingAuth++;
|
|
138
|
+
void (async () => {
|
|
139
|
+
let context = null;
|
|
140
|
+
let unavailable = false;
|
|
141
|
+
try {
|
|
142
|
+
context = await verifyServiceIdentity(config.auth, new Headers(headers));
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
unavailable = error instanceof VerificationTimeout;
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
pendingAuth--;
|
|
149
|
+
}
|
|
150
|
+
send({ type: "authenticated", id, context, unavailable });
|
|
151
|
+
})();
|
|
152
|
+
}
|
|
153
|
+
else if (frame.type === "error" && typeof frame.message === "string") {
|
|
154
|
+
// The supplied native binary emits only static, sanitized diagnostics.
|
|
155
|
+
fail(frame.message);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
fail("Database service startup or protocol failed");
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
async function close() {
|
|
165
|
+
if (!stopping) {
|
|
166
|
+
if (!settled)
|
|
167
|
+
send({ type: "shutdown" });
|
|
168
|
+
stopping = true;
|
|
169
|
+
child.stdin.end();
|
|
170
|
+
}
|
|
171
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), 2000);
|
|
172
|
+
try {
|
|
173
|
+
await closed;
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
await childExit;
|
|
177
|
+
clearTimeout(timer);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const timer = setTimeout(() => fail("Database service startup timed out"), 30_000);
|
|
181
|
+
try {
|
|
182
|
+
send({ type: "init", url: connection.url, namespace: connection.namespace ?? "hulla",
|
|
183
|
+
schema: schemaDescriptor(schema), manifest, development: process.env.NODE_ENV !== "production",
|
|
184
|
+
worker: {
|
|
185
|
+
executable: resolveNativeExecutable("js"),
|
|
186
|
+
entrypoint: bundle,
|
|
187
|
+
},
|
|
188
|
+
host: address?.host ?? config.service?.host ?? "127.0.0.1", port: address?.port ?? config.service?.port ?? 3001,
|
|
189
|
+
origins: config.service?.origins ?? [],
|
|
190
|
+
});
|
|
191
|
+
return { url: await startup, close, closed };
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
await close().catch(() => { });
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
}
|
|
200
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hulla/db-postgres",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "PostgreSQL application instances for Hulla schemas and functions",
|
|
6
6
|
"exports": {
|
|
@@ -15,6 +15,18 @@
|
|
|
15
15
|
},
|
|
16
16
|
"types": "./dist/index.d.ts",
|
|
17
17
|
"default": "./dist/index.js"
|
|
18
|
+
},
|
|
19
|
+
"./server": {
|
|
20
|
+
"types": "./dist/server.d.ts",
|
|
21
|
+
"default": "./dist/server.js"
|
|
22
|
+
},
|
|
23
|
+
"./service": {
|
|
24
|
+
"types": "./dist/service.d.ts",
|
|
25
|
+
"default": "./dist/service.js"
|
|
26
|
+
},
|
|
27
|
+
"./internal/host": {
|
|
28
|
+
"types": "./dist/host-configuration.d.ts",
|
|
29
|
+
"default": "./dist/host-configuration.js"
|
|
18
30
|
}
|
|
19
31
|
},
|
|
20
32
|
"files": [
|
|
@@ -23,7 +35,11 @@
|
|
|
23
35
|
"LICENSE"
|
|
24
36
|
],
|
|
25
37
|
"peerDependencies": {
|
|
26
|
-
"@hulla/db": "^0.3.
|
|
38
|
+
"@hulla/db": "^0.3.4"
|
|
39
|
+
},
|
|
40
|
+
"optionalDependencies": {
|
|
41
|
+
"@hulla/db-postgres-darwin-arm64": "0.3.4",
|
|
42
|
+
"@hulla/db-postgres-linux-x64": "0.3.4"
|
|
27
43
|
},
|
|
28
44
|
"engines": {
|
|
29
45
|
"node": ">=22.18.0"
|
|
@@ -45,5 +61,8 @@
|
|
|
45
61
|
"publishConfig": {
|
|
46
62
|
"access": "public",
|
|
47
63
|
"registry": "https://registry.npmjs.org/"
|
|
64
|
+
},
|
|
65
|
+
"bin": {
|
|
66
|
+
"hulla-db-serve": "./dist/serve.js"
|
|
48
67
|
}
|
|
49
68
|
}
|