payload-plugin-backup-postgres 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/backup-dashboard.css +27 -8
  2. package/dist/collections/BackupTasks.js +2 -1
  3. package/dist/collections/BackupTasks.js.map +1 -1
  4. package/dist/components/BackupDashboard/BackupItemActions.client.js +1 -0
  5. package/dist/components/BackupDashboard/BackupItemActions.client.js.map +1 -1
  6. package/dist/components/BackupDashboard/BackupListCollapsible.client.js +105 -98
  7. package/dist/components/BackupDashboard/BackupListCollapsible.client.js.map +1 -1
  8. package/dist/components/BackupDashboard/BackupSettingsModal.client.js +1 -1
  9. package/dist/components/BackupDashboard/BackupSettingsModal.client.js.map +1 -1
  10. package/dist/components/BackupDashboard/BackupUploadProgress.client.js +54 -8
  11. package/dist/components/BackupDashboard/BackupUploadProgress.client.js.map +1 -1
  12. package/dist/components/BackupDashboard/ManualBackupDialog.client.js +3 -23
  13. package/dist/components/BackupDashboard/ManualBackupDialog.client.js.map +1 -1
  14. package/dist/components/BackupDashboard/TaskActionButton.client.d.ts +2 -0
  15. package/dist/components/BackupDashboard/TaskActionButton.client.js +44 -34
  16. package/dist/components/BackupDashboard/TaskActionButton.client.js.map +1 -1
  17. package/dist/components/BackupDashboard/backupDashboardInlineCss.js +1 -1
  18. package/dist/components/BackupDashboard/backupDashboardInlineCss.js.map +1 -1
  19. package/dist/core/backup.js +53 -17
  20. package/dist/core/backup.js.map +1 -1
  21. package/dist/core/backupBlobIO.d.ts +1 -1
  22. package/dist/core/backupBlobIO.js +7 -1
  23. package/dist/core/backupBlobIO.js.map +1 -1
  24. package/dist/core/storage/s3.d.ts +1 -1
  25. package/dist/core/storage/s3.js +16 -2
  26. package/dist/core/storage/s3.js.map +1 -1
  27. package/dist/core/storage/types.d.ts +1 -1
  28. package/dist/core/storage/types.js.map +1 -1
  29. package/dist/core/storage/vercelBlob.d.ts +1 -1
  30. package/dist/core/storage/vercelBlob.js +2 -2
  31. package/dist/core/storage/vercelBlob.js.map +1 -1
  32. package/dist/core/taskProgress.d.ts +3 -1
  33. package/dist/core/taskProgress.js +29 -0
  34. package/dist/core/taskProgress.js.map +1 -1
  35. package/dist/endpoints/index.js +2 -0
  36. package/dist/endpoints/index.js.map +1 -1
  37. package/dist/endpoints/paths/admin-manual.js +9 -6
  38. package/dist/endpoints/paths/admin-manual.js.map +1 -1
  39. package/dist/endpoints/paths/admin-task-cancel.d.ts +3 -0
  40. package/dist/endpoints/paths/admin-task-cancel.js +34 -0
  41. package/dist/endpoints/paths/admin-task-cancel.js.map +1 -0
  42. package/dist/endpoints/paths/admin-task.js +1 -1
  43. package/dist/endpoints/paths/admin-task.js.map +1 -1
  44. package/dist/publicApiPaths.d.ts +1 -0
  45. package/dist/publicApiPaths.js +1 -0
  46. package/dist/publicApiPaths.js.map +1 -1
  47. package/package.json +1 -1
@@ -8,7 +8,7 @@ import { getPgDb, listTables, qi, qualified, withClient } from './db.js';
8
8
  import { ARCHIVE_FORMAT, ARCHIVE_VERSION, DATABASE_FILE_NAME, MEDIA_PREFIX, serializeBackupDocument } from './pgArchive.js';
9
9
  import { getBackupStorageKind, resolveBackupStorage } from './storage/index.js';
10
10
  import { resolveTableOwners } from './tableGroups.js';
11
- import { updateBackupTask } from './taskProgress.js';
11
+ import { isBackupTaskCancelled, updateBackupTask } from './taskProgress.js';
12
12
  export { DATABASE_FILE_NAME } from './pgArchive.js';
