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
9 changes: 5 additions & 4 deletions supabase/functions/_backend/triggers/on_version_update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { isCanonicalAppVersionR2Path } from '../utils/app_version_r2_path.ts'
import { BRES, middlewareAPISecret, simpleError, triggerValidator } from '../utils/hono.ts'
import { cloudlog } from '../utils/logging.ts'
import { deleteVersionManifestBatch } from '../utils/manifest_cleanup.ts'
import { closeClient, getDrizzleClient, getPgClient } from '../utils/pg.ts'
import { closeClient, getDrizzleClient, getPgClient, withPgTransaction } from '../utils/pg.ts'
import { queryJsonOne } from '../utils/pg_rls.ts'
import { getPath, s3 } from '../utils/s3.ts'
import { purgeUpdatesCache } from '../utils/purgeUpdatesCache.ts'
Expand Down Expand Up @@ -407,10 +407,11 @@ async function deleteVersionDatabaseState(c: Context, pg: PgClient, record: Data
}

// Files snippet copies live in every data center: queue a zone-wide purge of
// the app's tag on this connection, so it commits with the deletion (the
// drain is nudged below). The SQL function never fails the business write.
// the app's tag (the drain is nudged below). The SQL function never fails
// the business write. It writes, so it runs in a transaction: a bare SELECT
// can be answered from Hyperdrive's query cache without running it.
if (record.app_id)
await pg.query('SELECT public.notify_updates_edge_cache_purge($1::text[], $2::text)', [[record.app_id], 'files'])
await withPgTransaction(pg, tx => tx.query('SELECT public.notify_updates_edge_cache_purge($1::text[], $2::text)', [[record.app_id], 'files']))

// Release only manifest database references before ACK; delta objects stay in R2.
await deleteManifest(c, record, pg)
Expand Down
15 changes: 11 additions & 4 deletions supabase/functions/_backend/triggers/updates_cache_purge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { FILES_ROUTE_ZONE_NAMES, PLUGIN_ROUTE_HOSTS, PLUGIN_ROUTE_ZONE_NAMES } f
import { updatesCacheTagForScope } from '../plugin_runtime/utils/updatesCacheTag.ts'
import { BRES, middlewareAPISecret, quickError } from '../utils/hono.ts'
import { cloudlog, cloudlogErr, serializeError } from '../utils/logging.ts'
import { closeClient, getPgClient } from '../utils/pg.ts'
import { closeClient, getPgClient, withPgTransaction } from '../utils/pg.ts'
import { PREWARM_AFTER_PURGE_DELAY_MS, pluginStatePrewarmTargets, schedulePluginStatePrewarm } from '../utils/pluginStatePrewarm.ts'
import { backgroundTask, getEnv, isValidAppId } from '../utils/utils.ts'

