payload-plugin-backup-postgres 0.2.2 → 0.3.1
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.
- package/dist/backup-dashboard.css +77 -36
- package/dist/collections/BackupTasks.js +2 -1
- package/dist/collections/BackupTasks.js.map +1 -1
- package/dist/components/BackupDashboard/BackupItemActions.client.js +1 -0
- package/dist/components/BackupDashboard/BackupItemActions.client.js.map +1 -1
- package/dist/components/BackupDashboard/BackupUploadProgress.client.d.ts +1 -0
- package/dist/components/BackupDashboard/BackupUploadProgress.client.js +173 -0
- package/dist/components/BackupDashboard/BackupUploadProgress.client.js.map +1 -0
- package/dist/components/BackupDashboard/ManualBackupDialog.client.js +3 -23
- package/dist/components/BackupDashboard/ManualBackupDialog.client.js.map +1 -1
- package/dist/components/BackupDashboard/TaskActionButton.client.d.ts +2 -0
- package/dist/components/BackupDashboard/TaskActionButton.client.js +55 -35
- package/dist/components/BackupDashboard/TaskActionButton.client.js.map +1 -1
- package/dist/components/BackupDashboard/backupDashboardInlineCss.js +1 -1
- package/dist/components/BackupDashboard/backupDashboardInlineCss.js.map +1 -1
- package/dist/components/BackupDashboard/index.client.d.ts +1 -0
- package/dist/components/BackupDashboard/index.client.js +1 -0
- package/dist/components/BackupDashboard/index.client.js.map +1 -1
- package/dist/components/BackupDashboard/index.js +4 -3
- package/dist/components/BackupDashboard/index.js.map +1 -1
- package/dist/core/backup.js +71 -3
- package/dist/core/backup.js.map +1 -1
- package/dist/core/backupBlobIO.d.ts +4 -1
- package/dist/core/backupBlobIO.js +8 -1
- package/dist/core/backupBlobIO.js.map +1 -1
- package/dist/core/storage/s3.d.ts +4 -1
- package/dist/core/storage/s3.js +29 -4
- package/dist/core/storage/s3.js.map +1 -1
- package/dist/core/storage/types.d.ts +5 -1
- package/dist/core/storage/types.js.map +1 -1
- package/dist/core/storage/vercelBlob.d.ts +2 -2
- package/dist/core/storage/vercelBlob.js +2 -2
- package/dist/core/storage/vercelBlob.js.map +1 -1
- package/dist/core/taskProgress.d.ts +3 -1
- package/dist/core/taskProgress.js +34 -1
- package/dist/core/taskProgress.js.map +1 -1
- package/dist/endpoints/index.js +2 -0
- package/dist/endpoints/index.js.map +1 -1
- package/dist/endpoints/paths/admin-manual.js +15 -7
- package/dist/endpoints/paths/admin-manual.js.map +1 -1
- package/dist/endpoints/paths/admin-task-cancel.d.ts +3 -0
- package/dist/endpoints/paths/admin-task-cancel.js +34 -0
- package/dist/endpoints/paths/admin-task-cancel.js.map +1 -0
- package/dist/publicApiPaths.d.ts +1 -0
- package/dist/publicApiPaths.js +1 -0
- package/dist/publicApiPaths.js.map +1 -1
- package/dist/utils/backupUploadProgress.d.ts +12 -0
- package/dist/utils/backupUploadProgress.js +26 -0
- package/dist/utils/backupUploadProgress.js.map +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/BackupDashboard/index.tsx"],"sourcesContent":["import type { I18n } from '@payloadcms/translations'\nimport type { AdminViewServerProps, Payload } from 'payload'\n\nimport type { BackupPluginOptions } from '../../types'\n\nimport { listBackups, resolveBackupListToken } from '../../core/backup'\nimport { getBackupStorageKind, isBackupStorageConfigured } from '../../core/storage'\nimport {\n getBackupSortTimeMs,\n getCurrentDbName,\n getCurrentHostname,\n isUserAllowedByEnvRoles,\n transformBlobName,\n} from '../../utils/index'\nimport { backupDashboardInlineCss } from './backupDashboardInlineCss'\nimport { BackupListCollapsible, BackupSettingsModal, ManualBackupDialog } from './index.client'\nimport { DefaultTemplate } from '@payloadcms/next/templates'\nimport { Gutter } from '@payloadcms/ui'\n\ninterface BackupDashboardProps {\n i18n: I18n\n /**\n * Payload instance injected by Payload's admin `RenderServerComponent` as a server prop\n * for `afterDashboard` components. Avoids importing `@payload-config` from the plugin,\n * which does not resolve when the plugin runs from `node_modules`.\n */\n payload?: Payload\n /** Optional on admin server props; omitted does not mean logged out (see `defaultIsHidden`). */\n user?: null | Record<string, unknown>\n}\n\nfunction defaultIsHidden(\n user: null | Record<string, unknown> | undefined,\n access?: BackupPluginOptions['access'],\n): boolean {\n if (user === null) {\n return true\n }\n if (user === undefined) {\n if (access) {\n return true\n }\n return false\n }\n if (access) {\n return !access(user)\n }\n // Role allow-list via `PAYLOAD_BACKUP_ALLOWED_ROLES`. When unset, falls back to the\n // historical default (admin role, or \"visible\" when the project has no roles field).\n return !isUserAllowedByEnvRoles(user)\n}\n\nexport const BackupDashboard: React.FC<AdminViewServerProps> = ({\n initPageResult,\n params,\n searchParams,\n ...props\n}) => {\n\n return (\n <DefaultTemplate\n i18n={initPageResult.req.i18n}\n locale={initPageResult.locale}\n params={params}\n payload={initPageResult.req.payload}\n permissions={initPageResult.permissions}\n searchParams={searchParams}\n user={initPageResult.req.user || undefined}\n visibleEntities={initPageResult.visibleEntities}\n >\n <Gutter>\n <div style={{display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '24px'}}>\n <h1>Backups <span className=\"experimental\">(experimental)</span></h1>\n <p>Here you can manage your database backups</p>\n </div>\n <BackupDashboardView i18n={initPageResult.req.i18n} payload={initPageResult.req.payload}user={initPageResult.req.user || undefined} />\n </Gutter>\n </DefaultTemplate>\n )\n}\n\nexport const BackupDashboardView: React.FC<BackupDashboardProps> = async ({ i18n, payload, user }) => {\n if (defaultIsHidden(user)) {\n return null\n }\n\n const hasPostgresAdapter = (payload?.db as { name?: string } | undefined)?.name === 'postgres'\n if (!hasPostgresAdapter) {\n return (\n <>\n <style dangerouslySetInnerHTML={{ __html: backupDashboardInlineCss }} />\n <div className=\"backup-dashboard\">\n <h2>\n Backups <span className=\"experimental\">(experimental)</span>\n </h2>\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n This plugin requires Payload's Postgres adapter (\n <code className=\"backup-dashboard__setup-hint-code\">@payloadcms/db-postgres</code> or{' '}\n <code className=\"backup-dashboard__setup-hint-code\">\n @payloadcms/db-vercel-postgres\n </code>\n ). For MongoDB use @trieb.work/payload-plugin-backup-mongodb.\n </p>\n </div>\n </>\n )\n }\n\n if (!payload) {\n // Should not happen in a normal Payload admin render; guard for safety.\n return (\n <>\n <style dangerouslySetInnerHTML={{ __html: backupDashboardInlineCss }} />\n <div className=\"backup-dashboard\">\n <h2>\n Backups <span className=\"experimental\">(experimental)</span>\n </h2>\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n Backup dashboard could not initialise: Payload instance was not provided by the admin\n server props.\n </p>\n </div>\n </>\n )\n }\n\n const storageKind = getBackupStorageKind()\n const backupBlobToken = await resolveBackupListToken(payload)\n const storageConfigured = isBackupStorageConfigured(backupBlobToken)\n\n const blobs = storageConfigured ? await listBackups(payload, { blobToken: backupBlobToken }) : []\n const sortedBlobs = [...blobs].sort((a, b) => {\n const ta = getBackupSortTimeMs(transformBlobName(a.pathname), new Date(a.uploadedAt))\n const tb = getBackupSortTimeMs(transformBlobName(b.pathname), new Date(b.uploadedAt))\n return tb - ta\n })\n const currentHostname = getCurrentHostname()\n const currentDbName = getCurrentDbName()\n\n const countOtherDb = sortedBlobs.filter((blob) => {\n const { dbName } = transformBlobName(blob.pathname)\n return currentDbName !== dbName\n }).length\n\n const countOtherHostname = sortedBlobs.filter((blob) => {\n const { hostname } = transformBlobName(blob.pathname)\n return currentHostname !== hostname\n }).length\n const lastBackup = sortedBlobs[0]\n\n return (\n <>\n <style\n dangerouslySetInnerHTML={{ __html: backupDashboardInlineCss }}\n data-payload-backup-postgres=\"1\"\n />\n <div className=\"backup-dashboard\">\n {!storageConfigured && storageKind === 's3' && (\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n Set <code className=\"backup-dashboard__setup-hint-code\">BACKUP_S3_BUCKET</code> (and\n credentials) to enable the S3 backup target. Until then, the list stays empty and cron\n or manual backups cannot run.\n </p>\n )}\n {!storageConfigured && storageKind === 'vercel-blob' && (\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n Add a Vercel Blob read/write token: set environment variable{' '}\n <code className=\"backup-dashboard__setup-hint-code\">BLOB_READ_WRITE_TOKEN</code>, or\n open <strong>Backup settings</strong> and paste a token. Until then, the list stays\n empty and cron or manual backups cannot run.\n </p>\n )}\n\n <div className=\"backup-dashboard__toolbar\">\n <div className=\"backup-dashboard__toolbar-meta\">\n <span className=\"backup-dashboard__toolbar-pill\">\n <span className=\"backup-dashboard__toolbar-key\">Storage</span>\n {storageKind === 's3' ? 'AWS S3' : 'Vercel Blob'}\n </span>\n <span className=\"backup-dashboard__toolbar-pill\">\n <span className=\"backup-dashboard__toolbar-key\">Total</span>\n {sortedBlobs.length} backup{sortedBlobs.length === 1 ? '' : 's'}\n </span>\n <span className=\"backup-dashboard__toolbar-pill\">\n <span className=\"backup-dashboard__toolbar-key\">Last backup</span>\n {lastBackup ?\n new Date(\n getBackupSortTimeMs(\n transformBlobName(lastBackup.pathname),\n new Date(lastBackup.uploadedAt),\n ),\n ).toLocaleString(i18n?.language || 'en')\n : 'No backups yet'}\n </span>\n </div>\n <div className=\"make-backup-actions\">\n <BackupSettingsModal />\n <ManualBackupDialog />\n </div>\n </div>\n\n <BackupListCollapsible\n blobs={sortedBlobs.map((b) => ({\n downloadUrl: b.downloadUrl,\n pathname: b.pathname,\n size: b.size,\n uploadedAt: new Date(b.uploadedAt).toISOString(),\n url: b.url,\n }))}\n countOtherDb={countOtherDb}\n countOtherHostname={countOtherHostname}\n currentDbName={currentDbName}\n currentHostname={currentHostname}\n i18nLanguage={i18n?.language || 'en'}\n />\n </div>\n </>\n )\n}\n\nexport default BackupDashboard"],"names":["listBackups","resolveBackupListToken","getBackupStorageKind","isBackupStorageConfigured","getBackupSortTimeMs","getCurrentDbName","getCurrentHostname","isUserAllowedByEnvRoles","transformBlobName","backupDashboardInlineCss","BackupListCollapsible","BackupSettingsModal","ManualBackupDialog","DefaultTemplate","Gutter","defaultIsHidden","user","access","undefined","BackupDashboard","initPageResult","params","searchParams","props","i18n","req","locale","payload","permissions","visibleEntities","div","style","display","flexDirection","gap","marginBottom","h1","span","className","p","BackupDashboardView","hasPostgresAdapter","db","name","dangerouslySetInnerHTML","__html","h2","role","code","storageKind","backupBlobToken","storageConfigured","blobs","blobToken","sortedBlobs","sort","a","b","ta","pathname","Date","uploadedAt","tb","currentHostname","currentDbName","countOtherDb","filter","blob","dbName","length","countOtherHostname","hostname","lastBackup","data-payload-backup-postgres","strong","toLocaleString","language","map","downloadUrl","size","toISOString","url","i18nLanguage"],"mappings":";AAKA,SAASA,WAAW,EAAEC,sBAAsB,QAAQ,oBAAmB;AACvE,SAASC,oBAAoB,EAAEC,yBAAyB,QAAQ,qBAAoB;AACpF,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,kBAAkB,EAClBC,uBAAuB,EACvBC,iBAAiB,QACZ,oBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,6BAA4B;AACrE,SAASC,qBAAqB,EAAEC,mBAAmB,EAAEC,kBAAkB,QAAQ,iBAAgB;AAC/F,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,MAAM,QAAQ,iBAAgB;AAcvC,SAASC,gBACPC,IAAgD,EAChDC,MAAsC;IAEtC,IAAID,SAAS,MAAM;QACjB,OAAO;IACT;IACA,IAAIA,SAASE,WAAW;QACtB,IAAID,QAAQ;YACV,OAAO;QACT;QACA,OAAO;IACT;IACA,IAAIA,QAAQ;QACV,OAAO,CAACA,OAAOD;IACjB;IACA,oFAAoF;IACpF,qFAAqF;IACrF,OAAO,CAACT,wBAAwBS;AAClC;AAEA,OAAO,MAAMG,kBAAkD,CAAC,EAC9DC,cAAc,EACdC,MAAM,EACNC,YAAY,EACZ,GAAGC,OACJ;IAEC,qBACE,KAACV;QACCW,MAAMJ,eAAeK,GAAG,CAACD,IAAI;QAC7BE,QAAQN,eAAeM,MAAM;QAC7BL,QAAQA;QACRM,SAASP,eAAeK,GAAG,CAACE,OAAO;QACnCC,aAAaR,eAAeQ,WAAW;QACvCN,cAAcA;QACdN,MAAMI,eAAeK,GAAG,CAACT,IAAI,IAAIE;QACjCW,iBAAiBT,e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AAIQ,WAAU;;0CACb,MAACR;gCAAIQ,WAAU;;kDACb,MAACD;wCAAKC,WAAU;;0DACd,KAACD;gDAAKC,WAAU;0DAAgC;;4CAC/CW,gBAAgB,OAAO,WAAW;;;kDAErC,MAACZ;wCAAKC,WAAU;;0DACd,KAACD;gDAAKC,WAAU;0DAAgC;;4CAC/CgB,YAAYe,MAAM;4CAAC;4CAAQf,YAAYe,MAAM,KAAK,IAAI,KAAK;;;kDAE9D,MAAChC;wCAAKC,WAAU;;0DACd,KAACD;gDAAKC,WAAU;0DAAgC;;4CAC/CkC,aACC,IAAIZ,KACFxD,oBACEI,kBAAkBgE,WAAWb,QAAQ,GACrC,IAAIC,KAAKY,WAAWX,UAAU,IAEhCc,cAAc,CAACnD,MAAMoD,YAAY,QACnC;;;;;0CAGN,MAAC9C;gCAAIQ,WAAU;;kDACb,KAAC3B;kDACD,KAACC;;;;;kCAIL,KAACF;wBACC0C,OAAOE,YAAYuB,GAAG,CAAC,CAACpB,IAAO,CAAA;gCAC7BqB,aAAarB,EAAEqB,WAAW;gCAC1BnB,UAAUF,EAAEE,QAAQ;gCACpBoB,MAAMtB,EAAEsB,IAAI;gCACZlB,YAAY,IAAID,KAAKH,EAAEI,UAAU,EAAEmB,WAAW;gCAC9CC,KAAKxB,EAAEwB,GAAG;4BACZ,CAAA;wBACAhB,cAAcA;wBACdK,oBAAoBA;wBACpBN,eAAeA;wBACfD,iBAAiBA;wBACjBmB,cAAc1D,MAAMoD,YAAY;;;;;;AAK1C,EAAC;AAED,eAAezD,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/BackupDashboard/index.tsx"],"sourcesContent":["import type { I18n } from '@payloadcms/translations'\nimport type { AdminViewServerProps, Payload } from 'payload'\n\nimport { DefaultTemplate } from '@payloadcms/next/templates'\nimport { Gutter } from '@payloadcms/ui'\n\nimport type { BackupPluginOptions } from '../../types'\n\nimport { listBackups, resolveBackupListToken } from '../../core/backup'\nimport { getBackupStorageKind, isBackupStorageConfigured } from '../../core/storage'\nimport {\n getBackupSortTimeMs,\n getCurrentDbName,\n getCurrentHostname,\n isUserAllowedByEnvRoles,\n transformBlobName,\n} from '../../utils/index'\nimport { backupDashboardInlineCss } from './backupDashboardInlineCss'\nimport {\n BackupListCollapsible,\n BackupSettingsModal,\n BackupUploadProgress,\n ManualBackupDialog,\n} from './index.client'\n\ninterface BackupDashboardProps {\n i18n: I18n\n /**\n * Payload instance injected by Payload's admin `RenderServerComponent` as a server prop\n * for `afterDashboard` components. Avoids importing `@payload-config` from the plugin,\n * which does not resolve when the plugin runs from `node_modules`.\n */\n payload?: Payload\n /** Optional on admin server props; omitted does not mean logged out (see `defaultIsHidden`). */\n user?: null | Record<string, unknown>\n}\n\nfunction defaultIsHidden(\n user: null | Record<string, unknown> | undefined,\n access?: BackupPluginOptions['access'],\n): boolean {\n if (user === null) {\n return true\n }\n if (user === undefined) {\n if (access) {\n return true\n }\n return false\n }\n if (access) {\n return !access(user)\n }\n // Role allow-list via `PAYLOAD_BACKUP_ALLOWED_ROLES`. When unset, falls back to the\n // historical default (admin role, or \"visible\" when the project has no roles field).\n return !isUserAllowedByEnvRoles(user)\n}\n\nexport const BackupDashboard: React.FC<AdminViewServerProps> = ({\n initPageResult,\n params,\n searchParams,\n ...props\n}) => {\n\n return (\n <DefaultTemplate\n i18n={initPageResult.req.i18n}\n locale={initPageResult.locale}\n params={params}\n payload={initPageResult.req.payload}\n permissions={initPageResult.permissions}\n searchParams={searchParams}\n user={initPageResult.req.user || undefined}\n visibleEntities={initPageResult.visibleEntities}\n >\n <Gutter>\n <div style={{display: 'flex', flexDirection: 'column', gap: '8px', marginBottom: '24px'}}>\n <h1>Backups <span className=\"experimental\">(experimental)</span></h1>\n <p>Here you can manage your database backups</p>\n </div>\n <BackupDashboardView i18n={initPageResult.req.i18n} payload={initPageResult.req.payload}user={initPageResult.req.user || undefined} />\n </Gutter>\n </DefaultTemplate>\n )\n}\n\nexport const BackupDashboardView: React.FC<BackupDashboardProps> = async ({ i18n, payload, user }) => {\n if (defaultIsHidden(user)) {\n return null\n }\n\n const hasPostgresAdapter = (payload?.db as { name?: string } | undefined)?.name === 'postgres'\n if (!hasPostgresAdapter) {\n return (\n <>\n <style dangerouslySetInnerHTML={{ __html: backupDashboardInlineCss }} />\n <div className=\"backup-dashboard\">\n <h2>\n Backups <span className=\"experimental\">(experimental)</span>\n </h2>\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n This plugin requires Payload's Postgres adapter (\n <code className=\"backup-dashboard__setup-hint-code\">@payloadcms/db-postgres</code> or{' '}\n <code className=\"backup-dashboard__setup-hint-code\">\n @payloadcms/db-vercel-postgres\n </code>\n ). For MongoDB use @trieb.work/payload-plugin-backup-mongodb.\n </p>\n </div>\n </>\n )\n }\n\n if (!payload) {\n // Should not happen in a normal Payload admin render; guard for safety.\n return (\n <>\n <style dangerouslySetInnerHTML={{ __html: backupDashboardInlineCss }} />\n <div className=\"backup-dashboard\">\n <h2>\n Backups <span className=\"experimental\">(experimental)</span>\n </h2>\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n Backup dashboard could not initialise: Payload instance was not provided by the admin\n server props.\n </p>\n </div>\n </>\n )\n }\n\n const storageKind = getBackupStorageKind()\n const backupBlobToken = await resolveBackupListToken(payload)\n const storageConfigured = isBackupStorageConfigured(backupBlobToken)\n\n const blobs = storageConfigured ? await listBackups(payload, { blobToken: backupBlobToken }) : []\n const sortedBlobs = [...blobs].sort((a, b) => {\n const ta = getBackupSortTimeMs(transformBlobName(a.pathname), new Date(a.uploadedAt))\n const tb = getBackupSortTimeMs(transformBlobName(b.pathname), new Date(b.uploadedAt))\n return tb - ta\n })\n const currentHostname = getCurrentHostname()\n const currentDbName = getCurrentDbName()\n\n const countOtherDb = sortedBlobs.filter((blob) => {\n const { dbName } = transformBlobName(blob.pathname)\n return currentDbName !== dbName\n }).length\n\n const countOtherHostname = sortedBlobs.filter((blob) => {\n const { hostname } = transformBlobName(blob.pathname)\n return currentHostname !== hostname\n }).length\n const lastBackup = sortedBlobs[0]\n\n return (\n <>\n <style\n dangerouslySetInnerHTML={{ __html: backupDashboardInlineCss }}\n data-payload-backup-postgres=\"1\"\n />\n <div className=\"backup-dashboard\">\n {!storageConfigured && storageKind === 's3' && (\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n Set <code className=\"backup-dashboard__setup-hint-code\">BACKUP_S3_BUCKET</code> (and\n credentials) to enable the S3 backup target. Until then, the list stays empty and cron\n or manual backups cannot run.\n </p>\n )}\n {!storageConfigured && storageKind === 'vercel-blob' && (\n <p className=\"backup-dashboard__setup-hint\" role=\"status\">\n Add a Vercel Blob read/write token: set environment variable{' '}\n <code className=\"backup-dashboard__setup-hint-code\">BLOB_READ_WRITE_TOKEN</code>, or\n open <strong>Backup settings</strong> and paste a token. Until then, the list stays\n empty and cron or manual backups cannot run.\n </p>\n )}\n\n <div className=\"backup-dashboard__toolbar\">\n <div className=\"backup-dashboard__toolbar-meta\">\n <span className=\"backup-dashboard__toolbar-pill\">\n <span className=\"backup-dashboard__toolbar-key\">Storage</span>\n {storageKind === 's3' ? 'AWS S3' : 'Vercel Blob'}\n </span>\n <span className=\"backup-dashboard__toolbar-pill\">\n <span className=\"backup-dashboard__toolbar-key\">Total</span>\n {sortedBlobs.length} backup{sortedBlobs.length === 1 ? '' : 's'}\n </span>\n <span className=\"backup-dashboard__toolbar-pill\">\n <span className=\"backup-dashboard__toolbar-key\">Last backup</span>\n {lastBackup ?\n new Date(\n getBackupSortTimeMs(\n transformBlobName(lastBackup.pathname),\n new Date(lastBackup.uploadedAt),\n ),\n ).toLocaleString(i18n?.language || 'en')\n : 'No backups yet'}\n </span>\n </div>\n <div className=\"make-backup-actions\">\n <BackupSettingsModal />\n <ManualBackupDialog />\n </div>\n </div>\n\n <BackupUploadProgress />\n\n <BackupListCollapsible\n blobs={sortedBlobs.map((b) => ({\n downloadUrl: b.downloadUrl,\n pathname: b.pathname,\n size: b.size,\n uploadedAt: new Date(b.uploadedAt).toISOString(),\n url: b.url,\n }))}\n countOtherDb={countOtherDb}\n countOtherHostname={countOtherHostname}\n currentDbName={currentDbName}\n currentHostname={currentHostname}\n i18nLanguage={i18n?.language || 'en'}\n />\n </div>\n </>\n )\n}\n\nexport default BackupDashboard"],"names":["DefaultTemplate","Gutter","listBackups","resolveBackupListToken","getBackupStorageKind","isBackupStorageConfigured","getBackupSortTimeMs","getCurrentDbName","getCurrentHostname","isUserAllowedByEnvRoles","transformBlobName","backupDashboardInlineCss","BackupListCollapsible","BackupSettingsModal","BackupUploadProgress","ManualBackupDialog","defaultIsHidden","user","access","undefined","BackupDashboard","initPageResult","params","searchParams","props","i18n","req","locale","payload","permissions","visibleEntities","div","style","display","flexDirection","gap","marginBottom","h1","span","className","p","BackupDashboardView","hasPostgresAdapter","db","name","dangerouslySetInnerHTML","__html","h2","role","code","storageKind","backupBlobToken","storageConfigured","blobs","blobToken","sortedBlobs","sort","a","b","ta","pathname","Date","uploadedAt","tb","currentHostname","currentDbName","countOtherDb","filter","blob","dbName","length","countOtherHostname","hostname","lastBackup","data-payload-backup-postgres","strong","toLocaleString","language","map","downloadUrl","size","toISOString","url","i18nLanguage"],"mappings":";AAGA,SAASA,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,MAAM,QAAQ,iBAAgB;AAIvC,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,oBAAmB;AACvE,SAASC,oBAAoB,EAAEC,yBAAyB,QAAQ,qBAAoB;AACpF,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,kBAAkB,EAClBC,uBAAuB,EACvBC,iBAAiB,QACZ,oBAAmB;AAC1B,SAASC,wBAAwB,QAAQ,6BAA4B;AACrE,SACEC,qBAAqB,EACrBC,mBAAmB,EACnBC,oBAAoB,EACpBC,kBAAkB,QACb,iBAAgB;AAcvB,SAASC,gBACPC,IAAgD,EAChDC,MAAsC;IAEtC,IAAID,SAAS,MAAM;QACjB,OAAO;IACT;IACA,IAAIA,SAASE,WAAW;QACtB,I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CACZlB,YAAY,IAAID,KAAKH,EAAEI,UAAU,EAAEmB,WAAW;gCAC9CC,KAAKxB,EAAEwB,GAAG;4BACZ,CAAA;wBACAhB,cAAcA;wBACdK,oBAAoBA;wBACpBN,eAAeA;wBACfD,iBAAiBA;wBACjBmB,cAAc1D,MAAMoD,YAAY;;;;;;AAK1C,EAAC;AAED,eAAezD,gBAAe"}
|
package/dist/core/backup.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { list } from '@vercel/blob';
|
|
2
|
+
import { serializeBackupUploadProgress } from '../utils/backupUploadProgress.js';
|
|
2
3
|
import { createBlobName, getCurrentDbName, getCurrentHostname, sanitizeBackupLabel } from '../utils/index.js';
|
|
3
4
|
import { createTarGzip } from './archive.js';
|
|
4
5
|
import { readBackupBlobContentFlexible } from './backupBlobIO.js';
|
|
@@ -7,7 +8,7 @@ import { getPgDb, listTables, qi, qualified, withClient } from './db.js';
|
|
|
7
8
|
import { ARCHIVE_FORMAT, ARCHIVE_VERSION, DATABASE_FILE_NAME, MEDIA_PREFIX, serializeBackupDocument } from './pgArchive.js';
|
|
8
9
|
import { getBackupStorageKind, resolveBackupStorage } from './storage/index.js';
|
|
9
10
|
import { resolveTableOwners } from './tableGroups.js';
|
|
10
|
-
import { updateBackupTask } from './taskProgress.js';
|
|
11
|
+
import { isBackupTaskCancelled, updateBackupTask } from './taskProgress.js';
|
|
11
12
|
export { DATABASE_FILE_NAME } from './pgArchive.js';
|
|
12
13
|
/**
|
|
13
14
|
* Resolves the Vercel Blob read/write token the same way as backup endpoints and
|
|
@@ -200,6 +201,9 @@ export async function createBackup(payload, options = {}) {
|
|
|
200
201
|
includeMedia
|
|
201
202
|
}, '[backup] Starting backup');
|
|
202
203
|
if (taskId) {
|
|
204
|
+
if (await isBackupTaskCancelled(payload, taskId)) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
203
207
|
await updateBackupTask(payload, taskId, {
|
|
204
208
|
message: 'Starting backup',
|
|
205
209
|
status: 'running'
|
|
@@ -214,6 +218,9 @@ export async function createBackup(payload, options = {}) {
|
|
|
214
218
|
count: oldest.length
|
|
215
219
|
}, '[backup] Pruning old cron backups');
|
|
216
220
|
if (taskId) {
|
|
221
|
+
if (await isBackupTaskCancelled(payload, taskId)) {
|
|
222
|
+
throw new Error('Backup cancelled');
|
|
223
|
+
}
|
|
217
224
|
await updateBackupTask(payload, taskId, {
|
|
218
225
|
message: `Pruning ${oldest.length} old cron backup${oldest.length === 1 ? '' : 's'}`
|
|
219
226
|
});
|
|
@@ -242,9 +249,15 @@ export async function createBackup(payload, options = {}) {
|
|
|
242
249
|
table
|
|
243
250
|
}, '[backup] Table dumped');
|
|
244
251
|
if (taskId) {
|
|
252
|
+
if (await isBackupTaskCancelled(payload, taskId)) {
|
|
253
|
+
throw new Error('Backup cancelled');
|
|
254
|
+
}
|
|
245
255
|
await updateBackupTask(payload, taskId, {
|
|
246
256
|
message: `Dumped table ${table} (${rowCount} rows)`
|
|
247
257
|
});
|
|
258
|
+
if (taskId && await isBackupTaskCancelled(payload, taskId)) {
|
|
259
|
+
throw new Error('Backup cancelled');
|
|
260
|
+
}
|
|
248
261
|
}
|
|
249
262
|
},
|
|
250
263
|
skipTables: skipCollections
|
|
@@ -263,16 +276,71 @@ export async function createBackup(payload, options = {}) {
|
|
|
263
276
|
}
|
|
264
277
|
}
|
|
265
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
|
+
}
|
|
266
282
|
const name = `backups/${createBlobName(type, currentDbName, currentHostname, includedTableCount, backupTimestampMs, includeMedia ? 'tar.gz' : 'json', label || undefined)}`;
|
|
267
283
|
payload.logger.info({
|
|
268
284
|
name
|
|
269
285
|
}, '[backup] Uploading backup to blob storage');
|
|
286
|
+
const totalBytes = typeof backupFile === 'string' ? Buffer.byteLength(backupFile) : backupFile.byteLength;
|
|
287
|
+
let lastProgressUpdateAt = 0;
|
|
288
|
+
let progressWrites = Promise.resolve();
|
|
289
|
+
const uploadAbortController = new AbortController();
|
|
290
|
+
let cancellationPoll;
|
|
291
|
+
if (taskId) {
|
|
292
|
+
await updateBackupTask(payload, taskId, {
|
|
293
|
+
message: serializeBackupUploadProgress({
|
|
294
|
+
bytesUploaded: 0,
|
|
295
|
+
totalBytes
|
|
296
|
+
})
|
|
297
|
+
});
|
|
298
|
+
cancellationPoll = setInterval(()=>{
|
|
299
|
+
void isBackupTaskCancelled(payload, taskId).then((cancelled)=>{
|
|
300
|
+
if (cancelled) {
|
|
301
|
+
uploadAbortController.abort();
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
}, 1000);
|
|
305
|
+
}
|
|
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
|
|
317
|
+
});
|
|
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
|
+
}
|
|
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
|
+
}
|
|
270
336
|
if (taskId) {
|
|
271
337
|
await updateBackupTask(payload, taskId, {
|
|
272
|
-
message:
|
|
338
|
+
message: serializeBackupUploadProgress({
|
|
339
|
+
bytesUploaded: totalBytes,
|
|
340
|
+
totalBytes
|
|
341
|
+
})
|
|
273
342
|
});
|
|
274
343
|
}
|
|
275
|
-
await storage.put(name, backupFile);
|
|
276
344
|
payload.logger.info({
|
|
277
345
|
name,
|
|
278
346
|
durationMs: Date.now() - t0
|
package/dist/core/backup.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/backup.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { list } from '@vercel/blob'\n\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 if (taskId) {\n await updateBackupTask(payload, taskId, { message: 'Uploading backup to blob storage' })\n }\n await storage.put(name, backupFile)\n\n payload.logger.info({ name, durationMs: Date.now() - t0 }, '[backup] Backup complete')\n}\n"],"names":["list","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","put","durationMs"],"mappings":"AAEA,SAASA,IAAI,QAAQ,eAAc;AAEnC,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,OAAOX,qBAAqB;YAAEY,WAAWD;YAAOD;QAAK,GAAG9B,IAAI,CAAC;IAC/D;IACA,OAAOoB,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B9D,QAAQsC,MAAM,CAACuB,KAAK,CAAC;gBAAEN,MAAMO;gBAAUH;YAAM,GAAG;YAChD,IAAI+C,QAAQ;gBACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;oBACtCe,SAAS,CAAC,aAAa,EAAE9D,MAAM,EAAE,EAAEG,SAAS,MAAM,CAAC;gBACrD;YACF;QACF;QACAV,YAAYqD;IACd;IAEA,MAAM5F,eAAenB,wBAAwBuF;IAC7C,MAAMsD,qBAAqBnE,OAAOC,IAAI,CAACY,IAAIvB,MAAM,EAAEhD,MAAM;IACzD,MAAM8H,oBAAoBrD,KAAKiC,GAAG;IAElC,IAAIZ,cAAc;QAChBxG,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;YAAEoB,OAAO3H,eAAeJ,MAAM;QAAC,GAAG;QACtD,IAAIgG,QAAQ;YACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;gBAAEe,SAAS;YAAoC;QACzF;IACF;IAEA,MAAMiB,aACJlC,eACE,MAAM5F,sBAAsBC,cAAcC,gBAAgBP,OAAOI,WAAWX,WAC5Ea;IACJ,MAAM8B,OAAO,CAAC,QAAQ,EAAElE,eACtByI,MACAD,eACAD,iBACAuB,oBACAC,mBACAhC,eAAe,WAAW,QAC1BG,SAAShG,YACR;IAEHX,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;QAAE1E;IAAK,GAAG;IAC9B,IAAI+D,QAAQ;QACV,MAAM5G,iBAAiBE,SAAS0G,QAAQ;YAAEe,SAAS;QAAmC;IACxF;IACA,MAAMV,QAAQ4B,GAAG,CAAChG,MAAM+F;IAExB1I,QAAQsC,MAAM,CAAC+E,IAAI,CAAC;QAAE1E;QAAMiG,YAAYzD,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,mBAA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,CAACC;gBAChD,IAAIA,WAAW;oBACbN,sBAAsBO,KAAK;gBAC7B;YACF;QACF,GAAG;IACL;IACA,IAAI;QACF,MAAMzC,QAAQ0C,GAAG,CACf9G,MACAgG,YACAjC,SACE,CAAC,EAAEgD,MAAM,EAAEC,KAAK,EAAE;YAChB,MAAMvC,MAAMjC,KAAKiC,GAAG;YACpB,IAAIA,MAAM0B,uBAAuB,OAAOY,SAASC,OAAO;gBACtD;YACF;YACAb,uBAAuB1B;YACvB,MAAMwC,qBAAqBD,QAAQ,IAAIA,QAAQf;YAC/C,MAAMnB,UAAUlJ,8BAA8B;gBAC5C6K,eAAeM;gBACfd,YAAYgB;YACd;YACAb,iBAAiBA,eAAeO,IAAI,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"}
|
|
@@ -51,4 +51,7 @@ export declare function readBackupBlobContentFlexible(pathname: string, download
|
|
|
51
51
|
* `access: 'private'`). Returns the effective access level that succeeded so callers can log/track
|
|
52
52
|
* it; throws the original error if both attempts fail.
|
|
53
53
|
*/
|
|
54
|
-
export declare function putBackupBlobContent(pathname: string, body: Buffer | string | Uint8Array, token: string | undefined, access: BackupBlobAccessLevel
|
|
54
|
+
export declare function putBackupBlobContent(pathname: string, body: Buffer | string | Uint8Array, token: string | undefined, access: BackupBlobAccessLevel, onProgress?: (progress: {
|
|
55
|
+
loaded: number;
|
|
56
|
+
total: number;
|
|
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) {
|
|
136
|
+
*/ export async function putBackupBlobContent(pathname, body, token, access, onProgress, signal) {
|
|
137
137
|
const order = access === 'private' ? [
|
|
138
138
|
'private',
|
|
139
139
|
'public'
|
|
@@ -148,12 +148,19 @@ export async function bufferFromWebReadableStream(stream) {
|
|
|
148
148
|
access: attempt,
|
|
149
149
|
addRandomSuffix: false,
|
|
150
150
|
allowOverwrite: true,
|
|
151
|
+
...signal ? {
|
|
152
|
+
abortSignal: signal
|
|
153
|
+
} : {},
|
|
154
|
+
onUploadProgress: onProgress,
|
|
151
155
|
...token ? {
|
|
152
156
|
token
|
|
153
157
|
} : {}
|
|
154
158
|
});
|
|
155
159
|
return attempt;
|
|
156
160
|
} catch (error) {
|
|
161
|
+
if (signal?.aborted) {
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
157
164
|
if (firstError === undefined) {
|
|
158
165
|
firstError = error;
|
|
159
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): 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 ...(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","order","firstError","attempt","addRandomSuffix","allowOverwrite","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;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,OAAO;QAAEG,SAAS;YAAEC,eAAe,CAAC,OAAO,EAAEH,OAAO;QAAC;IAAE,IAAII;IACvF,OA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EA,8FAA8F,GAC9F,SAASY,4BAA4BD,KAAc;IACjD,MAAME,MACJF,iBAAiBX,QAAQW,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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QAAQ,CAAC,aACdF,CAAAA,MAAME,QAAQ,CAAC,aACdF,MAAME,QAAQ,CAAC,cACfF,MAAME,QAAQ,CAAC,kBACfF,MAAME,QAAQ,CAAC,UAAS;AAE9B"}
|
|
@@ -26,7 +26,10 @@ export declare class S3BackupStorage implements BackupStorageAdapter {
|
|
|
26
26
|
contentType: string;
|
|
27
27
|
stream: ReadableStream<Uint8Array<ArrayBufferLike>>;
|
|
28
28
|
} | null>;
|
|
29
|
-
put(pathname: string, body: Buffer | string | Uint8Array
|
|
29
|
+
put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: {
|
|
30
|
+
loaded: number;
|
|
31
|
+
total: number;
|
|
32
|
+
}) => void, signal?: AbortSignal): Promise<{
|
|
30
33
|
pathname: string;
|
|
31
34
|
url: string;
|
|
32
35
|
}>;
|
package/dist/core/storage/s3.js
CHANGED
|
@@ -147,19 +147,44 @@ function contentTypeFor(pathname) {
|
|
|
147
147
|
return null;
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
|
-
async put(pathname, body) {
|
|
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);
|
|
154
|
-
|
|
154
|
+
const uploadBody = typeof body === 'string' ? Buffer.from(body) : body;
|
|
155
|
+
const total = uploadBody.byteLength;
|
|
156
|
+
const upload = new Upload({
|
|
155
157
|
client,
|
|
156
158
|
params: {
|
|
157
|
-
Body:
|
|
159
|
+
Body: uploadBody,
|
|
158
160
|
Bucket: this.cfg.bucket,
|
|
159
161
|
ContentType: contentTypeFor(pathname),
|
|
160
162
|
Key: key
|
|
161
163
|
}
|
|
162
|
-
})
|
|
164
|
+
});
|
|
165
|
+
if (onProgress) {
|
|
166
|
+
upload.on('httpUploadProgress', (progress)=>{
|
|
167
|
+
onProgress({
|
|
168
|
+
loaded: progress.loaded ?? 0,
|
|
169
|
+
total
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
}
|
|
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
|
+
}
|
|
163
188
|
return {
|
|
164
189
|
pathname,
|
|
165
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(pathname: string, body: Buffer | string | Uint8Array) {\n const { Upload } = await import('@aws-sdk/lib-storage')\n const client = await this.client()\n const key = this.toKey(pathname)\n await new Upload({\n client,\n params: {\n Body: typeof body === 'string' ? Buffer.from(body) : body,\n Bucket: this.cfg.bucket,\n ContentType: contentTypeFor(pathname),\n Key: key,\n },\n }).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","Upload","params","Buffer","from","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;IACM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9E;QACA,MAAMgF,QAAQ,MAAM,AAClBpC,IAAIuB,IAAI,CACRc,oBAAoB;QACtB,OAAOL,OAAOC,IAAI,CAACG;IACrB;IAEA,MAAME,WAA6C;QACjD,IAAI;YACF,MAAM,EAAEC,iBAAiB,EAAE,GAAG,MAAM,IAAI,CAAC1E,GAAG;YAC5C,MAAMQ,SAAS,MAAM,IAAI,CAACA,MAAM;YAChC,MAAMA,OAAOqB,IAAI,CAAC,IAAI6C,kBAAkB;gBAAEtD,QAAQ,IAAI,CAAC1B,GAAG,CAAC2B,MAAM;YAAC;YAClE,OAAO;gBAAEsD,IAAI;YAAK;QACpB,EAAE,OAAOC,OAAO;YACd,OAAO;gBACLA,OAAOA,iBAAiBpD,QAAQoD,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;oBAAaC;oBAAiBC;gBAAa;YAAE,IAC9D,CAAC,CAAC;QACN;IACF;IAEA,MAAcK,SAA4B;QACxC,IAAI,CAAC,IAAI,CAACb,aAAa,EAAE;YACvB,IAAI,CAACA,aAAa,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I,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"}
|
|
@@ -33,6 +33,10 @@ export interface BackupStorageRef {
|
|
|
33
33
|
pathname: string;
|
|
34
34
|
url?: null | string;
|
|
35
35
|
}
|
|
36
|
+
export interface BackupStorageUploadProgress {
|
|
37
|
+
loaded: number;
|
|
38
|
+
total: number;
|
|
39
|
+
}
|
|
36
40
|
/**
|
|
37
41
|
* Provider-agnostic operations the plugin performs on backup archives. Implementations live in
|
|
38
42
|
* `vercelBlob.ts` and `s3.ts`; callers obtain one via {@link resolveBackupStorage}.
|
|
@@ -49,7 +53,7 @@ export interface BackupStorageAdapter {
|
|
|
49
53
|
stream: ReadableStream<Uint8Array>;
|
|
50
54
|
} | null>;
|
|
51
55
|
/** Upload an archive at `pathname`. */
|
|
52
|
-
put(pathname: string, body: Buffer | string | Uint8Array): Promise<{
|
|
56
|
+
put(pathname: string, body: Buffer | string | Uint8Array, onProgress?: (progress: BackupStorageUploadProgress) => void, signal?: AbortSignal): Promise<{
|
|
53
57
|
pathname: string;
|
|
54
58
|
url: string;
|
|
55
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\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 ): 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":"
|
|
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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { BackupStorageAdapter, BackupStorageObject, BackupStorageRef, BackupStorageValidation } from './types.js';
|
|
1
|
+
import type { BackupStorageAdapter, BackupStorageObject, BackupStorageRef, BackupStorageUploadProgress, BackupStorageValidation } from './types.js';
|
|
2
2
|
import { type BackupBlobAccessLevel } from '../backupBlobIO.js';
|
|
3
3
|
/**
|
|
4
4
|
* Vercel Blob backup target — the historical default. This is a thin wrapper around the existing
|
|
@@ -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): 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
|
}>;
|