diff --git a/docs/durable-object-reset.md b/docs/durable-object-reset.md new file mode 100644 index 00000000..794c1c7b --- /dev/null +++ b/docs/durable-object-reset.md @@ -0,0 +1,29 @@ +# Durable Object reset runbook + +GEN-2030 intentionally resets all application data stored in Durable Objects. It does not replace the `factorize` Worker, its KV namespace, its environment variables, or any Wrangler secrets. + +## Data loss and user impact + +The reset deletes tenant membership, Jobs, triggers, runs, Access Tokens, OAuth grants stored in Durable Objects, installed integrations, and saved execution connections. After deployment, every user must sign in again and reconnect Linear, GitHub, Cloudflare Tail, exe.dev, and Amp integrations as applicable. + +## Phase 1: switch to fresh namespaces + +1. Confirm the existing Worker secrets and environment configuration are present. Do not run `wrangler delete`, create another Worker, change the Worker name, replace the OAuth KV binding, or remove secrets. +2. Deploy this revision with `npm run deploy:app`. Migration `v3-fresh-durable-objects` creates the SQLite-backed `TenantV2` and `GitHubInstallationRegistryV2` classes. The existing binding names switch to those fresh namespaces, while the legacy class exports remain available for safe rollback. +3. Confirm the deployment succeeds before taking any retirement action. Sign in, reconnect an execution integration, and create a Job with a Manual trigger, prompt template `{{trigger-1.prompt}}`, and that execution target. Confirm the Job is created without `SQLITE_CONSTRAINT_NOTNULL`. +4. Notify users that they must sign in again and reconnect integrations. + +## Phase 2: retire legacy namespaces + +Perform this only in a later deployment after Phase 1 is live and verified: + +1. Add a new migration after `v3-fresh-durable-objects`: + + ```json + { "tag": "v4-delete-legacy-durable-objects", "deleted_classes": ["Tenant", "GitHubInstallationRegistry"] } + ``` + +2. Remove the legacy `Tenant` and `GitHubInstallationRegistry` aliases from the exports in `src/index.ts` and `src/worker.ts`. Keep the V2 bindings, V2 exports, Worker name, variables, KV binding, and secrets unchanged. +3. Run `npm run check`, deploy the Worker normally, and verify sign-in and Job creation again. + +Never combine legacy deletion with the Phase 1 namespace switch: the replacement bindings must be live and verified first. diff --git a/packages/app/src/github-registry.ts b/packages/app/src/github-registry.ts index ba345935..186b1283 100644 --- a/packages/app/src/github-registry.ts +++ b/packages/app/src/github-registry.ts @@ -1,7 +1,7 @@ import { DurableObject } from "cloudflare:workers"; import type { Env } from "./types"; -export class GitHubInstallationRegistry extends DurableObject { +export class GitHubInstallationRegistryV2 extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS installations (installation_id INTEGER PRIMARY KEY, tenant_id TEXT NOT NULL, account_login TEXT NOT NULL, account_type TEXT NOT NULL, state TEXT NOT NULL, updated_at TEXT NOT NULL)`); @@ -23,3 +23,6 @@ export class GitHubInstallationRegistry extends DurableObject { return new Response("Not found", { status: 404 }); } } + +/** @deprecated Retained only until the Phase 2 namespace-retirement deployment. */ +export class GitHubInstallationRegistry extends DurableObject {} diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 70d2c969..f49ae086 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -2,8 +2,8 @@ import { Hono } from "hono"; import { deleteCookie, getCookie, setCookie } from "hono/cookie"; import { parse } from "hono/utils/cookie"; import { equalHmac, hmac } from "./crypto"; -import { Tenant } from "./tenant"; -import { GitHubInstallationRegistry } from "./github-registry"; +import { Tenant, TenantV2 } from "./tenant"; +import { GitHubInstallationRegistry, GitHubInstallationRegistryV2 } from "./github-registry"; import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github"; import { apiKeysSettingsPage, jobDetailPage, jobPage, jobsPage, jobRunPage, landingPage, settingsPage } from "./ui"; import type { Env } from "./types"; @@ -313,5 +313,7 @@ app.get("/settings", async (c) => { const session = await owner(c); return sessi app.get("/settings/integrations", async (c) => { const session = await owner(c); return session ? c.html(render(settingsPage({ email: session.email }), c.get("cspNonce"))) : c.redirect("/auth/linear"); }); app.get("/settings/api-keys", async (c) => { const session = await owner(c); return session ? c.html(render(apiKeysSettingsPage({ email: session.email }), c.get("cspNonce"))) : c.redirect("/auth/linear"); }); -export { Tenant, GitHubInstallationRegistry }; +// Keep the legacy export names available until the follow-up retirement deployment. +// Worker traffic is bound exclusively to the fresh V2 namespaces below. +export { TenantV2, Tenant, GitHubInstallationRegistryV2, GitHubInstallationRegistry }; export default app; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 101f5663..c5da801d 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -39,7 +39,7 @@ type FlowSource = | { kind: "custom"; origin: "linear" | "github" | "cloudflare"; handlerName: string; handlerCode: string; handlerDeployment: { scriptName: string; codeDigest: string; state: "deploying" | "ready" | "failed" }; tail?: { signingSecret: string } }; type PipeInput = { pipeId?: string; name: string; flowId?: string; projectId?: string; matchRules: MatchRule[]; maxConcurrency: number; contextTemplate?: string; exeConnectionId?: string; cwd?: string; source?: FlowSource }; -export class Tenant extends DurableObject { +export class TenantV2 extends DurableObject { private linearRefresh?: Promise; constructor(ctx: DurableObjectState, env: Env) { @@ -1623,3 +1623,6 @@ export class Tenant extends DurableObject { private rows(query: string, ...params: unknown[]): Row[] { return [...this.ctx.storage.sql.exec(query, ...params)] as Row[]; } private one(query: string, ...params: unknown[]): Row | undefined { return this.rows(query, ...params)[0]; } } + +/** @deprecated Retained only until the Phase 2 namespace-retirement deployment. */ +export class Tenant extends DurableObject {} diff --git a/packages/app/src/worker.ts b/packages/app/src/worker.ts index 0624ce9b..42edf7a1 100644 --- a/packages/app/src/worker.ts +++ b/packages/app/src/worker.ts @@ -73,7 +73,7 @@ function providerOptions(env: Env): OAuthProviderOptions { return { }; } function provider(env: Env) { return new OAuthProvider(providerOptions(env)); } -export { Tenant, GitHubInstallationRegistry } from "./index"; +export { TenantV2, Tenant, GitHubInstallationRegistryV2, GitHubInstallationRegistry } from "./index"; export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { const oauth = provider(env); const url = new URL(request.url); diff --git a/packages/app/test/fresh-namespace.e2e.test.ts b/packages/app/test/fresh-namespace.e2e.test.ts new file mode 100644 index 00000000..1af59f30 --- /dev/null +++ b/packages/app/test/fresh-namespace.e2e.test.ts @@ -0,0 +1,63 @@ +import { env, fetchMock } from "cloudflare:test"; +import { beforeAll, describe, expect, it } from "vitest"; +import type { Env as FactorizeEnv } from "../src/types"; + +declare module "cloudflare:test" { + interface ProvidedEnv extends FactorizeEnv {} +} + +describe("fresh TenantV2 namespace", () => { + beforeAll(() => { + fetchMock.activate(); + fetchMock.disableNetConnect(); + }); + + it("initializes the current schema and creates a manual Job with a selected execution target", async () => { + fetchMock.get("https://ampcode.com").intercept({ path: "/api/cloud/v1/projects?limit=1" }).reply(200, {}); + const tenant = env.TENANTS.get(env.TENANTS.idFromName(`fresh-v2:${crypto.randomUUID()}`)); + + const connection = await tenant.fetch("https://tenant/connections/amp", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ connectionId: "execution-1", accessToken: "test-token", project: "generation/factorize" }), + }); + expect(connection.status, await connection.clone().text()).toBe(200); + + const created = await tenant.fetch("https://tenant/v1/jobs", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + name: "Manual prompt", + promptTemplate: "{{trigger-1.prompt}}", + concurrencyLimit: 1, + executionTargetId: "amp:execution-1", + triggers: [{ kind: "manual", slug: "trigger-1", config: {} }], + }), + }); + + expect(created.status, await created.clone().text()).toBe(200); + await expect(created.json()).resolves.toMatchObject({ + name: "Manual prompt", + promptTemplate: "{{trigger-1.prompt}}", + executionTargetId: "amp:execution-1", + triggers: [{ kind: "manual", slug: "trigger-1" }], + }); + }); +}); + +describe("fresh GitHubInstallationRegistryV2 namespace", () => { + it("initializes and stores a new installation claim", async () => { + const registry = env.GITHUB_INSTALLATIONS!.get(env.GITHUB_INSTALLATIONS!.idFromName(`fresh-v2:${crypto.randomUUID()}`)); + const installationId = 2030; + const stored = await registry.fetch(`https://registry/installations/${installationId}`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ tenantId: "tenant-2030", accountLogin: "generation", accountType: "Organization" }), + }); + expect(stored.status, await stored.clone().text()).toBe(200); + + const loaded = await registry.fetch(`https://registry/installations/${installationId}`); + expect(loaded.status, await loaded.clone().text()).toBe(200); + await expect(loaded.json()).resolves.toMatchObject({ installation_id: installationId, tenant_id: "tenant-2030" }); + }); +}); diff --git a/packages/app/test/run-inspection.test.ts b/packages/app/test/run-inspection.test.ts index f68e0196..14f1742f 100644 --- a/packages/app/test/run-inspection.test.ts +++ b/packages/app/test/run-inspection.test.ts @@ -2,17 +2,17 @@ import { describe, expect, it, vi } from "vitest"; vi.mock("cloudflare:workers", () => ({ DurableObject: class {} })); -import { Tenant } from "../src/tenant"; +import { TenantV2 } from "../src/tenant"; -function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record[]): Tenant { - const tenant = Object.create(Tenant.prototype) as Tenant; +function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record[]): TenantV2 { + const tenant = Object.create(TenantV2.prototype) as TenantV2; (tenant as any).rows = rows; return tenant; } describe("run invocation inspection", () => { it("preserves trigger slugs across edits and reordering", () => { - const tenant = Object.create(Tenant.prototype) as Tenant; + const tenant = Object.create(TenantV2.prototype) as TenantV2; const existing = new Map([ ["manual", { id: "manual", slug: "trigger-1" }], ["schedule", { id: "schedule", slug: "trigger-2" }], diff --git a/packages/app/vitest.e2e.config.ts b/packages/app/vitest.e2e.config.ts index 42e054d0..d321a04e 100644 --- a/packages/app/vitest.e2e.config.ts +++ b/packages/app/vitest.e2e.config.ts @@ -2,7 +2,7 @@ import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config"; export default defineWorkersConfig({ test: { - include: ["test/device-oauth.e2e.test.ts"], + include: ["test/device-oauth.e2e.test.ts", "test/fresh-namespace.e2e.test.ts"], poolOptions: { workers: { isolatedStorage: false, @@ -10,7 +10,7 @@ export default defineWorkersConfig({ miniflare: { bindings: { SESSION_SIGNING_SECRET: "e2e-session-secret", - CREDENTIAL_ENCRYPTION_KEY: "e2e-credential-key", + CREDENTIAL_ENCRYPTION_KEY: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", LINEAR_CLIENT_ID: "e2e-linear-client", LINEAR_CLIENT_SECRET: "e2e-linear-secret", LINEAR_WEBHOOK_SIGNING_SECRET: "e2e-webhook-secret", diff --git a/packages/app/wrangler.jsonc b/packages/app/wrangler.jsonc index 0a35c2d8..392727cd 100644 --- a/packages/app/wrangler.jsonc +++ b/packages/app/wrangler.jsonc @@ -8,9 +8,13 @@ "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "cacbf744337747ffbb9c0153329aad4f" }], "worker_loaders": [{ "binding": "CUSTOM_HANDLER_LOADER" }], "durable_objects": { - "bindings": [{ "name": "TENANTS", "class_name": "Tenant" }, { "name": "GITHUB_INSTALLATIONS", "class_name": "GitHubInstallationRegistry" }] + "bindings": [{ "name": "TENANTS", "class_name": "TenantV2" }, { "name": "GITHUB_INSTALLATIONS", "class_name": "GitHubInstallationRegistryV2" }] }, - "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Tenant"] }, { "tag": "v2", "new_sqlite_classes": ["GitHubInstallationRegistry"] }], + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["Tenant"] }, + { "tag": "v2", "new_sqlite_classes": ["GitHubInstallationRegistry"] }, + { "tag": "v3-fresh-durable-objects", "new_sqlite_classes": ["TenantV2", "GitHubInstallationRegistryV2"] } + ], "vars": { "APP_ORIGIN": "https://app.factorize.sh", "LINEAR_OAUTH_SCOPES": "read,write"