|
1 | 1 | import { Container, switchPort } from '@cloudflare/containers'; |
2 | | -import { eq } from 'drizzle-orm'; |
| 2 | +import { desc, eq } from 'drizzle-orm'; |
3 | 3 | import { drizzle } from 'drizzle-orm/d1'; |
4 | 4 |
|
5 | 5 | import * as schema from '../db/schema'; |
6 | 6 | import type { Env } from '../env'; |
7 | 7 | import { log } from '../lib/logger'; |
| 8 | +import { signCallbackToken, signNodeCallbackToken, signNodeManagementToken } from '../services/jwt'; |
8 | 9 |
|
9 | 10 | export const DEFAULT_CF_CONTAINER_SLEEP_AFTER = '1h'; |
10 | 11 | export const DEFAULT_CF_CONTAINER_ACTIVE_WORK_MAX_MS = 2 * 60 * 60 * 1000; |
@@ -45,14 +46,20 @@ interface ActiveWorkState { |
45 | 46 |
|
46 | 47 | const ACTIVE_WORK_KEY = 'activeWork'; |
47 | 48 | const KEEPALIVE_CALLBACK = 'renewActiveWorkKeepalive'; |
48 | | -const SLEEPING_RESPONSE = 'Container is asleep; wake/rehydrate is not implemented yet.'; |
| 49 | +const WAKE_DEGRADED_RESPONSE = 'Workspace woke with degraded snapshot restore; retry the prompt or fork from transcript history.'; |
49 | 50 |
|
50 | 51 | export class VmAgentContainer extends Container<Env> { |
51 | 52 | defaultPort = 8080; |
52 | 53 | requiredPorts = [8080]; |
53 | 54 | sleepAfter = DEFAULT_CF_CONTAINER_SLEEP_AFTER; |
54 | 55 | enableInternet = true; |
55 | 56 |
|
| 57 | + // Serializes wake-from-snapshot so two concurrent requests to a sleeping |
| 58 | + // container do not both launch a fresh container + restore. DO request |
| 59 | + // handlers interleave across `await`, so the sleeping-check + wake must run |
| 60 | + // as one critical section (see .claude/rules/45). |
| 61 | + private wakeChain: Promise<unknown> = Promise.resolve(); |
| 62 | + |
56 | 63 | constructor(ctx: DurableObjectState<Record<string, never>>, env: Env) { |
57 | 64 | super(ctx, env); |
58 | 65 | const configuredPort = Number.parseInt(env.CF_CONTAINER_VM_AGENT_PORT || env.SANDBOX_VM_AGENT_PORT || '', 10); |
@@ -108,12 +115,18 @@ export class VmAgentContainer extends Container<Env> { |
108 | 115 | } |
109 | 116 |
|
110 | 117 | async proxyHttp(request: Request, port?: number): Promise<Response> { |
111 | | - const state = await this.getState(); |
| 118 | + let state = await this.getState(); |
112 | 119 | const lifecycleStatus = await this.ctx.storage.get<LifecycleStatus>('lifecycleStatus'); |
113 | 120 | if (lifecycleStatus === 'sleeping') { |
114 | | - // Phase 3 of idea 01KX4KSXEXQMP41KS34TW9EN01 will replace this temporary |
115 | | - // response with wake/rehydrate before proxying the request. |
116 | | - return new Response(SLEEPING_RESPONSE, { status: 503 }); |
| 121 | + const wake = await this.ensureAwake(); |
| 122 | + if (!wake.ok) { |
| 123 | + return new Response(wake.message || WAKE_DEGRADED_RESPONSE, { status: 503 }); |
| 124 | + } |
| 125 | + // wakeFromSnapshot launched a fresh container and restored the session. |
| 126 | + // Re-read the container state so the stopped-check below reflects the |
| 127 | + // now-running container instead of the pre-wake stopped snapshot, |
| 128 | + // otherwise a successfully-woken session is wrongly rejected with 410. |
| 129 | + state = await this.getState(); |
117 | 130 | } |
118 | 131 | if (state.status === 'stopped' || state.status === 'stopped_with_code') { |
119 | 132 | return new Response('Container is stopped; create a new instant session.', { status: 410 }); |
@@ -232,12 +245,16 @@ export class VmAgentContainer extends Container<Env> { |
232 | 245 | } |
233 | 246 |
|
234 | 247 | override async fetch(request: Request): Promise<Response> { |
235 | | - const state = await this.getState(); |
| 248 | + let state = await this.getState(); |
236 | 249 | const lifecycleStatus = await this.ctx.storage.get<LifecycleStatus>('lifecycleStatus'); |
237 | 250 | if (lifecycleStatus === 'sleeping') { |
238 | | - // Phase 3 of idea 01KX4KSXEXQMP41KS34TW9EN01 will replace this temporary |
239 | | - // response with wake/rehydrate before proxying the request. |
240 | | - return new Response(SLEEPING_RESPONSE, { status: 503 }); |
| 251 | + const wake = await this.ensureAwake(); |
| 252 | + if (!wake.ok) { |
| 253 | + return new Response(wake.message || WAKE_DEGRADED_RESPONSE, { status: 503 }); |
| 254 | + } |
| 255 | + // Re-read the container state after wake so the stopped-check reflects |
| 256 | + // the freshly-launched container, not the pre-wake stopped snapshot. |
| 257 | + state = await this.getState(); |
241 | 258 | } |
242 | 259 | if (state.status === 'stopped' || state.status === 'stopped_with_code') { |
243 | 260 | return new Response('Container is stopped; create a new instant session.', { status: 410 }); |
@@ -299,6 +316,165 @@ export class VmAgentContainer extends Container<Env> { |
299 | 316 | return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_CF_CONTAINER_KEEPALIVE_RENEW_INTERVAL_MS; |
300 | 317 | } |
301 | 318 |
|
| 319 | + /** |
| 320 | + * Wake a sleeping container exactly once under concurrency. Serializes on |
| 321 | + * `wakeChain` and re-reads `lifecycleStatus` inside the critical section, so a |
| 322 | + * second request that arrives while the first is waking sees `running` and |
| 323 | + * skips a duplicate launch/restore instead of racing it (see rule 45). |
| 324 | + */ |
| 325 | + private async ensureAwake(): Promise<{ ok: boolean; message?: string }> { |
| 326 | + const run = this.wakeChain.then(async () => { |
| 327 | + const status = await this.ctx.storage.get<LifecycleStatus>('lifecycleStatus'); |
| 328 | + if (status !== 'sleeping') { |
| 329 | + return { ok: true }; |
| 330 | + } |
| 331 | + return this.wakeFromSnapshot(); |
| 332 | + }); |
| 333 | + // Keep the chain alive even if this wake rejects, so a failure does not |
| 334 | + // permanently wedge all future wakes. |
| 335 | + this.wakeChain = run.then( |
| 336 | + () => undefined, |
| 337 | + () => undefined |
| 338 | + ); |
| 339 | + return run; |
| 340 | + } |
| 341 | + |
| 342 | + private async wakeFromSnapshot(): Promise<{ ok: boolean; message?: string }> { |
| 343 | + const config = await this.ctx.storage.get<VmAgentContainerLaunchConfig>('launchConfig'); |
| 344 | + if (!config) { |
| 345 | + return { ok: false, message: 'Container launch configuration is unavailable.' }; |
| 346 | + } |
| 347 | + const db = drizzle(this.env.DATABASE, { schema }); |
| 348 | + const workspace = await db |
| 349 | + .select({ |
| 350 | + userId: schema.workspaces.userId, |
| 351 | + chatSessionId: schema.workspaces.chatSessionId, |
| 352 | + }) |
| 353 | + .from(schema.workspaces) |
| 354 | + .where(eq(schema.workspaces.id, config.workspaceId)) |
| 355 | + .get(); |
| 356 | + if (!workspace?.chatSessionId) { |
| 357 | + return { ok: false, message: 'Workspace session metadata is unavailable.' }; |
| 358 | + } |
| 359 | + const agentSession = await db |
| 360 | + .select({ id: schema.agentSessions.id, agentType: schema.agentSessions.agentType }) |
| 361 | + .from(schema.agentSessions) |
| 362 | + .where(eq(schema.agentSessions.workspaceId, config.workspaceId)) |
| 363 | + .orderBy(desc(schema.agentSessions.updatedAt)) |
| 364 | + .get(); |
| 365 | + if (!agentSession) { |
| 366 | + return { ok: false, message: 'Agent session metadata is unavailable.' }; |
| 367 | + } |
| 368 | + |
| 369 | + log.info('vm_agent_container_wake_started', { |
| 370 | + nodeId: config.nodeId, |
| 371 | + workspaceId: config.workspaceId, |
| 372 | + chatSessionId: workspace.chatSessionId, |
| 373 | + agentSessionId: agentSession.id, |
| 374 | + }); |
| 375 | + |
| 376 | + await this.ctx.storage.put('lifecycleStatus', 'launching' satisfies LifecycleStatus); |
| 377 | + // The container's CALLBACK_TOKEN must be node-scoped to match the initial |
| 378 | + // launch (see launchInstantSession): the vm-agent uses it for node callbacks |
| 379 | + // (error/activity/message reporting) which reject workspace-scoped tokens. |
| 380 | + // Using a workspace-scoped token here caused restored sessions to accept a |
| 381 | + // prompt (200) but silently fail to report the agent's reply back (403 |
| 382 | + // "Insufficient token scope"), so no answer appeared after wake. |
| 383 | + const callbackToken = await signNodeCallbackToken(config.nodeId, this.env); |
| 384 | + await this.launch(config, { nodeCallbackToken: callbackToken }); |
| 385 | + |
| 386 | + // The fresh container never ran create-workspace, so its workspace-scoped |
| 387 | + // runtime.CallbackToken is unset. The message reporter and snapshot |
| 388 | + // callbacks require it (they do NOT fall back to the node-scoped token), so |
| 389 | + // pass it on the restore request; without it, restored sessions accept a |
| 390 | + // prompt but silently discard the agent's reply ("no auth token"). |
| 391 | + const workspaceCallbackToken = await signCallbackToken(config.workspaceId, this.env); |
| 392 | + const { token } = await signNodeManagementToken(workspace.userId, config.nodeId, config.workspaceId, this.env); |
| 393 | + const restoreUrl = new URL(`http://localhost:${config.vmAgentPort}/workspaces/${config.workspaceId}/agent-sessions/${agentSession.id}/restore`); |
| 394 | + const restoreResponse = await this.containerFetch( |
| 395 | + new Request(restoreUrl.toString(), { |
| 396 | + method: 'POST', |
| 397 | + headers: { |
| 398 | + Authorization: `Bearer ${token}`, |
| 399 | + 'Content-Type': 'application/json', |
| 400 | + 'X-SAM-Node-Id': config.nodeId, |
| 401 | + 'X-SAM-Workspace-Id': config.workspaceId, |
| 402 | + }, |
| 403 | + body: JSON.stringify({ |
| 404 | + chatSessionId: workspace.chatSessionId, |
| 405 | + runtime: 'cf-container', |
| 406 | + agentType: agentSession.agentType, |
| 407 | + workspaceCallbackToken, |
| 408 | + }), |
| 409 | + }), |
| 410 | + config.vmAgentPort |
| 411 | + ); |
| 412 | + const restoreBody = await restoreResponse.text().catch(() => ''); |
| 413 | + if (!restoreResponse.ok) { |
| 414 | + await this.markWakeDegraded(config, restoreBody || `restore failed with HTTP ${restoreResponse.status}`); |
| 415 | + return { ok: false, message: restoreBody || 'Session restore failed.' }; |
| 416 | + } |
| 417 | + let restoreStatus = ''; |
| 418 | + try { |
| 419 | + const parsed = JSON.parse(restoreBody) as { status?: unknown }; |
| 420 | + restoreStatus = typeof parsed.status === 'string' ? parsed.status : ''; |
| 421 | + } catch { |
| 422 | + // A successful restore must provide an explicit machine-readable status. |
| 423 | + } |
| 424 | + if (restoreStatus !== 'restored') { |
| 425 | + const message = restoreBody || 'Session restore did not report restored status.'; |
| 426 | + await this.markWakeDegraded(config, message); |
| 427 | + return { ok: false, message }; |
| 428 | + } |
| 429 | + |
| 430 | + const now = new Date().toISOString(); |
| 431 | + await db.update(schema.nodes).set({ |
| 432 | + status: 'running', |
| 433 | + healthStatus: 'healthy', |
| 434 | + errorMessage: null, |
| 435 | + updatedAt: now, |
| 436 | + }).where(eq(schema.nodes.id, config.nodeId)); |
| 437 | + await db.update(schema.workspaces).set({ |
| 438 | + status: 'running', |
| 439 | + errorMessage: null, |
| 440 | + updatedAt: now, |
| 441 | + }).where(eq(schema.workspaces.id, config.workspaceId)); |
| 442 | + await db.update(schema.agentSessions).set({ |
| 443 | + status: 'running', |
| 444 | + errorMessage: null, |
| 445 | + updatedAt: now, |
| 446 | + }).where(eq(schema.agentSessions.id, agentSession.id)); |
| 447 | + await this.ctx.storage.put('lifecycleStatus', 'running' satisfies LifecycleStatus); |
| 448 | + |
| 449 | + log.info('vm_agent_container_wake_completed', { |
| 450 | + nodeId: config.nodeId, |
| 451 | + workspaceId: config.workspaceId, |
| 452 | + chatSessionId: workspace.chatSessionId, |
| 453 | + agentSessionId: agentSession.id, |
| 454 | + }); |
| 455 | + return { ok: true }; |
| 456 | + } |
| 457 | + |
| 458 | + private async markWakeDegraded(config: VmAgentContainerLaunchConfig, message: string): Promise<void> { |
| 459 | + const now = new Date().toISOString(); |
| 460 | + const db = drizzle(this.env.DATABASE, { schema }); |
| 461 | + await db.update(schema.workspaces).set({ |
| 462 | + status: 'recovery', |
| 463 | + errorMessage: message, |
| 464 | + updatedAt: now, |
| 465 | + }).where(eq(schema.workspaces.id, config.workspaceId)); |
| 466 | + await db.update(schema.agentSessions).set({ |
| 467 | + status: 'error', |
| 468 | + errorMessage: message, |
| 469 | + updatedAt: now, |
| 470 | + }).where(eq(schema.agentSessions.workspaceId, config.workspaceId)); |
| 471 | + log.warn('vm_agent_container_wake_degraded', { |
| 472 | + nodeId: config.nodeId, |
| 473 | + workspaceId: config.workspaceId, |
| 474 | + message, |
| 475 | + }); |
| 476 | + } |
| 477 | + |
302 | 478 | private async replaceKeepaliveSchedule(delayMs: number): Promise<void> { |
303 | 479 | await this.clearKeepaliveSchedule(); |
304 | 480 | await this.schedule(Math.max(1, Math.ceil(delayMs / 1000)), KEEPALIVE_CALLBACK); |
|
0 commit comments