13
13
  /**
14
14
  * Resolves the Vercel Blob read/write token the same way as backup endpoints and
@@ -201,6 +201,9 @@ export async function createBackup(payload, options = {}) {
201
201
  includeMedia
202
202
  }, '[backup] Starting backup');
203
203
  if (taskId) {
204
+ if (await isBackupTaskCancelled(payload, taskId)) {
205
+ return;
206
+ }
204
207
  await updateBackupTask(payload, taskId, {
205
208
  message: 'Starting backup',
206
209
  status: 'running'
@@ -215,6 +218,9 @@ export async function createBackup(payload, options = {}) {
215
218
  count: oldest.length
216
219
  }, '[backup] Pruning old cron backups');
217
220
  if (taskId) {
221
+ if (await isBackupTaskCancelled(payload, taskId)) {
222
+ throw new Error('Backup cancelled');
223
+ }
218
224
  await updateBackupTask(payload, taskId, {
219
225
  message: `Pruning ${oldest.length} old cron backup${oldest.length === 1 ? '' : 's'}`
220
226
  });
@@ -243,9 +249,15 @@ export async function createBackup(payload, options = {}) {
243
249
  table
244
250
  }, '[backup] Table dumped');
245
251
  if (taskId) {
252
+ if (await isBackupTaskCancelled(payload, taskId)) {
253
+ throw new Error('Backup cancelled');
254
+ }
246
255
  await updateBackupTask(payload, taskId, {
247
256
  message: `Dumped table ${table} (${rowCount} rows)`
248
257
  });
258
+ if (taskId && await isBackupTaskCancelled(payload, taskId)) {
259
+ throw new Error('Backup cancelled');
260
+ }
249
261
  }
250
262
  },
251
263
  skipTables: skipCollections
@@ -264,6 +276,9 @@ export async function createBackup(payload, options = {}) {
264
276
  }
265
277
  }
266
278
  const backupFile = includeMedia ? await createMediaBackupFile(databaseFile, mediaPathnames, token, undefined, payload) : databaseFile;
279
+ if (taskId && await isBackupTaskCancelled(payload, taskId)) {
280
+ throw new Error('Backup cancelled');
281
+ }
267
282
  const name = `backups/${createBlobName(type, currentDbName, currentHostname, includedTableCount, backupTimestampMs, includeMedia ? 'tar.gz' : 'json', label || undefined)}`;
268
283
  payload.logger.info({
269
284
  name
@@ -271,6 +286,8 @@ export async function createBackup(payload, options = {}) {
271
286
  const totalBytes = typeof backupFile === 'string' ? Buffer.byteLength(backupFile) : backupFile.byteLength;
272
287
  let lastProgressUpdateAt = 0;
273
288
  let progressWrites = Promise.resolve();
289
+ const uploadAbortController = new AbortController();
290
+ let cancellationPoll;
274
291
  if (taskId) {
275
292
  await updateBackupTask(payload, taskId, {
276
293
  message: serializeBackupUploadProgress({
@@ -278,25 +295,44 @@ export async function createBackup(payload, options = {}) {
278
295
  totalBytes
279
296
  })
280
297
  });
298
+ cancellationPoll = setInterval(()=>{
299
+ void isBackupTaskCancelled(payload, taskId).then((cancelled)=>{
300
+ if (cancelled) {
301
+ uploadAbortController.abort();
302
+ }
303
+ });
304
+ }, 1000);
281
305
  }
282
- await storage.put(name, backupFile, taskId ? ({ loaded, total })=>{
283
- const now = Date.now();
284
- if (now - lastProgressUpdateAt < 500 && loaded < total) {
285
- return;
286
- }
287
- lastProgressUpdateAt = now;
288
- const progressTotalBytes = total > 0 ? total : totalBytes;
289
- const message = serializeBackupUploadProgress({
290
- bytesUploaded: loaded,
291
- totalBytes: progressTotalBytes
292
- });
293
- progressWrites = progressWrites.then(async ()=>{
294
- await updateBackupTask(payload, taskId, {
295
- message
306
+ try {
307
+ await storage.put(name, backupFile, taskId ? ({ loaded, total })=>{
308
+ const now = Date.now();
309
+ if (now - lastProgressUpdateAt < 500 && loaded < total) {
310
+ return;
311
+ }
312
+ lastProgressUpdateAt = now;
313
+ const progressTotalBytes = total > 0 ? total : totalBytes;
314
+ const message = serializeBackupUploadProgress({
315
+ bytesUploaded: loaded,
316
+ totalBytes: progressTotalBytes
296
317
  });
297
- });
298
- } : undefined);
318
+ progressWrites = progressWrites.then(async ()=>{
319
+ await updateBackupTask(payload, taskId, {
320
+ message
321
+ });
322
+ });
323
+ } : undefined, taskId ? uploadAbortController.signal : undefined);
324
+ } finally{
325
+ if (cancellationPoll) {
326
+ clearInterval(cancellationPoll);
327
+ }
328
+ }
299
329
  await progressWrites;
330
+ if (taskId && await isBackupTaskCancelled(payload, taskId)) {
331
+ await storage.del({
332
+ pathname: name
333
+ });
334
+ throw new Error('Backup cancelled');
335
+ }
300
336
  if (taskId) {
301
337
  await updateBackupTask(payload, taskId, {
302
338
  message: serializeBackupUploadProgress({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/backup.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { list } from '@vercel/blob'\n\nimport { serializeBackupUploadProgress } from '../utils/backupUploadProgress'\nimport {\n createBlobName,\n getCurrentDbName,\n getCurrentHostname,\n sanitizeBackupLabel,\n} from '../utils/index'\nimport { createTarGzip } from './archive'\nimport { type BackupBlobAccessLevel, readBackupBlobContentFlexible } from './backupBlobIO'\nimport { getResolvedCronBackupSettings, resolveBackupBlobToken } from './backupSettings'\nimport { getPgDb, listTables, type PgClient, qi, qualified, withClient } from './db'\nimport {\n ARCHIVE_FORMAT,\n ARCHIVE_VERSION,\n DATABASE_FILE_NAME,\n MEDIA_PREFIX,\n type PgBackupDocument,\n serializeBackupDocument,\n} from './pgArchive'\nimport { getBackupStorageKind, resolveBackupStorage } from './storage'\nimport { resolveTableOwners } from './tableGroups'\nimport { updateBackupTask } from './taskProgress'\n\nexport { DATABASE_FILE_NAME } from './pgArchive'\n\n/**\n * Resolves the Vercel Blob read/write token the same way as backup endpoints and\n * {@link createBackup} / {@link restoreBackup}: settings document override, else `BLOB_READ_WRITE_TOKEN`.\n * Pass `explicitToken` to skip reading settings (same as `options.blobToken` in those calls).\n */\nexport async function resolveBackupListToken(\n payload: Payload,\n explicitToken?: string,\n): Promise<string> {\n const t = explicitToken?.trim()\n if (t) {\n return t\n }\n return resolveBackupBlobToken(await getResolvedCronBackupSettings(payload)).trim()\n}\n\nexport async function listBackups(\n payload: Payload,\n options: {\n /**\n * When set, used as the Vercel Blob token (e.g. tests or a pre-resolved value).\n * When omitted, uses {@link resolveBackupListToken} (settings + env), same as other backup APIs.\n */\n blobToken?: string\n } = {},\n) {\n const kind = getBackupStorageKind()\n if (kind === 'vercel-blob') {\n const token = await resolveBackupListToken(payload, options.blobToken)\n if (!token) {\n return []\n }\n return resolveBackupStorage({ blobToken: token, kind }).list('backups/')\n }\n return resolveBackupStorage({ kind }).list('backups/')\n}\n\nfunction resolveBlobToken(blobToken?: string): string | undefined {\n if (blobToken && blobToken.trim().length > 0) {\n return blobToken\n }\n return undefined\n}\n\n/**\n * Builds a tar.gz archive containing the database dump plus Payload upload-store media files.\n * Media always comes from the Vercel Blob upload store (via token/env), independent of the\n * configured backup archive target (S3 vs Vercel Blob).\n */\nexport async function createMediaBackupFile(\n databaseFile: string,\n mediaPathnames: string[],\n backupBlobToken?: string,\n mediaListToken?: string,\n payload?: Payload,\n): Promise<Buffer> {\n const envMedia = (process.env.BLOB_READ_WRITE_TOKEN || '').trim()\n const tokenForMedia =\n resolveBlobToken(mediaListToken) ??\n (envMedia.length > 0 ? envMedia : undefined) ??\n resolveBlobToken(backupBlobToken)\n const unique = [...new Set(mediaPathnames.filter(Boolean))]\n const mediaFiles = await Promise.all(\n unique.map(async (pathname) => {\n try {\n const matchingFiles = await list({ limit: 2, prefix: pathname, token: tokenForMedia })\n const blob = matchingFiles.blobs.find((b) => b.pathname === pathname)\n if (!blob) {\n payload?.logger.warn(\n { filename: pathname },\n '[backup] File was in database but not in blob storage',\n )\n return undefined\n }\n const content = await readBackupBlobContentFlexible(\n blob.pathname,\n blob.downloadUrl,\n tokenForMedia ?? '',\n )\n return { name: `${MEDIA_PREFIX}${pathname}`, content }\n } catch (err) {\n payload?.logger.warn(\n { err, filename: pathname },\n '[backup] Failed to read media file from blob storage',\n )\n return undefined\n }\n }),\n )\n return await createTarGzip([\n { name: DATABASE_FILE_NAME, content: Buffer.from(databaseFile) },\n ...(mediaFiles.filter(Boolean) as { content: Buffer; name: string }[]),\n ])\n}\n\ntype DumpResult = {\n doc: PgBackupDocument\n /** Blob pathnames referenced by upload collections (only collected when requested). */\n mediaPathnames: string[]\n}\n\n/**\n * Dumps every table of Payload's schema inside one `REPEATABLE READ READ ONLY` transaction,\n * so all tables come from the same snapshot.\n */\nexport async function dumpDatabase(\n payload: Payload,\n options: {\n collectMedia?: boolean\n onTable?: (table: string, rowCount: number) => Promise<void> | void\n skipTables?: string[]\n } = {},\n): Promise<DumpResult> {\n const { pool, schema, tableNameMap } = getPgDb(payload)\n const skip = new Set(options.skipTables ?? [])\n\n return withClient(pool, async (client) => {\n await client.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')\n try {\n const { rows: ver } = await client.query<{ v: string }>(\n `SELECT current_setting('server_version') AS v`,\n )\n const allTables = await listTables(client, schema)\n const tables: PgBackupDocument['tables'] = {}\n for (const table of allTables) {\n if (skip.has(table)) {\n payload.logger.debug({ table }, '[backup] Skipping blacklisted table')\n continue\n }\n const { rows } = await client.query<{ n: string; rows: string }>(\n `SELECT count(*)::text AS n, coalesce(json_agg(t), '[]'::json)::text AS rows\n FROM ${qualified(schema, table)} t`,\n )\n const rowCount = Number(rows[0]?.n ?? 0)\n tables[table] = { rowCount, rows: rows[0]?.rows ?? '[]' }\n await options.onTable?.(table, rowCount)\n }\n\n const mediaPathnames: string[] = []\n if (options.collectMedia) {\n const owners = resolveTableOwners(payload, Object.keys(tables), tableNameMap)\n const uploadSlugs = new Set(\n (payload.config.collections ?? []).filter((c) => Boolean(c.upload)).map((c) => c.slug),\n )\n for (const table of Object.keys(tables)) {\n const owner = owners.get(table)!\n // Only the main root table of an upload collection holds `filename` / `sizes_*_filename`.\n if (owner.kind !== 'collection' || owner.versions || !uploadSlugs.has(owner.slug)) {\n continue\n }\n mediaPathnames.push(...(await readMediaPathnames(client, schema, table)))\n }\n }\n\n await client.query('COMMIT')\n return {\n doc: {\n createdAt: new Date().toISOString(),\n format: ARCHIVE_FORMAT,\n schema,\n serverVersion: ver[0]?.v ?? 'unknown',\n tables,\n version: ARCHIVE_VERSION,\n },\n mediaPathnames,\n }\n } catch (err) {\n await client.query('ROLLBACK').catch(() => undefined)\n throw err\n }\n })\n}\n\nasync function readMediaPathnames(\n client: PgClient,\n schema: string,\n table: string,\n): Promise<string[]> {\n const { rows: cols } = await client.query<{ name: string }>(\n `SELECT a.attname AS name\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped`,\n [schema, table],\n )\n const names = new Set(cols.map((c) => c.name))\n if (!names.has('filename')) {\n return []\n }\n const fileCols = ['filename', ...[...names].filter((n) => /^sizes_.+_filename$/.test(n))]\n const prefixExpr = names.has('prefix') ? qi('prefix') : 'NULL::text'\n const out: string[] = []\n for (const col of fileCols) {\n const { rows } = await client.query<{ f: string; p: null | string }>(\n `SELECT ${prefixExpr} AS p, ${qi(col)}::text AS f\n FROM ${qualified(schema, table)}\n WHERE ${qi(col)} IS NOT NULL AND ${qi(col)}::text <> ''`,\n )\n for (const r of rows) {\n const prefix = (r.p ?? '').replace(/^\\/+|\\/+$/g, '')\n out.push(prefix ? `${prefix}/${r.f}` : r.f)\n }\n }\n return out\n}\n\nexport async function createBackup(\n payload: Payload,\n options: {\n backupsToKeep?: number\n /** Public (default) or private Vercel Blob access for the uploaded backup archive. */\n blobAccess?: BackupBlobAccessLevel\n /** Optional explicit Vercel Blob token (falls back to env inside @vercel/blob). */\n blobToken?: string\n cron?: boolean\n includeMedia?: boolean\n /**\n * Optional human-readable label for manual backups (appears in the backup list and is\n * searchable via the label filter). Ignored for cron backups.\n */\n label?: string\n /** Postgres table names to omit from the dump (e.g. manual backup UI). */\n skipCollections?: string[]\n taskId?: string\n } = {},\n): Promise<void> {\n const {\n backupsToKeep,\n blobToken,\n cron = false,\n includeMedia = false,\n skipCollections,\n taskId,\n } = options\n const label = cron ? '' : sanitizeBackupLabel(options.label)\n const blobAccess: BackupBlobAccessLevel = options.blobAccess ?? 'public'\n const token = resolveBlobToken(blobToken)\n const resolvedBackupsToKeep = backupsToKeep ?? (Number(process.env.BACKUPS_TO_KEEP) || 10)\n const storage = resolveBackupStorage({ blobAccess, blobToken: token })\n\n const currentHostname = getCurrentHostname()\n const currentDbName = getCurrentDbName()\n const type = cron ? 'cron' : 'manual'\n const t0 = Date.now()\n\n payload.logger.info(\n {\n type,\n blacklist: skipCollections?.length ?? 0,\n db: currentDbName,\n host: currentHostname,\n includeMedia,\n },\n '[backup] Starting backup',\n )\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Starting backup', status: 'running' })\n }\n\n if (cron) {\n const blobs = await storage.list('backups/cron-')\n const sorted = blobs.sort(\n (a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime(),\n )\n const oldest = sorted.slice(Math.max(0, resolvedBackupsToKeep - 1))\n if (oldest.length > 0) {\n payload.logger.info({ count: oldest.length }, '[backup] Pruning old cron backups')\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: `Pruning ${oldest.length} old cron backup${oldest.length === 1 ? '' : 's'}`,\n })\n }\n }\n for (const blob of oldest) {\n await storage.del({ pathname: blob.pathname, url: blob.url })\n payload.logger.info({ pathname: blob.pathname }, '[backup] Deleted old backup')\n }\n }\n\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Dumping tables' })\n }\n const { doc, mediaPathnames } = await dumpDatabase(payload, {\n collectMedia: includeMedia,\n onTable: async (table, rowCount) => {\n payload.logger.debug({ rows: rowCount, table }, '[backup] Table dumped')\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: `Dumped table ${table} (${rowCount} rows)`,\n })\n }\n },\n skipTables: skipCollections,\n })\n\n const databaseFile = serializeBackupDocument(doc)\n const includedTableCount = Object.keys(doc.tables).length\n const backupTimestampMs = Date.now()\n\n if (includeMedia) {\n payload.logger.info({ files: mediaPathnames.length }, '[backup] Bundling media files')\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Bundling media files into archive' })\n }\n }\n\n const backupFile =\n includeMedia ?\n await createMediaBackupFile(databaseFile, mediaPathnames, token, undefined, payload)\n : databaseFile\n const name = `backups/${createBlobName(\n type,\n currentDbName,\n currentHostname,\n includedTableCount,\n backupTimestampMs,\n includeMedia ? 'tar.gz' : 'json',\n label || undefined,\n )}`\n\n payload.logger.info({ name }, '[backup] Uploading backup to blob storage')\n const totalBytes =\n typeof backupFile === 'string' ? Buffer.byteLength(backupFile) : backupFile.byteLength\n let lastProgressUpdateAt = 0\n let progressWrites = Promise.resolve()\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: serializeBackupUploadProgress({ bytesUploaded: 0, totalBytes }),\n })\n }\n await storage.put(\n name,\n backupFile,\n taskId ?\n ({ loaded, total }) => {\n const now = Date.now()\n if (now - lastProgressUpdateAt < 500 && loaded < total) {\n return\n }\n lastProgressUpdateAt = now\n const progressTotalBytes = total > 0 ? total : totalBytes\n const message = serializeBackupUploadProgress({\n bytesUploaded: loaded,\n totalBytes: progressTotalBytes,\n })\n progressWrites = progressWrites.then(async () => {\n await updateBackupTask(payload, taskId, { message })\n })\n }\n : undefined,\n )\n await progressWrites\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: serializeBackupUploadProgress({ bytesUploaded: totalBytes, totalBytes }),\n })\n }\n\n payload.logger.info({ name, durationMs: Date.now() - t0 }, '[backup] Backup complete')\n}\n"],"names":["list","serializeBackupUploadProgress","createBlobName","getCurrentDbName","getCurrentHostname","sanitizeBackupLabel","createTarGzip","readBackupBlobContentFlexible","getResolvedCronBackupSettings","resolveBackupBlobToken","getPgDb","listTables","qi","qualified","withClient","ARCHIVE_FORMAT","ARCHIVE_VERSION","DATABASE_FILE_NAME","MEDIA_PREFIX","serializeBackupDocument","getBackupStorageKind","resolveBackupStorage","resolveTableOwners","updateBackupTask","resolveBackupListToken","payload","explicitToken","t","trim","listBackups","options","kind","token","blobToken","resolveBlobToken","length","undefined","createMediaBackupFile","databaseFile","mediaPathnames","backupBlobToken","mediaListToken","envMedia","process","env","BLOB_READ_WRITE_TOKEN","tokenForMedia","unique","Set","filter","Boolean","mediaFiles","Promise","all","map","pathname","matchingFiles","limit","prefix","blob","blobs","find","b","logger","warn","filename","content","downloadUrl","name","err","Buffer","from","dumpDatabase","pool","schema","tableNameMap","skip","skipTables","client","query","rows","ver","allTables","tables","table","has","debug","rowCount","Number","n","onTable","collectMedia","owners","Object","keys","uploadSlugs","config","collections","c","upload","slug","owner","get","versions","push","readMediaPathnames","doc","createdAt","Date","toISOString","format","serverVersion","v","version","catch","cols","names","fileCols","test","prefixExpr","out","col","r","p","replace","f","createBackup","backupsToKeep","cron","includeMedia","skipCollections","taskId","label","blobAccess","resolvedBackupsToKeep","BACKUPS_TO_KEEP","storage","currentHostname","currentDbName","type","t0","now","info","blacklist","db","host","message","status","sorted","sort","a","uploadedAt","getTime","oldest","slice","Math","max","count","del","url","includedTableCount","backupTimestampMs","files","backupFile","totalBytes","byteLength","lastProgressUpdateAt","progressWrites","resolve","bytesUploaded","put","loaded","total","progressTotalBytes","then","durationMs"],"mappings":"AAEA,SAASA,IAAI,QAAQ,eAAc;AAEnC,SAASC,6BAA6B,QAAQ,gCAA+B;AAC7E,SACEC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,QACd,iBAAgB;AACvB,SAASC,aAAa,QAAQ,YAAW;AACzC,SAAqCC,6BAA6B,QAAQ,iBAAgB;AAC1F,SAASC,6BAA6B,EAAEC,sBAAsB,QAAQ,mBAAkB;AACxF,SAASC,OAAO,EAAEC,UAAU,EAAiBC,EAAE,EAAEC,SAAS,EAAEC,UAAU,QAAQ,OAAM;AACpF,SACEC,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,YAAY,EAEZC,uBAAuB,QAClB,cAAa;AACpB,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,YAAW;AACtE,SAASC,kBAAkB,QAAQ,gBAAe;AAClD,SAASC,gBAAgB,QAAQ,iBAAgB;AAEjD,SAASN,kBAAkB,QAAQ,cAAa;AAEhD;;;;CAIC,GACD,OAAO,eAAeO,uBACpBC,OAAgB,EAChBC,aAAsB;IAEtB,MAAMC,IAAID,eAAeE;IACzB,IAAID,GAAG;QACL,OAAOA;IACT;IACA,OAAOlB,uBAAuB,MAAMD,8BAA8BiB,UAAUG,IAAI;AAClF;AAEA,OAAO,eAAeC,YACpBJ,OAAgB,EAChBK,UAMI,CAAC,CAAC;IAEN,MAAMC,OAAOX;IACb,IAAIW,SAAS,eAAe;QAC1B,MAAMC,QAAQ,MAAMR,uBAAuBC,SAASK,QAAQG,SAAS;QACrE,IAAI,CAACD,OAAO;YACV,OAAO,EAAE;QACX;QACA,OAA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G,CACftG,MACA+F,YACAhC,SACE,CAAC,EAAEwC,MAAM,EAAEC,KAAK,EAAE;QAChB,MAAM/B,MAAMjC,KAAKiC,GAAG;QACpB,IAAIA,MAAMyB,uBAAuB,OAAOK,SAASC,OAAO;YACtD;QACF;QACAN,uBAAuBzB;QACvB,MAAMgC,qBAAqBD,QAAQ,IAAIA,QAAQR;QAC/C,MAAMlB,UAAUjJ,8BAA8B;YAC5CwK,eAAeE;YACfP,YAAYS;QACd;QACAN,iBAAiBA,eAAeO,IAAI,CAAC;YACnC,MAAMvJ,iBAAiBE,SAAS0G,QAAQ;gBAAEe;YAAQ;QACpD;IACF,IACA9G;IAEJ,MAAMmI;IACN,IAAIpC,QAAQ;QACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;YACtCe,SAASjJ,8BAA8B;gBAAEwK,eAAeL;gBAAYA;YAAW;QACjF;IACF;IAEA3I,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;QAAE1E;QAAM2G,YAAYnE,KAAKiC,GAAG,KAAKD;IAAG,GAAG;AAC7D"}
