diff --git a/package-lock.json b/package-lock.json index 9d141423..e92cad35 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5954,6 +5954,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.0.tgz", + "integrity": "sha512-kVzTnYFYEyQ9RGzBjNCd2+yEqWmVbxl3AHPynv3qQ6JTjv4a+kwRcnqQwIpuP3NnrnIrE/Q6wWAIAvMfIE2/Yg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.0.tgz", + "integrity": "sha512-T9r+MZkTECl2+oUcZ26YgZzTrYidTsIhYYkJix+6iDOymOb1FB2RLLSOxRGnZGv5DStt+aduIVbt+E8WygXYpg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", @@ -7266,6 +7295,7 @@ "ajv": "^8.20.0", "drizzle-kit": "^0.31.10", "happy-dom": "^20.14.5", + "playwright": "^1.64.0", "tailwindcss": "^4.1.14", "tsx": "^4.23.15", "typescript": "^5.9.3", diff --git a/packages/app/package.json b/packages/app/package.json index c416cebb..7adec6f9 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -10,6 +10,7 @@ "check:api-boundaries": "node scripts/check-api-boundaries.mjs", "test": "vitest run", "deploy": "wrangler deploy", + "benchmark:loading": "vitest run --config scripts/loading-baseline.config.ts", "db:migrate": "node scripts/migrate.mjs", "db:verify": "node scripts/verify-schema.mjs", "db:studio": "drizzle-kit studio --config drizzle.config.ts", @@ -38,6 +39,7 @@ "ajv": "^8.20.0", "drizzle-kit": "^0.31.10", "happy-dom": "^20.14.5", + "playwright": "^1.64.0", "tailwindcss": "^4.1.14", "tsx": "^4.23.15", "typescript": "^5.9.3", diff --git a/packages/app/performance/GEN-2154.md b/packages/app/performance/GEN-2154.md new file mode 100644 index 00000000..d52e8ee8 --- /dev/null +++ b/packages/app/performance/GEN-2154.md @@ -0,0 +1,46 @@ +# GEN-2154 loading measurements + +Measured October 9, 2026. Before: default-branch commit `daf766e`; after: this branch. Both use the same ten-job fixture (two ordered triggers each, three run states, Exe/Amp/Tail connections), PostgreSQL 16.15, Node 22.20, headless Chromium 156, and five sequential samples per screen. The before and after suites ran sequentially on the same VM. Each query has an injected 20 ms delay to expose serial dependency costs. Normal pool settings (`max=5`, `maxUses=1`) remain in force. These are controlled local results, **not production latency estimates or p95**. + +The browser uses an actual signed session cookie, receives the authenticated Worker-generated HTML, runs its scripts and renders local CSS. Playwright intercepts HTTP and dispatches to the Worker entrypoint with the browser's cookie. It excludes internet transit, Cloudflare scheduling, Hyperdrive/Neon network latency, and real OAuth-provider transport. The only provider stub forwards HTML routes and supplies an empty authorized-client list; API authentication and PostgreSQL repositories are real. Navigation starts before the shell's membership lookup. Useful content means a populated Jobs list, job/run heading, loaded target choices in the editor, installed integration cards, or the completed empty API-key list. Endpoint timings include complete JSON response consumption. Job create measures execution-target latency; job edit measures job detail; the full browser measurements include their other concurrent requests. + +| Screen | Endpoint median ms (before → after) | Navigation to useful content median ms (before → after) | +| -- | -- | -- | +| Jobs | 174.1 → 106.4 | 264.4 → 260.4 | +| Job detail | 127.8 → 98.4 | 287.2 → 201.6 | +| Run detail | 179.2 → 80.1 | 868 → 175.2 | +| Job create | 123.2 → 49.5 | 305.6 → 265.6 | +| Job edit | 118.5 → 96.4 | 300.8 → 196.1 | +| Integrations | 280.3 → 51.3 | 378.8 → 160.5 | +| API Keys | 74.2 → 47.1 | 185.4 → 122.3 | + +Raw samples' median/range summaries, indexes, and local `EXPLAIN (ANALYZE, BUFFERS)` plans are in `gen-2154-before.json` and `gen-2154-after.json`. Browser scheduling contributes visible variance, particularly for run and editor pages; do not infer fixed per-page savings from five samples. For example, before-run useful-content samples ranged from 376.6–883.2 ms, while Jobs useful-content medians changed only 264.4→260.4 ms despite lower endpoint latency. Those browser results should not be treated as stable savings. + +## Repeat the cookie baseline + +Use a **disposable local PostgreSQL server** whose user can create/drop databases. The fixture creates an isolated database, applies all migrations, and removes it after the suite. Never point this at production. + +```sh +npm ci +npm exec --workspace=factorize -- playwright install chromium +AUTH_TEST_DATABASE_URL=postgresql://postgres@localhost:5432/postgres \ +LOADING_QUERY_DELAY_MS=20 \ +LOADING_REPORT_PATH=/tmp/loading.json \ +npm run benchmark:loading --workspace=factorize +``` + +For the old code, copy `test/helpers/loading-fixture.ts`, `test/loading-baseline.e2e.test.ts`, and `scripts/loading-baseline.config.ts` into a disposable checkout of `daf766e`, share/install the same dependencies, and run `vitest run --config scripts/loading-baseline.config.ts` in `packages/app`. Run the two suites sequentially. Set query delay to zero for an additional local execution-only baseline; that still cannot measure Cloudflare socket ownership or Hyperdrive connection setup. + +## Production comparison and remaining costs + +`gen-2154-proxy-baseline.jsonl` contains a fresh five-request sequential **integration-authenticated** production baseline. All measured API reads returned 200 except API Keys, which returned the expected 403 because that endpoint requires an interactive owner session. HTML through this proxy returns a sign-in shell. Those observations are separate from the cookie baseline above. This branch was not deployed, so there is no production after measurement. Repeat browser and cookie API measurements after rollout with a normal signed-in owner browser; use DevTools Network/Performance to measure navigation through the first populated content and save endpoint `Server-Timing` along with total latency for the same pages, same tenant, and same records. Warm once, measure at least five sequential navigations/requests, then expand the sample before considering tail latency. + +`Server-Timing` now separates authoritative service membership/token validation (`auth`) from the remaining application phase (`application`, including data reads, validation, decryption, serialization and rendering). HTML shell responses use the same phases. These durations are wall-clock phases, not summed per-query time. Cookie signature/expiry checks and upstream bearer-provider authentication happen before the protected API timer; network transit and deferred tasks are excluded. + +Jobs now use one jobs query, one ordered trigger query, and one grouped statistics query, instead of `1 + 2N` data queries. Prompts, trigger configs and existing response fields remain available for API compatibility. Integration status uses one filtered encrypted-connection read and one grouped Tail reference-count read; execution targets also use a single filtered connection read. Run metadata reads start together after tenant-scoped run existence is confirmed. A tenant-qualified join supplies `job_name`, so run rendering and trace loading no longer wait for a full job request. Live polling behavior remains unchanged. + +The local plans contain only three historical run rows: the old aggregate executed in 0.146 ms in the before fixture; the new ten-job batch executed in 0.095 ms in the after fixture. Both used the tenant-prefix bitmap index scan, with no disk sort spill. The batch replaces per-job round trips and full state arrays; these tiny plans do **not** establish a production index bottleneck or faster SQL execution. The checked-in schema has tenant primary/unique indexes and scheduler partial indexes, but no job-specific history-order index. For large production histories, obtain a read-only production plan and row/cardinality statistics before considering `(tenant_id, job_id, created_at DESC, id DESC)` and a partial active-state index. The batch still scans historical rows for counts/latest selection and materializes a CTE; that remains a scaling cost to measure. + +`databaseFor()` still constructs per-call request-local pools and retires checkouts with `maxUses=1`. Batching directly reduces checkouts. The prior #163 isolation constraint still applies: sharing a module-global Pool can exchange request-owned sockets even with `maxUses=1`. This local test cannot measure Hyperdrive setup cost; a request-scoped reusable pool with guaranteed cleanup needs a separate Worker canary (including overlapping requests and background work) before changing socket lifecycle. No upstream-connection savings are claimed. + +Worker placement and query caching remain unchanged. Neon us-west-2 plus unconfigured placement are hypotheses, not measured causes. Compare identical cookie requests and Server-Timing on a placement canary before choosing placement. Authorization and mutable run state must stay uncached. The shell→API dependency remains; initial-data rendering can be evaluated once production backend phases are understood. diff --git a/packages/app/performance/gen-2154-after.json b/packages/app/performance/gen-2154-after.json new file mode 100644 index 00000000..9285121e --- /dev/null +++ b/packages/app/performance/gen-2154-after.json @@ -0,0 +1,544 @@ +{ + "samples": 5, + "query_delay_ms": 20, + "environment": "Disposable local PostgreSQL; signed cookie Worker dispatch; headless Chromium with local CSS; intercepted HTTP, no Cloudflare/Hyperdrive/network transit", + "results": [ + { + "screen": "Jobs", + "endpoint": { + "median_ms": 106.4, + "range_ms": [ + 100.5, + 114 + ] + }, + "useful_content": { + "median_ms": 260.4, + "range_ms": [ + 217.3, + 303.1 + ] + } + }, + { + "screen": "Job detail", + "endpoint": { + "median_ms": 98.4, + "range_ms": [ + 97, + 107.1 + ] + }, + "useful_content": { + "median_ms": 201.6, + "range_ms": [ + 171.4, + 260.7 + ] + } + }, + { + "screen": "Run detail", + "endpoint": { + "median_ms": 80.1, + "range_ms": [ + 77.1, + 86 + ] + }, + "useful_content": { + "median_ms": 175.2, + "range_ms": [ + 152.9, + 186.1 + ] + } + }, + { + "screen": "Job create", + "endpoint": { + "median_ms": 49.5, + "range_ms": [ + 47.5, + 58.1 + ] + }, + "useful_content": { + "median_ms": 265.6, + "range_ms": [ + 184.7, + 289.8 + ] + } + }, + { + "screen": "Job edit", + "endpoint": { + "median_ms": 96.4, + "range_ms": [ + 92.9, + 108.2 + ] + }, + "useful_content": { + "median_ms": 196.1, + "range_ms": [ + 188.6, + 299.3 + ] + } + }, + { + "screen": "Integrations", + "endpoint": { + "median_ms": 51.3, + "range_ms": [ + 48.3, + 60.4 + ] + }, + "useful_content": { + "median_ms": 160.5, + "range_ms": [ + 129.9, + 166.7 + ] + } + }, + { + "screen": "API Keys", + "endpoint": { + "median_ms": 47.1, + "range_ms": [ + 46.8, + 52.6 + ] + }, + "useful_content": { + "median_ms": 122.3, + "range_ms": [ + 105.4, + 169.7 + ] + } + } + ], + "indexes": [ + { + "indexname": "job_runs_launch_lease", + "indexdef": "CREATE INDEX job_runs_launch_lease ON app.job_runs USING btree (launch_lease_expires_at) WHERE (state = 'starting'::text)" + }, + { + "indexname": "job_runs_pkey", + "indexdef": "CREATE UNIQUE INDEX job_runs_pkey ON app.job_runs USING btree (tenant_id, id)" + }, + { + "indexname": "job_runs_poll_due", + "indexdef": "CREATE INDEX job_runs_poll_due ON app.job_runs USING btree (next_poll_at) WHERE (state = ANY (ARRAY['running'::text, 'blocked'::text, 'stopping'::text]))" + }, + { + "indexname": "job_runs_queue", + "indexdef": "CREATE INDEX job_runs_queue ON app.job_runs USING btree (state, created_at) WHERE (state = 'queued'::text)" + }, + { + "indexname": "job_runs_tenant_id_invocation_id_key", + "indexdef": "CREATE UNIQUE INDEX job_runs_tenant_id_invocation_id_key ON app.job_runs USING btree (tenant_id, invocation_id)" + } + ], + "plans": { + "old_single_job": [ + { + "Plan": { + "Node Type": "Aggregate", + "Strategy": "Plain", + "Partial Mode": "Simple", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 9.54, + "Total Cost": 9.55, + "Plan Rows": 1, + "Plan Width": 64, + "Actual Startup Time": 0.032, + "Actual Total Time": 0.033, + "Actual Rows": 1, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 9.52, + "Total Cost": 9.52, + "Plan Rows": 1, + "Plan Width": 40, + "Actual Startup Time": 0.024, + "Actual Total Time": 0.025, + "Actual Rows": 3, + "Actual Loops": 1, + "Sort Key": [ + "created_at DESC" + ], + "Sort Method": "quicksort", + "Sort Space Used": 25, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "job_runs", + "Alias": "job_runs", + "Startup Cost": 4.16, + "Total Cost": 9.51, + "Plan Rows": 1, + "Plan Width": 40, + "Actual Startup Time": 0.01, + "Actual Total Time": 0.011, + "Actual Rows": 3, + "Actual Loops": 1, + "Recheck Cond": "(tenant_id = '7392e391-3df9-4fea-9e49-d4f6fd3a5f67'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(job_id = 'ae6781e8-3f1f-4bbc-bb4f-ca206c12902e'::uuid)", + "Rows Removed by Filter": 0, + "Exact Heap Blocks": 1, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "job_runs_tenant_id_invocation_id_key", + "Startup Cost": 0, + "Total Cost": 4.16, + "Plan Rows": 2, + "Plan Width": 0, + "Actual Startup Time": 0.003, + "Actual Total Time": 0.004, + "Actual Rows": 3, + "Actual Loops": 1, + "Index Cond": "(tenant_id = '7392e391-3df9-4fea-9e49-d4f6fd3a5f67'::uuid)", + "Shared Hit Blocks": 1, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 197, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.351, + "Triggers": [], + "Execution Time": 0.07 + } + ], + "new_batch": [ + { + "Plan": { + "Node Type": "Nested Loop", + "Parallel Aware": false, + "Async Capable": false, + "Join Type": "Inner", + "Startup Cost": 9.6, + "Total Cost": 9.64, + "Plan Rows": 1, + "Plan Width": 80, + "Actual Startup Time": 0.046, + "Actual Total Time": 0.047, + "Actual Rows": 1, + "Actual Loops": 1, + "Inner Unique": true, + "Join Filter": "(selected_runs.job_id = selected_runs_1.job_id)", + "Rows Removed by Join Filter": 0, + "Shared Hit Blocks": 8, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "InitPlan", + "Subplan Name": "CTE selected_runs", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "job_runs", + "Alias": "job_runs", + "Startup Cost": 4.19, + "Total Cost": 9.54, + "Plan Rows": 1, + "Plan Width": 72, + "Actual Startup Time": 0.011, + "Actual Total Time": 0.012, + "Actual Rows": 3, + "Actual Loops": 1, + "Recheck Cond": "(tenant_id = '7392e391-3df9-4fea-9e49-d4f6fd3a5f67'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(job_id = ANY ('{ae6781e8-3f1f-4bbc-bb4f-ca206c12902e,7feb87ab-b6b8-4245-8f3e-4dcfaf12fd3a,795a83f9-74e1-4647-9898-63cc71b2465c,aaf3a746-2fe4-4dfb-a85e-8da7c4115735,fa64f05c-7474-4218-8072-3ab6822473c8,b74f718f-946a-4423-b9ec-4678cb496a76,6562ccd2-ffc8-41b8-8419-c1eef0de4077,b24066e8-50de-4f92-8744-32a1d03bf5e7,82e37d4b-c671-4972-bb51-5ad9f446c1b0,50999b53-3a5c-45dd-a24e-c140664cbb43}'::uuid[]))", + "Rows Removed by Filter": 0, + "Exact Heap Blocks": 1, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "job_runs_tenant_id_invocation_id_key", + "Startup Cost": 0, + "Total Cost": 4.16, + "Plan Rows": 2, + "Plan Width": 0, + "Actual Startup Time": 0.005, + "Actual Total Time": 0.005, + "Actual Rows": 3, + "Actual Loops": 1, + "Index Cond": "(tenant_id = '7392e391-3df9-4fea-9e49-d4f6fd3a5f67'::uuid)", + "Shared Hit Blocks": 1, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + { + "Node Type": "Aggregate", + "Strategy": "Hashed", + "Partial Mode": "Simple", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.03, + "Total Cost": 0.04, + "Plan Rows": 1, + "Plan Width": 48, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.022, + "Actual Rows": 1, + "Actual Loops": 1, + "Group Key": [ + "selected_runs.job_id" + ], + "Planned Partitions": 0, + "HashAgg Batches": 1, + "Peak Memory Usage": 24, + "Disk Usage": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "selected_runs", + "Alias": "selected_runs", + "Startup Cost": 0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 48, + "Actual Startup Time": 0.013, + "Actual Total Time": 0.015, + "Actual Rows": 3, + "Actual Loops": 1, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + }, + { + "Node Type": "Unique", + "Parent Relationship": "Inner", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.03, + "Total Cost": 0.04, + "Plan Rows": 1, + "Plan Width": 72, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.023, + "Actual Rows": 1, + "Actual Loops": 1, + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 0.03, + "Total Cost": 0.04, + "Plan Rows": 1, + "Plan Width": 72, + "Actual Startup Time": 0.022, + "Actual Total Time": 0.022, + "Actual Rows": 1, + "Actual Loops": 1, + "Sort Key": [ + "selected_runs_1.job_id", + "selected_runs_1.created_at DESC", + "selected_runs_1.id DESC" + ], + "Sort Method": "quicksort", + "Sort Space Used": 25, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 6, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "CTE Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "CTE Name": "selected_runs", + "Alias": "selected_runs_1", + "Startup Cost": 0, + "Total Cost": 0.02, + "Plan Rows": 1, + "Plan Width": 72, + "Actual Startup Time": 0, + "Actual Total Time": 0, + "Actual Rows": 3, + "Actual Loops": 1, + "Shared Hit Blocks": 0, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 200, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.414, + "Triggers": [], + "Execution Time": 0.095 + } + ] + } +} diff --git a/packages/app/performance/gen-2154-before.json b/packages/app/performance/gen-2154-before.json new file mode 100644 index 00000000..5c86ae61 --- /dev/null +++ b/packages/app/performance/gen-2154-before.json @@ -0,0 +1,288 @@ +{ + "samples": 5, + "query_delay_ms": 20, + "environment": "Disposable local PostgreSQL; signed cookie Worker dispatch; headless Chromium with local CSS; intercepted HTTP, no Cloudflare/Hyperdrive/network transit", + "results": [ + { + "screen": "Jobs", + "endpoint": { + "median_ms": 174.1, + "range_ms": [ + 153.2, + 193.7 + ] + }, + "useful_content": { + "median_ms": 264.4, + "range_ms": [ + 256.6, + 299.8 + ] + } + }, + { + "screen": "Job detail", + "endpoint": { + "median_ms": 127.8, + "range_ms": [ + 120.3, + 145.7 + ] + }, + "useful_content": { + "median_ms": 287.2, + "range_ms": [ + 266.6, + 303 + ] + } + }, + { + "screen": "Run detail", + "endpoint": { + "median_ms": 179.2, + "range_ms": [ + 172.2, + 186.7 + ] + }, + "useful_content": { + "median_ms": 868, + "range_ms": [ + 376.6, + 883.2 + ] + } + }, + { + "screen": "Job create", + "endpoint": { + "median_ms": 123.2, + "range_ms": [ + 115.1, + 127.2 + ] + }, + "useful_content": { + "median_ms": 305.6, + "range_ms": [ + 304.2, + 307.8 + ] + } + }, + { + "screen": "Job edit", + "endpoint": { + "median_ms": 118.5, + "range_ms": [ + 117.7, + 147.4 + ] + }, + "useful_content": { + "median_ms": 300.8, + "range_ms": [ + 268.5, + 312.7 + ] + } + }, + { + "screen": "Integrations", + "endpoint": { + "median_ms": 280.3, + "range_ms": [ + 262.6, + 288.8 + ] + }, + "useful_content": { + "median_ms": 378.8, + "range_ms": [ + 371, + 396.1 + ] + } + }, + { + "screen": "API Keys", + "endpoint": { + "median_ms": 74.2, + "range_ms": [ + 72.5, + 75.3 + ] + }, + "useful_content": { + "median_ms": 185.4, + "range_ms": [ + 164.8, + 197.4 + ] + } + } + ], + "indexes": [ + { + "indexname": "job_runs_launch_lease", + "indexdef": "CREATE INDEX job_runs_launch_lease ON app.job_runs USING btree (launch_lease_expires_at) WHERE (state = 'starting'::text)" + }, + { + "indexname": "job_runs_pkey", + "indexdef": "CREATE UNIQUE INDEX job_runs_pkey ON app.job_runs USING btree (tenant_id, id)" + }, + { + "indexname": "job_runs_poll_due", + "indexdef": "CREATE INDEX job_runs_poll_due ON app.job_runs USING btree (next_poll_at) WHERE (state = ANY (ARRAY['running'::text, 'blocked'::text, 'stopping'::text]))" + }, + { + "indexname": "job_runs_queue", + "indexdef": "CREATE INDEX job_runs_queue ON app.job_runs USING btree (state, created_at) WHERE (state = 'queued'::text)" + }, + { + "indexname": "job_runs_tenant_id_invocation_id_key", + "indexdef": "CREATE UNIQUE INDEX job_runs_tenant_id_invocation_id_key ON app.job_runs USING btree (tenant_id, invocation_id)" + } + ], + "plans": { + "old_single_job": [ + { + "Plan": { + "Node Type": "Aggregate", + "Strategy": "Plain", + "Partial Mode": "Simple", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 9.54, + "Total Cost": 9.55, + "Plan Rows": 1, + "Plan Width": 64, + "Actual Startup Time": 0.064, + "Actual Total Time": 0.065, + "Actual Rows": 1, + "Actual Loops": 1, + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Sort", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Startup Cost": 9.52, + "Total Cost": 9.52, + "Plan Rows": 1, + "Plan Width": 40, + "Actual Startup Time": 0.049, + "Actual Total Time": 0.05, + "Actual Rows": 3, + "Actual Loops": 1, + "Sort Key": [ + "created_at DESC" + ], + "Sort Method": "quicksort", + "Sort Space Used": 25, + "Sort Space Type": "Memory", + "Shared Hit Blocks": 5, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Heap Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Relation Name": "job_runs", + "Alias": "job_runs", + "Startup Cost": 4.16, + "Total Cost": 9.51, + "Plan Rows": 1, + "Plan Width": 40, + "Actual Startup Time": 0.017, + "Actual Total Time": 0.019, + "Actual Rows": 3, + "Actual Loops": 1, + "Recheck Cond": "(tenant_id = '6b8681f8-face-42b1-a98f-09cd461075c2'::uuid)", + "Rows Removed by Index Recheck": 0, + "Filter": "(job_id = '882bcfa2-e902-45d8-9bd9-43725b4dbd76'::uuid)", + "Rows Removed by Filter": 0, + "Exact Heap Blocks": 1, + "Lossy Heap Blocks": 0, + "Shared Hit Blocks": 2, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0, + "Plans": [ + { + "Node Type": "Bitmap Index Scan", + "Parent Relationship": "Outer", + "Parallel Aware": false, + "Async Capable": false, + "Index Name": "job_runs_tenant_id_invocation_id_key", + "Startup Cost": 0, + "Total Cost": 4.16, + "Plan Rows": 2, + "Plan Width": 0, + "Actual Startup Time": 0.007, + "Actual Total Time": 0.007, + "Actual Rows": 3, + "Actual Loops": 1, + "Index Cond": "(tenant_id = '6b8681f8-face-42b1-a98f-09cd461075c2'::uuid)", + "Shared Hit Blocks": 1, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + } + ] + } + ] + } + ] + }, + "Planning": { + "Shared Hit Blocks": 197, + "Shared Read Blocks": 0, + "Shared Dirtied Blocks": 0, + "Shared Written Blocks": 0, + "Local Hit Blocks": 0, + "Local Read Blocks": 0, + "Local Dirtied Blocks": 0, + "Local Written Blocks": 0, + "Temp Read Blocks": 0, + "Temp Written Blocks": 0 + }, + "Planning Time": 0.787, + "Triggers": [], + "Execution Time": 0.146 + } + ] + } +} diff --git a/packages/app/performance/gen-2154-proxy-baseline.jsonl b/packages/app/performance/gen-2154-proxy-baseline.jsonl new file mode 100644 index 00000000..9358dfa2 --- /dev/null +++ b/packages/app/performance/gen-2154-proxy-baseline.jsonl @@ -0,0 +1,8 @@ +{"endpoint": "/healthz", "status": ["200", "200", "200", "200", "200"], "median_ms": 86.3, "range_ms": [77.3, 106.7]} +{"endpoint": "/api/v1/jobs", "status": ["200", "200", "200", "200", "200"], "median_ms": 775.7, "range_ms": [681.6, 795.1]} +{"endpoint": "/api/v1/jobs/:jobId", "status": ["200", "200", "200", "200", "200"], "median_ms": 528.8, "range_ms": [446.9, 661.4]} +{"endpoint": "/api/v1/runs/:runId", "status": ["200", "200", "200", "200", "200"], "median_ms": 492.4, "range_ms": [474.9, 518.5]} +{"endpoint": "/api/v1/execution-targets", "status": ["200", "200", "200", "200", "200"], "median_ms": 307.8, "range_ms": [292.5, 337.1]} +{"endpoint": "/api/v1/job-trigger-availability", "status": ["200", "200", "200", "200", "200"], "median_ms": 307.6, "range_ms": [296.9, 311.5]} +{"endpoint": "/api/v1/integrations", "status": ["200", "200", "200", "200", "200"], "median_ms": 505.2, "range_ms": [493.9, 512.7]} +{"endpoint": "/api/v1/access-tokens", "status": ["403", "403", "403", "403", "403"], "median_ms": 102.6, "range_ms": [85.0, 108.7]} diff --git a/packages/app/scripts/loading-baseline.config.ts b/packages/app/scripts/loading-baseline.config.ts new file mode 100644 index 00000000..0abaac33 --- /dev/null +++ b/packages/app/scripts/loading-baseline.config.ts @@ -0,0 +1,2 @@ +import { defineConfig } from "vitest/config"; +export default defineConfig({ test: { include: ["test/loading-baseline.e2e.test.ts"] } }); diff --git a/packages/app/src/api-document.json b/packages/app/src/api-document.json index ba2328ec..ee5f23bd 100644 --- a/packages/app/src/api-document.json +++ b/packages/app/src/api-document.json @@ -595,6 +595,10 @@ "null" ], "description": "Secondary artifact or cleanup error; does not replace execution_diagnostics" + }, + "job_name": { + "type": "string", + "description": "Current job name, included so run content does not require a separate job request." } } }, diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index db96193e..d59e5bc3 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -30,6 +30,7 @@ export class ServiceError extends Error { type Scope = "flows:read" | "flows:write" | "runs:read" | "runs:write"; export class ApiService { + authorizationDuration = 0; constructor(private env: Env, private auth: OAuthProps) {} private jobs() { return new PostgresJobRepository(databaseFor(this.env), this.auth.tenantId, value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY), value => decrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)); } @@ -61,18 +62,36 @@ export class ApiService { }); } - private async presentJob(job: Job) { - const stats = (await databaseFor(this.env).pool.query<{ running_count: string; last_run_state: string | null }>(`SELECT count(*) FILTER (WHERE state IN ('starting','running','blocked','stopping'))::text running_count,(array_agg(state ORDER BY created_at DESC))[1] last_run_state FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2`, [this.auth.tenantId, job.id])).rows[0]; + private async jobStatistics(ids: string[]) { + if (!ids.length) return new Map(); + const result = await databaseFor(this.env).pool.query<{ job_id: string; running_count: string; last_run_state: string | null }>(` + WITH selected_runs AS ( + SELECT job_id,state,created_at,id FROM app.job_runs WHERE tenant_id=$1 AND job_id=ANY($2::uuid[]) + ), counts AS ( + SELECT job_id,count(*) FILTER (WHERE state IN ('starting','running','blocked','stopping'))::text running_count + FROM selected_runs GROUP BY job_id + ), latest AS ( + SELECT DISTINCT ON (job_id) job_id,state FROM selected_runs ORDER BY job_id,created_at DESC,id DESC + ) + SELECT c.job_id,c.running_count,l.state last_run_state FROM counts c JOIN latest l USING (job_id)`, [this.auth.tenantId, ids]); + return new Map(result.rows.map(row => [row.job_id, row])); + } + + private async presentJob(job: Job, loadedStats?: { running_count: string; last_run_state: string | null }) { + const stats = loadedStats ?? (await this.jobStatistics([job.id])).get(job.id); const runningCount = Number(stats?.running_count ?? 0); return { ...job, runNameTemplate: job.runNameTemplate ?? "", executionTargetId: `${job.executionTarget.agentKind === "Amp" ? "amp:" : ""}${job.executionTarget.connectionId}`, agentKind: job.executionTarget.agentKind, runningCount, currentRuns: runningCount, maxConcurrency: job.concurrencyLimit, lastRunState: stats?.last_run_state ?? null }; } private async authorize(scope: Scope): Promise { if (!this.auth.scopes.includes(scope)) throw new ServiceError(403, "insufficient_scope", `The ${scope} scope is required.`); - const database = databaseFor(this.env); - const member = await new IdentityRepository(database, this.auth.tenantId).member(this.auth.userId); - const tokenActive = !this.auth.accessTokenId || await new AccessTokenRepository(database, this.auth.tenantId).active(this.auth.accessTokenId); - if (member?.role !== "owner" || member.sessionVersion !== this.auth.sessionVersion || !tokenActive) throw new ServiceError(401, "invalid_token", "The request is not authorized."); + const started = performance.now(); + try { + const database = databaseFor(this.env); + const member = await new IdentityRepository(database, this.auth.tenantId).member(this.auth.userId); + const tokenActive = !this.auth.accessTokenId || await new AccessTokenRepository(database, this.auth.tenantId).active(this.auth.accessTokenId); + if (member?.role !== "owner" || member.sessionVersion !== this.auth.sessionVersion || !tokenActive) throw new ServiceError(401, "invalid_token", "The request is not authorized."); + } finally { this.authorizationDuration += performance.now() - started; } } private async authorizeOwnerSession(scope: Scope): Promise { await this.authorize(scope); if (this.auth.authMethod !== "session") throw new ServiceError(403, "session_required", "An interactive owner session is required."); } @@ -89,7 +108,24 @@ export class ApiService { async listTailIntegrations() { await this.authorize("flows:read"); return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).tails(); } async listRuns(query: URLSearchParams) { await this.authorize("runs:read"); return new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).list(query); } async search(query: string) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).search(query); } - async getRun(runId: string) { await this.authorize("runs:read"); const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId), run = await repository.get(runId); if (!run) throw new ServiceError(404, "not_found", "Run not found"); const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; run.activity = await repository.activity(runId); run.execution_diagnostics ??= null; run.trace_sources ??= null; run.trace_projection = (await databaseFor(this.env).pool.query("SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId])).rows[0] ?? null; run.trace_generation = (await databaseFor(this.env).pool.query("SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId])).rows[0]?.generation ?? null; run.harness_log = (await new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId)).find(item => item.kind === "terminal_log") ?? null; return run; } + async getRun(runId: string) { + await this.authorize("runs:read"); + const repository = new RunQueryRepository(databaseFor(this.env), this.auth.tenantId); + const run = await repository.get(runId); + if (!run) throw new ServiceError(404, "not_found", "Run not found"); + const prompt = await decrypt(run.encrypted_prompt, this.env.CREDENTIAL_ENCRYPTION_KEY); + delete run.encrypted_prompt; run.prompt = prompt; run.capabilities = run.execution_capabilities; run.backend_kind = run.execution_backend_kind; run.invocation = { id: run.invocation_id, source: run.invocation_source, claim_key: run.invocation_claim_key, trigger_id: run.invocation_trigger_id, context: run.context, occurrence: run.occurrence, created_at: run.invocation_created_at }; + const [activity, projection, cursor, artifacts] = await Promise.all([ + repository.activity(runId), + databaseFor(this.env).pool.query("SELECT source_kind,artifact_sha256,parser_version,updated_at FROM app.run_trace_projections WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId]), + databaseFor(this.env).pool.query("SELECT generation FROM app.run_trace_cursors WHERE tenant_id=$1 AND run_id=$2", [this.auth.tenantId, runId]), + new ArtifactRepository(databaseFor(this.env), this.auth.tenantId).list(runId), + ]); + run.activity = activity; run.execution_diagnostics ??= null; run.trace_sources ??= null; + run.trace_projection = projection.rows[0] ?? null; run.trace_generation = cursor.rows[0]?.generation ?? null; + run.harness_log = artifacts.find(item => item.kind === "terminal_log") ?? null; + return run; + } async getRunTrace(runId: string, after: number, limit: number) { await this.authorize("runs:read"); return new TraceRepository(databaseFor(this.env), this.auth.tenantId).page(runId, after, limit); } async getRunDiagnostics(runId: string) { const run: any = await this.getRun(runId), database = databaseFor(this.env); @@ -115,7 +151,7 @@ export class ApiService { } async stopRun(runId: string) { await this.authorize("runs:write"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } killRun(runId: string) { return this.stopRun(runId); } - async listJobs() { await this.authorize("flows:read"); return Promise.all((await this.jobs().list()).map(job => this.presentJob(job))); } + async listJobs() { await this.authorize("flows:read"); const jobs = await this.jobs().list(), stats = await this.jobStatistics(jobs.map(job => job.id)); return Promise.all(jobs.map(job => this.presentJob(job, stats.get(job.id) ?? { running_count: "0", last_run_state: null }))); } async getJob(jobId: string) { await this.authorize("flows:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); } async listJobEvents(jobId: string, limit = 50) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).jobEvents(jobId, limit); } async listWebhookDeliveries(query: URLSearchParams) { await this.authorize("runs:read"); return new OperationsRepository(databaseFor(this.env), this.auth.tenantId).deliveries(query); } @@ -160,13 +196,13 @@ export class ApiService { return { invocationId: result.invocation.id, runId: result.run.id, state: result.run.state, duplicate: result.duplicate }; } async listExecutionTargets() { - await this.authorize("flows:read"); const connections = this.connections(), kinds = await connections.kinds(); const targets: any[] = []; - for (const kind of kinds) if (kind.startsWith("exe:")) { const id = kind.slice(4), value = await connections.get(kind); targets.push({ id, kind: "exe-vm", name: "Ephemeral exe.dev VMs", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: value.agentKind, models: value.models ?? [], modelsRefreshedAt: value.modelsRefreshedAt ?? null, efforts: value.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [], capabilities: ["recovery", "stop"] }); } - else if (kind.startsWith("amp:")) { const id = kind.slice(4), value = await connections.get(kind); targets.push({ id: `amp:${id}`, kind: "amp", name: `Amp · ${value.project}`, workspace: value.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }); } + await this.authorize("flows:read"); const connections = await this.connections().all(["exe:", "amp:"]); const targets: any[] = []; + for (const [kind, value] of connections) if (kind.startsWith("exe:")) { const id = kind.slice(4); targets.push({ id, kind: "exe-vm", name: "Ephemeral exe.dev VMs", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: value.agentKind, models: value.models ?? [], modelsRefreshedAt: value.modelsRefreshedAt ?? null, efforts: value.agentKind === "codex" ? ["minimal", "low", "medium", "high", "xhigh"] : [], capabilities: ["recovery", "stop"] }); } + else if (kind.startsWith("amp:")) { const id = kind.slice(4); targets.push({ id: `amp:${id}`, kind: "amp", name: `Amp · ${value.project}`, workspace: value.project, cwd: "Cloud orb", agentKind: "Amp", capabilities: ["stop"] }); } return targets; } async diagnoseExeIntegration(connectionId: string) { await this.authorize("flows:write"); const value = await new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY).diagnoseExe(connectionId); if (!value) throw new ServiceError(404,"not_found","Integration not found"); return value; } - async listJobTriggerAvailability() { await this.authorize("flows:read"); const connections=this.connections(), kinds=await connections.kinds(), states=(await new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()).map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } + async listJobTriggerAvailability() { await this.authorize("flows:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedTriggerAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } async previewSchedule(input: unknown) { await this.authorize("flows:read"); try { diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 37deadac..5f5052f4 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -12,12 +12,16 @@ import { ConnectionRepository } from "./postgres/connection-repository"; import { GitHubRepository } from "./postgres/github-repository"; import { WebhookService } from "./postgres/webhook-service"; -const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>(); +const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string; authorizationDuration: number } }>(); app.use("*", async (c, next) => { + const started = performance.now(); + c.set("authorizationDuration", 0); const nonce = crypto.randomUUID(); c.set("cspNonce", nonce); await next(); + const authorizationDuration = c.get("authorizationDuration"); + c.header("Server-Timing", `auth;dur=${authorizationDuration.toFixed(1)}, application;dur=${Math.max(0, performance.now() - started - authorizationDuration).toFixed(1)}`); c.header("Content-Security-Policy", `default-src 'self'; script-src 'nonce-${nonce}'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'`); // Keep Origin on same-origin form POSTs; no-referrer makes it "null" in // browsers and breaks the auth CSRF check. External requests still omit Referer. @@ -71,9 +75,12 @@ async function establishSession(c: any, identity: { userId: string; email: strin } async function authed(c: any): Promise { return readSession(getCookie(c, "factorize_session"), c.env.SESSION_SIGNING_SECRET); } async function owner(c: any): Promise { - const session = await authed(c); if (!session) return null; - const member = await new IdentityRepository(databaseFor(c.env), session.tenantId).member(session.userId); - return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? session : null; + const started = performance.now(); + try { + const session = await authed(c); if (!session) return null; + const member = await new IdentityRepository(databaseFor(c.env), session.tenantId).member(session.userId); + return member?.role === "owner" && member.sessionVersion === session.sessionVersion ? session : null; + } finally { c.set("authorizationDuration", (c.get("authorizationDuration") ?? 0) + performance.now() - started); } } app.get("/styles.css", (c) => c.env.ASSETS.fetch(c.req.raw)); diff --git a/packages/app/src/postgres/connection-repository.ts b/packages/app/src/postgres/connection-repository.ts index f6c63b4f..40d89319 100644 --- a/packages/app/src/postgres/connection-repository.ts +++ b/packages/app/src/postgres/connection-repository.ts @@ -1,6 +1,6 @@ import { decrypt, encrypt } from "../crypto"; import type { Database } from "./database"; -import { and, eq, like } from "drizzle-orm"; +import { and, eq, like, or } from "drizzle-orm"; import { connections } from "./schema"; export class ConnectionRepository { @@ -12,6 +12,10 @@ export class ConnectionRepository { if (!row) return null; return JSON.parse(await decrypt(row.encryptedValue, this.encryptionKey)) as T; } + async all(kinds: readonly string[] = []): Promise> { + const rows = await this.database.orm.select().from(connections).where(and(eq(connections.tenantId, this.tenantId), kinds.length ? or(...kinds.map(kind => kind.endsWith(":") ? like(connections.kind, `${kind}%`) : eq(connections.kind, kind))) : undefined)).orderBy(connections.kind); + return new Map(await Promise.all(rows.map(async row => [row.kind, JSON.parse(await decrypt(row.encryptedValue, this.encryptionKey))] as const))); + } async put(kind: string, value: unknown): Promise { const encrypted = await encrypt(JSON.stringify(value), this.encryptionKey); await this.database.orm.insert(connections).values({ tenantId: this.tenantId, kind, encryptedValue: encrypted }).onConflictDoUpdate({ target: [connections.tenantId, connections.kind], set: { encryptedValue: encrypted, updatedAt: new Date() } }); diff --git a/packages/app/src/postgres/integration-service.ts b/packages/app/src/postgres/integration-service.ts index dfe06ac9..ad57c034 100644 --- a/packages/app/src/postgres/integration-service.ts +++ b/packages/app/src/postgres/integration-service.ts @@ -57,16 +57,24 @@ export class IntegrationService { await this.connections.put(`cloudflare-tail:${integrationId}`, { name, signingSecret, createdAt: existing?.createdAt ?? now, updatedAt: now }); return { integrationId, name, status: "connected", secretConfigured: true, ...(value.generateSecret ? { generatedSecret: signingSecret } : {}) }; } - async tails() { - const values = [] as any[]; - for (const kind of await this.connections.kinds("cloudflare-tail:")) { const value = await this.connections.get(kind); const integrationId = kind.slice(16); const count = await this.database.pool.query<{ count: string }>("SELECT count(DISTINCT job_id)::text count FROM app.triggers WHERE tenant_id=$1 AND removed_at IS NULL AND kind='webhook' AND config->>'provider'='cloudflareTail' AND config->>'integrationId'=$2", [this.tenantId, integrationId]); const { signingSecret: _, ...safe } = value; values.push({ ...safe, integrationId, status: "connected", secretConfigured: true, referencedJobCount: Number(count.rows[0]?.count ?? 0) }); } - return values; + async tails(loaded?: Map | Promise>) { + const [connections, counts] = await Promise.all([ + loaded ?? this.connections.all(["cloudflare-tail:"]), + this.database.pool.query<{ integration_id: string; count: string }>("SELECT config->>'integrationId' integration_id,count(DISTINCT job_id)::text count FROM app.triggers WHERE tenant_id=$1 AND removed_at IS NULL AND kind='webhook' AND config->>'provider'='cloudflareTail' GROUP BY config->>'integrationId'", [this.tenantId]), + ]); + const byId = new Map(counts.rows.map(row => [row.integration_id, Number(row.count)])); + return [...connections].filter(([kind]) => kind.startsWith("cloudflare-tail:")).map(([kind, value]) => { + const { signingSecret: _, ...safe } = value, integrationId = kind.slice(16); + return { ...safe, integrationId, status: "connected", secretConfigured: true, referencedJobCount: byId.get(integrationId) ?? 0 }; + }); } async testTail(id: string) { const value = await this.connections.get(`cloudflare-tail:${id}`); if (!value) return null; const now = String(Date.now()), delivery = `test-${crypto.randomUUID()}`, body = "{}", signature = await signTailDelivery(value.signingSecret, now, delivery, body); return { ok: await verifyTailDelivery(value.signingSecret, now, delivery, body, signature) === "valid" }; } async status() { - const linear = await this.connections.get("linear"), clickup = await this.connections.get("clickup"), exeConnections = [], ampConnections = []; - for (const kind of await this.connections.kinds("exe:")) { const { apiToken: _, ...safe } = await this.connections.get(kind); exeConnections.push({ ...safe, connectionId: kind.slice(4) }); } - for (const kind of await this.connections.kinds("amp:")) { const { accessToken: _, ...safe } = await this.connections.get(kind); ampConnections.push({ ...safe, connectionId: kind.slice(4) }); } - const tails = await this.tails(); return { linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, clickup: clickup ? { teamName: clickup.teamName ?? null } : null, exe: exeConnections[0] ?? null, exeConnections, ampConnections, cloudflareTail: { count: tails.length, installations: tails } }; + const connectionsPromise = this.connections.all(["linear", "clickup", "exe:", "amp:", "cloudflare-tail:"]); + const [connections, tails] = await Promise.all([connectionsPromise, this.tails(connectionsPromise)]); + const linear = connections.get("linear"), clickup = connections.get("clickup"); + const exeConnections = [...connections].filter(([kind]) => kind.startsWith("exe:")).map(([kind, value]) => { const { apiToken: _, ...safe } = value; return { ...safe, connectionId: kind.slice(4) }; }); + const ampConnections = [...connections].filter(([kind]) => kind.startsWith("amp:")).map(([kind, value]) => { const { accessToken: _, ...safe } = value; return { ...safe, connectionId: kind.slice(4) }; }); + return { linear: linear ? { organizationName: linear.organizationName ?? null, viewerEmail: linear.viewerEmail ?? null } : null, clickup: clickup ? { teamName: clickup.teamName ?? null } : null, exe: exeConnections[0] ?? null, exeConnections, ampConnections, cloudflareTail: { count: tails.length, installations: tails } }; } } diff --git a/packages/app/src/postgres/job-repository.ts b/packages/app/src/postgres/job-repository.ts index 753398e5..e4f90c73 100644 --- a/packages/app/src/postgres/job-repository.ts +++ b/packages/app/src/postgres/job-repository.ts @@ -2,7 +2,7 @@ import { lockJobQueue, requireQueueCapacity } from "./queue-admission"; import type { Invocation, Job, JobRepository, JobRun, Trigger } from "../job-domain"; import type { Database, DatabaseClient } from "./database"; import { nextOccurrence, validateScheduleConfig } from "../schedule"; -import { and, eq, isNull, sql } from "drizzle-orm"; +import { and, eq, inArray, isNull, sql } from "drizzle-orm"; import { invocations, jobs, jobEditDeliveries, lifecycleDeliveries, pendingVerifications, scheduleState, triggers } from "./schema"; type Crypt = (value: string) => Promise; @@ -15,8 +15,8 @@ export class PostgresJobRepository implements JobRepository { } private trigger(row: TriggerRow): Trigger { return { id: row.id, jobId: row.jobId, kind: row.kind, slug: row.slug, enabled: row.enabled, config: row.config, createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } - private async mapped(row: JobRow, db: any = this.database.orm): Promise { - const triggerRows: TriggerRow[] = await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); + private async mapped(row: JobRow, db: any = this.database.orm, loadedTriggers?: TriggerRow[]): Promise { + const triggerRows: TriggerRow[] = loadedTriggers ?? await db.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), eq(triggers.jobId, row.id), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); return { id: row.id, name: row.name, slug: row.slug, promptTemplate: await this.decrypt(row.encryptedPromptTemplate), runNameTemplate: row.encryptedRunNameTemplate ? await this.decrypt(row.encryptedRunNameTemplate) : "", model: row.model, ...(row.effort ? { effort: row.effort } : {}), executionTarget: row.executionTarget, concurrencyLimit: row.concurrencyLimit, enabled: row.enabled, triggers: triggerRows.map(value => this.trigger(value)), createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString() }; } @@ -27,7 +27,15 @@ export class PostgresJobRepository implements JobRepository { async list(): Promise { const rows = await this.database.orm.select().from(jobs).where(eq(jobs.tenantId, this.tenantId)).orderBy(sql`${jobs.createdAt} desc`); - return Promise.all(rows.map(row => this.mapped(row))); + if (!rows.length) return []; + const triggerRows = await this.database.orm.select().from(triggers).where(and(eq(triggers.tenantId, this.tenantId), inArray(triggers.jobId, rows.map(row => row.id)), isNull(triggers.removedAt))).orderBy(triggers.position, triggers.createdAt, triggers.id); + const byJob = new Map(); + for (const trigger of triggerRows) { + const group = byJob.get(trigger.jobId) ?? []; + group.push(trigger); + byJob.set(trigger.jobId, group); + } + return Promise.all(rows.map(row => this.mapped(row, this.database.orm, byJob.get(row.id) ?? []))); } async create(job: Job): Promise { diff --git a/packages/app/src/postgres/run-query-repository.ts b/packages/app/src/postgres/run-query-repository.ts index 709f3abe..82c4612c 100644 --- a/packages/app/src/postgres/run-query-repository.ts +++ b/packages/app/src/postgres/run-query-repository.ts @@ -18,8 +18,8 @@ export class RunQueryRepository { return { items: rows, nextCursor: hasMore && rows.length ? encodeCursor(rows.at(-1).created_at, rows.at(-1).id) : null }; } async get(runId: string) { - return (await this.database.pool.query(`SELECT r.*,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.created_at invocation_created_at - FROM app.runs r JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id WHERE r.tenant_id=$1 AND r.id=$2`, [this.tenantId, runId])).rows[0] ?? null; + return (await this.database.pool.query(`SELECT r.*,j.name job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.created_at invocation_created_at + FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id WHERE r.tenant_id=$1 AND r.id=$2`, [this.tenantId, runId])).rows[0] ?? null; } async activity(runId: string) { return (await this.database.pool.query("SELECT action,detail,created_at FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } async stop(runId: string) { return (await this.database.pool.query("UPDATE app.job_runs SET state='stopping',next_poll_at=now(),updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state IN ('starting','running','blocked') RETURNING id,state", [this.tenantId, runId])).rows[0] ?? null; } diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 86957528..a32cebd1 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -38,8 +38,13 @@ function structured(value: unknown) { } export async function protectedApiFetch(request: Request, env: Env, auth: OAuthProps, ctx: ExecutionContext): Promise { + const started = performance.now(), service = new ApiService(env, auth); + const timed = (response: Response) => { + response.headers.set("Server-Timing", `auth;dur=${service.authorizationDuration.toFixed(1)}, application;dur=${Math.max(0, performance.now() - started - service.authorizationDuration).toFixed(1)}`); + return response; + }; try { - const url = new URL(request.url), path = url.pathname, service = new ApiService(env, auth); + const url = new URL(request.url), path = url.pathname; if (path === "/mcp") return mcp(request, service, env, ctx); const matched = matchApiOperation(request.method, path); if (!matched) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); @@ -54,8 +59,8 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP body = route.body.parse(body); } const query = route.query?.parse(queryInput(url)); - return Response.json(await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url }), { status: route.status }); - } catch (error) { return errorResponse(error); } + return timed(Response.json(await route.execute(service, { params: route.parameters.parse(params) as Record, body, query, url }), { status: route.status })); + } catch (error) { return timed(errorResponse(error)); } } const mcpServices = new WeakMap(); diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 4a4eee3c..b701feb4 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -259,7 +259,7 @@ function updateRun(r){ updateElapsed(r); } async function refreshOutput(){const generation=mutationGeneration;const r=await request('/api/v1/runs/'+encodeURIComponent(id));if(generation!==mutationGeneration){reconcile(()=>runRefresh.refresh());return}const reset=currentRun&&(r.trace_generation!==currentRun.trace_generation||JSON.stringify(r.trace_projection)!==JSON.stringify(currentRun.trace_projection)||(activeStates.includes(currentRun.state)&&!activeStates.includes(r.state)));updateRun(r);if(traceLoading)await traceLoading;traceDone=false;await loadTrace(Boolean(reset))} -async function loadRun(){return request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>({r,j:await request('/api/v1/jobs/'+encodeURIComponent(r.job_id))})).then(async({r,j})=>{const canKill=['starting','running','blocked'].includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='

'+esc(runLabel)+'

'+elapsed(r)+'

'+queueTime(r)+'

'+stateBadge(r.state)+''+(canKill?'':'')+'
'+triggerProvenance(r)+'
Prompt
'+esc(r.prompt||'Prompt is not available for this run.')+'

Trace

'+esc(traceSourceLabel(r))+'

'+(activeStates.includes(r.state)?'Live · refreshes automatically':'')+'

Trace events are not available yet.

';if(canKill)$('#kill-run').onclick=()=>{if(!confirm('Request this run to stop? It remains visible until the backend confirms termination.'))return;mutate('#kill-run','Stopping…',async()=>{try{const result=await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});updateRun({...currentRun,state:result.state})}catch(e){let error=$('[data-stop-error]');if(!error){root.insertAdjacentHTML('afterbegin','

');error=$('[data-stop-error]')}error.textContent=e.message+(e.definitive?'':' Outcome unknown; checking server state.')}reconcile(()=>runRefresh.refresh())})};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace().catch(()=>{})};updateRun(r);await loadTrace()})} +async function loadRun(){return request('/api/v1/runs/'+encodeURIComponent(id)).then(async r=>{const canKill=['starting','running','blocked'].includes(r.state),runLabel=r.name||r.run_name||r.issue_title||'Run '+r.id.slice(0,8);document.title=runLabel+' — Factorize';root.innerHTML='

'+esc(runLabel)+'

'+elapsed(r)+'

'+queueTime(r)+'

'+stateBadge(r.state)+''+(canKill?'':'')+'
'+triggerProvenance(r)+'
Prompt
'+esc(r.prompt||'Prompt is not available for this run.')+'

Trace

'+esc(traceSourceLabel(r))+'

'+(activeStates.includes(r.state)?'Live · refreshes automatically':'')+'

Trace events are not available yet.

';if(canKill)$('#kill-run').onclick=()=>{if(!confirm('Request this run to stop? It remains visible until the backend confirms termination.'))return;mutate('#kill-run','Stopping…',async()=>{try{const result=await request('/api/v1/runs/'+encodeURIComponent(id)+'/kill',{method:'POST'});updateRun({...currentRun,state:result.state})}catch(e){let error=$('[data-stop-error]');if(!error){root.insertAdjacentHTML('afterbegin','

');error=$('[data-stop-error]')}error.textContent=e.message+(e.definitive?'':' Outcome unknown; checking server state.')}reconcile(()=>runRefresh.refresh())})};$('[data-trace-more]').onclick=()=>{traceDone=false;loadTrace().catch(()=>{})};updateRun(r);await loadTrace()})} const runRefresh=pageRefresh(async()=>{if(!currentRun)await loadRun();else await refreshOutput()},{delay:()=>activeStates.includes(currentRun.state)?3000:['pending','collecting'].includes(currentRun.artifact_state)?10000:null,onError:e=>{if(!currentRun)root.innerHTML='

'+esc(e.message)+'

'}});`); const settingsLayout = (active: "integrations" | "api-keys", content: string) => `