@protobase/cli 0.30.0 → 0.30.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/supabase/import-state.js +4 -2
- package/dist/supabase/in-parallel.js +16 -0
- package/dist/supabase/project-files.js +12 -0
- package/dist/supabase/register.js +13 -2
- package/dist/supabase/report.js +1 -0
- package/dist/supabase/run.js +17 -3
- package/dist/supabase/storage-copy.js +48 -0
- package/dist/supabase/storage-download.js +10 -0
- package/dist/supabase/storage-objects.js +16 -0
- package/dist/supabase/storage-phase.js +42 -0
- package/dist/supabase/storage-report.js +18 -0
- package/dist/supabase/storage-sizes.js +22 -0
- package/dist/supabase/storage-verify.js +16 -0
- package/package.json +6 -6
- package/skills/protobase/SKILL.md +1 -0
- package/skills/protobase/references/reference/cli.md +3 -0
- package/skills/protobase/references/reference/supabase-storage.md +54 -0
package/dist/cli/package.js
CHANGED
|
@@ -5,7 +5,8 @@ import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
5
5
|
/**
|
|
6
6
|
* The project's folder for an import in progress, kept out of git: the data dump, which holds the users' password
|
|
7
7
|
* hashes and every row, and the replay of Vault's secrets, pgmq's queues and pg_cron's jobs, which holds the secrets'
|
|
8
|
-
* values, each readable by its owner only until the load deletes it; the manifest; and the report
|
|
8
|
+
* values, each readable by its owner only until the load deletes it; the manifest; the report; and the report of the
|
|
9
|
+
* copy of Storage's bytes.
|
|
9
10
|
*/
|
|
10
11
|
const importState = (projectDir) => {
|
|
11
12
|
const dir = path.join(projectDir, "supabase-import");
|
|
@@ -14,7 +15,8 @@ const importState = (projectDir) => {
|
|
|
14
15
|
replay: path.join(dir, "replay.sql"),
|
|
15
16
|
load: path.join(dir, "load.sql"),
|
|
16
17
|
manifest: path.join(dir, "import.json"),
|
|
17
|
-
report: path.join(dir, "report.md")
|
|
18
|
+
report: path.join(dir, "report.md"),
|
|
19
|
+
storage: path.join(dir, "storage.md")
|
|
18
20
|
};
|
|
19
21
|
return {
|
|
20
22
|
dir,
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/supabase/in-parallel.ts
|
|
2
|
+
/** `run` over `items`, at most `limit` at a time, giving the results in the items' order. */
|
|
3
|
+
const inParallel = async (items, limit, run) => {
|
|
4
|
+
const results = new Array(items.length);
|
|
5
|
+
let next = 0;
|
|
6
|
+
const worker = async () => {
|
|
7
|
+
while (next < items.length) {
|
|
8
|
+
const index = next++;
|
|
9
|
+
results[index] = await run(items[index]);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
13
|
+
return results;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { inParallel };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { importProjectFile } from "../project/import-project-file.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
//#region src/supabase/project-files.ts
|
|
5
|
+
/** `files` of the project's protobase.config.ts, or none when it has no such file or no `files`. */
|
|
6
|
+
const projectFilesOptions = async (projectDir) => {
|
|
7
|
+
const file = path.join(projectDir, "protobase.config.ts");
|
|
8
|
+
if (!existsSync(file)) return {};
|
|
9
|
+
return (await importProjectFile(file)).default?.files ?? {};
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { projectFilesOptions };
|
|
@@ -8,8 +8,14 @@ const variable = (name) => {
|
|
|
8
8
|
if (!value) throw new Error(`Environment variable ${name} is not set`);
|
|
9
9
|
return value;
|
|
10
10
|
};
|
|
11
|
+
const projectUrl = (text) => {
|
|
12
|
+
const url = URL.canParse(text) ? new URL(text) : void 0;
|
|
13
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:") throw new Error("--storage-url is not a URL; write it like https://<ref>.supabase.co");
|
|
14
|
+
if (url.username || url.password) throw new Error("--storage-url must not hold credentials; put the secret key in the variable --storage-key-env names");
|
|
15
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
16
|
+
};
|
|
11
17
|
const registerImport = (program) => {
|
|
12
|
-
program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config and writes supabase-import/report.md").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").action(async (source, opts) => {
|
|
18
|
+
program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config and writes supabase-import/report.md. With --storage-url, the second run, or any later one, copies Storage's files into the app's file provider").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").option("--storage-url <url>", "the Supabase project's URL, such as https://<ref>.supabase.co, to copy Storage's files from").option("--storage-key-env <variable>", "environment variable holding the Supabase project's secret key, for --storage-url", "SUPABASE_SERVICE_ROLE_KEY").option("--yes", "copy Storage's files even when they exceed the file provider's max_bytes", false).action(async (source, opts) => {
|
|
13
19
|
if (source && opts.sourceEnv) throw new Error("Pass either a connection string or --source-env, not both");
|
|
14
20
|
const projectDir = process.cwd();
|
|
15
21
|
loadNearestEnvFile(projectDir);
|
|
@@ -18,7 +24,12 @@ const registerImport = (program) => {
|
|
|
18
24
|
targetUrl: variable(opts.env),
|
|
19
25
|
projectDir,
|
|
20
26
|
migrationsDir: path.resolve(opts.dir),
|
|
21
|
-
configDir: path.resolve(opts.config)
|
|
27
|
+
configDir: path.resolve(opts.config),
|
|
28
|
+
storage: opts.storageUrl ? {
|
|
29
|
+
url: projectUrl(opts.storageUrl),
|
|
30
|
+
key: variable(opts.storageKeyEnv)
|
|
31
|
+
} : void 0,
|
|
32
|
+
yes: opts.yes
|
|
22
33
|
}, out);
|
|
23
34
|
});
|
|
24
35
|
};
|
package/dist/supabase/report.js
CHANGED
|
@@ -66,6 +66,7 @@ const importReport = (manifest, doctor, jobsWired, live) => [
|
|
|
66
66
|
section("Extensions left out", "The project's database does not let the importing role create these, so the migration does not. Replace what the app uses them for, or have the database's administrator make them available.", manifest.extensionsLeftOut.map((extension) => `${extension.name} (schema ${extension.schema})`)),
|
|
67
67
|
section("To convert", "Supabase dropped timescaledb, plv8, plls and plcoffee after Postgres 15. The migration restores a hypertable as a plain table without its rows, and leaves out a function in a language the project's database does not have, as comments; convert each.", conversions(manifest)),
|
|
68
68
|
section("HTTP triggers", "These triggers call out over HTTP with pg_net or a database webhook, and the project's database has no pg_net. The migration keeps a trigger calling the app's own function, but nothing sends; it leaves out a webhook's. Move each call to a Protobase event subscription or job.", manifest.httpSent ? [] : manifest.httpTriggers.map(trigger)),
|
|
69
|
+
"## Storage files\n\nThe load restored Storage's buckets and objects with their policies, but a dump holds no file bytes. Run `protobase import supabase --storage-url https://<ref>.supabase.co` with the project's secret key in `SUPABASE_SERVICE_ROLE_KEY` to copy them into the app's Storage file provider; it writes what it copied to `supabase-import/storage.md`, and a rerun copies what is left.\n",
|
|
69
70
|
section("Edge Functions", "`supabase/functions` holds these, which the import does not convert.", manifest.functions),
|
|
70
71
|
`## Indexes the scan guard needs\n\n${doctor === void 0 ? "No resources were scaffolded, so `protobase doctor` had nothing to check." : `\`protobase doctor\` on the scaffolded config. The API refuses a read that no index serves; add each index it names in a migration of its own.\n\n\`\`\`\n${doctor.trimEnd()}\n\`\`\``}\n`
|
|
71
72
|
].join("\n");
|
package/dist/supabase/run.js
CHANGED
|
@@ -1,18 +1,32 @@
|
|
|
1
1
|
import { importState } from "./import-state.js";
|
|
2
2
|
import { runDumpPhase } from "./dump-phase.js";
|
|
3
3
|
import { runLoadPhase } from "./load-phase.js";
|
|
4
|
+
import { runStorageCopy } from "./storage-phase.js";
|
|
4
5
|
//#region src/supabase/run.ts
|
|
5
6
|
/**
|
|
6
7
|
* `protobase import supabase`, in two runs with the project's migrations between them: the first dumps the source
|
|
7
8
|
* and writes the schema migration, the second loads the data into the migrated database. Which run this is follows
|
|
8
|
-
* from `supabase-import/`: a manifest with its data dump is an import waiting for its load.
|
|
9
|
+
* from `supabase-import/`: a manifest with its data dump is an import waiting for its load. Given a Supabase project
|
|
10
|
+
* to copy Storage's bytes from, the second run copies them after the load, and a later run copies what is left.
|
|
9
11
|
*/
|
|
10
12
|
const runSupabaseImport = async (options, out) => {
|
|
11
13
|
const state = importState(options.projectDir);
|
|
12
14
|
const pending = state.hasManifest() && state.hasData();
|
|
15
|
+
const copyStorage = (source) => runStorageCopy({
|
|
16
|
+
targetUrl: options.targetUrl,
|
|
17
|
+
projectDir: options.projectDir,
|
|
18
|
+
source,
|
|
19
|
+
yes: options.yes
|
|
20
|
+
}, out);
|
|
13
21
|
if (pending && options.sourceUrl) throw new Error("An import is waiting in supabase-import/: apply its migration and run `protobase import supabase` without a source to load it, or remove supabase-import/ to start over");
|
|
14
|
-
if (pending)
|
|
15
|
-
|
|
22
|
+
if (pending) {
|
|
23
|
+
await runLoadPhase(options, out);
|
|
24
|
+
if (options.storage) await copyStorage(options.storage);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (state.hasManifest() && options.storage && !options.sourceUrl) return copyStorage(options.storage);
|
|
28
|
+
if (state.hasManifest()) throw new Error(`This project imported a Supabase database already (see ${state.report}); pass --storage-url to copy Storage's files, or remove supabase-import/ to import again`);
|
|
29
|
+
if (options.storage) throw new Error("--storage-url copies Storage's files once the data is loaded; dump the database first");
|
|
16
30
|
if (!options.sourceUrl) throw new Error("Pass the Supabase database's connection string, or --source-env <VARIABLE>: the session pooler's or the direct one, for the postgres role");
|
|
17
31
|
return runDumpPhase({
|
|
18
32
|
...options,
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { copyFault } from "./storage-verify.js";
|
|
2
|
+
import { HttpProblem, objectKey } from "@protobase/server";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
//#region src/supabase/storage-copy.ts
|
|
5
|
+
const measured = () => {
|
|
6
|
+
const hash = createHash("md5");
|
|
7
|
+
let size = 0;
|
|
8
|
+
return {
|
|
9
|
+
stream: new TransformStream({ transform: (chunk, controller) => {
|
|
10
|
+
size += chunk.length;
|
|
11
|
+
hash.update(chunk);
|
|
12
|
+
controller.enqueue(chunk);
|
|
13
|
+
} }),
|
|
14
|
+
result: () => ({
|
|
15
|
+
size,
|
|
16
|
+
md5: hash.digest("hex")
|
|
17
|
+
})
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
const copyBytes = async (download, store, object, key) => {
|
|
21
|
+
const response = await download(object.bucket, object.name);
|
|
22
|
+
if (!response.ok || !response.body) {
|
|
23
|
+
await response.body?.cancel();
|
|
24
|
+
return `Supabase answered ${response.status}`;
|
|
25
|
+
}
|
|
26
|
+
const measure = measured();
|
|
27
|
+
await store.put(key, response.body.pipeThrough(measure.stream));
|
|
28
|
+
const fault = copyFault(object, measure.result(), (await store.head(key))?.size);
|
|
29
|
+
if (fault) await store.delete(key);
|
|
30
|
+
return fault;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Copies one object's bytes into `store`, at the key `/storage/v1` serves the object's row from. A download Supabase
|
|
34
|
+
* refuses, a copy that does not match, or a store that is full fails this object only; anything else, such as the
|
|
35
|
+
* connection failing, stops the copy, which a rerun resumes.
|
|
36
|
+
*/
|
|
37
|
+
const copyObject = async (download, store, object) => {
|
|
38
|
+
const key = await objectKey(object.bucket, object.name, object.version);
|
|
39
|
+
return {
|
|
40
|
+
object,
|
|
41
|
+
fault: await copyBytes(download, store, object, key).catch((error) => {
|
|
42
|
+
if (error instanceof HttpProblem && error.status === 507) return "the file provider is full";
|
|
43
|
+
throw error;
|
|
44
|
+
})
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
//#endregion
|
|
48
|
+
export { copyObject };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/supabase/storage-download.ts
|
|
2
|
+
/** Where Supabase's Storage API serves an object's bytes to the secret key: each segment of the name encoded. */
|
|
3
|
+
const objectUrl = (projectUrl, bucket, name) => `${projectUrl.replace(/\/+$/, "")}/storage/v1/object/authenticated/${encodeURIComponent(bucket)}/${name.split("/").map(encodeURIComponent).join("/")}`;
|
|
4
|
+
/** Downloads from the Supabase project `source` with its secret key, which goes in the request's headers only. */
|
|
5
|
+
const supabaseDownload = (source) => (bucket, name) => fetch(objectUrl(source.url, bucket, name), { headers: {
|
|
6
|
+
apikey: source.key,
|
|
7
|
+
authorization: `Bearer ${source.key}`
|
|
8
|
+
} });
|
|
9
|
+
//#endregion
|
|
10
|
+
export { objectUrl, supabaseDownload };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/supabase/storage-objects.ts
|
|
2
|
+
/** Every object the load restored to `storage.objects`, by bucket and name. */
|
|
3
|
+
const storageObjects = async (sql) => {
|
|
4
|
+
return (await sql`
|
|
5
|
+
select bucket_id as bucket, name, version, metadata->>'size' as size, metadata->>'eTag' as etag
|
|
6
|
+
from storage.objects where name is not null order by bucket_id, name
|
|
7
|
+
`).map((row) => ({
|
|
8
|
+
bucket: row.bucket,
|
|
9
|
+
name: row.name,
|
|
10
|
+
version: row.version,
|
|
11
|
+
size: row.size === null ? void 0 : Number(row.size),
|
|
12
|
+
eTag: row.etag ?? void 0
|
|
13
|
+
}));
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { storageObjects };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { connect } from "../db/connect.js";
|
|
2
|
+
import { importState } from "./import-state.js";
|
|
3
|
+
import { inParallel } from "./in-parallel.js";
|
|
4
|
+
import { projectFilesOptions } from "./project-files.js";
|
|
5
|
+
import { alreadyCopied } from "./storage-verify.js";
|
|
6
|
+
import { copyObject } from "./storage-copy.js";
|
|
7
|
+
import { supabaseDownload } from "./storage-download.js";
|
|
8
|
+
import { storageObjects } from "./storage-objects.js";
|
|
9
|
+
import { bucketLines, megabytes, objectCount, overQuota, totalBytes } from "./storage-sizes.js";
|
|
10
|
+
import { storageReport } from "./storage-report.js";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { writeFile } from "node:fs/promises";
|
|
13
|
+
import { objectKey, storageProvider, storeUsage } from "@protobase/server";
|
|
14
|
+
//#region src/supabase/storage-phase.ts
|
|
15
|
+
/** Objects copied at once: enough to keep a connection busy, few enough for any host. */
|
|
16
|
+
const parallel = 4;
|
|
17
|
+
/**
|
|
18
|
+
* Copies the bytes of every object the load restored to `storage.objects` from the Supabase project into the app's
|
|
19
|
+
* Storage file provider, streaming each, and checks each copy. Objects already in the provider are skipped, so a rerun
|
|
20
|
+
* resumes; a failed object does not stop the rest, and the run fails at the end, listing them in the storage report.
|
|
21
|
+
* It stops first when the bytes to copy exceed the provider's quota, unless `yes`.
|
|
22
|
+
*/
|
|
23
|
+
const runStorageCopy = async (options, out, download = supabaseDownload(options.source)) => {
|
|
24
|
+
const state = importState(options.projectDir);
|
|
25
|
+
const { name, provider } = storageProvider(await projectFilesOptions(options.projectDir), process.env);
|
|
26
|
+
const sql = connect(options.targetUrl);
|
|
27
|
+
const objects = await storageObjects(sql).finally(() => sql.end());
|
|
28
|
+
out(`Supabase Storage holds ${objectCount(objects.length)}, ${megabytes(totalBytes(objects))}:\n${bucketLines(objects).join("")}`);
|
|
29
|
+
const stored = await inParallel(objects, parallel, async (object) => (await provider.store.head(await objectKey(object.bucket, object.name, object.version)))?.size);
|
|
30
|
+
const todo = objects.filter((object, index) => !alreadyCopied(object, stored[index]));
|
|
31
|
+
const over = provider.maxBytes === void 0 ? void 0 : overQuota(totalBytes(todo), (await storeUsage(provider.store)).bytes, provider.maxBytes);
|
|
32
|
+
if (over && !options.yes) throw new Error(over);
|
|
33
|
+
out(`copying ${objectCount(todo.length)}, ${megabytes(totalBytes(todo))}, into the file provider ${name}; ${objects.length - todo.length} are there already\n`);
|
|
34
|
+
const outcomes = await inParallel(todo, parallel, (object) => copyObject(download, provider.store, object));
|
|
35
|
+
const failed = outcomes.filter((outcome) => outcome.fault);
|
|
36
|
+
await writeFile(state.storage, storageReport(options.source.url, name, objects, outcomes), { mode: 384 });
|
|
37
|
+
const report = path.relative(options.projectDir, state.storage);
|
|
38
|
+
if (failed.length > 0) throw new Error(`${failed.length} of ${objectCount(todo.length)} did not copy, listed in ${report}; run the command again to retry them`);
|
|
39
|
+
out(`copied ${objectCount(todo.length)}; each byte count matches the source. Wrote ${report}\n`);
|
|
40
|
+
};
|
|
41
|
+
//#endregion
|
|
42
|
+
export { runStorageCopy };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { megabytes, objectCount, totalBytes } from "./storage-sizes.js";
|
|
2
|
+
//#region src/supabase/storage-report.ts
|
|
3
|
+
const cell = (text) => text.replaceAll("|", "\\|").replaceAll("\n", " ");
|
|
4
|
+
/**
|
|
5
|
+
* `supabase-import/storage.md`: what the last copy of Storage's bytes did, from the Supabase project at `url`, into the
|
|
6
|
+
* file provider `provider`, and each object that failed, which the next run tries again.
|
|
7
|
+
*/
|
|
8
|
+
const storageReport = (url, provider, objects, outcomes) => {
|
|
9
|
+
const failed = outcomes.filter((outcome) => outcome.fault);
|
|
10
|
+
const copied = outcomes.length - failed.length;
|
|
11
|
+
return [
|
|
12
|
+
"# Supabase Storage copy\n",
|
|
13
|
+
`From ${url} into the file provider \`${provider}\`: ${objectCount(objects.length)}, ${megabytes(totalBytes(objects))}. This run copied ${copied}, found ${objects.length - outcomes.length} copied already and failed ${failed.length}. Each copy's byte count matched the size Supabase recorded, and its MD5 the object's ETag where that is one.\n`,
|
|
14
|
+
failed.length === 0 ? "## Failed\n\nNone.\n" : `## Failed\n\nRun \`protobase import supabase --storage-url ${url}\` again to retry these.\n\n| Bucket | Object | Why |\n| --- | --- | --- |\n${failed.map(({ object, fault }) => `| ${cell(object.bucket)} | ${cell(object.name)} | ${cell(fault)} |`).join("\n")}\n`
|
|
15
|
+
].join("\n");
|
|
16
|
+
};
|
|
17
|
+
//#endregion
|
|
18
|
+
export { storageReport };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/supabase/storage-sizes.ts
|
|
2
|
+
/** Bytes in decimal megabytes, as `max_bytes=500MB` counts them. */
|
|
3
|
+
const megabytes = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;
|
|
4
|
+
const objectCount = (count) => `${count} object${count === 1 ? "" : "s"}`;
|
|
5
|
+
/** The bytes Supabase recorded for `objects`; an object without a recorded size counts as empty. */
|
|
6
|
+
const totalBytes = (objects) => objects.reduce((sum, object) => sum + (object.size ?? 0), 0);
|
|
7
|
+
/** Each bucket's objects and bytes, as lines to print before the copy. */
|
|
8
|
+
const bucketLines = (objects) => {
|
|
9
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
10
|
+
for (const object of objects) buckets.set(object.bucket, [...buckets.get(object.bucket) ?? [], object]);
|
|
11
|
+
return [...buckets].map(([bucket, inBucket]) => ` ${bucket}: ${objectCount(inBucket.length)}, ${megabytes(totalBytes(inBucket))}\n`);
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Why the copy stops before it starts, or `undefined` when it fits: the bytes still to copy (`todo`) and those the
|
|
15
|
+
* store holds already (`used`) together exceed the provider's `maxBytes`.
|
|
16
|
+
*/
|
|
17
|
+
const overQuota = (todo, used, maxBytes) => {
|
|
18
|
+
if (maxBytes === void 0 || todo + used <= maxBytes) return void 0;
|
|
19
|
+
return `The objects still to copy take ${megabytes(todo)} and the file provider holds ${megabytes(used)} already, more than its ${megabytes(maxBytes)}: pick a larger plan or raise its max_bytes, or pass --yes to copy until it is full`;
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
export { bucketLines, megabytes, objectCount, overQuota, totalBytes };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/supabase/storage-verify.ts
|
|
2
|
+
const md5ETag = /^"?([0-9a-f]{32})"?$/i;
|
|
3
|
+
/** Whether a copy already in the store, of `storedSize` bytes, is the object's, so a rerun skips it. */
|
|
4
|
+
const alreadyCopied = (object, storedSize) => storedSize !== void 0 && (object.size === void 0 || storedSize === object.size);
|
|
5
|
+
/**
|
|
6
|
+
* What is wrong with a copy, or `undefined` when it is the object's: the bytes read (`read`, with their MD5) and those
|
|
7
|
+
* the store holds after the write (`stored`) must be the size Supabase recorded, and the MD5 its ETag where that is one.
|
|
8
|
+
*/
|
|
9
|
+
const copyFault = (object, read, stored) => {
|
|
10
|
+
if (object.size !== void 0 && read.size !== object.size) return `read ${read.size} bytes, Supabase recorded ${object.size}`;
|
|
11
|
+
if (stored !== read.size) return `the file provider holds ${stored ?? "no"} bytes of the ${read.size} written`;
|
|
12
|
+
const etag = object.eTag?.match(md5ETag)?.[1]?.toLowerCase();
|
|
13
|
+
if (etag && etag !== read.md5) return `MD5 ${read.md5} differs from the ETag ${etag}`;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { alreadyCopied, copyFault };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.30.
|
|
3
|
+
"version": "0.30.2",
|
|
4
4
|
"description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -36,11 +36,11 @@
|
|
|
36
36
|
"@better-auth/core": "^1.7.7",
|
|
37
37
|
"@hono/node-server": "^2.1.3",
|
|
38
38
|
"@hono/vite-dev-server": "^0.26.1",
|
|
39
|
-
"@protobase/layout": "0.30.
|
|
40
|
-
"@protobase/query": "0.30.
|
|
41
|
-
"@protobase/schema": "0.30.
|
|
42
|
-
"@protobase/server": "0.30.
|
|
43
|
-
"@protobase/ui": "0.30.
|
|
39
|
+
"@protobase/layout": "0.30.2",
|
|
40
|
+
"@protobase/query": "0.30.2",
|
|
41
|
+
"@protobase/schema": "0.30.2",
|
|
42
|
+
"@protobase/server": "0.30.2",
|
|
43
|
+
"@protobase/ui": "0.30.2",
|
|
44
44
|
"@react-email/render": "^2.1.0",
|
|
45
45
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
46
46
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -62,6 +62,7 @@ Reference:
|
|
|
62
62
|
- When asking how the packages fit together → read [Architecture](references/reference/architecture.md)
|
|
63
63
|
- When calling or changing the REST API, its filters, writes and errors → read [REST API](references/reference/api.md)
|
|
64
64
|
- When an app calls it with supabase-js, `from()` and `rpc()` under RLS → read [Supabase client API](references/reference/supabase-rest.md)
|
|
65
|
+
- When an app calls `storage` with supabase-js, under the storage policies → read [Supabase Storage API](references/reference/supabase-storage.md)
|
|
65
66
|
- When working with file fields and uploads → read [Files](references/reference/files.md)
|
|
66
67
|
- When reacting to changes of records → read [Events](references/reference/events.md)
|
|
67
68
|
- When delivering events to URLs → read [Webhooks](references/reference/webhooks.md)
|
|
@@ -467,6 +467,7 @@ Run inside a project whose `protobase.config.ts` exports `auth`, against its dat
|
|
|
467
467
|
|
|
468
468
|
```sh
|
|
469
469
|
protobase import supabase [<connection> | --source-env <variable>] [--env DATABASE_URL] [--dir db/migrations] [--config config]
|
|
470
|
+
[--storage-url <url>] [--storage-key-env SUPABASE_SERVICE_ROLE_KEY] [--yes]
|
|
470
471
|
```
|
|
471
472
|
|
|
472
473
|
Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
|
|
@@ -475,6 +476,8 @@ Turns a Supabase project's database into the project in the current directory, i
|
|
|
475
476
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
476
477
|
3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, Edge Functions, and the indexes [`doctor`](#doctor) finds missing.
|
|
477
478
|
|
|
479
|
+
4. **Storage's files**: with `--storage-url https://<ref>.supabase.co` and the project's secret key in the variable `--storage-key-env` names, `SUPABASE_SERVICE_ROLE_KEY` by default, the second run, or any run after it, copies the bytes of every object in `storage.objects` from the Supabase project's Storage API into the app's [Storage file provider](supabase-storage.md#where-things-are-kept)), where [`/storage/v1`](supabase-storage.md)) serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket's size and stops when what is left to copy and what the provider holds exceed the provider's `max_bytes`, unless `--yes`. An object that fails does not stop the rest; the run then fails, listing them in `supabase-import/storage.md`, and a rerun copies only what the provider does not hold yet. The key goes only in the requests' headers, never in a file.
|
|
480
|
+
|
|
478
481
|
Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
|
|
479
482
|
|
|
480
483
|
## `mobile`
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
<!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/supabase-storage.md: run `bun run docs:skill`, do not edit. -->
|
|
2
|
+
|
|
3
|
+
# Supabase Storage API
|
|
4
|
+
|
|
5
|
+
The Storage-compatible /storage/v1 that supabase-js's storage calls, over the app's file provider, under the restored storage policies.
|
|
6
|
+
|
|
7
|
+
An app with API keys also serves `/storage/v1`, the API that supabase-js's `storage` calls. An app moved from Supabase keeps its uploads, downloads, public URLs and signed URLs: point the client at the app and give it the publishable key.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createClient } from '@supabase/supabase-js'
|
|
11
|
+
|
|
12
|
+
const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
|
|
13
|
+
const { data, error } = await supabase.storage.from('avatars').upload(`${userId}/avatar.png`, file)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Where things are kept
|
|
17
|
+
|
|
18
|
+
The buckets and objects are the rows of `storage.buckets` and `storage.objects`, the schema that `protobase import supabase` restores with its policies. The bytes go to one of the app's [file providers](files.md)): `files.storage.provider` in `protobase.config.ts`, `private` by default, so a local folder or an S3-compatible bucket, with that provider's `max_bytes` and `max_files` quota. An object's bytes are kept at `storage/<SHA-256 of bucket and name>/<version>` in the provider, where [`protobase import supabase --storage-url`](cli.md#import-supabase)) copies a Supabase project's. `files.storage.maxFileSize` caps every upload, `50 MB` by default, and a bucket's `file_size_limit` can only lower it. `files: { storage: false }` serves no `/storage/v1`.
|
|
19
|
+
|
|
20
|
+
## Keys and roles
|
|
21
|
+
|
|
22
|
+
The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. Without either, or with `apiKeys: false`, the app serves no `/storage/v1`. A request sends a key in the `apikey` header and runs as:
|
|
23
|
+
|
|
24
|
+
| The request sends | It runs as |
|
|
25
|
+
| --- | --- |
|
|
26
|
+
| the publishable key | `anon` |
|
|
27
|
+
| either key and a signed-in user's token | `authenticated` |
|
|
28
|
+
| the secret key | the app's own role, which owns the tables |
|
|
29
|
+
|
|
30
|
+
The role is set with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()` works in the policies. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them. Every read and write of `storage.objects` and `storage.buckets` runs as that role, with the token's claims set, so the restored policies decide, as on Supabase:
|
|
31
|
+
|
|
32
|
+
- an upload needs an `insert` policy, and one with `upsert` also `select` and `update`;
|
|
33
|
+
- a download, a signed URL, `info`, `list`, `copy`'s source and `move` need `select`, and `move` also `update`;
|
|
34
|
+
- `remove` and `empty` delete only what a `delete` policy allows;
|
|
35
|
+
- the bucket calls need policies on `storage.buckets`, which usually only the secret key gets past.
|
|
36
|
+
|
|
37
|
+
An upload is checked against the policies before its bytes are stored, then its row is written as the caller in one transaction. A refused upload stores nothing, and the bytes of a write that fails are deleted.
|
|
38
|
+
|
|
39
|
+
Public buckets are served at `/storage/v1/object/public/<bucket>/<name>` without a key. A signed URL serves one object to anyone until it expires; a signed upload URL takes one upload for two hours, written for the user who signed it.
|
|
40
|
+
|
|
41
|
+
## What it serves
|
|
42
|
+
|
|
43
|
+
- `object/<bucket>/<name>`: upload (POST, with `x-upsert`), replace (PUT), download (GET, also `object/authenticated/...`), `exists` (HEAD) and delete.
|
|
44
|
+
- `object/public/...`, `object/sign/...` (one or many) and `object/upload/sign/...`.
|
|
45
|
+
- `object/list/<bucket>`, `object/move`, `object/copy` and `object/info/...`.
|
|
46
|
+
- `bucket`: list, get, create, update, empty and delete.
|
|
47
|
+
|
|
48
|
+
A download is sent with the type it was uploaded with, `nosniff` and a sandboxing Content-Security-Policy, so an uploaded page cannot run on the app's origin, and `?download` makes it an attachment.
|
|
49
|
+
|
|
50
|
+
Not yet: image transforms, resumable (TUS) uploads, the S3 protocol, and object versioning.
|
|
51
|
+
|
|
52
|
+
## Errors
|
|
53
|
+
|
|
54
|
+
Errors come back as Supabase Storage sends them: status `400` with `{ statusCode, error, message }`, where `statusCode` says what happened: `404` for an object or bucket that is not there or not visible, `403` for a refusal by policy, `409` for an object or bucket that exists, `413` for an object over the size limit, `415` for a type the bucket does not allow. A failure is `500`.
|