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
11 changes: 10 additions & 1 deletion .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,16 @@ data-doop-webfonts>` for the roster families the frame names and does not load i
gate every frame writer shares and throws `FrameDeletedError` (REST 410). Restore routes: `POST /api/frames/:id/restore`,
`POST /api/canvases/:id/pages/:pageId/restore` (brings the page's deleted frames), `GET /api/canvases/:id/trash`; MCP `restore_frame`, `restore_page`. `archive_frames` moves
frames to the per-canvas `Archive` page (`ARCHIVE_PAGE_ID`, always last) and hides them. Nothing in this
slice hard-deletes a frame, page or version row (`tests/frameTrashPersist.test.ts` scans for it).
slice hard-deletes a frame, page or version row except the one purge route (`tests/frameTrashPersist.test.ts` scans for it).
"Delete forever" (CHE-9399): `POST /api/frames/:id/purge` with `{deletedAt}` (REST only: no MCP tool or resident
path reaches it; agent keys get 401). Guards, in order: the frame is in the Trash (404/409 `not_in_trash`), an editor
(403), `deletedAt` is the Trash's (409 `stale_confirmation`), not a component main frame (409 `component_main`),
no comment on it (409 `has_comments`, memory and the database), no other purge open (409 `purge_in_progress`).
A frame with any comment is refused, never purged; lifting that refusal is CHE-9450. The transaction
(`server/db/purge.ts`, run by `server/framePurge.ts`) waits for the frame's writers (503 `purge_timeout`), removes the
frame, versions, write keys and asset refs, and keeps comments, snapshots, activity and the rest. A lost COMMIT
reply keeps the frame held in the Trash until the probe answers (503 `purge_outcome_unknown`, or 409
`purge_not_applied` when it did not happen). Every refusal and timeout leaves all rows.
- Page snapshots (CHE-5307, `server/pageSnapshots.ts`, `actions.createPageSnapshot` and friends): a named,
pinned copy of a whole page. `page_snapshots` holds name, page, author, time and each frame's state
(name, position, size, hidden, deleted, html hash); the html lives once per canvas in `snapshot_blobs`
Expand Down
148 changes: 148 additions & 0 deletions server/framePurge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { finishCommitted } from './actions.ts'
import * as persist from './db/persist.ts'
import { purgeTrashedFrame, resolvePurgeOutcome, type ProbeOptions, type PurgeReceipt } from './db/purge.ts'
import type { Actor } from '../shared/types.ts'
import type { PurgeLease } from './store.ts'

/**
* Steps 8 to 10 of "delete forever" (CHE-9399 step 4): once the route holds a lease on a Trash frame, settle the
* frame's writers, run the purge transaction and end the lease on a KNOWN outcome only. This file is the only
* caller of `purgeTrashedFrame` and `resolvePurgeOutcome`; no MCP tool or resident path reaches it.
*
* The route's request is a write boundary that undoes the lease when the handler throws, so nothing here throws:
* every path returns a reply. An outcome that is not known keeps the lease (the frame stays held in the Trash) and
* a probe, owned by the lease, ends it later.
*/

/** Knobs a test turns down; the defaults are the plan's (30 s settle, 10 s wait for the probe). */
export const purgeTiming: { settleTimeoutMs: number; outcomeWaitMs: number; probe: ProbeOptions } = {
settleTimeoutMs: 30_000,
outcomeWaitMs: 10_000,
probe: {},
}

export type PurgeReply = { status: 200 | 403 | 409 | 500 | 503; body: Record<string, unknown> }

export type PurgeRun = {
lease: PurgeLease
/** the `deletedAt` the caller confirmed */
deletedAt: number
/** the frame's current `deletedAt` in the Trash, for a stale answer */
currentDeletedAt: () => number | undefined
/** called inside the transaction right before COMMIT: may this caller still purge, and is the frame still free of comments */
stillMayPurge: () => boolean | 'has_comments'
/** credited with the activity line when the purge is finished */
actor: Actor
}

type NoReceipt = PurgeReceipt & { noReceipt: true }

export async function runFramePurge(run: PurgeRun): Promise<PurgeReply> {
const { lease, deletedAt, actor } = run
try {
await persist.settleFrameWrites(lease.frameId, { timeoutMs: purgeTiming.settleTimeoutMs })
} catch (error) {
lease.release()
if (error instanceof persist.SettleTimeout) {
return {
status: 503,
body: { error: 'frame writes are still in flight; nothing was deleted', code: 'purge_timeout' },
}
}
console.error('[purge] settle failed', lease.frameId, error)
return { status: 500, body: { error: 'purge failed; nothing was deleted' } }
}

let result: Awaited<ReturnType<typeof purgeTrashedFrame>>
try {
result = await purgeTrashedFrame({
frameId: lease.frameId,
canvasId: lease.canvasId,
deletedAt,
stillMayPurge: run.stillMayPurge,
onCommitRequested: (receipt) => {
lease.receipt = receipt
},
})
} catch (error) {
result = { outcome: 'unknown', error }
}

if (result.outcome === 'committed') {
finishCommitted(lease, result.receipt, actor)
return { status: 200, body: { ok: true } }
}
if (result.outcome === 'refused') {
lease.release()
if (result.reason === 'access_lost')
return {
status: 403,
body: { error: 'you can no longer edit this canvas; nothing was deleted', code: 'access_lost' },
}
if (result.reason === 'has_comments')
return { status: 409, body: { error: 'the frame has comments; nothing was deleted', code: 'has_comments' } }
return {
status: 409,
body: {
error: 'the frame changed; nothing was deleted',
code: 'stale_confirmation',
deletedAt: run.currentDeletedAt(),
},
}
}
return resolveUnknown(run, result.error)
}

/** The COMMIT reply is lost: keep the lease and ask the database what happened. */
async function resolveUnknown(run: PurgeRun, error: unknown): Promise<PurgeReply> {
const { lease, deletedAt, actor } = run
console.error('[purge] outcome unknown, probing', lease.frameId, error)
const probe = resolvePurgeOutcome(lease.frameId, purgeTiming.probe).then(
(answer) => {
try {
if (answer === 'committed') {
console.error('[purge] ALARM: the acknowledgement was lost but the purge committed', lease.frameId)
const receipt: PurgeReceipt | NoReceipt = lease.receipt ?? {
frameId: lease.frameId,
canvasId: lease.canvasId,
deletedAt,
versionIds: [],
writeKeyIds: [],
assetRefIds: [],
noReceipt: true,
}
finishCommitted(lease, receipt, actor)
} else {
lease.release()
}
} catch (finishError) {
console.error('[purge] could not end the lease after the probe', lease.frameId, finishError)
}
return answer
},
(probeError) => {
/* the probe never rejects (it retries); keep the lease if it somehow does */
console.error('[purge] probe failed', lease.frameId, probeError)
return 'unknown' as const
},
)
let timer: NodeJS.Timeout | undefined
const waited = new Promise<'timeout'>((resolve) => {
timer = setTimeout(() => resolve('timeout'), purgeTiming.outcomeWaitMs)
})
const answer = await Promise.race([probe, waited])
clearTimeout(timer)
if (answer === 'committed') return { status: 200, body: { ok: true } }
if (answer === 'rolled_back')
return {
status: 409,
body: { error: 'the purge did not happen; the frame is still in the Trash', code: 'purge_not_applied' },
}
return {
status: 503,
body: {
error: 'the purge is still being confirmed; the frame stays in the Trash until it is',
code: 'purge_outcome_unknown',
},
}
}
55 changes: 54 additions & 1 deletion server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,14 @@ import {
NoOpenPageError,
PageLimitError,
PurgeInProgressError,
PurgeRefusedError,
store,
} from './store.ts'
import { parseGuide } from '../shared/guides.ts'
import { getImage } from './previews.ts'
import { LayerNotFoundError, layerRefFromQuery, layerSelector } from './layerExport.ts'
import * as actions from './actions.ts'
import { runFramePurge, type PurgeReply } from './framePurge.ts'
import { captureFeature, captureTokenResults } from './featureEvents.ts'
import { liveActivitiesRouter, logLiveActivityRequests, startLiveActivityDelivery } from './liveActivities.ts'
import { onCanvasEvent } from './events.ts'
Expand Down Expand Up @@ -139,7 +141,7 @@ import { getAsset, reconcileAssetRefs, beginTicketUpload, endTicketUpload, creat
import * as ingest from './ingest.ts'
import { configurePins, loadPins } from './framePins.ts'
import { startPinReconcile } from './pinReconcile.ts'
import { PolicyRefused, setLockOwners } from './writePolicy.ts'
import { PolicyRefused, setLockOwners, writeContextFor } from './writePolicy.ts'
import { PageFinishedError } from './pageState.ts'
import * as agentKeys from './agentKeys.ts'
import * as backgrounds from './backgrounds.ts'
Expand Down Expand Up @@ -3173,6 +3175,57 @@ app.post('/api/frames/:id/restore', async (req, res) => {
}
})

/* "Delete forever" for one Trash frame (CHE-9399 step 4). REST only: the confirmation is a person's, so no MCP tool
and no resident path reaches it. The body is the `deletedAt` the person saw in the Trash. Every refusal and
timeout leaves every row; an outcome the database has not confirmed keeps the frame held in the Trash. */
app.post('/api/frames/:id/purge', async (req, res) => {
const id = req.params.id
const frame = store.getDeletedFrame(id)
const canvas = store.getCanvas((frame ?? store.getFrame(id))?.canvasId ?? '')
if (!canvas) return res.status(404).json({ error: 'frame not found' })
if (!checkRole(req, res, canvas, 'edit')) return // a live frame's existence is shown to an editor only
if (!frame) return res.status(409).json({ error: 'the frame is not in the Trash', code: 'not_in_trash' })
const deletedAt: unknown = req.body?.deletedAt
if (typeof deletedAt !== 'number' || !Number.isFinite(deletedAt))
return res.status(400).json({ error: 'deletedAt (the number the Trash shows) is required' })
if (frame.deletedAt !== deletedAt)
return res
.status(409)
.json({ error: 'the frame changed since you confirmed', code: 'stale_confirmation', deletedAt: frame.deletedAt })
const canvasId = frame.canvasId
let reply: PurgeReply
try {
await store.load(canvasId) // a trashed frame's canvas is not loaded by the frame routes
const actor = userActor(req)
const hasComments = () => actions.commentsOnFrame(canvasId, id)
if (hasComments()) return res.status(409).json({ error: 'the frame has comments', code: 'has_comments' })
const userId = req.user!.id
/* from here the lease is held and nothing below may throw: an unknown outcome must keep it */
const lease = store.beginPurge(writeContextFor(actor, userId), id, deletedAt, hasComments, (event) =>
broadcast(canvasId, event),
)
reply = await runFramePurge({
lease,
deletedAt,
actor,
currentDeletedAt: () => store.getDeletedFrame(id)?.deletedAt,
stillMayPurge: () => {
const now = store.getCanvas(canvasId)
const role = now ? canvasRole(userId, now) : null
if (!role || !roleAllows(role, 'edit')) return false
return hasComments() ? 'has_comments' : true
},
})
} catch (e) {
if (e instanceof PurgeRefusedError) {
const stale = e.code === 'stale_confirmation' ? { deletedAt: store.getDeletedFrame(id)?.deletedAt } : {}
return res.status(409).json({ error: e.message, code: e.code, ...stale })
}
return frameWriteFailed(res, e)
}
res.status(reply.status).json(reply.body)
})

/* Archive: both paths write the frame's origin in the same store call. A repeat of the same request
changes nothing, so a client whose reply was lost can send it again. */
app.post('/api/canvases/:id/frames/archive', (req, res) => {
Expand Down
Loading
Loading