OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
chore: export/import commands for selfhosting to cloud
Carl-Gerhard Lindesvärdf01d4b9387e5
diff --git a/self-hosting/export-for-cloud.sh b/self-hosting/export-for-cloud.shnew file mode 100755index 000000000..996277385--- /dev/null+++ b/self-hosting/export-for-cloud.sh@@ -0,0 +1,404 @@+#!/usr/bin/env bash+#+# Export OpenPanel ClickHouse data to gzipped JSONL, ready to be re-inserted+# into another OpenPanel instance (e.g. OpenPanel Cloud).+#+# Run it on the self-hosted server:+#+# chmod +x export-for-cloud.sh+# ./export-for-cloud.sh+#+# It finds the ClickHouse container by itself. If that fails — Coolify, Dokploy,+# Portainer and friends all rename containers — point it at one explicitly:+#+# ./export-for-cloud.sh --list # show every candidate+# ./export-for-cloud.sh --container a1b2c3d4 # container ID or name+#+# Every flag has an env-var equivalent; the flag wins.+#+# --container <id|name> CH_CONTAINER Docker container running ClickHouse+# --out <dir> OUT_DIR Output directory (default ./op-export)+# --project-id <a,b> PROJECT_ID Only these projects (default: all)+# --from "2026-05-01" FROM Only rows with created_at >= this+# --to "2026-08-16 12:00" TO Only rows with created_at < this+# --tables "events ..." TABLES Subset of tables to export+# --rows-per-file 100000 ROWS_PER_FILE Max rows per .jsonl.gz file+# --db openpanel CH_DB ClickHouse database+# --list List candidate containers and exit+# --help+#+# CH_USER= / CH_PASSWORD= / CH_HOST= ClickHouse credentials (rarely needed)+# GZIP=0 Write plain .jsonl instead of .jsonl.gz+#+# TABLES defaults to the four tables that actually need migrating: events,+# sessions, profiles, groups. Everything else in ClickHouse is derived (all the+# _mv views, cohort_members, cohort_metadata), staging (events_imports),+# re-syncable (gsc_*), host-local (self_hosting, events_bots), or dead+# (profile_aliases). Session replays are opt-in and rarely worth it:+#+# --tables "events sessions profiles groups session_replay_chunks"+#+# Typical migration flow:+# 1. Full export: ./export-for-cloud.sh+# 2. Ship it: tar czf op-export.tar.gz op-export && scp ...+# 3. Cut the SDK over to cloud, note the exact time.+# 4. Delta export: ./export-for-cloud.sh --from "<cutover time>" --out ./op-export-delta+#+set -euo pipefail++CH_DB="${CH_DB:-openpanel}"+OUT_DIR="${OUT_DIR:-./op-export}"+ROWS_PER_FILE="${ROWS_PER_FILE:-100000}"+PROJECT_ID="${PROJECT_ID:-}"+FROM="${FROM:-}"+TO="${TO:-}"+GZIP="${GZIP:-1}"+TABLES="${TABLES:-events sessions profiles groups}"+CH_CONTAINER="${CH_CONTAINER:-}"+LIST_ONLY=0++die() {+ echo "❌ $*" >&2+ exit 1+}++# If ClickHouse dies half way through a file we must not leave a truncated+# .jsonl.gz behind — the importer reads the directory, not the manifest, and+# would import it as if it were complete.+CURRENT_FILE=""+cleanup_partial() {+ local code=$?+ if [[ $code -ne 0 && -n "$CURRENT_FILE" && -f "$CURRENT_FILE" ]]; then+ rm -f "$CURRENT_FILE"+ echo "🧹 Removed partial file: $CURRENT_FILE" >&2+ fi+ exit $code+}+trap cleanup_partial EXIT++usage() {+ sed -n '2,/^set -euo/p' "$0" | sed 's/^# \{0,1\}//; $d'+}++while [[ $# -gt 0 ]]; do+ case "$1" in+ --container) CH_CONTAINER="${2:-}"; shift 2 ;;+ --out | --out-dir) OUT_DIR="${2:-}"; shift 2 ;;+ --project-id) PROJECT_ID="${2:-}"; shift 2 ;;+ --from) FROM="${2:-}"; shift 2 ;;+ --to) TO="${2:-}"; shift 2 ;;+ --tables) TABLES="${2:-}"; shift 2 ;;+ --rows-per-file) ROWS_PER_FILE="${2:-}"; shift 2 ;;+ --db) CH_DB="${2:-}"; shift 2 ;;+ --list | --list-containers) LIST_ONLY=1; shift ;;+ -h | --help) usage; exit 0 ;;+ *) die "Unknown option: $1 (try --help)" ;;+ esac+done++# ---------------------------------------------------------------------------+# Locate a clickhouse-client we can talk to+#+# Container names are not portable: docker compose gives you+# `self-hosting-op-ch-1`, Coolify/Dokploy give you `op-ch-<random>-<random>`,+# and a host can easily run more than one ClickHouse. So we never guess by+# name alone — a candidate only counts if it actually holds the OpenPanel+# `events` table, and if several do we stop and make the user choose.+# ---------------------------------------------------------------------------+CH_AUTH=()+if [[ -n "${CH_HOST:-}" ]]; then CH_AUTH+=(--host="$CH_HOST"); fi+if [[ -n "${CH_USER:-}" ]]; then CH_AUTH+=(--user="$CH_USER"); fi+if [[ -n "${CH_PASSWORD:-}" ]]; then CH_AUTH+=(--password="$CH_PASSWORD"); fi+# Prints "1" when the container holds "$CH_DB.events", "0" otherwise.+# `${arr[@]+...}` keeps the empty-array case working on bash 3.2 under `set -u`.+probe_container() {+ docker exec "$1" clickhouse-client ${CH_AUTH[@]+"${CH_AUTH[@]}"} \+ --query "SELECT count() FROM system.tables WHERE database = '$CH_DB' AND name = 'events'" \+ </dev/null 2>/dev/null || echo 0+}++docker_ps() { docker ps --format '{{.ID}}\t{{.Names}}\t{{.Image}}' 2>/dev/null || true; }++# Anything that smells like ClickHouse by image or by name, in that order.+name_matched_containers() {+ docker_ps | awk -F'\t' 'tolower($3) ~ /clickhouse/ || tolower($2) ~ /clickhouse|op-ch/ { print }'+}++list_candidates() {+ local rows+ rows="$(docker_ps)"+ if [[ -z "$rows" ]]; then+ die "No running docker containers (is docker running, and do you need sudo?)."+ fi+ echo "🐳 Running containers, and whether they hold '$CH_DB.events':"+ echo+ printf ' %-14s %-42s %s\n' 'CONTAINER ID' 'NAME' 'OPENPANEL DATA'+ while IFS=$'\t' read -r cid cname cimage <&3; do+ if [[ -z "$cid" ]]; then continue; fi+ if [[ "$(probe_container "$cid")" == "1" ]]; then+ printf ' %-14s %-42s ✅ yes\n' "$cid" "$cname"+ else+ printf ' %-14s %-42s –\n' "$cid" "$cname"+ fi+ done 3<<<"$rows"+ echo+ echo " Then run: $0 --container <CONTAINER ID>"+ return 0+}++if [[ "$LIST_ONLY" == "1" ]]; then+ list_candidates+ exit 0+fi++CH=()+if [[ -n "$CH_CONTAINER" ]]; then+ docker inspect "$CH_CONTAINER" >/dev/null 2>&1 ||+ die "No such container: '$CH_CONTAINER'. Run '$0 --list' to see what is available."+ if [[ "$(probe_container "$CH_CONTAINER")" != "1" ]]; then+ die "Container '$CH_CONTAINER' does not have a '$CH_DB.events' table. Wrong container, or wrong --db?"+ fi+ CH=(docker exec -i "$CH_CONTAINER" clickhouse-client)+else+ # Probe every plausible container, then fall back to probing all of them —+ # a rebranded or retagged image should not stop the export.+ matches=()+ for scope in name_matched_containers docker_ps; do+ while IFS=$'\t' read -r cid cname cimage <&3; do+ [[ -z "$cid" ]] && continue+ if [[ "$(probe_container "$cid")" == "1" ]]; then+ matches+=("$cid|$cname")+ fi+ done 3<<<"$($scope)"+ if [[ ${#matches[@]} -gt 0 ]]; then break; fi+ done++ if [[ ${#matches[@]} -eq 1 ]]; then+ CH_CONTAINER="${matches[0]%%|*}"+ echo "🐳 ClickHouse container: ${matches[0]#*|} ($CH_CONTAINER)"+ CH=(docker exec -i "$CH_CONTAINER" clickhouse-client)+ elif [[ ${#matches[@]} -gt 1 ]]; then+ echo "❌ Found ${#matches[@]} containers with a '$CH_DB.events' table:" >&2+ for match in "${matches[@]}"; do+ printf ' %-14s %s\n' "${match%%|*}" "${match#*|}" >&2+ done+ die "Pick one: $0 --container <CONTAINER ID>"+ elif command -v clickhouse-client >/dev/null 2>&1; then+ echo "🖥️ Using clickhouse-client from PATH"+ CH=(clickhouse-client)+ else+ echo "❌ Could not find a ClickHouse container holding '$CH_DB.events'." >&2+ echo >&2+ list_candidates >&2 || true+ die "Set the container explicitly with --container <id>."+ fi+fi++CH+=(--database="$CH_DB" --max_execution_time=0)+if [[ -n "${CH_HOST:-}" ]]; then CH+=(--host="$CH_HOST"); fi+if [[ -n "${CH_USER:-}" ]]; then CH+=(--user="$CH_USER"); fi+if [[ -n "${CH_PASSWORD:-}" ]]; then CH+=(--password="$CH_PASSWORD"); fi++# stdin is closed on purpose: `docker exec -i` would otherwise swallow the+# day-list we are reading from in the export loop below.+chq() { "${CH[@]}" --query="$1" </dev/null; }++chq "SELECT 1" >/dev/null || die "Could not query ClickHouse database '$CH_DB'."++# ---------------------------------------------------------------------------+# Per-table export rules+#+# sessions / profiles / groups are Replacing- or CollapsingMergeTree, so they+# need FINAL (+ a sign/deleted filter) to get one current row per entity.+# `country` is a LowCardinality(FixedString(2)) which JSON-encodes empty values+# as " " — we normalise it to "" so the JSONL stays clean.+# ---------------------------------------------------------------------------+COUNTRY_FIX="* EXCEPT (country), replaceAll(toString(country), '\\0', '') AS country"++tbl_select() {+ case "$1" in+ events | sessions) echo "$COUNTRY_FIX" ;;+ *) echo "*" ;;+ esac+}++tbl_from() {+ case "$1" in+ sessions | profiles | groups) echo "$1 FINAL" ;;+ *) echo "$1" ;;+ esac+}++tbl_extra() {+ case "$1" in+ sessions) echo "AND sign > 0" ;;+ groups) echo "AND deleted = 0" ;;+ *) echo "" ;;+ esac+}++# Deterministic tiebreaker so LIMIT/OFFSET paging never skips or repeats a row.+tbl_order() {+ case "$1" in+ session_replay_chunks) echo "started_at, session_id, chunk_index" ;;+ *) echo "created_at, id" ;;+ esac+}++# Column used to slice the export into daily windows. Every exportable table+# keys on a DateTime64(3), so the bounds below are always toDateTime64.+tbl_date() {+ case "$1" in+ session_replay_chunks) echo "started_at" ;;+ *) echo "created_at" ;;+ esac+}++# ---------------------------------------------------------------------------+# Filters+# ---------------------------------------------------------------------------+project_filter="1"+if [[ -n "$PROJECT_ID" ]]; then+ project_filter="project_id IN ('${PROJECT_ID//,/','}')"+fi++build_range_filter() {+ local col="$1" out=""+ if [[ -n "$FROM" ]]; then out="$out AND $col >= toDateTime64('$FROM', 3)"; fi+ if [[ -n "$TO" ]]; then out="$out AND $col < toDateTime64('$TO', 3)"; fi+ echo "$out"+}++mkdir -p "$OUT_DIR"+MANIFEST="$OUT_DIR/manifest.jsonl"+: >"$MANIFEST"++ch_version="$(chq "SELECT version()")"+echo "📦 ClickHouse $ch_version — exporting to $OUT_DIR"+echo " projects: ${PROJECT_ID:-<all>} range: ${FROM:-<start>} .. ${TO:-<now>}"+echo++declare -a summary_tables=()+declare -a summary_rows=()+declare -a summary_files=()++for table in $TABLES; do+ exists="$(chq "SELECT count() FROM system.tables WHERE database = '$CH_DB' AND name = '$table'")"+ if [[ "$exists" == "0" ]]; then+ echo "⏭️ $table — table does not exist, skipping"+ continue+ fi++ select_expr="$(tbl_select "$table")"+ from_expr="$(tbl_from "$table")"+ extra="$(tbl_extra "$table")"+ order_expr="$(tbl_order "$table")"+ date_col="$(tbl_date "$table")"+ where="WHERE $project_filter $extra$(build_range_filter "$date_col")"++ table_dir="$OUT_DIR/$table"+ mkdir -p "$table_dir"++ echo "▶️ $table"++ table_rows=0+ table_files=0++ # One pass to learn how many rows live on each day, then page through the+ # days. Day-sized windows keep OFFSET tiny, so paging stays cheap.+ while IFS=$'\t' read -r day next_day day_rows <&3; do+ [[ -z "$day" ]] && continue++ offset=0+ part=0+ day_written=0+ while ((offset < day_rows)); do+ file="$table_dir/${table}-${day}-$(printf '%04d' "$part").jsonl"++ sql="SELECT $select_expr+ FROM $from_expr+ $where+ AND $date_col >= toDateTime64('$day', 3)+ AND $date_col < toDateTime64('$next_day', 3)+ ORDER BY $order_expr+ LIMIT $ROWS_PER_FILE OFFSET $offset+ FORMAT JSONEachRow"++ if [[ "$GZIP" == "1" ]]; then file="$file.gz"; fi+ CURRENT_FILE="$file"+ if [[ "$GZIP" == "1" ]]; then+ chq "$sql" | gzip -c >"$file"+ written="$(gzip -dc "$file" | wc -l | tr -d ' ')"+ else+ chq "$sql" >"$file"+ written="$(wc -l <"$file" | tr -d ' ')"+ fi+ CURRENT_FILE=""++ # Count what actually landed rather than what the counting pass predicted.+ # On a live system the two differ: rows written between the two queries+ # still make it into the file, and a stale estimate would make the+ # verifier cry wolf.+ printf '{"table":"%s","file":"%s","day":"%s","rows":%s}\n' \+ "$table" "$(basename "$file")" "$day" "$written" >>"$MANIFEST"++ day_written=$((day_written + written))+ offset=$((offset + ROWS_PER_FILE))+ part=$((part + 1))+ table_files=$((table_files + 1))+ done++ table_rows=$((table_rows + day_written))+ printf ' %s %8s rows\n' "$day" "$day_written"+ done 3< <(chq "SELECT toDate($date_col) AS d, toDate($date_col) + 1 AS d_next, count() AS c+ FROM $from_expr+ $where+ GROUP BY d+ HAVING c > 0+ ORDER BY d")++ echo " ✅ $table: $table_rows rows in $table_files file(s)"+ echo++ summary_tables+=("$table")+ summary_rows+=("$table_rows")+ summary_files+=("$table_files")+done++# ---------------------------------------------------------------------------+# Metadata — lets the import side sanity-check counts and remap project ids+# ---------------------------------------------------------------------------+project_ids="$(chq "SELECT groupUniqArray(project_id) FROM events WHERE $project_filter" 2>/dev/null | tr -d '\n' || true)"++{+ echo '{'+ printf ' "exported_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ printf ' "clickhouse_version": "%s",\n' "$ch_version"+ printf ' "database": "%s",\n' "$CH_DB"+ printf ' "project_id_filter": "%s",\n' "$PROJECT_ID"+ printf ' "from": "%s",\n' "$FROM"+ printf ' "to": "%s",\n' "$TO"+ printf ' "project_ids_in_events": "%s",\n' "$project_ids"+ echo ' "tables": {'+ for i in "${!summary_tables[@]}"; do+ sep=","+ if ((i == ${#summary_tables[@]} - 1)); then sep=""; fi+ printf ' "%s": { "rows": %s, "files": %s }%s\n' \+ "${summary_tables[$i]}" "${summary_rows[$i]}" "${summary_files[$i]}" "$sep"+ done+ echo ' }'+ echo '}'+} >"$OUT_DIR/_meta.json"++echo "🎉 Done."+echo+echo " Projects found: $project_ids"+for i in "${!summary_tables[@]}"; do+ printf ' %-16s %10s rows\n' "${summary_tables[$i]}" "${summary_rows[$i]}"+done+echo+echo " Output: $OUT_DIR ($(du -sh "$OUT_DIR" | cut -f1))"+echo " Manifest: $MANIFEST"+echo+echo " Ship it with:"+echo " tar czf op-export.tar.gz -C \"$(dirname "$OUT_DIR")\" \"$(basename "$OUT_DIR")\""diff --git a/self-hosting/import-to-cloud.mjs b/self-hosting/import-to-cloud.mjsnew file mode 100755index 000000000..0f18af080--- /dev/null+++ b/self-hosting/import-to-cloud.mjs@@ -0,0 +1,328 @@+#!/usr/bin/env node+/**+ * Import an `export-for-cloud.sh` dump into another OpenPanel ClickHouse.+ *+ * Runs on plain Node (>= 18), no dependencies.+ *+ * node import-to-cloud.mjs \+ * --dir ./op-export \+ * --url https://user:[email protected]:8443 \+ * --db openpanel \+ * --map <old_project_id>=<new_project_id>+ *+ * Flags:+ * --dir <path> Export directory (default ./op-export)+ * --url <url> ClickHouse HTTP endpoint, credentials inline or via --user/--password.+ * The database may be the URL path, matching OpenPanel's own+ * CLICKHOUSE_URL format: https://user:pass@host:8443/openpanel+ * --db <name> Target database. Overrides the URL path. Defaults to the+ * path, then to "openpanel".+ * --map old=new Rewrite project_id. Repeatable. Required unless --no-map.+ * --no-map Keep every project_id as-is and import everything+ * --tables a,b Only import these tables+ * --batch 50000 Rows per INSERT+ * --dry-run Parse and count, insert nothing+ *+ * The mapping doubles as a filter: a row whose project_id has no --map entry is+ * dropped, not passed through with its original id. That keeps stray projects+ * out of the destination, and means `--map` is the single place that decides+ * both what moves and what it is called on the other side. Everything dropped+ * is counted and reported per project, so nothing disappears silently. Use+ * --no-map to import every project untouched.+ *+ * Re-runnable: every finished file is recorded in+ * <dir>/.import-state-<target-fingerprint>, and already-imported files are+ * skipped. ClickHouse MergeTree does not dedupe on insert, so do not delete+ * that file between runs against the same target. The fingerprint covers host,+ * database and the mapping itself, so changing any of them starts a fresh+ * state rather than silently skipping files the previous mapping had filtered.+ */+import { createReadStream, existsSync, appendFileSync, readFileSync } from 'node:fs';+import { readdir } from 'node:fs/promises';+import { createHash } from 'node:crypto';+import { createInterface } from 'node:readline';+import { createGunzip } from 'node:zlib';+import path from 'node:path';++const IMPORT_ORDER = [+ 'profiles',+ 'groups',+ 'sessions',+ 'events',+ 'session_replay_chunks',+];++const CH_SETTINGS = {+ // The self-hosted schema may be slightly ahead of / behind the target.+ input_format_skip_unknown_fields: 1,+ date_time_input_format: 'best_effort',+ async_insert: 0,+ wait_for_async_insert: 1,+};++function parseArgs(argv) {+ const args = {+ dir: './op-export',+ db: null,+ batch: 50_000,+ map: new Map(),+ tables: null,+ dryRun: false,+ noMap: false,+ url: process.env.CLICKHOUSE_URL ?? '',+ user: '',+ password: '',+ };+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ const next = () => argv[++i];+ if (arg === '--dir') args.dir = next();+ else if (arg === '--url') args.url = next();+ else if (arg === '--db') args.db = next();+ else if (arg === '--user') args.user = next();+ else if (arg === '--password') args.password = next();+ else if (arg === '--batch') args.batch = Number.parseInt(next(), 10);+ else if (arg === '--tables') args.tables = next().split(',');+ else if (arg === '--dry-run') args.dryRun = true;+ else if (arg === '--no-map') args.noMap = true;+ else if (arg === '--map') {+ const [from, to] = next().split('=');+ if (!from || !to) throw new Error('--map expects <old>=<new>');+ args.map.set(from, to);+ } else throw new Error(`Unknown flag: ${arg}`);+ }+ if (!args.url) throw new Error('Missing --url (or CLICKHOUSE_URL)');+ if (!args.noMap && args.map.size === 0) {+ throw new Error('Pass --map <old>=<new> to remap project_id, or --no-map to keep it');+ }++ // OpenPanel writes CLICKHOUSE_URL as http://host:8123/openpanel, so accept the+ // database in the path. ClickHouse's HTTP interface does NOT understand that+ // form — it answers "There is no handle /openpanel" — the client library just+ // rewrites it to ?database=. Do the same here, then blank the path.+ const parsed = new URL(args.url);+ const pathDb = parsed.pathname.replace(/^\/+|\/+$/g, '');+ if (args.db && pathDb && args.db !== pathDb) {+ console.warn(+ `⚠️ --db "${args.db}" overrides the database "${pathDb}" in the URL path`,+ );+ }+ args.db = args.db ?? (pathDb || 'openpanel');+ parsed.pathname = '/';+ args.url = parsed.toString();++ return args;+}++async function insert(args, table, rows) {+ if (args.dryRun || rows.length === 0) return;++ const url = new URL(args.url);+ if (args.user) url.username = args.user;+ if (args.password) url.password = args.password;++ const headers = { 'Content-Type': 'application/json' };+ if (url.username || url.password) {+ headers.Authorization = `Basic ${Buffer.from(+ `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`,+ ).toString('base64')}`;+ url.username = '';+ url.password = '';+ }++ url.searchParams.set('database', args.db);+ url.searchParams.set('query', `INSERT INTO ${table} FORMAT JSONEachRow`);+ for (const [key, value] of Object.entries(CH_SETTINGS)) {+ url.searchParams.set(key, String(value));+ }++ const body = `${rows.join('\n')}\n`;++ for (let attempt = 1; attempt <= 5; attempt++) {+ const res = await fetch(url, { method: 'POST', headers, body });+ if (res.ok) return;+ const text = await res.text();+ // 4xx means the payload is wrong — retrying will not help.+ if (res.status < 500 || attempt === 5) {+ throw new Error(`INSERT INTO ${table} failed (${res.status}): ${text.slice(0, 800)}`);+ }+ console.warn(` ⚠️ ${res.status} on ${table}, retry ${attempt}/4`);+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));+ }+}++const backfilled = { last_seen_at: 0 };+const importedByProject = new Map();+const droppedByProject = new Map();++const bump = (counter, key) => counter.set(key, (counter.get(key) ?? 0) + 1);++/** Returns the rewritten JSON line, or null when the row should be dropped. */+function remapLine(line, table, args) {+ const row = JSON.parse(line);+ const source = row.project_id;++ if (args.noMap) {+ bump(importedByProject, source);+ } else {+ const mapped = args.map.get(source);+ if (mapped === undefined) {+ bump(droppedByProject, source);+ return null;+ }+ row.project_id = mapped;+ bump(importedByProject, source);+ }++ // A collapsed session export only contains live rows.+ if (table === 'sessions') row.sign = 1;++ // A self-hosted install older than the 20260504 profiles restructure has no+ // `last_seen_at`. The target column is the ReplacingMergeTree version and has+ // no DEFAULT, so an absent value would land as 1970-01-01 and break both+ // dedup ordering and every "last seen" report. Seed it from `created_at`,+ // which is exactly what 16-restructure-profiles.ts does.+ if (table === 'profiles' && row.last_seen_at === undefined) {+ row.last_seen_at = row.created_at;+ backfilled.last_seen_at++;+ }++ return JSON.stringify(row);+}++async function importFile(args, table, file, state) {+ const key = `${table}/${path.basename(file)}`;+ if (state.has(key)) {+ console.log(` ⏭️ ${path.basename(file)} (already imported)`);+ return 0;+ }++ const stream = file.endsWith('.gz')+ ? createReadStream(file).pipe(createGunzip())+ : createReadStream(file);+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });++ let batch = [];+ let total = 0;+ let dropped = 0;++ for await (const line of lines) {+ if (!line.trim()) continue;+ const row = remapLine(line, table, args);+ if (row === null) {+ dropped++;+ continue;+ }+ batch.push(row);+ total++;+ if (batch.length >= args.batch) {+ await insert(args, table, batch);+ batch = [];+ }+ }+ await insert(args, table, batch);++ if (!args.dryRun) appendFileSync(state.file, `${key}\n`);+ state.add(key);+ const suffix = dropped > 0 ? ` (${dropped} dropped — unmapped project)` : '';+ console.log(` ✅ ${path.basename(file)} — ${total} rows${suffix}`);+ return total;+}++async function main() {+ const args = parseArgs(process.argv.slice(2));++ // Key the resume state to the destination. Sharing one state file across+ // targets means a dry run against staging would make the real import skip+ // every file and report success without writing anything.+ const target = new URL(args.url);+ console.log(`🎯 Target: ${target.origin} — database "${args.db}"\n`);+ const mappingKey = args.noMap+ ? 'no-map'+ : [...args.map.entries()]+ .map(([from, to]) => `${from}=${to}`)+ .sort()+ .join(',');+ // Keyed on the resolved database, so /openpanel in the path and --db openpanel+ // are the same target and resume each other rather than starting over.+ const fingerprint = createHash('sha256')+ .update(`${target.host}|${args.db}|${mappingKey}`)+ .digest('hex')+ .slice(0, 12);+ const stateFile = path.join(args.dir, `.import-state-${fingerprint}`);+ const state = new Set(+ existsSync(stateFile)+ ? readFileSync(stateFile, 'utf8').split('\n').filter(Boolean)+ : [],+ );+ state.file = stateFile;++ const metaPath = path.join(args.dir, '_meta.json');+ if (existsSync(metaPath)) {+ console.log(`📄 ${readFileSync(metaPath, 'utf8').trim()}\n`);+ }+ if (args.dryRun) console.log('🧪 Dry run — nothing will be written\n');++ const totals = {};+ for (const table of IMPORT_ORDER) {+ if (args.tables && !args.tables.includes(table)) continue;+ const dir = path.join(args.dir, table);+ if (!existsSync(dir)) continue;++ const files = (await readdir(dir)).filter((f) => f.includes('.jsonl')).sort();+ if (files.length === 0) continue;++ console.log(`▶️ ${table} (${files.length} files)`);+ let rows = 0;+ for (const file of files) {+ rows += await importFile(args, table, path.join(dir, file), state);+ }+ totals[table] = rows;+ console.log(` ${table}: ${rows} rows\n`);+ }++ console.log('🎉 Done.');+ for (const [table, rows] of Object.entries(totals)) {+ console.log(` ${table.padEnd(16)} ${String(rows).padStart(10)} rows`);+ }++ if (importedByProject.size > 0) {+ console.log('\n Imported by project:');+ for (const [source, rows] of [...importedByProject].sort((a, b) => b[1] - a[1])) {+ const dest = args.noMap ? source : args.map.get(source);+ console.log(` ${source} → ${dest}`.padEnd(58) + `${String(rows).padStart(10)} rows`);+ }+ }++ if (droppedByProject.size > 0) {+ console.log('\n Ignored (no --map entry):');+ for (const [source, rows] of [...droppedByProject].sort((a, b) => b[1] - a[1])) {+ console.log(` ${source}`.padEnd(58) + `${String(rows).padStart(10)} rows`);+ }+ }++ // Every row filtered out is almost always a typo in --map rather than intent.+ if (importedByProject.size === 0 && droppedByProject.size > 0) {+ console.error(+ '\n❌ Every row was dropped — no project_id in the export matched a --map entry.',+ );+ console.error(' Check _meta.json for the exact source project ids.');+ process.exit(1);+ }+ if (backfilled.last_seen_at > 0) {+ console.log(+ `\nℹ️ Seeded last_seen_at from created_at for ${backfilled.last_seen_at} profiles`,+ );+ console.log(+ ' (source install predates the 20260504 profiles restructure — see',+ );+ console.log(+ ' 16-restructure-profiles.ts for the optional events-derived backfill)',+ );+ }+}++main().catch((error) => {+ console.error(`❌ ${error.message}`);+ process.exit(1);+});diff --git a/self-hosting/verify-export.mjs b/self-hosting/verify-export.mjsnew file mode 100755index 000000000..7ee56da5c--- /dev/null+++ b/self-hosting/verify-export.mjs@@ -0,0 +1,103 @@+#!/usr/bin/env node+/**+ * Verify an export directory against its manifest before importing it.+ *+ * Catches the two things that actually go wrong: a file that never finished+ * transferring (truncated gzip) and a file that is silently missing.+ *+ * node verify-export.mjs ./op-export+ *+ * Exits non-zero if anything is wrong, so it chains: `node verify-export.mjs+ * ./op-export && node import-to-cloud.mjs --dir ./op-export ...`+ */+import { createReadStream, existsSync, readFileSync } from 'node:fs';+import { createInterface } from 'node:readline';+import { createGunzip } from 'node:zlib';+import path from 'node:path';++const dir = process.argv[2] ?? './op-export';+const manifestPath = path.join(dir, 'manifest.jsonl');++if (!existsSync(manifestPath)) {+ console.error(`❌ No manifest.jsonl in ${dir} — is that the export directory?`);+ process.exit(1);+}++async function countRows(file) {+ const stream = file.endsWith('.gz')+ ? createReadStream(file).pipe(createGunzip())+ : createReadStream(file);+ const lines = createInterface({ input: stream, crlfDelay: Number.POSITIVE_INFINITY });+ let rows = 0;+ for await (const line of lines) {+ if (line.trim()) rows++;+ }+ return rows;+}++const entries = readFileSync(manifestPath, 'utf8')+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line));++const problems = [];+const notes = [];+const totals = {};+let checked = 0;++for (const entry of entries) {+ const file = path.join(dir, entry.table, entry.file);++ if (!existsSync(file)) {+ problems.push(`MISSING ${entry.table}/${entry.file}`);+ continue;+ }++ let rows;+ try {+ rows = await countRows(file);+ } catch (error) {+ // An interrupted transfer shows up here as an unexpected end of stream.+ problems.push(`CORRUPT ${entry.table}/${entry.file} — ${error.message}`);+ continue;+ }++ // Fewer rows than expected means the file was cut short. More rows means+ // traffic arrived between the export's counting pass and its reading pass —+ // the file is complete, the manifest's estimate was just stale. Only the+ // first case is a problem.+ if (rows < entry.rows) {+ problems.push(+ `TRUNCATED ${entry.table}/${entry.file} — manifest says ${entry.rows}, file has ${rows}`,+ );+ continue;+ }++ if (rows > entry.rows) {+ notes.push(+ `${entry.table}/${entry.file} — ${rows - entry.rows} row(s) beyond the manifest (written while the export ran)`,+ );+ }++ totals[entry.table] = (totals[entry.table] ?? 0) + rows;+ checked++;+}++console.log(`Checked ${checked}/${entries.length} files in ${dir}\n`);+for (const [table, rows] of Object.entries(totals)) {+ console.log(` ${table.padEnd(24)} ${String(rows).padStart(10)} rows`);+}++if (notes.length > 0) {+ console.log(`\nℹ️ ${notes.length} file(s) grew during the export:`);+ for (const note of notes) console.log(` ${note}`);+}++if (problems.length > 0) {+ console.error(`\n❌ ${problems.length} problem(s):`);+ for (const problem of problems) console.error(` ${problem}`);+ console.error('\n Re-run your rsync — it will fetch just the bad files.');+ process.exit(1);+}++console.log('\n✅ Export is complete — no missing, truncated or corrupt files.');