Skip to content

feat: add active cdn purge on file changes to support smart cdn v2 - #1772

Open
itslenny wants to merge 1 commit into
masterfrom
lenny/active-cdn-cache-purge
Open

itslenny wants to merge 1 commit into
masterfrom
lenny/active-cdn-cache-purge

Conversation

@itslenny

@itslenny itslenny commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Feature

What is the current behavior?

  • Storage sends a webhook on every object create, update, delete, move, and promotion
  • That webhook is the only signal the CDN layer has that something changed
  • No explicit purge events are sent on object modifications
  • There is no way disable webhooks

What is the new behavior?

  • Storage can now also purge the CDN cache directly for objects affected by a write, overwrite, delete, move, or promotion.
  • This runs alongside the existing webhook, not instead of it. A purge only fires when the change could leave stale cached bytes behind. A new object at a brand new path does not trigger a purge, since nothing was cached there yet.
  • Webhooks can now be disabled with a flag. They stay on by default so there is no breaking change to the default behavior.
  • Supports purging individual object version (depends on cdn-cache-manager deploy first)

Together, this lets a project move from the old webhook-driven cache (Smart CDN V1) to the new active-purge cache (Smart CDN V2) without a hard cutover. Both behaviors run side by side during the migration. Once every project is on V2, webhooks can be turned off.

If no purge endpoint is configured, the purge step does nothing, so this has no effect without that extra configuration.

@itslenny
itslenny requested a review from a team as a code owner November 28, 2026 00:09
@blacksmith-sh

This comment has been minimized.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Smart CDN V2 tenants can keep serving stale bytes when an object changes again while an earlier purge for the same key is still in flight. The purgeCdnCache queue uses pg-boss policy exclusive (registry.ts:238), keyed by type/tenant/bucket/objectName. That policy silently drops a new job while one with the same key is queued or active. Fix: keep each per-object purge sent after a commit from being dropped by a purge already in flight, e.g. use a non-dropping policy for this queue (or a key that is unique per write) and accept duplicate purges as cheap.

Why this was flagged

Overwrite write1 commits and notify enqueues purge P1 with the key object/<tenant>/<bucket>/<name>. While P1 is active in cdnCacheManager.purge (up to the 10s abort budget), a second upsert or a delete of the same object commits and sends P2. pg-boss exclusive (registry.ts:238, options.ts:14-15) skips P2 silently because P1 holds the key. If P1 reaches the edge before write2 commits, a read in that gap caches write1's bytes, and no later purge ever clears them. The new comment at purge-cdn-cache.ts:51-52 says V2 has no other invalidation signal. On the base branch, object writes did not depend on this queue: V1 invalidation went through webhooks, which do not have this policy. The idempotency key was built for v1 manual or bucket purges, where dropping a duplicate was harmless.

Verification: run-migrations.ts:194 confirms that "v12's exclusive unique index spans created..active". So an enqueue is dropped while the earlier job is active, not only while it is queued. This change routes per-object writes into that queue. Before it, the only producer was the manual admin purge at storage.ts:325. V2 tenants then serve stale content until the edge TTL runs out.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Beyond the inline findings, I checked whether billing/audit logging could be lost now that logLifecycleEvent has moved out of sendWebhook. It isn't lost. Outside tests, the only callers of sendWebhook/sendWebhookBatch are the new notify/notifyBatch in lifecycle-events.ts, and both log before sending. The lifecycle executor already calls logLifecycleEvent directly.

Extended reasoning...

