Cotton code
88 lines · 4.1 KB · TypeScriptRaw
/** * Publish Cotton's reference sets as published databases (src/published.ts): * reads what `scripts/datasets/build.py` built and writes each set as a new * version, rows in batches, then commits it. A version already published is * left as it is. * *   pnpm datasets:publish --base <the dev Worker's address (config/dev-server.json)> [--dir .cache/datasets/built] [--only places] * * The publisher's token is PUBLISHER_TOKEN or the file * ~/.cotton-credentials/cloudflare/publisher-token-cotton (dev Worker: * dev-publisher-token-cotton), the value the Worker's PUBLISHER_TOKENS secret * holds under "cotton". Never printed. The coordinator runs this; a lane holds * no publisher token. */import { existsSync, readFileSync } from "node:fs";import { homedir } from "node:os";import { dirname, join, resolve } from "node:path";import { DatabaseSync } from "node:sqlite";import { fileURLToPath } from "node:url";import { batches, SETS, versionOf } from "./published-rows.ts";const here = dirname(fileURLToPath(import.meta.url));const argv = process.argv.slice(2);const flag = (name: string): string | undefined => {  const i = argv.indexOf(`--${name}`);  return i >= 0 ? argv[i + 1] : undefined;};const base = (flag("base") ?? fail("usage: pnpm datasets:publish --base <worker url> [--dir <datasets folder>] [--only <set>]")).replace(/\/$/, "");const dir = resolve(flag("dir") ?? join(here, "../../../.cache/datasets/built"));const only = flag("only");const token = process.env.PUBLISHER_TOKEN ?? readToken();const BATCH = 2000;function readToken(): string {  const name = /^cottondb-dev\./.test(new URL(base).hostname) ? "dev-publisher-token-cotton" : "publisher-token-cotton";  const file = join(homedir(), ".cotton-credentials/cloudflare", name);  if (!existsSync(file)) fail(`no publisher token: set PUBLISHER_TOKEN or write ${file}`);  return readFileSync(file, "utf8").trim();}function fail(message: string): never {  console.error(message);  process.exit(1);}async function send(method: string, path: string, body?: unknown): Promise<{ status: number; text: string }> {  for (let attempt = 1; ; attempt += 1) {    const r = await fetch(`${base}${path}`, { method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) }, body: body === undefined ? undefined : JSON.stringify(body) }).catch((error: unknown) => ({ status: 0, text: async () => String(error) }));    const text = await r.text();    // A lost answer is retried: a batch already loaded is kept as it was (src/published.ts `load`).    if ((r.status === 0 || r.status >= 500) && attempt < 4) continue;    return { status: r.status, text };  }}const opened = new Map<string, DatabaseSync>();const open = (file: string): DatabaseSync => {  const path = join(dir, file);  if (!existsSync(path)) fail(`${path} is missing: run python3 scripts/datasets/build.py first`);  let db = opened.get(path);  if (!db) opened.set(path, (db = new DatabaseSync(path, { readOnly: true })));  return db;};for (const set of SETS.filter((s) => !only || s.name === only)) {  const version = versionOf(open, set);  const root = `/v1/published/cotton/${set.name}/versions/${encodeURIComponent(version)}`;  const begun = await send("PUT", root);  if (begun.status === 409) {    console.log(`${set.name}: ${version} is already published`);    continue;  }  if (begun.status !== 200) fail(`${set.name}: begin → ${begun.status} ${begun.text.slice(0, 300)}`);  for (const { table, rows } of set.tables(open)) {    let count = 0;    for (const batch of batches(rows(), BATCH)) {      const loaded = await send("POST", `${root}/rows`, { table, rows: batch });      if (loaded.status !== 200) fail(`${set.name}/${table}: rows → ${loaded.status} ${loaded.text.slice(0, 300)}`);      count += batch.length;      process.stdout.write(`\r${set.name}/${table}: ${count} rows`);    }    process.stdout.write("\n");  }  const committed = await send("POST", `${root}/commit`);  if (committed.status !== 200) fail(`${set.name}: commit → ${committed.status} ${committed.text.slice(0, 300)}`);  console.log(`${set.name}: published ${version} ${committed.text}`);}