Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/durable-object-reset.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 4 additions & 1 deletion packages/app/src/github-registry.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DurableObject } from "cloudflare:workers";
import type { Env } from "./types";

export class GitHubInstallationRegistry extends DurableObject<Env> {
export class GitHubInstallationRegistryV2 extends DurableObject<Env> {
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)`);
Expand All @@ -23,3 +23,6 @@ export class GitHubInstallationRegistry extends DurableObject<Env> {
return new Response("Not found", { status: 404 });
}
}

/** @deprecated Retained only until the Phase 2 namespace-retirement deployment. */
export class GitHubInstallationRegistry extends DurableObject<Env> {}
8 changes: 5 additions & 3 deletions packages/app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
5 changes: 4 additions & 1 deletion packages/app/src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Env> {
export class TenantV2 extends DurableObject<Env> {
private linearRefresh?: Promise<string>;

constructor(ctx: DurableObjectState, env: Env) {
Expand Down Expand Up @@ -1623,3 +1623,6 @@ export class Tenant extends DurableObject<Env> {
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<Env> {}
2 changes: 1 addition & 1 deletion packages/app/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ function providerOptions(env: Env): OAuthProviderOptions<Env> { return {
}; }
function provider(env: Env) { return new OAuthProvider<Env>(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);
Expand Down
63 changes: 63 additions & 0 deletions packages/app/test/fresh-namespace.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -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" });
});
});
8 changes: 4 additions & 4 deletions packages/app/test/run-inspection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>[]): Tenant {
const tenant = Object.create(Tenant.prototype) as Tenant;
function tenantWithRows(rows: (query: string, ...params: unknown[]) => Record<string, unknown>[]): 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" }],
Expand Down
4 changes: 2 additions & 2 deletions packages/app/vitest.e2e.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ 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,
wrangler: { configPath: "./wrangler.jsonc" },
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",
Expand Down
8 changes: 6 additions & 2 deletions packages/app/wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down