Searching src showed that outside tests, the only callers of the class-level sendWebhook/sendWebhookBatch are notify/notifyBatch (lifecycle-events.ts:57 and :72). Both call logLifecycleEvent before sending, so turning off webhooks does not stop audit logging.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Comment thread src/storage/object.ts Outdated
},
committedAt
committedAt,
{ purgeCache: Boolean(replaced) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Copying over an existing object in a versioning ENABLED or SUSPENDED bucket never purges the CDN. Smart CDN V2 keeps serving the old bytes at the destination. purgeCache: Boolean(replaced) only sees rows overwritten in place. In versioned writes the old row is archived and a new row is inserted, so replacedContent returns undefined. Fix: purge whenever the copy replaced a current non-delete-marker object at the destination, as uploads do with isUpsert && !written.isNew. For example, return a flag from the transaction based on existingDestObject && !existingDestObject.is_delete_marker.

Why this was flagged

The trigger is copyObject with upsert onto an existing key in a bucket whose versioning status is ENABLED. writeCurrentVersion (src/storage/database/pg.ts:1512-1532) adds no ON CONFLICT clause for ENABLED. It archives the current row through archiveCurrentVersions and inserts a new row. So withReplacedRow (pg.ts:4105) finds no replaced_id, and replacedContent(destinationObject) at object.ts:1192 returns undefined. The notify call at object.ts:1219 then passes purgeCache: false, and no PurgeCdnCache job is queued for the destination. The current object at that path did change, so a V2 tenant (which has no webhook-driven invalidation) keeps getting the stale cached copy. SUSPENDED buckets whose current destination row is a versioned row behave the same way. Uploads do not have this gap, because uploader.ts:347 gates on isUpsert && !written.isNew rather than on replaced.

Verification: Trigger: a copy with upsert onto an existing current object in a bucket whose versioning is ENABLED, with Smart CDN V2 (purge) configured. The decisive line is object.ts:1219 { purgeCache: Boolean(replaced) }. The base branch had no purge at all, but this change ships the overwrite purge described in the PR, and on this path it never fires.

Comment on lines +56 to +79
export async function purgeObjectCache(object: PurgeableObject): Promise<void> {
try {
await PurgeCdnCache.send(toPurgeOptions(object))
} catch (error) {
logSchema.error(logger, 'Failed to purge object cache', {
type: 'cdn',
project: object.tenant.ref,
sbReqId: object.sbReqId,
error,
})
}
}

export async function purgeObjectCacheBatch(
objects: readonly PurgeableObject[],
options?: { readonly signal?: AbortSignal }
): Promise<void> {
if (objects.length === 0) return
try {
const payloads = objects.map(toPurgeOptions)
await PurgeCdnCache.batchSend(payloads, options)
} catch (error) {
for (const object of objects) {
logSchema.error(logger, 'Failed to purge object cache', {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 (optional) Deployments with no CDN purge endpoint now get a queue job for every delete, overwrite, move and promotion. Each job does nothing when it runs. purgeObjectCache and purgeObjectCacheBatch call PurgeCdnCache.send/batchSend without checking whether a purge URL is configured. Only the handler checks, at purge-cdn-cache.ts:100, after the job is already in the queue. Fix: check cdnCacheManager.isConfigured() before sending in both helpers, so nothing is queued when CDN_PURGE_ENDPOINT_URL is unset. Existing tests that spy on the send will need that config set.

Why this was flagged

The trigger is any deployment without CDN_PURGE_ENDPOINT_URL, which by the PR's own account is the default. In that setup every delete (object.ts:516), bulk delete (object.ts:918), promotion, overwriting copy or move, upsert overwrite (uploader.ts:366) and admin delete-all-before page (object-admin-delete-all-before.ts:90) now calls PurgeCdnCache.send/batchSend through notify/notifyBatch. That inserts a pg-boss row or SQS message on every call. The no-op check only happens in PurgeCdnCacheHandler.handle (purge-cdn-cache.ts:100), after the insert and dequeue have already been paid for. On the base branch these write paths never touched the purgeCdnCache queue. The PR description says the purge step "does nothing" when no endpoint is configured. In fact each such write adds a queue insert and a worker poll, and it also waits on that insert. The bucket-level purgeBucketCache in storage.ts:325 sends unconditionally too, but it runs only on bucket deletes, so it is far less frequent.

Verification: Trigger: a deployment with the queue enabled and no CDN_PURGE_ENDPOINT_URL set. In that setup every purge-eligible write now enqueues a job that does nothing when it runs. purgeObjectCache (purge-cdn-cache.ts:58) calls await PurgeCdnCache.send(toPurgeOptions(object)) with no config check. The only check is in the handler (purge-cdn-cache.ts:100), which runs after the job has been inserted and picked up.

*/
export async function purgeObjectCache(object: PurgeableObject): Promise<void> {
try {
await PurgeCdnCache.send(toPurgeOptions(object))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Severity: LOW

The purge queue is exclusive and keys jobs by tenant, bucket, and object, so a repeat send while the first job is queued or running is silently dropped. If another write or delete lands after the first purge but before its job settles, the second invalidation is lost and stale bytes can remain served.
Helpful? Add 👍 / 👎

💡 Fix Suggestion

Suggestion: The exclusive queue policy with a tenant/bucket/object idempotency key silently drops a second purge that arrives while the first job is queued or running. Change how purge jobs are deduplicated so a later write or delete still triggers a purge. Options: (1) switch the queue policy to one that allows one queued job plus one active job, such as pg-boss stately or short, so a new purge can queue behind the running one. (2) Add a time-bucket or version component, such as the object version or an updated-at timestamp, to the idempotency key. (3) Use a short singleton window so purges that arrive after the first job starts are not dropped. This needs changes to the queue registration in src/storage/events/registry.ts and to the idempotency key logic in the event class. It is not a fix at the send call on line 58.

@coveralls

coveralls commented Nov 28, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 46178288453

Coverage increased (+0.03%) to 88.714%

Details

  • Coverage increased (+0.03%) from the base build.
  • Patch coverage: 1 uncovered change across 1 file (62 of 63 lines covered, 98.41%).
  • No coverage regressions found.

Uncovered Changes

File Changed Covered %
src/http/routes/cdn/purgeCache.ts 8 7 87.5%
Total (11 files) 63 62 98.41%

Coverage Regressions

No coverage regressions found.


Coverage Stats

Coverage Status
Relevant Lines: 19327
Covered Lines: 17662
Line Coverage: 91.39%
Relevant Branches: 12200
Covered Branches: 10307
Branch Coverage: 84.48%
Branches in Coverage %: Yes
Coverage Strength: 1299.88 hits per line

💛 - Coveralls

@itslenny
itslenny force-pushed the lenny/active-cdn-cache-purge branch from 0d6e2b6 to a2d9cc3 Compare November 28, 2026 18:53

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants