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
28 changes: 28 additions & 0 deletions apps/ccv2/docs/scenarios.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,31 @@ deployments retain their snapshot. Updating a scenario resets only fault-call
counters. Resetting a run removes simulation resources and counters and restores
the default scenario while retaining its credentials, expiration, and security
boundary.

## Cleanup fixtures (candidate integration)

`PUT /sandbox/v1/runs/{runId}/cleanup-fixture` requires the run-control bearer.
It replaces only that run's builds/deployments (150/30 record limits), clears
operation counters, and accepts optional `changes` and `loseDeleteResponse`
simulation controls. The normal 64 KiB request limit still applies. A fixture's
`response` is the vendor-shaped record; intentionally malformed records are
supported so clients can test fail-closed validation.

`modifiedAt` is internal fixture metadata. When supplied, deletion rejects builds
modified within four hours. It is never returned by SAP-shaped build reads and
is not evidence that SAP exposes a build modification timestamp or enforces this
precondition at its API.

Changes specify `operationId` (`getBuilds`, `getBuild`, `deleteBuild`), `onCall`,
`buildCode`, and either `patch` or `remove`. Call counters are per operation and
resource, making races deterministic. `loseDeleteResponse` models acceptance
followed by a 500 response; the build remains stored with status `DELETED`,
representing deletion initiation rather than physical disappearance.

The existing state endpoint's `faultCounters` now counts all target operations
(and token issuance), even when no fault is configured. Keys such as
`deleteBuild:build-1` count attempted target mutations independently of control
fixture operations; do not count run teardown or fixture PUT as SAP mutations.

