Skip to content
Open
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
25 changes: 25 additions & 0 deletions src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,31 @@ describe('configuration parsing', () => {
})
})

describe('webhooksEnabled config parsing', () => {
test('defaults to enabled when unset, so existing self-hosted deployments keep working', async () => {
vi.stubEnv('WEBHOOKS_ENABLED', undefined)
vi.stubEnv('ENABLE_WEBHOOKS', undefined)
const { getConfig } = await import('./config')

expect(getConfig({ reload: true }).webhooksEnabled).toBe(true)
})

test('is disabled only by an explicit "false"', async () => {
vi.stubEnv('WEBHOOKS_ENABLED', 'false')
const { getConfig } = await import('./config')

expect(getConfig({ reload: true }).webhooksEnabled).toBe(false)
})

test('ENABLE_WEBHOOKS is an alias for WEBHOOKS_ENABLED', async () => {
vi.stubEnv('WEBHOOKS_ENABLED', undefined)
vi.stubEnv('ENABLE_WEBHOOKS', 'false')
const { getConfig } = await import('./config')

expect(getConfig({ reload: true }).webhooksEnabled).toBe(false)
})
})

describe('vectorS3Buckets config parsing', () => {
afterEach(() => {
vi.resetModules()
Expand Down
2 changes: 2 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ type StorageConfigType = {
queueStatsTtlMs: number
queueStatsCountCap: number
queuePollIdleIntervalMs: number
webhooksEnabled: boolean
webhookURL?: string
webhookApiKey?: string
webhookQueuePullInterval?: number
Expand Down Expand Up @@ -876,6 +877,7 @@ export function getConfig(options?: { reload?: boolean }): StorageConfigType {
),

// Webhooks
webhooksEnabled: getOptionalConfigFromEnv('WEBHOOKS_ENABLED', 'ENABLE_WEBHOOKS') !== 'false',
webhookURL: getOptionalConfigFromEnv('WEBHOOK_URL'),
webhookApiKey: getOptionalConfigFromEnv('WEBHOOK_API_KEY'),
webhookQueuePullInterval: parseInt(
Expand Down
38 changes: 27 additions & 11 deletions src/http/routes/cdn/purgeCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ const purgeQuerySchema = {
},
} as const

const purgeObjectQuerySchema = {
type: 'object',
properties: {
transformations: { type: 'boolean' },
versionId: { type: 'string' },
},
} as const

const successResponseSchema = {
type: 'object',
properties: {
Expand All @@ -38,7 +46,7 @@ const successResponseSchema = {

interface PurgeObjectRequestInterface extends AuthenticatedRequest {
Params: FromSchema<typeof purgeObjectParamsSchema>
Querystring: FromSchema<typeof purgeQuerySchema>
Querystring: FromSchema<typeof purgeObjectQuerySchema>
}

interface PurgeBucketRequestInterface extends AuthenticatedRequest {
Expand Down Expand Up @@ -112,8 +120,8 @@ export default async function routes(fastify: FastifyInstance) {
{
schema: createDefaultSchema(successResponseSchema, {
params: purgeObjectParamsSchema,
querystring: purgeQuerySchema,
summary: 'Purge cache for an object or object transformations',
querystring: purgeObjectQuerySchema,
summary: 'Purge cache for an object, a specific object version, or object transformations',
tags: ['cdn'],
}),
config: {
Expand All @@ -123,14 +131,22 @@ export default async function routes(fastify: FastifyInstance) {
async (request, response) => {
const { bucketName } = request.params
const objectName = request.params['*']
const { transformations } = request.query

await cdnCache.purge({
type: transformations ? 'object-transforms' : 'object',
bucket: bucketName,
objectName,
tenant: request.tenantId,
})
const { transformations, versionId } = request.query
const tenant = request.tenantId

if (transformations) {
await cdnCache.purge({ type: 'object-transforms', bucket: bucketName, objectName, tenant })
} else if (versionId) {
await cdnCache.purge({
type: 'object-version',
bucket: bucketName,
objectName,
tenant,
versionId,
})
} else {
await cdnCache.purge({ type: 'object', bucket: bucketName, objectName, tenant })
}

return response.status(200).send(createResponse('success', '200'))
}
Expand Down
30 changes: 30 additions & 0 deletions src/storage/cdn/cdn-cache-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,36 @@ describe('CdnCacheManager', () => {
expect(timeoutSpy).toHaveBeenCalledWith(10_000)
})

it('sends an object-version purge request for a specific object version', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetchMock)

const { CdnCacheManager } = await importCdnCacheManager({
cdnPurgeEndpointURL: 'https://cdn.example.com/stub/cache',
cdnPurgeEndpointKey: 'test-key',
})

await new CdnCacheManager().purge({
type: 'object-version',
tenant: 'tenant-ref',
bucket: 'bucket-id',
objectName: 'folder/image.png',
versionId: 'version-123',
})

const [, init] = fetchMock.mock.calls[0]
const requestInit = init as RequestInit
expect(JSON.parse(requestInit.body as string)).toEqual({
type: 'object-version',
tenant: {
ref: 'tenant-ref',
},
bucketId: 'bucket-id',
objectName: 'folder/image.png',
versionId: 'version-123',
})
})

it('omits the authorization header when the purge endpoint key is not configured', async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetchMock)
Expand Down
12 changes: 12 additions & 0 deletions src/storage/cdn/cdn-cache-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ interface PurgeObjectInput extends BasePurgeInput {
objectName: string
}

interface PurgeObjectVersionInput extends BasePurgeInput {
type: 'object-version'
bucket: string
objectName: string
versionId: string
}

interface PurgeBucketInput extends BasePurgeInput {
type: 'bucket'
bucket: string
Expand All @@ -64,6 +71,7 @@ interface PurgeTenantTransformsInput extends BasePurgeInput {

export type PurgeCacheInput =
| PurgeObjectInput
| PurgeObjectVersionInput
| PurgeBucketInput
| PurgeTenantInput
| PurgeObjectTransformsInput
Expand Down Expand Up @@ -109,6 +117,10 @@ export class CdnCacheManager {
requestBody.objectName = opts.objectName
}

if ('versionId' in opts && opts.versionId) {
requestBody.versionId = opts.versionId
}

// Purge cache
try {
const requestInit: RequestInit & { dispatcher: typeof dispatcher } = {
Expand Down
16 changes: 16 additions & 0 deletions src/storage/database/adapter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest'
import { wasNoncurrentVersion } from './adapter'

describe('wasNoncurrentVersion', () => {
it('is true for a row archived before it was removed', () => {
expect(wasNoncurrentVersion({ archived_at: '2026-01-01T00:00:00Z' })).toBe(true)
})

it('is false for a row that was current (archived_at null)', () => {
expect(wasNoncurrentVersion({ archived_at: null })).toBe(false)
})

it('is false when archived_at was not selected on the row', () => {
expect(wasNoncurrentVersion({})).toBe(false)
})
})
4 changes: 4 additions & 0 deletions src/storage/database/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ export function replacedContent(
return { version: replaced.version, metadata: replaced.metadata }
}

export function wasNoncurrentVersion(deleted: Pick<Obj, 'archived_at'>): boolean {
return deleted.archived_at != null
}

export interface ObjectLockKey {
bucketId: string
objectName: string
Expand Down
55 changes: 55 additions & 0 deletions src/storage/events/cdn/purge-cdn-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ vi.mock('../base', () => ({
storageEvent: (opts: { type: string }) =>
class {
static readonly eventType = opts.type
static send = vi.fn()
static batchSend = vi.fn()
constructor(readonly data: unknown) {}
},
}))
Expand Down Expand Up @@ -60,6 +62,59 @@ function makeCtx(): StorageJob<PurgeCdnCachePayload> {
}
}

describe('purgeObjectCache', () => {
afterEach(() => {
vi.resetModules()
})

it('sends an object-version purge when given a versionId', async () => {
const { PurgeCdnCache, purgeObjectCache } = await importPurgeCdnCache()
const sendSpy = vi.mocked(PurgeCdnCache.send).mockResolvedValue(undefined)

await purgeObjectCache({
tenant: { ref: 'tenant-ref', host: 'tenant-host' },
bucketId: 'bucket-id',
name: 'folder/image.png',
sbReqId: 'sb-req-1',
versionId: 'version-123',
})

expect(sendSpy).toHaveBeenCalledWith({
tenant: { ref: 'tenant-ref', host: 'tenant-host' },
sbReqId: 'sb-req-1',
purgeOptions: {
type: 'object-version',
tenant: 'tenant-ref',
bucket: 'bucket-id',
objectName: 'folder/image.png',
versionId: 'version-123',
},
})
})

it('sends a plain object purge when no versionId is given', async () => {
const { PurgeCdnCache, purgeObjectCache } = await importPurgeCdnCache()
const sendSpy = vi.mocked(PurgeCdnCache.send).mockResolvedValue(undefined)

await purgeObjectCache({
tenant: { ref: 'tenant-ref', host: 'tenant-host' },
bucketId: 'bucket-id',
name: 'folder/image.png',
})

expect(sendSpy).toHaveBeenCalledWith({
tenant: { ref: 'tenant-ref', host: 'tenant-host' },
sbReqId: undefined,
purgeOptions: {
type: 'object',
tenant: 'tenant-ref',
bucket: 'bucket-id',
objectName: 'folder/image.png',
},
})
})
})

describe('PurgeCdnCacheHandler.handle', () => {
const cdnPurgeEndpointURL = 'https://cdn.example.com/stub/cache'
const cdnPurgeEndpointKey = 'test-key'
Expand Down
67 changes: 67 additions & 0 deletions src/storage/events/cdn/purge-cdn-cache.ts

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.

Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,78 @@ export class PurgeCdnCache extends storageEvent<PurgeCdnCachePayload>({
purgeOptions.tenant,
'bucket' in purgeOptions ? purgeOptions.bucket : undefined,
'objectName' in purgeOptions ? purgeOptions.objectName : undefined,
'versionId' in purgeOptions ? purgeOptions.versionId : undefined,
]
.filter(Boolean)
.join('/'),
}) {}

export interface PurgeableObject {
readonly tenant: { readonly ref: string; readonly host: string }
readonly bucketId: string
readonly name: string
readonly sbReqId?: string
readonly versionId?: string
}

const toPurgeOptions = (object: PurgeableObject): PurgeCdnCachePayload => ({
tenant: object.tenant,
sbReqId: object.sbReqId,
purgeOptions: object.versionId
? {
type: 'object-version',
tenant: object.tenant.ref,
bucket: object.bucketId,
objectName: object.name,
versionId: object.versionId,
}
: {
type: 'object',
tenant: object.tenant.ref,
bucket: object.bucketId,
objectName: object.name,
},
})

/**
* Purges one object's CDN cache: for Smart CDN V2 tenants this is the only invalidation
* signal there is, since V2 removes the V1 edge KV and purges the cache directly.
* Best-effort: failures are logged, never thrown, so a purge failure can't fail the write
* that triggered it.
*/
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.

} 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', {
Comment on lines +66 to +89

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.

type: 'cdn',
project: object.tenant.ref,
sbReqId: object.sbReqId,
error,
})
}
}
}

export class PurgeCdnCacheHandler extends QueueHandler(PurgeCdnCache) {
override readonly options: SubscribeOptions = {
prefetch: pgQueueConcurrentTasksPerQueue * 2,
Expand Down
Loading