@north-light/api 0.3.742 → 0.3.743

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.
@@ -25,3 +25,5 @@ export interface CopyInput {
25
25
  export declare const copyOrder: (catalog: Catalog) => string[];
26
26
  /** Must run inside `withCanvasWrite`. */
27
27
  export declare function copyRows(input: CopyInput): Promise<CopyResult>;
28
+ /** Adds keys to a table's manifest row, creating it when the copy inserted no row of that table. */
29
+ export declare function appendManifest(tx: CanvasDb, runId: string, table: string, keys: string[][]): Promise<void>;
@@ -61,6 +61,9 @@ export async function copyRows(input) {
61
61
  await db.prepareUncached(`UPDATE ${S('review_comments')} c SET created_seq = m.target_key::bigint FROM import_key_map m
62
62
  WHERE m.source_install_id = ? AND m.table_name = 'review_comment_events' AND m.source_key = c.created_seq::text`).run(source.installId);
63
63
  const order = copyOrder(catalog);
64
+ // Rows the fill step creates have no staged row: kept in staging for verify, and appended to the manifest after the loop so rollback removes them.
65
+ await db.exec(`CREATE TABLE IF NOT EXISTS ${S('_filled')} (tbl text NOT NULL, k jsonb NOT NULL)`);
66
+ const filled = [];
64
67
  for (const table of order) {
65
68
  if (table in KEY_MAPPED_TABLES)
66
69
  continue;
@@ -68,7 +71,7 @@ export async function copyRows(input) {
68
71
  if (table === 'profiles') {
69
72
  if (order.indexOf('identities') > order.indexOf('profiles'))
70
73
  throw new ImportLaneError('copy', 'bundle_invalid', 'identities must be copied before profiles');
71
- await fillEnvironments(db, schema, target, source, input.person);
74
+ filled.push(...await fillEnvironments(db, schema, target, source, input.person));
72
75
  }
73
76
  const info = catalog.tables.get(table);
74
77
  const staged = Number((await db.prepareUncached(`SELECT count(*) AS n FROM ${S(table)}`).get()).n);
@@ -115,6 +118,10 @@ export async function copyRows(input) {
115
118
  await manifest(table, inserted.map((row) => Object.values(row)));
116
119
  result.mapped[table] = staged - inserted.length;
117
120
  }
121
+ for (const f of filled)
122
+ await db.prepare(`INSERT INTO ${S('_filled')} VALUES (?, ?::jsonb)`).run(f.table, JSON.stringify(f.key));
123
+ for (const table of new Set(filled.map((f) => f.table)))
124
+ await appendManifest(db, runId, table, filled.filter((f) => f.table === table).map((f) => f.key));
118
125
  // The rollup is recomputed from the copied charges for every (month, payer) the bundle held: an additive upsert would double on a rerun.
119
126
  await db.prepareUncached(`DELETE FROM ${T('charge_totals')} t WHERE (t.month, t.payer) IN (SELECT DISTINCT month, payer FROM ${S('charges')})`).run();
120
127
  await db.prepareUncached(`INSERT INTO ${T('charge_totals')} (month, payer, funding, sub, grantee, provider, usd, billed_usd)
@@ -130,3 +137,13 @@ export async function copyRows(input) {
130
137
  await db.prepare("UPDATE import_runs SET state = 'committed', committed_at = ?, step = 'copy' WHERE run_id = ?").run(new Date().toISOString(), runId);
131
138
  return result;
132
139
  }
140
+ /** Adds keys to a table's manifest row, creating it when the copy inserted no row of that table. */
141
+ export async function appendManifest(tx, runId, table, keys) {
142
+ if (keys.length === 0)
143
+ return;
144
+ const existing = await tx.prepare('SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?').get(runId, table);
145
+ if (existing === undefined)
146
+ await tx.prepare('INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)').run(runId, table, encodeKeys(keys));
147
+ else
148
+ await tx.prepare('UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?').run(encodeKeys([...decodeKeys(existing.inserted_keys), ...keys]), runId, table);
149
+ }
@@ -36,9 +36,17 @@ export declare function dropExistingWatches(db: CanvasDb, schema: string, target
36
36
  watches: number;
37
37
  watch_subscriptions: number;
38
38
  }>;
39
+ /** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
40
+ * row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
41
+ export declare function dropExistingIdempotencyKeys(db: CanvasDb, schema: string, target: string): Promise<number>;
42
+ /** The rows `fillEnvironments` created, as manifest keys per table, so rollback removes them and verify (which has no staged row for them) skips them. */
43
+ export interface FilledRow {
44
+ table: string;
45
+ key: string[];
46
+ }
39
47
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
40
48
  * absent). Runs in the copy transaction: it writes target objects. */
41
- export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<number>;
49
+ export declare function fillEnvironments(tx: CanvasDb, schema: string, target: string, source: SourceJson, person: string): Promise<FilledRow[]>;
42
50
  /** Staged edits that need nothing from the target but its key map: limits the directory or an operator wrote stay out, a hosted source's own
43
51
  * machine environment is marked for the drop step, claims of the old runtime's lanes are cleared, and rows of the identity-keyed tables already in
44
52
  * `import_key_map` are not staged again. Returns the rows removed per table. */
@@ -120,22 +120,35 @@ export async function dropExistingWatches(db, schema, target) {
120
120
  const watches = await db.prepareUncached(`DELETE FROM ${sq(schema, 'watches')} s WHERE EXISTS (SELECT 1 ${same})`).run();
121
121
  return { watches: Number(watches.changes), watch_subscriptions: Number(subs.changes) };
122
122
  }
123
+ /** A staged idempotency key whose (grantee, key) the target already holds is already imported (a hosted person's runs the control plane has since served): it is dropped, the target's
124
+ * row stands, so the copy never inserts it and verify never compares it. Only this key is skipped; any other difference still fails. Returns the dropped rows. Runs before the pre-check. */
125
+ export async function dropExistingIdempotencyKeys(db, schema, target) {
126
+ const done = await db.prepareUncached(`DELETE FROM ${sq(schema, 'idempotency_keys')} s WHERE EXISTS (SELECT 1 FROM ${sq(target, 'idempotency_keys')} t WHERE t.grantee = s.grantee AND t.key = s.key)`).run();
127
+ return Number(done.changes);
128
+ }
123
129
  /** Fill: a staged profile with no environment gets the source's machine environment (a Mac) or the person's Blaxel environment (hosted, created if
124
130
  * absent). Runs in the copy transaction: it writes target objects. */
125
131
  export async function fillEnvironments(tx, schema, target, source, person) {
126
132
  const S = (t) => sq(schema, t);
127
- let filled = 0;
133
+ const filled = [];
128
134
  const profiles = await tx.prepareUncached(`SELECT id, grantee FROM ${S('profiles')} WHERE environment_id IS NULL ORDER BY id`).all();
129
135
  for (const profile of profiles) {
130
136
  let environment = source.kind === 'machine' ? source.environmentObject ?? null : null;
131
137
  if (source.kind === 'hosted') {
132
138
  const existing = await tx.prepareUncached(`SELECT environment_id FROM ${sq(target, 'profiles')} WHERE id = ?`).get(profile.id);
133
- environment = existing?.environment_id ?? await createProfileBlaxelEnvironment(tx, { profileId: profile.id, grantee: profile.grantee ?? 'app:terminal', person });
139
+ if (existing?.environment_id != null)
140
+ environment = existing.environment_id;
141
+ else {
142
+ environment = await createProfileBlaxelEnvironment(tx, { profileId: profile.id, grantee: profile.grantee ?? 'app:terminal', person });
143
+ filled.push({ table: 'objects', key: [environment] }, { table: 'environments', key: [environment] });
144
+ for (const r of await tx.prepareUncached('SELECT resource_type, resource_id, relation, subject_type, subject_id, subject_relation FROM relations WHERE resource_id = ?').all(environment)) {
145
+ filled.push({ table: 'relations', key: [r['resource_type'], r['resource_id'], r['relation'], r['subject_type'], r['subject_id'], r['subject_relation']] });
146
+ }
147
+ }
134
148
  }
135
149
  if (environment === null)
136
150
  throw new ImportLaneError('fill', 'bundle_invalid', `profile ${profile.id} has no environment and the source names none`);
137
151
  await tx.prepareUncached(`UPDATE ${S('profiles')} SET environment_id = ? WHERE id = ?`).run(environment, profile.id);
138
- filled += 1;
139
152
  }
140
153
  return filled;
141
154
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.742",
3
+ "version": "0.3.743",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",