Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

15.1 KB
Raw Blame
/**
 * Bulk transfer for environment database export/import requests and the Dashboard’s downloads. Each runs on
 * its own connection (not the query pools: a transfer can take minutes) in one transaction:
 *  - CSV export: `COPY public.t TO STDOUT (FORMAT csv, HEADER)` as the reader, READ ONLY.
 *  - SQL export: schema and data of the public schema as plain SQL (no pg_dump in the CP Box),
 *    read in one REPEATABLE READ snapshot as the reader. Restores with psql into an empty
 *    database (through `boxlite app psql --proxy --write` on a non-main env).
 *  - CSV import: `COPY public.t (cols) FROM STDIN (FORMAT csv, HEADER MATCH)` as the owner; the
 *    header names the columns, all rows land or none do.
 */
import { Readable, Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import pg from 'pg'
import Cursor from 'pg-cursor'
import { from as copyFrom, to as copyTo } from 'pg-copy-streams'
import { fail } from './errors'
import { quoteIdent, quoteLiteral } from './services/db'

/** A transfer may run this long on the server (the query endpoints stop at 15 s). */
export const TRANSFER_TIMEOUT = '10min'
/** Largest CSV body an import accepts. */
export const MAX_IMPORT_BYTES = 512 * 1024 * 1024
/** Rows per INSERT statement in a SQL dump. */
const ROWS_PER_INSERT = 100

export type Connect = () => Promise<pg.Client>

const q = (name: string) => `public.${quoteIdent(name)}`

/** Runs `fn` on a client and ends it however the stream ends (done, failed, or the HTTP client went away). */
function streamOn(
  connect: Connect,
  begin: string,
  produce: (c: pg.Client) => Readable | AsyncIterable<string>,
): Promise<Readable> {
  return (async () => {
    const client = await connect()
    try {
      await client.query(begin)
      await client.query(`SET LOCAL statement_timeout = '${TRANSFER_TIMEOUT}'`)
    } catch (err) {
      await client.end().catch(() => undefined)
      throw err
    }
    const out = produce(client)
    // Bytes, not strings: the HTTP response is a web stream of Uint8Array.
    const stream =
      out instanceof Readable
        ? out
        : Readable.from(
            (async function* () {
              for await (const text of out) yield Buffer.from(text, 'utf8')
            })(),
            { objectMode: false },
          )
    let ended = false
    const end = () => {
      if (ended) return
      ended = true
      void client.end().catch(() => undefined)
    }
    stream.once('close', end)
    stream.once('end', end)
    stream.once('error', end)
    return stream
  })()
}

/** CSV of one table (with a header row), streamed. */
export async function exportCsv(connect: Connect, table: string): Promise<Readable> {
  return await streamOn(connect, 'BEGIN TRANSACTION READ ONLY', (c) =>
    c.query(copyTo(`COPY ${q(table)} TO STDOUT WITH (FORMAT csv, HEADER)`)),
  )
}

interface Col {
  name: string
  type: string
  notnull: boolean
  def: string | null
  identity: string
  generated: string
}

/** Schema and data of the public schema (or one table) as SQL statements, streamed. */
export async function exportSql(connect: Connect, opts: { table?: string; title: string }): Promise<Readable> {
  return await streamOn(connect, 'BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY', (c) => dump(c, opts))
}

async function* dump(c: pg.Client, opts: { table?: string; title: string }): AsyncGenerator<string> {
  const rows = async <T>(text: string, values: unknown[] = []) => (await c.query(text, values)).rows as T[]
  yield `-- ${opts.title}\n-- Generated by BoxLite at ${new Date().toISOString()}: schema and data of the public schema${opts.table ? ` (table ${opts.table} only)` : ''}.\n`
  yield `-- Restore into an empty database: psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f <this file>\n\n`
  yield "SET statement_timeout = 0;\nSET client_encoding = 'UTF8';\nSET standard_conforming_strings = on;\nSET check_function_bodies = false;\nSET search_path = public, pg_catalog;\n\nBEGIN;\n\n"

  const tables = await rows<{ oid: number; name: string; rls: boolean; force: boolean }>(
    `SELECT c.oid::int AS oid, c.relname AS name, c.relrowsecurity AS rls, c.relforcerowsecurity AS force
       FROM pg_class c WHERE c.relnamespace = 'public'::regnamespace AND c.relkind = 'r' AND NOT c.relispartition
        AND ($1::text IS NULL OR c.relname = $1) ORDER BY c.relname`,
    [opts.table ?? null],
  )
  const oids = tables.map((t) => t.oid)
  const nameOf = new Map(tables.map((t) => [t.oid, t.name]))

  for (const e of await rows<{ extname: string }>(
    `SELECT extname FROM pg_extension WHERE extname <> 'plpgsql' ORDER BY extname`,
  ))
    yield `CREATE EXTENSION IF NOT EXISTS ${quoteIdent(e.extname)};\n`
  for (const t of await rows<{ name: string; labels: string[] }>(
    `SELECT t.typname AS name, array_agg(e.enumlabel::text ORDER BY e.enumsortorder) AS labels FROM pg_type t JOIN pg_enum e ON e.enumtypid = t.oid
      WHERE t.typnamespace = 'public'::regnamespace GROUP BY t.typname ORDER BY t.typname`,
  )) {
    yield `CREATE TYPE ${q(t.name)} AS ENUM (${t.labels.map(quoteLiteral).join(', ')});\n`
  }

  // Sequences: serial ones (owned by a column) and free-standing ones; identity columns make their own.
  const seqs = await rows<{
    name: string
    type: string
    start: string
    inc: string
    min: string
    max: string
    cache: string
    cycle: boolean
    deptype: string | null
    tbl: number | null
    col: string | null
    last: string | null
  }>(
    `SELECT s.relname AS name, format_type(q.seqtypid, NULL) AS type, q.seqstart::text AS start, q.seqincrement::text AS inc, q.seqmin::text AS min,
            q.seqmax::text AS max, q.seqcache::text AS cache, q.seqcycle AS cycle, d.deptype::text AS deptype, d.refobjid::int AS tbl, a.attname AS col,
            ps.last_value::text AS last
       FROM pg_class s JOIN pg_sequence q ON q.seqrelid = s.oid
       LEFT JOIN pg_depend d ON d.objid = s.oid AND d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i')
       LEFT JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
       LEFT JOIN pg_sequences ps ON ps.schemaname = 'public' AND ps.sequencename = s.relname
      WHERE s.relkind = 'S' AND s.relnamespace = 'public'::regnamespace ORDER BY s.relname`,
  )
  const ours = seqs.filter((s) => (s.tbl === null ? !opts.table : nameOf.has(s.tbl)))
  for (const s of ours.filter((s) => s.deptype !== 'i')) {
    yield `CREATE SEQUENCE ${q(s.name)} AS ${s.type} START WITH ${s.start} INCREMENT BY ${s.inc} MINVALUE ${s.min} MAXVALUE ${s.max} CACHE ${s.cache}${s.cycle ? ' CYCLE' : ''};\n`
  }

  if (!opts.table) {
    for (const f of await rows<{ def: string }>(
      `SELECT pg_get_functiondef(p.oid) AS def FROM pg_proc p WHERE p.pronamespace = 'public'::regnamespace AND p.prokind IN ('f', 'p')
          AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e') ORDER BY p.proname, p.oid`,
    )) {
      yield `\n${f.def.trimEnd()};\n`
    }
  }

  const cols = new Map<number, Col[]>()
  for (const r of await rows<Col & { rel: number }>(
    `SELECT a.attrelid::int AS rel, a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS notnull,
            pg_get_expr(ad.adbin, ad.adrelid) AS def, a.attidentity::text AS identity, a.attgenerated::text AS generated
       FROM pg_attribute a LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum
      WHERE a.attrelid = ANY($1::oid[]) AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attrelid, a.attnum`,
    [oids],
  )) {
    if (!cols.has(r.rel)) cols.set(r.rel, [])
    cols.get(r.rel)!.push(r)
  }
  for (const t of tables) {
    const defs = (cols.get(t.oid) ?? []).map((col) => {
      let d = `    ${quoteIdent(col.name)} ${col.type}`
      if (col.identity) d += ` GENERATED ${col.identity === 'a' ? 'ALWAYS' : 'BY DEFAULT'} AS IDENTITY`
      else if (col.generated === 's') d += ` GENERATED ALWAYS AS (${col.def}) STORED`
      else if (col.def !== null) d += ` DEFAULT ${col.def}`
      if (col.notnull) d += ' NOT NULL'
      return d
    })
    yield `\nCREATE TABLE ${q(t.name)} (\n${defs.join(',\n')}\n);\n`
  }
  for (const s of ours.filter((s) => s.deptype === 'a' && s.col))
    yield `ALTER SEQUENCE ${q(s.name)} OWNED BY ${q(nameOf.get(s.tbl!)!)}.${quoteIdent(s.col!)};\n`

  // Data, one table at a time, ROWS_PER_INSERT rows per statement. quote_nullable renders every
  // value as a literal its column type reads back.
  for (const t of tables) {
    const data = (cols.get(t.oid) ?? []).filter((col) => col.generated !== 's')
    if (!data.length) continue
    const head = `INSERT INTO ${q(t.name)} (${data.map((col) => quoteIdent(col.name)).join(', ')})${data.some((col) => col.identity === 'a') ? ' OVERRIDING SYSTEM VALUE' : ''} VALUES\n`
    const cur = c.query(
      new Cursor(
        `SELECT '(' || concat_ws(', ', ${data.map((col) => `quote_nullable(${quoteIdent(col.name)})`).join(', ')}) || ')' FROM ${q(t.name)}`,
        [],
        { rowMode: 'array' },
      ),
    )
    try {
      yield `\n-- data of ${t.name}\n`
      for (;;) {
        const batch = (await cur.read(ROWS_PER_INSERT)) as string[][]
        if (!batch.length) break
        yield `${head}${batch.map((r) => r[0]).join(',\n')};\n`
        if (batch.length < ROWS_PER_INSERT) break
      }
    } finally {
      await cur.close().catch(() => undefined)
    }
  }
  yield '\n'
  for (const s of ours) {
    if (s.last === null) continue
    const target =
      s.deptype === 'i'
        ? `pg_get_serial_sequence(${quoteLiteral(q(nameOf.get(s.tbl!)!))}, ${quoteLiteral(s.col!)})`
        : quoteLiteral(q(s.name))
    yield `SELECT pg_catalog.setval(${target}, ${s.last}, true);\n`
  }

  const cons = await rows<{ rel: number; name: string; type: string; def: string }>(
    `SELECT conrelid::int AS rel, conname AS name, contype::text AS type, pg_get_constraintdef(oid) AS def FROM pg_constraint
      WHERE conrelid = ANY($1::oid[]) AND contype IN ('p', 'u', 'c', 'x', 'f') ORDER BY contype = 'f', conrelid, contype <> 'p', conname`,
    [oids],
  )
  for (const k of cons)
    yield `ALTER TABLE ONLY ${q(nameOf.get(k.rel)!)} ADD CONSTRAINT ${quoteIdent(k.name)} ${k.def};\n`
  for (const i of await rows<{ def: string }>(
    `SELECT pg_get_indexdef(i.indexrelid) AS def FROM pg_index i WHERE i.indrelid = ANY($1::oid[])
        AND NOT EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conindid = i.indexrelid AND k.conrelid = i.indrelid AND k.contype IN ('p', 'u', 'x'))
      ORDER BY i.indrelid, i.indexrelid`,
    [oids],
  )) {
    yield `${i.def};\n`
  }
  for (const tr of await rows<{ def: string }>(
    `SELECT pg_get_triggerdef(oid) AS def FROM pg_trigger WHERE tgrelid = ANY($1::oid[]) AND NOT tgisinternal ORDER BY tgrelid, tgname`,
    [oids],
  ))
    yield `${tr.def};\n`
  for (const t of tables.filter((t) => t.rls))
    yield `ALTER TABLE ${q(t.name)} ENABLE ROW LEVEL SECURITY;\n${t.force ? `ALTER TABLE ${q(t.name)} FORCE ROW LEVEL SECURITY;\n` : ''}`
  for (const p of await rows<{
    tbl: string
    name: string
    permissive: string
    roles: string[]
    cmd: string
    qual: string | null
    check: string | null
  }>(
    `SELECT tablename AS tbl, policyname AS name, permissive, roles::text[] AS roles, cmd, qual, with_check AS check FROM pg_policies
      WHERE schemaname = 'public' AND ($1::text IS NULL OR tablename = $1) ORDER BY tablename, policyname`,
    [opts.table ?? null],
  )) {
    const roles = p.roles.map((r) => (r === 'public' ? 'PUBLIC' : quoteIdent(r))).join(', ')
    yield `CREATE POLICY ${quoteIdent(p.name)} ON ${q(p.tbl)} AS ${p.permissive} FOR ${p.cmd} TO ${roles}${p.qual ? ` USING (${p.qual})` : ''}${p.check ? ` WITH CHECK (${p.check})` : ''};\n`
  }
  if (!opts.table) {
    for (const v of await rows<{ name: string; kind: string; def: string }>(
      `SELECT relname AS name, relkind::text AS kind, pg_get_viewdef(oid) AS def FROM pg_class WHERE relnamespace = 'public'::regnamespace AND relkind IN ('v', 'm') ORDER BY oid`,
    )) {
      const body = v.def.trim().replace(/;$/, '')
      yield v.kind === 'v'
        ? `CREATE VIEW ${q(v.name)} AS\n${body};\n`
        : `CREATE MATERIALIZED VIEW ${q(v.name)} AS\n${body}\nWITH DATA;\n`
    }
  }
  yield '\nCOMMIT;\n'
}

/**
 * Reads the CSV header record (quoted fields allowed) from the front of `body`; the returned
 * stream still starts with it, so COPY … HEADER MATCH checks it against the column list.
 */
export async function csvHeader(body: Readable): Promise<{ columns: string[]; stream: Readable }> {
  const chunks: Buffer[] = []
  let seen = 0
  let header: string | null = null
  const it = body[Symbol.asyncIterator]()
  for (;;) {
    const { value, done } = await it.next()
    if (done) break
    const b = Buffer.isBuffer(value) ? value : Buffer.from(value as Uint8Array)
    chunks.push(b)
    seen += b.length
    const text = Buffer.concat(chunks).toString('utf8')
    let quoted = false
    for (let i = 0; i < text.length; i++) {
      if (text[i] === '"') quoted = !quoted
      else if (text[i] === '\n' && !quoted) {
        header = text.slice(0, i).replace(/\r$/, '')
        break
      }
    }
    if (header !== null || seen > 1024 * 1024) break
  }
  if (header === null)
    header = Buffer.concat(chunks)
      .toString('utf8')
      .replace(/\r?\n?$/, '')
  const columns: string[] = []
  let cur = ''
  let quoted = false
  for (let i = 0; i < header.length; i++) {
    const ch = header[i]!
    if (quoted) {
      if (ch === '"' && header[i + 1] === '"') {
        cur += '"'
        i++
      } else if (ch === '"') quoted = false
      else cur += ch
    } else if (ch === '"') quoted = true
    else if (ch === ',') {
      columns.push(cur)
      cur = ''
    } else cur += ch
  }
  columns.push(cur)
  const rest = Readable.from(
    (async function* () {
      for (const c of chunks) yield c
      for (;;) {
        const { value, done } = await it.next()
        if (done) return
        yield value as Buffer
      }
    })(),
  )
  return { columns: header.trim() ? columns : [], stream: rest }
}

/** COPY FROM STDIN as the owner, in one transaction; returns the rows written. */
export async function importCsv(connect: Connect, table: string, columns: string[], csv: Readable): Promise<number> {
  const client = await connect()
  try {
    await client.query('BEGIN')
    await client.query(`SET LOCAL statement_timeout = '${TRANSFER_TIMEOUT}'`)
    const copy = client.query(
      copyFrom(`COPY ${q(table)} (${columns.map(quoteIdent).join(', ')}) FROM STDIN WITH (FORMAT csv, HEADER MATCH)`),
    )
    let bytes = 0
    const cap = new Transform({
      transform(chunk: Buffer, _enc, cb) {
        bytes += chunk.length
        if (bytes > MAX_IMPORT_BYTES)
          cb(
            fail(
              'invalid_request',
              `the CSV is larger than ${MAX_IMPORT_BYTES / 1024 / 1024} MiB`,
              'split it into several files and import them one by one',
            ),
          )
        else cb(null, chunk)
      },
    })
    await pipeline(csv, cap, copy)
    await client.query('COMMIT')
    return copy.rowCount ?? 0
  } catch (err) {
    await client.query('ROLLBACK').catch(() => undefined)
    throw err
  } finally {
    await client.end().catch(() => undefined)
  }
}