Always delete the isolated run in a `finally` block. Hosted runs require explicit
configuration; these controls do not grant permission for production SAP writes.
71 changes: 71 additions & 0 deletions apps/ccv2/openapi/sandbox-control.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,29 @@ paths:
"400": { $ref: "#/components/responses/ControlError" },
default: { $ref: "#/components/responses/ControlError" },
}
/sandbox/v1/runs/{runId}/cleanup-fixture:
parameters: [{ $ref: "#/components/parameters/RunId" }]
put:
operationId: seedCleanupFixture
security: [{ RunControl: [] }]
description: Replace isolated build/deployment inventory and install cleanup-only simulation controls. No SAP DTO extension.
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/CleanupFixture" }
responses:
"200":
description: Fixture installed
content:
application/json:
schema:
type: object
required: [builds, deployments]
properties:
builds: { type: integer, minimum: 0 }
deployments: { type: integer, minimum: 0 }
default: { $ref: "#/components/responses/ControlError" }
/sandbox/v1/runs/{runId}/state:
parameters: [{ $ref: "#/components/parameters/RunId" }]
get:
Expand Down Expand Up @@ -327,3 +350,51 @@ components:
type: object
required: [code, message]
properties: { code: { type: string }, message: { type: string } }
CleanupFixture:
type: object
additionalProperties: false
required: [builds]
properties:
builds:
type: array
maxItems: 150
items:
type: object
additionalProperties: false
required: [code, response]
properties:
code: { type: string, pattern: "^[A-Za-z0-9_-]{1,100}$" }
response: { type: object, additionalProperties: true }
modifiedAt:
{
type: string,
format: date-time,
description: Internal simulation metadata; never returned by SAP-shaped reads.,
}
deployments:
type: array
maxItems: 30
items:
type: object
additionalProperties: false
required: [code, response]
properties:
code: { type: string, pattern: "^[A-Za-z0-9_-]{1,100}$" }
response: { type: object, additionalProperties: true }
changes:
type: array
maxItems: 20
items:
type: object
additionalProperties: false
required: [operationId, onCall, buildCode]
properties:
operationId: { type: string, enum: [getBuilds, getBuild, deleteBuild] }
onCall: { type: integer, minimum: 1, maximum: 1000 }
buildCode: { type: string, pattern: "^[A-Za-z0-9_-]{1,100}$" }
patch: { type: object, additionalProperties: true }
remove: { type: boolean }
loseDeleteResponse:
type: array
maxItems: 20
items: { type: string, pattern: "^[A-Za-z0-9_-]{1,100}$" }
4 changes: 2 additions & 2 deletions apps/ccv2/scripts/validate-openapi.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,8 @@ const sandboxOperations = Object.entries(sandboxDocument.paths).flatMap(([route,
)
.map(([method, operation]) => ({ method, operationId: operation.operationId, route })),
);
if (sandboxOperations.length !== 10) {
throw new Error(`Expected 10 sandbox operations, found ${String(sandboxOperations.length)}`);
if (sandboxOperations.length !== 11) {
throw new Error(`Expected 11 sandbox operations, found ${String(sandboxOperations.length)}`);
}
const invalidSandboxRoute = sandboxOperations.find(
({ route }) =>
Expand Down
43 changes: 43 additions & 0 deletions apps/ccv2/src/domain/cleanup-fixture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { z } from "zod";

const code = z.string().regex(/^[A-Za-z0-9_-]{1,100}$/);
const build = z
.object({
code,
response: z.record(z.string(), z.unknown()),
modifiedAt: z.iso.datetime().optional(),
})
.strict();
const deployment = z.object({ code, response: z.record(z.string(), z.unknown()) }).strict();

/** Simulation controls never appear in SAP response DTOs. */
export const cleanupFixtureSchema = z
.object({
builds: z.array(build).max(150),
deployments: z.array(deployment).max(30).default([]),
changes: z
.array(
z
.object({
operationId: z.enum(["getBuilds", "getBuild", "deleteBuild"]),
onCall: z.number().int().min(1).max(1000),
buildCode: code,
patch: z.record(z.string(), z.unknown()).optional(),
remove: z.boolean().optional(),
})
.strict(),
)
.max(20)
.default([]),
loseDeleteResponse: z.array(code).max(20).default([]),
})
.strict()
.superRefine((value, context) => {
for (const name of ["builds", "deployments"] as const) {
if (new Set(value[name].map((item) => item.code)).size !== value[name].length) {
context.addIssue({ code: "custom", path: [name], message: "Fixture keys must be unique." });
}
}
});

export type CleanupFixture = z.infer<typeof cleanupFixtureSchema>;
150 changes: 147 additions & 3 deletions apps/ccv2/src/durable-objects/ccv2-run.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { DurableObject } from "cloudflare:workers";

import type { CleanupFixture } from "../domain/cleanup-fixture";
import { timingSafeTextEqual } from "../auth/crypto";
import type {
BuildDetail,
Expand Down Expand Up @@ -32,6 +33,11 @@ import { DEFAULT_SCENARIO, type Scenario } from "../domain/scenario";
const SCHEMA_VERSION = 3;
const MAX_EVENTS = 200;

// Control-plane fixtures can deliberately omit flags despite the production DTO type.
function explicitlyFalse(value: unknown): boolean {
return value === false;
}

export interface RunMetadata {
runId: string;
createdAt: string;
Expand Down Expand Up @@ -507,12 +513,40 @@ export class Ccv2Run extends DurableObject<CloudflareBindings> {
const row = this.buildRow(subscriptionCode, buildCode);
if (!row) return this.failure(404, "build_not_found", "The build was not found.");
const detail = this.buildDetail(row);
if (detail.status === "SCHEDULED" || detail.status === "BUILDING") {
if (detail.status !== "SUCCESS" && detail.status !== "FAIL") {
return this.failure(409, "build_in_progress", "A build in progress cannot be deleted.");
}
if (detail.deployed) {
if (!explicitlyFalse(detail.deployed)) {
return this.failure(409, "build_in_use", "A deployed build cannot be deleted.");
}
if (!explicitlyFalse(detail.hasSnapshot))
return this.failure(409, "build_has_snapshot", "A build with a snapshot cannot be deleted.");
if (
this.deploymentRows(subscriptionCode).some((deployment) => {
const reference = this.deploymentDetail(deployment);
return (
reference.buildCode === buildCode &&
["SCHEDULED", "DEPLOYING", "DEPLOYED"].includes(reference.status)
);
})
)
return this.failure(
409,
"build_deployment_reference",
"The build is referenced by an operational deployment.",
);
const modification = this.ctx.storage.sql
.exec<ResourceRow>(
"SELECT code, state_json, created_at FROM resources WHERE kind = 'cleanup-modification' AND code = ?",
buildCode,
)
.toArray()[0];
if (modification) {
const { modifiedAt } = JSON.parse(modification.state_json) as { modifiedAt: string };
if (Date.now() - Date.parse(modifiedAt) <= 4 * 60 * 60 * 1000)
return this.failure(409, "build_recently_modified", "The build was recently modified.");
}
// A DELETED record remains observable: the deletion request has been initiated.
detail.status = "DELETED";
this.ctx.storage.sql.exec(
"UPDATE builds SET state_json = ? WHERE code = ?",
Expand Down Expand Up @@ -1384,14 +1418,123 @@ export class Ccv2Run extends DurableObject<CloudflareBindings> {
return { ok: true, value: null };
}

async seedCleanupFixture(
controlTokenHash: string,
fixture: CleanupFixture,
): Promise<RunResult<{ builds: number; deployments: number }>> {
const authorization = await this.authorizeControl(controlTokenHash);
if (!authorization.ok) return authorization;
this.ctx.storage.transactionSync(() => {
this.ctx.storage.sql.exec("DELETE FROM builds");
this.ctx.storage.sql.exec("DELETE FROM deployments");
this.ctx.storage.sql.exec("DELETE FROM operation_counters");
this.ctx.storage.sql.exec("DELETE FROM resources WHERE kind LIKE 'cleanup-%'");
for (const item of fixture.builds) {
const timestamp =
typeof item.response.buildStartTimestamp === "string"
? item.response.buildStartTimestamp
: "2000-01-01T00:00:00.000Z";
this.ctx.storage.sql.exec(
"INSERT INTO builds (code, subscription_code, state_json, scenario_json, poll_count, created_at) VALUES (?, ?, ?, ?, 0, ?)",
item.code,
SUBSCRIPTION_CODE,
JSON.stringify(item.response),
JSON.stringify(DEFAULT_SCENARIO.build),
timestamp,
);
if (item.modifiedAt)
this.ctx.storage.sql.exec(
"INSERT INTO resources (kind, subscription_code, code, state_json, created_at) VALUES ('cleanup-modification', ?, ?, ?, ?)",
SUBSCRIPTION_CODE,
item.code,
JSON.stringify({ modifiedAt: item.modifiedAt }),
timestamp,
);
}
for (const item of fixture.deployments) {
const detail = item.response;
this.ctx.storage.sql.exec(
"INSERT INTO deployments (code, subscription_code, environment_code, build_code, state_json, scenario_json, poll_count, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)",
item.code,
SUBSCRIPTION_CODE,
typeof detail.environmentCode === "string" ? detail.environmentCode : "d1",
typeof detail.buildCode === "string" ? detail.buildCode : "",
JSON.stringify(detail),
JSON.stringify(DEFAULT_SCENARIO.deployment),
typeof detail.createdTimestamp === "string"
? detail.createdTimestamp
: "2000-01-01T00:00:00.000Z",
);
}
this.ctx.storage.sql.exec(
"INSERT INTO resources (kind, subscription_code, code, state_json, created_at) VALUES ('cleanup-controls', ?, 'controls', ?, ?)",
SUBSCRIPTION_CODE,
JSON.stringify({
changes: fixture.changes,
loseDeleteResponse: fixture.loseDeleteResponse,
}),
new Date().toISOString(),
);
});
return {
ok: true,
value: { builds: fixture.builds.length, deployments: fixture.deployments.length },
};
}

consumeCleanupDeleteResponseFault(buildCode: string): boolean {
const row = this.ctx.storage.sql
.exec<ResourceRow>(
"SELECT code, state_json, created_at FROM resources WHERE kind = 'cleanup-controls'",
)
.toArray()[0];
if (!row) return false;
const controls = JSON.parse(row.state_json) as Pick<
CleanupFixture,
"changes" | "loseDeleteResponse"
>;
return controls.loseDeleteResponse.includes(buildCode);
}

private applyCleanupChanges(operationId: string, resourceIdentifier: string, call: number): void {
const row = this.ctx.storage.sql
.exec<ResourceRow>(
"SELECT code, state_json, created_at FROM resources WHERE kind = 'cleanup-controls'",
)
.toArray()[0];
if (!row) return;
const controls = JSON.parse(row.state_json) as Pick<
CleanupFixture,
"changes" | "loseDeleteResponse"
>;
for (const change of controls.changes) {
if (
change.operationId !== operationId ||
change.onCall !== call ||
(operationId !== "getBuilds" && change.buildCode !== resourceIdentifier)
)
continue;
if (change.remove) {
this.ctx.storage.sql.exec("DELETE FROM builds WHERE code = ?", change.buildCode);
} else {
const build = this.buildRow(SUBSCRIPTION_CODE, change.buildCode);
if (build)
this.ctx.storage.sql.exec(
"UPDATE builds SET state_json = ? WHERE code = ?",
JSON.stringify({ ...this.buildDetail(build), ...change.patch }),
change.buildCode,
);
}
}
}

consumeFault(operationId: string, resourceIdentifier = ""): OperationFault | null {
const current = this.scenario();
const applicable = current.faults.filter(
(fault) =>
fault.operationId === operationId &&
(fault.resourceIdentifier === undefined || fault.resourceIdentifier === resourceIdentifier),
);
if (applicable.length === 0) return null;
this.ctx.storage.sql.exec(
`INSERT INTO operation_counters (operation_id, resource_id, call_count) VALUES (?, ?, 1)
ON CONFLICT(operation_id, resource_id) DO UPDATE SET call_count = call_count + 1`,
Expand All @@ -1405,6 +1548,7 @@ export class Ccv2Run extends DurableObject<CloudflareBindings> {
resourceIdentifier,
)
.one().count;
this.applyCleanupChanges(operationId, resourceIdentifier, call);
const fault = applicable.find((candidate) => candidate.onCalls.includes(call));
if (!fault) return null;
this.recordEvent("scenario.fault", operationId, resourceIdentifier, fault.status, { call });
Expand Down
12 changes: 12 additions & 0 deletions apps/ccv2/src/routes/builds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ buildRoutes.delete("/v2/subscriptions/:subscriptionCode/builds/:buildCode", asyn
context.req.param("subscriptionCode"),
context.req.param("buildCode"),
);
if (
result.ok &&
(await context.env.CCV2_RUN.getByName(context.get("runId")).consumeCleanupDeleteResponseFault(
context.req.param("buildCode"),
))
) {
return vendorProblem(
500,
"Simulated response loss",
"Deletion accepted before simulated response loss.",
);
}
return result.ok
? new Response(null, { status: 204, headers: { "Cache-Control": "no-store" } })
: vendorError(result);
Expand Down
Loading
Loading