1
+ {"version":3,"sources":["../../src/core/backup.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { list } from '@vercel/blob'\n\nimport { serializeBackupUploadProgress } from '../utils/backupUploadProgress'\nimport {\n createBlobName,\n getCurrentDbName,\n getCurrentHostname,\n sanitizeBackupLabel,\n} from '../utils/index'\nimport { createTarGzip } from './archive'\nimport { type BackupBlobAccessLevel, readBackupBlobContentFlexible } from './backupBlobIO'\nimport { getResolvedCronBackupSettings, resolveBackupBlobToken } from './backupSettings'\nimport { getPgDb, listTables, type PgClient, qi, qualified, withClient } from './db'\nimport {\n ARCHIVE_FORMAT,\n ARCHIVE_VERSION,\n DATABASE_FILE_NAME,\n MEDIA_PREFIX,\n type PgBackupDocument,\n serializeBackupDocument,\n} from './pgArchive'\nimport { getBackupStorageKind, resolveBackupStorage } from './storage'\nimport { resolveTableOwners } from './tableGroups'\nimport { isBackupTaskCancelled, updateBackupTask } from './taskProgress'\n\nexport { DATABASE_FILE_NAME } from './pgArchive'\n\n/**\n * Resolves the Vercel Blob read/write token the same way as backup endpoints and\n * {@link createBackup} / {@link restoreBackup}: settings document override, else `BLOB_READ_WRITE_TOKEN`.\n * Pass `explicitToken` to skip reading settings (same as `options.blobToken` in those calls).\n */\nexport async function resolveBackupListToken(\n payload: Payload,\n explicitToken?: string,\n): Promise<string> {\n const t = explicitToken?.trim()\n if (t) {\n return t\n }\n return resolveBackupBlobToken(await getResolvedCronBackupSettings(payload)).trim()\n}\n\nexport async function listBackups(\n payload: Payload,\n options: {\n /**\n * When set, used as the Vercel Blob token (e.g. tests or a pre-resolved value).\n * When omitted, uses {@link resolveBackupListToken} (settings + env), same as other backup APIs.\n */\n blobToken?: string\n } = {},\n) {\n const kind = getBackupStorageKind()\n if (kind === 'vercel-blob') {\n const token = await resolveBackupListToken(payload, options.blobToken)\n if (!token) {\n return []\n }\n return resolveBackupStorage({ blobToken: token, kind }).list('backups/')\n }\n return resolveBackupStorage({ kind }).list('backups/')\n}\n\nfunction resolveBlobToken(blobToken?: string): string | undefined {\n if (blobToken && blobToken.trim().length > 0) {\n return blobToken\n }\n return undefined\n}\n\n/**\n * Builds a tar.gz archive containing the database dump plus Payload upload-store media files.\n * Media always comes from the Vercel Blob upload store (via token/env), independent of the\n * configured backup archive target (S3 vs Vercel Blob).\n */\nexport async function createMediaBackupFile(\n databaseFile: string,\n mediaPathnames: string[],\n backupBlobToken?: string,\n mediaListToken?: string,\n payload?: Payload,\n): Promise<Buffer> {\n const envMedia = (process.env.BLOB_READ_WRITE_TOKEN || '').trim()\n const tokenForMedia =\n resolveBlobToken(mediaListToken) ??\n (envMedia.length > 0 ? envMedia : undefined) ??\n resolveBlobToken(backupBlobToken)\n const unique = [...new Set(mediaPathnames.filter(Boolean))]\n const mediaFiles = await Promise.all(\n unique.map(async (pathname) => {\n try {\n const matchingFiles = await list({ limit: 2, prefix: pathname, token: tokenForMedia })\n const blob = matchingFiles.blobs.find((b) => b.pathname === pathname)\n if (!blob) {\n payload?.logger.warn(\n { filename: pathname },\n '[backup] File was in database but not in blob storage',\n )\n return undefined\n }\n const content = await readBackupBlobContentFlexible(\n blob.pathname,\n blob.downloadUrl,\n tokenForMedia ?? '',\n )\n return { name: `${MEDIA_PREFIX}${pathname}`, content }\n } catch (err) {\n payload?.logger.warn(\n { err, filename: pathname },\n '[backup] Failed to read media file from blob storage',\n )\n return undefined\n }\n }),\n )\n return await createTarGzip([\n { name: DATABASE_FILE_NAME, content: Buffer.from(databaseFile) },\n ...(mediaFiles.filter(Boolean) as { content: Buffer; name: string }[]),\n ])\n}\n\ntype DumpResult = {\n doc: PgBackupDocument\n /** Blob pathnames referenced by upload collections (only collected when requested). */\n mediaPathnames: string[]\n}\n\n/**\n * Dumps every table of Payload's schema inside one `REPEATABLE READ READ ONLY` transaction,\n * so all tables come from the same snapshot.\n */\nexport async function dumpDatabase(\n payload: Payload,\n options: {\n collectMedia?: boolean\n onTable?: (table: string, rowCount: number) => Promise<void> | void\n skipTables?: string[]\n } = {},\n): Promise<DumpResult> {\n const { pool, schema, tableNameMap } = getPgDb(payload)\n const skip = new Set(options.skipTables ?? [])\n\n return withClient(pool, async (client) => {\n await client.query('BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY')\n try {\n const { rows: ver } = await client.query<{ v: string }>(\n `SELECT current_setting('server_version') AS v`,\n )\n const allTables = await listTables(client, schema)\n const tables: PgBackupDocument['tables'] = {}\n for (const table of allTables) {\n if (skip.has(table)) {\n payload.logger.debug({ table }, '[backup] Skipping blacklisted table')\n continue\n }\n const { rows } = await client.query<{ n: string; rows: string }>(\n `SELECT count(*)::text AS n, coalesce(json_agg(t), '[]'::json)::text AS rows\n FROM ${qualified(schema, table)} t`,\n )\n const rowCount = Number(rows[0]?.n ?? 0)\n tables[table] = { rowCount, rows: rows[0]?.rows ?? '[]' }\n await options.onTable?.(table, rowCount)\n }\n\n const mediaPathnames: string[] = []\n if (options.collectMedia) {\n const owners = resolveTableOwners(payload, Object.keys(tables), tableNameMap)\n const uploadSlugs = new Set(\n (payload.config.collections ?? []).filter((c) => Boolean(c.upload)).map((c) => c.slug),\n )\n for (const table of Object.keys(tables)) {\n const owner = owners.get(table)!\n // Only the main root table of an upload collection holds `filename` / `sizes_*_filename`.\n if (owner.kind !== 'collection' || owner.versions || !uploadSlugs.has(owner.slug)) {\n continue\n }\n mediaPathnames.push(...(await readMediaPathnames(client, schema, table)))\n }\n }\n\n await client.query('COMMIT')\n return {\n doc: {\n createdAt: new Date().toISOString(),\n format: ARCHIVE_FORMAT,\n schema,\n serverVersion: ver[0]?.v ?? 'unknown',\n tables,\n version: ARCHIVE_VERSION,\n },\n mediaPathnames,\n }\n } catch (err) {\n await client.query('ROLLBACK').catch(() => undefined)\n throw err\n }\n })\n}\n\nasync function readMediaPathnames(\n client: PgClient,\n schema: string,\n table: string,\n): Promise<string[]> {\n const { rows: cols } = await client.query<{ name: string }>(\n `SELECT a.attname AS name\n FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relname = $2 AND a.attnum > 0 AND NOT a.attisdropped`,\n [schema, table],\n )\n const names = new Set(cols.map((c) => c.name))\n if (!names.has('filename')) {\n return []\n }\n const fileCols = ['filename', ...[...names].filter((n) => /^sizes_.+_filename$/.test(n))]\n const prefixExpr = names.has('prefix') ? qi('prefix') : 'NULL::text'\n const out: string[] = []\n for (const col of fileCols) {\n const { rows } = await client.query<{ f: string; p: null | string }>(\n `SELECT ${prefixExpr} AS p, ${qi(col)}::text AS f\n FROM ${qualified(schema, table)}\n WHERE ${qi(col)} IS NOT NULL AND ${qi(col)}::text <> ''`,\n )\n for (const r of rows) {\n const prefix = (r.p ?? '').replace(/^\\/+|\\/+$/g, '')\n out.push(prefix ? `${prefix}/${r.f}` : r.f)\n }\n }\n return out\n}\n\nexport async function createBackup(\n payload: Payload,\n options: {\n backupsToKeep?: number\n /** Public (default) or private Vercel Blob access for the uploaded backup archive. */\n blobAccess?: BackupBlobAccessLevel\n /** Optional explicit Vercel Blob token (falls back to env inside @vercel/blob). */\n blobToken?: string\n cron?: boolean\n includeMedia?: boolean\n /**\n * Optional human-readable label for manual backups (appears in the backup list and is\n * searchable via the label filter). Ignored for cron backups.\n */\n label?: string\n /** Postgres table names to omit from the dump (e.g. manual backup UI). */\n skipCollections?: string[]\n taskId?: string\n } = {},\n): Promise<void> {\n const {\n backupsToKeep,\n blobToken,\n cron = false,\n includeMedia = false,\n skipCollections,\n taskId,\n } = options\n const label = cron ? '' : sanitizeBackupLabel(options.label)\n const blobAccess: BackupBlobAccessLevel = options.blobAccess ?? 'public'\n const token = resolveBlobToken(blobToken)\n const resolvedBackupsToKeep = backupsToKeep ?? (Number(process.env.BACKUPS_TO_KEEP) || 10)\n const storage = resolveBackupStorage({ blobAccess, blobToken: token })\n\n const currentHostname = getCurrentHostname()\n const currentDbName = getCurrentDbName()\n const type = cron ? 'cron' : 'manual'\n const t0 = Date.now()\n\n payload.logger.info(\n {\n type,\n blacklist: skipCollections?.length ?? 0,\n db: currentDbName,\n host: currentHostname,\n includeMedia,\n },\n '[backup] Starting backup',\n )\n if (taskId) {\n if (await isBackupTaskCancelled(payload, taskId)) {\n return\n }\n await updateBackupTask(payload, taskId, { message: 'Starting backup', status: 'running' })\n }\n\n if (cron) {\n const blobs = await storage.list('backups/cron-')\n const sorted = blobs.sort(\n (a, b) => new Date(b.uploadedAt).getTime() - new Date(a.uploadedAt).getTime(),\n )\n const oldest = sorted.slice(Math.max(0, resolvedBackupsToKeep - 1))\n if (oldest.length > 0) {\n payload.logger.info({ count: oldest.length }, '[backup] Pruning old cron backups')\n if (taskId) {\n if (await isBackupTaskCancelled(payload, taskId)) {\n throw new Error('Backup cancelled')\n }\n await updateBackupTask(payload, taskId, {\n message: `Pruning ${oldest.length} old cron backup${oldest.length === 1 ? '' : 's'}`,\n })\n }\n }\n for (const blob of oldest) {\n await storage.del({ pathname: blob.pathname, url: blob.url })\n payload.logger.info({ pathname: blob.pathname }, '[backup] Deleted old backup')\n }\n }\n\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Dumping tables' })\n }\n const { doc, mediaPathnames } = await dumpDatabase(payload, {\n collectMedia: includeMedia,\n onTable: async (table, rowCount) => {\n payload.logger.debug({ rows: rowCount, table }, '[backup] Table dumped')\n if (taskId) {\n if (await isBackupTaskCancelled(payload, taskId)) {\n throw new Error('Backup cancelled')\n }\n await updateBackupTask(payload, taskId, {\n message: `Dumped table ${table} (${rowCount} rows)`,\n })\n if (taskId && (await isBackupTaskCancelled(payload, taskId))) {\n throw new Error('Backup cancelled')\n }\n }\n },\n skipTables: skipCollections,\n })\n\n const databaseFile = serializeBackupDocument(doc)\n const includedTableCount = Object.keys(doc.tables).length\n const backupTimestampMs = Date.now()\n\n if (includeMedia) {\n payload.logger.info({ files: mediaPathnames.length }, '[backup] Bundling media files')\n if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Bundling media files into archive' })\n }\n }\n\n const backupFile =\n includeMedia ?\n await createMediaBackupFile(databaseFile, mediaPathnames, token, undefined, payload)\n : databaseFile\n if (taskId && (await isBackupTaskCancelled(payload, taskId))) {\n throw new Error('Backup cancelled')\n }\n const name = `backups/${createBlobName(\n type,\n currentDbName,\n currentHostname,\n includedTableCount,\n backupTimestampMs,\n includeMedia ? 'tar.gz' : 'json',\n label || undefined,\n )}`\n\n payload.logger.info({ name }, '[backup] Uploading backup to blob storage')\n const totalBytes =\n typeof backupFile === 'string' ? Buffer.byteLength(backupFile) : backupFile.byteLength\n let lastProgressUpdateAt = 0\n let progressWrites = Promise.resolve()\n const uploadAbortController = new AbortController()\n let cancellationPoll: ReturnType<typeof setInterval> | undefined\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: serializeBackupUploadProgress({ bytesUploaded: 0, totalBytes }),\n })\n cancellationPoll = setInterval(() => {\n void isBackupTaskCancelled(payload, taskId).then((cancelled) => {\n if (cancelled) {\n uploadAbortController.abort()\n }\n })\n }, 1000)\n }\n try {\n await storage.put(\n name,\n backupFile,\n taskId ?\n ({ loaded, total }) => {\n const now = Date.now()\n if (now - lastProgressUpdateAt < 500 && loaded < total) {\n return\n }\n lastProgressUpdateAt = now\n const progressTotalBytes = total > 0 ? total : totalBytes\n const message = serializeBackupUploadProgress({\n bytesUploaded: loaded,\n totalBytes: progressTotalBytes,\n })\n progressWrites = progressWrites.then(async () => {\n await updateBackupTask(payload, taskId, { message })\n })\n }\n : undefined,\n taskId ? uploadAbortController.signal : undefined,\n )\n } finally {\n if (cancellationPoll) {\n clearInterval(cancellationPoll)\n }\n }\n await progressWrites\n if (taskId && (await isBackupTaskCancelled(payload, taskId))) {\n await storage.del({ pathname: name })\n throw new Error('Backup cancelled')\n }\n if (taskId) {\n await updateBackupTask(payload, taskId, {\n message: serializeBackupUploadProgress({ bytesUploaded: totalBytes, totalBytes }),\n })\n }\n\n payload.logger.info({ name, durationMs: Date.now() - t0 }, '[backup] Backup complete')\n}\n"],"names":["list","serializeBackupUploadProgress","createBlobName","getCurrentDbName","getCurrentHostname","sanitizeBackupLabel","createTarGzip","readBackupBlobContentFlexible","getResolvedCronBackupSettings","resolveBackupBlobToken","getPgDb","listTables","qi","qualified","withClient","ARCHIVE_FORMAT","ARCHIVE_VERSION","DATABASE_FILE_NAME","MEDIA_PREFIX","serializeBackupDocument","getBackupStorageKind","resolveBackupStorage","resolveTableOwners","isBackupTaskCancelled","updateBackupTask","resolveBackupListToken","payload","explicitToken","t","trim","listBackups","options","kind","token","blobToken","resolveBlobToken","length","undefined","createMediaBackupFile","databaseFile","mediaPathnames","backupBlobToken","mediaListToken","envMedia","process","env","BLOB_READ_WRITE_TOKEN","tokenForMedia","unique","Set","filter","Boolean","mediaFiles","Promise","all","map","pathname","matchingFiles","limit","prefix","blob","blobs","find","b","logger","warn","filename","content","downloadUrl","name","err","Buffer","from","dumpDatabase","pool","schema","tableNameMap","skip","skipTables","client","query","rows","ver","allTables","tables","table","has","debug","rowCount","Number","n","onTable","collectMedia","owners","Object","keys","uploadSlugs","config","collections","c","upload","slug","owner","get","versions","push","readMediaPathnames","doc","createdAt","Date","toISOString","format","serverVersion","v","version","catch","cols","names","fileCols","test","prefixExpr","out","col","r","p","replace","f","createBackup","backupsToKeep","cron","includeMedia","skipCollections","taskId","label","blobAccess","resolvedBackupsToKeep","BACKUPS_TO_KEEP","storage","currentHostname","currentDbName","type","t0","now","info","blacklist","db","host","message","status","sorted","sort","a","uploadedAt","getTime","oldest","slice","Math","max","count","Error","del","url","includedTableCount","backupTimestampMs","files","backupFile","totalBytes","byteLength","lastProgressUpdateAt","progressWrites","resolve","uploadAbortController","AbortController","cancellationPoll","bytesUploaded","setInterval","then","cancelled","abort","put","loaded","total","progressTotalBytes","signal","clearInterval","durationMs"],"mappings":"AAEA,SAASA,IAAI,QAAQ,eAAc;AAEnC,SAASC,6BAA6B,QAAQ,gCAA+B;AAC7E,SACEC,cAAc,EACdC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,QACd,iBAAgB;AACvB,SAASC,aAAa,QAAQ,YAAW;AACzC,SAAqCC,6BAA6B,QAAQ,iBAAgB;AAC1F,SAASC,6BAA6B,EAAEC,sBAAsB,QAAQ,mBAAkB;AACxF,SAASC,OAAO,EAAEC,UAAU,EAAiBC,EAAE,EAAEC,SAAS,EAAEC,UAAU,QAAQ,OAAM;AACpF,SACEC,cAAc,EACdC,eAAe,EACfC,kBAAkB,EAClBC,YAAY,EAEZC,uBAAuB,QAClB,cAAa;AACpB,SAASC,oBAAoB,EAAEC,oBAAoB,QAAQ,YAAW;AACtE,SAASC,kBAAkB,QAAQ,gBAAe;AAClD,SAASC,qBAAqB,EAAEC,gBAAgB,QAAQ,iBAAgB;AAExE,SAASP,kBAAkB,QAAQ,cAAa;AAEhD;;;;CAIC,GACD,OAAO,eAAeQ,uBACpBC,OAAgB,EAChBC,aAAsB;IAEtB,MAAMC,IAAID,eAAeE;IACzB,IAA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CAAC;gBACnC,MAAMxJ,iBAAiBE,SAAS0G,QAAQ;oBAAEe;gBAAQ;YACpD;QACF,IACA9G,WACF+F,SAASuC,sBAAsBY,MAAM,GAAGlJ;IAE5C,SAAU;QACR,IAAIwI,kBAAkB;YACpBW,cAAcX;QAChB;IACF;IACA,MAAMJ;IACN,IAAIrC,UAAW,MAAM7G,sBAAsBG,SAAS0G,SAAU;QAC5D,MAAMK,QAAQuB,GAAG,CAAC;YAAExG,UAAUa;QAAK;QACnC,MAAM,IAAI0F,MAAM;IAClB;IACA,IAAI3B,QAAQ;QACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;YACtCe,SAASlJ,8BAA8B;gBAAE6K,eAAeR;gBAAYA;YAAW;QACjF;IACF;IAEA5I,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;QAAE1E;QAAMoH,YAAY5E,KAAKiC,GAAG,KAAKD;IAAG,GAAG;AAC7D"}
@@ -54,4 +54,4 @@ export declare function readBackupBlobContentFlexible(pathname: string, download
54
54
  export declare function putBackupBlobContent(pathname: string, body: Buffer | string | Uint8Array, token: string | undefined, access: BackupBlobAccessLevel, onProgress?: (progress: {
55
55
  loaded: number;
56
56
  total: number;
57
- }) => void): Promise<BackupBlobAccessLevel>;
57
+ }) => void, signal?: AbortSignal): Promise<BackupBlobAccessLevel>;
@@ -133,7 +133,7 @@ export async function bufferFromWebReadableStream(stream) {
133
133
  * if the Vercel Blob store rejects the preferred one (e.g. legacy public-only stores reject
134
134
  * `access: 'private'`). Returns the effective access level that succeeded so callers can log/track
135
135
  * it; throws the original error if both attempts fail.
136
- */ export async function putBackupBlobContent(pathname, body, token, access, onProgress) {
136
+ */ export async function putBackupBlobContent(pathname, body, token, access, onProgress, signal) {
137
137
  const order = access === 'private' ? [
138
138
  'private',
139
139
  'public'
@@ -148,6 +148,9 @@ export async function bufferFromWebReadableStream(stream) {
148
148
  access: attempt,
149
149
  addRandomSuffix: false,
150
150
  allowOverwrite: true,
151
+ ...signal ? {
152
+ abortSignal: signal
153
+ } : {},
151
154
  onUploadProgress: onProgress,
152
155
  ...token ? {
153
156
  token
@@ -155,6 +158,9 @@ export async function bufferFromWebReadableStream(stream) {
155
158
  });
156
159
  return attempt;
157
160
  } catch (error) {
161
+ if (signal?.aborted) {
162
+ throw error;
163
+ }
158
164
  if (firstError === undefined) {
159
165
  firstError = error;
160
166
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/backupBlobIO.ts"],"sourcesContent":["import { put } from '@vercel/blob'\n\n/** Vercel Blob access for backup archives under `backups/`. */\nexport type BackupBlobAccessLevel = 'private' | 'public'\n\n/**\n * Returns the blob pathname (no leading slash) for a trusted Vercel Blob HTTPS URL, or null.\n * The URL's path component is percent-decoded once so the result matches the literal pathname\n * stored by Vercel Blob (e.g. blobs whose own pathname contains `%2F` are served from a URL that\n * double-encodes it to `%252F`).\n */\nexport function vercelBlobPathnameFromUrl(urlStr: string): null | string {\n try {\n const u = new URL(urlStr)\n if (u.protocol !== 'https:') {\n return null\n }\n if (!u.hostname.endsWith('.blob.vercel-storage.com')) {\n return null\n }\n const raw = u.pathname.replace(/^\\//, '')\n if (raw.length === 0) {\n return null\n }\n try {\n return decodeURIComponent(raw)\n } catch {\n return raw\n }\n } catch {\n return null\n }\n}\n\nexport function isTrustedBackupBlobReference(urlStr: string, expectedPathname: string): boolean {\n const fromUrl = vercelBlobPathnameFromUrl(urlStr)\n return Boolean(fromUrl && fromUrl === expectedPathname)\n}\n\n/** True when the URL points to any Vercel Blob host (public or private). */\nfunction isVercelBlobHost(urlStr: string): boolean {\n try {\n const u = new URL(urlStr)\n return u.protocol === 'https:' && u.hostname.endsWith('.blob.vercel-storage.com')\n } catch {\n return false\n }\n}\n\n/**\n * Fetches a Vercel Blob URL with the Bearer token attached when the host belongs to Vercel Blob.\n * Works transparently for public stores (token is ignored) and private stores (token is required).\n * Tokens are never sent to non-Vercel hosts.\n */\nasync function fetchBackupBlobUrl(url: string, token: string): Promise<Response> {\n const init: RequestInit | undefined =\n token && isVercelBlobHost(url) ? { headers: { authorization: `Bearer ${token}` } } : undefined\n return fetch(url, init)\n}\n\nexport type BackupBlobDownloadStream = {\n contentType: string\n stream: ReadableStream<Uint8Array>\n}\n\n/**\n * Opens a readable stream for a backup object (public or private). Prefers the `downloadUrl` /\n * `blobUrl` returned by `list()` because Vercel Blob already encodes the pathname correctly there\n * (some legacy backups store literal `%2F` sequences inside the pathname, which the SDK's\n * pathname-to-URL construction would misinterpret).\n */\nexport async function streamBackupBlobForDownload(options: {\n blobUrl?: null | string\n downloadUrl?: null | string\n pathname: string\n preferredAccess: BackupBlobAccessLevel\n token: string\n}): Promise<BackupBlobDownloadStream | null> {\n const { blobUrl, downloadUrl, pathname, token } = options\n const candidates: string[] = []\n if (downloadUrl && isTrustedBackupBlobReference(downloadUrl, pathname)) {\n candidates.push(downloadUrl)\n }\n if (blobUrl && isTrustedBackupBlobReference(blobUrl, pathname)) {\n candidates.push(blobUrl)\n }\n\n for (const target of candidates) {\n try {\n const res = await fetchBackupBlobUrl(target, token)\n if (res.ok && res.body) {\n return {\n contentType: res.headers.get('content-type') || 'application/octet-stream',\n stream: res.body,\n }\n }\n } catch {\n /* try next candidate */\n }\n }\n\n return null\n}\n\nexport async function bufferFromWebReadableStream(\n stream: ReadableStream<Uint8Array>,\n): Promise<Buffer> {\n const reader = stream.getReader()\n const chunks: Buffer[] = []\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n if (value) {\n chunks.push(Buffer.from(value))\n }\n }\n return Buffer.concat(chunks)\n}\n\n/**\n * Read a backup blob using the trusted `downloadUrl` returned by `list()`. The Bearer token is\n * always attached for Vercel Blob hosts; this works for public blobs (token ignored) and is\n * required for private blobs.\n */\nexport async function readBackupBlobContent(options: {\n /** Kept for API compatibility — the fetch path is the same for public and private stores. */\n access: BackupBlobAccessLevel\n downloadUrl: string\n pathname: string\n token: string\n}): Promise<Buffer> {\n const { downloadUrl, pathname, token } = options\n const res = await fetchBackupBlobUrl(downloadUrl, token)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n throw new Error(`Failed to read backup blob (${pathname}): HTTP ${res.status}`)\n}\n\n/**\n * Flexible read used during restore/preview/transfer where the source store visibility may differ\n * from the new one. Always tries authenticated access first (correct for private stores and\n * harmless for public ones). Falls back to anonymous fetch only when the URL is not a Vercel\n * Blob URL, so tokens never leak to arbitrary hosts.\n */\nexport async function readBackupBlobContentFlexible(\n pathname: string,\n downloadUrl: string,\n token: string,\n _sourceAccessHint?: BackupBlobAccessLevel,\n): Promise<Buffer> {\n try {\n const res = await fetchBackupBlobUrl(downloadUrl, token)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n } catch {\n /* try anonymous fallback */\n }\n\n if (!isVercelBlobHost(downloadUrl)) {\n try {\n const res = await fetch(downloadUrl)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n } catch {\n /* fall through to error */\n }\n }\n\n throw new Error(`Failed to read backup blob ${pathname}`)\n}\n\n/**\n * Uploads a backup blob with the preferred access level and transparently retries the other level\n * if the Vercel Blob store rejects the preferred one (e.g. legacy public-only stores reject\n * `access: 'private'`). Returns the effective access level that succeeded so callers can log/track\n * it; throws the original error if both attempts fail.\n */\nexport async function putBackupBlobContent(\n pathname: string,\n body: Buffer | string | Uint8Array,\n token: string | undefined,\n access: BackupBlobAccessLevel,\n onProgress?: (progress: { loaded: number; total: number }) => void,\n): Promise<BackupBlobAccessLevel> {\n const order: BackupBlobAccessLevel[] =\n access === 'private' ? ['private', 'public'] : ['public', 'private']\n let firstError: unknown\n for (const attempt of order) {\n try {\n await put(pathname, body, {\n access: attempt,\n addRandomSuffix: false,\n allowOverwrite: true,\n onUploadProgress: onProgress,\n ...(token ? { token } : {}),\n })\n return attempt\n } catch (error) {\n if (firstError === undefined) {\n firstError = error\n }\n if (!looksLikeAccessModeMismatch(error)) {\n throw error\n }\n }\n }\n throw firstError instanceof Error ? firstError : new Error('Failed to upload backup blob')\n}\n\n/** Heuristic for Vercel Blob errors that indicate the store rejects the chosen access level. */\nfunction looksLikeAccessModeMismatch(error: unknown): boolean {\n const msg =\n error instanceof Error ? error.message\n : typeof error === 'string' ? error\n : error == null ? ''\n : (() => {\n try {\n return JSON.stringify(error)\n } catch {\n return 'unknown'\n }\n })()\n const lower = msg.toLowerCase()\n return (\n lower.includes('access') &&\n (lower.includes('public') ||\n lower.includes('private') ||\n lower.includes('not support') ||\n lower.includes('invalid'))\n )\n}\n"],"names":["put","vercelBlobPathnameFromUrl","urlStr","u","URL","protocol","hostname","endsWith","raw","pathname","replace","length","decodeURIComponent","isTrustedBackupBlobReference","expectedPathname","fromUrl","Boolean","isVercelBlobHost","fetchBackupBlobUrl","url","token","init","headers","authorization","undefined","fetch","streamBackupBlobForDownload","options","blobUrl","downloadUrl","candidates","push","target","res","ok","body","contentType","get","stream","bufferFromWebReadableStream","reader","getReader","chunks","done","value","read","Buffer","from","concat","readBackupBlobContent","arrayBuffer","Error","status","readBackupBlobContentFlexible","_sourceAccessHint","putBackupBlobContent","access","onProgress","order","firstError","attempt","addRandomSuffix","allowOverwrite","onUploadProgress","error","looksLikeAccessModeMismatch","msg","message","JSON","stringify","lower","toLowerCase","includes"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAKlC;;;;;CAKC,GACD,OAAO,SAASC,0BAA0BC,MAAc;IACtD,IAAI;QACF,MAAMC,IAAI,IAAIC,IAAIF;QAClB,IAAIC,EAAEE,QAAQ,KAAK,UAAU;YAC3B,OAAO;QACT;QACA,IAAI,CAACF,EAAEG,QAAQ,CAACC,QAAQ,CAAC,6BAA6B;YACpD,OAAO;QACT;QACA,MAAMC,MAAML,EAAEM,QAAQ,CAACC,OAAO,CAAC,OAAO;QACtC,IAAIF,IAAIG,MAAM,KAAK,GAAG;YACpB,OAAO;QACT;QACA,IAAI;YACF,OAAOC,mBAAmBJ;QAC5B,EAAE,OAAM;YACN,OAAOA;QACT;IACF,EAAE,OAAM;QACN,OAAO;IACT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EACzBoC,MAA6B,EAC7BC,UAAkE;IAElE,MAAMC,QACJF,WAAW,YAAY;QAAC;QAAW;KAAS,GAAG;QAAC;QAAU;KAAU;IACtE,IAAIG;IACJ,KAAK,MAAMC,WAAWF,MAAO;QAC3B,IAAI;YACF,MAAM1D,IAAIS,UAAU0B,MAAM;gBACxBqB,QAAQI;gBACRC,iBAAiB;gBACjBC,gBAAgB;gBAChBC,kBAAkBN;gBAClB,GAAIrC,QAAQ;oBAAEA;gBAAM,IAAI,CAAC,CAAC;YAC5B;YACA,OAAOwC;QACT,EAAE,OAAOI,OAAO;YACd,IAAIL,eAAenC,WAAW;gBAC5BmC,aAAaK;YACf;YACA,IAAI,CAACC,4BAA4BD,QAAQ;gBACvC,MAAMA;YACR;QACF;IACF;IACA,MAAML,sBAAsBR,QAAQQ,aAAa,IAAIR,MAAM;AAC7D;AAEA,8FAA8F,GAC9F,SAASc,4BAA4BD,KAAc;IACjD,MAAME,MACJF,iBAAiBb,QAAQa,MAAMG,OAAO,GACpC,OAAOH,UAAU,WAAWA,QAC5BA,SAAS,OAAO,KAChB,AAAC,CAAA;QACC,IAAI;YACF,OAAOI,KAAKC,SAAS,CAACL;QACxB,EAAE,OAAM;YACN,OAAO;QACT;IACF,CAAA;IACJ,MAAMM,QAAQJ,IAAIK,WAAW;IAC7B,OACED,MAAME,QAAQ,CAAC,aACdF,CAAAA,MAAME,QAAQ,CAAC,aACdF,MAAME,QAAQ,CAAC,cACfF,MAAME,QAAQ,CAAC,kBACfF,MAAME,QAAQ,CAAC,UAAS;AAE9B"}
1
+ {"version":3,"sources":["../../src/core/backupBlobIO.ts"],"sourcesContent":["import { put } from '@vercel/blob'\n\n/** Vercel Blob access for backup archives under `backups/`. */\nexport type BackupBlobAccessLevel = 'private' | 'public'\n\n/**\n * Returns the blob pathname (no leading slash) for a trusted Vercel Blob HTTPS URL, or null.\n * The URL's path component is percent-decoded once so the result matches the literal pathname\n * stored by Vercel Blob (e.g. blobs whose own pathname contains `%2F` are served from a URL that\n * double-encodes it to `%252F`).\n */\nexport function vercelBlobPathnameFromUrl(urlStr: string): null | string {\n try {\n const u = new URL(urlStr)\n if (u.protocol !== 'https:') {\n return null\n }\n if (!u.hostname.endsWith('.blob.vercel-storage.com')) {\n return null\n }\n const raw = u.pathname.replace(/^\\//, '')\n if (raw.length === 0) {\n return null\n }\n try {\n return decodeURIComponent(raw)\n } catch {\n return raw\n }\n } catch {\n return null\n }\n}\n\nexport function isTrustedBackupBlobReference(urlStr: string, expectedPathname: string): boolean {\n const fromUrl = vercelBlobPathnameFromUrl(urlStr)\n return Boolean(fromUrl && fromUrl === expectedPathname)\n}\n\n/** True when the URL points to any Vercel Blob host (public or private). */\nfunction isVercelBlobHost(urlStr: string): boolean {\n try {\n const u = new URL(urlStr)\n return u.protocol === 'https:' && u.hostname.endsWith('.blob.vercel-storage.com')\n } catch {\n return false\n }\n}\n\n/**\n * Fetches a Vercel Blob URL with the Bearer token attached when the host belongs to Vercel Blob.\n * Works transparently for public stores (token is ignored) and private stores (token is required).\n * Tokens are never sent to non-Vercel hosts.\n */\nasync function fetchBackupBlobUrl(url: string, token: string): Promise<Response> {\n const init: RequestInit | undefined =\n token && isVercelBlobHost(url) ? { headers: { authorization: `Bearer ${token}` } } : undefined\n return fetch(url, init)\n}\n\nexport type BackupBlobDownloadStream = {\n contentType: string\n stream: ReadableStream<Uint8Array>\n}\n\n/**\n * Opens a readable stream for a backup object (public or private). Prefers the `downloadUrl` /\n * `blobUrl` returned by `list()` because Vercel Blob already encodes the pathname correctly there\n * (some legacy backups store literal `%2F` sequences inside the pathname, which the SDK's\n * pathname-to-URL construction would misinterpret).\n */\nexport async function streamBackupBlobForDownload(options: {\n blobUrl?: null | string\n downloadUrl?: null | string\n pathname: string\n preferredAccess: BackupBlobAccessLevel\n token: string\n}): Promise<BackupBlobDownloadStream | null> {\n const { blobUrl, downloadUrl, pathname, token } = options\n const candidates: string[] = []\n if (downloadUrl && isTrustedBackupBlobReference(downloadUrl, pathname)) {\n candidates.push(downloadUrl)\n }\n if (blobUrl && isTrustedBackupBlobReference(blobUrl, pathname)) {\n candidates.push(blobUrl)\n }\n\n for (const target of candidates) {\n try {\n const res = await fetchBackupBlobUrl(target, token)\n if (res.ok && res.body) {\n return {\n contentType: res.headers.get('content-type') || 'application/octet-stream',\n stream: res.body,\n }\n }\n } catch {\n /* try next candidate */\n }\n }\n\n return null\n}\n\nexport async function bufferFromWebReadableStream(\n stream: ReadableStream<Uint8Array>,\n): Promise<Buffer> {\n const reader = stream.getReader()\n const chunks: Buffer[] = []\n while (true) {\n const { done, value } = await reader.read()\n if (done) {\n break\n }\n if (value) {\n chunks.push(Buffer.from(value))\n }\n }\n return Buffer.concat(chunks)\n}\n\n/**\n * Read a backup blob using the trusted `downloadUrl` returned by `list()`. The Bearer token is\n * always attached for Vercel Blob hosts; this works for public blobs (token ignored) and is\n * required for private blobs.\n */\nexport async function readBackupBlobContent(options: {\n /** Kept for API compatibility — the fetch path is the same for public and private stores. */\n access: BackupBlobAccessLevel\n downloadUrl: string\n pathname: string\n token: string\n}): Promise<Buffer> {\n const { downloadUrl, pathname, token } = options\n const res = await fetchBackupBlobUrl(downloadUrl, token)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n throw new Error(`Failed to read backup blob (${pathname}): HTTP ${res.status}`)\n}\n\n/**\n * Flexible read used during restore/preview/transfer where the source store visibility may differ\n * from the new one. Always tries authenticated access first (correct for private stores and\n * harmless for public ones). Falls back to anonymous fetch only when the URL is not a Vercel\n * Blob URL, so tokens never leak to arbitrary hosts.\n */\nexport async function readBackupBlobContentFlexible(\n pathname: string,\n downloadUrl: string,\n token: string,\n _sourceAccessHint?: BackupBlobAccessLevel,\n): Promise<Buffer> {\n try {\n const res = await fetchBackupBlobUrl(downloadUrl, token)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n } catch {\n /* try anonymous fallback */\n }\n\n if (!isVercelBlobHost(downloadUrl)) {\n try {\n const res = await fetch(downloadUrl)\n if (res.ok) {\n return Buffer.from(await res.arrayBuffer())\n }\n } catch {\n /* fall through to error */\n }\n }\n\n throw new Error(`Failed to read backup blob ${pathname}`)\n}\n\n/**\n * Uploads a backup blob with the preferred access level and transparently retries the other level\n * if the Vercel Blob store rejects the preferred one (e.g. legacy public-only stores reject\n * `access: 'private'`). Returns the effective access level that succeeded so callers can log/track\n * it; throws the original error if both attempts fail.\n */\nexport async function putBackupBlobContent(\n pathname: string,\n body: Buffer | string | Uint8Array,\n token: string | undefined,\n access: BackupBlobAccessLevel,\n onProgress?: (progress: { loaded: number; total: number }) => void,\n signal?: AbortSignal,\n): Promise<BackupBlobAccessLevel> {\n const order: BackupBlobAccessLevel[] =\n access === 'private' ? ['private', 'public'] : ['public', 'private']\n let firstError: unknown\n for (const attempt of order) {\n try {\n await put(pathname, body, {\n access: attempt,\n addRandomSuffix: false,\n allowOverwrite: true,\n ...(signal ? { abortSignal: signal } : {}),\n onUploadProgress: onProgress,\n ...(token ? { token } : {}),\n })\n return attempt\n } catch (error) {\n if (signal?.aborted) {\n throw error\n }\n if (firstError === undefined) {\n firstError = error\n }\n if (!looksLikeAccessModeMismatch(error)) {\n throw error\n }\n }\n }\n throw firstError instanceof Error ? firstError : new Error('Failed to upload backup blob')\n}\n\n/** Heuristic for Vercel Blob errors that indicate the store rejects the chosen access level. */\nfunction looksLikeAccessModeMismatch(error: unknown): boolean {\n const msg =\n error instanceof Error ? error.message\n : typeof error === 'string' ? error\n : error == null ? ''\n : (() => {\n try {\n return JSON.stringify(error)\n } catch {\n return 'unknown'\n }\n })()\n const lower = msg.toLowerCase()\n return (\n lower.includes('access') &&\n (lower.includes('public') ||\n lower.includes('private') ||\n lower.includes('not support') ||\n lower.includes('invalid'))\n )\n}\n"],"names":["put","vercelBlobPathnameFromUrl","urlStr","u","URL","protocol","hostname","endsWith","raw","pathname","replace","length","decodeURIComponent","isTrustedBackupBlobReference","expectedPathname","fromUrl","Boolean","isVercelBlobHost","fetchBackupBlobUrl","url","token","init","headers","authorization","undefined","fetch","streamBackupBlobForDownload","options","blobUrl","downloadUrl","candidates","push","target","res","ok","body","contentType","get","stream","bufferFromWebReadableStream","reader","getReader","chunks","done","value","read","Buffer","from","concat","readBackupBlobContent","arrayBuffer","Error","status","readBackupBlobContentFlexible","_sourceAccessHint","putBackupBlobContent","access","onProgress","signal","order","firstError","attempt","addRandomSuffix","allowOverwrite","abortSignal","onUploadProgress","error","aborted","looksLikeAccessModeMismatch","msg","message","JSON","stringify","lower","toLowerCase","includes"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAKlC;;;;;CAKC,GACD,OAAO,SAASC,0BAA0BC,MAAc;IACtD,IAAI;QACF,MAAMC,IAAI,IAAIC,IAAIF;QAClB,IAAIC,EAAEE,QAAQ,KAAK,UAAU;YAC3B,OAAO;QACT;QACA,IAAI,CAACF,EAAEG,QAAQ,CAACC,QAAQ,CAAC,6BAA6B;YACpD,OAAO;QACT;QACA,MAAMC,MAAML,EAAEM,QAAQ,CAACC,OAAO,CAAC,OAAO;QACtC,IAAIF,IAAIG,MAAM,KAAK,GAAG;YACpB,OAAO;QACT;QACA,IAAI;YACF,OAAOC,mBAAmBJ;QAC5B,EAAE,OAAM;YACN,OAAOA;QACT;IACF,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,OAAO,SAASK,6BAA6BX,MAAc,EAAEY,gBAAwB;IACnF,MAAMC,UAAUd,0BAA0BC;IAC1C,OAAOc,QAAQD,WAAWA,YAAYD;AACxC;AAEA,0EAA0E,GAC1E,SAASG,iBAAiBf,MAAc;IACtC,IAAI;QACF,MAAMC,IAAI,IAAIC,IAAIF;QAClB,OAAOC,EAAEE,QAAQ,KAAK,YAAYF,EAAEG,QAAQ,CAACC,QAAQ,CAAC;IACxD,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;;CAIC,GACD,eAAeW,mBAAmBC,GAAW,EAAEC,KAAa;IAC1D,MAAMC,OACJD,SAASH,iBAAiBE,OAA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AAE,OAAOK,OAAO;YACd,IAAIR,QAAQS,SAAS;gBACnB,MAAMD;YACR;YACA,IAAIN,eAAepC,WAAW;gBAC5BoC,aAAaM;YACf;YACA,IAAI,CAACE,4BAA4BF,QAAQ;gBACvC,MAAMA;YACR;QACF;IACF;IACA,MAAMN,sBAAsBT,QAAQS,aAAa,IAAIT,MAAM;AAC7D;AAEA,8FAA8F,GAC9F,SAASiB,4BAA4BF,KAAc;IACjD,MAAMG,MACJH,iBAAiBf,QAAQe,MAAMI,OAAO,GACpC,OAAOJ,UAAU,WAAWA,QAC5BA,SAAS,OAAO,KAChB,AAAC,CAAA;QACC,IAAI;YACF,OAAOK,KAAKC,SAAS,CAACN;QACxB,EAAE,OAAM;YACN,OAAO;QACT;IACF,CAAA;IACJ,MAAMO,QAAQJ,IAAIK,WAAW;IAC7B,OACED,MAAME,QAAQ,CAAC,aACdF,CAAAA,MAAME,QAAQ,CAAC,aACdF,MAAME,QAAQ,CAAC,cACfF,MAAME,QAAQ,CAAC,kBACfF,MAAME,QAAQ,CAAC,UAAS;AAE9B"}
@@ -29,7 +29,7 @@ export declare class S3BackupStorage implements BackupStorageAdapter {
29
29
  put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: {
30
30
  loaded: number;
31
31
  total: number;
32
- }) => void): Promise<{
32
+ }) => void, signal?: AbortSignal): Promise<{
33
33
  pathname: string;
34
34
  url: string;
35
35
  }>;
@@ -147,7 +147,7 @@ function contentTypeFor(pathname) {
147
147
  return null;
148
148
  }
149
149
  }
150
- async put(pathname, body, onProgress) {
150
+ async put(pathname, body, onProgress, signal) {
151
151
  const { Upload } = await import('@aws-sdk/lib-storage');
152
152
  const client = await this.client();
153
153
  const key = this.toKey(pathname);
@@ -170,7 +170,21 @@ function contentTypeFor(pathname) {
170
170
  });
171
171
  });
172
172
  }
173
- await upload.done();
173
+ const abort = ()=>{
174
+ void upload.abort();
175
+ };
176
+ if (signal?.aborted) {
177
+ abort();
178
+ } else {
179
+ signal?.addEventListener('abort', abort, {
180
+ once: true
181
+ });
182
+ }
183
+ try {
184
+ await upload.done();
185
+ } finally{
186
+ signal?.removeEventListener('abort', abort);
187
+ }
174
188
  return {
175
189
  pathname,
176
190
  url: await this.presignGet(key)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/storage/s3.ts"],"sourcesContent":["import type { S3Client } from '@aws-sdk/client-s3'\n\nimport type { BackupS3Config } from './config'\nimport type {\n BackupStorageAdapter,\n BackupStorageObject,\n BackupStorageRef,\n BackupStorageValidation,\n} from './types'\n\n/** Presigned download URLs are valid this long — long enough to start a restore/download. */\nconst SIGNED_URL_TTL_SECONDS = 3600\n\ntype S3PresignerModule = {\n getSignedUrl: (\n client: S3Client,\n command: unknown,\n options: { expiresIn: number },\n ) => Promise<string>\n}\n\nfunction contentTypeFor(pathname: string): string {\n if (pathname.endsWith('.json')) {\n return 'application/json'\n }\n if (pathname.endsWith('.gz') || pathname.endsWith('.tar.gz')) {\n return 'application/gzip'\n }\n return 'application/octet-stream'\n}\n\n/**\n * AWS S3 backup target. The same implementation serves any S3-compatible store (Cloudflare R2,\n * MinIO, …) — only the `endpoint`/`forcePathStyle` config differs, never the code. The AWS SDK is\n * loaded lazily via dynamic import so it stays an optional dependency for Vercel-only installs.\n */\nexport class S3BackupStorage implements BackupStorageAdapter {\n private readonly cfg: BackupS3Config\n\n private clientPromise: null | Promise<S3Client> = null\n private presignerPromise: null | Promise<S3PresignerModule> = null\n readonly kind = 's3'\n\n constructor(cfg: BackupS3Config) {\n this.cfg = cfg\n }\n\n private async buildClient(): Promise<S3Client> {\n const { S3Client } = await this.sdk()\n const { accessKeyId, secretAccessKey, sessionToken } = this.cfg\n return new S3Client({\n ...(this.cfg.endpoint ? { endpoint: this.cfg.endpoint } : {}),\n forcePathStyle: this.cfg.forcePathStyle,\n region: this.cfg.region,\n // When keys are absent, fall back to the SDK's default credential provider chain\n // (env vars, shared config, instance/role credentials).\n ...(accessKeyId && secretAccessKey ?\n { credentials: { accessKeyId, secretAccessKey, sessionToken } }\n : {}),\n })\n }\n\n private async client(): Promise<S3Client> {\n if (!this.clientPromise) {\n this.clientPromise = this.buildClient()\n }\n return this.clientPromise\n }\n\n /** Strip the configured key prefix, returning the provider-agnostic `backups/...` pathname. */\n private fromKey(key: string): string {\n if (!this.cfg.prefix) {\n return key\n }\n const lead = `${this.cfg.prefix}/`\n return key.startsWith(lead) ? key.slice(lead.length) : key\n }\n\n private async presigner() {\n if (!this.presignerPromise) {\n this.presignerPromise = import('@aws-sdk/s3-request-presigner')\n }\n return this.presignerPromise\n }\n\n private async presignGet(key: string): Promise<string> {\n const { GetObjectCommand } = await this.sdk()\n const { getSignedUrl } = await this.presigner()\n const client = await this.client()\n return getSignedUrl(client, new GetObjectCommand({ Bucket: this.cfg.bucket, Key: key }), {\n expiresIn: SIGNED_URL_TTL_SECONDS,\n })\n }\n\n private async sdk() {\n try {\n return await import('@aws-sdk/client-s3')\n } catch {\n throw new Error(\n 'BACKUP_STORAGE=s3 requires the AWS SDK. Install it with: ' +\n 'pnpm add @aws-sdk/client-s3 @aws-sdk/lib-storage @aws-sdk/s3-request-presigner',\n )\n }\n }\n\n /** Prepend the configured key prefix to a provider-agnostic `backups/...` pathname. */\n private toKey(pathname: string): string {\n return this.cfg.prefix ? `${this.cfg.prefix}/${pathname}` : pathname\n }\n\n async del(ref: BackupStorageRef): Promise<void> {\n const { DeleteObjectCommand } = await this.sdk()\n const client = await this.client()\n await client.send(\n new DeleteObjectCommand({ Bucket: this.cfg.bucket, Key: this.toKey(ref.pathname) }),\n )\n }\n\n async list(prefix: string): Promise<BackupStorageObject[]> {\n const { ListObjectsV2Command } = await this.sdk()\n const client = await this.client()\n const keyPrefix = this.toKey(prefix)\n\n const objects: BackupStorageObject[] = []\n let continuationToken: string | undefined\n do {\n const res = await client.send(\n new ListObjectsV2Command({\n Bucket: this.cfg.bucket,\n ContinuationToken: continuationToken,\n Prefix: keyPrefix,\n }),\n )\n const pageEntries: Array<{\n key: string\n pathname: string\n size: number\n uploadedAt: Date\n }> = []\n for (const obj of res.Contents ?? []) {\n if (!obj.Key) {\n continue\n }\n pageEntries.push({\n key: obj.Key,\n pathname: this.fromKey(obj.Key),\n size: obj.Size ?? 0,\n uploadedAt: obj.LastModified ?? new Date(0),\n })\n }\n const signed = await Promise.all(\n pageEntries.map(async (entry) => {\n const url = await this.presignGet(entry.key)\n return {\n downloadUrl: url,\n pathname: entry.pathname,\n size: entry.size,\n uploadedAt: entry.uploadedAt,\n url,\n }\n }),\n )\n objects.push(...signed)\n continuationToken = res.IsTruncated ? res.NextContinuationToken : undefined\n } while (continuationToken)\n\n return objects\n }\n\n async openDownloadStream(ref: BackupStorageRef) {\n const { GetObjectCommand } = await this.sdk()\n const client = await this.client()\n try {\n const res = await client.send(\n new GetObjectCommand({ Bucket: this.cfg.bucket, Key: this.toKey(ref.pathname) }),\n )\n if (!res.Body) {\n return null\n }\n const stream = (\n res.Body as { transformToWebStream: () => ReadableStream<Uint8Array> }\n ).transformToWebStream()\n return {\n contentType: res.ContentType || contentTypeFor(ref.pathname),\n stream,\n }\n } catch {\n return null\n }\n }\n\n async put(\n pathname: string,\n body: Buffer | string | Uint8Array,\n onProgress?: (progress: { loaded: number; total: number }) => void,\n ) {\n const { Upload } = await import('@aws-sdk/lib-storage')\n const client = await this.client()\n const key = this.toKey(pathname)\n const uploadBody = typeof body === 'string' ? Buffer.from(body) : body\n const total = uploadBody.byteLength\n const upload = new Upload({\n client,\n params: {\n Body: uploadBody,\n Bucket: this.cfg.bucket,\n ContentType: contentTypeFor(pathname),\n Key: key,\n },\n })\n if (onProgress) {\n upload.on('httpUploadProgress', (progress) => {\n onProgress({ loaded: progress.loaded ?? 0, total })\n })\n }\n await upload.done()\n return { pathname, url: await this.presignGet(key) }\n }\n\n async read(ref: BackupStorageRef): Promise<Buffer> {\n const { GetObjectCommand } = await this.sdk()\n const client = await this.client()\n const res = await client.send(\n new GetObjectCommand({ Bucket: this.cfg.bucket, Key: this.toKey(ref.pathname) }),\n )\n if (!res.Body) {\n throw new Error(`Failed to read backup object (${ref.pathname}): empty body`)\n }\n const bytes = await (\n res.Body as { transformToByteArray: () => Promise<Uint8Array> }\n ).transformToByteArray()\n return Buffer.from(bytes)\n }\n\n async validate(): Promise<BackupStorageValidation> {\n try {\n const { HeadBucketCommand } = await this.sdk()\n const client = await this.client()\n await client.send(new HeadBucketCommand({ Bucket: this.cfg.bucket }))\n return { ok: true }\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : 'S3 bucket not reachable',\n ok: false,\n }\n }\n }\n}\n"],"names":["SIGNED_URL_TTL_SECONDS","contentTypeFor","pathname","endsWith","S3BackupStorage","cfg","clientPromise","presignerPromise","kind","buildClient","S3Client","sdk","accessKeyId","secretAccessKey","sessionToken","endpoint","forcePathStyle","region","credentials","client","fromKey","key","prefix","lead","startsWith","slice","length","presigner","presignGet","GetObjectCommand","getSignedUrl","Bucket","bucket","Key","expiresIn","Error","toKey","del","ref","DeleteObjectCommand","send","list","ListObjectsV2Command","keyPrefix","objects","continuationToken","res","ContinuationToken","Prefix","pageEntries","obj","Contents","push","size","Size","uploadedAt","LastModified","Date","signed","Promise","all","map","entry","url","downloadUrl","IsTruncated","NextContinuationToken","undefined","openDownloadStream","Body","stream","transformToWebStream","contentType","ContentType","put","body","onProgress","Upload","uploadBody","Buffer","from","total","byteLength","upload","params","on","progress","loaded","done","read","bytes","transformToByteArray","validate","HeadBucketCommand","ok","error","message"],"mappings":"AAUA,2FAA2F,GAC3F,MAAMA,yBAAyB;AAU/B,SAASC,eAAeC,QAAgB;IACtC,IAAIA,SAASC,QAAQ,CAAC,UAAU;QAC9B,OAAO;IACT;IACA,IAAID,SAASC,QAAQ,CAAC,UAAUD,SAASC,QAAQ,CAAC,YAAY;QAC5D,OAAO;IACT;IACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMC;IACMC,IAAmB;IAE5BC,gBAA0C,KAAI;IAC9CC,mBAAsD,KAAI;IACzDC,OAA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,IAAIpC,QAAQ;QAAE;QAEhF,IAAI,CAAC4C,IAAIuB,IAAI,EAAE;YACb,MAAM,IAAIlC,MAAM,CAAC,8BAA8B,EAAEG,IAAIpC,QAAQ,CAAC,aAAa,CAAC;QAC9E;QACA,MAAMwF,QAAQ,MAAM,AAClB5C,IAAIuB,IAAI,CACRsB,oBAAoB;QACtB,OAAOZ,OAAOC,IAAI,CAACU;IACrB;IAEA,MAAME,WAA6C;QACjD,IAAI;YACF,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,IAAI,CAAClF,GAAG;YAC5C,MAAMQ,SAAS,MAAM,IAAI,CAACA,MAAM;YAChC,MAAMA,OAAOqB,IAAI,CAAC,IAAIqD,kBAAkB;gBAAE9D,QAAQ,IAAI,CAAC1B,GAAG,CAAC2B,MAAM;YAAC;YAClE,OAAO;gBAAE8D,IAAI;YAAK;QACpB,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLA,OAAOA,iBAAiB5D,QAAQ4D,MAAMC,OAAO,GAAG;gBAChDF,IAAI;YACN;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/core/storage/s3.ts"],"sourcesContent":["import type { S3Client } from '@aws-sdk/client-s3'\n\nimport type { BackupS3Config } from './config'\nimport type {\n BackupStorageAdapter,\n BackupStorageObject,\n BackupStorageRef,\n BackupStorageValidation,\n} from './types'\n\n/** Presigned download URLs are valid this long — long enough to start a restore/download. */\nconst SIGNED_URL_TTL_SECONDS = 3600\n\ntype S3PresignerModule = {\n getSignedUrl: (\n client: S3Client,\n command: unknown,\n options: { expiresIn: number },\n ) => Promise<string>\n}\n\nfunction contentTypeFor(pathname: string): string {\n if (pathname.endsWith('.json')) {\n return 'application/json'\n }\n if (pathname.endsWith('.gz') || pathname.endsWith('.tar.gz')) {\n return 'application/gzip'\n }\n return 'application/octet-stream'\n}\n\n/**\n * AWS S3 backup target. The same implementation serves any S3-compatible store (Cloudflare R2,\n * MinIO, …) — only the `endpoint`/`forcePathStyle` config differs, never the code. The AWS SDK is\n * loaded lazily via dynamic import so it stays an optional dependency for Vercel-only installs.\n */\nexport class S3BackupStorage implements BackupStorageAdapter {\n private readonly cfg: BackupS3Config\n\n private clientPromise: null | Promise<S3Client> = null\n private presignerPromise: null | Promise<S3PresignerModule> = null\n readonly kind = 's3'\n\n constructor(cfg: BackupS3Config) {\n this.cfg = cfg\n }\n\n private async buildClient(): Promise<S3Client> {\n const { S3Client } = await this.sdk()\n const { accessKeyId, secretAccessKey, sessionToken } = this.cfg\n return new S3Client({\n ...(this.cfg.endpoint ? { endpoint: this.cfg.endpoint } : {}),\n forcePathStyle: this.cfg.forcePathStyle,\n region: this.cfg.region,\n // When keys are absent, fall back to the SDK's default credential provider chain\n // (env vars, shared config, instance/role credentials).\n ...(accessKeyId && secretAccessKey ?\n { credentials: { accessKeyId, secretAccessKey, sessionToken } }\n : {}),\n })\n }\n\n private async client(): Promise<S3Client> {\n if (!this.clientPromise) {\n this.clientPromise = this.buildClient()\n }\n return this.clientPromise\n }\n\n /** Strip the configured key prefix, returning the provider-agnostic `backups/...` pathname. */\n private fromKey(key: string): string {\n if (!this.cfg.prefix) {\n return key\n }\n const lead = `${this.cfg.prefix}/`\n return key.startsWith(lead) ? key.slice(lead.length) : key\n }\n\n private async presigner() {\n if (!this.presignerPromise) {\n this.presignerPromise = import('@aws-sdk/s3-request-presigner')\n }\n return this.presignerPromise\n }\n\n private async presignGet(key: string): Promise<string> {\n const { GetObjectCommand } = await this.sdk()\n const { getSignedUrl } = await this.presigner()\n const client = await this.client()\n return getSignedUrl(client, new GetObjectCommand({ Bucket: this.cfg.bucket, Key: key }), {\n expiresIn: SIGNED_URL_TTL_SECONDS,\n })\n }\n\n private async sdk() {\n try {\n return await import('@aws-sdk/client-s3')\n } catch {\n throw new Error(\n 'BACKUP_STORAGE=s3 requires the AWS SDK. Install it with: ' +\n 'pnpm add @aws-sdk/client-s3 @aws-sdk/lib-storage @aws-sdk/s3-request-presigner',\n )\n }\n }\n\n /** Prepend the configured key prefix to a provider-agnostic `backups/...` pathname. */\n private toKey(pathname: string): string {\n return this.cfg.prefix ? `${this.cfg.prefix}/${pathname}` : pathname\n }\n\n async del(ref: BackupStorageRef): Promise<void> {\n const { DeleteObjectCommand } = await this.sdk()\n const client = await this.client()\n await client.send(\n new DeleteObjectCommand({ Bucket: this.cfg.bucket, Key: this.toKey(ref.pathname) }),\n )\n }\n\n async list(prefix: string): Promise<BackupStorageObject[]> {\n const { ListObjectsV2Command } = await this.sdk()\n const client = await this.client()\n const keyPrefix = this.toKey(prefix)\n\n const objects: BackupStorageObject[] = []\n let continuationToken: string | undefined\n do {\n const res = await client.send(\n new ListObjectsV2Command({\n Bucket: this.cfg.bucket,\n ContinuationToken: continuationToken,\n Prefix: keyPrefix,\n }),\n )\n const pageEntries: Array<{\n key: string\n pathname: string\n size: number\n uploadedAt: Date\n }> = []\n for (const obj of res.Contents ?? []) {\n if (!obj.Key) {\n continue\n }\n pageEntries.push({\n key: obj.Key,\n pathname: this.fromKey(obj.Key),\n size: obj.Size ?? 0,\n uploadedAt: obj.LastModified ?? new Date(0),\n })\n }\n const signed = await Promise.all(\n pageEntries.map(async (entry) => {\n const url = await this.presignGet(entry.key)\n return {\n downloadUrl: url,\n pathname: entry.pathname,\n size: entry.size,\n uploadedAt: entry.uploadedAt,\n url,\n }\n }),\n )\n objects.push(...signed)\n continuationToken = res.IsTruncated ? res.NextContinuationToken : undefined\n } while (continuationToken)\n\n return objects\n }\n\n async openDownloadStream(ref: BackupStorageRef) {\n const { GetObjectCommand } = await this.sdk()\n const client = await this.client()\n try {\n const res = await client.send(\n new GetObjectCommand({ Bucket: this.cfg.bucket, Key: this.toKey(ref.pathname) }),\n )\n if (!res.Body) {\n return null\n }\n const stream = (\n res.Body as { transformToWebStream: () => ReadableStream<Uint8Array> }\n ).transformToWebStream()\n return {\n contentType: res.ContentType || contentTypeFor(ref.pathname),\n stream,\n }\n } catch {\n return null\n }\n }\n\n async put(\n pathname: string,\n body: Buffer | string | Uint8Array,\n onProgress?: (progress: { loaded: number; total: number }) => void,\n signal?: AbortSignal,\n ) {\n const { Upload } = await import('@aws-sdk/lib-storage')\n const client = await this.client()\n const key = this.toKey(pathname)\n const uploadBody = typeof body === 'string' ? Buffer.from(body) : body\n const total = uploadBody.byteLength\n const upload = new Upload({\n client,\n params: {\n Body: uploadBody,\n Bucket: this.cfg.bucket,\n ContentType: contentTypeFor(pathname),\n Key: key,\n },\n })\n if (onProgress) {\n upload.on('httpUploadProgress', (progress) => {\n onProgress({ loaded: progress.loaded ?? 0, total })\n })\n }\n const abort = () => {\n void upload.abort()\n }\n if (signal?.aborted) {\n abort()\n } else {\n signal?.addEventListener('abort', abort, { once: true })\n }\n try {\n await upload.done()\n } finally {\n signal?.removeEventListener('abort', abort)\n }\n return { pathname, url: await this.presignGet(key) }\n }\n\n async read(ref: BackupStorageRef): Promise<Buffer> {\n const { GetObjectCommand } = await this.sdk()\n const client = await this.client()\n const res = await client.send(\n new GetObjectCommand({ Bucket: this.cfg.bucket, Key: this.toKey(ref.pathname) }),\n )\n if (!res.Body) {\n throw new Error(`Failed to read backup object (${ref.pathname}): empty body`)\n }\n const bytes = await (\n res.Body as { transformToByteArray: () => Promise<Uint8Array> }\n ).transformToByteArray()\n return Buffer.from(bytes)\n }\n\n async validate(): Promise<BackupStorageValidation> {\n try {\n const { HeadBucketCommand } = await this.sdk()\n const client = await this.client()\n await client.send(new HeadBucketCommand({ Bucket: this.cfg.bucket }))\n return { ok: true }\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : 'S3 bucket not reachable',\n ok: false,\n }\n }\n }\n}\n"],"names":["SIGNED_URL_TTL_SECONDS","contentTypeFor","pathname","endsWith","S3BackupStorage","cfg","clientPromise","presignerPromise","kind","buildClient","S3Client","sdk","accessKeyId","secretAccessKey","sessionToken","endpoint","forcePathStyle","region","credentials","client","fromKey","key","prefix","lead","startsWith","slice","length","presigner","presignGet","GetObjectCommand","getSignedUrl","Bucket","bucket","Key","expiresIn","Error","toKey","del","ref","DeleteObjectCommand","send","list","ListObjectsV2Command","keyPrefix","objects","continuationToken","res","ContinuationToken","Prefix","pageEntries","obj","Contents","push","size","Size","uploadedAt","LastModified","Date","signed","Promise","all","map","entry","url","downloadUrl","IsTruncated","NextContinuationToken","undefined","openDownloadStream","Body","stream","transformToWebStream","contentType","ContentType","put","body","onProgress","signal","Upload","uploadBody","Buffer","from","total","byteLength","upload","params","on","progress","loaded","abort","aborted","addEventListener","once","done","removeEventListener","read","bytes","transformToByteArray","validate","HeadBucketCommand","ok","error","message"],"mappings":"AAUA,2FAA2F,GAC3F,MAAMA,yBAAyB;AAU/B,SAASC,eAAeC,QAAgB;IACtC,IAAIA,SAASC,QAAQ,CAAC,UAAU;QAC9B,OAAO;IACT;IACA,IAAID,SAASC,QAAQ,CAAC,UAAUD,SAASC,QAAQ,CAAC,YAAY;QAC5D,OAAO;IACT;IACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMC;IACMC,IAAmB;IAE5BC,gBAA0C,KAAI;IAC9CC,mBAAsD,KAAI;IACzDC,OAAO,KAAI;IAEpB,YAAYH,GAAmB,CAAE;QAC/B,IAAI,CAACA,GAAG,GAAGA;IACb;IAEA,MAAcI,cAAiC;QAC7C,MAAM,EAAEC,QAAQ,EAAE,GAAG,MAAM,IAAI,CAACC,GAAG;QACnC,MAAM,EAAEC,WAAW,EAAEC,eAAe,EAAEC,YAAY,EAAE,GAAG,IAAI,CAACT,GAAG;QAC/D,OAAO,IAAIK,SAAS;YAClB,GAAI,IAAI,CAACL,GAAG,CAACU,QAAQ,GAAG;gBAAEA,UAAU,IAAI,CAACV,GAAG,CAACU,QAAQ;YAAC,IAAI,CAAC,CAAC;YAC5DC,gBAAgB,IAAI,CAACX,GAAG,CAACW,cAAc;YACvCC,QAAQ,IAAI,CAACZ,GAAG,CAACY,MAAM;YACvB,iFAAiF;YACjF,wDAAwD;YACxD,GAAIL,eAAeC,kBACjB;gBAAEK,aAAa;oBAAEN;oB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G,MAAM,IAAI,CAACxF,GAAG;YAC5C,MAAMQ,SAAS,MAAM,IAAI,CAACA,MAAM;YAChC,MAAMA,OAAOqB,IAAI,CAAC,IAAI2D,kBAAkB;gBAAEpE,QAAQ,IAAI,CAAC1B,GAAG,CAAC2B,MAAM;YAAC;YAClE,OAAO;gBAAEoE,IAAI;YAAK;QACpB,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLA,OAAOA,iBAAiBlE,QAAQkE,MAAMC,OAAO,GAAG;gBAChDF,IAAI;YACN;QACF;IACF;AACF"}
@@ -53,7 +53,7 @@ export interface BackupStorageAdapter {
53
53
  stream: ReadableStream<Uint8Array>;
54
54
  } | null>;
55
55
  /** Upload an archive at `pathname`. */
56
- put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: BackupStorageUploadProgress) => void): Promise<{
56
+ put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: BackupStorageUploadProgress) => void, signal?: AbortSignal): Promise<{
57
57
  pathname: string;
58
58
  url: string;
59
59
  }>;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/storage/types.ts"],"sourcesContent":["import type { BackupBlobAccessLevel } from '../backupBlobIO'\n\n/** Selectable backup target. Vercel Blob is the historical default; `s3` covers AWS S3 and any\n * S3-compatible store (Cloudflare R2, MinIO, …) — they share one implementation. */\nexport type BackupStorageKind = 's3' | 'vercel-blob'\n\n/**\n * Backup archive as seen by the dashboard and the cron/list endpoints. The field names match the\n * objects Vercel Blob's `list()` returns so existing consumers (UI, restore-by-`url`) keep working;\n * the S3 adapter synthesizes the same shape (with a presigned `downloadUrl`/`url`).\n */\nexport interface BackupStorageObject {\n /** Time-limited URL suitable for downloading the object (presigned for S3). */\n downloadUrl: string\n /** Object key without any provider prefix, e.g. `backups/manual---db---host---2-1700.json`. */\n pathname: string\n /** Object size in bytes. */\n size: number\n /** Upload/last-modified time. */\n uploadedAt: Date | string\n /** Stable reference used for download/delete (Vercel blob URL; presigned GET for S3). */\n url: string\n}\n\n/** Result of probing the target's credentials/reachability. */\nexport interface BackupStorageValidation {\n /** Detected Vercel Blob access level, when applicable. */\n access?: BackupBlobAccessLevel\n /** Short description when validation fails. */\n error?: string\n ok: boolean\n}\n\n/** A reference good enough to read or delete a single archive across providers. */\nexport interface BackupStorageRef {\n downloadUrl?: null | string\n pathname: string\n url?: null | string\n}\n\nexport interface BackupStorageUploadProgress {\n loaded: number\n total: number\n}\n\n/**\n * Provider-agnostic operations the plugin performs on backup archives. Implementations live in\n * `vercelBlob.ts` and `s3.ts`; callers obtain one via {@link resolveBackupStorage}.\n */\nexport interface BackupStorageAdapter {\n /** Delete a single archive. */\n del(ref: BackupStorageRef): Promise<void>\n readonly kind: BackupStorageKind\n /** List archives under a pathname prefix (e.g. `backups/` or `backups/cron-`). */\n list(prefix: string): Promise<BackupStorageObject[]>\n /** Open a readable stream for streaming a download response, or null when not found. */\n openDownloadStream(\n ref: BackupStorageRef,\n ): Promise<{ contentType: string; stream: ReadableStream<Uint8Array> } | null>\n /** Upload an archive at `pathname`. */\n put(\n pathname: string,\n body: Buffer | string | Uint8Array,\n onProgress?: (progress: BackupStorageUploadProgress) => void,\n ): Promise<{ pathname: string; url: string }>\n /** Read the full bytes of an archive. */\n read(ref: BackupStorageRef): Promise<Buffer>\n /** Probe credentials / reachability without persisting anything. */\n validate(): Promise<BackupStorageValidation>\n}\n"],"names":[],"mappings":"AA6CA;;;CAGC,GACD,WAoBC"}
1
+ {"version":3,"sources":["../../../src/core/storage/types.ts"],"sourcesContent":["import type { BackupBlobAccessLevel } from '../backupBlobIO'\n\n/** Selectable backup target. Vercel Blob is the historical default; `s3` covers AWS S3 and any\n * S3-compatible store (Cloudflare R2, MinIO, …) — they share one implementation. */\nexport type BackupStorageKind = 's3' | 'vercel-blob'\n\n/**\n * Backup archive as seen by the dashboard and the cron/list endpoints. The field names match the\n * objects Vercel Blob's `list()` returns so existing consumers (UI, restore-by-`url`) keep working;\n * the S3 adapter synthesizes the same shape (with a presigned `downloadUrl`/`url`).\n */\nexport interface BackupStorageObject {\n /** Time-limited URL suitable for downloading the object (presigned for S3). */\n downloadUrl: string\n /** Object key without any provider prefix, e.g. `backups/manual---db---host---2-1700.json`. */\n pathname: string\n /** Object size in bytes. */\n size: number\n /** Upload/last-modified time. */\n uploadedAt: Date | string\n /** Stable reference used for download/delete (Vercel blob URL; presigned GET for S3). */\n url: string\n}\n\n/** Result of probing the target's credentials/reachability. */\nexport interface BackupStorageValidation {\n /** Detected Vercel Blob access level, when applicable. */\n access?: BackupBlobAccessLevel\n /** Short description when validation fails. */\n error?: string\n ok: boolean\n}\n\n/** A reference good enough to read or delete a single archive across providers. */\nexport interface BackupStorageRef {\n downloadUrl?: null | string\n pathname: string\n url?: null | string\n}\n\nexport interface BackupStorageUploadProgress {\n loaded: number\n total: number\n}\n\n/**\n * Provider-agnostic operations the plugin performs on backup archives. Implementations live in\n * `vercelBlob.ts` and `s3.ts`; callers obtain one via {@link resolveBackupStorage}.\n */\nexport interface BackupStorageAdapter {\n /** Delete a single archive. */\n del(ref: BackupStorageRef): Promise<void>\n readonly kind: BackupStorageKind\n /** List archives under a pathname prefix (e.g. `backups/` or `backups/cron-`). */\n list(prefix: string): Promise<BackupStorageObject[]>\n /** Open a readable stream for streaming a download response, or null when not found. */\n openDownloadStream(\n ref: BackupStorageRef,\n ): Promise<{ contentType: string; stream: ReadableStream<Uint8Array> } | null>\n /** Upload an archive at `pathname`. */\n put(\n pathname: string,\n body: Buffer | string | Uint8Array,\n onProgress?: (progress: BackupStorageUploadProgress) => void,\n signal?: AbortSignal,\n ): Promise<{ pathname: string; url: string }>\n /** Read the full bytes of an archive. */\n read(ref: BackupStorageRef): Promise<Buffer>\n /** Probe credentials / reachability without persisting anything. */\n validate(): Promise<BackupStorageValidation>\n}\n"],"names":[],"mappings":"AA6CA;;;CAGC,GACD,WAqBC"}
@@ -16,7 +16,7 @@ export declare class VercelBlobStorage implements BackupStorageAdapter {
16
16
  del(ref: BackupStorageRef): Promise<void>;
17
17
  list(prefix: string): Promise<BackupStorageObject[]>;
18
18
  openDownloadStream(ref: BackupStorageRef): Promise<import("../backupBlobIO.js").BackupBlobDownloadStream | null>;
19
- put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: BackupStorageUploadProgress) => void): Promise<{
19
+ put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: BackupStorageUploadProgress) => void, signal?: AbortSignal): Promise<{
20
20
  pathname: string;
21
21
  url: string;
22
22
  }>;
@@ -35,8 +35,8 @@ import { validateBackupBlobToken } from '../blobTokenValidate.js';
35
35
  token: this.token ?? ''
36
36
  });
37
37
  }
38
- async put(pathname, body, onProgress) {
39
- await putBackupBlobContent(pathname, body, this.token, this.access, onProgress);
38
+ async put(pathname, body, onProgress, signal) {
39
+ await putBackupBlobContent(pathname, body, this.token, this.access, onProgress, signal);
40
40
  return {
41
41
  pathname,
42
42
  url: ''
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/storage/vercelBlob.ts"],"sourcesContent":["import { del, list } from '@vercel/blob'\n\nimport type {\n BackupStorageAdapter,\n BackupStorageObject,\n BackupStorageRef,\n BackupStorageUploadProgress,\n BackupStorageValidation,\n} from './types'\n\nimport {\n type BackupBlobAccessLevel,\n putBackupBlobContent,\n readBackupBlobContentFlexible,\n streamBackupBlobForDownload,\n} from '../backupBlobIO'\nimport { validateBackupBlobToken } from '../blobTokenValidate'\n\n/**\n * Vercel Blob backup target — the historical default. This is a thin wrapper around the existing\n * `@vercel/blob` helpers so behaviour (and the test seams that mock `@vercel/blob`) is unchanged;\n * the adapter only generalizes the call shape so S3 can slot in alongside it.\n */\nexport class VercelBlobStorage implements BackupStorageAdapter {\n private readonly access: BackupBlobAccessLevel\n\n private readonly token: string | undefined\n readonly kind = 'vercel-blob'\n\n constructor(options: { access?: BackupBlobAccessLevel; token?: string }) {\n this.token = options.token\n this.access = options.access ?? 'public'\n }\n\n async del(ref: BackupStorageRef): Promise<void> {\n await del(ref.url ?? ref.pathname, { token: this.token })\n }\n\n async list(prefix: string): Promise<BackupStorageObject[]> {\n const { blobs } = await list({ limit: 1000, prefix, token: this.token })\n return blobs as unknown as BackupStorageObject[]\n }\n\n async openDownloadStream(ref: BackupStorageRef) {\n return streamBackupBlobForDownload({\n blobUrl: ref.url,\n downloadUrl: ref.downloadUrl,\n pathname: ref.pathname,\n preferredAccess: this.access,\n token: this.token ?? '',\n })\n }\n\n async put(\n pathname: string,\n body: Buffer | string | Uint8Array,\n onProgress?: (progress: BackupStorageUploadProgress) => void,\n ) {\n await putBackupBlobContent(pathname, body, this.token, this.access, onProgress)\n return { pathname, url: '' }\n }\n\n async read(ref: BackupStorageRef): Promise<Buffer> {\n return readBackupBlobContentFlexible(\n ref.pathname,\n ref.downloadUrl ?? ref.url ?? '',\n this.token ?? '',\n )\n }\n\n async validate(): Promise<BackupStorageValidation> {\n return validateBackupBlobToken(this.token ?? '')\n }\n}\n"],"names":["del","list","putBackupBlobContent","readBackupBlobContentFlexible","streamBackupBlobForDownload","validateBackupBlobToken","VercelBlobStorage","access","token","kind","options","ref","url","pathname","prefix","blobs","limit","openDownloadStream","blobUrl","downloadUrl","preferredAccess","put","body","onProgress","read","validate"],"mappings":"AAAA,SAASA,GAAG,EAAEC,IAAI,QAAQ,eAAc;AAUxC,SAEEC,oBAAoB,EACpBC,6BAA6B,EAC7BC,2BAA2B,QACtB,kBAAiB;AACxB,SAASC,uBAAuB,QAAQ,uBAAsB;AAE9D;;;;CAIC,GACD,OAAO,MAAMC;IACMC,OAA6B;IAE7BC,MAAyB;IACjCC,OAAO,cAAa;IAE7B,YAAYC,OAA2D,CAAE;QACvE,IAAI,CAACF,KAAK,GAAGE,QAAQF,KAAK;QAC1B,IAAI,CAACD,MAAM,GAAGG,QAAQH,MAAM,IAAI;IAClC;IAEA,MAAMP,IAAIW,GAAqB,EAAiB;QAC9C,MAAMX,IAAIW,IAAIC,GAAG,IAAID,IAAIE,QAAQ,EAAE;YAAEL,OAAO,IAAI,CAACA,KAAK;QAAC;IACzD;IAEA,MAAMP,KAAKa,MAAc,EAAkC;QACzD,MAAM,EAAEC,KAAK,EAAE,GAAG,MAAMd,KAAK;YAAEe,OAAO;YAAMF;YAAQN,OAAO,IAAI,CAACA,KAAK;QAAC;QACtE,OAAOO;IACT;IAEA,MAAME,mBAAmBN,GAAqB,EAAE;QAC9C,OAAOP,4BAA4B;YACjCc,SAASP,IAAIC,GAAG;YAChBO,aAAaR,IAAIQ,WAAW;YAC5BN,UAAUF,IAAIE,QAAQ;YACtBO,iBAAiB,IAAI,CAACb,MAAM;YAC5BC,OAAO,IAAI,CAACA,KAAK,IAAI;QACvB;IACF;IAEA,MAAMa,IACJR,QAAgB,EAChBS,IAAkC,EAClCC,UAA4D,EAC5D;QACA,MAAMrB,qBAAqBW,UAAUS,MAAM,IAAI,CAACd,KAAK,EAAE,IAAI,CAACD,MAAM,EAAEgB;QACpE,OAAO;YAAEV;YAAUD,KAAK;QAAG;IAC7B;IAEA,MAAMY,KAAKb,GAAqB,EAAmB;QACjD,OAAOR,8BACLQ,IAAIE,QAAQ,EACZF,IAAIQ,WAAW,IAAIR,IAAIC,GAAG,IAAI,IAC9B,IAAI,CAACJ,KAAK,IAAI;IAElB;IAEA,MAAMiB,WAA6C;QACjD,OAAOpB,wBAAwB,IAAI,CAACG,KAAK,IAAI;IAC/C;AACF"}
1
+ {"version":3,"sources":["../../../src/core/storage/vercelBlob.ts"],"sourcesContent":["import { del, list } from '@vercel/blob'\n\nimport type {\n BackupStorageAdapter,\n BackupStorageObject,\n BackupStorageRef,\n BackupStorageUploadProgress,\n BackupStorageValidation,\n} from './types'\n\nimport {\n type BackupBlobAccessLevel,\n putBackupBlobContent,\n readBackupBlobContentFlexible,\n streamBackupBlobForDownload,\n} from '../backupBlobIO'\nimport { validateBackupBlobToken } from '../blobTokenValidate'\n\n/**\n * Vercel Blob backup target — the historical default. This is a thin wrapper around the existing\n * `@vercel/blob` helpers so behaviour (and the test seams that mock `@vercel/blob`) is unchanged;\n * the adapter only generalizes the call shape so S3 can slot in alongside it.\n */\nexport class VercelBlobStorage implements BackupStorageAdapter {\n private readonly access: BackupBlobAccessLevel\n\n private readonly token: string | undefined\n readonly kind = 'vercel-blob'\n\n constructor(options: { access?: BackupBlobAccessLevel; token?: string }) {\n this.token = options.token\n this.access = options.access ?? 'public'\n }\n\n async del(ref: BackupStorageRef): Promise<void> {\n await del(ref.url ?? ref.pathname, { token: this.token })\n }\n\n async list(prefix: string): Promise<BackupStorageObject[]> {\n const { blobs } = await list({ limit: 1000, prefix, token: this.token })\n return blobs as unknown as BackupStorageObject[]\n }\n\n async openDownloadStream(ref: BackupStorageRef) {\n return streamBackupBlobForDownload({\n blobUrl: ref.url,\n downloadUrl: ref.downloadUrl,\n pathname: ref.pathname,\n preferredAccess: this.access,\n token: this.token ?? '',\n })\n }\n\n async put(\n pathname: string,\n body: Buffer | string | Uint8Array,\n onProgress?: (progress: BackupStorageUploadProgress) => void,\n signal?: AbortSignal,\n ) {\n await putBackupBlobContent(pathname, body, this.token, this.access, onProgress, signal)\n return { pathname, url: '' }\n }\n\n async read(ref: BackupStorageRef): Promise<Buffer> {\n return readBackupBlobContentFlexible(\n ref.pathname,\n ref.downloadUrl ?? ref.url ?? '',\n this.token ?? '',\n )\n }\n\n async validate(): Promise<BackupStorageValidation> {\n return validateBackupBlobToken(this.token ?? '')\n }\n}\n"],"names":["del","list","putBackupBlobContent","readBackupBlobContentFlexible","streamBackupBlobForDownload","validateBackupBlobToken","VercelBlobStorage","access","token","kind","options","ref","url","pathname","prefix","blobs","limit","openDownloadStream","blobUrl","downloadUrl","preferredAccess","put","body","onProgress","signal","read","validate"],"mappings":"AAAA,SAASA,GAAG,EAAEC,IAAI,QAAQ,eAAc;AAUxC,SAEEC,oBAAoB,EACpBC,6BAA6B,EAC7BC,2BAA2B,QACtB,kBAAiB;AACxB,SAASC,uBAAuB,QAAQ,uBAAsB;AAE9D;;;;CAIC,GACD,OAAO,MAAMC;IACMC,OAA6B;IAE7BC,MAAyB;IACjCC,OAAO,cAAa;IAE7B,YAAYC,OAA2D,CAAE;QACvE,IAAI,CAACF,KAAK,GAAGE,QAAQF,KAAK;QAC1B,IAAI,CAACD,MAAM,GAAGG,QAAQH,MAAM,IAAI;IAClC;IAEA,MAAMP,IAAIW,GAAqB,EAAiB;QAC9C,MAAMX,IAAIW,IAAIC,GAAG,IAAID,IAAIE,QAAQ,EAAE;YAAEL,OAAO,IAAI,CAACA,KAAK;QAAC;IACzD;IAEA,MAAMP,KAAKa,MAAc,EAAkC;QACzD,MAAM,EAAEC,KAAK,EAAE,GAAG,MAAMd,KAAK;YAAEe,OAAO;YAAMF;YAAQN,OAAO,IAAI,CAACA,KAAK;QAAC;QACtE,OAAOO;IACT;IAEA,MAAME,mBAAmBN,GAAqB,EAAE;QAC9C,OAAOP,4BAA4B;YACjCc,SAASP,IAAIC,GAAG;YAChBO,aAAaR,IAAIQ,WAAW;YAC5BN,UAAUF,IAAIE,QAAQ;YACtBO,iBAAiB,IAAI,CAACb,MAAM;YAC5BC,OAAO,IAAI,CAACA,KAAK,IAAI;QACvB;IACF;IAEA,MAAMa,IACJR,QAAgB,EAChBS,IAAkC,EAClCC,UAA4D,EAC5DC,MAAoB,EACpB;QACA,MAAMtB,qBAAqBW,UAAUS,MAAM,IAAI,CAACd,KAAK,EAAE,IAAI,CAACD,MAAM,EAAEgB,YAAYC;QAChF,OAAO;YAAEX;YAAUD,KAAK;QAAG;IAC7B;IAEA,MAAMa,KAAKd,GAAqB,EAAmB;QACjD,OAAOR,8BACLQ,IAAIE,QAAQ,EACZF,IAAIQ,WAAW,IAAIR,IAAIC,GAAG,IAAI,IAC9B,IAAI,CAACJ,KAAK,IAAI;IAElB;IAEA,MAAMkB,WAA6C;QACjD,OAAOrB,wBAAwB,IAAI,CAACG,KAAK,IAAI;IAC/C;AACF"}
@@ -1,7 +1,7 @@
1
1
  import type { Payload } from 'payload';
2
2
  import type { RestoreBackupResult } from './restoreResult.js';
3
3
  export type BackupTaskKind = 'backup' | 'blobTransfer' | 'delete' | 'restore';
4
- export type BackupTaskStatus = 'completed' | 'completed_with_warnings' | 'failed' | 'queued' | 'running';
4
+ export type BackupTaskStatus = 'cancelled' | 'completed' | 'completed_with_warnings' | 'failed' | 'queued' | 'running';
5
5
  export type BackupTaskProgress = {
6
6
  createdAt: string;
7
7
  error?: null | string;
@@ -28,6 +28,8 @@ export declare function completeBackupTask(payload: Payload, id: string, message
28
28
  status?: 'completed' | 'completed_with_warnings';
29
29
  warnings?: string;
30
30
  }): Promise<BackupTaskProgress | undefined>;
31
+ export declare function cancelBackupTask(payload: Payload, id: string): Promise<BackupTaskProgress | undefined>;
32
+ export declare function isBackupTaskCancelled(payload: Payload, id: string): Promise<boolean>;
31
33
  export declare function completeRestoreBackupTask(payload: Payload, id: string, result: RestoreBackupResult): Promise<BackupTaskProgress | undefined>;
32
34
  export declare function failBackupTask(payload: Payload, id: string, error: unknown): Promise<BackupTaskProgress | undefined>;
33
35
  /** Default age after which progress rows are deleted (matches the MongoDB plugin's TTL index). */
@@ -47,6 +47,15 @@ export async function getBackupTask(payload, id) {
47
47
  }
48
48
  export async function updateBackupTask(payload, id, patch) {
49
49
  try {
50
+ const current = await getBackupTask(payload, id);
51
+ if (current && [
52
+ 'cancelled',
53
+ 'completed',
54
+ 'completed_with_warnings',
55
+ 'failed'
56
+ ].includes(current.status) && patch.status !== current.status) {
57
+ return stripPollSecretForClient(current);
58
+ }
50
59
  const doc = await payload.update({
51
60
  id,
52
61
  collection: 'backup-tasks',
@@ -63,12 +72,32 @@ export async function updateBackupTask(payload, id, patch) {
63
72
  }
64
73
  }
65
74
  export async function completeBackupTask(payload, id, message, options) {
75
+ const current = await getBackupTask(payload, id);
76
+ if (current?.status === 'cancelled') {
77
+ return stripPollSecretForClient(current);
78
+ }
66
79
  return updateBackupTask(payload, id, {
67
80
  message,
68
81
  status: options?.status ?? 'completed',
69
82
  warnings: options?.warnings ?? null
70
83
  });
71
84
  }
85
+ export async function cancelBackupTask(payload, id) {
86
+ const current = await getBackupTask(payload, id);
87
+ if (!current || ![
88
+ 'queued',
89
+ 'running'
90
+ ].includes(current.status)) {
91
+ return current ? stripPollSecretForClient(current) : undefined;
92
+ }
93
+ return updateBackupTask(payload, id, {
94
+ message: 'Backup cancelled',
95
+ status: 'cancelled'
96
+ });
97
+ }
98
+ export async function isBackupTaskCancelled(payload, id) {
99
+ return (await getBackupTask(payload, id))?.status === 'cancelled';
100
+ }
72
101
  export async function completeRestoreBackupTask(payload, id, result) {
73
102
  const warnings = buildRestoreWarnings(result);
74
103
  return completeBackupTask(payload, id, formatRestoreSummary(result), {