Expand Down Expand Up @@ -313,10 +313,12 @@ export async function enqueueUpdatesEdgeCachePurge(c: Context, appId: string, sc
let pg: Awaited<ReturnType<typeof getPgClient>> | null = null
try {
pg = await getPgClient(c)
await pg.query(
const client = pg
// Writes a pending purge: a cached bare SELECT would silently drop it.
await withPgTransaction(client, tx => tx.query(
'SELECT public.notify_updates_edge_cache_purge($1::text[], $2::text)',
[[appId], scope],
)
))
return true
}
catch (error) {
Expand All @@ -340,7 +342,12 @@ export async function nudgeUpdatesCachePurgeDrain(c: Context) {
? [args.p_limit]
: [args.p_lease_token, args.p_success, args.p_retry_after_seconds]
try {
const result = await client.query<{ result: unknown }>(PURGE_RPC_SQL[fn], values)
// Claims and acks write (leases, throttle, requeues). A bare SELECT of
// a custom function can be answered from Hyperdrive's query cache
// without running it: many drains then replayed one cached claim and
// purged the same apps, and failed acks never reached the database.
// A transaction always reaches the database.
const result = await withPgTransaction(client, tx => tx.query<{ result: unknown }>(PURGE_RPC_SQL[fn], values))
return { data: result.rows[0]?.result ?? null, error: null }
}
catch (error) {
Expand Down
2 changes: 2 additions & 0 deletions tests/compatibility-events-handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ async function routeQuery(sql: string, params: any[], ctx: { appVersionsById: ty
vi.mock('../supabase/functions/_backend/utils/pg.ts', () => ({
getPgClient: vi.fn(async () => ({ query: pgQuery })),
closeClient: vi.fn(),
// Runs the body on the mocked client: tests see the same queries.
withPgTransaction: async (pg: any, run: (client: any) => unknown) => run(pg),
}))

vi.mock('../supabase/functions/_backend/utils/logging.ts', () => ({
Expand Down
2 changes: 2 additions & 0 deletions tests/on-version-update-cleanup.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ vi.mock('../supabase/functions/_backend/utils/pg.ts', () => ({
closeClient,
getDrizzleClient,
getPgClient,
// Runs the body on the mocked client: tests see the same queries.
withPgTransaction: async (pg: any, run: (client: any) => unknown) => run(pg),
}))

vi.mock('../supabase/functions/_backend/utils/logging.ts', () => ({
Expand Down
2 changes: 2 additions & 0 deletions tests/purge-updates-cache-triggers.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ vi.mock('../supabase/functions/_backend/utils/pg.ts', () => ({
getPgClient: mocks.getPgClient,
closeClient: mocks.closeClient,
getDrizzleClient: mocks.getDrizzleClient,
// Runs the body on the mocked client: tests see the same queries.
withPgTransaction: async (pg: any, run: (client: any) => unknown) => run(pg),
}))

vi.mock('../supabase/functions/_backend/utils/version_notifications.ts', () => ({
Expand Down
70 changes: 70 additions & 0 deletions tests/updates-cache-purge-transaction.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it, vi } from 'vitest'

// The purge queue RPCs write (leases, throttle, requeues, pending rows). A
// bare SELECT of a custom function can be answered from Hyperdrive's query
// cache without running it, so each one must run inside a transaction.
const mocks = vi.hoisted(() => {
const queries: { sql: string, inTransaction: boolean }[] = []
let inTransaction = false
const client = {
query: vi.fn(async (sql: string) => {
queries.push({ sql, inTransaction })
return { rows: [{ result: { status: 'empty' } }] }
}),
}
return {
queries,
client,
getPgClient: vi.fn(async () => client),
closeClient: vi.fn(),
withPgTransaction: vi.fn(async (_pg: unknown, run: (tx: typeof client) => unknown) => {
inTransaction = true
try {
return await run(client)
}
finally {
inTransaction = false
}
}),
}
})

vi.mock('../supabase/functions/_backend/utils/pg.ts', () => ({
getPgClient: mocks.getPgClient,
closeClient: mocks.closeClient,
withPgTransaction: mocks.withPgTransaction,
}))

const { enqueueUpdatesEdgeCachePurge, nudgeUpdatesCachePurgeDrain } = await import('../supabase/functions/_backend/triggers/updates_cache_purge.ts')

function makeContext() {
return {
env: { CF_CACHE_PURGE_TOKEN: 'token', CF_CACHE_PURGE_ZONE_IDS: 'zone-a' },
get: (key: string) => key === 'requestId' ? 'req-purge-tx' : undefined,
} as any
}

describe('updates cache purge queue writes', () => {
afterEach(() => {
mocks.queries.length = 0
vi.clearAllMocks()
vi.unstubAllEnvs()
})

it('claims inside a transaction', async () => {
vi.stubEnv('CF_CACHE_PURGE_TOKEN', 'token')
vi.stubEnv('CF_CACHE_PURGE_ZONE_IDS', 'zone-a')
await nudgeUpdatesCachePurgeDrain(makeContext())

const claims = mocks.queries.filter(query => query.sql.includes('claim_updates_cache_purge'))
expect(claims.length).toBeGreaterThan(0)
expect(claims.every(query => query.inTransaction)).toBe(true)
})

it('enqueues a purge inside a transaction', async () => {
await expect(enqueueUpdatesEdgeCachePurge(makeContext(), 'com.example.app', 'files')).resolves.toBe(true)

const enqueues = mocks.queries.filter(query => query.sql.includes('notify_updates_edge_cache_purge'))
expect(enqueues).toEqual([expect.objectContaining({ inTransaction: true })])
})
})
2 changes: 2 additions & 0 deletions tests/version-notifications.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ vi.mock('../supabase/functions/_backend/utils/pg.ts', () => ({
getPgClient: mocks.getPgClient,
closeClient: mocks.closeClient,
getDrizzleClient: vi.fn(() => ({})),
// Runs the body on the mocked client: tests see the same queries.
withPgTransaction: async (pg: any, run: (client: any) => unknown) => run(pg),
}))
vi.mock('../supabase/functions/_backend/utils/org_email_notifications.ts', () => ({
sendEmailToOrgMembers: mocks.sendEmailToOrgMembers,
Expand Down
Loading