From 03251a4cd7666c33bf81a8f375d2bcd5935238fd Mon Sep 17 00:00:00 2001 From: Manu Date: Mon, 23 Nov 2026 16:39:06 -0600 Subject: [PATCH 1/7] Add Cloudflare D1 as a database source Backs up and restores the D1 databases of a Cloudflare account through the REST API of Cloudflare, with an API token from a Token credential profile. The export is polled and its SQL dump stored unchanged. A restore into an existing database puts the drops ahead of the dump in one import, so a failed import leaves the database as it was, and logs the Time Travel bookmark from before. A new name creates the database in the jurisdiction of the source or where the connection says. A check before the export warns about integers beyond 2^53, which the export of Cloudflare rounds. --- README.md | 1 + changelog/unreleased/Skyfay-cloudflare-d1.md | 7 + docs/.vitepress/config.mts | 1 + docs/developer-guide/adapters/database.md | 4 +- docs/user-guide/sources/cloudflare-d1.md | 101 ++++++++ docs/user-guide/sources/index.md | 1 + .../adapter/database-form-layout.ts | 19 ++ .../adapter/database-form-sections.tsx | 17 +- src/components/adapter/enum-labels.ts | 12 + src/components/adapter/utils.ts | 2 + .../storage/restore/use-restore-databases.ts | 2 +- src/lib/adapters/combinable.ts | 1 + src/lib/adapters/connection-summary.ts | 2 + .../adapters/database/cloudflare-d1/api.ts | 234 ++++++++++++++++++ .../database/cloudflare-d1/browser.ts | 107 ++++++++ .../database/cloudflare-d1/connection.ts | 57 +++++ .../adapters/database/cloudflare-d1/dump.ts | 64 +++++ .../adapters/database/cloudflare-d1/index.ts | 35 +++ .../adapters/database/cloudflare-d1/jobs.ts | 153 ++++++++++++ .../database/cloudflare-d1/large-integers.ts | 72 ++++++ .../database/cloudflare-d1/restore.ts | 166 +++++++++++++ .../adapters/database/cloudflare-d1/sql.ts | 21 ++ .../database/cloudflare-d1/transfer.ts | 77 ++++++ src/lib/adapters/definitions/database.ts | 14 +- src/lib/adapters/definitions/index.ts | 3 +- src/lib/adapters/dialed-hosts.ts | 2 + src/lib/adapters/index.ts | 3 + src/lib/auth/adapter-permissions.ts | 1 + src/lib/core/credential-requirements.ts | 1 + src/lib/runner/steps/dump-databases.ts | 1 + src/services/storage/backup-contents.ts | 2 +- .../database/cloudflare-d1/api.test.ts | 111 +++++++++ .../cloudflare-d1/backup-restore.test.ts | 211 ++++++++++++++++ .../database/cloudflare-d1/browser.test.ts | 59 +++++ .../database/cloudflare-d1/fake-cloudflare.ts | 65 +++++ website/src/i18n/messages/de.json | 4 + website/src/i18n/messages/en.json | 4 + website/src/lib/adapter-icons.ts | 1 + website/src/lib/content.ts | 1 + website/src/lib/integrations.ts | 2 + 40 files changed, 1635 insertions(+), 6 deletions(-) create mode 100644 changelog/unreleased/Skyfay-cloudflare-d1.md create mode 100644 docs/user-guide/sources/cloudflare-d1.md create mode 100644 src/lib/adapters/database/cloudflare-d1/api.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/browser.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/connection.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/dump.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/index.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/jobs.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/large-integers.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/restore.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/sql.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/transfer.ts create mode 100644 tests/unit/adapters/database/cloudflare-d1/api.test.ts create mode 100644 tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts create mode 100644 tests/unit/adapters/database/cloudflare-d1/browser.test.ts create mode 100644 tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts diff --git a/README.md b/README.md index adb154b8e..8a3e6c8a3 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ Nothing locks you in. Every database backup is a standard dump and every file ba | SQLite | 3.x | Local, SSH | Yes | | Microsoft SQL Server | 2017, 2019, 2022, Azure SQL Edge | Direct, SSH | Yes | | Azure SQL Database (beta) | Single database, elastic pool | Direct | Yes, drops the target first | +| Cloudflare D1 (beta) | Every D1 database of an account | API token | Yes, replaces the tables | | Firebird (beta) | 3.x, 4.x, 5.x | Direct, SSH | Yes, through configured aliases | **Destinations**: local filesystem, Amazon S3 and S3-compatible storage like Cloudflare R2, Hetzner, MinIO or Wasabi, Google Drive, Dropbox, OneDrive, SFTP, FTP/FTPS, WebDAV, SMB and rsync over SSH. Each of them can also be a source for file backups, and so can Docker volumes. diff --git a/changelog/unreleased/Skyfay-cloudflare-d1.md b/changelog/unreleased/Skyfay-cloudflare-d1.md new file mode 100644 index 000000000..1c9d28617 --- /dev/null +++ b/changelog/unreleased/Skyfay-cloudflare-d1.md @@ -0,0 +1,7 @@ +### ✨ Features + +- **Cloudflare D1**: New source that backs up and restores the D1 databases of a Cloudflare account through its API, with an API token and nothing to install. A restore keeps the database and its ID and logs a Time Travel bookmark to go back to. ([#202](https://github.com/Skyfay/DBackup/issues/202)) + +### 📝 Documentation + +- **Cloudflare D1**: New source guide with the token setup, the lock during an export and the integers the export of Cloudflare rounds. diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index e2f92102e..a56d4e85f 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -112,6 +112,7 @@ export default defineConfig({ { text: 'SQLite', link: '/user-guide/sources/sqlite' }, { text: 'Microsoft SQL Server', link: '/user-guide/sources/mssql' }, { text: 'Azure SQL Database', link: '/user-guide/sources/azure-sql' }, + { text: 'Cloudflare D1', link: '/user-guide/sources/cloudflare-d1' }, { text: 'Firebird', link: '/user-guide/sources/firebird' } ] }, diff --git a/docs/developer-guide/adapters/database.md b/docs/developer-guide/adapters/database.md index e4678297e..7002a3350 100644 --- a/docs/developer-guide/adapters/database.md +++ b/docs/developer-guide/adapters/database.md @@ -13,6 +13,7 @@ Database adapters handle the dump and restore operations for different database | SQLite | `sqlite` | None (file copy) | ✅ | `sqlite` | | MSSQL | `mssql` | None (TDS protocol) | ✅ (TDS tunnelled) | `bak` | | Azure SQL Database | `azure-sql` | `sqlpackage` | ❌ (public PaaS endpoint) | `bacpac` | +| Cloudflare D1 | `cloudflare-d1` | None (REST API of Cloudflare) | ❌ (public API) | `sql` | | Redis | `redis` | `redis-cli` | ✅ | `rdb` | | Firebird | `firebird` | `gbak`, `isql` | ✅ | `fbk` | @@ -24,7 +25,7 @@ Each adapter declares the format of its dump in `DB_FORMAT_BY_ADAPTER` in `src/l | Format | Extension | Adapters | Stored as-is | |--------|-----------|----------|--------------| -| `sql` | `.sql` | MySQL, MariaDB | | +| `sql` | `.sql` | MySQL, MariaDB, Cloudflare D1 | | | `custom` | `.dump` | PostgreSQL | ✅ unless compression is `NONE` | | `archive` | `.archive` | MongoDB | ✅ (`--gzip`) | | `bak` | `.bak` | MSSQL | | @@ -125,6 +126,7 @@ Each database adapter can optionally return size and table count information. Th | **MongoDB** | Native `sizeOnDisk` from `listDatabases` command | `listCollections().length` per database | | **MSSQL** | `sys.master_files` (`SUM(size) * 8 * 1024`) | `COUNT(*)` from `INFORMATION_SCHEMA.TABLES` | | **Azure SQL Database** | `sys.database_files` (`SUM(size) * 8 * 1024`, data files only), one connection per database | `COUNT(*)` from `sys.tables`, same connection | +| **Cloudflare D1** | `file_size` of the database list, one API call for all | `num_tables` of the same list | | **SQLite** | Not supported | Not supported | | **Redis** | Not supported | Not supported | diff --git a/docs/user-guide/sources/cloudflare-d1.md b/docs/user-guide/sources/cloudflare-d1.md new file mode 100644 index 000000000..bc9705999 --- /dev/null +++ b/docs/user-guide/sources/cloudflare-d1.md @@ -0,0 +1,101 @@ +# Cloudflare D1 + +Backs up the D1 databases of a Cloudflare account through the API of Cloudflare, with an API token and nothing to install. + +## Supported Versions + +| Database | Supported | Note | +| :--- | :--- | :--- | +| D1 databases of the current storage backend (`version: production`) | ✅ | Every database since D1 left its alpha | +| D1 databases of the alpha backend | ❌ | Cloudflare offers no export for them | +| Databases with a virtual table (FTS5, R*Tree) | ❌ | Cloudflare refuses to export them, see [Troubleshooting](#cannot-export-databases-with-virtual-tables) | + +The connection is a whole Cloudflare account. A job picks one, several or all of its D1 databases, like the databases of a server. + +## Prerequisites + +An API token of the account with the permission **D1 Edit**: + +1. In the Cloudflare dashboard, open the account and go to **Manage Account > Account API Tokens**. +2. **Create Token**, then **Custom Token**. +3. Under **Permissions**, add **Account > D1 > Edit**. Nothing else is needed. +4. Optionally limit the token to the IP address DBackup connects from and give it an expiry date. + +::: warning D1 Read is not enough +Cloudflare allows the export of a database only with **D1 Edit**, even though a backup never writes. A token with **D1 Read** passes Test connection and fails at the first backup. Cloudflare also has no way to limit a D1 token to single databases: the token can change every D1 database of the account. +::: + +## Configuration + +::: info Credential Profiles +A `TOKEN` [credential profile](/user-guide/security/credential-profiles) holds the API token. Create one in **Vault > Credentials** before saving the source. +::: + +| Field | Description | Default | Required | +| :--- | :--- | :--- | :--- | +| **Account ID** | The 32 hex characters on the overview of the account in the Cloudflare dashboard | - | ✅ | +| **Login** | `TOKEN` credential profile with the API token | - | ✅ | +| **Check for large integers** | Warns in the run log when a column holds an integer the export rounds, see [below](#large-integers) | On | ❌ | +| **Location of new databases** | Where a restore under a new name creates the database: **Automatic**, a jurisdiction (EU, FedRAMP) or a location hint | Automatic | ❌ | + +## Setup Guide + +1. Create the API token as described under [Prerequisites](#prerequisites). +2. In **Vault > Credentials**, add a profile of the type **Token** with the token. +3. In **Connections**, add a source of the type **Cloudflare D1**, enter the account ID and pick the profile. +4. **Test connection** lists the databases of the account. +5. Create a job and pick the databases to back up. + +## How It Works + +Each database is exported by Cloudflare as a SQL dump, the same file `wrangler d1 export` writes. DBackup starts the export, polls it until Cloudflare is done, downloads the dump from R2 and stores it as one `.sql` entry of the backup's archive, unchanged. + +::: warning The database is locked during the export +Cloudflare answers no queries on a database while its export runs. A small database takes a second or two, a large one longer. Schedule the backup for a quiet time. +::: + +Databases are picked by name and looked up on every run, so a database that was deleted and created again under the same name is backed up under its new ID. + +### Large integers + +SQLite stores integers with 64 bits, but the export of Cloudflare writes them through JavaScript numbers, which hold an integer exactly only up to 2^53 (9,007,199,254,740,991). A larger one lands in the dump rounded, and one near 2^63 comes back from a restore as a floating point number. This is a limit of Cloudflare's export that DBackup cannot work around. It mostly concerns IDs like those of Discord or Twitter stored as `INTEGER`. Store them as `TEXT` to keep them exact. + +With **Check for large integers** on, DBackup reads every table once before the export and names each column that holds such a value in the run log. The backup runs either way. The check counts against the rows read of the account, so a connection with large databases can turn it off. + +## Restore + +Restoring onto an existing database **replaces its tables, views and triggers** with those of the backup, like every other source. The database itself stays, with its ID, so the Workers bound to it keep working. The drops and the dump run as one import, which Cloudflare runs in one transaction: if the import fails, the database is left exactly as it was. + +Before it replaces anything, the restore writes the current [Time Travel](https://developers.cloudflare.com/d1/reference/time-travel/) bookmark of the database into its log, with the command that goes back to it: + +```bash +wrangler d1 time-travel restore --bookmark= +``` + +Restoring under a new name creates a new database. With **Location of new databases** on **Automatic**, it gets the jurisdiction of the database the backup came from while that one still exists, otherwise Cloudflare picks the location. The log names the ID of the new database, which a Worker needs as its `database_id`. + +Like the export, an import locks the database while it runs. + +## Troubleshooting + +### Cloudflare refused the export. The API token needs the permission D1 Edit + +The token has **D1 Read** only. Edit the token in the Cloudflare dashboard and change the permission to **D1 Edit**. + +### Cannot export databases with virtual tables + +``` +D1 Export error: cannot export databases with virtual tables (like FTS5) +``` + +**Solution:** Cloudflare cannot export a database that holds a virtual table, like an FTS5 search index. Drop the virtual tables before the backup and create them again afterwards, for example in the Worker that uses them, or leave this database out of the job. + +### Cloudflare refused the API token + +The token is wrong, expired, limited to other IP addresses, or belongs to another account than the account ID. Check it under **Account API Tokens**, and that the account ID is the one of the same account. + +## Next Steps + +- [Restore Guide](/user-guide/features/restore) - General restore documentation +- [Encryption](/user-guide/security/encryption) - Encrypting your backups +- [Database Explorer](/user-guide/features/database-explorer) - Browsing the tables of a D1 database diff --git a/docs/user-guide/sources/index.md b/docs/user-guide/sources/index.md index e93f8fe79..18f53219c 100644 --- a/docs/user-guide/sources/index.md +++ b/docs/user-guide/sources/index.md @@ -15,6 +15,7 @@ DBackup supports a wide variety of database engines. | [SQLite](/user-guide/sources/sqlite) | 3.x | `sqlite3 .backup`, stores the database file | ✅ | | [MSSQL](/user-guide/sources/mssql) | 2017, 2019, 2022, Azure SQL Edge | `BACKUP DATABASE` | ✅ | | [Azure SQL Database](/user-guide/sources/azure-sql) (beta) | Single database, elastic pool | `SqlPackage` BACPAC export | ✅ (drops the target first) | +| [Cloudflare D1](/user-guide/sources/cloudflare-d1) (beta) | Every D1 database of an account | D1 export API, SQL dump | ✅ (replaces the tables, keeps the database) | | [Firebird](/user-guide/sources/firebird) (beta) | 3.x, 4.x, 5.x | `gbak` | ✅ (pre-configured aliases) | ## Directory Sources diff --git a/src/components/adapter/database-form-layout.ts b/src/components/adapter/database-form-layout.ts index 0175b7346..537af3299 100644 --- a/src/components/adapter/database-form-layout.ts +++ b/src/components/adapter/database-form-layout.ts @@ -40,6 +40,8 @@ const NOT_OPTIONS = new Set([ "databases", "database", "uri", "backupPath", "fileTransferMode", "localBackupPath", // The host key check of the SSH login, shown beside it, see `HostKeySwitch`. "verifyHostKey", + // The Cloudflare account of D1, which takes the place of host and port. + "accountId", ]); /** @@ -97,6 +99,22 @@ function sqliteLayout(config: Record): SectionLayout[] { return [...sections, behavior()]; } +/** Cloudflare D1 has no server to reach, its connection is an account and a token. */ +function d1Layout(adapter: AdapterDefinition, config: Record): SectionLayout[] { + const sections: SectionLayout[] = [{ + id: "connection", + label: "Connection", + description: "The Cloudflare account that holds the D1 databases, and an API token with the permission D1 Edit.", + keys: [NAME_KEY, "accountId", LOGIN_KEY], + expects: [NAME_KEY, "accountId", LOGIN_KEY], + }]; + const options = optionKeys(adapter, config); + if (options.length > 0) { + sections.push({ id: "options", label: "Options", description: "Only needed when the defaults do not fit.", keys: options, expects: [] }); + } + return [...sections, behavior()]; +} + /** * The parts of the form for a database, for the mode picked so far. * @@ -105,6 +123,7 @@ function sqliteLayout(config: Record): SectionLayout[] { */ export function databaseLayout(adapter: AdapterDefinition, config: Record): SectionLayout[] { if (adapter.id === "sqlite") return sqliteLayout(config); + if (adapter.id === "cloudflare-d1") return d1Layout(adapter, config); const shape = adapter.configSchema.shape as Record; const hasMode = "connectionMode" in shape; diff --git a/src/components/adapter/database-form-sections.tsx b/src/components/adapter/database-form-sections.tsx index 21cc4edae..1453c9459 100644 --- a/src/components/adapter/database-form-sections.tsx +++ b/src/components/adapter/database-form-sections.tsx @@ -25,11 +25,15 @@ const LABELS: Record = { backupPath: "Backup folder on the server", localBackupPath: "The same folder on this machine", sqliteBinaryPath: "sqlite3 binary", + accountId: "Account ID", + newDatabaseLocation: "Location of new databases", }; const DESCRIPTIONS: Record = { mode: "A single server, or a Sentinel group that points to the current master.", localBackupPath: "The server's backup folder as it is mounted here, for example as a Docker volume or an NFS share.", + accountId: "On the overview of the account in the Cloudflare dashboard.", + newDatabaseLocation: "Where a restore under a new name creates the D1 database. Automatic takes the jurisdiction of the database the backup came from while it still exists.", }; /** Booleans of the database schemas, as sentences that are true when the switch is on. */ @@ -47,6 +51,10 @@ const SWITCHES: Record = { disableSsl: { title: "Disable SSL", description: "For development databases with a self-signed certificate." }, encrypt: { title: "Encrypt the connection", description: "Required by Azure SQL and most hosted servers." }, trustServerCertificate: { title: "Trust the server certificate", description: "Accepts a self-signed certificate, for development servers." }, + checkLargeIntegers: { + title: "Check for large integers", + description: "Warns in the run log when a column holds an integer beyond 2^53, which the export of Cloudflare rounds. Reads every table once more before the export.", + }, }; function Field(props: { adapter: AdapterDefinition; fieldKey: string; label?: string; description?: string; sshCredentialId?: string | null }) { @@ -91,6 +99,7 @@ function ConnectionPart(props: ConnectionSectionProps) { const { adapter } = props; const { watch } = useFormContext(); const isSqlite = adapter.id === "sqlite"; + const isD1 = adapter.id === "cloudflare-d1"; const modeKey = isSqlite ? "mode" : "connectionMode"; const hasMode = modeKey in (adapter.configSchema.shape as Record); const mode = hasMode ? watch(`config.${modeKey}`) : "direct"; @@ -103,7 +112,13 @@ function ConnectionPart(props: ConnectionSectionProps) { )} {isSqlite && mode === "local" && } - {!isSqlite && mode === "direct" && ( + {isD1 && ( + <> + + + + )} + {!isSqlite && !isD1 && mode === "direct" && ( <> diff --git a/src/components/adapter/enum-labels.ts b/src/components/adapter/enum-labels.ts index 7edbb8577..6f9e19296 100644 --- a/src/components/adapter/enum-labels.ts +++ b/src/components/adapter/enum-labels.ts @@ -10,6 +10,18 @@ const ENUM_LABELS: Record> = { storageClass: { STANDARD: "Standard", STANDARD_IA: "Standard, infrequent access", GLACIER: "Glacier", DEEP_ARCHIVE: "Glacier Deep Archive" }, // Cloudflare R2 jurisdiction: { default: "Standard", eu: "EU", fedramp: "FedRAMP" }, + // Cloudflare D1, where a restore creates a new database + newDatabaseLocation: { + auto: "Automatic", + eu: "EU jurisdiction", + fedramp: "FedRAMP jurisdiction", + weur: "Western Europe (hint)", + eeur: "Eastern Europe (hint)", + wnam: "Western North America (hint)", + enam: "Eastern North America (hint)", + apac: "Asia-Pacific (hint)", + oc: "Oceania (hint)", + }, // Email secure: { none: "None (insecure)", ssl: "SSL / TLS", starttls: "STARTTLS" }, }; diff --git a/src/components/adapter/utils.ts b/src/components/adapter/utils.ts index 4e411231a..2e4b31707 100644 --- a/src/components/adapter/utils.ts +++ b/src/components/adapter/utils.ts @@ -77,6 +77,8 @@ const ADAPTER_ICON_MAP: Record = { "mssql": mssqlIcon, // logos:azure is multi-colour, so no ADAPTER_COLOR_MAP entry is needed. "azure-sql": azureIcon, + // logos:cloudflare-icon is multi-colour, like the one of R2. + "cloudflare-d1": cloudflareIcon, "firebird": firebirdIcon, // Storage - Local diff --git a/src/components/dashboard/storage/restore/use-restore-databases.ts b/src/components/dashboard/storage/restore/use-restore-databases.ts index 510a7d360..aec6106d5 100644 --- a/src/components/dashboard/storage/restore/use-restore-databases.ts +++ b/src/components/dashboard/storage/restore/use-restore-databases.ts @@ -9,7 +9,7 @@ import { getCustomerDatabases } from "@/app/actions/tenant/database-assignments" import { buildDbRows, copyName, type CustomerHolders, type DbChoice, type ServerDatabase } from "./restore-model"; /** Adapters that run a server DBackup can list the databases of. The rest restore into a file, like SQLite. */ -const SERVER_ADAPTERS = ["mysql", "mariadb", "postgres", "mongodb", "mssql", "azure-sql", "redis", "valkey", "firebird"]; +const SERVER_ADAPTERS = ["mysql", "mariadb", "postgres", "mongodb", "mssql", "azure-sql", "cloudflare-d1", "redis", "valkey", "firebird"]; /** Whether the picked server can take the backup, and what the page says about it. */ export interface Compatibility { diff --git a/src/lib/adapters/combinable.ts b/src/lib/adapters/combinable.ts index a5b6b3c1a..c2483f406 100644 --- a/src/lib/adapters/combinable.ts +++ b/src/lib/adapters/combinable.ts @@ -14,6 +14,7 @@ export const COMBINABLE_WITH_DIRECTORIES: readonly string[] = [ "firebird", "mssql", "azure-sql", + "cloudflare-d1", "sqlite", ]; diff --git a/src/lib/adapters/connection-summary.ts b/src/lib/adapters/connection-summary.ts index 459a81f42..c44f024c1 100644 --- a/src/lib/adapters/connection-summary.ts +++ b/src/lib/adapters/connection-summary.ts @@ -45,6 +45,8 @@ export function connectionAddress(adapterId: string, configJson: string): string } case "sqlite": return text(config.path) || null; + case "cloudflare-d1": + return config.accountId ? `Account ${text(config.accountId).slice(0, 8)}...` : null; case "local-filesystem": return text(config.basePath) || null; case "docker-volume": { diff --git a/src/lib/adapters/database/cloudflare-d1/api.ts b/src/lib/adapters/database/cloudflare-d1/api.ts new file mode 100644 index 000000000..684e89407 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/api.ts @@ -0,0 +1,234 @@ +import { Readable } from "stream"; +import type { ReadableStream as WebReadableStream } from "stream/web"; +import { AdapterError } from "@/lib/logging/errors"; +import { collectCapped } from "@/lib/adapters/storage/common/read-limit"; +import type { CloudflareD1Config } from "@/lib/adapters/definitions"; + +/** + * The REST API of Cloudflare D1, the only way this adapter reaches a database. + * + * Every call goes to the fixed host `api.cloudflare.com` with the API token as a bearer token. The + * token never appears in a log line or an error message, and neither does a signed URL, see + * `signed-url.ts`. + */ + +const API_BASE = "https://api.cloudflare.com/client/v4/accounts"; + +/** A single API call answers within this time, the long work (export, import) is polled. */ +const REQUEST_TIMEOUT_MS = 60_000; + +/** + * The largest answer of the API this adapter reads. A page of the table browser is the largest + * answer there is, and D1 caps a query result at 50 MB itself. + */ +const RESPONSE_LIMIT = 64 * 1024 * 1024; + +/** An account ID is 32 hex characters. Checked before it becomes part of a URL. */ +const ACCOUNT_ID = /^[0-9a-f]{32}$/i; + +/** A database ID is a UUID. Checked before it becomes part of a URL. */ +const DATABASE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** The fields of a connection this client reads. The token comes from the credential profile. */ +export type D1Connection = Pick & { token?: string }; + +/** A D1 database as list and get describe it. */ +export interface D1Database { + uuid: string; + name: string; + version?: string; + jurisdiction?: string | null; + file_size?: number; + num_tables?: number; + created_at?: string; + running_in_region?: string; +} + +/** One statement's result of the query endpoint. */ +export interface D1QueryResult> { + results: Row[]; + success: boolean; + meta?: { served_by_region?: string; rows_read?: number; duration?: number }; +} + +/** One statement's result of the raw endpoint, rows as arrays. */ +export interface D1RawResult { + results: { columns: string[]; rows: unknown[][] }; + success: boolean; +} + +interface Envelope { + success?: boolean; + errors?: { code?: number; message?: string }[]; + result?: T; + result_info?: { page?: number; per_page?: number; count?: number; total_count?: number }; +} + +/** Cloudflare's own error codes this adapter turns into a sentence a person can act on. */ +const AUTHENTICATION_ERROR = 10000; +const INVALID_TOKEN = 1000; +const NO_PERMISSION = 7500; + +/** + * Whether an error is a call the API refused for a missing right, as opposed to a request that is + * wrong. `d1Request` keeps the status and the codes of Cloudflare in the context of its + * `AdapterError`. A plain `AdapterError` rather than a subclass, since suites that replace the + * module of the error classes load this file too. + */ +export function isPermissionRefusal(error: unknown): boolean { + const context = error instanceof Error ? (error as Error & { context?: { status?: number; codes?: number[] } }).context : undefined; + const status = context?.status; + const codes = Array.isArray(context?.codes) ? context.codes : []; + return status === 401 || status === 403 || codes.includes(AUTHENTICATION_ERROR) || codes.includes(NO_PERMISSION); +} + +/** The account ID of a config, refused unless it has the form Cloudflare gives it. */ +export function accountIdOf(config: D1Connection): string { + const id = typeof config.accountId === "string" ? config.accountId.trim() : ""; + if (!ACCOUNT_ID.test(id)) { + throw new AdapterError("cloudflare-d1", "config", "The account ID must be the 32 hex characters shown in the Cloudflare dashboard."); + } + return id.toLowerCase(); +} + +/** A database ID from an answer of the API, refused unless it is a UUID. */ +export function databaseIdOf(id: unknown): string { + if (typeof id !== "string" || !DATABASE_ID.test(id)) { + throw new AdapterError("cloudflare-d1", "api", "Cloudflare answered with a database ID that is not a UUID."); + } + return id.toLowerCase(); +} + +function tokenOf(config: D1Connection): string { + const token = typeof config.token === "string" ? config.token.trim() : ""; + if (!token) { + throw new AdapterError("cloudflare-d1", "config", "No API token. Pick a credential profile of the type Token."); + } + return token; +} + +/** Reads an answer of the API as JSON, at most `RESPONSE_LIMIT` bytes of it. */ +async function readEnvelope(response: Response): Promise | null> { + if (!response.body) return null; + const bytes = await collectCapped(Readable.fromWeb(response.body as WebReadableStream), RESPONSE_LIMIT); + try { + return JSON.parse(bytes.toString("utf-8")) as Envelope; + } catch { + return null; + } +} + +/** A sentence for a refused call, without anything of the request in it. */ +function describeFailure(status: number, envelope: Envelope | null): { message: string; codes: number[] } { + const errors = envelope?.errors ?? []; + const codes = errors.map((error) => Number(error.code)).filter((code) => Number.isFinite(code)); + if (status === 401 || codes.includes(AUTHENTICATION_ERROR) || codes.includes(INVALID_TOKEN)) { + return { codes, message: "Cloudflare refused the API token. Check that it is active, belongs to this account and has the permission D1 Edit." }; + } + if (status === 403 || codes.includes(NO_PERMISSION)) { + return { codes, message: "The API token is missing a permission for this. It needs D1 Edit." }; + } + const detail = errors.map((error) => error.message).filter(Boolean).join("; "); + return { codes, message: detail ? `Cloudflare answered ${status}: ${detail}` : `Cloudflare answered ${status}.` }; +} + +/** + * One call of the API, with the path below `/accounts/`. Answers the `result` of the envelope + * and throws an `AdapterError` with the status and the codes of Cloudflare in its context for anything + * Cloudflare refused. + */ +export async function d1Request( + config: D1Connection, + operation: string, + method: "GET" | "POST" | "DELETE", + path: string, + body?: unknown, +): Promise<{ result: T; resultInfo?: Envelope["result_info"] }> { + const url = `${API_BASE}/${accountIdOf(config)}${path}`; + let response: Response; + try { + response = await fetch(url, { + method, + headers: { + Authorization: `Bearer ${tokenOf(config)}`, + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: "error", + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } catch (error: unknown) { + if (error instanceof AdapterError) throw error; + const reason = error instanceof Error && error.name === "TimeoutError" ? "did not answer in time" : "could not be reached"; + throw new AdapterError("cloudflare-d1", operation, `The Cloudflare API ${reason}.`); + } + + const envelope = await readEnvelope(response); + if (!response.ok || !envelope?.success) { + const { message, codes } = describeFailure(response.status, envelope); + throw new AdapterError("cloudflare-d1", operation, message, { context: { status: response.status, codes } }); + } + return { result: envelope.result as T, resultInfo: envelope.result_info }; +} + +/** How many databases one page of the list holds. The API allows up to 10'000. */ +const LIST_PAGE_SIZE = 1000; + +/** Every D1 database of the account, across all pages of the list. */ +export async function listDatabases(config: D1Connection): Promise { + const all: D1Database[] = []; + for (let page = 1; ; page++) { + const { result, resultInfo } = await d1Request(config, "list", "GET", `/d1/database?page=${page}&per_page=${LIST_PAGE_SIZE}`); + const rows = Array.isArray(result) ? result : []; + all.push(...rows); + const total = resultInfo?.total_count; + if (rows.length < LIST_PAGE_SIZE || (typeof total === "number" && all.length >= total)) break; + } + return all.filter((db) => typeof db.name === "string" && typeof db.uuid === "string"); +} + +/** The database of this name, or null. Names are unique within an account. */ +export async function findDatabase(config: D1Connection, name: string): Promise { + // The name filter of the API matches more than the exact name, so a full page can hide it. + const { result } = await d1Request(config, "list", "GET", `/d1/database?name=${encodeURIComponent(name)}&per_page=100`); + const rows = Array.isArray(result) ? result : []; + const match = rows.find((db) => db.name === name); + if (match || rows.length < 100) return match ?? null; + return (await listDatabases(config)).find((db) => db.name === name) ?? null; +} + +/** The database of this name, refused when the account has none. */ +export async function requireDatabase(config: D1Connection, name: string, operation: string): Promise { + const db = await findDatabase(config, name); + if (!db) throw new AdapterError("cloudflare-d1", operation, `The account has no D1 database named "${name}".`); + return { ...db, uuid: databaseIdOf(db.uuid) }; +} + +/** The details of one database, its size among them. */ +export async function getDatabase(config: D1Connection, uuid: string): Promise { + const { result } = await d1Request(config, "get", "GET", `/d1/database/${databaseIdOf(uuid)}`); + return result; +} + +/** Runs SQL through the query endpoint, rows as objects. */ +export async function query>( + config: D1Connection, + uuid: string, + sql: string, + params?: unknown[], +): Promise[]> { + const { result } = await d1Request[]>(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/query`, params ? { sql, params } : { sql }); + return Array.isArray(result) ? result : []; +} + +/** Runs several statements as one batch, which D1 runs in one transaction. */ +export async function batch(config: D1Connection, uuid: string, statements: { sql: string; params?: unknown[] }[]): Promise { + const { result } = await d1Request(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/query`, { batch: statements }); + return Array.isArray(result) ? result : []; +} + +/** Runs SQL through the raw endpoint, rows as arrays with the column names apart. */ +export async function rawQuery(config: D1Connection, uuid: string, sql: string, params?: unknown[]): Promise { + const { result } = await d1Request(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/raw`, params ? { sql, params } : { sql }); + return Array.isArray(result) ? result : []; +} diff --git a/src/lib/adapters/database/cloudflare-d1/browser.ts b/src/lib/adapters/database/cloudflare-d1/browser.ts new file mode 100644 index 000000000..9cccc4270 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/browser.ts @@ -0,0 +1,107 @@ +import type { ColumnInfo, DatabaseAdapter, TableInfo } from "@/lib/core/interfaces"; +import { ValidationError } from "@/lib/logging/errors"; +import { query, rawQuery, requireDatabase, type D1Connection } from "./api"; +import { INTERNAL_OBJECT_FILTER, quoteIdentifier } from "./sql"; + +/** + * The Database Explorer of a D1 database, through the query API. Every call is a query on the + * database of the customer and counts against its rows read, and nothing here writes. + * + * Values go in as parameters, names only after `sqlite_master` and `pragma_table_info` listed them, + * so a name never reaches the SQL text that the database does not know. The API answers numbers + * as JavaScript numbers, which round an integer beyond 2^53, so such an integer is read as text. + */ + +/** 2^53 - 1, the largest integer a JavaScript number holds exactly. */ +const SAFE = "9007199254740991"; + +/** The most rows one page shows, whatever the caller asks. */ +const MAX_PAGE_SIZE = 500; + +const LISTED = `type IN ('table', 'view') AND ${INTERNAL_OBJECT_FILTER}`; + +export const getTables: NonNullable = async (config, database) => { + const connection = config as D1Connection; + const db = await requireDatabase(connection, database, "browse"); + const [objects] = await query<{ name: string; type: string }>(connection, db.uuid, `SELECT name, type FROM sqlite_master WHERE ${LISTED} ORDER BY name`); + const tables: TableInfo[] = (objects?.results ?? []).map((object) => ({ name: object.name, type: object.type === "view" ? "view" : "table" })); + + const names = tables.filter((table) => table.type === "table").map((table) => table.name); + if (names.length === 0) return tables; + + // One statement for every count, by position, so no table name becomes an alias. + const counts = names.map((name) => `SELECT count(*) AS n FROM ${quoteIdentifier(name)}`).join(" UNION ALL "); + try { + const [result] = await query<{ n: number }>(connection, db.uuid, counts); + const rows = result?.results ?? []; + const byName = new Map(names.map((name, index) => [name, Number(rows[index]?.n)])); + return tables.map((table) => (byName.has(table.name) && Number.isFinite(byName.get(table.name)) ? { ...table, rowCount: byName.get(table.name) } : table)); + } catch { + // A virtual table can refuse a count. The list without counts is still useful. + return tables; + } +}; + +/** The columns of a listed table or view, refused for a name `sqlite_master` does not list. */ +async function columnsOf(connection: D1Connection, uuid: string, table: string): Promise { + const [listed] = await query<{ n: number }>(connection, uuid, `SELECT count(*) AS n FROM sqlite_master WHERE ${LISTED} AND name = ?`, [table]); + if (!Number(listed?.results?.[0]?.n)) { + throw new ValidationError("This table does not exist in the database.", { field: "table" }); + } + const [info] = await query<{ name: string; type: string; notnull: number; dflt_value: string | null; pk: number }>( + connection, + uuid, + "SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info(?)", + [table], + ); + return (info?.results ?? []).map((column) => ({ + name: column.name, + dataType: column.type || "ANY", + nullable: !column.notnull, + primaryKey: Number(column.pk) > 0, + defaultValue: column.dflt_value ?? undefined, + })); +} + +/** A column as the page shows it: a large integer as text, a BLOB as hex. */ +function shownValue(column: string): string { + const col = quoteIdentifier(column); + return `CASE WHEN typeof(${col}) = 'integer' AND (${col} > ${SAFE} OR ${col} < -${SAFE}) THEN CAST(${col} AS TEXT) WHEN typeof(${col}) = 'blob' THEN 'x''' || hex(${col}) || '''' ELSE ${col} END`; +} + +export const getTableData: NonNullable = async (config, options) => { + const connection = config as D1Connection; + const { database, table, page, sortBy, sortDir, search, searchColumn, matchMode } = options; + const pageSize = Math.min(Math.max(Math.floor(options.pageSize) || 50, 1), MAX_PAGE_SIZE); + const offset = (Math.max(Math.floor(page) || 1, 1) - 1) * pageSize; + + const db = await requireDatabase(connection, database, "browse"); + const columns = await columnsOf(connection, db.uuid, table); + const known = new Set(columns.map((column) => column.name)); + for (const name of [searchColumn, sortBy]) { + if (name && !known.has(name)) throw new ValidationError("This column does not exist in the table."); + } + + const params: unknown[] = []; + let where = ""; + if (search && searchColumn) { + const col = quoteIdentifier(searchColumn); + if (matchMode === "equals") { + where = ` WHERE ${col} = ?`; + params.push(search); + } else { + where = ` WHERE ${col} LIKE ?`; + params.push(matchMode === "starts" ? `${search}%` : matchMode === "ends" ? `%${search}` : `%${search}%`); + } + } + const order = sortBy ? ` ORDER BY ${quoteIdentifier(sortBy)} ${sortDir === "desc" ? "DESC" : "ASC"}` : ""; + const from = ` FROM ${quoteIdentifier(table)}${where}`; + + const [countResult] = await query<{ n: number }>(connection, db.uuid, `SELECT count(*) AS n${from}`, params.length ? params : undefined); + const select = columns.length > 0 ? columns.map((column) => shownValue(column.name)).join(", ") : "*"; + const [data] = await rawQuery(connection, db.uuid, `SELECT ${select}${from}${order} LIMIT ${pageSize} OFFSET ${offset}`, params.length ? params : undefined); + + const names = columns.length > 0 ? columns.map((column) => column.name) : data?.results?.columns ?? []; + const rows = (data?.results?.rows ?? []).map((values) => Object.fromEntries(names.map((name, index) => [name, values[index] ?? null]))); + return { rows, totalCount: Number(countResult?.results?.[0]?.n) || 0, columns }; +}; diff --git a/src/lib/adapters/database/cloudflare-d1/connection.ts b/src/lib/adapters/database/cloudflare-d1/connection.ts new file mode 100644 index 000000000..b316d8b29 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/connection.ts @@ -0,0 +1,57 @@ +import type { DatabaseAdapter, DatabaseInfo } from "@/lib/core/interfaces"; +import { d1Request, listDatabases, type D1Connection } from "./api"; + +/** + * Connectivity and the list of databases of a Cloudflare account. + * + * The test lists the databases, which checks the token, the account and the right to read D1 at + * once. It cannot check the right to export (D1 Edit) without side effects: an export locks the + * database while it runs. A token with D1 Read only passes the test and fails at the first backup, + * with a message that names the missing permission. + */ + +/** The sentence of an error, without the `[adapter] operation:` an `AdapterError` puts in front. */ +function errorText(error: unknown): string { + const message = error instanceof Error ? error.message : String(error); + return message.replace(/^\[cloudflare-d1\] [a-z-]+: /, ""); +} + +export const test: NonNullable = async (config) => { + try { + const databases = await listDatabases(config as D1Connection); + const count = databases.length === 1 ? "1 database" : `${databases.length} databases`; + return { + success: true, + message: `Connected to Cloudflare D1 (${count}). Backups need the permission D1 Edit on the token.`, + }; + } catch (error: unknown) { + return { success: false, message: errorText(error) }; + } +}; + +/** One small page of the list, the cheapest call that proves token and account. */ +export const ping: NonNullable = async (config) => { + try { + await d1Request(config as D1Connection, "ping", "GET", "/d1/database?per_page=10"); + return { success: true, message: "Cloudflare D1 answered" }; + } catch (error: unknown) { + return { success: false, message: errorText(error) }; + } +}; + +export const getDatabases: NonNullable = async (config) => { + const databases = await listDatabases(config as D1Connection); + return databases.map((db) => db.name).sort((a, b) => a.localeCompare(b)); +}; + +/** The list answers size and table count of every database, so no call per database is needed. */ +export const getDatabasesWithStats: NonNullable = async (config) => { + const databases = await listDatabases(config as D1Connection); + return databases + .map((db): DatabaseInfo => ({ + name: db.name, + sizeInBytes: typeof db.file_size === "number" ? db.file_size : undefined, + tableCount: typeof db.num_tables === "number" ? db.num_tables : undefined, + })) + .sort((a, b) => a.name.localeCompare(b.name)); +}; diff --git a/src/lib/adapters/database/cloudflare-d1/dump.ts b/src/lib/adapters/database/cloudflare-d1/dump.ts new file mode 100644 index 000000000..52f46fa64 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/dump.ts @@ -0,0 +1,64 @@ +import type { DatabaseAdapter } from "@/lib/core/interfaces"; +import type { LogLevel, LogType } from "@/lib/core/logs"; +import { AdapterError } from "@/lib/logging/errors"; +import { formatBytes } from "@/lib/utils"; +import { requireDatabase, type D1Connection } from "./api"; +import { exportDatabase } from "./jobs"; +import { warnAboutLargeIntegers } from "./large-integers"; +import type { CloudflareD1Config } from "@/lib/adapters/definitions"; + +type OnLog = (msg: string, level?: LogLevel, type?: LogType, details?: string) => void; + +/** + * The backup of one D1 database: the SQL dump of Cloudflare's export, unchanged. + * + * The export locks the database while it runs (it serves no queries until the export ends), which + * the run log says before it starts. Databases are picked by name and looked up on every run, so a + * database deleted and created again under the same name is backed up under its new ID. + */ +export const dumpOne: NonNullable = async (config, dbName, destinationPath, _host, onLog) => { + const log = (message: string, level: LogLevel = "info") => onLog?.(message, level); + const connection = config as CloudflareD1Config & D1Connection; + + const db = await requireDatabase(connection, dbName, "dump"); + if (connection.checkLargeIntegers !== false) { + await warnAboutLargeIntegers(connection, db.uuid, dbName, log); + } + + log(`Exporting ${dbName}. Cloudflare locks the database until the export ends, it serves no queries meanwhile.`); + const size = await exportDatabase(connection, db.uuid, destinationPath, log); + if (size === 0) { + throw new AdapterError("cloudflare-d1", "dump", `The export of ${dbName} is empty.`); + } + log(`Exported ${dbName} (${formatBytes(size)})`); + return { size }; +}; + +/** The databases of the job's selection, refused when it names none. */ +function selectedDatabases(config: Record): string[] { + const value = config.database; + const names = Array.isArray(value) ? value : typeof value === "string" ? value.split(",") : []; + return names.map((name) => String(name).trim()).filter(Boolean); +} + +/** + * The backup in the format before the seekable archive. A new adapter has no such backups, the + * interface still asks for it, so this writes the single database a job names. + */ +// LEGACY-FORMAT(write): Part of DatabaseAdapter.dump, which no job calls anymore. Remove it together with DatabaseAdapter.dump. +export const dump: DatabaseAdapter["dump"] = async (config, destinationPath, host, onLog) => { + const startedAt = new Date(); + const logs: string[] = []; + const log: OnLog = (message, level, type, details) => { + logs.push(message); + onLog?.(message, level, type, details); + }; + try { + const names = selectedDatabases(config as Record); + if (names.length !== 1) throw new AdapterError("cloudflare-d1", "dump", "A dump without the archive holds exactly one database."); + const { size } = await dumpOne(config, names[0], destinationPath, host, log); + return { success: true, path: destinationPath, size, logs, startedAt, completedAt: new Date() }; + } catch (error: unknown) { + return { success: false, error: error instanceof Error ? error.message : String(error), logs, startedAt, completedAt: new Date() }; + } +}; diff --git a/src/lib/adapters/database/cloudflare-d1/index.ts b/src/lib/adapters/database/cloudflare-d1/index.ts new file mode 100644 index 000000000..d5698e40e --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/index.ts @@ -0,0 +1,35 @@ +import { DatabaseAdapter } from "@/lib/core/interfaces"; +import { CloudflareD1Schema } from "@/lib/adapters/definitions"; +import { test, ping, getDatabases, getDatabasesWithStats } from "./connection"; +import { dump, dumpOne } from "./dump"; +import { restore, restoreOne, prepareRestore } from "./restore"; +import { getTables, getTableData } from "./browser"; + +/** + * Cloudflare D1, through its REST API alone. + * + * No binary and no SSH: the export and import of Cloudflare do the work, this adapter starts and + * polls them and moves the dump. The connection is a Cloudflare account, its token comes from a + * credential profile of the type Token, and a job picks D1 databases of that account by name. + * + * The transport answers a DirectHost whatever the config holds, since nothing here runs on a host. + */ +export const CloudflareD1Adapter: DatabaseAdapter = { + id: "cloudflare-d1", + type: "database", + name: "Cloudflare D1", + configSchema: CloudflareD1Schema, + credentials: { primary: "TOKEN" }, + transport: () => ({ kind: "direct" }), + dump, + dumpOne, + restore, + restoreOne, + prepareRestore, + test, + ping, + getDatabases, + getDatabasesWithStats, + getTables, + getTableData, +}; diff --git a/src/lib/adapters/database/cloudflare-d1/jobs.ts b/src/lib/adapters/database/cloudflare-d1/jobs.ts new file mode 100644 index 000000000..31a2f6b1b --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/jobs.ts @@ -0,0 +1,153 @@ +import { AdapterError } from "@/lib/logging/errors"; +import { d1Request, databaseIdOf, isPermissionRefusal, type D1Connection } from "./api"; +import { downloadTo, md5Of, signedUrlOf, uploadFrom } from "./transfer"; + +/** + * The export and the import of D1, both long running work that Cloudflare does on its side and + * that is polled until it ends. + * + * An export that is not polled is cancelled by Cloudflare, so the loop never waits long between + * two polls. Both lock the database while they run: it serves no queries until they end. + */ + +/** The pause between two polls. Cloudflare holds a poll for a moment itself. */ +const POLL_PAUSE_MS = 500; + +/** No export or import runs longer than this. */ +const MAX_DURATION_MS = 6 * 60 * 60 * 1000; + +type Log = (message: string, level?: "info" | "warning" | "error") => void; + +interface PollAnswer { + status?: string; + at_bookmark?: string; + error?: string; + messages?: string[]; + upload_url?: string; + filename?: string; + result?: { + signed_url?: string; + filename?: string; + num_queries?: number; + final_bookmark?: string; + meta?: { rows_written?: number; duration?: number; size_after?: number }; + }; +} + +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +function relay(answer: PollAnswer, log: Log): void { + for (const line of answer.messages ?? []) { + if (typeof line === "string" && line.trim()) log(`Cloudflare: ${line.trim()}`); + } +} + +/** A failed export in words a person can act on. */ +function exportFailure(error: string | undefined): string { + const text = error?.trim() || "Cloudflare did not say why."; + if (/virtual table/i.test(text)) { + return `${text} Cloudflare cannot export a database that holds a virtual table, like an FTS5 search index. Drop the virtual tables before the backup and create them again after it, or leave this database out of the job.`; + } + return `The export failed: ${text}`; +} + +/** + * Exports one database to a SQL dump at `destinationPath`. Answers its size. + * + * The dump is what Cloudflare writes for an import into D1 (`compatibility: "d1"`): schema and + * data, `PRAGMA defer_foreign_keys=TRUE` at the top, no transaction statements. + */ +export async function exportDatabase(config: D1Connection, uuid: string, destinationPath: string, log: Log): Promise { + const id = databaseIdOf(uuid); + const path = `/d1/database/${id}/export`; + const started = Date.now(); + + let answer: PollAnswer; + try { + ({ result: answer } = await d1Request(config, "export", "POST", path, { output_format: "polling" })); + } catch (error: unknown) { + if (isPermissionRefusal(error)) { + throw new AdapterError("cloudflare-d1", "export", "Cloudflare refused the export. The API token needs the permission D1 Edit, D1 Read is not enough to export."); + } + throw error; + } + relay(answer, log); + + while (answer.status !== "complete" && answer.status !== "error") { + if (Date.now() - started > MAX_DURATION_MS) { + throw new AdapterError("cloudflare-d1", "export", "The export did not finish within 6 hours."); + } + if (!answer.at_bookmark) { + throw new AdapterError("cloudflare-d1", "export", `Cloudflare answered the export with the status "${answer.status ?? "none"}" and no bookmark to poll.`); + } + await pause(POLL_PAUSE_MS); + ({ result: answer } = await d1Request(config, "export", "POST", path, { output_format: "polling", current_bookmark: answer.at_bookmark })); + relay(answer, log); + } + + if (answer.status === "error") { + throw new AdapterError("cloudflare-d1", "export", exportFailure(answer.error)); + } + + const url = signedUrlOf(answer.result?.signed_url, "export"); + log(`Downloading the export from ${url.hostname}`); + return downloadTo(url, destinationPath); +} + +/** What an import reports when it ends. */ +export interface ImportOutcome { + queries?: number; + rowsWritten?: number; + finalBookmark?: string; +} + +/** + * Imports a SQL dump into one database: start, upload, ingest, poll. + * + * D1 runs the whole file in one transaction, so a failed import leaves the database as it was. A + * file Cloudflare already holds (the same MD5) needs no upload, `init` then starts the import + * itself and answers its state right away. + */ +export async function importDatabase(config: D1Connection, uuid: string, filePath: string, log: Log): Promise { + const id = databaseIdOf(uuid); + const path = `/d1/database/${id}/import`; + const started = Date.now(); + const etag = await md5Of(filePath); + + let { result: answer } = await d1Request(config, "import", "POST", path, { action: "init", etag }); + + if (answer.upload_url) { + const url = signedUrlOf(answer.upload_url, "import"); + log(`Uploading the dump to ${url.hostname}`); + await uploadFrom(url, filePath, etag); + if (typeof answer.filename !== "string" || !answer.filename) { + throw new AdapterError("cloudflare-d1", "import", "Cloudflare answered the import without a file name."); + } + ({ result: answer } = await d1Request(config, "import", "POST", path, { action: "ingest", etag, filename: answer.filename })); + } else { + log("Cloudflare already holds this dump, the import starts without an upload"); + } + relay(answer, log); + + while (answer.status !== "complete" && answer.status !== "error") { + if (Date.now() - started > MAX_DURATION_MS) { + throw new AdapterError("cloudflare-d1", "import", "The import did not finish within 6 hours."); + } + if (!answer.at_bookmark) { + throw new AdapterError("cloudflare-d1", "import", `Cloudflare answered the import with the status "${answer.status ?? "none"}" and no bookmark to poll.`); + } + await pause(POLL_PAUSE_MS); + ({ result: answer } = await d1Request(config, "import", "POST", path, { action: "poll", current_bookmark: answer.at_bookmark })); + relay(answer, log); + } + + if (answer.status === "error") { + throw new AdapterError("cloudflare-d1", "import", `The import failed and the database was left as it was: ${answer.error?.trim() || "Cloudflare did not say why."}`); + } + + return { + queries: answer.result?.num_queries, + rowsWritten: answer.result?.meta?.rows_written, + finalBookmark: answer.result?.final_bookmark, + }; +} diff --git a/src/lib/adapters/database/cloudflare-d1/large-integers.ts b/src/lib/adapters/database/cloudflare-d1/large-integers.ts new file mode 100644 index 000000000..e38e4d925 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/large-integers.ts @@ -0,0 +1,72 @@ +import { query, type D1Connection } from "./api"; +import { quoteIdentifier, userTablesSql } from "./sql"; + +/** + * Integers the export of Cloudflare cannot write exactly. + * + * SQLite stores an integer with 64 bits, but the export of D1 writes every number through a + * JavaScript number, which holds an integer exactly only up to 2^53. A larger one lands in the dump + * rounded (9007199254740993 becomes 9007199254740992), and one near 2^63 comes back from an import + * as a REAL. The fault is Cloudflare's and DBackup takes their export as it is, so before each export + * this check names every column that holds such a value, which makes the run log say what the + * backup will not keep. It reads every table once, which counts against the rows read of the + * account, so a connection can turn it off. + */ + +/** 2^53 - 1, the largest integer a JavaScript number holds exactly. */ +const SAFE = "9007199254740991"; + +type Log = (message: string, level?: "info" | "warning" | "error") => void; + +/** One column with integers beyond the safe range, and how many rows hold one. */ +export interface LargeIntegerColumn { + table: string; + column: string; + rows: number; +} + +/** Every column of every user table that holds an integer beyond ±(2^53 - 1). */ +export async function findLargeIntegers(config: D1Connection, uuid: string): Promise { + const [tables] = await query<{ name: string }>(config, uuid, userTablesSql()); + const found: LargeIntegerColumn[] = []; + + for (const { name: table } of tables?.results ?? []) { + const [columns] = await query<{ name: string }>(config, uuid, "SELECT name FROM pragma_table_info(?)", [table]); + const names = (columns?.results ?? []).map((column) => column.name); + if (names.length === 0) continue; + + // One scan per table: a count per column, by position, so no column name becomes an alias. + const counts = names.map((column, index) => { + const col = quoteIdentifier(column); + return `SUM(typeof(${col}) = 'integer' AND (${col} > ${SAFE} OR ${col} < -${SAFE})) AS c${index}`; + }); + const [result] = await query>(config, uuid, `SELECT ${counts.join(", ")} FROM ${quoteIdentifier(table)}`); + const row = result?.results?.[0] ?? {}; + names.forEach((column, index) => { + const rows = Number(row[`c${index}`] ?? 0); + if (rows > 0) found.push({ table, column, rows }); + }); + } + return found; +} + +/** Runs the check and writes what it found into the run log. Never fails the backup. */ +export async function warnAboutLargeIntegers(config: D1Connection, uuid: string, database: string, log: Log): Promise { + let found: LargeIntegerColumn[]; + try { + found = await findLargeIntegers(config, uuid); + } catch (error: unknown) { + log(`Could not check ${database} for integers the export rounds: ${error instanceof Error ? error.message : String(error)}`, "warning"); + return; + } + if (found.length === 0) return; + + for (const { table, column, rows } of found) { + log(`${database}: table "${table}", column "${column}" holds ${rows === 1 ? "1 integer" : `${rows} integers`} beyond ±2^53.`, "warning"); + } + log( + "The export of Cloudflare D1 rounds integers beyond ±2^53, so the backup holds these values rounded and a restore writes them back rounded. " + + "This is a limit of Cloudflare's export, which DBackup cannot work around. Storing such values as TEXT keeps them exact.", + "warning", + ); +} diff --git a/src/lib/adapters/database/cloudflare-d1/restore.ts b/src/lib/adapters/database/cloudflare-d1/restore.ts new file mode 100644 index 000000000..581c2f26f --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/restore.ts @@ -0,0 +1,166 @@ +import fs from "fs"; +import { pipeline } from "stream/promises"; +import type { DatabaseAdapter } from "@/lib/core/interfaces"; +import type { LogLevel, LogType } from "@/lib/core/logs"; +import { AdapterError } from "@/lib/logging/errors"; +import type { CloudflareD1Config } from "@/lib/adapters/definitions"; +import { d1Request, databaseIdOf, findDatabase, listDatabases, query, type D1Connection, type D1Database } from "./api"; +import { importDatabase } from "./jobs"; +import { INTERNAL_OBJECT_FILTER, quoteIdentifier } from "./sql"; + +type OnLog = (msg: string, level?: LogLevel, type?: LogType, details?: string) => void; +type Log = (message: string, level?: "info" | "warning" | "error") => void; +type D1RestoreConfig = CloudflareD1Config & D1Connection & { + databaseMapping?: { originalName: string; targetName: string; selected: boolean }[]; +}; + +/** + * A restore into D1, like every other adapter: an existing target is replaced, a new name creates + * a new database. + * + * Replacing never deletes the database itself. A Worker binds a D1 database by its ID, and a new + * database gets a new ID, so the restore drops the objects inside and keeps the database. The drops + * go into the same file as the dump, ahead of it, and D1 runs an import as one transaction: an + * import that fails leaves the target exactly as it was, never half empty. + * + * Before it replaces anything, the restore writes the current Time Travel bookmark of the target + * into the log, with the command that goes back to it. + */ + +/** The Time Travel bookmark of a database now, or null when Cloudflare does not answer one. */ +async function currentBookmark(config: D1Connection, uuid: string): Promise { + try { + const { result } = await d1Request<{ bookmark?: string }>(config, "restore", "GET", `/d1/database/${databaseIdOf(uuid)}/time_travel/bookmark`); + return typeof result?.bookmark === "string" ? result.bookmark : null; + } catch { + return null; + } +} + +/** + * The statements that empty a database: triggers, views, virtual tables, then tables, each with + * `IF EXISTS`, since dropping a virtual table drops its shadow tables too. Objects of SQLite and of + * Cloudflare stay. + */ +async function dropStatements(config: D1Connection, uuid: string): Promise { + const [result] = await query<{ type: string; name: string; sql: string | null }>( + config, + uuid, + `SELECT type, name, sql FROM sqlite_master WHERE type IN ('trigger', 'view', 'table') AND ${INTERNAL_OBJECT_FILTER}`, + ); + const rank = (object: { type: string; sql: string | null }) => + object.type === "trigger" ? 0 : object.type === "view" ? 1 : /^CREATE VIRTUAL TABLE/i.test(object.sql ?? "") ? 2 : 3; + return (result?.results ?? []) + .sort((a, b) => rank(a) - rank(b)) + .map((object) => `DROP ${object.type === "trigger" ? "TRIGGER" : object.type === "view" ? "VIEW" : "TABLE"} IF EXISTS ${quoteIdentifier(object.name)};`); +} + +/** The dump with the drops ahead of it, in a file beside it. */ +async function withDropsAhead(dumpPath: string, drops: string[]): Promise { + const combined = `${dumpPath}.replace.sql`; + const out = fs.createWriteStream(combined); + out.write(["PRAGMA defer_foreign_keys=TRUE;", ...drops, ""].join("\n")); + await pipeline(fs.createReadStream(dumpPath), out); + return combined; +} + +/** Where a new database goes: what the connection says, or like the database the backup came from. */ +async function locationOf(config: D1RestoreConfig, originalName: string | undefined, log: Log): Promise> { + const wanted = config.newDatabaseLocation ?? "auto"; + if (wanted === "eu" || wanted === "fedramp") return { jurisdiction: wanted }; + if (wanted !== "auto") return { primary_location_hint: wanted }; + + const original = originalName ? await findDatabase(config, originalName).catch(() => null) : null; + if (original?.jurisdiction) { + log(`Creating it in the jurisdiction ${original.jurisdiction}, like ${originalName}`); + return { jurisdiction: original.jurisdiction }; + } + return {}; +} + +async function createDatabase(config: D1RestoreConfig, name: string, originalName: string | undefined, log: Log): Promise { + const location = await locationOf(config, originalName, log); + const { result } = await d1Request(config, "restore", "POST", "/d1/database", { name, ...location }); + const uuid = databaseIdOf(result?.uuid); + log(`Created the D1 database ${name} (ID ${uuid}). A Worker that should use it needs this ID as its database_id.`); + return { ...result, uuid }; +} + +async function deleteDatabase(config: D1Connection, uuid: string): Promise { + await d1Request(config, "restore", "DELETE", `/d1/database/${databaseIdOf(uuid)}`); +} + +/** Restores one dump of `dumpOne` into the database named `targetDbName`. */ +export const restoreOne: NonNullable = async (config, filePath, targetDbName, _host, onLog, _onProgress, originalDbName) => { + const log: Log = (message, level = "info") => onLog?.(message, level); + const connection = config as D1RestoreConfig; + const existing = await findDatabase(connection, targetDbName); + + if (!existing) { + log(`${targetDbName} does not exist yet`); + const created = await createDatabase(connection, targetDbName, originalDbName, log); + try { + const outcome = await importDatabase(connection, created.uuid, filePath, log); + log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); + } catch (error: unknown) { + // The database came from this restore and holds nothing, so it does not stay behind. + await deleteDatabase(connection, created.uuid).catch(() => log(`Could not delete the empty database ${targetDbName} again, delete it in the Cloudflare dashboard.`, "warning")); + throw error; + } + return; + } + + const uuid = databaseIdOf(existing.uuid); + const bookmark = await currentBookmark(connection, uuid); + if (bookmark) { + log(`Time Travel bookmark of ${targetDbName} before the restore: ${bookmark}. Back to it with: wrangler d1 time-travel restore ${targetDbName} --bookmark=${bookmark}`); + } else { + log(`Cloudflare answered no Time Travel bookmark for ${targetDbName}, the state before the restore can only be found by its time.`, "warning"); + } + + const drops = await dropStatements(connection, uuid); + log(drops.length > 0 ? `Replacing ${targetDbName}: dropping its ${drops.length} objects and importing the backup in one transaction` : `${targetDbName} is empty, importing the backup`); + + const importPath = drops.length > 0 ? await withDropsAhead(filePath, drops) : filePath; + try { + const outcome = await importDatabase(connection, uuid, importPath, log); + log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); + } finally { + if (importPath !== filePath) await fs.promises.rm(importPath, { force: true }); + } +}; + +/** + * Before the restore starts: the token reaches the account. Whether it may write shows first at + * the import, Cloudflare offers no check without side effects. + */ +export const prepareRestore: NonNullable = async (config) => { + await listDatabases(config as D1Connection); +}; + +/** + * A restore of a backup in the format before the seekable archive. This adapter never wrote one, + * so the only file that can arrive is a single dump. + */ +// LEGACY-FORMAT(read): Part of DatabaseAdapter.restore. Remove it together with DatabaseAdapter.restore. +export const restore: DatabaseAdapter["restore"] = async (config, sourcePath, host, onLog, onProgress) => { + const startedAt = new Date(); + const logs: string[] = []; + const log: OnLog = (message, level, type, details) => { + logs.push(message); + onLog?.(message, level, type, details); + }; + try { + const connection = config as D1RestoreConfig; + const picked = connection.databaseMapping?.find((entry) => entry.selected); + const named = Array.isArray(connection.database) ? connection.database[0] : connection.database; + const target = picked?.targetName || picked?.originalName || named; + if (!target) throw new AdapterError("cloudflare-d1", "restore", "No target database named for the restore."); + await restoreOne(config, sourcePath, target, host, log, onProgress, picked?.originalName); + return { success: true, path: sourcePath, logs, startedAt, completedAt: new Date() }; + } catch (error: unknown) { + const message = error instanceof Error ? error.message : String(error); + log(`Error: ${message}`, "error"); + return { success: false, error: message, logs, startedAt, completedAt: new Date() }; + } +}; diff --git a/src/lib/adapters/database/cloudflare-d1/sql.ts b/src/lib/adapters/database/cloudflare-d1/sql.ts new file mode 100644 index 000000000..8c24f1406 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/sql.ts @@ -0,0 +1,21 @@ +/** + * SQL text this adapter builds itself. Values always go in as parameters, only identifiers are + * written into the text, quoted. + */ + +/** An identifier of SQLite in double quotes, a quote inside doubled. */ +export function quoteIdentifier(name: string): string { + return `"${name.replace(/"/g, '""')}"`; +} + +/** + * Objects of SQLite and of Cloudflare that are no data of the user. `sqlite_*` belongs to SQLite + * (`sqlite_sequence` comes back with the dump), `_cf_*` to Cloudflare (`_cf_KV` exists in every D1 + * database and is never exported). `\` escapes the `_` of LIKE. + */ +export const INTERNAL_OBJECT_FILTER = "name NOT LIKE 'sqlite\\_%' ESCAPE '\\' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'"; + +/** The tables of the user, virtual tables left out, by name. */ +export function userTablesSql(): string { + return `SELECT name FROM sqlite_master WHERE type = 'table' AND ${INTERNAL_OBJECT_FILTER} AND sql NOT LIKE 'CREATE VIRTUAL TABLE%' ORDER BY name`; +} diff --git a/src/lib/adapters/database/cloudflare-d1/transfer.ts b/src/lib/adapters/database/cloudflare-d1/transfer.ts new file mode 100644 index 000000000..bbfa47323 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/transfer.ts @@ -0,0 +1,77 @@ +import fs from "fs"; +import { createHash } from "crypto"; +import { Readable } from "stream"; +import { pipeline } from "stream/promises"; +import type { ReadableStream as WebReadableStream } from "stream/web"; +import { AdapterError } from "@/lib/logging/errors"; + +/** + * Moving a dump between this machine and the R2 bucket Cloudflare keeps exports and imports in. + * + * The export and the import of D1 answer with a presigned URL of R2. The URL comes from an answer + * of the API, so before anything is sent to it or read from it, it has to be HTTPS on R2 itself + * (`.r2.cloudflarestorage.com`, or `.eu.r2.cloudflarestorage.com` for a database in + * the EU). An answer that points anywhere else is refused, so a tampered or broken answer cannot + * make DBackup send a dump or fetch something from a host of its choosing. Redirects are refused + * for the same reason. The signature in the query is an access right, so the URL is never logged, + * only its host. + */ + +const R2_HOST = /^(?:[a-z0-9-]+\.)+r2\.cloudflarestorage\.com$/i; + +/** A transfer of a dump may take long, but not forever. */ +const TRANSFER_TIMEOUT_MS = 6 * 60 * 60 * 1000; + +/** The presigned URL, refused unless it is HTTPS on R2. */ +export function signedUrlOf(value: unknown, operation: string): URL { + let url: URL; + try { + url = new URL(String(value)); + } catch { + throw new AdapterError("cloudflare-d1", operation, "Cloudflare answered without a valid transfer URL."); + } + if (url.protocol !== "https:" || !R2_HOST.test(url.hostname) || url.port !== "" || url.username || url.password) { + throw new AdapterError("cloudflare-d1", operation, `Cloudflare answered with a transfer URL on ${url.hostname || "no host"}, which is not R2. Refusing to use it.`); + } + return url; +} + +/** Streams the file behind a presigned URL to `destinationPath`. Answers its size. */ +export async function downloadTo(url: URL, destinationPath: string): Promise { + const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(TRANSFER_TIMEOUT_MS) }).catch(() => null); + if (!response?.ok || !response.body) { + throw new AdapterError("cloudflare-d1", "export", `Downloading the export from ${url.hostname} failed${response ? ` with ${response.status}` : ""}.`); + } + await pipeline(Readable.fromWeb(response.body as WebReadableStream), fs.createWriteStream(destinationPath)); + return (await fs.promises.stat(destinationPath)).size; +} + +/** The MD5 of a file in hex, the `etag` the import of D1 asks for. */ +export async function md5Of(filePath: string): Promise { + const hash = createHash("md5"); + await pipeline(fs.createReadStream(filePath), hash); + return hash.digest("hex"); +} + +/** + * Streams a file to a presigned URL with PUT, as Wrangler does. R2 answers the MD5 of what it got as + * the ETag, which has to be the one the import was started with. + */ +export async function uploadFrom(url: URL, filePath: string, etag: string): Promise { + const { size } = await fs.promises.stat(filePath); + const response = await fetch(url, { + method: "PUT", + headers: { "Content-Length": String(size) }, + body: Readable.toWeb(fs.createReadStream(filePath)) as unknown as BodyInit, + duplex: "half", + redirect: "error", + signal: AbortSignal.timeout(TRANSFER_TIMEOUT_MS), + } as RequestInit & { duplex: "half" }).catch(() => null); + if (!response?.ok) { + throw new AdapterError("cloudflare-d1", "import", `Uploading the dump to ${url.hostname} failed${response ? ` with ${response.status}` : ""}.`); + } + const answered = (response.headers.get("etag") ?? "").replace(/^"|"$/g, ""); + if (answered !== etag) { + throw new AdapterError("cloudflare-d1", "import", "The upload of the dump arrived damaged (its MD5 does not match). Run the restore again."); + } +} diff --git a/src/lib/adapters/definitions/database.ts b/src/lib/adapters/definitions/database.ts index 577c29ffb..93be7e818 100644 --- a/src/lib/adapters/definitions/database.ts +++ b/src/lib/adapters/definitions/database.ts @@ -122,6 +122,17 @@ export const AzureSQLSchema = z.object({ requestTimeout: z.coerce.number().default(300000).describe("Timeout in ms for catalog queries. The export itself is never timed out."), }); +/** Where a restore puts a D1 database it creates, see `cloudflare-d1/restore.ts`. */ +export const D1_NEW_DATABASE_LOCATIONS = ["auto", "eu", "fedramp", "weur", "eeur", "wnam", "enam", "apac", "oc"] as const; + +export const CloudflareD1Schema = z.object({ + accountId: z.string().trim().regex(/^[0-9a-fA-F]{32}$/, "The account ID is the 32 hex characters shown in the Cloudflare dashboard").describe("Account ID of the Cloudflare account that holds the D1 databases"), + token: z.string().optional().describe("API token with the permission D1 Edit"), + database: z.union([z.string(), z.array(z.string())]).default(""), + checkLargeIntegers: z.boolean().default(true).describe("Warn before each backup when a column holds an integer beyond 2^53, which the export of Cloudflare rounds. Reads every table once more"), + newDatabaseLocation: z.enum(D1_NEW_DATABASE_LOCATIONS).default("auto").describe("Where a restore under a new name creates the database"), +}); + export const FirebirdSchema = z.object({ // The host goes in front of `:path` in the connection string of gbak and isql, see `firebird/host.ts`. host: z.string().superRefine((value, ctx) => { @@ -167,8 +178,9 @@ export type MSSQLConfig = z.infer; export type AzureSQLConfig = z.infer; export type RedisConfig = z.infer; export type FirebirdConfig = z.infer; +export type CloudflareD1Config = z.infer; -export type DatabaseConfig = MySQLConfig | MariaDBConfig | PostgresConfig | MongoDBConfig | SQLiteConfig | MSSQLConfig | AzureSQLConfig | RedisConfig | FirebirdConfig; +export type DatabaseConfig = MySQLConfig | MariaDBConfig | PostgresConfig | MongoDBConfig | SQLiteConfig | MSSQLConfig | AzureSQLConfig | RedisConfig | FirebirdConfig | CloudflareD1Config; // Generic type alias for dialect base class (accepts any database config) export type AnyDatabaseConfig = DatabaseConfig; diff --git a/src/lib/adapters/definitions/index.ts b/src/lib/adapters/definitions/index.ts index 305f33c62..3e11fdc95 100644 --- a/src/lib/adapters/definitions/index.ts +++ b/src/lib/adapters/definitions/index.ts @@ -4,7 +4,7 @@ import { DEFAULT_S3_UPLOAD_TUNING, type AdapterDefinition } from "./shared"; import { STORAGE_ROLES } from "@/lib/core/storage-roles"; import { MySQLSchema, MariaDBSchema, PostgresSchema, MongoDBSchema, - SQLiteSchema, MSSQLSchema, AzureSQLSchema, RedisSchema, FirebirdSchema, + SQLiteSchema, MSSQLSchema, AzureSQLSchema, RedisSchema, FirebirdSchema, CloudflareD1Schema, } from "./database"; import { LocalStorageSchema, S3GenericSchema, S3AWSSchema, S3R2Schema, S3HetznerSchema, @@ -33,6 +33,7 @@ export const ADAPTER_DEFINITIONS: AdapterDefinition[] = [ { id: "redis", type: "database", group: "Key value", name: "Redis", sharesSingleDatabases: false, configSchema: RedisSchema }, { id: "valkey", type: "database", group: "Key value", name: "Valkey", sharesSingleDatabases: false, configSchema: RedisSchema }, { id: "firebird", type: "database", group: "Relational", name: "Firebird", beta: true, sharesSingleDatabases: true, customerRestores: false, configSchema: FirebirdSchema }, + { id: "cloudflare-d1", type: "database", group: "Relational", name: "Cloudflare D1", beta: true, sharesSingleDatabases: true, customerRestores: false, configSchema: CloudflareD1Schema }, { id: "local-filesystem", type: "storage", group: "Local", name: "Local Filesystem", configSchema: LocalStorageSchema }, { diff --git a/src/lib/adapters/dialed-hosts.ts b/src/lib/adapters/dialed-hosts.ts index e1d0b419f..d6bbe09b7 100644 --- a/src/lib/adapters/dialed-hosts.ts +++ b/src/lib/adapters/dialed-hosts.ts @@ -242,6 +242,8 @@ export const DIALED_HOSTS: Readonly> = { mssql, // SqlPackage gets `tcp:,` and the driver the same server name, see `sqlServerHost`. "azure-sql": (config) => [sqlServerHost(config.host)].filter(present), + // The API of Cloudflare and the R2 bucket of its exports, both fixed, see `cloudflare-d1/transfer.ts`. + "cloudflare-d1": none, redis, valkey: redis, // `host/port` and `[v6]/port` by the host, see `firebirdHosts`. diff --git a/src/lib/adapters/index.ts b/src/lib/adapters/index.ts index 867bc0caa..0f2adad96 100644 --- a/src/lib/adapters/index.ts +++ b/src/lib/adapters/index.ts @@ -6,6 +6,7 @@ import { MongoDBAdapter } from "./database/mongodb"; import { SQLiteAdapter } from "./database/sqlite"; import { MSSQLAdapter } from "./database/mssql"; import { AzureSQLAdapter } from "./database/azure-sql"; +import { CloudflareD1Adapter } from "./database/cloudflare-d1"; import { RedisAdapter } from "./database/redis"; import { ValkeyAdapter } from "./database/valkey"; import { FirebirdAdapter } from "./database/firebird"; @@ -55,6 +56,8 @@ export function registerAdapters() { registry.register(SQLiteAdapter); registry.register(MSSQLAdapter); registry.register(AzureSQLAdapter); + // Reaches only the fixed API of Cloudflare, so there is no host of the customer to pin. + registry.register(CloudflareD1Adapter); registry.register(withPinnedDatabaseHost(RedisAdapter)); registry.register(withPinnedDatabaseHost(ValkeyAdapter)); registry.register(withPinnedDatabaseHost(FirebirdAdapter)); diff --git a/src/lib/auth/adapter-permissions.ts b/src/lib/auth/adapter-permissions.ts index 30d4d98ed..0ec1d51d9 100644 --- a/src/lib/auth/adapter-permissions.ts +++ b/src/lib/auth/adapter-permissions.ts @@ -8,6 +8,7 @@ const ADAPTER_PERMISSIONS: Record = { sqlite: PERMISSIONS.SOURCES.VIEW, mssql: PERMISSIONS.SOURCES.VIEW, "azure-sql": PERMISSIONS.SOURCES.VIEW, + "cloudflare-d1": PERMISSIONS.SOURCES.VIEW, redis: PERMISSIONS.SOURCES.VIEW, valkey: PERMISSIONS.SOURCES.VIEW, firebird: PERMISSIONS.SOURCES.VIEW, diff --git a/src/lib/core/credential-requirements.ts b/src/lib/core/credential-requirements.ts index 2ba641ce7..eb2105776 100644 --- a/src/lib/core/credential-requirements.ts +++ b/src/lib/core/credential-requirements.ts @@ -24,6 +24,7 @@ export const ADAPTER_CREDENTIAL_REQUIREMENTS: Record< // No SSH slot: Azure SQL Database is a public PaaS endpoint, and a tunnel would // not help anyway since SqlPackage runs in this container, not on a jump host. "azure-sql": { primary: "USERNAME_PASSWORD" }, + "cloudflare-d1": { primary: "TOKEN" }, redis: { primary: "USERNAME_PASSWORD", ssh: "SSH_KEY" }, valkey: { primary: "USERNAME_PASSWORD", ssh: "SSH_KEY" }, firebird: { primary: "USERNAME_PASSWORD", ssh: "SSH_KEY" }, diff --git a/src/lib/runner/steps/dump-databases.ts b/src/lib/runner/steps/dump-databases.ts index 33f25f1f4..d6eb8e850 100644 --- a/src/lib/runner/steps/dump-databases.ts +++ b/src/lib/runner/steps/dump-databases.ts @@ -23,6 +23,7 @@ export const DB_FORMAT_BY_ADAPTER: Record = { firebird: "fbk", mssql: "bak", "azure-sql": "bacpac", + "cloudflare-d1": "sql", redis: "rdb", valkey: "rdb", sqlite: "sqlite", diff --git a/src/services/storage/backup-contents.ts b/src/services/storage/backup-contents.ts index 5e7a6acce..f94e4baff 100644 --- a/src/services/storage/backup-contents.ts +++ b/src/services/storage/backup-contents.ts @@ -27,7 +27,7 @@ export interface ArchiveListing { } /** Source types whose backups restore into a server, which the restore page asks a target for. */ -const SERVER_ADAPTERS = ['mysql', 'mariadb', 'postgres', 'mongodb', 'mssql', 'azure-sql', 'redis', 'valkey', 'firebird']; +const SERVER_ADAPTERS = ['mysql', 'mariadb', 'postgres', 'mongodb', 'mssql', 'azure-sql', 'cloudflare-d1', 'redis', 'valkey', 'firebird']; /** The adapters a downloaded dump is offered to when the caller does not name its type. */ const GUESSED_ADAPTERS = ["mysql", "postgres", "mongodb"]; diff --git a/tests/unit/adapters/database/cloudflare-d1/api.test.ts b/tests/unit/adapters/database/cloudflare-d1/api.test.ts new file mode 100644 index 000000000..3be888343 --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/api.test.ts @@ -0,0 +1,111 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { accountIdOf, d1Request, findDatabase, isPermissionRefusal, listDatabases } from "@/lib/adapters/database/cloudflare-d1/api"; +import { signedUrlOf } from "@/lib/adapters/database/cloudflare-d1/transfer"; +import { CloudflareD1Adapter } from "@/lib/adapters/database/cloudflare-d1"; +import { ACCOUNT, DB_ID, config, fakeCloudflare, ok, refused } from "./fake-cloudflare"; + +const host = {} as never; + +afterEach(() => vi.unstubAllGlobals()); + +describe("the account of a D1 connection", () => { + it("takes the 32 hex characters of the dashboard, in any case", () => { + expect(accountIdOf({ accountId: ` ${ACCOUNT.toUpperCase()} ` })).toBe(ACCOUNT); + }); + + it("refuses anything else before it becomes part of a URL", () => { + expect(() => accountIdOf({ accountId: "../../zones" })).toThrow(/32 hex characters/); + expect(() => accountIdOf({ accountId: `${ACCOUNT}/d1` })).toThrow(/32 hex characters/); + }); +}); + +describe("a call of the Cloudflare API", () => { + it("sends the token as a bearer token and answers the result of the envelope", async () => { + const { calls } = fakeCloudflare(() => ok([{ uuid: DB_ID, name: "shop" }])); + const { result } = await d1Request(config, "list", "GET", "/d1/database"); + expect(result).toEqual([{ uuid: DB_ID, name: "shop" }]); + expect(calls[0].headers.Authorization).toBe("Bearer test-token"); + }); + + it("names the token, not the request, when Cloudflare refuses it, and never repeats the token", async () => { + fakeCloudflare(() => refused(401, 10000, "Authentication error")); + const error = await d1Request(config, "list", "GET", "/d1/database").catch((e: Error) => e); + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toMatch(/refused the API token/); + expect((error as Error).message).not.toContain("test-token"); + expect(isPermissionRefusal(error)).toBe(true); + }); + + it("tells a broken request from a missing right", async () => { + fakeCloudflare(() => refused(400, 7400, "bad SQL")); + const error = await d1Request(config, "query", "POST", "/x", {}).catch((e: Error) => e); + expect((error as Error).message).toMatch(/400: bad SQL/); + expect(isPermissionRefusal(error)).toBe(false); + }); + + it("refuses a connection without a token before anything is sent", async () => { + const { calls } = fakeCloudflare(() => ok([])); + await expect(d1Request({ accountId: ACCOUNT }, "list", "GET", "/d1/database")).rejects.toThrow(/No API token/); + expect(calls).toHaveLength(0); + }); +}); + +describe("the databases of an account", () => { + it("reads every page of the list", async () => { + const page = (n: number, count: number) => Array.from({ length: count }, (_, i) => ({ uuid: DB_ID, name: `db-${n}-${i}` })); + fakeCloudflare((call) => ok(call.path.includes("page=1&") ? page(1, 1000) : page(2, 3), { result_info: { total_count: 1003 } })); + expect(await listDatabases(config)).toHaveLength(1003); + }); + + it("finds a database by its exact name, not by the wider name filter of the API", async () => { + fakeCloudflare(() => ok([{ uuid: DB_ID, name: "shop-staging" }, { uuid: DB_ID, name: "shop" }])); + expect((await findDatabase(config, "shop"))?.name).toBe("shop"); + expect(await findDatabase(config, "sho")).toBeNull(); + }); + + it("lists names and sizes for the job form and the explorer from one call", async () => { + const { calls } = fakeCloudflare(() => ok([{ uuid: DB_ID, name: "b", file_size: 2048, num_tables: 3 }, { uuid: DB_ID, name: "a" }])); + expect(await CloudflareD1Adapter.getDatabasesWithStats!(config, host)).toEqual([ + { name: "a", sizeInBytes: undefined, tableCount: undefined }, + { name: "b", sizeInBytes: 2048, tableCount: 3 }, + ]); + expect(calls).toHaveLength(1); + }); +}); + +describe("Test connection", () => { + it("succeeds with a token that can list D1 and says that backups need D1 Edit", async () => { + fakeCloudflare(() => ok([{ uuid: DB_ID, name: "shop" }])); + const answer = await CloudflareD1Adapter.test!(config, host); + expect(answer.success).toBe(true); + expect(answer.message).toMatch(/1 database/); + expect(answer.message).toMatch(/D1 Edit/); + }); + + it("fails with the reason alone, without the prefix of the adapter error", async () => { + fakeCloudflare(() => refused(401, 1000, "Invalid API Token")); + const answer = await CloudflareD1Adapter.test!(config, host); + expect(answer.success).toBe(false); + expect(answer.message).toMatch(/^Cloudflare refused the API token/); + }); +}); + +describe("the transfer URL of an export or import", () => { + it("accepts R2, also in the EU", () => { + expect(signedUrlOf("https://abc.r2.cloudflarestorage.com/x.sql?sig=1", "export").hostname).toBe("abc.r2.cloudflarestorage.com"); + expect(signedUrlOf("https://abc.eu.r2.cloudflarestorage.com/x.sql", "import").hostname).toBe("abc.eu.r2.cloudflarestorage.com"); + }); + + it("refuses any other host, plain HTTP, a port or a login, so a tampered answer cannot point the dump elsewhere", () => { + for (const url of [ + "https://evil.example.com/x.sql", + "https://r2.cloudflarestorage.com.evil.example/x.sql", + "http://abc.r2.cloudflarestorage.com/x.sql", + "https://abc.r2.cloudflarestorage.com:8443/x.sql", + "https://user:pw@abc.r2.cloudflarestorage.com/x.sql", + "not a url", + ]) { + expect(() => signedUrlOf(url, "export"), url).toThrow(); + } + }); +}); diff --git a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts new file mode 100644 index 000000000..97209a948 --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts @@ -0,0 +1,211 @@ +import fs from "fs"; +import os from "os"; +import path from "path"; +import { createHash } from "crypto"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CloudflareD1Adapter } from "@/lib/adapters/database/cloudflare-d1"; +import { DB_ID, NEW_ID, R2_URL, config, fakeCloudflare, ok, refused, type Call } from "./fake-cloudflare"; + +const host = {} as never; +const DUMP = "PRAGMA defer_foreign_keys=TRUE;\nCREATE TABLE t (id INTEGER PRIMARY KEY);\nINSERT INTO \"t\" VALUES(1);\n"; +const md5 = (text: string) => createHash("md5").update(text).digest("hex"); + +let dir: string; +beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "d1-test-")); +}); +afterEach(() => { + vi.unstubAllGlobals(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +/** The list of databases the account answers. */ +const listing = (names: Record, jurisdiction?: string) => (call: Call) => + call.method === "GET" && call.path.startsWith("/d1/database?") + ? ok(Object.entries(names).map(([name, uuid]) => ({ name, uuid, jurisdiction: jurisdiction ?? null }))) + : undefined; + +describe("a backup of a D1 database", () => { + it("exports by polling until Cloudflare is done and stores its dump unchanged", async () => { + let polls = 0; + const { calls } = fakeCloudflare((call) => { + if (call.url === R2_URL) return { text: DUMP }; + if (call.path === `/d1/database/${DB_ID}/export`) { + polls++; + return polls === 1 ? ok({ status: "active", at_bookmark: "bm-1" }) : ok({ status: "complete", result: { signed_url: R2_URL } }); + } + return listing({ shop: DB_ID })(call); + }); + + const target = path.join(dir, "dump.sql"); + const { size } = await CloudflareD1Adapter.dumpOne!(config, "shop", target, host); + + expect(fs.readFileSync(target, "utf8")).toBe(DUMP); + expect(size).toBe(Buffer.byteLength(DUMP)); + const exports = calls.filter((call) => call.path.endsWith("/export")); + expect(exports.map((call) => call.body)).toEqual([ + { output_format: "polling" }, + { output_format: "polling", current_bookmark: "bm-1" }, + ]); + }); + + it("names the missing permission when the token may read but not export", async () => { + fakeCloudflare((call) => (call.path.endsWith("/export") ? refused(401, 10000, "Authentication error") : listing({ shop: DB_ID })(call))); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", path.join(dir, "d.sql"), host)).rejects.toThrow(/needs the permission D1 Edit/); + }); + + it("explains a database with an FTS5 table, which Cloudflare cannot export", async () => { + fakeCloudflare((call) => + call.path.endsWith("/export") + ? ok({ status: "error", error: "D1 Export error: cannot export databases with virtual tables (like FTS5)" }) + : listing({ shop: DB_ID })(call)); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", path.join(dir, "d.sql"), host)).rejects.toThrow(/Drop the virtual tables before the backup/); + }); + + it("refuses a download URL that is not on R2", async () => { + fakeCloudflare((call) => + call.path.endsWith("/export") + ? ok({ status: "complete", result: { signed_url: "https://attacker.example/x.sql" } }) + : listing({ shop: DB_ID })(call)); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", path.join(dir, "d.sql"), host)).rejects.toThrow(/not R2/); + }); + + it("fails for a database the account does not have", async () => { + fakeCloudflare(listing({ other: DB_ID })); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", path.join(dir, "d.sql"), host)).rejects.toThrow(/no D1 database named "shop"/); + }); + + it("checks for large integers first when the connection asks for it, and backs up anyway", async () => { + const { calls } = fakeCloudflare((call) => { + if (call.url === R2_URL) return { text: DUMP }; + if (call.path.endsWith("/export")) return ok({ status: "complete", result: { signed_url: R2_URL } }); + if (call.path.endsWith("/query")) { + const sql = (call.body as { sql: string }).sql; + if (sql.startsWith("SELECT name FROM sqlite_master")) return ok([{ success: true, results: [{ name: "big" }] }]); + if (sql.includes("pragma_table_info")) return ok([{ success: true, results: [{ name: "n" }] }]); + return ok([{ success: true, results: [{ c0: 1 }] }]); + } + return listing({ shop: DB_ID })(call); + }); + await CloudflareD1Adapter.dumpOne!({ ...config, checkLargeIntegers: true }, "shop", path.join(dir, "d.sql"), host); + const scan = calls.find((call) => (call.body as { sql?: string })?.sql?.startsWith("SELECT SUM(")); + expect((scan?.body as { sql: string }).sql).toContain(`typeof("n") = 'integer'`); + expect(calls.some((call) => call.path.endsWith("/export"))).toBe(true); + }); +}); + +/** Answers the import flow, keeping what was uploaded. */ +function importing(uuid: string, outcome: Record = { status: "complete", result: { num_queries: 3 } }) { + return (call: Call) => { + if (call.method === "PUT") return { headers: { etag: `"${md5(call.uploaded ?? "")}"` } }; + if (call.path !== `/d1/database/${uuid}/import`) return undefined; + const action = (call.body as { action: string }).action; + if (action === "init") return ok({ upload_url: "https://abc.r2.cloudflarestorage.com/up?sig=1", filename: "f.sql" }); + return ok(outcome); + }; +} + +describe("a restore into D1", () => { + it("replaces an existing database in one import: drops ahead of the dump, the database and its ID kept", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const { calls } = fakeCloudflare((call) => { + if (call.path.endsWith("/time_travel/bookmark")) return ok({ bookmark: "bm-before" }); + if (call.path.endsWith("/query")) { + return ok([{ success: true, results: [ + { type: "table", name: "orders", sql: "CREATE TABLE orders (x)" }, + { type: "trigger", name: "touch", sql: "CREATE TRIGGER touch ..." }, + { type: "view", name: "paid", sql: "CREATE VIEW paid AS ..." }, + ] }]); + } + return importing(DB_ID)(call) ?? listing({ shop: DB_ID })(call); + }); + + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host); + + const uploaded = calls.find((call) => call.method === "PUT")?.uploaded ?? ""; + expect(uploaded.indexOf('DROP TRIGGER IF EXISTS "touch";')).toBeLessThan(uploaded.indexOf('DROP VIEW IF EXISTS "paid";')); + expect(uploaded.indexOf('DROP VIEW IF EXISTS "paid";')).toBeLessThan(uploaded.indexOf('DROP TABLE IF EXISTS "orders";')); + expect(uploaded.endsWith(DUMP)).toBe(true); + const init = calls.find((call) => (call.body as { action?: string })?.action === "init"); + expect((init?.body as { etag: string }).etag).toBe(md5(uploaded)); + expect(calls.some((call) => call.method === "DELETE" || (call.method === "POST" && call.path === "/d1/database"))).toBe(false); + expect(fs.readdirSync(dir)).toEqual(["dump.sql"]); + }); + + it("leaves Cloudflare's and SQLite's own tables out of the drops", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const { calls } = fakeCloudflare((call) => { + if (call.path.endsWith("/time_travel/bookmark")) return ok({ bookmark: "bm" }); + if (call.path.endsWith("/query")) return ok([{ success: true, results: [] }]); + return importing(DB_ID)(call) ?? listing({ shop: DB_ID })(call); + }); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host); + const filter = (calls.find((call) => call.path.endsWith("/query"))?.body as { sql: string }).sql; + expect(filter).toContain("NOT LIKE 'sqlite\\_%'"); + expect(filter).toContain("NOT LIKE '\\_cf\\_%'"); + // An empty database gets the dump as it is. + expect(calls.find((call) => call.method === "PUT")?.uploaded).toBe(DUMP); + }); + + it("creates a database under a new name in the jurisdiction of the database the backup came from", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const { calls } = fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "shop-copy" }); + if (call.method === "GET" && call.path.includes("name=shop-copy")) return ok([]); + return importing(NEW_ID)(call) ?? listing({ shop: DB_ID }, "eu")(call); + }); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop-copy", host, undefined, undefined, "shop"); + expect(calls.find((call) => call.method === "POST" && call.path === "/d1/database")?.body).toEqual({ name: "shop-copy", jurisdiction: "eu" }); + }); + + it("creates a new database where the connection says, as a location hint", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const { calls } = fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + return importing(NEW_ID)(call) ?? listing({})(call); + }); + await CloudflareD1Adapter.restoreOne!({ ...config, newDatabaseLocation: "weur" }, dumpPath, "copy", host); + expect(calls.find((call) => call.method === "POST" && call.path === "/d1/database")?.body).toEqual({ name: "copy", primary_location_hint: "weur" }); + }); + + it("deletes a database it created when the import into it fails", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const { calls } = fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + if (call.method === "DELETE") return ok(null); + return importing(NEW_ID, { status: "error", error: "syntax error" })(call) ?? listing({})(call); + }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host)).rejects.toThrow(/left as it was: syntax error/); + expect(calls.find((call) => call.method === "DELETE")?.path).toBe(`/d1/database/${NEW_ID}`); + }); + + it("starts the import without an upload when Cloudflare already holds the file", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const { calls } = fakeCloudflare((call) => { + if (call.path.endsWith("/time_travel/bookmark")) return ok({ bookmark: "bm" }); + if (call.path.endsWith("/query")) return ok([{ success: true, results: [] }]); + if (call.path.endsWith("/import")) return ok({ status: "complete", result: { num_queries: 3 } }); + return listing({ shop: DB_ID })(call); + }); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host); + expect(calls.some((call) => call.method === "PUT")).toBe(false); + }); + + it("refuses an upload that arrived damaged", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + fakeCloudflare((call) => { + if (call.method === "PUT") return { headers: { etag: '"0000"' } }; + if (call.path.endsWith("/time_travel/bookmark")) return ok({ bookmark: "bm" }); + if (call.path.endsWith("/query")) return ok([{ success: true, results: [] }]); + return importing(DB_ID)(call) ?? listing({ shop: DB_ID })(call); + }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host)).rejects.toThrow(/arrived damaged/); + }); +}); diff --git a/tests/unit/adapters/database/cloudflare-d1/browser.test.ts b/tests/unit/adapters/database/cloudflare-d1/browser.test.ts new file mode 100644 index 000000000..1a22c7a64 --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/browser.test.ts @@ -0,0 +1,59 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { CloudflareD1Adapter } from "@/lib/adapters/database/cloudflare-d1"; +import { DB_ID, config, fakeCloudflare, ok, type Call } from "./fake-cloudflare"; + +const host = {} as never; + +afterEach(() => vi.unstubAllGlobals()); + +/** A database with one table `orders (id, note)`. */ +function shop(extra?: (call: Call) => ReturnType | undefined) { + return fakeCloudflare((call) => { + const answer = extra?.(call); + if (answer) return answer; + if (call.method === "GET") return ok([{ uuid: DB_ID, name: "shop" }]); + const { sql, params } = call.body as { sql: string; params?: unknown[] }; + if (sql.includes("count(*) AS n FROM sqlite_master")) return ok([{ success: true, results: [{ n: params?.[0] === "orders" ? 1 : 0 }] }]); + if (sql.includes("pragma_table_info")) { + return ok([{ success: true, results: [ + { name: "id", type: "INTEGER", notnull: 1, dflt_value: null, pk: 1 }, + { name: "note", type: "TEXT", notnull: 0, dflt_value: null, pk: 0 }, + ] }]); + } + if (sql.startsWith("SELECT count(*) AS n FROM")) return ok([{ success: true, results: [{ n: 1 }] }]); + if (call.path.endsWith("/raw")) return ok([{ success: true, results: { columns: ["a", "b"], rows: [["9007199254740993", "hi"]] } }]); + return undefined; + }); +} + +describe("the Database Explorer of a D1 database", () => { + it("reads a page with the search as a parameter and maps the rows to the column names", async () => { + const { calls } = shop(); + const page = await CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "orders", page: 2, pageSize: 10, search: "x'; DROP", searchColumn: "note", sortBy: "id", sortDir: "desc" }, host); + expect(page.rows).toEqual([{ id: "9007199254740993", note: "hi" }]); + expect(page.totalCount).toBe(1); + const raw = calls.find((call) => call.path.endsWith("/raw"))?.body as { sql: string; params: unknown[] }; + expect(raw.params).toEqual(["%x'; DROP%"]); + expect(raw.sql).not.toContain("DROP"); + expect(raw.sql).toContain(`ORDER BY "id" DESC LIMIT 10 OFFSET 10`); + // A large integer comes as text, so the page shows it exactly. + expect(raw.sql).toContain(`CAST("id" AS TEXT)`); + }); + + it("refuses a table sqlite_master does not list, like sqlite_master itself", async () => { + const { calls } = shop(); + await expect(CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "sqlite_master", page: 1, pageSize: 10 }, host)).rejects.toThrow(/does not exist/); + expect(calls.some((call) => call.path.endsWith("/raw"))).toBe(false); + }); + + it("refuses a sort or search column the table does not have", async () => { + shop(); + await expect(CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "orders", page: 1, pageSize: 10, sortBy: "id\" DESC; --" }, host)).rejects.toThrow(/column does not exist/); + }); + + it("caps the page size, whatever the caller asks", async () => { + const { calls } = shop(); + await CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "orders", page: 1, pageSize: 1_000_000 }, host); + expect((calls.find((call) => call.path.endsWith("/raw"))?.body as { sql: string }).sql).toContain("LIMIT 500 OFFSET 0"); + }); +}); diff --git a/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts b/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts new file mode 100644 index 000000000..1a6d03cb3 --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts @@ -0,0 +1,65 @@ +import { vi } from "vitest"; + +/** + * A stand-in for the API of Cloudflare and its R2 bucket behind `fetch`. Each test answers the + * calls it cares about through `route`, every call is recorded with its parsed body. + */ + +export const ACCOUNT = "0123456789abcdef0123456789abcdef"; +export const DB_ID = "11111111-2222-3333-4444-555555555555"; +export const NEW_ID = "66666666-7777-8888-9999-000000000000"; +export const R2_URL = "https://abc123.r2.cloudflarestorage.com/export.sql?X-Amz-Signature=secret"; + +export interface Call { + method: string; + url: string; + /** The path below `/accounts/`, or the full URL for a call elsewhere. */ + path: string; + body: unknown; + headers: Record; + /** The text of an upload. */ + uploaded?: string; +} + +export type Answer = { status?: number; json?: unknown; text?: string; headers?: Record }; + +export function ok(result: unknown, extra: Record = {}): Answer { + return { json: { success: true, errors: [], messages: [], result, ...extra } }; +} + +export function refused(status: number, code: number, message: string): Answer { + return { status, json: { success: false, errors: [{ code, message }], messages: [], result: null } }; +} + +async function textOf(body: unknown): Promise { + if (body == null || typeof body === "string") return body ?? undefined; + if (typeof (body as ReadableStream).getReader === "function") { + return new Response(body as ReadableStream).text(); + } + return undefined; +} + +export function fakeCloudflare(route: (call: Call) => Answer | undefined) { + const calls: Call[] = []; + const fetchMock = vi.fn(async (input: string | URL, init: RequestInit = {}) => { + const url = String(input); + const prefix = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}`; + const raw = typeof init.body === "string" ? init.body : undefined; + const call: Call = { + method: init.method ?? "GET", + url, + path: url.startsWith(prefix) ? url.slice(prefix.length) : url, + body: raw ? JSON.parse(raw) : undefined, + headers: Object.fromEntries(Object.entries((init.headers ?? {}) as Record)), + }; + if (call.method === "PUT") call.uploaded = await textOf(init.body); + calls.push(call); + const answer = route(call) ?? { status: 404, json: { success: false, errors: [{ code: 7404, message: `no route for ${call.method} ${call.path}` }] } }; + const body = answer.text ?? JSON.stringify(answer.json ?? {}); + return new Response(body, { status: answer.status ?? 200, headers: answer.headers }); + }); + vi.stubGlobal("fetch", fetchMock); + return { calls, fetchMock }; +} + +export const config = { accountId: ACCOUNT, token: "test-token", database: "", checkLargeIntegers: false, newDatabaseLocation: "auto" }; diff --git a/website/src/i18n/messages/de.json b/website/src/i18n/messages/de.json index a533a3279..7b6e8d4b6 100644 --- a/website/src/i18n/messages/de.json +++ b/website/src/i18n/messages/de.json @@ -647,6 +647,10 @@ "versions": "Einzeldatenbank, Pool für elastische Datenbanken", "text": "Ein BACPAC-Export per SqlPackage. Eine Wiederherstellung ersetzt die Zieldatenbank." }, + "cloudflare-d1": { + "versions": "Jede D1-Datenbank eines Accounts", + "text": "Der SQL-Export von Cloudflare über die API, mit einem API-Token und ohne Installation. Eine Wiederherstellung ersetzt die Tabellen und behält die ID der Datenbank." + }, "firebird": { "versions": "Versionen 3, 4 und 5", "text": "Backups mit gbak, wiederhergestellt über Aliase, die Sie auf dem Server einrichten." diff --git a/website/src/i18n/messages/en.json b/website/src/i18n/messages/en.json index de3df6497..ed8dfefb7 100644 --- a/website/src/i18n/messages/en.json +++ b/website/src/i18n/messages/en.json @@ -647,6 +647,10 @@ "versions": "Single database, elastic pool", "text": "A BACPAC export through SqlPackage. A restore replaces the target database." }, + "cloudflare-d1": { + "versions": "Every D1 database of an account", + "text": "The SQL export of Cloudflare through its API, with an API token and nothing to install. A restore replaces the tables and keeps the database ID." + }, "firebird": { "versions": "Versions 3, 4 and 5", "text": "Backups with gbak, restored through aliases you set up on the server." diff --git a/website/src/lib/adapter-icons.ts b/website/src/lib/adapter-icons.ts index 935b6d145..3197439be 100644 --- a/website/src/lib/adapter-icons.ts +++ b/website/src/lib/adapter-icons.ts @@ -65,6 +65,7 @@ const ADAPTER_ICON_MAP: Record = { valkey: valkeyIcon, mssql: mssqlIcon, "azure-sql": azureIcon, + "cloudflare-d1": cloudflareIcon, firebird: firebirdIcon, // Storage "local-filesystem": harddiskIcon, diff --git a/website/src/lib/content.ts b/website/src/lib/content.ts index e23504c87..154e9d773 100644 --- a/website/src/lib/content.ts +++ b/website/src/lib/content.ts @@ -41,6 +41,7 @@ export const DATABASES: AdapterItem[] = [ { id: "valkey", label: "Valkey" }, { id: "mssql", label: "Microsoft SQL Server" }, { id: "azure-sql", label: "Azure SQL Database", beta: true }, + { id: "cloudflare-d1", label: "Cloudflare D1", beta: true }, { id: "firebird", label: "Firebird", beta: true }, ]; diff --git a/website/src/lib/integrations.ts b/website/src/lib/integrations.ts index b0c13bb6a..1ad65dc38 100644 --- a/website/src/lib/integrations.ts +++ b/website/src/lib/integrations.ts @@ -26,6 +26,7 @@ export const DUMP_TOOL: Record = { valkey: "redis-cli --rdb", mssql: "BACKUP DATABASE", "azure-sql": "SqlPackage", + "cloudflare-d1": "D1 export API", firebird: "gbak", }; @@ -40,6 +41,7 @@ export const DATABASE_COLORS: Record = { valkey: "#3b82f6", mssql: "#cc2927", "azure-sql": "#0089d6", + "cloudflare-d1": "#f38020", firebird: "#f97316", }; From 30d87aec6df52f6ab51cf85b61863fe0611d5eeb Mon Sep 17 00:00:00 2001 From: Manu Date: Mon, 23 Nov 2026 17:04:08 -0600 Subject: [PATCH 2/7] Add Cloudflare D1 to the dev lab With cloudflareD1 in the lab config the seed fills the database dbackup-lab-shop of the test account with the SQLite dataset and adds the source Lab Cloudflare D1 and a job to Local, which lab:check tests and runs like the other lab connections. --- docs/developer-guide/reference/dev-lab.md | 7 +++ lab/src/config.ts | 14 +++++ lab/src/seed/cloudflare-d1.ts | 63 +++++++++++++++++++++++ lab/src/seed/jobs.ts | 6 ++- lab/src/seed/sources.ts | 3 ++ lab/src/status.ts | 1 + tests/unit/lab/config.test.ts | 15 ++++++ 7 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 lab/src/seed/cloudflare-d1.ts diff --git a/docs/developer-guide/reference/dev-lab.md b/docs/developer-guide/reference/dev-lab.md index 995462042..883be8660 100644 --- a/docs/developer-guide/reference/dev-lab.md +++ b/docs/developer-guide/reference/dev-lab.md @@ -107,6 +107,7 @@ The lab reads the first config it finds: the file in `DBACKUP_LAB_CONFIG`, then | `profile` | `core` for the oldest and newest version of each engine, `full` for every version | `core` | | `docker` | The Docker host of the whole lab: its [docker context](https://docs.docker.com/engine/manage-resources/contexts/), the address DBackup reaches its ports under, and an `ssh` login for SQL Server, see [A Remote Docker Host](#a-remote-docker-host) | this machine | | `native` | Servers without Docker by name: their address, an `ssh` login that may run the setup as root, and the `login` of their sources, see [A Native Server](#a-native-server) | none | +| `cloudflareD1` | The `accountId` and `token` of a Cloudflare account just for tests, see [Cloudflare D1](#cloudflare-d1). A token of `env:NAME` is read from that environment variable | none | Every field is checked, and one the lab does not know is refused, so a typo does not go unnoticed. @@ -134,6 +135,12 @@ The seed then adds every database of the server as a source in SSH mode. The end MongoDB 5 and later need a CPU with AVX. A virtual machine with a generic CPU model has none, so give it the CPU type of its host, or MongoDB 8.0 does not start there, in a container or from the packages. +## Cloudflare D1 + +D1 runs at Cloudflare and nowhere else, so no container stands in for it. With `cloudflareD1` in the config, the seed makes sure the account holds the database `dbackup-lab-shop` with the SQLite dataset, adds the source **Lab Cloudflare D1** with a Token profile and the job **Lab Cloudflare D1 to Local**, which backs up that database only. Without it the lab has no D1 source, and `lab:status` says so. + +Use a Cloudflare account of its own for this, with an API token that has **Account > D1 > Edit**. Cloudflare cannot limit a D1 token to single databases, so a token of an account with real databases could change every one of them. The free plan is enough. + ## Adding an Engine or Version Everything the lab knows about an engine is in its file under `lab/src/engines/`: the versions with their services and ports, the login, the clients in the container, the dataset with how to check for it and load it, the config of a source, and how its tools read a database and drop one again. The catalog, the dataset loader, the seed, `lab:status` and the tests all read it from there. diff --git a/lab/src/config.ts b/lab/src/config.ts index de7a488df..d153926e9 100644 --- a/lab/src/config.ts +++ b/lab/src/config.ts @@ -56,6 +56,15 @@ const ConfigSchema = z.object({ /** The OpenSSH login of the sources, a user without root like on a real server. */ login: SshSchema, }).strict()).optional(), + /** + * A Cloudflare account just for tests, with an API token that has D1 Edit. Without it the lab + * has no Cloudflare D1 source, since D1 runs at Cloudflare and nowhere else. + */ + cloudflareD1: z.object({ + accountId: z.string().regex(/^[0-9a-fA-F]{32}$/, "the 32 hex characters of the Cloudflare dashboard"), + /** The token, or `env:NAME`. */ + token: z.string().min(1), + }).strict().optional(), }).strict(); export interface SshLogin { @@ -90,6 +99,8 @@ export interface LabConfig { profile: "core" | "full"; docker: DockerHost; natives: NativeHost[]; + /** The Cloudflare account of the D1 source, when the config has one. */ + cloudflareD1?: { accountId: string; token: string }; } /** A NetBird SSH server takes any password, so a host that only has one of those needs none in the config. */ @@ -148,6 +159,9 @@ export function parseConfig(raw: unknown, source: string): LabConfig { ssh: host.ssh ? sshLogin(host.ssh, 22) : undefined, login: sshLogin(host.login, 22), })), + cloudflareD1: config.cloudflareD1 + ? { accountId: config.cloudflareD1.accountId.toLowerCase(), token: resolveSecret(config.cloudflareD1.token) } + : undefined, }; } diff --git a/lab/src/seed/cloudflare-d1.ts b/lab/src/seed/cloudflare-d1.ts new file mode 100644 index 000000000..eb861e86f --- /dev/null +++ b/lab/src/seed/cloudflare-d1.ts @@ -0,0 +1,63 @@ +/** + * The Cloudflare D1 source of the lab. D1 runs at Cloudflare and nowhere else, so the lab needs a + * Cloudflare account of its own for tests (`cloudflareD1` in the lab config), and without one it + * has no D1 source. The seed makes sure the account holds the database `dbackup-lab-shop` with the + * SQLite dataset of the lab, and adds the source with its token. + */ + +import { readFileSync } from "fs"; +import os from "os"; +import path from "path"; +import { mkdtemp, rm, writeFile } from "fs/promises"; +import { d1Request, databaseIdOf, findDatabase, query } from "@/lib/adapters/database/cloudflare-d1/api"; +import { importDatabase } from "@/lib/adapters/database/cloudflare-d1/jobs"; +import { REPO_ROOT, type LabConfig } from "../config"; +import { ensureCredential } from "./records"; +import type { Note } from "./sources"; + +/** The database of the lab in the test account. */ +export const LAB_D1_DATABASE = "dbackup-lab-shop"; + +/** The database of the lab, created and filled with the dataset when it is missing or empty. */ +async function ensureLabDatabase(connection: { accountId: string; token: string }, log: string[]): Promise { + let database = await findDatabase(connection, LAB_D1_DATABASE); + if (!database) { + const { result } = await d1Request<{ uuid: string }>(connection, "seed", "POST", "/d1/database", { name: LAB_D1_DATABASE }); + database = { uuid: databaseIdOf(result.uuid), name: LAB_D1_DATABASE }; + log.push(`created the D1 database ${LAB_D1_DATABASE}`); + } + const uuid = databaseIdOf(database.uuid); + const [tables] = await query<{ n: number }>(connection, uuid, "SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = 'customers'"); + if (Number(tables?.results?.[0]?.n) > 0) return; + + const folder = await mkdtemp(path.join(os.tmpdir(), "lab-d1-")); + try { + const file = path.join(folder, "shop.sql"); + await writeFile(file, readFileSync(path.join(REPO_ROOT, "lab", "datasets", "sqlite.sql"), "utf8")); + await importDatabase(connection, uuid, file, () => undefined); + log.push(`filled the D1 database ${LAB_D1_DATABASE} with the dataset of SQLite`); + } finally { + await rm(folder, { recursive: true, force: true }); + } +} + +export async function seedCloudflareD1(config: LabConfig, note: Note, log: string[]): Promise { + const account = config.cloudflareD1; + if (!account) { + log.push("skipped Cloudflare D1, the lab config has no cloudflareD1"); + return; + } + try { + await ensureLabDatabase(account, log); + } catch (error) { + log.push(`could not prepare the D1 database ${LAB_D1_DATABASE}: ${error instanceof Error ? error.message : String(error)}`); + } + const token = await ensureCredential("Lab Cloudflare D1 token", "TOKEN", { token: account.token }); + await note({ + name: "Lab Cloudflare D1", + type: "database", + adapterId: "cloudflare-d1", + config: { accountId: account.accountId, database: "", checkLargeIntegers: true, newDatabaseLocation: "auto" }, + primaryCredentialId: token, + }, "cloudflare-d1"); +} diff --git a/lab/src/seed/jobs.ts b/lab/src/seed/jobs.ts index c0c1c5dc2..046a8da40 100644 --- a/lab/src/seed/jobs.ts +++ b/lab/src/seed/jobs.ts @@ -21,6 +21,8 @@ interface JobSpec { retentionPolicyId?: string; notify?: string[]; incremental?: boolean; + /** The databases the job backs up, all of the source when left out. */ + databases?: string[]; } const JOBS: JobSpec[] = [ @@ -33,6 +35,8 @@ const JOBS: JobSpec[] = [ { name: "Lab Firebird 5 to Rsync", source: "firebird-5", destinations: ["rsync"] }, { name: "Lab PostgreSQL 12 over SSH to Local", source: "postgres-12-ssh", destinations: ["local"] }, { name: "Lab SQLite to Local", source: "sqlite", destinations: ["local"] }, + // Only the database of the lab, the test account may hold others. + { name: "Lab Cloudflare D1 to Local", source: "cloudflare-d1", destinations: ["local"], databases: ["dbackup-lab-shop"] }, { name: "Lab Files incremental to Local", source: "files", destinations: ["local"], incremental: true }, ]; @@ -72,7 +76,7 @@ export async function seedJobs(connections: SeededConnections, nativeHosts: stri enabled: false, ...(job.incremental ? { sources: [{ configId: sourceId, priority: 0, path: "/" }], backupMode: "INCREMENTAL", fullEveryDays: 7 } - : { sourceId, databases: [] }), + : { sourceId, databases: job.databases ?? [] }), destinations: destinationIds.map((configId, priority) => ({ configId: configId!, priority, diff --git a/lab/src/seed/sources.ts b/lab/src/seed/sources.ts index b85233d25..4b1a53e47 100644 --- a/lab/src/seed/sources.ts +++ b/lab/src/seed/sources.ts @@ -10,6 +10,7 @@ import { STORAGE, databasesOf, sourceName } from "../catalog"; import { ENGINES, engineOf } from "../engines"; import { ensureCredential, type ConnectionSpec } from "./records"; import { ensureFilesFolder, ensureLocalSqlite } from "./setup"; +import { seedCloudflareD1 } from "./cloudflare-d1"; export type Note = (spec: ConnectionSpec, key: string) => Promise; @@ -104,6 +105,8 @@ export async function seedSources(config: LabConfig, note: Note, log: string[]): sshCredentialId: sshHost, }, "sqlite-ssh"); + await seedCloudflareD1(config, note, log); + await note({ name: "Lab Files", type: "storage", diff --git a/lab/src/status.ts b/lab/src/status.ts index 72749c4db..de3bafc17 100644 --- a/lab/src/status.ts +++ b/lab/src/status.ts @@ -159,6 +159,7 @@ export async function status(config: LabConfig, workspace: string, write: Write) `${bold("Config")} ${config.source}, profile ${config.profile}`, `${bold("Docker host")} ${config.docker.name} (${config.docker.address})`, `${bold("Workspace")} ${workspace}`, + `${bold("Cloudflare")} ${config.cloudflareD1 ? `D1 account ${config.cloudflareD1.accountId.slice(0, 8)}...` : "no cloudflareD1 in the config, the lab has no D1 source"}`, ]; for (const line of renderStatus(header, sections)) write(line); return !sections.some((section) => section.rows.some((row) => row.mark === "fail")); diff --git a/tests/unit/lab/config.test.ts b/tests/unit/lab/config.test.ts index c0d593d45..cb8178c47 100644 --- a/tests/unit/lab/config.test.ts +++ b/tests/unit/lab/config.test.ts @@ -34,6 +34,21 @@ describe("the dev lab config", () => { expect(config.natives[0].login).toEqual({ user: "dbackup", port: 2222, password: "Real-Password-42" }); }); + it("reads the Cloudflare account of the D1 source, with the token from the environment", () => { + process.env.LAB_TEST_D1_TOKEN = "token-from-env"; + try { + const config = parseConfig({ admin, cloudflareD1: { accountId: "0123456789ABCDEF0123456789ABCDEF", token: "env:LAB_TEST_D1_TOKEN" } }, "test.json"); + expect(config.cloudflareD1).toEqual({ accountId: "0123456789abcdef0123456789abcdef", token: "token-from-env" }); + } finally { + delete process.env.LAB_TEST_D1_TOKEN; + } + expect(parseConfig({ admin }, "test.json").cloudflareD1).toBeUndefined(); + }); + + it("refuses an account ID that is not the one of the Cloudflare dashboard", () => { + expect(() => parseConfig({ admin, cloudflareD1: { accountId: "my-account", token: "t" } }, "test.json")).toThrow(/cloudflareD1\.accountId/); + }); + it("says how to move a config that still places the parts on several hosts", () => { expect(() => parseConfig({ admin, hosts: { debian: { docker: "lab-debian", address: "100.100.30.1" } }, place: { databases: "debian" } }, "test.json")) .toThrow(/one Docker host now/); From d1779505a9ba2437aaa8168ca873d545759912b9 Mon Sep 17 00:00:00 2001 From: Manu Date: Mon, 23 Nov 2026 17:22:41 -0600 Subject: [PATCH 3/7] Add an end-to-end family for Cloudflare D1 The family cloud backs up a database of a Cloudflare test account, restores it under a new name and over a changed copy, and compares both through the API of Cloudflare. It reads the account from E2E_D1_ACCOUNT_ID and E2E_D1_TOKEN or the lab config and skips without one, and only its CI job gets the token. --- .github/workflows/validate.yml | 6 +- e2e/CLAUDE.md | 1 + e2e/support/cloudflare.ts | 104 +++++++++++++++++++++++++++++++++ e2e/support/targets.ts | 2 + e2e/tests/cloud.spec.ts | 63 ++++++++++++++++++++ 5 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 e2e/support/cloudflare.ts create mode 100644 e2e/tests/cloud.spec.ts diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index f33f59824..71673196c 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -177,13 +177,17 @@ jobs: strategy: fail-fast: false matrix: - family: [ui, postgres, mysql, mongodb, mssql, small, customer, storage] + family: [ui, postgres, mysql, mongodb, mssql, small, customer, storage, cloud] env: CI: "true" E2E_FAMILIES: ${{ matrix.family }} E2E_NO_BUILD: "1" # The runner is thrown away anyway, and the logs of DBackup are wanted after a failure. E2E_KEEP: "1" + # The Cloudflare account of the D1 tests, an account just for them. Only the job of the family + # cloud gets the token, and a pull request from a fork none, so its D1 test skips. + E2E_D1_ACCOUNT_ID: ${{ matrix.family == 'cloud' && vars.E2E_D1_ACCOUNT_ID || '' }} + E2E_D1_TOKEN: ${{ matrix.family == 'cloud' && secrets.E2E_D1_TOKEN || '' }} steps: # The image, its build and the images of the family take more than the free space of a # runner leaves, SQL Server alone pulls 4 GB. Deleting takes a while, so it runs in the diff --git a/e2e/CLAUDE.md b/e2e/CLAUDE.md index cab604e90..8fb2796da 100644 --- a/e2e/CLAUDE.md +++ b/e2e/CLAUDE.md @@ -33,6 +33,7 @@ pnpm test:e2e:ui # Playwright UI mode | `small` | `engines.spec.ts`, `folders.spec.ts` | Redis, Valkey, Firebird, SQLite over SSH, a folder | | `customer` | `engines.spec.ts` | The databases of the customer server over its OpenSSH | | `storage` | `storage.spec.ts`, `notifications.spec.ts` | Every destination and every channel, with SQLite inside DBackup as the source | +| `cloud` | `cloud.spec.ts` | Cloudflare D1 in a test account at Cloudflare, through `support/cloudflare.ts`. Skips without `E2E_D1_ACCOUNT_ID` and `E2E_D1_TOKEN` (CI reads them from the variable and the secret of the same names) or `cloudflareD1` in the lab config | - The sign-in specs under `tests/ui/` (`auth*.spec.ts`) make a person of their own per test through `support/auth.ts`, never a second factor or a passkey on the shared admin, which the setup signs in with on every run. The code of an authenticator app comes from the key the setup shows (`totp`), a passkey from the virtual authenticator of Chromium over CDP (`addVirtualAuthenticator`). better-auth limits `/sign-in/*` and `/two-factor/*` on its own, three requests from one address each within ten seconds of the last, which Settings does not lift, so every such request goes through `paced` and the specs end with `quietLimits`. - `auth-sso.spec.ts` and `tenants-sso.spec.ts` sign in through Dex, the service `dex` of `lab/compose/e2e.yml` with `DEX` of `lab/src/catalog.ts`. DBackup reaches it at `http://dex:5556` in the network of the lab, and the browser of the `ui` project at the same name through `DEX_HOST_RULE` (`--host-resolver-rules`), so both see one issuer. Dex knows a fixed client and fixed people, so each attempt of a retry takes the provider ID and the people of its number (`dexProviderId`, `dexPerson`). Its client redirects to port 3300 only, so another `E2E_PORT` skips the specs. The tenant spec claims a domain of its own (`DEX_TENANT_DOMAIN`, `dexTenantPerson`), since the provider of the platform adds nobody of a domain a tenant claims. A new person or redirect URI goes into the inline config of Dex in `e2e.yml`, which `tests/unit/lab/lab-parts.test.ts` checks against the catalog. diff --git a/e2e/support/cloudflare.ts b/e2e/support/cloudflare.ts new file mode 100644 index 000000000..8070db2b0 --- /dev/null +++ b/e2e/support/cloudflare.ts @@ -0,0 +1,104 @@ +/** + * The test account of Cloudflare D1, reached from the tests themselves to make a database, fill it, + * read what a restore wrote and delete it again. Nothing of the app is imported here. + * + * The account comes from `E2E_D1_ACCOUNT_ID` and `E2E_D1_TOKEN`, which CI sets from the settings + * of the repository, or from `cloudflareD1` of the lab config. Without either the D1 tests skip, + * also in CI, since a pull request from a fork gets no secrets. + */ + +import { readFileSync } from "fs"; +import path from "path"; +import { REPO_ROOT } from "../../lab/src/config"; +import { lab } from "./environment"; + +export interface D1Account { + accountId: string; + token: string; +} + +export function d1Account(): D1Account | null { + const accountId = process.env.E2E_D1_ACCOUNT_ID || lab.cloudflareD1?.accountId; + const token = process.env.E2E_D1_TOKEN || lab.cloudflareD1?.token; + return accountId && token ? { accountId: accountId.toLowerCase(), token } : null; +} + +/** A database of a test run older than this is left over from a run that never cleaned up. */ +const LEFTOVER_AGE_MS = 2 * 60 * 60 * 1000; + +interface Database { + uuid: string; + name: string; + created_at?: string; +} + +export class D1 { + constructor(private readonly account: D1Account) {} + + private async call(method: string, apiPath: string, body?: unknown): Promise { + const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${this.account.accountId}${apiPath}`, { + method, + headers: { Authorization: `Bearer ${this.account.token}`, "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const json = await response.json() as { success: boolean; result: T; errors?: { message: string }[] }; + if (!json.success) throw new Error(`Cloudflare ${method} ${apiPath}: ${(json.errors ?? []).map((error) => error.message).join("; ")}`); + return json.result; + } + + async list(): Promise { + return this.call("GET", "/d1/database?per_page=1000"); + } + + async find(name: string): Promise { + return (await this.list()).find((database) => database.name === name); + } + + /** A new database with the SQLite dataset of the lab. */ + async createShop(name: string): Promise { + const database = await this.call("POST", "/d1/database", { name }); + await this.query(database.uuid, readFileSync(path.join(REPO_ROOT, "lab", "datasets", "sqlite.sql"), "utf8")); + return database; + } + + async query>(uuid: string, sql: string, params?: unknown[]): Promise { + const results = await this.call<{ results: Row[] }[]>("POST", `/d1/database/${uuid}/query`, params ? { sql, params } : { sql }); + return results[results.length - 1]?.results ?? []; + } + + async delete(name: string): Promise { + const database = await this.find(name); + if (database) await this.call("DELETE", `/d1/database/${database.uuid}`); + } + + /** Deletes the databases of earlier runs that ended before their cleanup. The free plan holds only a few. */ + async deleteLeftovers(): Promise { + const now = Date.now(); + for (const database of await this.list()) { + const age = database.created_at ? now - Date.parse(database.created_at) : 0; + if (database.name.startsWith("e2e") && age > LEFTOVER_AGE_MS) { + await this.call("DELETE", `/d1/database/${database.uuid}`).catch(() => undefined); + } + } + } + + /** + * What a database holds, as text: the schema of every object and every row of every table, + * each value through quote(), so blobs and large integers compare exactly. Objects of SQLite + * and of Cloudflare are left out. + */ + async fingerprint(name: string): Promise { + const database = await this.find(name); + if (!database) throw new Error(`No D1 database ${name}`); + const internal = "name NOT LIKE 'sqlite\\_%' ESCAPE '\\' AND name NOT LIKE '\\_cf\\_%' ESCAPE '\\'"; + const schema = await this.query<{ type: string; name: string; sql: string }>(database.uuid, `SELECT type, name, sql FROM sqlite_master WHERE ${internal} ORDER BY type, name`); + const lines = schema.map((object) => `${object.type} ${object.name}: ${object.sql}`); + for (const table of schema.filter((object) => object.type === "table")) { + const columns = await this.query<{ name: string }>(database.uuid, "SELECT name FROM pragma_table_info(?)", [table.name]); + const values = columns.map((column) => `quote("${column.name.replace(/"/g, '""')}")`).join(" || '|' || "); + const rows = await this.query<{ r: string }>(database.uuid, `SELECT ${values} AS r FROM "${table.name.replace(/"/g, '""')}" ORDER BY rowid`); + lines.push(...rows.map((row) => `${table.name}: ${row.r}`)); + } + return lines.join("\n"); + } +} diff --git a/e2e/support/targets.ts b/e2e/support/targets.ts index 92131fcfd..e8d4ea89f 100644 --- a/e2e/support/targets.ts +++ b/e2e/support/targets.ts @@ -122,6 +122,8 @@ export const FAMILIES: Family[] = [ { name: "customer", targets: customerTargets() }, // The destinations and channels, with SQLite inside DBackup as the source. { name: "storage", targets: [], services: [...STORAGE_SERVICES, ...NOTIFY_SERVICES] }, + // Cloudflare D1, which runs at Cloudflare and needs no service of the lab, see `cloud.spec.ts`. + { name: "cloud", targets: [] }, ]; /** The services of the lab a family needs. */ diff --git a/e2e/tests/cloud.spec.ts b/e2e/tests/cloud.spec.ts new file mode 100644 index 000000000..628cf6c03 --- /dev/null +++ b/e2e/tests/cloud.spec.ts @@ -0,0 +1,63 @@ +/** + * Cloudflare D1 through DBackup, against the test account of Cloudflare: Test connection, a backup + * encrypted and compressed through the real queue and runner of the image, a restore under a new + * name that creates the database, and a restore over that database after it changed. The test + * reads both databases through the API of Cloudflare and compares them. + * + * Without an account (`E2E_D1_ACCOUNT_ID` and `E2E_D1_TOKEN`, or `cloudflareD1` of the lab config) + * the test skips, also in CI, where a pull request from a fork gets no secrets. + */ + +import { expect, test } from "@playwright/test"; +import { App, problemOf, unique } from "../support/app"; +import { localDestination } from "../support/backups"; +import { D1, d1Account } from "../support/cloudflare"; + +test("[cloud] cloudflare-d1 restores under a new name and over a changed database with the same content", async ({ request }) => { + const account = d1Account(); + test.skip(!account, "No Cloudflare test account, set E2E_D1_ACCOUNT_ID and E2E_D1_TOKEN or cloudflareD1 in the lab config"); + test.setTimeout(10 * 60_000); + const d1 = new D1(account!); + const app = new App(request); + const name = unique(); + const original = `${name}-shop`; + const copy = `${name}-copy`; + + await d1.deleteLeftovers(); + await d1.createShop(original); + try { + const connection = { + adapterId: "cloudflare-d1", + config: { accountId: account!.accountId, database: "", checkLargeIntegers: true, newDatabaseLocation: "auto" }, + primaryCredentialId: await app.credential(`${name} token`, "TOKEN", { token: account!.token }), + }; + const tested = await app.testConnection(connection); + expect(tested.success, tested.message).toBe(true); + const sourceId = await app.connection({ ...connection, name: `${name} cloudflare-d1`, type: "database" }); + + const destination = await localDestination(app, name); + const job = await app.job(`${name} cloudflare-d1`, sourceId, [destination], await app.vaultKey(), "database", [original]); + const backup = await app.backUp(job.id); + expect(backup.status, problemOf(backup)).toBe("Success"); + expect(Number(backup.size)).toBeGreaterThan(0); + + const before = await d1.fingerprint(original); + const restored = await app.restore(destination, { file: backup.path, targetSourceId: sourceId, databaseMapping: { [original]: copy } }); + expect(restored.status, problemOf(restored)).toBe("Success"); + expect(await d1.fingerprint(copy)).toBe(before); + + // A restore over an existing database replaces what changed since, and keeps the database. + const target = (await d1.find(copy))!; + await d1.query(target.uuid, "INSERT INTO customers (name, email, created_at) VALUES ('Later', 'later@example.ch', '2030-01-01'); CREATE TABLE added_later (x INTEGER);"); + const replaced = await app.restore(destination, { file: backup.path, targetSourceId: sourceId, databaseMapping: { [original]: copy } }); + expect(replaced.status, problemOf(replaced)).toBe("Success"); + expect(await d1.fingerprint(copy)).toBe(before); + expect((await d1.find(copy))?.uuid).toBe(target.uuid); + } finally { + // CI sets E2E_KEEP for the runner it throws away, but these databases live at Cloudflare. + if (!process.env.E2E_KEEP || process.env.CI) { + await d1.delete(copy).catch(() => undefined); + await d1.delete(original).catch(() => undefined); + } + } +}); From fbe55faa04ef112666ab9941268e2b6c7edda64b Mon Sep 17 00:00:00 2001 From: Manu Date: Mon, 23 Nov 2026 17:22:41 -0600 Subject: [PATCH 4/7] Harden the Cloudflare D1 adapter after its security review A restore streams the drops ahead of the dump into the upload instead of writing a second file, so no decrypted copy lands in the temp folder. A stored token no longer follows a change of the account ID. The Database Explorer reads at most 16 MB per page and shows BLOBs cut to 1 KB, polls are tried again with a pause after a failure on the way, and a database a restore created stays when Cloudflare may still finish the import. URLs in the messages of Cloudflare are left out of the run log. --- docs/user-guide/sources/cloudflare-d1.md | 4 + lab/src/seed/cloudflare-d1.ts | 2 +- .../adapters/database/cloudflare-d1/api.ts | 33 +++++--- .../database/cloudflare-d1/browser.ts | 13 ++- .../adapters/database/cloudflare-d1/jobs.ts | 82 ++++++++++++++----- .../database/cloudflare-d1/restore.ts | 31 ++----- .../database/cloudflare-d1/transfer.ts | 36 ++++++-- src/lib/adapters/stored-secrets.ts | 2 + .../cloudflare-d1/backup-restore.test.ts | 40 +++++++++ .../adapters/stored-secrets-address.test.ts | 13 +++ 10 files changed, 192 insertions(+), 64 deletions(-) diff --git a/docs/user-guide/sources/cloudflare-d1.md b/docs/user-guide/sources/cloudflare-d1.md index bc9705999..e51f3865f 100644 --- a/docs/user-guide/sources/cloudflare-d1.md +++ b/docs/user-guide/sources/cloudflare-d1.md @@ -56,6 +56,10 @@ Cloudflare answers no queries on a database while its export runs. A small datab Databases are picked by name and looked up on every run, so a database that was deleted and created again under the same name is backed up under its new ID. +::: info Rows read count against the account +Cloudflare bills rows read to the account. Besides the export, the check for large integers reads every table once per backup, and the [Database Explorer](/user-guide/features/database-explorer) counts the rows of every table it lists and reads the rows of each page it shows. On the free plan these count against the daily limit. +::: + ### Large integers SQLite stores integers with 64 bits, but the export of Cloudflare writes them through JavaScript numbers, which hold an integer exactly only up to 2^53 (9,007,199,254,740,991). A larger one lands in the dump rounded, and one near 2^63 comes back from a restore as a floating point number. This is a limit of Cloudflare's export that DBackup cannot work around. It mostly concerns IDs like those of Discord or Twitter stored as `INTEGER`. Store them as `TEXT` to keep them exact. diff --git a/lab/src/seed/cloudflare-d1.ts b/lab/src/seed/cloudflare-d1.ts index eb861e86f..75d71f612 100644 --- a/lab/src/seed/cloudflare-d1.ts +++ b/lab/src/seed/cloudflare-d1.ts @@ -34,7 +34,7 @@ async function ensureLabDatabase(connection: { accountId: string; token: string try { const file = path.join(folder, "shop.sql"); await writeFile(file, readFileSync(path.join(REPO_ROOT, "lab", "datasets", "sqlite.sql"), "utf8")); - await importDatabase(connection, uuid, file, () => undefined); + await importDatabase(connection, uuid, { filePath: file }, () => undefined); log.push(`filled the D1 database ${LAB_D1_DATABASE} with the dataset of SQLite`); } finally { await rm(folder, { recursive: true, force: true }); diff --git a/src/lib/adapters/database/cloudflare-d1/api.ts b/src/lib/adapters/database/cloudflare-d1/api.ts index 684e89407..867a06017 100644 --- a/src/lib/adapters/database/cloudflare-d1/api.ts +++ b/src/lib/adapters/database/cloudflare-d1/api.ts @@ -9,7 +9,7 @@ import type { CloudflareD1Config } from "@/lib/adapters/definitions"; * * Every call goes to the fixed host `api.cloudflare.com` with the API token as a bearer token. The * token never appears in a log line or an error message, and neither does a signed URL, see - * `signed-url.ts`. + * `transfer.ts`. */ const API_BASE = "https://api.cloudflare.com/client/v4/accounts"; @@ -18,8 +18,8 @@ const API_BASE = "https://api.cloudflare.com/client/v4/accounts"; const REQUEST_TIMEOUT_MS = 60_000; /** - * The largest answer of the API this adapter reads. A page of the table browser is the largest - * answer there is, and D1 caps a query result at 50 MB itself. + * The largest answer of the API this adapter reads. D1 caps a query result at 50 MB itself. The + * Database Explorer asks for less, see `BROWSE_RESPONSE_LIMIT` in `browser.ts`. */ const RESPONSE_LIMIT = 64 * 1024 * 1024; @@ -107,10 +107,10 @@ function tokenOf(config: D1Connection): string { return token; } -/** Reads an answer of the API as JSON, at most `RESPONSE_LIMIT` bytes of it. */ -async function readEnvelope(response: Response): Promise | null> { +/** Reads an answer of the API as JSON, at most `limit` bytes of it. */ +async function readEnvelope(response: Response, limit: number): Promise | null> { if (!response.body) return null; - const bytes = await collectCapped(Readable.fromWeb(response.body as WebReadableStream), RESPONSE_LIMIT); + const bytes = await collectCapped(Readable.fromWeb(response.body as WebReadableStream), limit); try { return JSON.parse(bytes.toString("utf-8")) as Envelope; } catch { @@ -143,6 +143,7 @@ export async function d1Request( method: "GET" | "POST" | "DELETE", path: string, body?: unknown, + responseLimit = RESPONSE_LIMIT, ): Promise<{ result: T; resultInfo?: Envelope["result_info"] }> { const url = `${API_BASE}/${accountIdOf(config)}${path}`; let response: Response; @@ -163,7 +164,13 @@ export async function d1Request( throw new AdapterError("cloudflare-d1", operation, `The Cloudflare API ${reason}.`); } - const envelope = await readEnvelope(response); + let envelope: Envelope | null; + try { + envelope = await readEnvelope(response, responseLimit); + } catch (error: unknown) { + const reason = error instanceof Error && error.name === "FileTooLargeError" ? "answered more than DBackup reads of one answer" : "broke off its answer"; + throw new AdapterError("cloudflare-d1", operation, `The Cloudflare API ${reason}.`, { context: { status: response.status, codes: [] } }); + } if (!response.ok || !envelope?.success) { const { message, codes } = describeFailure(response.status, envelope); throw new AdapterError("cloudflare-d1", operation, message, { context: { status: response.status, codes } }); @@ -174,10 +181,13 @@ export async function d1Request( /** How many databases one page of the list holds. The API allows up to 10'000. */ const LIST_PAGE_SIZE = 1000; +/** The most pages the list reads, a bound in case the API keeps answering full pages. */ +const LIST_MAX_PAGES = 100; + /** Every D1 database of the account, across all pages of the list. */ export async function listDatabases(config: D1Connection): Promise { const all: D1Database[] = []; - for (let page = 1; ; page++) { + for (let page = 1; page <= LIST_MAX_PAGES; page++) { const { result, resultInfo } = await d1Request(config, "list", "GET", `/d1/database?page=${page}&per_page=${LIST_PAGE_SIZE}`); const rows = Array.isArray(result) ? result : []; all.push(...rows); @@ -216,8 +226,9 @@ export async function query>( uuid: string, sql: string, params?: unknown[], + responseLimit?: number, ): Promise[]> { - const { result } = await d1Request[]>(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/query`, params ? { sql, params } : { sql }); + const { result } = await d1Request[]>(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/query`, params ? { sql, params } : { sql }, responseLimit); return Array.isArray(result) ? result : []; } @@ -228,7 +239,7 @@ export async function batch(config: D1Connection, uuid: string, statements: { sq } /** Runs SQL through the raw endpoint, rows as arrays with the column names apart. */ -export async function rawQuery(config: D1Connection, uuid: string, sql: string, params?: unknown[]): Promise { - const { result } = await d1Request(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/raw`, params ? { sql, params } : { sql }); +export async function rawQuery(config: D1Connection, uuid: string, sql: string, params?: unknown[], responseLimit?: number): Promise { + const { result } = await d1Request(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/raw`, params ? { sql, params } : { sql }, responseLimit); return Array.isArray(result) ? result : []; } diff --git a/src/lib/adapters/database/cloudflare-d1/browser.ts b/src/lib/adapters/database/cloudflare-d1/browser.ts index 9cccc4270..507f2c75e 100644 --- a/src/lib/adapters/database/cloudflare-d1/browser.ts +++ b/src/lib/adapters/database/cloudflare-d1/browser.ts @@ -18,6 +18,12 @@ const SAFE = "9007199254740991"; /** The most rows one page shows, whatever the caller asks. */ const MAX_PAGE_SIZE = 500; +/** The largest answer a read of the Explorer takes, well below the bound of the backup path. */ +const BROWSE_RESPONSE_LIMIT = 16 * 1024 * 1024; + +/** The bytes of a BLOB a page shows as hex, the rest is only counted. */ +const BLOB_PREVIEW_BYTES = 1024; + const LISTED = `type IN ('table', 'view') AND ${INTERNAL_OBJECT_FILTER}`; export const getTables: NonNullable = async (config, database) => { @@ -63,10 +69,11 @@ async function columnsOf(connection: D1Connection, uuid: string, table: string): })); } -/** A column as the page shows it: a large integer as text, a BLOB as hex. */ +/** A column as the page shows it: a large integer as text, a BLOB as hex, a long one cut with its size. */ function shownValue(column: string): string { const col = quoteIdentifier(column); - return `CASE WHEN typeof(${col}) = 'integer' AND (${col} > ${SAFE} OR ${col} < -${SAFE}) THEN CAST(${col} AS TEXT) WHEN typeof(${col}) = 'blob' THEN 'x''' || hex(${col}) || '''' ELSE ${col} END`; + const blob = `'x''' || hex(substr(${col}, 1, ${BLOB_PREVIEW_BYTES})) || '''' || CASE WHEN length(${col}) > ${BLOB_PREVIEW_BYTES} THEN '... (' || length(${col}) || ' bytes)' ELSE '' END`; + return `CASE WHEN typeof(${col}) = 'integer' AND (${col} > ${SAFE} OR ${col} < -${SAFE}) THEN CAST(${col} AS TEXT) WHEN typeof(${col}) = 'blob' THEN ${blob} ELSE ${col} END`; } export const getTableData: NonNullable = async (config, options) => { @@ -99,7 +106,7 @@ export const getTableData: NonNullable = async const [countResult] = await query<{ n: number }>(connection, db.uuid, `SELECT count(*) AS n${from}`, params.length ? params : undefined); const select = columns.length > 0 ? columns.map((column) => shownValue(column.name)).join(", ") : "*"; - const [data] = await rawQuery(connection, db.uuid, `SELECT ${select}${from}${order} LIMIT ${pageSize} OFFSET ${offset}`, params.length ? params : undefined); + const [data] = await rawQuery(connection, db.uuid, `SELECT ${select}${from}${order} LIMIT ${pageSize} OFFSET ${offset}`, params.length ? params : undefined, BROWSE_RESPONSE_LIMIT); const names = columns.length > 0 ? columns.map((column) => column.name) : data?.results?.columns ?? []; const rows = (data?.results?.rows ?? []).map((values) => Object.fromEntries(names.map((name, index) => [name, values[index] ?? null]))); diff --git a/src/lib/adapters/database/cloudflare-d1/jobs.ts b/src/lib/adapters/database/cloudflare-d1/jobs.ts index 31a2f6b1b..97c98144d 100644 --- a/src/lib/adapters/database/cloudflare-d1/jobs.ts +++ b/src/lib/adapters/database/cloudflare-d1/jobs.ts @@ -1,6 +1,6 @@ import { AdapterError } from "@/lib/logging/errors"; import { d1Request, databaseIdOf, isPermissionRefusal, type D1Connection } from "./api"; -import { downloadTo, md5Of, signedUrlOf, uploadFrom } from "./transfer"; +import { downloadTo, md5Of, signedUrlOf, uploadFrom, type ImportBody } from "./transfer"; /** * The export and the import of D1, both long running work that Cloudflare does on its side and @@ -11,11 +11,14 @@ import { downloadTo, md5Of, signedUrlOf, uploadFrom } from "./transfer"; */ /** The pause between two polls. Cloudflare holds a poll for a moment itself. */ -const POLL_PAUSE_MS = 500; +const POLL_PAUSE_MS = 1_000; /** No export or import runs longer than this. */ const MAX_DURATION_MS = 6 * 60 * 60 * 1000; +/** How often a poll that failed on the way is tried again, with a pause that doubles each time. */ +const POLL_RETRIES = 5; + type Log = (message: string, level?: "info" | "warning" | "error") => void; interface PollAnswer { @@ -36,9 +39,31 @@ interface PollAnswer { const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +/** A line of Cloudflare for the run log, without any URL, which could be a signed one. */ function relay(answer: PollAnswer, log: Log): void { for (const line of answer.messages ?? []) { - if (typeof line === "string" && line.trim()) log(`Cloudflare: ${line.trim()}`); + if (typeof line === "string" && line.trim()) log(`Cloudflare: ${line.trim().replace(/https?:\/\/\S+/gi, "[URL]")}`); + } +} + +/** Whether a failed call is worth another try: the network, a rate limit or a server error, not a refusal. */ +function isTransient(error: unknown): boolean { + if (isPermissionRefusal(error)) return false; + const status = (error as { context?: { status?: number } })?.context?.status; + return status === undefined || status === 429 || status >= 500; +} + +/** One poll, tried again a few times when it fails on the way, since the work at Cloudflare goes on. */ +async function poll(config: D1Connection, operation: string, path: string, body: unknown, log: Log): Promise { + for (let attempt = 0; ; attempt++) { + try { + return (await d1Request(config, operation, "POST", path, body)).result; + } catch (error: unknown) { + if (attempt >= POLL_RETRIES || !isTransient(error)) throw error; + const wait = 2_000 * 2 ** attempt; + log(`Polling the ${operation} failed, trying again in ${wait / 1000} s`, "warning"); + await pause(wait); + } } } @@ -81,7 +106,7 @@ export async function exportDatabase(config: D1Connection, uuid: string, destina throw new AdapterError("cloudflare-d1", "export", `Cloudflare answered the export with the status "${answer.status ?? "none"}" and no bookmark to poll.`); } await pause(POLL_PAUSE_MS); - ({ result: answer } = await d1Request(config, "export", "POST", path, { output_format: "polling", current_bookmark: answer.at_bookmark })); + answer = await poll(config, "export", path, { output_format: "polling", current_bookmark: answer.at_bookmark }, log); relay(answer, log); } @@ -102,24 +127,33 @@ export interface ImportOutcome { } /** - * Imports a SQL dump into one database: start, upload, ingest, poll. + * Whether an import failed in a way that leaves open what Cloudflare did: it was handed over and + * then the polling broke off. Cloudflare may still finish it, so a database made for it stays. + */ +export function importMayContinue(error: unknown): boolean { + return (error as { context?: { importMayContinue?: boolean } })?.context?.importMayContinue === true; +} + +/** + * Imports SQL into one database: start, upload, ingest, poll. The body is a dump file, with SQL + * put ahead of it when the restore replaces a database. * - * D1 runs the whole file in one transaction, so a failed import leaves the database as it was. A - * file Cloudflare already holds (the same MD5) needs no upload, `init` then starts the import + * D1 runs the whole body in one transaction, so a failed import leaves the database as it was. A + * body Cloudflare already holds (the same MD5) needs no upload, `init` then starts the import * itself and answers its state right away. */ -export async function importDatabase(config: D1Connection, uuid: string, filePath: string, log: Log): Promise { +export async function importDatabase(config: D1Connection, uuid: string, body: ImportBody, log: Log): Promise { const id = databaseIdOf(uuid); const path = `/d1/database/${id}/import`; const started = Date.now(); - const etag = await md5Of(filePath); + const etag = await md5Of(body); let { result: answer } = await d1Request(config, "import", "POST", path, { action: "init", etag }); if (answer.upload_url) { const url = signedUrlOf(answer.upload_url, "import"); log(`Uploading the dump to ${url.hostname}`); - await uploadFrom(url, filePath, etag); + await uploadFrom(url, body, etag); if (typeof answer.filename !== "string" || !answer.filename) { throw new AdapterError("cloudflare-d1", "import", "Cloudflare answered the import without a file name."); } @@ -129,16 +163,26 @@ export async function importDatabase(config: D1Connection, uuid: string, filePat } relay(answer, log); - while (answer.status !== "complete" && answer.status !== "error") { - if (Date.now() - started > MAX_DURATION_MS) { - throw new AdapterError("cloudflare-d1", "import", "The import did not finish within 6 hours."); - } - if (!answer.at_bookmark) { - throw new AdapterError("cloudflare-d1", "import", `Cloudflare answered the import with the status "${answer.status ?? "none"}" and no bookmark to poll.`); + try { + while (answer.status !== "complete" && answer.status !== "error") { + if (Date.now() - started > MAX_DURATION_MS) { + throw new AdapterError("cloudflare-d1", "import", "The import did not finish within 6 hours."); + } + if (!answer.at_bookmark) { + throw new AdapterError("cloudflare-d1", "import", `Cloudflare answered the import with the status "${answer.status ?? "none"}" and no bookmark to poll.`); + } + await pause(POLL_PAUSE_MS); + answer = await poll(config, "import", path, { action: "poll", current_bookmark: answer.at_bookmark }, log); + relay(answer, log); } - await pause(POLL_PAUSE_MS); - ({ result: answer } = await d1Request(config, "import", "POST", path, { action: "poll", current_bookmark: answer.at_bookmark })); - relay(answer, log); + } catch (error: unknown) { + const message = error instanceof Error ? error.message.replace(/^\[cloudflare-d1\] [a-z-]+: /, "") : String(error); + throw new AdapterError( + "cloudflare-d1", + "import", + `Lost track of the import, Cloudflare may still finish it: ${message} Check the database in the Cloudflare dashboard before restoring again.`, + { context: { importMayContinue: true } }, + ); } if (answer.status === "error") { diff --git a/src/lib/adapters/database/cloudflare-d1/restore.ts b/src/lib/adapters/database/cloudflare-d1/restore.ts index 581c2f26f..dc87b73e4 100644 --- a/src/lib/adapters/database/cloudflare-d1/restore.ts +++ b/src/lib/adapters/database/cloudflare-d1/restore.ts @@ -1,11 +1,9 @@ -import fs from "fs"; -import { pipeline } from "stream/promises"; import type { DatabaseAdapter } from "@/lib/core/interfaces"; import type { LogLevel, LogType } from "@/lib/core/logs"; import { AdapterError } from "@/lib/logging/errors"; import type { CloudflareD1Config } from "@/lib/adapters/definitions"; import { d1Request, databaseIdOf, findDatabase, listDatabases, query, type D1Connection, type D1Database } from "./api"; -import { importDatabase } from "./jobs"; +import { importDatabase, importMayContinue } from "./jobs"; import { INTERNAL_OBJECT_FILTER, quoteIdentifier } from "./sql"; type OnLog = (msg: string, level?: LogLevel, type?: LogType, details?: string) => void; @@ -20,8 +18,8 @@ type D1RestoreConfig = CloudflareD1Config & D1Connection & { * * Replacing never deletes the database itself. A Worker binds a D1 database by its ID, and a new * database gets a new ID, so the restore drops the objects inside and keeps the database. The drops - * go into the same file as the dump, ahead of it, and D1 runs an import as one transaction: an - * import that fails leaves the target exactly as it was, never half empty. + * go into the same import as the dump, streamed ahead of it, and D1 runs an import as one + * transaction: an import that fails leaves the target exactly as it was, never half empty. * * Before it replaces anything, the restore writes the current Time Travel bookmark of the target * into the log, with the command that goes back to it. @@ -55,15 +53,6 @@ async function dropStatements(config: D1Connection, uuid: string): Promise `DROP ${object.type === "trigger" ? "TRIGGER" : object.type === "view" ? "VIEW" : "TABLE"} IF EXISTS ${quoteIdentifier(object.name)};`); } -/** The dump with the drops ahead of it, in a file beside it. */ -async function withDropsAhead(dumpPath: string, drops: string[]): Promise { - const combined = `${dumpPath}.replace.sql`; - const out = fs.createWriteStream(combined); - out.write(["PRAGMA defer_foreign_keys=TRUE;", ...drops, ""].join("\n")); - await pipeline(fs.createReadStream(dumpPath), out); - return combined; -} - /** Where a new database goes: what the connection says, or like the database the backup came from. */ async function locationOf(config: D1RestoreConfig, originalName: string | undefined, log: Log): Promise> { const wanted = config.newDatabaseLocation ?? "auto"; @@ -100,9 +89,11 @@ export const restoreOne: NonNullable = async (con log(`${targetDbName} does not exist yet`); const created = await createDatabase(connection, targetDbName, originalDbName, log); try { - const outcome = await importDatabase(connection, created.uuid, filePath, log); + const outcome = await importDatabase(connection, created.uuid, { filePath }, log); log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); } catch (error: unknown) { + // Cloudflare may still finish an import it was handed, so that database stays. + if (importMayContinue(error)) throw error; // The database came from this restore and holds nothing, so it does not stay behind. await deleteDatabase(connection, created.uuid).catch(() => log(`Could not delete the empty database ${targetDbName} again, delete it in the Cloudflare dashboard.`, "warning")); throw error; @@ -121,13 +112,9 @@ export const restoreOne: NonNullable = async (con const drops = await dropStatements(connection, uuid); log(drops.length > 0 ? `Replacing ${targetDbName}: dropping its ${drops.length} objects and importing the backup in one transaction` : `${targetDbName} is empty, importing the backup`); - const importPath = drops.length > 0 ? await withDropsAhead(filePath, drops) : filePath; - try { - const outcome = await importDatabase(connection, uuid, importPath, log); - log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); - } finally { - if (importPath !== filePath) await fs.promises.rm(importPath, { force: true }); - } + const prefix = drops.length > 0 ? ["PRAGMA defer_foreign_keys=TRUE;", ...drops, ""].join("\n") : undefined; + const outcome = await importDatabase(connection, uuid, { filePath, prefix }, log); + log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); }; /** diff --git a/src/lib/adapters/database/cloudflare-d1/transfer.ts b/src/lib/adapters/database/cloudflare-d1/transfer.ts index bbfa47323..1de9d6982 100644 --- a/src/lib/adapters/database/cloudflare-d1/transfer.ts +++ b/src/lib/adapters/database/cloudflare-d1/transfer.ts @@ -46,23 +46,43 @@ export async function downloadTo(url: URL, destinationPath: string): Promise { +/** + * What an import uploads: SQL text put ahead of a file, then the file. Streamed from both, so the + * dump is never written a second time to disk. + */ +export interface ImportBody { + filePath: string; + prefix?: string; +} + +function streamOf(body: ImportBody): Readable { + return Readable.from((async function* () { + if (body.prefix) yield Buffer.from(body.prefix, "utf8"); + for await (const chunk of fs.createReadStream(body.filePath)) yield chunk as Buffer; + })()); +} + +async function sizeOf(body: ImportBody): Promise { + return Buffer.byteLength(body.prefix ?? "", "utf8") + (await fs.promises.stat(body.filePath)).size; +} + +/** The MD5 of an import body in hex, the `etag` the import of D1 asks for. */ +export async function md5Of(body: ImportBody): Promise { const hash = createHash("md5"); - await pipeline(fs.createReadStream(filePath), hash); + await pipeline(streamOf(body), hash); return hash.digest("hex"); } /** - * Streams a file to a presigned URL with PUT, as Wrangler does. R2 answers the MD5 of what it got as - * the ETag, which has to be the one the import was started with. + * Streams an import body to a presigned URL with PUT, as Wrangler does. R2 answers the MD5 of what it + * got as the ETag, which has to be the one the import was started with. */ -export async function uploadFrom(url: URL, filePath: string, etag: string): Promise { - const { size } = await fs.promises.stat(filePath); +export async function uploadFrom(url: URL, body: ImportBody, etag: string): Promise { + const size = await sizeOf(body); const response = await fetch(url, { method: "PUT", headers: { "Content-Length": String(size) }, - body: Readable.toWeb(fs.createReadStream(filePath)) as unknown as BodyInit, + body: Readable.toWeb(streamOf(body)) as unknown as BodyInit, duplex: "half", redirect: "error", signal: AbortSignal.timeout(TRANSFER_TIMEOUT_MS), diff --git a/src/lib/adapters/stored-secrets.ts b/src/lib/adapters/stored-secrets.ts index ae60e0550..e7da38d4d 100644 --- a/src/lib/adapters/stored-secrets.ts +++ b/src/lib/adapters/stored-secrets.ts @@ -93,6 +93,8 @@ export function addressOf(adapterId: string, config: Config): Set { const url = schemeAndPort(view[key]); if (url) parts.add(`${key}:${url}`); } + // Cloudflare D1 dials only the fixed API, its account is where the token reaches. + if (adapterId === "cloudflare-d1" && !isEmpty(view.accountId)) parts.add(`account:${text(view.accountId).toLowerCase()}`); return parts; } diff --git a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts index 97209a948..3ba9a9fae 100644 --- a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts +++ b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts @@ -209,3 +209,43 @@ describe("a restore into D1", () => { await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host)).rejects.toThrow(/arrived damaged/); }); }); + +/** An import into a new database `copy` whose polls answer with `pollAnswer`. */ +function importingNew(pollAnswer: (poll: number) => ReturnType) { + let polls = 0; + const fake = fakeCloudflare((call) => { + if (call.method === "PUT") return { headers: { etag: `"${md5(call.uploaded ?? "")}"` } }; + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + if (call.path === `/d1/database/${NEW_ID}/import`) { + const action = (call.body as { action: string }).action; + if (action === "init") return ok({ upload_url: "https://abc.r2.cloudflarestorage.com/up?sig=1", filename: "f.sql" }); + if (action === "ingest") return ok({ status: "active", at_bookmark: "bm" }); + return pollAnswer(++polls); + } + return listing({})(call); + }); + return { ...fake, polls: () => polls }; +} + +describe("a restore that loses track of Cloudflare", () => { + it("polls again after a failure on the way and finishes", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true, advanceTimeDelta: 1_000 }); + try { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const fake = importingNew((poll) => (poll === 1 ? refused(503, 0, "unavailable") : ok({ status: "complete", result: { num_queries: 3 } }))); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host); + expect(fake.polls()).toBe(2); + } finally { + vi.useRealTimers(); + } + }); + + it("keeps a database it created when the import was handed over and the polling broke off, since Cloudflare may still finish it", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + const fake = importingNew(() => refused(400, 7400, "bookmark unknown")); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host)).rejects.toThrow(/may still finish it/); + expect(fake.calls.some((call) => call.method === "DELETE")).toBe(false); + }); +}); diff --git a/tests/unit/adapters/stored-secrets-address.test.ts b/tests/unit/adapters/stored-secrets-address.test.ts index 30a9dfb8e..f93defcda 100644 --- a/tests/unit/adapters/stored-secrets-address.test.ts +++ b/tests/unit/adapters/stored-secrets-address.test.ts @@ -60,6 +60,19 @@ describe("a database source", () => { }); }); +describe("a Cloudflare D1 source", () => { + const account = "0123456789abcdef0123456789abcdef"; + const stored = { accountId: account, token: "cf-token" }; + + it("keeps its token for the same account, also written in capitals", () => { + expect(merge("cloudflare-d1", { accountId: account.toUpperCase(), checkLargeIntegers: false }, stored).token).toBe("cf-token"); + }); + + it("never sends the saved token to another account, which the fixed API host alone does not tell apart", () => { + refused("cloudflare-d1", { accountId: "fedcba9876543210fedcba9876543210" }, stored, LOGIN_FOR_NEW_ADDRESS); + }); +}); + describe("a source over SSH", () => { const stored = { host: "127.0.0.1", port: 3306, password: "db-pw", From d6ddddd65fc496f4a804dafd679b3777dc313e81 Mon Sep 17 00:00:00 2001 From: Manu Date: Tue, 24 Nov 2026 02:52:10 -0600 Subject: [PATCH 5/7] Start no lab services for an end-to-end family that needs none Compose up without a service starts every service of the project, so the family cloud started the whole lab on the runner beside the build of the image. --- e2e/support/global-setup.ts | 2 +- e2e/support/services.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/e2e/support/global-setup.ts b/e2e/support/global-setup.ts index 4fbfec908..4c89d72fd 100644 --- a/e2e/support/global-setup.ts +++ b/e2e/support/global-setup.ts @@ -85,7 +85,7 @@ async function prepare(): Promise { if (trimmed.code !== 0) write(`Could not trim the build cache of the lab host: ${tail(trimmed)}`); } - write(`Starting ${services.join(", ")}`); + if (services.length) write(`Starting ${services.join(", ")}`); const started = await startServices(services); const unavailable = await servicesDown(services); if (started.code !== 0 && Object.keys(unavailable).length === 0) throw new Error(`Starting the services failed:\n${tail(started)}`); diff --git a/e2e/support/services.ts b/e2e/support/services.ts index 3a447c115..ebf988487 100644 --- a/e2e/support/services.ts +++ b/e2e/support/services.ts @@ -32,6 +32,8 @@ async function removeNeverStarted(services: string[]): Promise { /** Starts the services and waits until they are healthy. A service that does not come up shows in the result, it does not throw. */ export async function startServices(services: string[]): Promise { + // `compose up` without a service starts every one, so a family that needs none, like cloud, starts nothing. + if (services.length === 0) return { code: 0, stdout: "", stderr: "" }; // DBackup mounts the folder of SQL Server too, and Docker would make a missing one as root. await prepareMssqlFolder(lab); // --build rebuilds the images of the lab whose files changed, like the customer server, from the cache otherwise. From d71c46c905746cec51663c1c9cacf67dae4763e7 Mon Sep 17 00:00:00 2001 From: Manu Date: Tue, 24 Nov 2026 05:10:18 -0600 Subject: [PATCH 6/7] Guard D1 restores against imports Cloudflare cuts short The export of Cloudflare writes a NUL character of a text raw into the dump, and the import stops reading at it and still reports success, so a restore writes such a character as char(0). Every import now ends with a check table, and a restore that did not run to the end fails instead of reporting success. The check before a backup also names values too long for the import of D1, the code 7500 no longer reads as a missing permission, and the guide gives the measured lock times. --- changelog/unreleased/Skyfay-cloudflare-d1.md | 2 +- docs/user-guide/sources/cloudflare-d1.md | 21 ++-- e2e/tests/cloud.spec.ts | 2 +- lab/src/seed/cloudflare-d1.ts | 2 +- .../adapter/database-form-sections.tsx | 6 +- .../adapters/database/cloudflare-d1/api.ts | 11 +- .../adapters/database/cloudflare-d1/dump.ts | 6 +- .../adapters/database/cloudflare-d1/jobs.ts | 12 +- .../database/cloudflare-d1/large-integers.ts | 72 ------------ .../database/cloudflare-d1/restore.ts | 34 +++++- .../database/cloudflare-d1/transfer.ts | 48 +++++--- .../database/cloudflare-d1/value-check.ts | 103 ++++++++++++++++++ src/lib/adapters/definitions/database.ts | 2 +- .../cloudflare-d1/backup-restore.test.ts | 50 ++++++++- .../database/cloudflare-d1/fake-cloudflare.ts | 21 +++- .../adapters/stored-secrets-address.test.ts | 2 +- 16 files changed, 275 insertions(+), 119 deletions(-) delete mode 100644 src/lib/adapters/database/cloudflare-d1/large-integers.ts create mode 100644 src/lib/adapters/database/cloudflare-d1/value-check.ts diff --git a/changelog/unreleased/Skyfay-cloudflare-d1.md b/changelog/unreleased/Skyfay-cloudflare-d1.md index 1c9d28617..0e46aee73 100644 --- a/changelog/unreleased/Skyfay-cloudflare-d1.md +++ b/changelog/unreleased/Skyfay-cloudflare-d1.md @@ -4,4 +4,4 @@ ### 📝 Documentation -- **Cloudflare D1**: New source guide with the token setup, the lock during an export and the integers the export of Cloudflare rounds. +- **Cloudflare D1**: New source guide with the token setup, the lock during an export and import, and the values the export of Cloudflare cannot carry. diff --git a/docs/user-guide/sources/cloudflare-d1.md b/docs/user-guide/sources/cloudflare-d1.md index e51f3865f..70c124d90 100644 --- a/docs/user-guide/sources/cloudflare-d1.md +++ b/docs/user-guide/sources/cloudflare-d1.md @@ -35,7 +35,7 @@ A `TOKEN` [credential profile](/user-guide/security/credential-profiles) holds t | :--- | :--- | :--- | :--- | | **Account ID** | The 32 hex characters on the overview of the account in the Cloudflare dashboard | - | ✅ | | **Login** | `TOKEN` credential profile with the API token | - | ✅ | -| **Check for large integers** | Warns in the run log when a column holds an integer the export rounds, see [below](#large-integers) | On | ❌ | +| **Check the values before each backup** | Warns in the run log about values Cloudflare's export or import cannot carry, see [below](#values-cloudflare-cannot-carry) | On | ❌ | | **Location of new databases** | Where a restore under a new name creates the database: **Automatic**, a jurisdiction (EU, FedRAMP) or a location hint | Automatic | ❌ | ## Setup Guide @@ -51,20 +51,25 @@ A `TOKEN` [credential profile](/user-guide/security/credential-profiles) holds t Each database is exported by Cloudflare as a SQL dump, the same file `wrangler d1 export` writes. DBackup starts the export, polls it until Cloudflare is done, downloads the dump from R2 and stores it as one `.sql` entry of the backup's archive, unchanged. ::: warning The database is locked during the export -Cloudflare answers no queries on a database while its export runs. A small database takes a second or two, a large one longer. Schedule the backup for a quiet time. +Cloudflare answers queries on a database with errors while its export runs. A small database takes a second or two, one of about 120 MB around 10 seconds. Schedule the backup for a quiet time. Cancelling a run does not stop an export that has started, so the database stays locked until Cloudflare finishes it. ::: Databases are picked by name and looked up on every run, so a database that was deleted and created again under the same name is backed up under its new ID. ::: info Rows read count against the account -Cloudflare bills rows read to the account. Besides the export, the check for large integers reads every table once per backup, and the [Database Explorer](/user-guide/features/database-explorer) counts the rows of every table it lists and reads the rows of each page it shows. On the free plan these count against the daily limit. +Cloudflare bills rows read to the account. Besides the export, the check of the values reads every table once per backup, and the [Database Explorer](/user-guide/features/database-explorer) counts the rows of every table it lists and reads the rows of each page it shows. On the free plan these count against the daily limit. ::: -### Large integers +### Values Cloudflare cannot carry -SQLite stores integers with 64 bits, but the export of Cloudflare writes them through JavaScript numbers, which hold an integer exactly only up to 2^53 (9,007,199,254,740,991). A larger one lands in the dump rounded, and one near 2^63 comes back from a restore as a floating point number. This is a limit of Cloudflare's export that DBackup cannot work around. It mostly concerns IDs like those of Discord or Twitter stored as `INTEGER`. Store them as `TEXT` to keep them exact. +Two kinds of values do not survive Cloudflare's export and import. DBackup takes the export as it is and cannot work around either: -With **Check for large integers** on, DBackup reads every table once before the export and names each column that holds such a value in the run log. The backup runs either way. The check counts against the rows read of the account, so a connection with large databases can turn it off. +- **Integers beyond 2^53** (9,007,199,254,740,991). SQLite stores integers with 64 bits, but the export writes them through JavaScript numbers. A larger one lands in the dump rounded, and one near 2^63 comes back from a restore as a floating point number. It mostly concerns IDs like those of Discord or Twitter stored as `INTEGER`. Store them as `TEXT` to keep them exact. +- **Values too long for one statement.** The export writes each row as one `INSERT`, and the import of D1 takes no statement over 100 KB. A row with a text over about 100 KB or a BLOB over about 50 KB is in the backup, but a restore into D1 fails on it, and the target stays as it was. + +With **Check the values before each backup** on, DBackup reads every table once before the export and names each column that holds such a value in the run log. The backup runs either way. The check counts against the rows read of the account, so a connection with large databases can turn it off. + +A text with a NUL character is restored correctly. The export writes it raw into the dump, where Cloudflare's import would stop reading without an error, so DBackup writes it as `char(0)` on the way to the import. ## Restore @@ -78,7 +83,9 @@ wrangler d1 time-travel restore --bookmark= Restoring under a new name creates a new database. With **Location of new databases** on **Automatic**, it gets the jurisdiction of the database the backup came from while that one still exists, otherwise Cloudflare picks the location. The log names the ID of the new database, which a Worker needs as its `database_id`. -Like the export, an import locks the database while it runs. +Like the export, an import locks the database while it runs. A database of about 120 MB took around 25 seconds to restore under a new name and around 35 seconds to restore over itself. + +After the import DBackup checks that Cloudflare ran all of it, since Cloudflare can report an import complete that stopped early. A restore that did not run to the end fails with a message, and one into a database it created deletes that database again. ## Troubleshooting diff --git a/e2e/tests/cloud.spec.ts b/e2e/tests/cloud.spec.ts index 628cf6c03..16b2f7289 100644 --- a/e2e/tests/cloud.spec.ts +++ b/e2e/tests/cloud.spec.ts @@ -28,7 +28,7 @@ test("[cloud] cloudflare-d1 restores under a new name and over a changed databas try { const connection = { adapterId: "cloudflare-d1", - config: { accountId: account!.accountId, database: "", checkLargeIntegers: true, newDatabaseLocation: "auto" }, + config: { accountId: account!.accountId, database: "", checkValues: true, newDatabaseLocation: "auto" }, primaryCredentialId: await app.credential(`${name} token`, "TOKEN", { token: account!.token }), }; const tested = await app.testConnection(connection); diff --git a/lab/src/seed/cloudflare-d1.ts b/lab/src/seed/cloudflare-d1.ts index 75d71f612..3276944cd 100644 --- a/lab/src/seed/cloudflare-d1.ts +++ b/lab/src/seed/cloudflare-d1.ts @@ -57,7 +57,7 @@ export async function seedCloudflareD1(config: LabConfig, note: Note, log: strin name: "Lab Cloudflare D1", type: "database", adapterId: "cloudflare-d1", - config: { accountId: account.accountId, database: "", checkLargeIntegers: true, newDatabaseLocation: "auto" }, + config: { accountId: account.accountId, database: "", checkValues: true, newDatabaseLocation: "auto" }, primaryCredentialId: token, }, "cloudflare-d1"); } diff --git a/src/components/adapter/database-form-sections.tsx b/src/components/adapter/database-form-sections.tsx index 1453c9459..2e6627a5d 100644 --- a/src/components/adapter/database-form-sections.tsx +++ b/src/components/adapter/database-form-sections.tsx @@ -51,9 +51,9 @@ const SWITCHES: Record = { disableSsl: { title: "Disable SSL", description: "For development databases with a self-signed certificate." }, encrypt: { title: "Encrypt the connection", description: "Required by Azure SQL and most hosted servers." }, trustServerCertificate: { title: "Trust the server certificate", description: "Accepts a self-signed certificate, for development servers." }, - checkLargeIntegers: { - title: "Check for large integers", - description: "Warns in the run log when a column holds an integer beyond 2^53, which the export of Cloudflare rounds. Reads every table once more before the export.", + checkValues: { + title: "Check the values before each backup", + description: "Warns in the run log about integers beyond 2^53, which the export of Cloudflare rounds, and about values too long to import back into D1. Reads every table once more before the export.", }, }; diff --git a/src/lib/adapters/database/cloudflare-d1/api.ts b/src/lib/adapters/database/cloudflare-d1/api.ts index 867a06017..b168b2de5 100644 --- a/src/lib/adapters/database/cloudflare-d1/api.ts +++ b/src/lib/adapters/database/cloudflare-d1/api.ts @@ -64,10 +64,13 @@ interface Envelope { result_info?: { page?: number; per_page?: number; count?: number; total_count?: number }; } -/** Cloudflare's own error codes this adapter turns into a sentence a person can act on. */ +/** + * Cloudflare's own error codes this adapter turns into a sentence a person can act on. D1 answers + * 7500 for every failed statement, a syntax error, a write with a read-only token and a database + * busy with an import alike, so that code says nothing and its message is passed on instead. + */ const AUTHENTICATION_ERROR = 10000; const INVALID_TOKEN = 1000; -const NO_PERMISSION = 7500; /** * Whether an error is a call the API refused for a missing right, as opposed to a request that is @@ -79,7 +82,7 @@ export function isPermissionRefusal(error: unknown): boolean { const context = error instanceof Error ? (error as Error & { context?: { status?: number; codes?: number[] } }).context : undefined; const status = context?.status; const codes = Array.isArray(context?.codes) ? context.codes : []; - return status === 401 || status === 403 || codes.includes(AUTHENTICATION_ERROR) || codes.includes(NO_PERMISSION); + return status === 401 || status === 403 || codes.includes(AUTHENTICATION_ERROR); } /** The account ID of a config, refused unless it has the form Cloudflare gives it. */ @@ -125,7 +128,7 @@ function describeFailure(status: number, envelope: Envelope | null): { if (status === 401 || codes.includes(AUTHENTICATION_ERROR) || codes.includes(INVALID_TOKEN)) { return { codes, message: "Cloudflare refused the API token. Check that it is active, belongs to this account and has the permission D1 Edit." }; } - if (status === 403 || codes.includes(NO_PERMISSION)) { + if (status === 403) { return { codes, message: "The API token is missing a permission for this. It needs D1 Edit." }; } const detail = errors.map((error) => error.message).filter(Boolean).join("; "); diff --git a/src/lib/adapters/database/cloudflare-d1/dump.ts b/src/lib/adapters/database/cloudflare-d1/dump.ts index 52f46fa64..47e607556 100644 --- a/src/lib/adapters/database/cloudflare-d1/dump.ts +++ b/src/lib/adapters/database/cloudflare-d1/dump.ts @@ -4,7 +4,7 @@ import { AdapterError } from "@/lib/logging/errors"; import { formatBytes } from "@/lib/utils"; import { requireDatabase, type D1Connection } from "./api"; import { exportDatabase } from "./jobs"; -import { warnAboutLargeIntegers } from "./large-integers"; +import { warnAboutRiskyValues } from "./value-check"; import type { CloudflareD1Config } from "@/lib/adapters/definitions"; type OnLog = (msg: string, level?: LogLevel, type?: LogType, details?: string) => void; @@ -21,8 +21,8 @@ export const dumpOne: NonNullable = async (config, d const connection = config as CloudflareD1Config & D1Connection; const db = await requireDatabase(connection, dbName, "dump"); - if (connection.checkLargeIntegers !== false) { - await warnAboutLargeIntegers(connection, db.uuid, dbName, log); + if (connection.checkValues !== false) { + await warnAboutRiskyValues(connection, db.uuid, dbName, log); } log(`Exporting ${dbName}. Cloudflare locks the database until the export ends, it serves no queries meanwhile.`); diff --git a/src/lib/adapters/database/cloudflare-d1/jobs.ts b/src/lib/adapters/database/cloudflare-d1/jobs.ts index 97c98144d..f33cd7706 100644 --- a/src/lib/adapters/database/cloudflare-d1/jobs.ts +++ b/src/lib/adapters/database/cloudflare-d1/jobs.ts @@ -1,6 +1,6 @@ import { AdapterError } from "@/lib/logging/errors"; import { d1Request, databaseIdOf, isPermissionRefusal, type D1Connection } from "./api"; -import { downloadTo, md5Of, signedUrlOf, uploadFrom, type ImportBody } from "./transfer"; +import { downloadTo, measure, signedUrlOf, uploadFrom, type ImportBody } from "./transfer"; /** * The export and the import of D1, both long running work that Cloudflare does on its side and @@ -146,14 +146,14 @@ export async function importDatabase(config: D1Connection, uuid: string, body: I const id = databaseIdOf(uuid); const path = `/d1/database/${id}/import`; const started = Date.now(); - const etag = await md5Of(body); + const { etag, size } = await measure(body); let { result: answer } = await d1Request(config, "import", "POST", path, { action: "init", etag }); if (answer.upload_url) { const url = signedUrlOf(answer.upload_url, "import"); log(`Uploading the dump to ${url.hostname}`); - await uploadFrom(url, body, etag); + await uploadFrom(url, body, etag, size); if (typeof answer.filename !== "string" || !answer.filename) { throw new AdapterError("cloudflare-d1", "import", "Cloudflare answered the import without a file name."); } @@ -186,7 +186,11 @@ export async function importDatabase(config: D1Connection, uuid: string, body: I } if (answer.status === "error") { - throw new AdapterError("cloudflare-d1", "import", `The import failed and the database was left as it was: ${answer.error?.trim() || "Cloudflare did not say why."}`); + const reason = answer.error?.trim() || "Cloudflare did not say why."; + const tooLong = /TOOBIG|too long/i.test(reason) + ? " D1 takes no statement over 100 KB, and the export writes each row as one statement, so a row with a text over about 100 KB or a BLOB over about 50 KB cannot be imported back into D1." + : ""; + throw new AdapterError("cloudflare-d1", "import", `The import failed and the database was left as it was: ${reason}${tooLong}`); } return { diff --git a/src/lib/adapters/database/cloudflare-d1/large-integers.ts b/src/lib/adapters/database/cloudflare-d1/large-integers.ts deleted file mode 100644 index e38e4d925..000000000 --- a/src/lib/adapters/database/cloudflare-d1/large-integers.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { query, type D1Connection } from "./api"; -import { quoteIdentifier, userTablesSql } from "./sql"; - -/** - * Integers the export of Cloudflare cannot write exactly. - * - * SQLite stores an integer with 64 bits, but the export of D1 writes every number through a - * JavaScript number, which holds an integer exactly only up to 2^53. A larger one lands in the dump - * rounded (9007199254740993 becomes 9007199254740992), and one near 2^63 comes back from an import - * as a REAL. The fault is Cloudflare's and DBackup takes their export as it is, so before each export - * this check names every column that holds such a value, which makes the run log say what the - * backup will not keep. It reads every table once, which counts against the rows read of the - * account, so a connection can turn it off. - */ - -/** 2^53 - 1, the largest integer a JavaScript number holds exactly. */ -const SAFE = "9007199254740991"; - -type Log = (message: string, level?: "info" | "warning" | "error") => void; - -/** One column with integers beyond the safe range, and how many rows hold one. */ -export interface LargeIntegerColumn { - table: string; - column: string; - rows: number; -} - -/** Every column of every user table that holds an integer beyond ±(2^53 - 1). */ -export async function findLargeIntegers(config: D1Connection, uuid: string): Promise { - const [tables] = await query<{ name: string }>(config, uuid, userTablesSql()); - const found: LargeIntegerColumn[] = []; - - for (const { name: table } of tables?.results ?? []) { - const [columns] = await query<{ name: string }>(config, uuid, "SELECT name FROM pragma_table_info(?)", [table]); - const names = (columns?.results ?? []).map((column) => column.name); - if (names.length === 0) continue; - - // One scan per table: a count per column, by position, so no column name becomes an alias. - const counts = names.map((column, index) => { - const col = quoteIdentifier(column); - return `SUM(typeof(${col}) = 'integer' AND (${col} > ${SAFE} OR ${col} < -${SAFE})) AS c${index}`; - }); - const [result] = await query>(config, uuid, `SELECT ${counts.join(", ")} FROM ${quoteIdentifier(table)}`); - const row = result?.results?.[0] ?? {}; - names.forEach((column, index) => { - const rows = Number(row[`c${index}`] ?? 0); - if (rows > 0) found.push({ table, column, rows }); - }); - } - return found; -} - -/** Runs the check and writes what it found into the run log. Never fails the backup. */ -export async function warnAboutLargeIntegers(config: D1Connection, uuid: string, database: string, log: Log): Promise { - let found: LargeIntegerColumn[]; - try { - found = await findLargeIntegers(config, uuid); - } catch (error: unknown) { - log(`Could not check ${database} for integers the export rounds: ${error instanceof Error ? error.message : String(error)}`, "warning"); - return; - } - if (found.length === 0) return; - - for (const { table, column, rows } of found) { - log(`${database}: table "${table}", column "${column}" holds ${rows === 1 ? "1 integer" : `${rows} integers`} beyond ±2^53.`, "warning"); - } - log( - "The export of Cloudflare D1 rounds integers beyond ±2^53, so the backup holds these values rounded and a restore writes them back rounded. " + - "This is a limit of Cloudflare's export, which DBackup cannot work around. Storing such values as TEXT keeps them exact.", - "warning", - ); -} diff --git a/src/lib/adapters/database/cloudflare-d1/restore.ts b/src/lib/adapters/database/cloudflare-d1/restore.ts index dc87b73e4..7968327b6 100644 --- a/src/lib/adapters/database/cloudflare-d1/restore.ts +++ b/src/lib/adapters/database/cloudflare-d1/restore.ts @@ -1,3 +1,4 @@ +import { randomBytes } from "crypto"; import type { DatabaseAdapter } from "@/lib/core/interfaces"; import type { LogLevel, LogType } from "@/lib/core/logs"; import { AdapterError } from "@/lib/logging/errors"; @@ -79,17 +80,42 @@ async function deleteDatabase(config: D1Connection, uuid: string): Promise await d1Request(config, "restore", "DELETE", `/d1/database/${databaseIdOf(uuid)}`); } +/** + * A table the import creates as its very last statement. Cloudflare reports an import complete + * once it ran what it read, also when it read only part of the file, like up to a NUL byte of an + * older dump. Only when this table exists afterwards did every statement before it run. + */ +function completionMark(): { name: string; suffix: string } { + const name = `_dbackup_restore_${randomBytes(6).toString("hex")}`; + return { name, suffix: `\nCREATE TABLE "${name}" (done INTEGER);\n` }; +} + +/** Whether the import ran up to its mark, which is dropped again. */ +async function ranToTheEnd(config: D1Connection, uuid: string, mark: string, log: Log): Promise { + const [found] = await query<{ n: number }>(config, uuid, "SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ?", [mark]); + if (!Number(found?.results?.[0]?.n)) return false; + await query(config, uuid, `DROP TABLE IF EXISTS ${quoteIdentifier(mark)}`) + .catch(() => log(`Could not drop the check table ${mark} again, drop it by hand.`, "warning")); + return true; +} + +const INCOMPLETE = "Cloudflare reported the import complete, but it did not run all of the backup."; + /** Restores one dump of `dumpOne` into the database named `targetDbName`. */ export const restoreOne: NonNullable = async (config, filePath, targetDbName, _host, onLog, _onProgress, originalDbName) => { const log: Log = (message, level = "info") => onLog?.(message, level); const connection = config as D1RestoreConfig; const existing = await findDatabase(connection, targetDbName); + const mark = completionMark(); if (!existing) { log(`${targetDbName} does not exist yet`); const created = await createDatabase(connection, targetDbName, originalDbName, log); try { - const outcome = await importDatabase(connection, created.uuid, { filePath }, log); + const outcome = await importDatabase(connection, created.uuid, { filePath, suffix: mark.suffix }, log); + if (!(await ranToTheEnd(connection, created.uuid, mark.name, log))) { + throw new AdapterError("cloudflare-d1", "restore", `${INCOMPLETE} The database ${targetDbName} it created is deleted again.`); + } log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); } catch (error: unknown) { // Cloudflare may still finish an import it was handed, so that database stays. @@ -113,7 +139,11 @@ export const restoreOne: NonNullable = async (con log(drops.length > 0 ? `Replacing ${targetDbName}: dropping its ${drops.length} objects and importing the backup in one transaction` : `${targetDbName} is empty, importing the backup`); const prefix = drops.length > 0 ? ["PRAGMA defer_foreign_keys=TRUE;", ...drops, ""].join("\n") : undefined; - const outcome = await importDatabase(connection, uuid, { filePath, prefix }, log); + const outcome = await importDatabase(connection, uuid, { filePath, prefix, suffix: mark.suffix }, log); + if (!(await ranToTheEnd(connection, uuid, mark.name, log))) { + const back = bookmark ? ` Go back to the state before with: wrangler d1 time-travel restore ${targetDbName} --bookmark=${bookmark}` : ""; + throw new AdapterError("cloudflare-d1", "restore", `${INCOMPLETE} ${targetDbName} now holds only part of it.${back}`); + } log(`Restored ${targetDbName} (${outcome.queries ?? "?"} statements)`); }; diff --git a/src/lib/adapters/database/cloudflare-d1/transfer.ts b/src/lib/adapters/database/cloudflare-d1/transfer.ts index 1de9d6982..86b86f29f 100644 --- a/src/lib/adapters/database/cloudflare-d1/transfer.ts +++ b/src/lib/adapters/database/cloudflare-d1/transfer.ts @@ -47,38 +47,60 @@ export async function downloadTo(url: URL, destinationPath: string): Promise { - return Buffer.byteLength(body.prefix ?? "", "utf8") + (await fs.promises.stat(body.filePath)).size; -} - -/** The MD5 of an import body in hex, the `etag` the import of D1 asks for. */ -export async function md5Of(body: ImportBody): Promise { +/** The MD5 in hex, the `etag` the import of D1 asks for, and the size of an import body as it is uploaded. */ +export async function measure(body: ImportBody): Promise<{ etag: string; size: number }> { const hash = createHash("md5"); - await pipeline(streamOf(body), hash); - return hash.digest("hex"); + let size = 0; + for await (const chunk of streamOf(body)) { + hash.update(chunk as Buffer); + size += (chunk as Buffer).length; + } + return { etag: hash.digest("hex"), size }; } /** * Streams an import body to a presigned URL with PUT, as Wrangler does. R2 answers the MD5 of what it * got as the ETag, which has to be the one the import was started with. */ -export async function uploadFrom(url: URL, body: ImportBody, etag: string): Promise { - const size = await sizeOf(body); +export async function uploadFrom(url: URL, body: ImportBody, etag: string, size: number): Promise { const response = await fetch(url, { method: "PUT", headers: { "Content-Length": String(size) }, diff --git a/src/lib/adapters/database/cloudflare-d1/value-check.ts b/src/lib/adapters/database/cloudflare-d1/value-check.ts new file mode 100644 index 000000000..c9e2e02b6 --- /dev/null +++ b/src/lib/adapters/database/cloudflare-d1/value-check.ts @@ -0,0 +1,103 @@ +import { query, type D1Connection } from "./api"; +import { quoteIdentifier, userTablesSql } from "./sql"; + +/** + * Values Cloudflare's export or import cannot carry, named before each backup. + * + * - **Integers beyond 2^53.** SQLite stores an integer with 64 bits, but the export of D1 writes + * every number through a JavaScript number, which holds an integer exactly only up to 2^53. A + * larger one lands in the dump rounded (9007199254740993 becomes 9007199254740992), and one near + * 2^63 comes back from an import as a REAL. + * - **Values too long for one statement.** The export writes each row as one INSERT, and the import + * takes no statement over 100 KB. A row with a text over about 100 KB or a BLOB over about 50 KB + * (it is written as hex) is in the backup, but a restore into D1 fails on it. + * + * The fault is Cloudflare's and DBackup takes their export as it is, so this check makes the run + * log say what the backup will not give back. It reads every table once, which counts against the + * rows read of the account, so a connection can turn it off. + */ + +/** 2^53 - 1, the largest integer a JavaScript number holds exactly. */ +const SAFE = "9007199254740991"; + +/** Bytes of a text in one INSERT that leave room for the rest of the statement below 100 KB. */ +const LONG_TEXT = 95_000; + +/** Bytes of a BLOB whose hex is that long. */ +const LONG_BLOB = LONG_TEXT / 2; + +type Log = (message: string, level?: "info" | "warning" | "error") => void; + +/** One column with values the export or import cannot carry, and how many rows hold one. */ +export interface RiskyColumn { + table: string; + column: string; + largeIntegers: number; + longValues: number; +} + +/** Every column of every user table with an integer beyond ±(2^53 - 1) or a value too long for the import. */ +export async function findRiskyValues(config: D1Connection, uuid: string): Promise { + const [tables] = await query<{ name: string }>(config, uuid, userTablesSql()); + const found: RiskyColumn[] = []; + + for (const { name: table } of tables?.results ?? []) { + const [columns] = await query<{ name: string }>(config, uuid, "SELECT name FROM pragma_table_info(?)", [table]); + const names = (columns?.results ?? []).map((column) => column.name); + if (names.length === 0) continue; + + // One scan per table: two counts per column, by position, so no column name becomes an alias. + const counts = names.flatMap((column, index) => { + const col = quoteIdentifier(column); + return [ + `SUM(typeof(${col}) = 'integer' AND (${col} > ${SAFE} OR ${col} < -${SAFE})) AS i${index}`, + `SUM((typeof(${col}) = 'text' AND length(CAST(${col} AS BLOB)) > ${LONG_TEXT}) OR (typeof(${col}) = 'blob' AND length(${col}) > ${LONG_BLOB})) AS l${index}`, + ]; + }); + const [result] = await query>(config, uuid, `SELECT ${counts.join(", ")} FROM ${quoteIdentifier(table)}`); + const row = result?.results?.[0] ?? {}; + names.forEach((column, index) => { + const largeIntegers = Number(row[`i${index}`] ?? 0); + const longValues = Number(row[`l${index}`] ?? 0); + if (largeIntegers > 0 || longValues > 0) found.push({ table, column, largeIntegers, longValues }); + }); + } + return found; +} + +const rowsOf = (count: number, what: string) => (count === 1 ? `1 ${what}` : `${count} ${what}s`); + +/** Runs the check and writes what it found into the run log. Never fails the backup. */ +export async function warnAboutRiskyValues(config: D1Connection, uuid: string, database: string, log: Log): Promise { + let found: RiskyColumn[]; + try { + found = await findRiskyValues(config, uuid); + } catch (error: unknown) { + log(`Could not check the values of ${database}: ${error instanceof Error ? error.message : String(error)}`, "warning"); + return; + } + + const integers = found.filter((entry) => entry.largeIntegers > 0); + for (const { table, column, largeIntegers } of integers) { + log(`${database}: table "${table}", column "${column}" holds ${rowsOf(largeIntegers, "integer")} beyond ±2^53.`, "warning"); + } + if (integers.length > 0) { + log( + "The export of Cloudflare D1 rounds integers beyond ±2^53, so the backup holds these values rounded and a restore writes them back rounded. " + + "This is a limit of Cloudflare's export, which DBackup cannot work around. Storing such values as TEXT keeps them exact.", + "warning", + ); + } + + const long = found.filter((entry) => entry.longValues > 0); + for (const { table, column, longValues } of long) { + log(`${database}: table "${table}", column "${column}" holds ${rowsOf(longValues, "value")} too long for the import of D1.`, "warning"); + } + if (long.length > 0) { + log( + "The backup holds these rows, but D1 imports no statement over 100 KB and its export writes each row as one, so a restore into D1 fails on them. " + + "A text over about 100 KB or a BLOB over about 50 KB is too long. The dump itself is complete and can be read by sqlite3.", + "warning", + ); + } +} diff --git a/src/lib/adapters/definitions/database.ts b/src/lib/adapters/definitions/database.ts index 93be7e818..da02902df 100644 --- a/src/lib/adapters/definitions/database.ts +++ b/src/lib/adapters/definitions/database.ts @@ -129,7 +129,7 @@ export const CloudflareD1Schema = z.object({ accountId: z.string().trim().regex(/^[0-9a-fA-F]{32}$/, "The account ID is the 32 hex characters shown in the Cloudflare dashboard").describe("Account ID of the Cloudflare account that holds the D1 databases"), token: z.string().optional().describe("API token with the permission D1 Edit"), database: z.union([z.string(), z.array(z.string())]).default(""), - checkLargeIntegers: z.boolean().default(true).describe("Warn before each backup when a column holds an integer beyond 2^53, which the export of Cloudflare rounds. Reads every table once more"), + checkValues: z.boolean().default(true).describe("Warn before each backup about integers beyond 2^53 and values too long to import back into D1. Reads every table once more"), newDatabaseLocation: z.enum(D1_NEW_DATABASE_LOCATIONS).default("auto").describe("Where a restore under a new name creates the database"), }); diff --git a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts index 3ba9a9fae..74365e95f 100644 --- a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts +++ b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts @@ -87,7 +87,7 @@ describe("a backup of a D1 database", () => { } return listing({ shop: DB_ID })(call); }); - await CloudflareD1Adapter.dumpOne!({ ...config, checkLargeIntegers: true }, "shop", path.join(dir, "d.sql"), host); + await CloudflareD1Adapter.dumpOne!({ ...config, checkValues: true }, "shop", path.join(dir, "d.sql"), host); const scan = calls.find((call) => (call.body as { sql?: string })?.sql?.startsWith("SELECT SUM(")); expect((scan?.body as { sql: string }).sql).toContain(`typeof("n") = 'integer'`); expect(calls.some((call) => call.path.endsWith("/export"))).toBe(true); @@ -126,7 +126,7 @@ describe("a restore into D1", () => { const uploaded = calls.find((call) => call.method === "PUT")?.uploaded ?? ""; expect(uploaded.indexOf('DROP TRIGGER IF EXISTS "touch";')).toBeLessThan(uploaded.indexOf('DROP VIEW IF EXISTS "paid";')); expect(uploaded.indexOf('DROP VIEW IF EXISTS "paid";')).toBeLessThan(uploaded.indexOf('DROP TABLE IF EXISTS "orders";')); - expect(uploaded.endsWith(DUMP)).toBe(true); + expect(uploaded).toMatch(new RegExp(`${DUMP.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\nCREATE TABLE "_dbackup_restore_[0-9a-f]{12}" \\(done INTEGER\\);\\n$`)); const init = calls.find((call) => (call.body as { action?: string })?.action === "init"); expect((init?.body as { etag: string }).etag).toBe(md5(uploaded)); expect(calls.some((call) => call.method === "DELETE" || (call.method === "POST" && call.path === "/d1/database"))).toBe(false); @@ -146,7 +146,7 @@ describe("a restore into D1", () => { expect(filter).toContain("NOT LIKE 'sqlite\\_%'"); expect(filter).toContain("NOT LIKE '\\_cf\\_%'"); // An empty database gets the dump as it is. - expect(calls.find((call) => call.method === "PUT")?.uploaded).toBe(DUMP); + expect(calls.find((call) => call.method === "PUT")?.uploaded?.startsWith(DUMP)).toBe(true); }); it("creates a database under a new name in the jurisdiction of the database the backup came from", async () => { @@ -249,3 +249,47 @@ describe("a restore that loses track of Cloudflare", () => { expect(fake.calls.some((call) => call.method === "DELETE")).toBe(false); }); }); + +describe("a dump Cloudflare's import would cut short", () => { + it("writes a NUL character of a text as char(0), since the import stops reading at a raw NUL byte", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, "CREATE TABLE a (x TEXT);\nINSERT INTO \"a\" VALUES('before\u0000after');\nCREATE TABLE b (x);\n"); + const fake = importingNew(() => ok({ status: "complete", result: { num_queries: 4 } })); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host); + const uploaded = fake.calls.find((call) => call.method === "PUT")?.uploaded ?? ""; + expect(uploaded).toContain("VALUES('before'||char(0)||'after');"); + expect(uploaded).not.toContain("\u0000"); + }); + + it("fails a restore into a new database that Cloudflare reports complete but did not run to the end, and deletes that database", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + let polls = 0; + const { calls } = fakeCloudflare((call) => { + if (call.method === "PUT") return { headers: { etag: `"${md5(call.uploaded ?? "")}"` } }; + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + if (call.method === "DELETE") return ok(null); + if (call.path === `/d1/database/${NEW_ID}/import`) { + const action = (call.body as { action: string }).action; + if (action === "init") return ok({ upload_url: "https://abc.r2.cloudflarestorage.com/up?sig=1", filename: "f.sql" }); + polls++; + return ok({ status: "complete", result: { num_queries: 1 } }); + } + return listing({})(call); + }, { importRanToTheEnd: false }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host)).rejects.toThrow(/did not run all of the backup/); + expect(polls).toBe(1); + expect(calls.find((call) => call.method === "DELETE")?.path).toBe(`/d1/database/${NEW_ID}`); + }); + + it("fails a restore over a database that did not run to the end, with the way back to the state before", async () => { + const dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); + fakeCloudflare((call) => { + if (call.path.endsWith("/time_travel/bookmark")) return ok({ bookmark: "bm-before" }); + if (call.path.endsWith("/query")) return ok([{ success: true, results: [] }]); + return importing(DB_ID)(call) ?? listing({ shop: DB_ID })(call); + }, { importRanToTheEnd: false }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host)).rejects.toThrow(/holds only part of it.*--bookmark=bm-before/); + }); +}); diff --git a/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts b/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts index 1a6d03cb3..131ae3f8c 100644 --- a/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts +++ b/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts @@ -39,7 +39,22 @@ async function textOf(body: unknown): Promise { return undefined; } -export function fakeCloudflare(route: (call: Call) => Answer | undefined) { +/** The table a restore makes its import end with, which it looks for and drops afterwards. */ +const MARK = "_dbackup_restore_"; + +/** + * Answers the check of a restore whether its import ran to the end: found, unless + * `importRanToTheEnd` is false, like an import Cloudflare cut short. + */ +function completionCheck(call: Call, ranToTheEnd: boolean): Answer | undefined { + const body = call.body as { sql?: string; params?: unknown[] } | undefined; + if (!body?.sql) return undefined; + if (String(body.params?.[0] ?? "").startsWith(MARK)) return ok([{ success: true, results: [{ n: ranToTheEnd ? 1 : 0 }] }]); + if (body.sql.startsWith(`DROP TABLE IF EXISTS "${MARK}`)) return ok([{ success: true, results: [] }]); + return undefined; +} + +export function fakeCloudflare(route: (call: Call) => Answer | undefined, options: { importRanToTheEnd?: boolean } = {}) { const calls: Call[] = []; const fetchMock = vi.fn(async (input: string | URL, init: RequestInit = {}) => { const url = String(input); @@ -54,7 +69,7 @@ export function fakeCloudflare(route: (call: Call) => Answer | undefined) { }; if (call.method === "PUT") call.uploaded = await textOf(init.body); calls.push(call); - const answer = route(call) ?? { status: 404, json: { success: false, errors: [{ code: 7404, message: `no route for ${call.method} ${call.path}` }] } }; + const answer = completionCheck(call, options.importRanToTheEnd !== false) ?? route(call) ?? { status: 404, json: { success: false, errors: [{ code: 7404, message: `no route for ${call.method} ${call.path}` }] } }; const body = answer.text ?? JSON.stringify(answer.json ?? {}); return new Response(body, { status: answer.status ?? 200, headers: answer.headers }); }); @@ -62,4 +77,4 @@ export function fakeCloudflare(route: (call: Call) => Answer | undefined) { return { calls, fetchMock }; } -export const config = { accountId: ACCOUNT, token: "test-token", database: "", checkLargeIntegers: false, newDatabaseLocation: "auto" }; +export const config = { accountId: ACCOUNT, token: "test-token", database: "", checkValues: false, newDatabaseLocation: "auto" }; diff --git a/tests/unit/adapters/stored-secrets-address.test.ts b/tests/unit/adapters/stored-secrets-address.test.ts index f93defcda..75c5bb44c 100644 --- a/tests/unit/adapters/stored-secrets-address.test.ts +++ b/tests/unit/adapters/stored-secrets-address.test.ts @@ -65,7 +65,7 @@ describe("a Cloudflare D1 source", () => { const stored = { accountId: account, token: "cf-token" }; it("keeps its token for the same account, also written in capitals", () => { - expect(merge("cloudflare-d1", { accountId: account.toUpperCase(), checkLargeIntegers: false }, stored).token).toBe("cf-token"); + expect(merge("cloudflare-d1", { accountId: account.toUpperCase(), checkValues: false }, stored).token).toBe("cf-token"); }); it("never sends the saved token to another account, which the fixed API host alone does not tell apart", () => { From 0b40977695c9fc976e8e49e975e294f3ca069a53 Mon Sep 17 00:00:00 2001 From: Manu Date: Tue, 24 Nov 2026 06:17:09 -0600 Subject: [PATCH 7/7] Cover the failure paths of the Cloudflare D1 adapter with tests Tests for an API that times out, breaks off or answers too much, the bound of the database list, ping and the job form, the value check, failed exports, downloads and uploads, where a restore puts a new database, the order of the drops and the restore of earlier versions. The unused batch and getDatabase helpers are gone. --- .../adapters/database/cloudflare-d1/api.ts | 12 -- .../cloudflare-d1/api-failures.test.ts | 106 ++++++++++ .../backup-restore-paths.test.ts | 194 ++++++++++++++++++ .../cloudflare-d1/backup-restore.test.ts | 27 +-- .../database/cloudflare-d1/browser.test.ts | 58 ++++++ .../database/cloudflare-d1/fake-cloudflare.ts | 23 +++ .../cloudflare-d1/value-check.test.ts | 51 +++++ .../components/connection-summary.test.ts | 6 + 8 files changed, 442 insertions(+), 35 deletions(-) create mode 100644 tests/unit/adapters/database/cloudflare-d1/api-failures.test.ts create mode 100644 tests/unit/adapters/database/cloudflare-d1/backup-restore-paths.test.ts create mode 100644 tests/unit/adapters/database/cloudflare-d1/value-check.test.ts diff --git a/src/lib/adapters/database/cloudflare-d1/api.ts b/src/lib/adapters/database/cloudflare-d1/api.ts index b168b2de5..201fc93ad 100644 --- a/src/lib/adapters/database/cloudflare-d1/api.ts +++ b/src/lib/adapters/database/cloudflare-d1/api.ts @@ -217,12 +217,6 @@ export async function requireDatabase(config: D1Connection, name: string, operat return { ...db, uuid: databaseIdOf(db.uuid) }; } -/** The details of one database, its size among them. */ -export async function getDatabase(config: D1Connection, uuid: string): Promise { - const { result } = await d1Request(config, "get", "GET", `/d1/database/${databaseIdOf(uuid)}`); - return result; -} - /** Runs SQL through the query endpoint, rows as objects. */ export async function query>( config: D1Connection, @@ -235,12 +229,6 @@ export async function query>( return Array.isArray(result) ? result : []; } -/** Runs several statements as one batch, which D1 runs in one transaction. */ -export async function batch(config: D1Connection, uuid: string, statements: { sql: string; params?: unknown[] }[]): Promise { - const { result } = await d1Request(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/query`, { batch: statements }); - return Array.isArray(result) ? result : []; -} - /** Runs SQL through the raw endpoint, rows as arrays with the column names apart. */ export async function rawQuery(config: D1Connection, uuid: string, sql: string, params?: unknown[], responseLimit?: number): Promise { const { result } = await d1Request(config, "query", "POST", `/d1/database/${databaseIdOf(uuid)}/raw`, params ? { sql, params } : { sql }, responseLimit); diff --git a/tests/unit/adapters/database/cloudflare-d1/api-failures.test.ts b/tests/unit/adapters/database/cloudflare-d1/api-failures.test.ts new file mode 100644 index 000000000..0096e8367 --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/api-failures.test.ts @@ -0,0 +1,106 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { databaseIdOf, findDatabase, isPermissionRefusal, listDatabases, rawQuery } from "@/lib/adapters/database/cloudflare-d1/api"; +import { CloudflareD1Adapter } from "@/lib/adapters/database/cloudflare-d1"; +import { DB_ID, config, fakeCloudflare, ok, refused } from "./fake-cloudflare"; + +const host = {} as never; + +afterEach(() => vi.unstubAllGlobals()); + +/** `fetch` replaced by a function that throws or answers as given. */ +function stubFetch(answer: () => Promise) { + vi.stubGlobal("fetch", vi.fn(answer)); +} + +describe("a Cloudflare API that does not answer as expected", () => { + it("says the API did not answer in time, without anything of the request", async () => { + stubFetch(async () => { + throw Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" }); + }); + await expect(listDatabases(config)).rejects.toThrow("The Cloudflare API did not answer in time."); + }); + + it("says the API could not be reached when the network fails", async () => { + stubFetch(async () => { + throw new TypeError("fetch failed"); + }); + await expect(listDatabases(config)).rejects.toThrow("The Cloudflare API could not be reached."); + }); + + it("names the status of an answer that is no JSON, like the HTML page of a gateway error", async () => { + stubFetch(async () => new Response("Bad gateway", { status: 502 })); + const error = await listDatabases(config).catch((e: Error) => e); + expect((error as Error).message).toMatch(/Cloudflare answered 502\.$/); + // A server error is worth another try, a refusal is not. + expect(isPermissionRefusal(error)).toBe(false); + }); + + it("stops reading an answer larger than the call allows, during the transfer", async () => { + stubFetch(async () => new Response(JSON.stringify({ success: true, result: [{ results: { columns: ["x"], rows: [["y".repeat(5_000)]] } }] }))); + await expect(rawQuery(config, DB_ID, "SELECT x FROM t", undefined, 1_000)).rejects.toThrow("answered more than DBackup reads of one answer"); + }); + + it("names a refused permission apart from a refused token", async () => { + fakeCloudflare(() => refused(403, 9109, "Unauthorized to access requested resource")); + const error = await listDatabases(config).catch((e: Error) => e); + expect((error as Error).message).toMatch(/missing a permission/); + expect(isPermissionRefusal(error)).toBe(true); + }); + + it("passes on the words of a failed statement, since D1 answers 7500 for any SQL error", async () => { + fakeCloudflare(() => refused(400, 7500, "no such table: missing: SQLITE_ERROR")); + const error = await rawQuery(config, DB_ID, "SELECT * FROM missing").catch((e: Error) => e); + expect((error as Error).message).toMatch(/400: no such table: missing/); + expect(isPermissionRefusal(error)).toBe(false); + }); + + it("refuses a database ID from an answer that is no UUID before it becomes part of a URL", () => { + expect(() => databaseIdOf("../../tokens")).toThrow(/not a UUID/); + expect(() => databaseIdOf(undefined)).toThrow(/not a UUID/); + expect(databaseIdOf(DB_ID.toUpperCase())).toBe(DB_ID); + }); +}); + +describe("the list of databases", () => { + it("stops after a bound of pages when the API keeps answering full pages", async () => { + const full = Array.from({ length: 1000 }, (_, i) => ({ uuid: DB_ID, name: `db-${i}` })); + const { calls } = fakeCloudflare(() => ok(full)); + expect(await listDatabases(config)).toHaveLength(100_000); + expect(calls).toHaveLength(100); + }); + + it("finds a name the wide filter of the API hides behind a full page in the whole list", async () => { + const decoys = Array.from({ length: 100 }, (_, i) => ({ uuid: DB_ID, name: `shop-${i}` })); + fakeCloudflare((call) => (call.path.includes("name=shop") ? ok(decoys) : ok([...decoys, { uuid: DB_ID, name: "shop" }]))); + expect((await findDatabase(config, "shop"))?.name).toBe("shop"); + }); + + it("leaves out entries without a name or an ID", async () => { + fakeCloudflare(() => ok([{ uuid: DB_ID, name: "shop" }, { name: "no-id" }, { uuid: DB_ID }])); + expect((await listDatabases(config)).map((db) => db.name)).toEqual(["shop"]); + }); +}); + +describe("the health check and the job form of a D1 connection", () => { + it("pings with one small page of the list", async () => { + const { calls } = fakeCloudflare(() => ok([])); + expect(await CloudflareD1Adapter.ping!(config, host)).toEqual({ success: true, message: "Cloudflare D1 answered" }); + expect(calls.map((call) => call.path)).toEqual(["/d1/database?per_page=10"]); + }); + + it("reports a ping the token fails, without the prefix of the adapter error", async () => { + fakeCloudflare(() => refused(401, 10000, "Authentication error")); + const answer = await CloudflareD1Adapter.ping!(config, host); + expect(answer.success).toBe(false); + expect(answer.message).toMatch(/^Cloudflare refused the API token/); + }); + + it("offers the names of the databases sorted, for the job form", async () => { + fakeCloudflare(() => ok([{ uuid: DB_ID, name: "web" }, { uuid: DB_ID, name: "api" }])); + expect(await CloudflareD1Adapter.getDatabases!(config, host)).toEqual(["api", "web"]); + }); + + it("runs in DBackup itself whatever the config holds, since nothing reaches a host of the customer", () => { + expect(CloudflareD1Adapter.transport!({ connectionMode: "ssh", sshHost: "elsewhere" })).toEqual({ kind: "direct" }); + }); +}); diff --git a/tests/unit/adapters/database/cloudflare-d1/backup-restore-paths.test.ts b/tests/unit/adapters/database/cloudflare-d1/backup-restore-paths.test.ts new file mode 100644 index 000000000..4c1666ea6 --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/backup-restore-paths.test.ts @@ -0,0 +1,194 @@ +import fs from "fs"; +import os from "os"; +import path from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { CloudflareD1Adapter } from "@/lib/adapters/database/cloudflare-d1"; +import { DB_ID, DUMP, NEW_ID, R2_URL, config, fakeCloudflare, importing, listing, ok, refused, type Answer, type Call } from "./fake-cloudflare"; + +const host = {} as never; + +let dir: string; +let dumpPath: string; +beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "d1-paths-")); + dumpPath = path.join(dir, "dump.sql"); + fs.writeFileSync(dumpPath, DUMP); +}); +afterEach(() => { + vi.unstubAllGlobals(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const target = () => path.join(dir, `${Math.random().toString(36).slice(2)}.sql`); + +describe("a backup that does not go as planned", () => { + /** The database shop, whose export answers `exportAnswer` per poll and whose dump R2 serves by `download`. */ + function exporting(exportAnswer: (poll: number) => Answer, download: () => Answer = () => ({ text: DUMP })) { + let polls = 0; + return fakeCloudflare((call) => { + if (call.url === R2_URL) return download(); + if (call.path.endsWith("/export")) return exportAnswer(++polls); + return listing({ shop: DB_ID })(call); + }); + } + const complete = () => ok({ status: "complete", result: { signed_url: R2_URL } }); + + it("fails on an export that came back empty, rather than storing an empty backup", async () => { + exporting(complete, () => ({ text: "" })); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", target(), host)).rejects.toThrow(/export of shop is empty/); + }); + + it("fails when R2 refuses the download of the export", async () => { + exporting(complete, () => ({ status: 403, text: "AccessDenied" })); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", target(), host)).rejects.toThrow(/Downloading the export from abc123\.r2\.cloudflarestorage\.com failed with 403/); + }); + + it("fails an export that Cloudflare reports running but gives no bookmark to poll", async () => { + exporting(() => ok({ status: "active" })); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", target(), host)).rejects.toThrow(/status "active" and no bookmark to poll/); + }); + + it("passes on why Cloudflare failed an export", async () => { + exporting(() => ok({ status: "error", error: "storage unavailable" })); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", target(), host)).rejects.toThrow("The export failed: storage unavailable"); + }); + + it("does not poll again when Cloudflare refuses a poll, since only a failure on the way is worth another try", async () => { + const fake = exporting((poll) => (poll === 1 ? ok({ status: "active", at_bookmark: "bm" }) : refused(400, 7400, "bookmark unknown"))); + await expect(CloudflareD1Adapter.dumpOne!(config, "shop", target(), host)).rejects.toThrow(/bookmark unknown/); + expect(fake.calls.filter((call) => call.path.endsWith("/export"))).toHaveLength(2); + }); + + it("reads no table before the export when the connection turns the check off", async () => { + const fake = exporting(complete); + await CloudflareD1Adapter.dumpOne!({ ...config, checkValues: false }, "shop", target(), host); + expect(fake.calls.some((call) => call.path.endsWith("/query"))).toBe(false); + }); + + it("still answers the dump of earlier versions for a job of one database, and refuses one of several", async () => { + exporting(complete); + expect(await CloudflareD1Adapter.dump({ ...config, database: "shop" }, target(), host)).toMatchObject({ success: true, size: Buffer.byteLength(DUMP) }); + expect(await CloudflareD1Adapter.dump({ ...config, database: "shop,other" }, target(), host)) + .toMatchObject({ success: false, error: expect.stringMatching(/exactly one database/) }); + }); +}); + +describe("where a restore puts a new database", () => { + function creating(names: Record, jurisdiction?: string) { + return fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + return importing(NEW_ID)(call) ?? listing(names, jurisdiction)(call); + }); + } + const created = (calls: Call[]) => calls.find((call) => call.method === "POST" && call.path === "/d1/database")?.body; + + it("puts it into the jurisdiction the connection names", async () => { + const { calls } = creating({}); + await CloudflareD1Adapter.restoreOne!({ ...config, newDatabaseLocation: "eu" }, dumpPath, "copy", host); + expect(created(calls)).toEqual({ name: "copy", jurisdiction: "eu" }); + }); + + it("lets Cloudflare pick when the original has no jurisdiction", async () => { + const { calls } = creating({ shop: DB_ID }); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host, undefined, undefined, "shop"); + expect(created(calls)).toEqual({ name: "copy" }); + }); + + it("lets Cloudflare pick when the original is gone from the account", async () => { + const { calls } = creating({}); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host, undefined, undefined, "shop"); + expect(created(calls)).toEqual({ name: "copy" }); + }); + + it("throws why the import failed, also when the empty database cannot be deleted again", async () => { + fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + if (call.method === "DELETE") return refused(500, 0, "try later"); + return importing(NEW_ID, { status: "error", error: "syntax error" })(call) ?? listing({})(call); + }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host)).rejects.toThrow(/left as it was: syntax error/); + }); + + it("keeps the database when Cloudflare answers the import as running without a bookmark to follow", async () => { + const { calls } = fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + if (call.method === "DELETE") return ok(null); + return importing(NEW_ID, { status: "active" })(call) ?? listing({})(call); + }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host)).rejects.toThrow(/may still finish it/); + expect(calls.some((call) => call.method === "DELETE")).toBe(false); + }); + + it("explains a statement over 100 KB, which D1 cannot import", async () => { + fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + if (call.method === "DELETE") return ok(null); + return importing(NEW_ID, { status: "error", error: "statement too long: SQLITE_TOOBIG" })(call) ?? listing({})(call); + }); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "copy", host)).rejects.toThrow(/D1 takes no statement over 100 KB/); + }); +}); + +describe("a restore over an existing database", () => { + /** The database shop holding `objects`, with `extra` answering first. */ + function replacing(objects: { type: string; name: string; sql: string }[], extra?: (call: Call) => Answer | undefined) { + return fakeCloudflare((call) => { + const answer = extra?.(call); + if (answer) return answer; + if (call.path.endsWith("/time_travel/bookmark")) return ok({ bookmark: "bm" }); + if (call.path.endsWith("/query")) return ok([{ success: true, results: objects }]); + return importing(DB_ID)(call) ?? listing({ shop: DB_ID })(call); + }); + } + + it("drops a virtual table after the views and before the tables, which takes its shadow tables along", async () => { + const { calls } = replacing([ + { type: "table", name: "notes_fts_data", sql: "CREATE TABLE 'notes_fts_data'(id INTEGER PRIMARY KEY, block BLOB)" }, + { type: "table", name: "notes_fts", sql: "CREATE VIRTUAL TABLE notes_fts USING fts5(body)" }, + { type: "view", name: "recent", sql: "CREATE VIEW recent AS SELECT 1" }, + ]); + await CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host); + const uploaded = calls.find((call) => call.method === "PUT")?.uploaded ?? ""; + const order = ['DROP VIEW IF EXISTS "recent"', 'DROP TABLE IF EXISTS "notes_fts";', 'DROP TABLE IF EXISTS "notes_fts_data"'].map((line) => uploaded.indexOf(line)); + expect(order.every((at) => at >= 0)).toBe(true); + expect([...order].sort((a, b) => a - b)).toEqual(order); + }); + + it("still restores when Cloudflare answers no Time Travel bookmark", async () => { + replacing([], (call) => (call.path.endsWith("/time_travel/bookmark") ? refused(404, 0, "not found") : undefined)); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host)).resolves.toBeUndefined(); + }); + + it("succeeds when only dropping the check table fails, which a person can do by hand", async () => { + replacing([], (call) => ((call.body as { sql?: string } | undefined)?.sql?.startsWith('DROP TABLE IF EXISTS "_dbackup_restore_') ? refused(500, 0, "busy") : undefined)); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host)).resolves.toBeUndefined(); + }); + + it("fails when R2 refuses the upload of the dump, before Cloudflare imports anything", async () => { + const { calls } = replacing([], (call) => (call.method === "PUT" ? { status: 500, text: "InternalError" } : undefined)); + await expect(CloudflareD1Adapter.restoreOne!(config, dumpPath, "shop", host)).rejects.toThrow(/Uploading the dump to abc\.r2\.cloudflarestorage\.com failed with 500/); + expect(calls.some((call) => (call.body as { action?: string } | undefined)?.action === "ingest")).toBe(false); + }); +}); + +describe("before and around a restore", () => { + it("checks before it starts that the token reaches the account", async () => { + fakeCloudflare(() => refused(401, 10000, "Authentication error")); + await expect(CloudflareD1Adapter.prepareRestore!(config, ["shop"], host)).rejects.toThrow(/refused the API token/); + }); + + it("still restores a single dump through the restore of earlier versions, into the database the mapping picks", async () => { + const { calls } = fakeCloudflare((call) => { + if (call.method === "POST" && call.path === "/d1/database") return ok({ uuid: NEW_ID, name: "copy" }); + return importing(NEW_ID)(call) ?? listing({ shop: DB_ID })(call); + }); + const databaseMapping = [{ originalName: "shop", targetName: "copy", selected: true }]; + expect(await CloudflareD1Adapter.restore({ ...config, databaseMapping }, dumpPath, host)).toMatchObject({ success: true }); + expect(calls.find((call) => call.method === "POST" && call.path === "/d1/database")?.body).toMatchObject({ name: "copy" }); + }); + + it("answers a restore of earlier versions without a target as failed, instead of guessing one", async () => { + fakeCloudflare(() => ok([])); + expect(await CloudflareD1Adapter.restore(config, dumpPath, host)).toMatchObject({ success: false, error: expect.stringMatching(/No target database/) }); + }); +}); diff --git a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts index 74365e95f..19e9ad70e 100644 --- a/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts +++ b/tests/unit/adapters/database/cloudflare-d1/backup-restore.test.ts @@ -1,14 +1,11 @@ import fs from "fs"; import os from "os"; import path from "path"; -import { createHash } from "crypto"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { CloudflareD1Adapter } from "@/lib/adapters/database/cloudflare-d1"; -import { DB_ID, NEW_ID, R2_URL, config, fakeCloudflare, ok, refused, type Call } from "./fake-cloudflare"; +import { DB_ID, DUMP, NEW_ID, R2_URL, config, fakeCloudflare, importing, listing, md5, ok, refused } from "./fake-cloudflare"; const host = {} as never; -const DUMP = "PRAGMA defer_foreign_keys=TRUE;\nCREATE TABLE t (id INTEGER PRIMARY KEY);\nINSERT INTO \"t\" VALUES(1);\n"; -const md5 = (text: string) => createHash("md5").update(text).digest("hex"); let dir: string; beforeEach(() => { @@ -19,12 +16,6 @@ afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); -/** The list of databases the account answers. */ -const listing = (names: Record, jurisdiction?: string) => (call: Call) => - call.method === "GET" && call.path.startsWith("/d1/database?") - ? ok(Object.entries(names).map(([name, uuid]) => ({ name, uuid, jurisdiction: jurisdiction ?? null }))) - : undefined; - describe("a backup of a D1 database", () => { it("exports by polling until Cloudflare is done and stores its dump unchanged", async () => { let polls = 0; @@ -75,7 +66,7 @@ describe("a backup of a D1 database", () => { await expect(CloudflareD1Adapter.dumpOne!(config, "shop", path.join(dir, "d.sql"), host)).rejects.toThrow(/no D1 database named "shop"/); }); - it("checks for large integers first when the connection asks for it, and backs up anyway", async () => { + it("checks the values first when the connection asks for it, and backs up anyway when it finds some", async () => { const { calls } = fakeCloudflare((call) => { if (call.url === R2_URL) return { text: DUMP }; if (call.path.endsWith("/export")) return ok({ status: "complete", result: { signed_url: R2_URL } }); @@ -83,7 +74,8 @@ describe("a backup of a D1 database", () => { const sql = (call.body as { sql: string }).sql; if (sql.startsWith("SELECT name FROM sqlite_master")) return ok([{ success: true, results: [{ name: "big" }] }]); if (sql.includes("pragma_table_info")) return ok([{ success: true, results: [{ name: "n" }] }]); - return ok([{ success: true, results: [{ c0: 1 }] }]); + // One integer beyond 2^53 and one value too long in the column n. + return ok([{ success: true, results: [{ i0: 1, l0: 1 }] }]); } return listing({ shop: DB_ID })(call); }); @@ -94,17 +86,6 @@ describe("a backup of a D1 database", () => { }); }); -/** Answers the import flow, keeping what was uploaded. */ -function importing(uuid: string, outcome: Record = { status: "complete", result: { num_queries: 3 } }) { - return (call: Call) => { - if (call.method === "PUT") return { headers: { etag: `"${md5(call.uploaded ?? "")}"` } }; - if (call.path !== `/d1/database/${uuid}/import`) return undefined; - const action = (call.body as { action: string }).action; - if (action === "init") return ok({ upload_url: "https://abc.r2.cloudflarestorage.com/up?sig=1", filename: "f.sql" }); - return ok(outcome); - }; -} - describe("a restore into D1", () => { it("replaces an existing database in one import: drops ahead of the dump, the database and its ID kept", async () => { const dumpPath = path.join(dir, "dump.sql"); diff --git a/tests/unit/adapters/database/cloudflare-d1/browser.test.ts b/tests/unit/adapters/database/cloudflare-d1/browser.test.ts index 1a22c7a64..0bea4ffb9 100644 --- a/tests/unit/adapters/database/cloudflare-d1/browser.test.ts +++ b/tests/unit/adapters/database/cloudflare-d1/browser.test.ts @@ -56,4 +56,62 @@ describe("the Database Explorer of a D1 database", () => { await CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "orders", page: 1, pageSize: 1_000_000 }, host); expect((calls.find((call) => call.path.endsWith("/raw"))?.body as { sql: string }).sql).toContain("LIMIT 500 OFFSET 0"); }); + + it("shows a BLOB cut to its first KB with its size, so a page stays small", async () => { + const { calls } = shop(); + await CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "orders", page: 1, pageSize: 10 }, host); + const sql = (calls.find((call) => call.path.endsWith("/raw"))?.body as { sql: string }).sql; + expect(sql).toContain(`hex(substr("note", 1, 1024))`); + expect(sql).toContain(`' bytes)'`); + }); + + it("matches a search exactly, at the start or at the end, as the page asks", async () => { + const { calls } = shop(); + for (const matchMode of ["equals", "starts", "ends"] as const) { + await CloudflareD1Adapter.getTableData!(config, { database: "shop", table: "orders", page: 1, pageSize: 10, search: "abc", searchColumn: "note", matchMode }, host); + } + const searches = calls.filter((call) => call.path.endsWith("/raw")).map((call) => call.body as { sql: string; params: unknown[] }); + expect(searches.map((search) => search.params)).toEqual([["abc"], ["abc%"], ["%abc"]]); + expect(searches[0].sql).toContain(`WHERE "note" = ?`); + expect(searches[1].sql).toContain(`WHERE "note" LIKE ?`); + }); +}); + +describe("the tables of a D1 database", () => { + /** A database with the objects given, whose counts answer `counts`. */ + function objects(list: { name: string; type: string }[], counts: () => ReturnType) { + return fakeCloudflare((call) => { + if (call.method === "GET") return ok([{ uuid: DB_ID, name: "shop" }]); + const { sql } = call.body as { sql: string }; + if (sql.startsWith("SELECT name, type FROM sqlite_master")) return ok([{ success: true, results: list }]); + if (sql.includes("UNION ALL") || sql.startsWith("SELECT count(*) AS n FROM")) return counts(); + return undefined; + }); + } + + it("lists tables with their rows and views without, leaving out what belongs to SQLite and Cloudflare", async () => { + const { calls } = objects( + [{ name: "customers", type: "table" }, { name: "open_orders", type: "view" }, { name: "orders", type: "table" }], + () => ok([{ success: true, results: [{ n: 3 }, { n: 7 }] }]), + ); + expect(await CloudflareD1Adapter.getTables!(config, "shop", host)).toEqual([ + { name: "customers", type: "table", rowCount: 3 }, + { name: "open_orders", type: "view" }, + { name: "orders", type: "table", rowCount: 7 }, + ]); + const listed = (calls.find((call) => (call.body as { sql?: string } | undefined)?.sql?.startsWith("SELECT name, type"))?.body as { sql: string }).sql; + expect(listed).toContain("NOT LIKE 'sqlite\\_%'"); + expect(listed).toContain("NOT LIKE '\\_cf\\_%'"); + }); + + it("still lists the tables when counting their rows fails, like on a virtual table", async () => { + objects([{ name: "notes_fts", type: "table" }], () => ({ status: 400, json: { success: false, errors: [{ code: 7500, message: "no such module: fts5" }] } })); + expect(await CloudflareD1Adapter.getTables!(config, "shop", host)).toEqual([{ name: "notes_fts", type: "table" }]); + }); + + it("asks for no counts in a database of views only", async () => { + const { calls } = objects([{ name: "v", type: "view" }], () => ok([])); + expect(await CloudflareD1Adapter.getTables!(config, "shop", host)).toEqual([{ name: "v", type: "view" }]); + expect(calls.filter((call) => call.method === "POST")).toHaveLength(1); + }); }); diff --git a/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts b/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts index 131ae3f8c..8f77000a4 100644 --- a/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts +++ b/tests/unit/adapters/database/cloudflare-d1/fake-cloudflare.ts @@ -1,3 +1,4 @@ +import { createHash } from "crypto"; import { vi } from "vitest"; /** @@ -78,3 +79,25 @@ export function fakeCloudflare(route: (call: Call) => Answer | undefined, option } export const config = { accountId: ACCOUNT, token: "test-token", database: "", checkValues: false, newDatabaseLocation: "auto" }; + +/** A dump as Cloudflare's export writes it. */ +export const DUMP = "PRAGMA defer_foreign_keys=TRUE;\nCREATE TABLE t (id INTEGER PRIMARY KEY);\nINSERT INTO \"t\" VALUES(1);\n"; + +export const md5 = (text: string) => createHash("md5").update(text).digest("hex"); + +/** The list of databases the account answers, by name and ID. */ +export const listing = (names: Record, jurisdiction?: string) => (call: Call): Answer | undefined => + call.method === "GET" && call.path.startsWith("/d1/database?") + ? ok(Object.entries(names).map(([name, uuid]) => ({ name, uuid, jurisdiction: jurisdiction ?? null }))) + : undefined; + +/** Answers the import flow into one database, the upload with the MD5 of what arrived. */ +export function importing(uuid: string, outcome: Record = { status: "complete", result: { num_queries: 3 } }) { + return (call: Call): Answer | undefined => { + if (call.method === "PUT") return { headers: { etag: `"${md5(call.uploaded ?? "")}"` } }; + if (call.path !== `/d1/database/${uuid}/import`) return undefined; + const action = (call.body as { action: string }).action; + if (action === "init") return ok({ upload_url: "https://abc.r2.cloudflarestorage.com/up?sig=1", filename: "f.sql" }); + return ok(outcome); + }; +} diff --git a/tests/unit/adapters/database/cloudflare-d1/value-check.test.ts b/tests/unit/adapters/database/cloudflare-d1/value-check.test.ts new file mode 100644 index 000000000..bda56d4fe --- /dev/null +++ b/tests/unit/adapters/database/cloudflare-d1/value-check.test.ts @@ -0,0 +1,51 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { findRiskyValues, warnAboutRiskyValues } from "@/lib/adapters/database/cloudflare-d1/value-check"; +import { DB_ID, config, fakeCloudflare, ok, refused, type Call } from "./fake-cloudflare"; + +afterEach(() => vi.unstubAllGlobals()); + +/** A database whose tables, columns and counts the test names. */ +function database(tables: Record, counts: Record>) { + return fakeCloudflare((call: Call) => { + const { sql, params } = call.body as { sql: string; params?: unknown[] }; + if (sql.startsWith("SELECT name FROM sqlite_master")) return ok([{ success: true, results: Object.keys(tables).map((name) => ({ name })) }]); + if (sql.includes("pragma_table_info")) return ok([{ success: true, results: (tables[String(params?.[0])] ?? []).map((name) => ({ name })) }]); + const table = Object.keys(tables).find((name) => sql.endsWith(`FROM "${name}"`)); + return ok([{ success: true, results: [counts[table ?? ""] ?? {}] }]); + }); +} + +describe("the check of the values before a backup", () => { + it("names each column with integers the export rounds or values too long for the import", async () => { + database( + { users: ["id", "discord_id", "bio"], files: ["id", "content"] }, + { users: { i0: 0, l0: 0, i1: 3, l1: 0, i2: 0, l2: null }, files: { i0: 0, l0: 0, i1: 0, l1: 2 } }, + ); + expect(await findRiskyValues(config, DB_ID)).toEqual([ + { table: "users", column: "discord_id", largeIntegers: 3, longValues: 0 }, + { table: "files", column: "content", largeIntegers: 0, longValues: 2 }, + ]); + }); + + it("reads each table once, with both counts for every column, and quotes every name", async () => { + const { calls } = database({ 'odd "name"': ["a b"] }, {}); + await findRiskyValues(config, DB_ID); + const scans = calls.map((call) => (call.body as { sql: string }).sql).filter((sql) => sql.startsWith("SELECT SUM(")); + expect(scans).toHaveLength(1); + expect(scans[0]).toContain(`typeof("a b") = 'integer'`); + expect(scans[0]).toContain(`length(CAST("a b" AS BLOB)) > 95000`); + expect(scans[0]).toContain(`length("a b") > 47500`); + expect(scans[0]).toMatch(/FROM "odd ""name"""$/); + }); + + it("skips a table without columns it can read, instead of sending an empty SELECT", async () => { + const { calls } = database({ empty: [] }, {}); + expect(await findRiskyValues(config, DB_ID)).toEqual([]); + expect(calls.some((call) => (call.body as { sql: string }).sql.startsWith("SELECT SUM("))).toBe(false); + }); + + it("never fails the backup when the check itself fails", async () => { + fakeCloudflare(() => refused(500, 7500, "internal error")); + await expect(warnAboutRiskyValues(config, DB_ID, "shop", () => undefined)).resolves.toBeUndefined(); + }); +}); diff --git a/tests/unit/components/connection-summary.test.ts b/tests/unit/components/connection-summary.test.ts index b261d44ef..cb9686394 100644 --- a/tests/unit/components/connection-summary.test.ts +++ b/tests/unit/components/connection-summary.test.ts @@ -8,6 +8,12 @@ describe("connectionAddress", () => { expect(connectionAddress("postgres", config({ host: "db-01.internal", port: 5432, user: "backup" }))).toBe("db-01.internal:5432"); }); + it("names the start of the Cloudflare account of D1, which has no host, and never its token", () => { + const address = connectionAddress("cloudflare-d1", config({ accountId: "0123456789abcdef0123456789abcdef", token: "secret-token" })); + expect(address).toBe("Account 01234567..."); + expect(connectionAddress("cloudflare-d1", config({ token: "secret-token" }))).toBeNull(); + }); + it("adds the database index for Redis", () => { expect(connectionAddress("redis", config({ host: "cache-01", port: 6379 }))).toBe("cache-01:6379, DB 0"); });