@prisma/composer-prisma-cloud 0.2.0-dev.12 → 0.2.0-dev.14
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/dist/buckets-main.mjs +795 -0
- package/dist/buckets-main.mjs.map +1 -0
- package/dist/compute-main.mjs +532 -0
- package/dist/compute-main.mjs.map +1 -0
- package/dist/control.mjs +41 -1257
- package/dist/control.mjs.map +1 -1
- package/dist/cron/index.mjs +2 -3
- package/dist/cron/index.mjs.map +1 -1
- package/dist/cron/scheduler-entrypoint.mjs.map +1 -1
- package/dist/cron/scheduler-service.mjs +2 -3
- package/dist/cron/scheduler-service.mjs.map +1 -1
- package/dist/email/email-entrypoint.mjs.map +1 -1
- package/dist/email/email-service.mjs +2 -3
- package/dist/email/email-service.mjs.map +1 -1
- package/dist/email/index.mjs +2 -3
- package/dist/email/index.mjs.map +1 -1
- package/dist/email/testing.mjs.map +1 -1
- package/dist/get-port-BYnpbW5H.mjs +111 -0
- package/dist/get-port-BYnpbW5H.mjs.map +1 -0
- package/dist/index.mjs +4 -2
- package/dist/index.mjs.map +1 -1
- package/dist/local-target.d.mts +12 -0
- package/dist/local-target.d.mts.map +1 -0
- package/dist/local-target.mjs +6181 -0
- package/dist/local-target.mjs.map +1 -0
- package/dist/param-BTzY0ne5-CW6ojZ3E.mjs +66 -0
- package/dist/param-BTzY0ne5-CW6ojZ3E.mjs.map +1 -0
- package/dist/pg-connection-CadPZuEK-CF3FsSQu.mjs +79 -0
- package/dist/pg-connection-CadPZuEK-CF3FsSQu.mjs.map +1 -0
- package/dist/postgres-main.mjs +492 -0
- package/dist/postgres-main.mjs.map +1 -0
- package/dist/preflight-names-BPL-qsZF-BfoRgbgb.mjs +1252 -0
- package/dist/preflight-names-BPL-qsZF-BfoRgbgb.mjs.map +1 -0
- package/dist/{prisma-next-BvBwGCIt-CSauMX4l.mjs → prisma-next-BvBwGCIt-DssgnctU.mjs} +3 -78
- package/dist/prisma-next-BvBwGCIt-DssgnctU.mjs.map +1 -0
- package/dist/prisma-next.mjs +1 -1
- package/dist/{provisioned-edges-B_XS1Mz--NFJgcXK7.mjs → provisioned-edges-C1wSO3cx-YC5C19f9.mjs} +5 -65
- package/dist/provisioned-edges-C1wSO3cx-YC5C19f9.mjs.map +1 -0
- package/dist/secret-rz_ZqNeq-_xd97Jd9.mjs +47 -0
- package/dist/secret-rz_ZqNeq-_xd97Jd9.mjs.map +1 -0
- package/dist/segments-NpKN-46R-B01DmCqy.mjs +1441 -0
- package/dist/segments-NpKN-46R-B01DmCqy.mjs.map +1 -0
- package/dist/{serializer-D8_84XWO-DA2B6YbX.mjs → serializer-CJiOhF2d-DJUjQj1i.mjs} +4 -44
- package/dist/serializer-CJiOhF2d-DJUjQj1i.mjs.map +1 -0
- package/dist/storage/index.mjs +2 -3
- package/dist/storage/index.mjs.map +1 -1
- package/dist/storage/storage-entrypoint.mjs.map +1 -1
- package/dist/storage/storage-service.mjs +2 -3
- package/dist/storage/storage-service.mjs.map +1 -1
- package/dist/streams/index.mjs +2 -3
- package/dist/streams/index.mjs.map +1 -1
- package/dist/streams/streams-entrypoint.mjs.map +1 -1
- package/dist/streams/streams-service.mjs +2 -3
- package/dist/streams/streams-service.mjs.map +1 -1
- package/dist/testing.mjs +1 -1
- package/dist/testing.mjs.map +1 -1
- package/package.json +21 -15
- package/src/exports/local-target.ts +1 -0
- package/dist/prisma-next-BvBwGCIt-CSauMX4l.mjs.map +0 -1
- package/dist/provisioned-edges-B_XS1Mz--NFJgcXK7.mjs.map +0 -1
- package/dist/serializer-D8_84XWO-DA2B6YbX.mjs.map +0 -1
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { isParamSource, paramSource } from "@prisma/composer";
|
|
2
|
+
import { blindCast } from "@prisma/composer/casts";
|
|
3
|
+
//#region ../../1-prisma-cloud/1-extensions/target/dist/param-BTzY0ne5.mjs
|
|
4
|
+
/**
|
|
5
|
+
* Brands the payload `envParam` builds. Core's `paramSource()` is a public
|
|
6
|
+
* SPI, so a user could bypass `envParam` and bind a raw `paramSource('x')`;
|
|
7
|
+
* the brand lets `paramName` reject such a source (or another target's) with
|
|
8
|
+
* a clear error instead of reading an absent `.name`.
|
|
9
|
+
*/
|
|
10
|
+
const PRISMA_CLOUD_PARAM_SOURCE = blindCast(Symbol.for("prisma:prisma-cloud-param-source"));
|
|
11
|
+
const RESERVED_PARAM_PREFIX = "COMPOSER_";
|
|
12
|
+
const POISONED_PARAM_NAMES = /* @__PURE__ */ new Set(["DATABASE_URL", "DATABASE_URL_POOLED"]);
|
|
13
|
+
/**
|
|
14
|
+
* Binds a param slot to a named Prisma Cloud platform env var — the non-secret
|
|
15
|
+
* sibling of `envSecret` (spec: env-sourced config params). The platform
|
|
16
|
+
* injects the value into the running instance per stage; the param's own
|
|
17
|
+
* schema validates it at boot, unredacted. The name may not use the
|
|
18
|
+
* framework's reserved `COMPOSER_` prefix or the poisoned
|
|
19
|
+
* `DATABASE_URL(_POOLED)` keys — same parity as `envSecret`.
|
|
20
|
+
*/
|
|
21
|
+
function envParam(name) {
|
|
22
|
+
if (typeof name !== "string" || name.length === 0) throw new Error("envParam() requires a non-empty platform env-var name, e.g. envParam('APP_ORIGIN').");
|
|
23
|
+
if (name.startsWith(RESERVED_PARAM_PREFIX)) throw new Error(`envParam name "${name}" may not start with "${RESERVED_PARAM_PREFIX}" — that prefix is reserved for the framework's own generated config keys.`);
|
|
24
|
+
if (POISONED_PARAM_NAMES.has(name)) throw new Error(`envParam name "${name}" is reserved — ${[...POISONED_PARAM_NAMES].join(" and ")} are poisoned at project provision and cannot back a param.`);
|
|
25
|
+
return paramSource({
|
|
26
|
+
[PRISMA_CLOUD_PARAM_SOURCE]: true,
|
|
27
|
+
name
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
/** True only for a payload that `envParam` built — i.e. one carrying the brand. */
|
|
31
|
+
function isEnvParamPayload(payload) {
|
|
32
|
+
return typeof payload === "object" && payload !== null && blindCast(payload)[PRISMA_CLOUD_PARAM_SOURCE] === true;
|
|
33
|
+
}
|
|
34
|
+
/** True iff a resolved param value is an env-sourced pointer this target built (as opposed to a literal, or a foreign/raw `ParamSource`). */
|
|
35
|
+
function isEnvParamSource(value) {
|
|
36
|
+
return isParamSource(value) && isEnvParamPayload(value.payload);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Reads the Prisma Cloud env-var name back out of a param binding's opaque
|
|
40
|
+
* source. A source not built by `envParam` (a raw `paramSource(...)` or
|
|
41
|
+
* another target's source) carries no name — reject it here. `paramName` runs
|
|
42
|
+
* in preflight and at serialize before any value ever crosses the wire, so a
|
|
43
|
+
* foreign source fails early and clearly rather than producing a broken
|
|
44
|
+
* deploy with an undefined name.
|
|
45
|
+
*/
|
|
46
|
+
function paramName(binding) {
|
|
47
|
+
const { binding: bound } = binding;
|
|
48
|
+
if (!isEnvParamSource(bound)) throw new Error(`param slot "${binding.slot}" of service "${binding.serviceAddress}" is bound to a source not created by envParam() — bind env-sourced params with envParam('NAME') from @prisma/composer-prisma-cloud.`);
|
|
49
|
+
return bound.payload.name;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Finds the manifest entry for one service param slot. `serialize` calls this
|
|
53
|
+
* only after confirming `buildConfig` resolved the slot to a `ParamSource`
|
|
54
|
+
* (`isParamSource(value)`), so a miss here means `graph.params` and the
|
|
55
|
+
* resolved `Config` have drifted — a Load invariant violation, surfaced
|
|
56
|
+
* loudly rather than producing a pointer row with an undefined name.
|
|
57
|
+
*/
|
|
58
|
+
function paramBindingFor(bindings, serviceAddress, slot) {
|
|
59
|
+
const binding = bindings.find((b) => b.serviceAddress === serviceAddress && b.slot === slot);
|
|
60
|
+
if (binding === void 0) throw new Error(`param slot "${slot}" of "${serviceAddress}" resolved to a source but has no bound entry in the manifest — Load should have recorded it.`);
|
|
61
|
+
return binding;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { paramName as i, isEnvParamSource as n, paramBindingFor as r, envParam as t };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=param-BTzY0ne5-CW6ojZ3E.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"param-BTzY0ne5-CW6ojZ3E.mjs","names":[],"sources":["../../../1-prisma-cloud/1-extensions/target/dist/param-BTzY0ne5.mjs"],"sourcesContent":["import { isParamSource, paramSource } from \"@internal/core\";\nimport { blindCast } from \"@internal/foundation/casts\";\n//#region src/param.ts\n/**\n* Brands the payload `envParam` builds. Core's `paramSource()` is a public\n* SPI, so a user could bypass `envParam` and bind a raw `paramSource('x')`;\n* the brand lets `paramName` reject such a source (or another target's) with\n* a clear error instead of reading an absent `.name`.\n*/\nconst PRISMA_CLOUD_PARAM_SOURCE = blindCast(Symbol.for(\"prisma:prisma-cloud-param-source\"));\nconst RESERVED_PARAM_PREFIX = \"COMPOSER_\";\nconst POISONED_PARAM_NAMES = /* @__PURE__ */ new Set([\"DATABASE_URL\", \"DATABASE_URL_POOLED\"]);\n/**\n* Binds a param slot to a named Prisma Cloud platform env var — the non-secret\n* sibling of `envSecret` (spec: env-sourced config params). The platform\n* injects the value into the running instance per stage; the param's own\n* schema validates it at boot, unredacted. The name may not use the\n* framework's reserved `COMPOSER_` prefix or the poisoned\n* `DATABASE_URL(_POOLED)` keys — same parity as `envSecret`.\n*/\nfunction envParam(name) {\n\tif (typeof name !== \"string\" || name.length === 0) throw new Error(\"envParam() requires a non-empty platform env-var name, e.g. envParam('APP_ORIGIN').\");\n\tif (name.startsWith(RESERVED_PARAM_PREFIX)) throw new Error(`envParam name \"${name}\" may not start with \"${RESERVED_PARAM_PREFIX}\" — that prefix is reserved for the framework's own generated config keys.`);\n\tif (POISONED_PARAM_NAMES.has(name)) throw new Error(`envParam name \"${name}\" is reserved — ${[...POISONED_PARAM_NAMES].join(\" and \")} are poisoned at project provision and cannot back a param.`);\n\treturn paramSource({\n\t\t[PRISMA_CLOUD_PARAM_SOURCE]: true,\n\t\tname\n\t});\n}\n/** True only for a payload that `envParam` built — i.e. one carrying the brand. */\nfunction isEnvParamPayload(payload) {\n\treturn typeof payload === \"object\" && payload !== null && blindCast(payload)[PRISMA_CLOUD_PARAM_SOURCE] === true;\n}\n/** True iff a resolved param value is an env-sourced pointer this target built (as opposed to a literal, or a foreign/raw `ParamSource`). */\nfunction isEnvParamSource(value) {\n\treturn isParamSource(value) && isEnvParamPayload(value.payload);\n}\n/**\n* Reads the Prisma Cloud env-var name back out of a param binding's opaque\n* source. A source not built by `envParam` (a raw `paramSource(...)` or\n* another target's source) carries no name — reject it here. `paramName` runs\n* in preflight and at serialize before any value ever crosses the wire, so a\n* foreign source fails early and clearly rather than producing a broken\n* deploy with an undefined name.\n*/\nfunction paramName(binding) {\n\tconst { binding: bound } = binding;\n\tif (!isEnvParamSource(bound)) throw new Error(`param slot \"${binding.slot}\" of service \"${binding.serviceAddress}\" is bound to a source not created by envParam() — bind env-sourced params with envParam('NAME') from @prisma/composer-prisma-cloud.`);\n\treturn bound.payload.name;\n}\n/**\n* Finds the manifest entry for one service param slot. `serialize` calls this\n* only after confirming `buildConfig` resolved the slot to a `ParamSource`\n* (`isParamSource(value)`), so a miss here means `graph.params` and the\n* resolved `Config` have drifted — a Load invariant violation, surfaced\n* loudly rather than producing a pointer row with an undefined name.\n*/\nfunction paramBindingFor(bindings, serviceAddress, slot) {\n\tconst binding = bindings.find((b) => b.serviceAddress === serviceAddress && b.slot === slot);\n\tif (binding === void 0) throw new Error(`param slot \"${slot}\" of \"${serviceAddress}\" resolved to a source but has no bound entry in the manifest — Load should have recorded it.`);\n\treturn binding;\n}\n//#endregion\nexport { paramName as i, isEnvParamSource as n, paramBindingFor as r, envParam as t };\n\n//# sourceMappingURL=param-BTzY0ne5.mjs.map"],"mappings":";;;;;;;;;AASA,MAAM,4BAA4B,UAAU,OAAO,IAAI,kCAAkC,CAAC;AAC1F,MAAM,wBAAwB;AAC9B,MAAM,uCAAuC,IAAI,IAAI,CAAC,gBAAgB,qBAAqB,CAAC;;;;;;;;;AAS5F,SAAS,SAAS,MAAM;CACvB,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG,MAAM,IAAI,MAAM,qFAAqF;CACxJ,IAAI,KAAK,WAAW,qBAAqB,GAAG,MAAM,IAAI,MAAM,kBAAkB,KAAK,wBAAwB,sBAAsB,2EAA2E;CAC5M,IAAI,qBAAqB,IAAI,IAAI,GAAG,MAAM,IAAI,MAAM,kBAAkB,KAAK,kBAAkB,CAAC,GAAG,oBAAoB,CAAC,CAAC,KAAK,OAAO,EAAE,4DAA4D;CACjM,OAAO,YAAY;GACjB,4BAA4B;EAC7B;CACD,CAAC;AACF;;AAEA,SAAS,kBAAkB,SAAS;CACnC,OAAO,OAAO,YAAY,YAAY,YAAY,QAAQ,UAAU,OAAO,CAAC,CAAC,+BAA+B;AAC7G;;AAEA,SAAS,iBAAiB,OAAO;CAChC,OAAO,cAAc,KAAK,KAAK,kBAAkB,MAAM,OAAO;AAC/D;;;;;;;;;AASA,SAAS,UAAU,SAAS;CAC3B,MAAM,EAAE,SAAS,UAAU;CAC3B,IAAI,CAAC,iBAAiB,KAAK,GAAG,MAAM,IAAI,MAAM,eAAe,QAAQ,KAAK,gBAAgB,QAAQ,eAAe,qIAAqI;CACtP,OAAO,MAAM,QAAQ;AACtB;;;;;;;;AAQA,SAAS,gBAAgB,UAAU,gBAAgB,MAAM;CACxD,MAAM,UAAU,SAAS,MAAM,MAAM,EAAE,mBAAmB,kBAAkB,EAAE,SAAS,IAAI;CAC3F,IAAI,YAAY,KAAK,GAAG,MAAM,IAAI,MAAM,eAAe,KAAK,QAAQ,eAAe,8FAA8F;CACjL,OAAO;AACR"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
//#region ../../1-prisma-cloud/1-extensions/target/dist/pg-connection-CadPZuEK.mjs
|
|
2
|
+
/** Connection resilience helpers for Prisma Postgres cold-starts (FT-5226); no heavy imports (no `effect`/`alchemy`/`pg`), so the deploy lowerings, the pnPostgres runtime client, and bun-runnable services (the storage store, via the pure `@internal/prisma-cloud/connection` subpath) all share one implementation. */
|
|
3
|
+
/** Network-level socket failures node-postgres surfaces as `err.code`. */
|
|
4
|
+
const TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
5
|
+
"ECONNREFUSED",
|
|
6
|
+
"ECONNRESET",
|
|
7
|
+
"ETIMEDOUT",
|
|
8
|
+
"EPIPE",
|
|
9
|
+
"ENOTFOUND",
|
|
10
|
+
"EAI_AGAIN"
|
|
11
|
+
]);
|
|
12
|
+
/** Connection-establishment failure messages (no useful `err.code`). */
|
|
13
|
+
const TRANSIENT_MESSAGE_FRAGMENTS = [
|
|
14
|
+
"upstream database",
|
|
15
|
+
"connection terminated",
|
|
16
|
+
"connection refused",
|
|
17
|
+
"terminating connection",
|
|
18
|
+
"server closed the connection",
|
|
19
|
+
"connection timeout",
|
|
20
|
+
"timeout expired"
|
|
21
|
+
];
|
|
22
|
+
/** Whether an error is a transient connection failure worth retrying, as opposed to a real query error that must surface at once. */
|
|
23
|
+
function isTransientConnectionError(error) {
|
|
24
|
+
if (typeof error !== "object" || error === null) return false;
|
|
25
|
+
const code = "code" in error && typeof error.code === "string" ? error.code : void 0;
|
|
26
|
+
if (code !== void 0 && TRANSIENT_CODES.has(code)) return true;
|
|
27
|
+
const message = "message" in error && typeof error.message === "string" ? error.message.toLowerCase() : "";
|
|
28
|
+
return TRANSIENT_MESSAGE_FRAGMENTS.some((fragment) => message.includes(fragment));
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Rewrites a deprecating `sslmode` (`require`/`prefer`/`verify-ca`) to the
|
|
32
|
+
* explicit `verify-full` these already mean, silencing node-postgres's
|
|
33
|
+
* deprecation warning. `disable`/`no-verify`/unset are left untouched.
|
|
34
|
+
*/
|
|
35
|
+
function normalizeSslMode(url) {
|
|
36
|
+
let parsed;
|
|
37
|
+
try {
|
|
38
|
+
parsed = new URL(url);
|
|
39
|
+
} catch {
|
|
40
|
+
return url;
|
|
41
|
+
}
|
|
42
|
+
const sslmode = parsed.searchParams.get("sslmode");
|
|
43
|
+
if (sslmode === "require" || sslmode === "prefer" || sslmode === "verify-ca") {
|
|
44
|
+
parsed.searchParams.set("sslmode", "verify-full");
|
|
45
|
+
return parsed.toString();
|
|
46
|
+
}
|
|
47
|
+
return url;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Retries an operation past a transient connection failure, bounded (default
|
|
51
|
+
* ~1 min). `shouldRetry` decides what's transient — defaults to retrying
|
|
52
|
+
* everything; the runtime client passes {@link isTransientConnectionError}.
|
|
53
|
+
*/
|
|
54
|
+
async function withConnectionRetry(operation, opts = {}) {
|
|
55
|
+
const attempts = opts.attempts ?? 12;
|
|
56
|
+
const delayMs = opts.delayMs ?? 5e3;
|
|
57
|
+
const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
58
|
+
const shouldRetry = opts.shouldRetry ?? (() => true);
|
|
59
|
+
let lastError;
|
|
60
|
+
for (let attempt = 1; attempt <= attempts; attempt++) try {
|
|
61
|
+
return await operation();
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (!shouldRetry(error)) throw error;
|
|
64
|
+
lastError = error;
|
|
65
|
+
if (attempt < attempts) await sleep(delayMs);
|
|
66
|
+
}
|
|
67
|
+
throw lastError;
|
|
68
|
+
}
|
|
69
|
+
/** Retries acquiring a connection past a transient cold-start; {@link withConnectionRetry} with {@link isTransientConnectionError} fixed as the predicate. */
|
|
70
|
+
function retryTransientConnect(acquire, opts = {}) {
|
|
71
|
+
return withConnectionRetry(acquire, {
|
|
72
|
+
...opts,
|
|
73
|
+
shouldRetry: isTransientConnectionError
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
export { retryTransientConnect as n, withConnectionRetry as r, normalizeSslMode as t };
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=pg-connection-CadPZuEK-CF3FsSQu.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pg-connection-CadPZuEK-CF3FsSQu.mjs","names":[],"sources":["../../../1-prisma-cloud/1-extensions/target/dist/pg-connection-CadPZuEK.mjs"],"sourcesContent":["//#region src/pg-connection.ts\n/** Connection resilience helpers for Prisma Postgres cold-starts (FT-5226); no heavy imports (no `effect`/`alchemy`/`pg`), so the deploy lowerings, the pnPostgres runtime client, and bun-runnable services (the storage store, via the pure `@internal/prisma-cloud/connection` subpath) all share one implementation. */\n/** Network-level socket failures node-postgres surfaces as `err.code`. */\nconst TRANSIENT_CODES = /* @__PURE__ */ new Set([\n\t\"ECONNREFUSED\",\n\t\"ECONNRESET\",\n\t\"ETIMEDOUT\",\n\t\"EPIPE\",\n\t\"ENOTFOUND\",\n\t\"EAI_AGAIN\"\n]);\n/** Connection-establishment failure messages (no useful `err.code`). */\nconst TRANSIENT_MESSAGE_FRAGMENTS = [\n\t\"upstream database\",\n\t\"connection terminated\",\n\t\"connection refused\",\n\t\"terminating connection\",\n\t\"server closed the connection\",\n\t\"connection timeout\",\n\t\"timeout expired\"\n];\n/** Whether an error is a transient connection failure worth retrying, as opposed to a real query error that must surface at once. */\nfunction isTransientConnectionError(error) {\n\tif (typeof error !== \"object\" || error === null) return false;\n\tconst code = \"code\" in error && typeof error.code === \"string\" ? error.code : void 0;\n\tif (code !== void 0 && TRANSIENT_CODES.has(code)) return true;\n\tconst message = \"message\" in error && typeof error.message === \"string\" ? error.message.toLowerCase() : \"\";\n\treturn TRANSIENT_MESSAGE_FRAGMENTS.some((fragment) => message.includes(fragment));\n}\n/**\n* Rewrites a deprecating `sslmode` (`require`/`prefer`/`verify-ca`) to the\n* explicit `verify-full` these already mean, silencing node-postgres's\n* deprecation warning. `disable`/`no-verify`/unset are left untouched.\n*/\nfunction normalizeSslMode(url) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(url);\n\t} catch {\n\t\treturn url;\n\t}\n\tconst sslmode = parsed.searchParams.get(\"sslmode\");\n\tif (sslmode === \"require\" || sslmode === \"prefer\" || sslmode === \"verify-ca\") {\n\t\tparsed.searchParams.set(\"sslmode\", \"verify-full\");\n\t\treturn parsed.toString();\n\t}\n\treturn url;\n}\n/**\n* Retries an operation past a transient connection failure, bounded (default\n* ~1 min). `shouldRetry` decides what's transient — defaults to retrying\n* everything; the runtime client passes {@link isTransientConnectionError}.\n*/\nasync function withConnectionRetry(operation, opts = {}) {\n\tconst attempts = opts.attempts ?? 12;\n\tconst delayMs = opts.delayMs ?? 5e3;\n\tconst sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\tconst shouldRetry = opts.shouldRetry ?? (() => true);\n\tlet lastError;\n\tfor (let attempt = 1; attempt <= attempts; attempt++) try {\n\t\treturn await operation();\n\t} catch (error) {\n\t\tif (!shouldRetry(error)) throw error;\n\t\tlastError = error;\n\t\tif (attempt < attempts) await sleep(delayMs);\n\t}\n\tthrow lastError;\n}\n/** Retries acquiring a connection past a transient cold-start; {@link withConnectionRetry} with {@link isTransientConnectionError} fixed as the predicate. */\nfunction retryTransientConnect(acquire, opts = {}) {\n\treturn withConnectionRetry(acquire, {\n\t\t...opts,\n\t\tshouldRetry: isTransientConnectionError\n\t});\n}\n//#endregion\nexport { withConnectionRetry as i, normalizeSslMode as n, retryTransientConnect as r, isTransientConnectionError as t };\n\n//# sourceMappingURL=pg-connection-CadPZuEK.mjs.map"],"mappings":";;;AAGA,MAAM,kCAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AAED,MAAM,8BAA8B;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAEA,SAAS,2BAA2B,OAAO;CAC1C,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,OAAO,UAAU,SAAS,OAAO,MAAM,SAAS,WAAW,MAAM,OAAO,KAAK;CACnF,IAAI,SAAS,KAAK,KAAK,gBAAgB,IAAI,IAAI,GAAG,OAAO;CACzD,MAAM,UAAU,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,QAAQ,YAAY,IAAI;CACxG,OAAO,4BAA4B,MAAM,aAAa,QAAQ,SAAS,QAAQ,CAAC;AACjF;;;;;;AAMA,SAAS,iBAAiB,KAAK;CAC9B,IAAI;CACJ,IAAI;EACH,SAAS,IAAI,IAAI,GAAG;CACrB,QAAQ;EACP,OAAO;CACR;CACA,MAAM,UAAU,OAAO,aAAa,IAAI,SAAS;CACjD,IAAI,YAAY,aAAa,YAAY,YAAY,YAAY,aAAa;EAC7E,OAAO,aAAa,IAAI,WAAW,aAAa;EAChD,OAAO,OAAO,SAAS;CACxB;CACA,OAAO;AACR;;;;;;AAMA,eAAe,oBAAoB,WAAW,OAAO,CAAC,GAAG;CACxD,MAAM,WAAW,KAAK,YAAY;CAClC,MAAM,UAAU,KAAK,WAAW;CAChC,MAAM,QAAQ,KAAK,WAAW,OAAO,IAAI,SAAS,YAAY,WAAW,SAAS,EAAE,CAAC;CACrF,MAAM,cAAc,KAAK,sBAAsB;CAC/C,IAAI;CACJ,KAAK,IAAI,UAAU,GAAG,WAAW,UAAU,WAAW,IAAI;EACzD,OAAO,MAAM,UAAU;CACxB,SAAS,OAAO;EACf,IAAI,CAAC,YAAY,KAAK,GAAG,MAAM;EAC/B,YAAY;EACZ,IAAI,UAAU,UAAU,MAAM,MAAM,OAAO;CAC5C;CACA,MAAM;AACP;;AAEA,SAAS,sBAAsB,SAAS,OAAO,CAAC,GAAG;CAClD,OAAO,oBAAoB,SAAS;EACnC,GAAG;EACH,aAAa;CACd,CAAC;AACF"}
|
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { i as readOwnVersion, n as isValidSegment, r as readJsonFile, t as StateFile } from "./segments-NpKN-46R-B01DmCqy.mjs";
|
|
2
|
+
import { n as portNumbers, t as getPorts } from "./get-port-BYnpbW5H.mjs";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import * as http from "node:http";
|
|
7
|
+
//#region ../../1-prisma-cloud/0-lowering/dev-emulators/dist/instance-name-BF6J_weL.mjs
|
|
8
|
+
/**
|
|
9
|
+
* `pcdev-<app>-<database-id>` instance-name derivation (local-dev spec § 2
|
|
10
|
+
* `postgres-main.ts`): each half lowercased, every char outside `[a-z0-9]`
|
|
11
|
+
* replaced by `-`, runs collapsed, the combined name trimmed to 63 chars.
|
|
12
|
+
*
|
|
13
|
+
* A separate, side-effect-free module (not defined inline in
|
|
14
|
+
* `postgres-main.ts`) so it can be imported directly by tests without also
|
|
15
|
+
* running that file's own `main()` — `postgres-main.ts` is a daemon
|
|
16
|
+
* entrypoint script, always invoked as a subprocess, and calls `main()`
|
|
17
|
+
* unconditionally at module load.
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Deliberately linear, no ambiguous quantifiers: a per-character replace
|
|
21
|
+
* (no `+`, so no run-length backtracking surface), a bounded-quantifier
|
|
22
|
+
* collapse (`{2,}`, not alternation-with-quantifiers), and plain
|
|
23
|
+
* index-walking for the leading/trailing trim instead of a regex — a
|
|
24
|
+
* combined `+`-plus-alternation trim (`/^-+|-+$/g`) is exactly the shape
|
|
25
|
+
* CodeQL's polynomial-ReDoS check flags, whether or not this particular
|
|
26
|
+
* instance is provably safe.
|
|
27
|
+
*/
|
|
28
|
+
function slug(segment) {
|
|
29
|
+
const collapsed = segment.toLowerCase().replace(/[^a-z0-9]/g, "-").replace(/-{2,}/g, "-");
|
|
30
|
+
let start = 0;
|
|
31
|
+
let end = collapsed.length;
|
|
32
|
+
while (start < end && collapsed[start] === "-") start++;
|
|
33
|
+
while (end > start && collapsed[end - 1] === "-") end--;
|
|
34
|
+
return collapsed.slice(start, end);
|
|
35
|
+
}
|
|
36
|
+
function instanceNameFor(app, id) {
|
|
37
|
+
return `pcdev-${slug(app)}-${slug(id)}`.slice(0, 63);
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region ../../1-prisma-cloud/0-lowering/dev-emulators/dist/postgres-main.mjs
|
|
41
|
+
/**
|
|
42
|
+
* The Postgres emulator daemon (local-dev spec § 2 `postgres-main.ts`): a
|
|
43
|
+
* small local counterpart of hosted Postgres, hosting `@prisma/dev`'s
|
|
44
|
+
* `startPrismaDevServer()` — one named, persistent server per `Database`
|
|
45
|
+
* resource, several servers in this one daemon process. Loopback
|
|
46
|
+
* `node:http` JSON admin API; state under its `--state-dir`.
|
|
47
|
+
*
|
|
48
|
+
* `@prisma/dev` is imported dynamically from a CALLER-RESOLVED path (each
|
|
49
|
+
* admin request that needs it carries `prismaDevModulePath`) so the app
|
|
50
|
+
* owns its own Prisma version — this daemon has no `@prisma/dev` dependency
|
|
51
|
+
* of its own.
|
|
52
|
+
*
|
|
53
|
+
* Runs as its own OS process, started by `daemon.ts`'s `ensureDaemon` via
|
|
54
|
+
* `process.execPath <this file> --port <n> --state-dir <dir>`.
|
|
55
|
+
*/
|
|
56
|
+
const MIN_DATABASE_PORT = 51300;
|
|
57
|
+
const MAX_DATABASE_PORT = 65535;
|
|
58
|
+
const APPS_STATE_MODE = 384;
|
|
59
|
+
/** Spec § 2 step 5's pattern, applied to a fresh database-port allocation. */
|
|
60
|
+
const MAX_FRESH_PORT_CANDIDATES = 5;
|
|
61
|
+
const NOT_INSTALLED_MESSAGE = "local dev needs @prisma/dev for its local Postgres emulator — add \"prisma\" to your app's devDependencies.";
|
|
62
|
+
function maskCredentials(text) {
|
|
63
|
+
return text.replace(/:\/\/([^:@/\s]+):[^@/\s]+@/g, "://$1:***@");
|
|
64
|
+
}
|
|
65
|
+
function firstLine(text) {
|
|
66
|
+
return (text.split("\n")[0] ?? text).trim();
|
|
67
|
+
}
|
|
68
|
+
function isDatabaseRecord(value) {
|
|
69
|
+
return typeof value === "object" && value !== null && "id" in value && typeof value.id === "string" && "instanceName" in value && typeof value.instanceName === "string" && "databasePort" in value && typeof value.databasePort === "number" && "url" in value && typeof value.url === "string";
|
|
70
|
+
}
|
|
71
|
+
function isAppRecord(value) {
|
|
72
|
+
return typeof value === "object" && value !== null && "databases" in value && typeof value.databases === "object" && value.databases !== null && Object.values(value.databases).every(isDatabaseRecord);
|
|
73
|
+
}
|
|
74
|
+
function isAppsState(value) {
|
|
75
|
+
return typeof value === "object" && value !== null && Object.values(value).every(isAppRecord);
|
|
76
|
+
}
|
|
77
|
+
function isDatabaseBody(value) {
|
|
78
|
+
return typeof value === "object" && value !== null && "prismaDevModulePath" in value && typeof value.prismaDevModulePath === "string";
|
|
79
|
+
}
|
|
80
|
+
function isPrismaDevModule(value) {
|
|
81
|
+
return typeof value === "object" && value !== null && "startPrismaDevServer" in value && typeof value.startPrismaDevServer === "function";
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* `@prisma/dev` exports a `PortNotAvailableError` class with a `readonly
|
|
85
|
+
* port: number`, but the daemon dynamically imports the module from a
|
|
86
|
+
* caller-given path while the class identity checked here would come from
|
|
87
|
+
* whatever module graph THIS file's own bundle produced — two separate
|
|
88
|
+
* instantiations of the same logical class, so `instanceof` doesn't match
|
|
89
|
+
* across them (confirmed empirically: a real port conflict's `err
|
|
90
|
+
* instanceof mod.PortNotAvailableError` is `false` even though the error IS
|
|
91
|
+
* the port-conflict one). Duck-typing the documented shape — a `port`
|
|
92
|
+
* number matching the candidate we just tried — is what actually survives
|
|
93
|
+
* that boundary.
|
|
94
|
+
*/
|
|
95
|
+
/**
|
|
96
|
+
* The port a start refusal is about, when it is one of THIS attempt's ports.
|
|
97
|
+
* Duck-typed (`instanceof` fails across the dynamic-import boundary): every
|
|
98
|
+
* `@prisma/dev` port refusal — not-available, requested-twice, and
|
|
99
|
+
* belongs-to-another-server (its registry can claim a port no bind probe
|
|
100
|
+
* sees) — carries the offending port as `.port`, and any of the four ports
|
|
101
|
+
* we requested (database + the three aux listeners) can be the one refused.
|
|
102
|
+
*/
|
|
103
|
+
function portConflictOf(err, ports) {
|
|
104
|
+
if (typeof err !== "object" || err === null || !("port" in err)) return void 0;
|
|
105
|
+
const port = err.port;
|
|
106
|
+
return typeof port === "number" && ports.includes(port) ? port : void 0;
|
|
107
|
+
}
|
|
108
|
+
function isPrismaDevServer(value) {
|
|
109
|
+
if (!isStringKeyedRecord(value) || typeof value["close"] !== "function") return false;
|
|
110
|
+
const database = value["database"];
|
|
111
|
+
return isStringKeyedRecord(database) && typeof database["connectionString"] === "string";
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The live server behind a "name is already running" refusal, when there is
|
|
115
|
+
* one. A start that fails mid-boot (e.g. on a port another server's
|
|
116
|
+
* registry claims) can leave its state entry behind, so OUR OWN next
|
|
117
|
+
* attempt for the same name is refused. `@prisma/dev`'s
|
|
118
|
+
* `ServerAlreadyRunningError` carries the running server as a `.server`
|
|
119
|
+
* getter (duck-typed — `instanceof` fails across the dynamic-import
|
|
120
|
+
* boundary); its parent class (state entry exists but nothing actually
|
|
121
|
+
* runs) has no such getter, and a dead ghost resolves to null — both mean
|
|
122
|
+
* "nothing to adopt".
|
|
123
|
+
*/
|
|
124
|
+
async function adoptableServerOf(err) {
|
|
125
|
+
if (!isStringKeyedRecord(err) || !("server" in err)) return void 0;
|
|
126
|
+
if (err["name"] !== "ServerAlreadyRunningError") return void 0;
|
|
127
|
+
try {
|
|
128
|
+
const server = await err["server"];
|
|
129
|
+
return isPrismaDevServer(server) ? server : void 0;
|
|
130
|
+
} catch {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function isNameAlreadyTaken(err) {
|
|
135
|
+
return isStringKeyedRecord(err) && (err["name"] === "ServerAlreadyRunningError" || err["name"] === "ServerStateAlreadyExistsError");
|
|
136
|
+
}
|
|
137
|
+
/** The port of a postgres connection URL, when it parses as one. */
|
|
138
|
+
function databasePortOf(connectionString) {
|
|
139
|
+
try {
|
|
140
|
+
const port = Number(new URL(connectionString).port);
|
|
141
|
+
return Number.isInteger(port) && port > 0 ? port : void 0;
|
|
142
|
+
} catch {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* A dynamic `import()` failure's own message routinely names a SECOND path
|
|
148
|
+
* (e.g. bun's "Cannot find module '<target>' from '<importer>'") — the
|
|
149
|
+
* importer half is this daemon's own internal location, not anything the
|
|
150
|
+
* caller gave us, and has no business in a response body. Rather than try
|
|
151
|
+
* to scrub an arbitrary underlying message for every runtime's own error
|
|
152
|
+
* phrasing, the resolution-failure case names only what the caller
|
|
153
|
+
* supplied — the pinned message plus the given `prismaDevModulePath`, and
|
|
154
|
+
* nothing else. (A DIFFERENT case — a module that resolves fine but whose
|
|
155
|
+
* `startPrismaDevServer()` call itself fails — still surfaces its
|
|
156
|
+
* underlying text verbatim, credential-masked, per spec § 2.)
|
|
157
|
+
*/
|
|
158
|
+
async function importPrismaDev(prismaDevModulePath) {
|
|
159
|
+
let mod;
|
|
160
|
+
try {
|
|
161
|
+
mod = await import(pathToFileURL(prismaDevModulePath).href);
|
|
162
|
+
} catch {
|
|
163
|
+
throw new Error(`${NOT_INSTALLED_MESSAGE} (could not resolve "${prismaDevModulePath}")`);
|
|
164
|
+
}
|
|
165
|
+
if (!isPrismaDevModule(mod)) throw new Error(`${NOT_INSTALLED_MESSAGE} ("${prismaDevModulePath}" is not a @prisma/dev module)`);
|
|
166
|
+
return mod;
|
|
167
|
+
}
|
|
168
|
+
function isStringKeyedRecord(value) {
|
|
169
|
+
return typeof value === "object" && value !== null;
|
|
170
|
+
}
|
|
171
|
+
function isPrismaDevInternalStateModule(value) {
|
|
172
|
+
return isStringKeyedRecord(value) && typeof value["deleteServer"] === "function";
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* `@prisma/dev`'s own package.json declares `./internal/state`, whose
|
|
176
|
+
* `deleteServer(name)` actually removes a stateful server's persisted PGlite
|
|
177
|
+
* data — `startPrismaDevServer`'s public surface only starts/closes a live
|
|
178
|
+
* server, never deletes what a closed one left on disk. Resolved by reading
|
|
179
|
+
* the SAME package's own `exports` map (walked up from the caller-given
|
|
180
|
+
* entry path to find `@prisma/dev`'s `package.json`), never by guessing at
|
|
181
|
+
* `dist/` file layout.
|
|
182
|
+
*/
|
|
183
|
+
async function importPrismaDevInternalState(prismaDevModulePath) {
|
|
184
|
+
let dir = path.dirname(prismaDevModulePath);
|
|
185
|
+
for (;;) {
|
|
186
|
+
const pkgPath = path.join(dir, "package.json");
|
|
187
|
+
if (fs.existsSync(pkgPath)) {
|
|
188
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
189
|
+
if (isStringKeyedRecord(pkg) && pkg["name"] === "@prisma/dev" && isStringKeyedRecord(pkg["exports"])) {
|
|
190
|
+
const entry = pkg["exports"]["./internal/state"];
|
|
191
|
+
const target = resolveExportTarget(entry);
|
|
192
|
+
if (target === void 0) throw new Error(`"@prisma/dev" at "${dir}" does not declare an "./internal/state" export — cannot delete its persisted database data.`);
|
|
193
|
+
const mod = await import(pathToFileURL(path.join(dir, target)).href);
|
|
194
|
+
if (isPrismaDevInternalStateModule(mod)) return mod;
|
|
195
|
+
throw new Error(`"@prisma/dev"'s "./internal/state" export at "${dir}" has no deleteServer.`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const parent = path.dirname(dir);
|
|
199
|
+
if (parent === dir) throw new Error(`could not find "@prisma/dev"'s package.json above "${prismaDevModulePath}".`);
|
|
200
|
+
dir = parent;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function resolveExportTarget(entry) {
|
|
204
|
+
if (typeof entry === "string") return entry;
|
|
205
|
+
if (!isStringKeyedRecord(entry)) return void 0;
|
|
206
|
+
const nested = entry["import"] ?? entry["require"] ?? entry["default"];
|
|
207
|
+
if (typeof nested === "string") return nested;
|
|
208
|
+
if (isStringKeyedRecord(nested)) {
|
|
209
|
+
const def = nested["default"];
|
|
210
|
+
if (typeof def === "string") return def;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function parseArgs(argv) {
|
|
214
|
+
let port;
|
|
215
|
+
let stateDir;
|
|
216
|
+
for (let i = 0; i < argv.length; i++) if (argv[i] === "--port") port = Number(argv[i + 1]);
|
|
217
|
+
else if (argv[i] === "--state-dir") stateDir = argv[i + 1];
|
|
218
|
+
if (port === void 0 || Number.isNaN(port)) throw new Error("postgres-main: --port <n> is required");
|
|
219
|
+
if (stateDir === void 0) throw new Error("postgres-main: --state-dir <dir> is required");
|
|
220
|
+
return {
|
|
221
|
+
port,
|
|
222
|
+
stateDir
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function readBody(req) {
|
|
226
|
+
return new Promise((resolve, reject) => {
|
|
227
|
+
const chunks = [];
|
|
228
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
229
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
230
|
+
req.on("error", reject);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
function main() {
|
|
234
|
+
const { port, stateDir } = parseArgs(process.argv.slice(2));
|
|
235
|
+
const ownVersion = readOwnVersion();
|
|
236
|
+
const appsJsonPath = path.join(stateDir, "apps.json");
|
|
237
|
+
const stateFile = new StateFile(appsJsonPath, APPS_STATE_MODE);
|
|
238
|
+
let state = {};
|
|
239
|
+
const runtimes = /* @__PURE__ */ new Map();
|
|
240
|
+
const liveAuxPorts = /* @__PURE__ */ new Set();
|
|
241
|
+
const auxPortsByInstance = /* @__PURE__ */ new Map();
|
|
242
|
+
function releaseAuxPorts(instanceName) {
|
|
243
|
+
for (const p of auxPortsByInstance.get(instanceName) ?? []) liveAuxPorts.delete(p);
|
|
244
|
+
auxPortsByInstance.delete(instanceName);
|
|
245
|
+
}
|
|
246
|
+
function schedulePersist() {
|
|
247
|
+
stateFile.write(state);
|
|
248
|
+
}
|
|
249
|
+
function getOrCreateApp(app) {
|
|
250
|
+
let appRec = state[app];
|
|
251
|
+
if (!appRec) {
|
|
252
|
+
appRec = { databases: {} };
|
|
253
|
+
state[app] = appRec;
|
|
254
|
+
}
|
|
255
|
+
return appRec;
|
|
256
|
+
}
|
|
257
|
+
function usedDatabasePorts() {
|
|
258
|
+
const ports = /* @__PURE__ */ new Set();
|
|
259
|
+
for (const appRec of Object.values(state)) for (const db of Object.values(appRec.databases)) ports.add(db.databasePort);
|
|
260
|
+
return ports;
|
|
261
|
+
}
|
|
262
|
+
async function smallestUnusedDatabasePort(min, alsoExclude = /* @__PURE__ */ new Set()) {
|
|
263
|
+
return getPorts({
|
|
264
|
+
port: portNumbers(min, MAX_DATABASE_PORT),
|
|
265
|
+
exclude: [...usedDatabasePorts(), ...alsoExclude]
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
/** Three fresh, mutually distinct ports for a server's own HTTP/shadow-database/streams listeners — never persisted, only unique right now. */
|
|
269
|
+
async function allocateAuxPorts(excluding) {
|
|
270
|
+
const taken = /* @__PURE__ */ new Set([
|
|
271
|
+
...usedDatabasePorts(),
|
|
272
|
+
...liveAuxPorts,
|
|
273
|
+
...excluding
|
|
274
|
+
]);
|
|
275
|
+
const httpPort = await getPorts({
|
|
276
|
+
port: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),
|
|
277
|
+
exclude: taken
|
|
278
|
+
});
|
|
279
|
+
taken.add(httpPort);
|
|
280
|
+
const shadowDatabasePort = await getPorts({
|
|
281
|
+
port: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),
|
|
282
|
+
exclude: taken
|
|
283
|
+
});
|
|
284
|
+
taken.add(shadowDatabasePort);
|
|
285
|
+
return {
|
|
286
|
+
httpPort,
|
|
287
|
+
shadowDatabasePort,
|
|
288
|
+
streamsPort: await getPorts({
|
|
289
|
+
port: portNumbers(MIN_DATABASE_PORT, MAX_DATABASE_PORT),
|
|
290
|
+
exclude: taken
|
|
291
|
+
})
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
const inflightEnsures = /* @__PURE__ */ new Map();
|
|
295
|
+
/** Concurrent PUTs for the same database coalesce onto one start — a second `startPrismaDevServer` for a name whose first start is still booting fails as "already running". */
|
|
296
|
+
function ensureDatabase(app, id, prismaDevModulePath) {
|
|
297
|
+
const instanceName = instanceNameFor(app, id);
|
|
298
|
+
const inflight = inflightEnsures.get(instanceName);
|
|
299
|
+
if (inflight) return inflight;
|
|
300
|
+
const run = ensureDatabaseSerialized(app, id, prismaDevModulePath, instanceName).finally(() => {
|
|
301
|
+
inflightEnsures.delete(instanceName);
|
|
302
|
+
});
|
|
303
|
+
inflightEnsures.set(instanceName, run);
|
|
304
|
+
return run;
|
|
305
|
+
}
|
|
306
|
+
async function ensureDatabaseSerialized(app, id, prismaDevModulePath, instanceName) {
|
|
307
|
+
const appRec = getOrCreateApp(app);
|
|
308
|
+
const existingRecord = appRec.databases[id];
|
|
309
|
+
const runningServer = runtimes.get(instanceName);
|
|
310
|
+
if (existingRecord && runningServer) return { url: existingRecord.url };
|
|
311
|
+
const prismaDev = await importPrismaDev(prismaDevModulePath);
|
|
312
|
+
const isFreshAllocation = existingRecord === void 0;
|
|
313
|
+
let dbPort = existingRecord?.databasePort ?? await smallestUnusedDatabasePort(MIN_DATABASE_PORT);
|
|
314
|
+
const conflicted = /* @__PURE__ */ new Set();
|
|
315
|
+
for (let attempt = 1;; attempt++) {
|
|
316
|
+
const aux = await allocateAuxPorts(/* @__PURE__ */ new Set([dbPort, ...conflicted]));
|
|
317
|
+
try {
|
|
318
|
+
const server = await prismaDev.startPrismaDevServer({
|
|
319
|
+
name: instanceName,
|
|
320
|
+
databasePort: dbPort,
|
|
321
|
+
port: aux.httpPort,
|
|
322
|
+
shadowDatabasePort: aux.shadowDatabasePort,
|
|
323
|
+
streamsPort: aux.streamsPort,
|
|
324
|
+
persistenceMode: "stateful"
|
|
325
|
+
});
|
|
326
|
+
const url = server.database.connectionString;
|
|
327
|
+
runtimes.set(instanceName, server);
|
|
328
|
+
liveAuxPorts.add(aux.httpPort);
|
|
329
|
+
liveAuxPorts.add(aux.shadowDatabasePort);
|
|
330
|
+
liveAuxPorts.add(aux.streamsPort);
|
|
331
|
+
auxPortsByInstance.set(instanceName, [
|
|
332
|
+
aux.httpPort,
|
|
333
|
+
aux.shadowDatabasePort,
|
|
334
|
+
aux.streamsPort
|
|
335
|
+
]);
|
|
336
|
+
appRec.databases[id] = {
|
|
337
|
+
id,
|
|
338
|
+
instanceName,
|
|
339
|
+
databasePort: dbPort,
|
|
340
|
+
url
|
|
341
|
+
};
|
|
342
|
+
schedulePersist();
|
|
343
|
+
return { url };
|
|
344
|
+
} catch (err) {
|
|
345
|
+
if (isNameAlreadyTaken(err)) {
|
|
346
|
+
const ghost = await adoptableServerOf(err);
|
|
347
|
+
if (ghost !== void 0) {
|
|
348
|
+
const url = ghost.database.connectionString;
|
|
349
|
+
runtimes.set(instanceName, ghost);
|
|
350
|
+
appRec.databases[id] = {
|
|
351
|
+
id,
|
|
352
|
+
instanceName,
|
|
353
|
+
databasePort: databasePortOf(url) ?? dbPort,
|
|
354
|
+
url
|
|
355
|
+
};
|
|
356
|
+
schedulePersist();
|
|
357
|
+
return { url };
|
|
358
|
+
}
|
|
359
|
+
if (attempt < MAX_FRESH_PORT_CANDIDATES) {
|
|
360
|
+
await (await importPrismaDevInternalState(prismaDevModulePath)).deleteServer(instanceName);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
const conflictPort = portConflictOf(err, [
|
|
365
|
+
dbPort,
|
|
366
|
+
aux.httpPort,
|
|
367
|
+
aux.shadowDatabasePort,
|
|
368
|
+
aux.streamsPort
|
|
369
|
+
]);
|
|
370
|
+
if (!(conflictPort !== void 0 && attempt < MAX_FRESH_PORT_CANDIDATES && (conflictPort !== dbPort || isFreshAllocation))) {
|
|
371
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
372
|
+
throw new Error(`postgres emulator failed to start database "${instanceName}" on port ${String(dbPort)}: ${maskCredentials(firstLine(reason))}`);
|
|
373
|
+
}
|
|
374
|
+
conflicted.add(conflictPort);
|
|
375
|
+
if (conflictPort === dbPort) dbPort = await smallestUnusedDatabasePort(dbPort + 1, conflicted);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
async function deleteApp(app, prismaDevModulePathHint) {
|
|
380
|
+
const appRec = state[app];
|
|
381
|
+
if (!appRec) return;
|
|
382
|
+
const entries = Object.values(appRec.databases);
|
|
383
|
+
for (const db of entries) {
|
|
384
|
+
const server = runtimes.get(db.instanceName);
|
|
385
|
+
if (server) {
|
|
386
|
+
await server.close().catch(() => void 0);
|
|
387
|
+
runtimes.delete(db.instanceName);
|
|
388
|
+
releaseAuxPorts(db.instanceName);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (entries.length > 0 && prismaDevModulePathHint) {
|
|
392
|
+
const { deleteServer } = await importPrismaDevInternalState(prismaDevModulePathHint);
|
|
393
|
+
for (const db of entries) await deleteServer(db.instanceName);
|
|
394
|
+
}
|
|
395
|
+
delete state[app];
|
|
396
|
+
schedulePersist();
|
|
397
|
+
}
|
|
398
|
+
function json(res, status, body) {
|
|
399
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
400
|
+
res.end(JSON.stringify(body));
|
|
401
|
+
}
|
|
402
|
+
function text(res, status, body) {
|
|
403
|
+
res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
|
|
404
|
+
res.end(body);
|
|
405
|
+
}
|
|
406
|
+
function badSegment(res, segment) {
|
|
407
|
+
text(res, 400, `invalid path segment "${segment}": must match /^[a-z0-9][a-z0-9-]*$/ and be at most 63 characters`);
|
|
408
|
+
}
|
|
409
|
+
function databaseView(db) {
|
|
410
|
+
return {
|
|
411
|
+
id: db.id,
|
|
412
|
+
url: db.url,
|
|
413
|
+
instanceName: db.instanceName,
|
|
414
|
+
databasePort: db.databasePort
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/** The most recently observed `prismaDevModulePath` for any database of `app` — DELETE has no body of its own to carry one. */
|
|
418
|
+
const recentPrismaDevModulePath = /* @__PURE__ */ new Map();
|
|
419
|
+
function lastKnownPrismaDevModulePath(app) {
|
|
420
|
+
return recentPrismaDevModulePath.get(app);
|
|
421
|
+
}
|
|
422
|
+
async function handleRequest(req, res) {
|
|
423
|
+
const url = new URL(req.url ?? "/", `http://127.0.0.1:${String(port)}`);
|
|
424
|
+
const method = req.method ?? "GET";
|
|
425
|
+
const segments = url.pathname.split("/").filter((s) => s.length > 0).map((s) => decodeURIComponent(s));
|
|
426
|
+
if (method === "GET" && segments.length === 1 && segments[0] === "health") return json(res, 200, { version: ownVersion });
|
|
427
|
+
if (segments[0] === "apps" && segments.length >= 2) {
|
|
428
|
+
const app = segments[1];
|
|
429
|
+
if (app === void 0 || !isValidSegment(app)) return badSegment(res, app ?? "");
|
|
430
|
+
if (method === "PUT" && segments.length === 4 && segments[2] === "databases") {
|
|
431
|
+
const id = segments[3];
|
|
432
|
+
if (id === void 0 || !isValidSegment(id)) return badSegment(res, id ?? "");
|
|
433
|
+
const raw = await readBody(req);
|
|
434
|
+
let parsed;
|
|
435
|
+
try {
|
|
436
|
+
parsed = JSON.parse(raw.toString("utf8"));
|
|
437
|
+
} catch {
|
|
438
|
+
return text(res, 400, "malformed JSON body");
|
|
439
|
+
}
|
|
440
|
+
if (!isDatabaseBody(parsed)) return text(res, 400, "malformed database body: expected { \"prismaDevModulePath\": string }");
|
|
441
|
+
recentPrismaDevModulePath.set(app, parsed.prismaDevModulePath);
|
|
442
|
+
return json(res, 200, await ensureDatabase(app, id, parsed.prismaDevModulePath));
|
|
443
|
+
}
|
|
444
|
+
if (method === "GET" && segments.length === 3 && segments[2] === "databases") {
|
|
445
|
+
const appRec = state[app];
|
|
446
|
+
return json(res, 200, appRec ? Object.values(appRec.databases).map(databaseView) : []);
|
|
447
|
+
}
|
|
448
|
+
if (method === "DELETE" && segments.length === 2) {
|
|
449
|
+
await deleteApp(app, lastKnownPrismaDevModulePath(app));
|
|
450
|
+
res.writeHead(204);
|
|
451
|
+
res.end();
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
res.writeHead(404);
|
|
456
|
+
res.end();
|
|
457
|
+
}
|
|
458
|
+
const server = http.createServer((req, res) => {
|
|
459
|
+
handleRequest(req, res).catch((err) => {
|
|
460
|
+
if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" });
|
|
461
|
+
res.end(err instanceof Error ? maskCredentials(err.message) : String(err));
|
|
462
|
+
});
|
|
463
|
+
});
|
|
464
|
+
async function shutdown() {
|
|
465
|
+
for (const server of runtimes.values()) await server.close().catch(() => void 0);
|
|
466
|
+
await stateFile.flush();
|
|
467
|
+
server.close();
|
|
468
|
+
process.exit(0);
|
|
469
|
+
}
|
|
470
|
+
process.on("SIGTERM", () => void shutdown());
|
|
471
|
+
process.on("SIGINT", () => void shutdown());
|
|
472
|
+
process.on("unhandledRejection", (reason) => {
|
|
473
|
+
console.error("postgres-main: unhandled rejection from background work:", reason instanceof Error ? maskCredentials(reason.stack ?? reason.message) : reason);
|
|
474
|
+
});
|
|
475
|
+
process.on("uncaughtException", (err) => {
|
|
476
|
+
console.error("postgres-main: uncaught exception from background work:", err instanceof Error ? maskCredentials(err.stack ?? err.message) : err);
|
|
477
|
+
});
|
|
478
|
+
readJsonFile(appsJsonPath, isAppsState).then((loaded) => {
|
|
479
|
+
if (loaded) state = loaded;
|
|
480
|
+
server.listen(port, "127.0.0.1", () => {
|
|
481
|
+
console.log(`[dev-emulators] postgres-main listening on 127.0.0.1:${String(port)}`);
|
|
482
|
+
});
|
|
483
|
+
}).catch((err) => {
|
|
484
|
+
console.error("postgres-main: failed to load state", err);
|
|
485
|
+
process.exit(1);
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
main();
|
|
489
|
+
//#endregion
|
|
490
|
+
export {};
|
|
491
|
+
|
|
492
|
+
//# sourceMappingURL=postgres-main.mjs.map
|