blankthing 0.1.0 → 0.2.0

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.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/src/cli.js +84 -40
  3. package/src/client.js +58 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blankthing",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Blankthing CLI: a remote control for the blan_db service",
5
5
  "keywords": [
6
6
  "blankthing",
package/src/cli.js CHANGED
@@ -2,7 +2,6 @@
2
2
  // API call and prints the reply.
3
3
 
4
4
  import { parseArgs } from 'node:util';
5
- import { readFile } from 'node:fs/promises';
6
5
  import { createInterface } from 'node:readline/promises';
7
6
  import { createRequire } from 'node:module';
8
7
  import { makeClient, ApiError, DEFAULT_SERVER, DEFAULT_BARE_SERVER } from './client.js';
@@ -104,12 +103,20 @@ ${s.bold('DETAILS')}
104
103
  BLAN_MONGODB_URL / BLAN_SQLSERVER_URL instead, to keep it out of your
105
104
  shell history. Migrations run between two databases of the same engine.
106
105
 
107
- blan db demo [--direction to-blankthing|from-blankthing] [--file ROWS.jsonl]
108
- A free test migration on blan_db, start to finish, in a throwaway sandbox.
109
- to-blankthing your test rows move into Blankthing (--file, one JSON
110
- object per line, or piped on stdin)
111
- from-blankthing Blankthing's sample rows move out to your side
112
- Without --direction you are asked which way.
106
+ blan db demo --from postgres://USER:PASSWORD@HOST:PORT/DB [--window 30]
107
+ The free test migration, on your own data: your Postgres source moves
108
+ into a temporary Postgres database of Blankthing's. Load your test rows
109
+ first; up to 300 are copied. While the live feed is open (--window
110
+ seconds, default 30), keep writing to your source: up to 200 writes are
111
+ carried and shown as they land. Then every row, the row counts and the
112
+ checksums are printed for you to check against your source, with a
113
+ read-only connection string to the destination so you can check it
114
+ yourself (psql "<that string>"). The destination stays up for 30
115
+ minutes, then it is deleted.
116
+ Postgres only; once per account; needs only your token, no license.
117
+ The source needs wal_level=logical and a user with REPLICATION, and
118
+ every table needs a primary key. --from can come from BLAN_PG_URL;
119
+ without either you are asked for it.
113
120
 
114
121
  blan db migrate --from NAME --to NAME [--finish-now] [--settle 10s]
115
122
  blan db migrate SOURCE [--into DEST] [--finish-now] [--settle 10s]
@@ -144,8 +151,7 @@ const OPTIONS = {
144
151
  json: { type: 'boolean' },
145
152
  help: { type: 'boolean', short: 'h' },
146
153
  version: { type: 'boolean', short: 'v' },
147
- direction: { type: 'string', short: 'd' },
148
- file: { type: 'string', short: 'f' },
154
+ window: { type: 'string', short: 'w' },
149
155
  into: { type: 'string' },
150
156
  from: { type: 'string' },
151
157
  to: { type: 'string' },
@@ -264,43 +270,81 @@ function printSteps(out, steps) {
264
270
  for (const s of steps || []) out(` ${s.step.padEnd(10)} ${s.detail}`);
265
271
  }
266
272
 
267
- async function readRows(o, io) {
268
- let text;
269
- if (o.file) text = await readFile(o.file, 'utf8');
270
- else if (!io.stdin.isTTY) {
271
- const chunks = [];
272
- for await (const c of io.stdin) chunks.push(Buffer.from(c));
273
- text = Buffer.concat(chunks).toString('utf8');
274
- } else {
275
- throw new UsageError('to-blankthing needs your test rows: --file ROWS.jsonl, or pipe them on stdin');
276
- }
277
- const rows = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
278
- if (rows.length === 0) throw new UsageError('no rows found (one JSON object per line)');
279
- return rows;
280
- }
281
-
282
273
  // ---- commands: each is one API call
283
274
 
275
+ // blan db demo: the free test migration, on your own Postgres data. Your
276
+ // source goes into a temporary database of Blankthing's; the live feed
277
+ // carries what you write meanwhile; then every row, the counts and the
278
+ // checksums are printed for you to check against your source, with a
279
+ // read-only connection string to the destination, which is deleted when
280
+ // its window (30 minutes) ends.
284
281
  async function demo({ client, o, args, io, out }) {
285
- if (args.length) throw new UsageError('usage: blan db demo [--direction to-blankthing|from-blankthing] [--file ROWS.jsonl]');
286
- let dir = o.direction;
287
- if (!dir) {
288
- if (!io.stdin.isTTY) throw new UsageError('--direction to-blankthing|from-blankthing is required when not in a terminal');
289
- const a = await ask(io, 'Which way?\n 1) your test data -> Blankthing\n 2) Blankthing -> your side\nChoose 1 or 2: ');
290
- dir = { 1: 'to-blankthing', 2: 'from-blankthing' }[a];
291
- if (!dir) throw new UsageError(`"${a}" isn't 1 or 2`);
282
+ const usage = 'usage: blan db demo --from postgres://USER:PASSWORD@HOST:PORT/DB [--window SECONDS]';
283
+ if (args.length) throw new UsageError(usage);
284
+ let from = o.from || io.env.BLAN_PG_URL;
285
+ if (!from) {
286
+ if (!io.stdin.isTTY) throw new UsageError(`${usage}\n (or set BLAN_PG_URL)`);
287
+ from = await ask(io, 'Your source Postgres connection string (postgres://USER:PASSWORD@HOST:PORT/DB): ');
288
+ if (!from) throw new UsageError('no connection string given');
292
289
  }
293
- if (dir !== 'to-blankthing' && dir !== 'from-blankthing') {
294
- throw new UsageError('--direction must be to-blankthing or from-blankthing');
290
+ let window;
291
+ if (o.window !== undefined) {
292
+ window = Number(o.window);
293
+ if (!Number.isInteger(window) || window < 5 || window > 300) throw new UsageError('--window must be a whole number of seconds from 5 to 300');
295
294
  }
296
- const rows = dir === 'to-blankthing' ? await readRows(o, io) : undefined;
297
- const r = await client.demo(dir, rows);
295
+ const show = o.json ? () => {} : out;
296
+ const one = (row) => JSON.stringify(row);
297
+ if (!o.json) out(`demo: your Postgres -> a temporary Blankthing database (deleted 30 minutes after the run)`);
298
+ const r = await client.demo(from, window, (ev) => {
299
+ switch (ev.event) {
300
+ case 'step': show(` ${ev.step.padEnd(11)} ${ev.detail}`); break;
301
+ case 'live': show(`\n${icons.ok} ${ev.detail}`); break;
302
+ case 'write': show(` live ${String(ev.n).padStart(3)}/${ev.cap} ${ev.op.padEnd(8)} ${ev.table} ${ev.row ? one(ev.row) : ''}`); break;
303
+ case 'cap': show(`${icons.warn} ${ev.detail}`); break;
304
+ case 'verified': if (!o.json) printDemoVerified(out, ev); break;
305
+ case 'kept': show(`\n${icons.ok} the destination is yours to check, read-only, until ${fmtUntil(ev.until)}; then it is deleted:\n\n ${ev.url}\n\n e.g. psql "${ev.url}"`); break;
306
+ default: break;
307
+ }
308
+ });
298
309
  if (o.json) return r;
299
- out(`${icons.ok} demo ${r.direction}: ${r.source} -> ${r.destination}`);
300
- printSteps(out, r.steps);
301
- out(`\n${r.destination} now holds ${r.rows.length} row(s):`);
302
- for (const row of r.rows) out(` ${row}`);
303
- out('\nThat was a free test run in a sandbox; nothing was kept. Real moves: blan db migrate');
310
+ const fate = r.destination_url ? `the destination is deleted at ${fmtUntil(r.delete_at)} (the connection string above stops working then)`
311
+ : r.deleted ? 'the temporary destination is deleted' : 'the temporary destination could not be confirmed deleted; Blankthing will remove it';
312
+ out(`\n${r.match ? icons.ok : icons.fail} ${r.match ? 'match' : 'NO MATCH'}: ${fate}`);
313
+ out('That was your free demo (one per account). Real migrations: blan db migrate');
314
+ if (!r.match) throw new ApiError('your source and the destination differ', 0, {});
315
+ }
316
+
317
+ function fmtUntil(t) {
318
+ return String(t).replace('T', ' ').replace(/(\.\d+)?Z$/, ' UTC');
319
+ }
320
+
321
+ function printDemoVerified(out, v) {
322
+ const c = v.counts, live = v.live, pre = v.pre;
323
+ out(`\nVERIFICATION at your source's position ${v.verified_lsn}`);
324
+ out(['TABLE'.padEnd(24), 'SOURCE ROWS'.padStart(12), 'DEST ROWS'.padStart(10), ' CHECKSUM (md5, source = dest)'].join(''));
325
+ for (const t of v.tables) {
326
+ let sum;
327
+ if (t.cut) sum = 'left out: truncated on your source past the live cap';
328
+ else sum = t.match ? `${t.source_md5 || '(empty)'} match` : `${t.source_md5 || '-'} != ${t.dest_md5 || '-'}`;
329
+ out([t.table.padEnd(24), String(t.source_rows).padStart(12), String(t.dest_rows).padStart(10), ` ${sum}`].join(''));
330
+ }
331
+ out(` rows: ${c.source} on your source (those the demo copied or carried) = ${c.destination} on the destination`);
332
+ if (pre.source_rows > pre.copied) out(` pre-stored: your source held ${pre.source_rows} rows; the first ${pre.copied} were copied (cap ${pre.cap})`);
333
+ else out(` pre-stored: all ${pre.copied} of your rows were copied (cap ${pre.cap})`);
334
+ out(` live writes: ${live.carried} carried (cap ${live.cap})` +
335
+ (live.dropped ? `; ${live.dropped} more arrived past the cap and were NOT carried` : '') +
336
+ (live.outside ? `; ${live.outside} touched rows outside the first ${pre.cap} and were not carried` : ''));
337
+ if (c.excluded) out(` ${c.excluded} row(s) changed on your source after the cap; the destination keeps them as they were, so they are left out of the checksum`);
338
+ if (v.exact) out(` your whole source (${c.source_total} rows) equals the destination: an exact match`);
339
+ else out(` your whole source holds ${c.source_total} rows; the demo's caps carried ${c.source} of them, and those match`);
340
+ const tables = Object.keys(v.rows || {});
341
+ const n = tables.reduce((a, t) => a + v.rows[t].length, 0);
342
+ out(`\nFULL DATA on the destination (${n} rows), to check against your source:`);
343
+ for (const t of tables) {
344
+ out(` ${t} (${v.rows[t].length} rows)`);
345
+ for (const row of v.rows[t]) out(` ${JSON.stringify(row)}`);
346
+ }
347
+ out('');
304
348
  }
305
349
 
306
350
  async function init({ client, o, args, io, out }) {
package/src/client.js CHANGED
@@ -32,6 +32,40 @@ function send(method, url, headers, body) {
32
32
  });
33
33
  }
34
34
 
35
+ // stream POSTs body and calls onEvent with each JSON line of a streamed
36
+ // (application/x-ndjson) reply as it arrives. A plain JSON reply (a
37
+ // refusal) is returned as { res, text } for request() to read.
38
+ function stream(url, headers, body, onEvent) {
39
+ return new Promise((resolve, reject) => {
40
+ const u = new URL(url);
41
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
42
+ if (!lib) return reject(new Error(`unsupported protocol ${u.protocol}`));
43
+ headers['Content-Length'] = Buffer.byteLength(body);
44
+ const req = lib.request(u, { method: 'POST', headers }, (res) => {
45
+ const ndjson = String(res.headers['content-type'] || '').startsWith('application/x-ndjson');
46
+ let text = '';
47
+ res.setEncoding('utf8');
48
+ res.on('data', (c) => {
49
+ text += c;
50
+ if (!ndjson) return;
51
+ let i;
52
+ while ((i = text.indexOf('\n')) >= 0) {
53
+ const line = text.slice(0, i).trim();
54
+ text = text.slice(i + 1);
55
+ if (line) onEvent(JSON.parse(line));
56
+ }
57
+ });
58
+ res.on('end', () => {
59
+ if (ndjson && text.trim()) onEvent(JSON.parse(text));
60
+ resolve({ res, text: ndjson ? null : text });
61
+ });
62
+ res.on('error', reject);
63
+ });
64
+ req.on('error', reject);
65
+ req.end(body);
66
+ });
67
+ }
68
+
35
69
  export function makeClient({ server = DEFAULT_SERVER, token, service = 'blan_db' } = {}) {
36
70
  const base = server.replace(/\/+$/, '');
37
71
 
@@ -61,9 +95,32 @@ export function makeClient({ server = DEFAULT_SERVER, token, service = 'blan_db'
61
95
  return data;
62
96
  }
63
97
 
98
+ // A streamed call: onEvent sees every line; the last (result or error) is returned.
99
+ async function streamed(path, body, onEvent) {
100
+ const headers = { Accept: 'application/x-ndjson, application/json', 'Content-Type': 'application/json' };
101
+ if (token) headers.Authorization = `Bearer ${token}`;
102
+ let last;
103
+ let reply;
104
+ try {
105
+ reply = await stream(base + path, headers, JSON.stringify(body), (ev) => { last = ev; onEvent(ev); });
106
+ } catch (err) {
107
+ if (err instanceof SyntaxError) throw new ApiError(`${service} sent an unreadable reply`, 0);
108
+ throw new ApiError(`can't reach ${service} at ${base} (${err.code || err.message})`, 0);
109
+ }
110
+ const { res, text } = reply;
111
+ if (text !== null) { // a plain JSON reply: a refusal before the run started
112
+ let data;
113
+ try { data = JSON.parse(text); } catch { throw new ApiError(`${service} sent an unreadable reply (HTTP ${res.statusCode})`, res.statusCode, text); }
114
+ throw new ApiError(data.error || `HTTP ${res.statusCode}`, res.statusCode, data);
115
+ }
116
+ if (!last) throw new ApiError(`${service} ended the reply early`, res.statusCode);
117
+ if (last.event === 'error') throw new ApiError(last.error, res.statusCode, last);
118
+ return last;
119
+ }
120
+
64
121
  return {
65
122
  init: (engine, name, url) => request('POST', '/v1/db/init', { engine, name, url }),
66
- demo: (direction, rows) => request('POST', '/v1/db/demo', rows ? { direction, rows } : { direction }),
123
+ demo: (from, window, onEvent) => streamed('/v1/db/demo', window ? { from, window } : { from }, onEvent),
67
124
  migrate: (req) => request('POST', '/v1/db/migrate', req),
68
125
  status: (store) => request('GET', '/v1/db/status' + (store ? `?store=${encodeURIComponent(store)}` : '')),
69
126
  retire: (source) => request('POST', '/v1/db/retire', { source }),