diff --git a/apps/hosted/server/src/implementation/provisioning.ts b/apps/hosted/server/src/implementation/provisioning.ts index 003c8d1db8..fc7d48b97c 100644 --- a/apps/hosted/server/src/implementation/provisioning.ts +++ b/apps/hosted/server/src/implementation/provisioning.ts @@ -1,5 +1,13 @@ /** Host-owned lifecycle jobs. No browser session, secrets, or live request enters the queue. */ -import { BuildStage, StorageError } from "@executor-js/sdk/core"; +import { + BuildStage, + RegistryBuildFailureFields, + safeExactSemver, + safeHttpStatus, + safeNpmPackageName, + safeRegistryOrigin, + StorageError, +} from "@executor-js/sdk/core"; import { Effect, Exit, Schedule, Schema } from "effect"; import { SqlClient } from "effect/sql"; import { traceFailure } from "@executor-js/telemetry/failed-span"; @@ -33,26 +41,9 @@ const FailureCause = Schema.Struct({ tag: Schema.String, /** The build step a failed build names, such as `dependencies`; a closed set, never text. */ stage: Schema.optional(BuildStage), - package: Schema.optional(Schema.String), - version: Schema.optional(Schema.String), - registry: Schema.optional(Schema.String), - status: Schema.optional(Schema.Int), + ...RegistryBuildFailureFields, }); type FailureCause = typeof FailureCause.Type; -/** A log line keeps one record: no control character may enter it from a field. */ -const hasControlCharacter = (value: string) => - [...value].some((character) => { - const code = character.codePointAt(0) ?? 0; - return code < 0x20 || code === 0x7f; - }); -/** A bounded name an error states as its own field, never text quoted from a response. */ -const causeName = (value: unknown) => - typeof value === "string" && - value.length > 0 && - value.length <= 200 && - !hasControlCharacter(value) - ? value - : undefined; /** Only a tag an error class names, so a response cannot choose the text logged. */ const causeTag = (value: unknown) => typeof value === "object" && @@ -62,14 +53,6 @@ const causeTag = (value: unknown) => /^[A-Za-z][A-Za-z0-9]{0,63}$/u.test(value._tag) ? value._tag : undefined; -const causeOrigin = (value: unknown) => { - if (typeof value !== "string" || value.length === 0) return undefined; - try { - return new URL(value).origin; - } catch { - return undefined; - } -}; /** * Project a failure onto the fields that may reach a background log: its tagged name and, when an * error or its cause chain states them as typed fields, the build stage, package, version, registry @@ -86,17 +69,11 @@ const failureCause = (error: unknown): FailureCause => { for (let depth = 0; depth < 4 && typeof current === "object" && current !== null; depth += 1) { const value = current as Record; tag = tag === "Unknown" ? (causeTag(value) ?? tag) : tag; - packageName ??= causeName(value.dependency) ?? causeName(value.package); - version ??= causeName(value.version); - registry ??= causeOrigin(value.registry); + packageName ??= safeNpmPackageName(value.package) ?? safeNpmPackageName(value.dependency); + version ??= safeExactSemver(value.version); + registry ??= safeRegistryOrigin(value.registry); stage ??= Schema.is(BuildStage)(value.stage) ? value.stage : undefined; - status ??= - typeof value.status === "number" && - Number.isInteger(value.status) && - value.status >= 100 && - value.status <= 599 - ? value.status - : undefined; + status ??= safeHttpStatus(value.status); current = value.cause; } return { diff --git a/e2e/support/credentialed-registry.ts b/e2e/support/credentialed-registry.ts index 6975aed8c6..67a43cda51 100644 --- a/e2e/support/credentialed-registry.ts +++ b/e2e/support/credentialed-registry.ts @@ -1,7 +1,8 @@ /** * A product npm registry reached through a URL that carries synthetic credentials in its userinfo * and a token in its query, as an operator's private registry URL can. It forwards every request - * to the suite's registry, so the product starts and builds as usual. + * to the suite's registry, except the given path, which redirects there instead so the product + * sees the response on a different origin. * * The package installer appends each package's path to the configured URL, so with a query in * that URL the path arrives after the token: `/mirror?token=/`. The server reads @@ -11,48 +12,54 @@ import { randomUUID } from "node:crypto"; import { createServer } from "node:http"; import { Config, Effect } from "effect"; -export const credentialedRegistry = Effect.gen(function* () { - const upstream = (yield* Config.String("E2E_NPM_REGISTRY").pipe( - Config.withDefault("https://registry.npmjs.org"), - )).replace(/\/$/, ""); - const user = `synthetic-user-${randomUUID().slice(0, 8)}`; - const password = `synthetic-password-${randomUUID().slice(0, 8)}`; - const token = `synthetic-token-${randomUUID().slice(0, 8)}`; - const tokenPrefix = `/mirror?token=${token}`; - const server = yield* Effect.acquireRelease( - Effect.callback>((resume) => { - const server = createServer((request, response) => { - const url = request.url ?? "/"; - const path = url.startsWith(tokenPrefix) ? url.slice(tokenPrefix.length) || "/" : url; - fetch(`${upstream}${path}`).then( - (reply) => - reply.arrayBuffer().then((bytes) => { - response.writeHead(reply.status, { - "content-type": reply.headers.get("content-type") ?? "application/octet-stream", - }); - response.end(Buffer.from(bytes)); - }), - () => { - response.writeHead(502); +export const credentialedRegistry = (redirectPath: string) => + Effect.gen(function* () { + const upstream = (yield* Config.String("E2E_NPM_REGISTRY").pipe( + Config.withDefault("https://registry.npmjs.org"), + )).replace(/\/$/, ""); + const user = `synthetic-user-${randomUUID().slice(0, 8)}`; + const password = `synthetic-password-${randomUUID().slice(0, 8)}`; + const token = `synthetic-token-${randomUUID().slice(0, 8)}`; + const tokenPrefix = `/mirror?token=${token}`; + const server = yield* Effect.acquireRelease( + Effect.callback>((resume) => { + const server = createServer((request, response) => { + const url = request.url ?? "/"; + const path = url.startsWith(tokenPrefix) ? url.slice(tokenPrefix.length) || "/" : url; + if (path === redirectPath) { + response.writeHead(302, { location: `${upstream}${path}` }); response.end(); - }, - ); - }); - server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); - }), - (server) => - Effect.callback((resume) => { - server.close(() => resume(Effect.void)); + return; + } + fetch(`${upstream}${path}`).then( + (reply) => + reply.arrayBuffer().then((bytes) => { + response.writeHead(reply.status, { + "content-type": reply.headers.get("content-type") ?? "application/octet-stream", + }); + response.end(Buffer.from(bytes)); + }), + () => { + response.writeHead(502); + response.end(); + }, + ); + }); + server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); }), - ); - const address = server.address(); - if (address === null || typeof address === "string") - return yield* Effect.die("The credentialed registry has no port"); - const host = `127.0.0.1:${address.port}`; - return { - url: `http://${user}:${password}@${host}/mirror?token=${token}`, - /** The registry's host and path, which a failure may show. */ - location: `http://${host}/mirror`, - secrets: [user, password, token], - }; -}); + (server) => + Effect.callback((resume) => { + server.close(() => resume(Effect.void)); + }), + ); + const address = server.address(); + if (address === null || typeof address === "string") + return yield* Effect.die("The credentialed registry has no port"); + const host = `127.0.0.1:${address.port}`; + return { + url: `http://${user}:${password}@${host}/mirror?token=${token}`, + /** The registry's host and path, which a failure may show. */ + location: `http://${host}/mirror`, + secrets: [user, password, token], + }; + }); diff --git a/e2e/tests/local-registry-credentials.spec.ts b/e2e/tests/local-registry-credentials.spec.ts index 0a47ffb3ba..78e190e6b2 100644 --- a/e2e/tests/local-registry-credentials.spec.ts +++ b/e2e/tests/local-registry-credentials.spec.ts @@ -18,10 +18,16 @@ const BuildFailed = Schema.Struct({ _tag: Schema.Literal("VersionBuildFailed"), stage: Schema.String, message: Schema.String, + package: Schema.String, + version: Schema.optionalKey(Schema.String), + registry: Schema.String, + status: Schema.optionalKey(Schema.Int), }); /** A package the suite's registry does not serve, so installing it fails with the registry's 404. */ const missingPackage = "@executor-fixture/missing-package"; +const redirectedPackage = "redirected-missing-package"; +const longVersion = `1.0.0+${"a".repeat(195)}`; layer(TestLive, { excludeTestServices: true })("Local registry credentials", (it) => { it.effect( @@ -30,42 +36,59 @@ layer(TestLive, { excludeTestServices: true })("Local registry credentials", (it withCase( context, Effect.gen(function* () { - const registry = yield* credentialedRegistry; + const registry = yield* credentialedRegistry(`/${redirectedPackage}`); const local = yield* startLocalProduct({ EXECUTOR_NPM_REGISTRY: registry.url }); - const deployed = yield* local.request("POST", "/v1/apps/deploy", { - owner: "registry-credentials-e2e", - name: `Registry credentials ${randomUUID().slice(0, 8)}`, - files: [ - { - path: "index.ts", - content: `import { defineApp, query, object, router } from "apps"; -import missing from "${missingPackage}"; + for (const { name, version, reportedVersion, status } of [ + { name: missingPackage, version: "1.0.0", reportedVersion: "1.0.0", status: 404 }, + { + name: "@executor-fixture/_worker", + version: "1.0.0", + reportedVersion: "1.0.0", + status: 404, + }, + { name: "@executor-fixture/-worker", version: longVersion, status: 404 }, + { name: redirectedPackage, version: "1.0.0", reportedVersion: "1.0.0" }, + ]) { + const deployed = yield* local.request("POST", "/v1/apps/deploy", { + owner: "registry-credentials-e2e", + name: `Registry credentials ${randomUUID().slice(0, 8)}`, + files: [ + { + path: "index.ts", + content: `import { defineApp, query, object, router } from "apps"; +import missing from "${name}"; export default defineApp({}, { tools: router({ missing: query({ input: object({}) }, async () => String(missing)), }) });`, - }, - { - path: "package.json", - content: JSON.stringify({ - type: "module", - dependencies: withApps({ [missingPackage]: "1.0.0" }), - }), - }, - ], - }); - expect(deployed.status, deployed.text).toBe(422); - const failed = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(BuildFailed))( - deployed.text, - ); - for (const secret of registry.secrets) - expect(deployed.text, "the failure omits the registry's credentials").not.toContain( - secret, + }, + { + path: "package.json", + content: JSON.stringify({ + type: "module", + dependencies: withApps({ [name]: version }), + }), + }, + ], + }); + expect(deployed.status, deployed.text).toBe(422); + const failed = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(BuildFailed))( + deployed.text, ); - // The installer's failure reaches the deployer through the bundler's import resolution. - expect(failed.stage).toBe("compile"); - // Still useful: it names the package and the registry's host and path. - expect(failed.message).toContain(`Installing ${missingPackage}@1.0.0 failed`); - expect(failed.message).toContain(registry.location); + for (const secret of registry.secrets) + expect(deployed.text, "the failure omits the registry's credentials").not.toContain( + secret, + ); + // The installer's failure reaches the deployer through the bundler's import resolution. + expect(failed.stage).toBe("compile"); + expect(failed.package).toBe(name); + expect(failed.version).toBe(reportedVersion); + expect(failed.registry).toBe(new URL(registry.url).origin); + expect(failed.status).toBe(status); + // The message still names the dependency, registry path and actual HTTP response. + expect(failed.message).toContain(`Installing ${name}@${version} failed`); + expect(failed.message).toContain(registry.location); + expect(failed.message).toContain("HTTP 404"); + } }), ), 120_000, diff --git a/e2e/tests/self-host-provisioning-failure.spec.ts b/e2e/tests/self-host-provisioning-failure.spec.ts index 8ba9540ed5..5f87ee7ecd 100644 --- a/e2e/tests/self-host-provisioning-failure.spec.ts +++ b/e2e/tests/self-host-provisioning-failure.spec.ts @@ -1,13 +1,14 @@ /** * A self-host whose npm registry cannot serve the `apps` package keeps failing its default app - * installation. The provisioning log names the failed step by its tagged cause, and never quotes - * the registry's credentials, path or the packages it was asked for. + * installation. The provisioning log names the failed step and package without quoting the + * registry's credentials, path, query or response. */ import { randomUUID } from "node:crypto"; import { createServer } from "node:http"; import { expect, layer } from "@effect/vitest"; import { Effect, FileSystem, Layer, Option, Schedule, Schema } from "effect"; import { Api, SessionClients } from "../support/api.ts"; +import { appsVersion } from "../support/apps-release.ts"; import { TestLive, withCase } from "../support/case.ts"; import { startLoggedSelfHost } from "../support/managed-server.ts"; import { Target } from "../support/platform.ts"; @@ -29,7 +30,7 @@ const records = (text: string, message: string) => const record = Schema.decodeUnknownOption(LogRecord)(line.slice(at)); if (Option.isNone(record)) return []; const logged = record.value.message; - return Array.isArray(logged) && logged[0] === message ? [{ line, fields: logged[1] }] : []; + return Array.isArray(logged) && logged[0] === message ? [{ fields: logged[1] }] : []; }); /** An npm registry answering every request with 404, reached through a credentialed URL. */ @@ -37,13 +38,17 @@ const refusingRegistry = Effect.gen(function* () { const user = `synthetic-user-${randomUUID().slice(0, 8)}`; const password = `synthetic-password-${randomUUID().slice(0, 8)}`; const token = `synthetic-token-${randomUUID().slice(0, 8)}`; + const responseMarker = `synthetic-registry-response-${randomUUID()}`; const paths: string[] = []; const server = yield* Effect.acquireRelease( Effect.callback>((resume) => { const server = createServer((request, response) => { paths.push(request.url ?? "/"); - response.writeHead(404, { "content-type": "application/json" }); - response.end(JSON.stringify({ error: "not found" })); + response.writeHead(404, { + "content-type": "application/json", + "x-registry-response": responseMarker, + }); + response.end(JSON.stringify({ error: responseMarker })); }); server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); }), @@ -58,7 +63,7 @@ const refusingRegistry = Effect.gen(function* () { return { url: `http://${user}:${password}@127.0.0.1:${address.port}/mirror?token=${token}`, paths, - secrets: [user, password, token, "mirror"], + secrets: [user, password, token, "/mirror", "?token=", responseMarker], }; }); @@ -95,8 +100,9 @@ layer(TestLive, { excludeTestServices: true })("Self-host provisioning failure", // The default app pins the `apps` package this host ships; its build asks the registry // for it, and the refusal fails the team's installation. const fs = yield* FileSystem.FileSystem; - const { step, attempt } = yield* fs.readFileString(server.log).pipe( + const { text, step, attempt } = yield* fs.readFileString(server.log).pipe( Effect.map((text) => ({ + text, step: records(text, "Provisioning step failed"), attempt: records(text, "Provisioning attempt failed"), })), @@ -116,24 +122,23 @@ layer(TestLive, { excludeTestServices: true })("Self-host provisioning failure", if (failed === undefined || retried === undefined) return yield* Effect.die("Provisioning failure lines missing"); expect(failed.fields["reason"]).toBe("dependency"); - // The failed build's stage is a closed name, so the log can say which step broke. - expect(failed.fields["cause"]).toMatchObject({ + const cause = { tag: "VersionBuildFailed", stage: "dependencies", - }); + package: "apps", + version: appsVersion, + registry: new URL(registry.url).origin, + status: 404, + }; + expect(failed.fields["cause"]).toEqual(cause); expect(retried.fields["attempts"]).toBeGreaterThanOrEqual(1); expect(retried.fields["outcome"]).toBe("requeued"); - expect(retried.fields["cause"]).toMatchObject({ - tag: "VersionBuildFailed", - stage: "dependencies", - }); + expect(retried.fields["cause"]).toEqual(cause); - // The registry's credentials, path and query stay out of both lines. - for (const { line } of [...step, ...attempt]) + // The registry's credentials, path, query and response stay out of the server log. + for (const line of text.split("\n")) for (const secret of registry.secrets) - expect(line, "the failure omits the registry's credentials and path").not.toContain( - secret, - ); + expect(line, "the failure omits private registry details").not.toContain(secret); }), ), 120_000, diff --git a/packages/app-templates/executor/skills/app-authoring/tools.md b/packages/app-templates/executor/skills/app-authoring/tools.md index b2701a62d8..2a27fdffa1 100644 --- a/packages/app-templates/executor/skills/app-authoring/tools.md +++ b/packages/app-templates/executor/skills/app-authoring/tools.md @@ -393,12 +393,19 @@ Use `ctx.cache.get({ key, schema, freshFor, staleFor, load })` for shared JSON. Put every result dependency in the key. Use `ctx.cache.forAccount(account)` for private results; the host also scopes entries to current credentials. Use `ctx.cache.forCaller()` for anything computed from who is calling: the shared -scope serves every caller of the app. Use the +scope is not caller-specific. Use the loader's `fetch`, `signal`, and `cache` so stale refreshes can finish after the request. Pass `stale: "revalidate"` to await the load past `freshFor` instead of serving the old value; the loader can `read(key, schema)` the old value to confirm it cheaply. Errors are not cached. `invalidate(key)` also fences pending loaders. +On hosted scoped MCP connections, the host partitions `ctx.cache` namespaces by +caller connection and policy revision. A new revision starts with an empty +slot, and a scoped caller can invalidate only its own slot. Writes and +`ctx.cache.invalidate` from unscoped contexts (schedules, webhooks, and +full-access callers) affect only the shared unscoped slot. Scoped entries can +still be served until they expire. + The cache keeps an entry at most 7 days. A longer `freshFor` plus `staleFor`, or a longer `write` retention, is shortened to 7 days, taking `staleFor` first. A call that exceeds another limit fails with `CacheError` and code `capacity`, diff --git a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts index 2502e3b278..622c21b49a 100644 --- a/packages/app-templates/src/implementation/executor-skill-digests.gen.ts +++ b/packages/app-templates/src/implementation/executor-skill-digests.gen.ts @@ -9,7 +9,7 @@ export const executorSkillDigests: Readonly> = { "app-authoring/integrations.md": "1788ddee892c69a9d895a2d8c7bec63f1d41963ed5b00ed3e6f0b5c4a671d867", "app-authoring/starter.md": "382bd769d7b10e9c09eaa2367755f23153a31a484aaca9c449ab4aac7d61e224", "app-authoring/storage.md": "d2c2288c8a6dafa0a88f09e7e91409d9afc08158205ea6d25064d0dee67a33df", - "app-authoring/tools.md": "7dc2ab6620fffd39657b5714ac01e22eb16bd9cf5b30a9253f80c8a1f21f7439", + "app-authoring/tools.md": "769e384ff6ef4c9a7c796da0ba96e8ca289faac746b3c069df5ace5ef8df63f7", "app-authoring/ui.md": "09dacca76ef6997d4530a2a46561683017484915f0a4d89bed6fccd3fabb2a87", "app-authoring/upgrades/0.0.1-beta.38.md": "0e0e38e0334fbece5bdb8264a32be4f36cef9c51705e8f6b749dc0d3b86dcdb5", "app-authoring/upgrades/0.0.1-beta.90.md": "38c727888b2773efa1d83795e8704f7c38ad9ec27c62fcdd89b5177ec5e338c3", diff --git a/packages/sdk/src/contracts/registry-build-failure.ts b/packages/sdk/src/contracts/registry-build-failure.ts new file mode 100644 index 0000000000..b889b6c4dc --- /dev/null +++ b/packages/sdk/src/contracts/registry-build-failure.ts @@ -0,0 +1,53 @@ +/** Registry diagnostics shared by the build errors and the provisioning log. */ +import { Schema } from "effect"; + +const NpmPackageName = Schema.String.check( + Schema.isMaxLength(214), + Schema.isPattern(/^(?:[a-z0-9][a-z0-9._-]*|@[a-z0-9][a-z0-9._-]*\/[a-z0-9_-][a-z0-9._-]*)$/u), + Schema.makeFilter((name) => name !== "node_modules" && name !== "favicon.ico"), +); +const ExactSemver = Schema.String.check( + Schema.isMaxLength(200), + Schema.isPattern( + /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u, + ), +); +const HttpStatus = Schema.Int.check(Schema.isBetween({ minimum: 100, maximum: 599 })); + +export const safeNpmPackageName = (value: unknown) => + Schema.is(NpmPackageName)(value) ? value : undefined; +export const safeExactSemver = (value: unknown) => + Schema.is(ExactSemver)(value) ? value : undefined; +export const safeHttpStatus = (value: unknown) => + Schema.is(HttpStatus)(value) ? value : undefined; +export const safeRegistryOrigin = (value: unknown) => { + const url = typeof value === "string" ? URL.parse(value) : null; + return url?.protocol === "http:" || url?.protocol === "https:" ? url.origin : undefined; +}; + +const RegistryOrigin = Schema.String.check( + Schema.makeFilter((value) => safeRegistryOrigin(value) === value), +); + +export const RegistryBuildFailureFields = { + package: Schema.optionalKey(NpmPackageName), + version: Schema.optionalKey(ExactSemver), + registry: Schema.optionalKey(RegistryOrigin), + status: Schema.optionalKey(HttpStatus), +}; + +/** Project the usable fields and leave unavailable keys absent on the wire. */ +export const safeRegistryBuildFailure = ( + failure: Partial> | undefined, +) => { + const packageName = safeNpmPackageName(failure?.package); + const version = safeExactSemver(failure?.version); + const registry = safeRegistryOrigin(failure?.registry); + const status = safeHttpStatus(failure?.status); + return { + ...(packageName === undefined ? {} : { package: packageName }), + ...(version === undefined ? {} : { version }), + ...(registry === undefined ? {} : { registry }), + ...(status === undefined ? {} : { status }), + }; +}; diff --git a/packages/sdk/src/contracts/runtime.ts b/packages/sdk/src/contracts/runtime.ts index f522bbd2a3..86ddfc638e 100644 --- a/packages/sdk/src/contracts/runtime.ts +++ b/packages/sdk/src/contracts/runtime.ts @@ -19,6 +19,7 @@ import { import { DatabaseFieldReserved } from "@executor-js/app-data/contracts"; import { RecordedMessage } from "@executor-js/utils/recorded-message"; import { BuildStage, SourceLocation, type BuildMemoryExceeded } from "./version.ts"; +import { RegistryBuildFailureFields } from "./registry-build-failure.ts"; import type { CodeFiles } from "./source.ts"; import { BuildId, Json } from "./shared.ts"; import type { BlobKey, BlobRange, BlobStoreError } from "./blobs.ts"; @@ -276,6 +277,7 @@ export class RuntimeBuildFailed extends Schema.TaggedError() { stage: BuildStage, dependency: Schema.optional(Schema.String), + ...RegistryBuildFailureFields, /** A named declaration problem the author can fix, reported with the failed deploy. */ declaration: Schema.optional(DatabaseFieldReserved), message: Schema.optional(BuildMessage), diff --git a/packages/sdk/src/contracts/version.ts b/packages/sdk/src/contracts/version.ts index 93d1b0e40f..058dbdcd12 100644 --- a/packages/sdk/src/contracts/version.ts +++ b/packages/sdk/src/contracts/version.ts @@ -5,6 +5,7 @@ import { RecordedMessage } from "@executor-js/utils/recorded-message"; import { UserFacingError } from "@executor-js/utils/user-facing-error"; import { AppCodeId, AppId, BuildId, VersionId, OwnerId } from "./shared.ts"; import { SourceCommit, SourceFiles } from "./source.ts"; +import { RegistryBuildFailureFields } from "./registry-build-failure.ts"; export { SourceFiles, SourceFile, SourceFilePath } from "./source.ts"; @@ -109,6 +110,7 @@ export class VersionBuildFailed extends Schema.TaggedError() reason: Schema.String, /** The build step that failed, when the runtime reported it. */ stage: Schema.optional(BuildStage), + ...RegistryBuildFailureFields, /** The first failing source location, when known. */ location: Schema.optional(SourceLocation), /** The stage, location and underlying failure, such as the compiler's own errors. */ diff --git a/packages/sdk/src/core.ts b/packages/sdk/src/core.ts index a14173004e..d19fbfc719 100644 --- a/packages/sdk/src/core.ts +++ b/packages/sdk/src/core.ts @@ -1,5 +1,12 @@ /** Public Effect-native SDK. The caller owns platform layers and resource lifetimes. */ export * from "./contracts/index.ts"; +export { + RegistryBuildFailureFields, + safeExactSemver, + safeHttpStatus, + safeNpmPackageName, + safeRegistryOrigin, +} from "./contracts/registry-build-failure.ts"; export { createExecutor, createRemoteExecutor } from "./implementation/create.ts"; export { httpEventSender } from "./implementation/event-sender.ts"; export { makeDeclarationCache } from "./implementation/declarations.ts"; diff --git a/packages/sdk/src/implementation/apps.ts b/packages/sdk/src/implementation/apps.ts index 99565a05fe..fd3edbb419 100644 --- a/packages/sdk/src/implementation/apps.ts +++ b/packages/sdk/src/implementation/apps.ts @@ -36,6 +36,7 @@ import { RuntimeProtocolUnsupported, type Runtime, } from "../contracts/runtime.ts"; +import { safeRegistryBuildFailure } from "../contracts/registry-build-failure.ts"; import { AppCodeId, AppId, @@ -98,6 +99,7 @@ const versionBuildFailed = (owner: OwnerId, name: string, error: RuntimeBuildFai reason: hint ?? error.declaration?.message ?? "App build failed", stage, ...(location === undefined ? {} : { location }), + ...safeRegistryBuildFailure(error), message: `App build failed at the ${stage} stage${where}${detail === undefined ? "." : `: ${detail}`}`, }); }; diff --git a/packages/sdk/src/implementation/worker-build.ts b/packages/sdk/src/implementation/worker-build.ts index d3ad76804e..d06b6edb83 100644 --- a/packages/sdk/src/implementation/worker-build.ts +++ b/packages/sdk/src/implementation/worker-build.ts @@ -7,6 +7,7 @@ import { RuntimeBuildFailed, } from "../contracts/runtime.ts"; import type { CodeFiles } from "../contracts/source.ts"; +import { safeRegistryBuildFailure } from "../contracts/registry-build-failure.ts"; import { prepareUiBuild } from "./ui-build.ts"; import { Effect, Option, Path, Schema } from "effect"; import type { Plugin } from "esbuild"; @@ -91,9 +92,15 @@ const EsbuildFailure = Schema.Struct({ const shownCompileErrors = 5; /** Keep the compiler's own errors and the first failing location for the deployer. */ -const compileFailure = (cause: unknown) => - Option.match(Schema.decodeUnknownOption(EsbuildFailure)(cause), { - onNone: () => new RuntimeBuildFailed({ stage: "compile", message: describeBuildCause(cause) }), +const compileFailure = (cause: unknown, dependency: RuntimeBuildFailed | undefined) => { + const diagnostics = safeRegistryBuildFailure(dependency); + return Option.match(Schema.decodeUnknownOption(EsbuildFailure)(cause), { + onNone: () => + new RuntimeBuildFailed({ + stage: "compile", + message: describeBuildCause(cause), + ...diagnostics, + }), onSome: (failure) => { const errors = failure.errors.map(({ text, location }) => ({ text, @@ -110,6 +117,7 @@ const compileFailure = (cause: unknown) => const more = errors.length - lines.length; return new RuntimeBuildFailed({ stage: "compile", + ...diagnostics, message: boundBuildMessage( [...lines, ...(more > 0 ? [`(${more} more errors)`] : [])].join("\n") || describeBuildCause(cause), @@ -118,6 +126,7 @@ const compileFailure = (cause: unknown) => }); }, }); +}; const selectedFramework = (filesystem: InMemoryFileSystem) => Effect.gen(function* () { @@ -209,7 +218,8 @@ export const compileWorkerApp = ( sizes.plugin, ], }), - catch: (cause) => sizes.failure() ?? json.failure() ?? compileFailure(cause), + catch: (cause) => + sizes.failure() ?? json.failure() ?? compileFailure(cause, dependencies.failure()), }); const map = sourceMap.map(); if (map === undefined) diff --git a/packages/sdk/src/implementation/worker-dependencies.ts b/packages/sdk/src/implementation/worker-dependencies.ts index 3f1feae187..4d63cf80b1 100644 --- a/packages/sdk/src/implementation/worker-dependencies.ts +++ b/packages/sdk/src/implementation/worker-dependencies.ts @@ -5,6 +5,7 @@ import { Effect, Schema, Semaphore } from "effect"; import type { WorkerHost } from "./worker-build.ts"; import type { Plugin } from "esbuild"; import { boundBuildMessage, describeBuildCause, RuntimeBuildFailed } from "../contracts/runtime.ts"; +import { safeRegistryBuildFailure } from "../contracts/registry-build-failure.ts"; import tailwind from "tailwindcss/package.json" with { type: "json" }; import { withoutUrlSecrets } from "@executor-js/utils/url-policy"; @@ -80,6 +81,7 @@ export const workerDependencies = (filesystem: InMemoryFileSystem, host: WorkerH return yield* new RuntimeBuildFailed({ stage: "dependencies", dependency: name, + ...safeRegistryBuildFailure(result.failure), message: boundBuildMessage( withoutUrlSecrets( result.warnings.length > 0 @@ -93,6 +95,17 @@ export const workerDependencies = (filesystem: InMemoryFileSystem, host: WorkerH }); }).pipe(Effect.withSpan("runtime.cloud.dependencies")), ); + let importFailure: RuntimeBuildFailed | undefined; + const installImport = (name: string, version: string, transitive?: boolean) => + Effect.runPromiseWith(context)( + install(name, version, transitive).pipe( + Effect.tapError((error) => + Effect.sync(() => { + importFailure ??= error; + }), + ), + ), + ); const plugin: Plugin = { name: "executor-imported-dependencies", setup(build) { @@ -102,7 +115,7 @@ export const workerDependencies = (filesystem: InMemoryFileSystem, host: WorkerH args.kind === "import-rule" && (args.path === "tailwindcss" || args.path.startsWith("tailwindcss/")) ) { - await Effect.runPromiseWith(context)(install("tailwindcss", tailwind.version, false)); + await installImport("tailwindcss", tailwind.version, false); return undefined; } const parts = args.path.split("/"); @@ -110,7 +123,7 @@ export const workerDependencies = (filesystem: InMemoryFileSystem, host: WorkerH if (name === undefined || !Object.hasOwn(dependencies, name)) return undefined; const version = dependencies[name]; if (version === undefined) return undefined; - await Effect.runPromiseWith(context)(install(name, version)); + await installImport(name, version); // Let the existing resolver apply package exports, conditions, and asset handling. return undefined; }); @@ -118,6 +131,7 @@ export const workerDependencies = (filesystem: InMemoryFileSystem, host: WorkerH }; return { plugin, + failure: () => importFailure, framework: dependencies.apps === undefined ? Effect.succeed(false) diff --git a/patches/@cloudflare%2Fworker-bundler@0.2.4.patch b/patches/@cloudflare%2Fworker-bundler@0.2.4.patch index 3c87cdbe40..cc7c2edb1d 100644 --- a/patches/@cloudflare%2Fworker-bundler@0.2.4.patch +++ b/patches/@cloudflare%2Fworker-bundler@0.2.4.patch @@ -21,7 +21,7 @@ index fa559109c179700e47dd94029abea7d76a00fb50..aa562a81a15e168b321e063ce668d85f list(prefix?: string): string[]; flush(): Promise; diff --git a/dist/index.d.ts b/dist/index.d.ts -index 53dd55f4cd0292a11050505c4824afe0cac15d33..6ccabb03b2982011b5ad2635f2f302a87d8c164f 100644 +index 53dd55f4cd0292a11050505c4824afe0cac15d33..59a61ecae3bd0f291169e4ee1009eebfc8c5330d 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -331,6 +331,8 @@ declare function handleAssetRequest( @@ -33,7 +33,20 @@ index 53dd55f4cd0292a11050505c4824afe0cac15d33..6ccabb03b2982011b5ad2635f2f302a8 /** * Input files — keys are paths relative to project root, values are file contents. * Accepts a plain object (which is wrapped in an InMemoryFileSystem automatically) -@@ -499,6 +501,16 @@ interface InstallResult { +@@ -495,10 +497,29 @@ interface InstallResult { + * Warnings encountered during installation + */ + warnings: string[]; ++ /** The first package installation failure. */ ++ failure?: { ++ package?: string; ++ /** The resolved version, or the declared range if resolution failed. */ ++ version?: string; ++ registry?: string; ++ /** HTTP status from the configured registry for a direct dependency. */ ++ status?: number; ++ }; + } //#endregion //#region src/installer.d.ts interface InstallOptions { @@ -125,10 +138,10 @@ index 9ddcbac086bbd60fece6571299c86f92d33412a6..2f2667088015a158ebd9f1d324137199 installWarnings.push(...installResult.warnings); } diff --git a/dist/installer-DDvaMqav.js b/dist/installer-DDvaMqav.js -index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a627bc8e2ec 100644 +index 5ed55da1726ab87d1c11932262f972cf39c3dd45..5b1f8d0bc35f62009f0c687c1fd897644edf21b8 100644 --- a/dist/installer-DDvaMqav.js +++ b/dist/installer-DDvaMqav.js -@@ -49,21 +49,63 @@ function isTextFile(path) { +@@ -49,21 +49,72 @@ function isTextFile(path) { * Fetch with a timeout. * Throws an error if the request takes longer than the specified timeout. */ @@ -156,7 +169,12 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 +* chose and repeats nothing a server or an archive sent; any other error is +* reported as unexpected. +*/ -+var InstallFailure = class extends Error {}; ++var InstallFailure = class extends Error { ++ constructor(message, registryStatus) { ++ super(message); ++ this.registryStatus = registryStatus; ++ } ++}; +/** +* Why a request failed to send. A fetch hook rejects with an error named +* `NetworkRefused` for a destination its network policy refuses. workerd @@ -179,13 +197,17 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 +async function fetchFrom(url, options, timeoutMs, network) { + let current = url; + for (let hop = 0; hop <= MAX_REDIRECTS; hop++) { -+ const send = URL.parse(current)?.origin === network.registryOrigin ? fetch : network.elsewhere; ++ const onRegistry = URL.parse(current)?.origin === network.registryOrigin; ++ const send = onRegistry ? fetch : network.elsewhere; + const response = await fetchWithTimeout(current, { + ...options, + redirect: "manual" + }, timeoutMs, send); + const location = REDIRECT_STATUSES.has(response.status) ? response.headers.get("location") : null; -+ if (location === null) return response; ++ if (location === null) return { ++ response, ++ registryStatus: onRegistry && network.registryOrigin !== void 0 ? response.status : void 0 ++ }; + response.body?.cancel().catch(() => {}); + const next = URL.parse(location, current); + if (next === null || next.protocol !== "https:" && next.protocol !== "http:") throw new InstallFailure("a redirect named an invalid URL"); @@ -196,7 +218,7 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 //#endregion //#region src/installer-python.ts const PYODIDE_VERSION = "v0.27.5"; -@@ -381,7 +423,11 @@ const NPM_REGISTRY = "https://registry.npmjs.org"; +@@ -381,7 +432,11 @@ const NPM_REGISTRY = "https://registry.npmjs.org"; * @returns Metadata about the installation */ async function installDependencies(fileSystem, options = {}) { @@ -209,7 +231,7 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 const result = { installed: [], warnings: [] -@@ -407,14 +453,19 @@ async function installDependencies(fileSystem, options = {}) { +@@ -407,14 +462,19 @@ async function installDependencies(fileSystem, options = {}) { if (Object.keys(depsToInstall).length === 0) return result; const installedPackages = /* @__PURE__ */ new Set(); const inProgress = /* @__PURE__ */ new Map(); @@ -231,12 +253,13 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 if (installedPackages.has(name)) return; if (fileSystem.read(`node_modules/${name}/package.json`) !== null) { installedPackages.add(name); -@@ -422,28 +473,43 @@ async function installPackage(name, versionRange, result, fileSystem, installedP +@@ -422,28 +482,55 @@ async function installPackage(name, versionRange, result, fileSystem, installedP } const existing = inProgress.get(name); if (existing) return existing; + const installDependency = (depName, depVersion) => installPackage(depName, depVersion, result, fileSystem, installedPackages, inProgress, registry, transitive, extract, network, root ?? name); const installPromise = (async () => { ++ let failedVersion; try { - const metadata = await fetchPackageMetadata(name, registry); - const version = resolveVersion(versionRange, metadata); @@ -260,9 +283,11 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 + if (transitive) await Promise.all(Object.entries(deps).map(([depName, depVersion]) => installDependency(depName, depVersion))); return; } ++ failedVersion = versionRange; + const metadata = await fetchPackageMetadata(name, registry, network); + const version = resolveVersion(versionRange, metadata); + if (!version) throw new InstallFailure("no version in the registry matches its declared range"); ++ failedVersion = version; const versionMetadata = metadata.versions[version]; - if (!versionMetadata) { - result.warnings.push(`Version ${version} not found for ${name}`); @@ -285,10 +310,19 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 + // the declared package is named. + const reason = error instanceof InstallFailure ? error.message : "it failed unexpectedly"; + result.warnings.push(root === void 0 ? `Failed to install ${name}: ${reason}` : `Failed to install a dependency of ${root}: ${reason}`); ++ if (result.failure === void 0) { ++ const configured = URL.parse(registry); ++ result.failure = { ++ package: root ?? name, ++ ...(root === void 0 && typeof failedVersion === "string" ? { version: failedVersion } : {}), ++ ...(configured?.protocol === "https:" || configured?.protocol === "http:" ? { registry: configured.origin } : {}), ++ ...(root === void 0 && error instanceof InstallFailure && error.registryStatus !== void 0 ? { status: error.registryStatus } : {}) ++ }; ++ } } })(); inProgress.set(name, installPromise); -@@ -453,104 +519,128 @@ async function installPackage(name, versionRange, result, fileSystem, installedP +@@ -453,104 +540,128 @@ async function installPackage(name, versionRange, result, fileSystem, installedP inProgress.delete(name); } } @@ -308,9 +342,9 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 - if (!response.ok) { - const hint = response.status === 404 ? " (package not found — check the name in package.json or set the `registry` option if it lives on a private registry)" : ""; - throw new Error(`Registry returned ${response.status} ${response.statusText} for "${name}" at ${url}${hint}`); -+ const response = await fetchFrom(url, { headers: { Accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" } }, DEFAULT_TIMEOUT_MS, network); -+ if (response.status === 404) throw new InstallFailure(`the registry at ${registry} has no such package (HTTP 404)`); -+ if (!response.ok) throw new InstallFailure(`the registry at ${registry} answered HTTP ${response.status}`); ++ const { response, registryStatus } = await fetchFrom(url, { headers: { Accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" } }, DEFAULT_TIMEOUT_MS, network); ++ if (response.status === 404) throw new InstallFailure(`the registry at ${registry} has no such package (HTTP 404)`, registryStatus); ++ if (!response.ok) throw new InstallFailure(`the registry at ${registry} answered HTTP ${response.status}`, registryStatus); + let metadata; + try { + metadata = await response.json(); @@ -367,11 +401,11 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 - const buffer = await response.arrayBuffer(); - return extractTarball(new Uint8Array(buffer)); + if (typeof tarballUrl !== "string") throw new InstallFailure("the registry's metadata names no tarball"); -+ const response = await fetchFrom(tarballUrl, {}, DEFAULT_TIMEOUT_MS * 2, options.network ?? { ++ const { response, registryStatus } = await fetchFrom(tarballUrl, {}, DEFAULT_TIMEOUT_MS * 2, options.network ?? { + registryOrigin: void 0, + elsewhere: fetch + }); -+ if (!response.ok) throw new InstallFailure(`the tarball download answered HTTP ${response.status}`); ++ if (!response.ok) throw new InstallFailure(`the tarball download answered HTTP ${response.status}`, registryStatus); + if (response.body === null) throw new InstallFailure("the tarball download has no body"); + try { + return await extractTarball(response.body, options.buildInputsOnly === true ? isBuildInput : isTextFile); @@ -487,7 +521,7 @@ index 5ed55da1726ab87d1c11932262f972cf39c3dd45..c50d0cf085a7dffd44af6558f56c5a62 } const archiveRoot = findSharedTarRootDirectory(regularFilePaths); const files = {}; -@@ -560,6 +650,70 @@ function parseTar(data) { +@@ -560,6 +671,70 @@ function parseTar(data) { } return files; }