@tangle-network/agent-app 0.60.60 → 0.60.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -468,6 +468,85 @@ WHERE key = ?1 AND expires_at = ?2`;
468
468
  };
469
469
  }
470
470
 
471
+ // src/sandbox/prewarm-route.ts
472
+ var AUTOMATED_AGENT = /bot\b|crawler|spider|slurp|facebookexternalhit|embedly|preview|whatsapp|curl\/|wget\/|python-requests|go-http-client/i;
473
+ function isAutomatedPrewarmRequest(request) {
474
+ const purpose = `${request.headers.get("sec-purpose") ?? ""} ${request.headers.get("purpose") ?? ""}`;
475
+ if (/prefetch|prerender/i.test(purpose)) return true;
476
+ return AUTOMATED_AGENT.test(request.headers.get("user-agent") ?? "");
477
+ }
478
+ var RECENT_LIMIT = 1e3;
479
+ function reply(body, status = 200) {
480
+ return Response.json(body, { status, headers: { "Cache-Control": "private, no-store" } });
481
+ }
482
+ function createWorkspacePrewarmRoute(options) {
483
+ const recentMs = options.recentMs ?? 3e4;
484
+ const now = options.now ?? (() => Date.now());
485
+ const inFlight = /* @__PURE__ */ new Map();
486
+ const recent = /* @__PURE__ */ new Map();
487
+ const emit = (event) => {
488
+ try {
489
+ options.onEvent?.(event);
490
+ } catch {
491
+ }
492
+ };
493
+ const remember = (key, at) => {
494
+ recent.delete(key);
495
+ recent.set(key, at);
496
+ for (const old of recent.keys()) {
497
+ if (recent.size <= RECENT_LIMIT) break;
498
+ recent.delete(old);
499
+ }
500
+ };
501
+ async function run(key, warm) {
502
+ const started = now();
503
+ try {
504
+ const report = await warm() ?? void 0;
505
+ const ms = now() - started;
506
+ remember(key, now());
507
+ emit({ type: "warmed", key, ms, ...report ? { report } : {} });
508
+ return { outcome: "warmed", ms, ...report ? { report } : {} };
509
+ } catch (err) {
510
+ const ms = now() - started;
511
+ emit({ type: "failed", key, ms, error: err instanceof Error ? err.message : String(err) });
512
+ return { outcome: "failed", ms };
513
+ }
514
+ }
515
+ return async function prewarm(request, context) {
516
+ const started = now();
517
+ if (request.method !== "POST") {
518
+ return new Response(null, { status: 405, headers: { Allow: "POST" } });
519
+ }
520
+ if (isAutomatedPrewarmRequest(request)) return reply({ outcome: "automated", ms: 0 });
521
+ let auth;
522
+ try {
523
+ auth = await options.authorize({ request, context });
524
+ } catch (err) {
525
+ emit({ type: "failed", key: "", ms: now() - started, error: err instanceof Error ? err.message : String(err) });
526
+ return reply({ outcome: "failed", ms: now() - started });
527
+ }
528
+ if (auth.status === "denied") return auth.response;
529
+ if (auth.status === "declined") return reply({ outcome: "declined", ms: now() - started, reason: auth.reason });
530
+ const { key } = auth;
531
+ const running = inFlight.get(key);
532
+ if (running) {
533
+ const result2 = await running;
534
+ return reply({ ...result2, outcome: result2.outcome === "warmed" ? "joined" : result2.outcome, ms: now() - started });
535
+ }
536
+ const warmedAt = recent.get(key);
537
+ if (warmedAt !== void 0 && now() - warmedAt < recentMs) {
538
+ return reply({ outcome: "recent", ms: now() - started });
539
+ }
540
+ const result = run(key, auth.warm);
541
+ inFlight.set(key, result);
542
+ try {
543
+ return reply({ ...await result, ms: now() - started });
544
+ } finally {
545
+ if (inFlight.get(key) === result) inFlight.delete(key);
546
+ }
547
+ };
548
+ }
549
+
471
550
  // src/sandbox/foreground-single-flight.ts
472
551
  var DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS = 180;
473
552
  var DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS = 5e3;
@@ -1654,14 +1733,15 @@ async function provisionWorkspaceSandbox(shell, options) {
1654
1733
  throw new Error("livenessProbe.execTimeoutMs must be an integer between 100 and 600000");
1655
1734
  }
1656
1735
  const { workspaceId, userId, harness, forceNew, onProgress, billingOwnerId } = options;
1657
- const resolved = await resolveWorkspaceSandboxClient(shell, workspaceId, userId);
1736
+ const measure = (stage, operation) => options.measure ? options.measure(`sandbox.ensure.${stage}`, operation) : operation();
1737
+ const resolved = await measure("credentials", () => resolveWorkspaceSandboxClient(shell, workspaceId, userId));
1658
1738
  const { scope, client } = resolved;
1659
1739
  let name = resolved.name;
1660
1740
  let recoveryRestore;
1661
1741
  let replacementRequested = false;
1662
1742
  const resources = shell.resources ?? DEFAULT_SANDBOX_RESOURCES;
1663
1743
  const resumeTimeout = shell.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS;
1664
- let existing = await listRunning(client, name);
1744
+ let existing = await measure("list_running", () => listRunning(client, name));
1665
1745
  if (forceNew && existing.succeeded && !existing.value) {
1666
1746
  existing = await listStopped(client, name);
1667
1747
  }
@@ -1674,11 +1754,17 @@ async function provisionWorkspaceSandbox(shell, options) {
1674
1754
  throw new Error(`forceNew: sandbox ${name} could not be deleted`, { cause: dropped.error });
1675
1755
  }
1676
1756
  } else if (found.metadata?.harness === harness) {
1677
- const runtimeEnv2 = await resolveWorkspaceRuntimeEnv(shell, scope);
1757
+ const [envResult, readyResult] = await Promise.allSettled([
1758
+ measure("runtime_env", () => resolveWorkspaceRuntimeEnv(shell, scope)),
1759
+ measure("refresh", () => refreshRuntimeConnection(client, found))
1760
+ ]);
1761
+ if (envResult.status === "rejected") throw envResult.reason;
1762
+ const runtimeEnv2 = envResult.value;
1678
1763
  try {
1679
- const ready = await refreshRuntimeConnection(client, found);
1680
- if ((await isReusableBox(ready, shell.livenessProbe)).succeeded) {
1681
- return await finalizeExistingBox(shell, client, ready, "reused", name, workspaceId, userId, harness, scope, runtimeEnv2);
1764
+ if (readyResult.status === "rejected") throw readyResult.reason;
1765
+ const ready = readyResult.value;
1766
+ if ((await measure("liveness", () => isReusableBox(ready, shell.livenessProbe))).succeeded) {
1767
+ return await measure("finalize", () => finalizeExistingBox(shell, client, ready, "reused", name, workspaceId, userId, harness, scope, runtimeEnv2));
1682
1768
  }
1683
1769
  const recovered = await recoverUnresponsiveBox(
1684
1770
  client,
@@ -2455,6 +2541,8 @@ export {
2455
2541
  DEFAULT_PREWARM_CLAIM_TABLE,
2456
2542
  PREWARM_CLAIM_TABLE_DDL,
2457
2543
  createD1PrewarmClaimStore,
2544
+ isAutomatedPrewarmRequest,
2545
+ createWorkspacePrewarmRoute,
2458
2546
  DEFAULT_FOREGROUND_PROVISION_CLAIM_TTL_SECONDS,
2459
2547
  DEFAULT_FOREGROUND_PROVISION_POLL_INTERVAL_MS,
2460
2548
  SandboxProvisioningFailedElsewhereError,
@@ -2513,4 +2601,4 @@ export {
2513
2601
  isTerminalPromptEvent,
2514
2602
  detectInteractiveQuestion
2515
2603
  };
2516
- //# sourceMappingURL=chunk-WMCROSA4.js.map
2604
+ //# sourceMappingURL=chunk-7DG6GGRN.js.map