@celilo/cli 0.5.0-alpha.3 → 0.5.0-alpha.5

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.
package/src/db/client.ts CHANGED
@@ -41,145 +41,6 @@ export function findMigrationsFolder(): string {
41
41
  throw new Error(`Could not find drizzle migrations folder. Tried: ${candidates.join(', ')}`);
42
42
  }
43
43
 
44
- /**
45
- * Check if database needs initialization (tables don't exist)
46
- */
47
- function needsMigration(sqlite: Database): boolean {
48
- try {
49
- // Check if the modules table exists at all (new database)
50
- const result = sqlite
51
- .query("SELECT name FROM sqlite_master WHERE type='table' AND name='modules'")
52
- .get();
53
- if (!result) return true; // New database — run full migrations
54
-
55
- // Existing database — apply incremental schema updates
56
- // Each statement is wrapped in try/catch (no-op if already applied)
57
- const alterStatements = [
58
- 'ALTER TABLE capabilities ADD zones text',
59
- 'ALTER TABLE machines ADD earmarked_module text',
60
- // web_routes' subdomain/custom_domain columns were folded into a
61
- // single `hostname` field by migration 0004. Don't re-add them
62
- // here — the migration drops and recreates the table.
63
- // Backup system tables (Phase 1)
64
- `CREATE TABLE IF NOT EXISTS backup_storages (
65
- id text PRIMARY KEY NOT NULL,
66
- storage_id text NOT NULL UNIQUE,
67
- name text NOT NULL,
68
- provider_name text NOT NULL,
69
- credentials_encrypted text NOT NULL,
70
- provider_config text NOT NULL,
71
- verified integer DEFAULT 0 NOT NULL,
72
- verified_at integer,
73
- verification_error text,
74
- is_default integer DEFAULT 0 NOT NULL,
75
- created_at integer DEFAULT (unixepoch()) NOT NULL,
76
- updated_at integer DEFAULT (unixepoch()) NOT NULL
77
- )`,
78
- `CREATE TABLE IF NOT EXISTS backups (
79
- id text PRIMARY KEY NOT NULL,
80
- module_id text REFERENCES modules(id) ON DELETE SET NULL,
81
- storage_id text NOT NULL REFERENCES backup_storages(id),
82
- storage_path text NOT NULL,
83
- backup_type text NOT NULL,
84
- module_version text,
85
- schema_version text,
86
- size_bytes integer,
87
- metadata text DEFAULT '{}' NOT NULL,
88
- status text DEFAULT 'in_progress' NOT NULL,
89
- error_message text,
90
- started_at integer DEFAULT (unixepoch()) NOT NULL,
91
- completed_at integer
92
- )`,
93
- // Backup naming support
94
- 'ALTER TABLE backups ADD name text',
95
- // Module systems (v2/MODULE_SYSTEMS_ADDRESSING.md) — a module's 0..N
96
- // deployed hosts. Fresh DBs get this via migration 0007; existing installs
97
- // get it here. Replaces the scalar target_ip/vmid rows in module_configs.
98
- `CREATE TABLE IF NOT EXISTS module_systems (
99
- module_id text NOT NULL REFERENCES modules(id) ON DELETE cascade,
100
- name text NOT NULL,
101
- hostname text NOT NULL,
102
- ipv4_address text NOT NULL,
103
- zone text NOT NULL,
104
- infra_type text NOT NULL,
105
- machine_id text REFERENCES machines(id),
106
- service_id text REFERENCES container_services(id),
107
- vmid integer,
108
- created_at integer DEFAULT (unixepoch()) NOT NULL,
109
- updated_at integer DEFAULT (unixepoch()) NOT NULL,
110
- PRIMARY KEY (module_id, name)
111
- )`,
112
- // Aspect consent decision (ISS-0027). Fresh DBs get this via migration
113
- // 0008; existing installs get it here. Defaults to true so pre-existing
114
- // rows (all approvals) keep running; false = a durable refusal.
115
- 'ALTER TABLE aspect_approvals ADD consented integer DEFAULT true NOT NULL',
116
- ];
117
-
118
- for (const stmt of alterStatements) {
119
- try {
120
- sqlite.exec(stmt);
121
- } catch {
122
- // Column already exists — fine
123
- }
124
- }
125
-
126
- // web_routes hostname migration (CADDY_HOSTNAME_LIST design).
127
- // Drizzle's auto-migrate path (`migrate()`) only runs for fresh
128
- // databases — for existing celilo installs we apply the schema
129
- // change here. Phase 0 + no production users = destructive
130
- // rebuild; modules repopulate routes on their next deploy.
131
- try {
132
- const cols = sqlite.query("SELECT name FROM pragma_table_info('web_routes')").all() as Array<{
133
- name: string;
134
- }>;
135
- const hasHostname = cols.some((c) => c.name === 'hostname');
136
- const hasOldColumns = cols.some((c) => c.name === 'subdomain' || c.name === 'custom_domain');
137
- if (!hasHostname && cols.length > 0) {
138
- // Old shape detected (or missing hostname) — drop and recreate.
139
- // Wrap in a transaction so the table is never half-migrated.
140
- sqlite.exec('BEGIN');
141
- try {
142
- sqlite.exec('DROP TABLE web_routes');
143
- sqlite.exec(`CREATE TABLE web_routes (
144
- id integer PRIMARY KEY AUTOINCREMENT NOT NULL,
145
- slug text NOT NULL,
146
- module_id text NOT NULL,
147
- type text NOT NULL,
148
- path text NOT NULL,
149
- hostname text NOT NULL,
150
- target_host text,
151
- target_port integer,
152
- websocket integer DEFAULT false NOT NULL,
153
- content_hash text,
154
- created_at integer DEFAULT (unixepoch()) NOT NULL,
155
- updated_at integer DEFAULT (unixepoch()) NOT NULL,
156
- FOREIGN KEY (module_id) REFERENCES modules(id) ON UPDATE no action ON DELETE cascade
157
- )`);
158
- sqlite.exec(
159
- 'CREATE UNIQUE INDEX web_routes_hostname_path_idx ON web_routes (hostname, path)',
160
- );
161
- sqlite.exec('COMMIT');
162
- if (hasOldColumns) {
163
- console.log(
164
- 'web_routes migrated to hostname-based schema. Modules will repopulate their routes on next deploy.',
165
- );
166
- }
167
- } catch (err) {
168
- sqlite.exec('ROLLBACK');
169
- throw err;
170
- }
171
- }
172
- } catch (err) {
173
- console.error('Failed to migrate web_routes schema:', err);
174
- throw err;
175
- }
176
-
177
- return false; // Schema is up to date
178
- } catch {
179
- return true;
180
- }
181
- }
182
-
183
44
  /**
184
45
  * Create database client and run migrations if needed
185
46
  */
@@ -209,12 +70,21 @@ export function createDbClient(config?: Partial<DatabaseConfig>) {
209
70
 
210
71
  const db = drizzle(sqlite, { schema });
211
72
 
212
- // Auto-run migrations if database is new
213
- if (!readonly && needsMigration(sqlite)) {
73
+ // Apply migrations on open (ISS-0100). Drizzle's migrator is the single
74
+ // migration mechanism for ALL DBs — fresh and existing — and the only place
75
+ // schema changes live (the old imperative hand-list is gone). migrate() is
76
+ // idempotent: it applies every migration newer than the latest recorded in
77
+ // `__drizzle_migrations` and no-ops once current.
78
+ //
79
+ // One-time caveat (ISS-0100): an existing DB from the hand-list era has a
80
+ // frozen `__drizzle_migrations` watermark; it must be remediated by hand
81
+ // (stamp the watermark to the latest migration + create any missing table)
82
+ // BEFORE this code opens it, or migrate() re-runs already-applied migrations
83
+ // and throws. `celilo system doctor` (checkSchemaDrift) detects the drift.
84
+ if (!readonly) {
214
85
  try {
215
86
  const migrationsFolder = findMigrationsFolder();
216
87
  migrate(db, { migrationsFolder });
217
- console.log('Database initialized with migrations');
218
88
  } catch (error) {
219
89
  console.error('Failed to run migrations:', error);
220
90
  throw error;
@@ -222,10 +92,9 @@ export function createDbClient(config?: Partial<DatabaseConfig>) {
222
92
  }
223
93
 
224
94
  // One-time upgrade backfill for the target_ip → module_systems refactor
225
- // (v2/MODULE_SYSTEMS_ADDRESSING.md). Runs for both paths above: needsMigration
226
- // has already ensured the module_systems table exists (via migration 0007 for
227
- // a fresh DB, or the imperative CREATE for an existing install). A deployment
228
- // created before the refactor has its host data only in module_configs /
95
+ // (v2/MODULE_SYSTEMS_ADDRESSING.md). migrate() above has ensured the
96
+ // module_systems table exists (migration 0007). A deployment created before
97
+ // the refactor has its host data only in module_configs /
229
98
  // ip_allocations / module_infrastructure and an EMPTY module_systems, so its
230
99
  // modules resolve to no system and the migrated hooks throw "No deployed
231
100
  // system found". This lifts that state across. Idempotent (skips modules
package/src/db/migrate.ts CHANGED
@@ -1,17 +1,25 @@
1
1
  import { migrate } from 'drizzle-orm/bun-sqlite/migrator';
2
- import { closeDb, createDbClient, findMigrationsFolder } from './client';
2
+ import { type DbClient, closeDb, createDbClient, findMigrationsFolder } from './client';
3
3
 
4
4
  /**
5
- * Run database migrations
5
+ * Apply pending drizzle migrations to an open DB. Idempotent — drizzle applies
6
+ * only migrations newer than the latest recorded in `__drizzle_migrations`.
7
+ * The single migration mechanism (ISS-0100); createDbClient also calls this
8
+ * shape on open (auto-migrate).
9
+ */
10
+ export function runMigrationsOn(db: DbClient): void {
11
+ migrate(db, { migrationsFolder: findMigrationsFolder() });
12
+ }
13
+
14
+ /**
15
+ * Run database migrations (standalone entrypoint — `bun run src/db/migrate.ts`).
16
+ * createDbClient already migrates on open; this re-asserts for explicit use.
6
17
  */
7
18
  export async function runMigrations(dbPath?: string) {
8
19
  console.log('Running database migrations...');
9
-
10
20
  const db = createDbClient(dbPath ? { path: dbPath } : undefined);
11
-
12
21
  try {
13
- const migrationsFolder = findMigrationsFolder();
14
- await migrate(db, { migrationsFolder });
22
+ runMigrationsOn(db);
15
23
  console.log('Migrations completed successfully');
16
24
  } catch (error) {
17
25
  console.error('Migration failed:', error);
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Schema introspection — compare the DB's actual tables/columns against the
3
+ * tables the running code's drizzle schema declares. The single source for
4
+ * "what does the code expect, and is it present?" shared by:
5
+ * - the migration baseline (db/migrate.ts) — to decide which migrations are
6
+ * already applied on an existing DB before running migrate() (ISS-0100), and
7
+ * - the doctor's schema-drift check (services/fleet-checks.ts) — to report
8
+ * missing tables/columns to the operator (ISS-0113).
9
+ */
10
+
11
+ import type { Database } from 'bun:sqlite';
12
+ import { is } from 'drizzle-orm';
13
+ import { SQLiteTable, getTableConfig } from 'drizzle-orm/sqlite-core';
14
+ import * as dbSchema from './schema';
15
+
16
+ export interface SchemaDrift {
17
+ /** Tables the code's schema declares that the DB lacks. */
18
+ missingTables: string[];
19
+ /** `table.column` the code declares that the DB's table lacks. */
20
+ missingColumns: string[];
21
+ /** Total number of tables the code's schema declares. */
22
+ tableCount: number;
23
+ }
24
+
25
+ /** Every table name + column names the drizzle schema declares. */
26
+ export function getSchemaTables(): Array<{ name: string; columns: string[] }> {
27
+ const out: Array<{ name: string; columns: string[] }> = [];
28
+ for (const value of Object.values(dbSchema)) {
29
+ if (!is(value, SQLiteTable)) continue;
30
+ const cfg = getTableConfig(value);
31
+ out.push({ name: cfg.name, columns: cfg.columns.map((c) => c.name) });
32
+ }
33
+ return out;
34
+ }
35
+
36
+ /** Names of all tables that physically exist in the DB. */
37
+ export function getExistingTables(sqlite: Database): Set<string> {
38
+ return new Set(
39
+ sqlite
40
+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='table'")
41
+ .all()
42
+ .map((r) => r.name),
43
+ );
44
+ }
45
+
46
+ /** Names of all indexes that physically exist in the DB. */
47
+ export function getExistingIndexes(sqlite: Database): Set<string> {
48
+ return new Set(
49
+ sqlite
50
+ .query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type='index'")
51
+ .all()
52
+ .map((r) => r.name),
53
+ );
54
+ }
55
+
56
+ /** Column names physically present on a table (empty if the table is absent). */
57
+ export function getExistingColumns(sqlite: Database, table: string): Set<string> {
58
+ // `table` is a schema/migration identifier (never user input) — safe to inline.
59
+ return new Set(
60
+ sqlite
61
+ .query<{ name: string }, []>(`SELECT name FROM pragma_table_info('${table}')`)
62
+ .all()
63
+ .map((r) => r.name),
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Compare the running code's drizzle schema to the DB and report what's missing.
69
+ * Track-agnostic: it reads actual table/column presence, so it's honest whether
70
+ * the DB was migrated, baselined, or hand-patched.
71
+ */
72
+ export function findSchemaDrift(sqlite: Database): SchemaDrift {
73
+ const present = getExistingTables(sqlite);
74
+ const missingTables: string[] = [];
75
+ const missingColumns: string[] = [];
76
+ const tables = getSchemaTables();
77
+ for (const t of tables) {
78
+ if (!present.has(t.name)) {
79
+ missingTables.push(t.name);
80
+ continue;
81
+ }
82
+ const cols = getExistingColumns(sqlite, t.name);
83
+ for (const c of t.columns) {
84
+ if (!cols.has(c)) missingColumns.push(`${t.name}.${c}`);
85
+ }
86
+ }
87
+ return { missingTables, missingColumns, tableCount: tables.length };
88
+ }
package/src/db/schema.ts CHANGED
@@ -468,6 +468,44 @@ export const dnsRegistrations = sqliteTable(
468
468
  }),
469
469
  );
470
470
 
471
+ /**
472
+ * Internal split-horizon DNS A-record ledger. Mirrors `dns_registrations`
473
+ * but for the dns_internal capability (technitium/knot): the capability
474
+ * loader records every `dns_internal.registerRecord({type:'A'})` here so
475
+ * celilo has an offline, queryable record of what hostname → IP it asked
476
+ * the internal resolver to serve. Without this, the only source of truth
477
+ * is the resolver's own DB, requiring a live probe (ISS-0094 / ISS-0111).
478
+ *
479
+ * `celilo system doctor` reads this to assert service hostnames resolve to
480
+ * the firewall natIp (LAN-reachable) and not a zone-side container IP that
481
+ * a LAN device can't route to. Rows die with either module via FK cascade.
482
+ */
483
+ export const dnsInternalRecords = sqliteTable(
484
+ 'dns_internal_records',
485
+ {
486
+ id: integer('id').primaryKey({ autoIncrement: true }),
487
+ providerModuleId: text('provider_module_id')
488
+ .notNull()
489
+ .references(() => modules.id, { onDelete: 'cascade' }),
490
+ consumerModuleId: text('consumer_module_id')
491
+ .notNull()
492
+ .references(() => modules.id, { onDelete: 'cascade' }),
493
+ /** The registered hostname (e.g. "git-ssh.git.celilo.computer"). */
494
+ host: text('host').notNull(),
495
+ /** The A-record value celilo asked the resolver to serve. */
496
+ ip: text('ip').notNull(),
497
+ registeredAt: integer('registered_at', { mode: 'timestamp' })
498
+ .notNull()
499
+ .default(sql`(unixepoch())`),
500
+ },
501
+ (table) => ({
502
+ providerHostUnique: uniqueIndex('dns_internal_records_provider_host_idx').on(
503
+ table.providerModuleId,
504
+ table.host,
505
+ ),
506
+ }),
507
+ );
508
+
471
509
  /**
472
510
  * Backup storage providers - destinations for backup archives
473
511
  * Supports local filesystem and S3-compatible storage (AWS S3, MinIO, Backblaze B2, Wasabi)
@@ -31,6 +31,7 @@ import { decryptSecret } from '../secrets/encryption';
31
31
  import { getOrCreateMasterKey } from '../secrets/master-key';
32
32
  import { emitWebRoutesChangedAndWait } from '../services/celilo-events';
33
33
  import { getModuleSystems } from '../services/deployed-systems';
34
+ import { withDnsInternalLedger } from '../services/dns-internal-records';
34
35
  import { withDnsRegistrationLedger } from '../services/dns-registrations';
35
36
  import { loadHookConfigMap } from './load-hook-config';
36
37
 
@@ -62,6 +63,10 @@ const CAPABILITY_MODULE_MAP: Record<string, { script: string; legacyFactoryName:
62
63
  script: 'scripts/idp-functions.ts',
63
64
  legacyFactoryName: 'createIdp',
64
65
  },
66
+ git_forge: {
67
+ script: 'scripts/git-forge-functions.ts',
68
+ legacyFactoryName: 'createForgejoGitForge',
69
+ },
65
70
  dhcp_server: {
66
71
  script: 'scripts/dhcp-server-functions.ts',
67
72
  legacyFactoryName: 'default',
@@ -196,19 +201,27 @@ export async function loadCapabilityFunctions(
196
201
  const providerConfig = await loadModuleConfig(capability.moduleId, db);
197
202
  const providerSecrets = await loadModuleSecrets(capability.moduleId, masterKey, db);
198
203
 
199
- // dns_registrar interfaces get the registration-ledger wrapper:
200
- // every successful registerHost is recorded in dns_registrations so
201
- // the provider's refresh_registrations hook can re-assert it later
202
- // (designs/DISPATCHER_DAEMON_AND_TIMER_EVENTS.md B2). The loader is
203
- // the one layer that knows both provider and consumer.
204
- const withLedgerIfDnsRegistrar = (iface: unknown): unknown =>
205
- capName === 'dns_registrar'
206
- ? withDnsRegistrationLedger(iface as DnsRegistrarCapability, {
207
- db,
208
- providerModuleId: capability.moduleId,
209
- consumerModuleId: consumingModuleId,
210
- })
211
- : iface;
204
+ // dns_registrar and dns_internal interfaces get a registration-ledger
205
+ // wrapper: every successful registerHost / registerRecord is recorded so
206
+ // celilo has an offline record of what it asked DNS to serve. The
207
+ // external ledger feeds the provider's refresh_registrations hook
208
+ // (DISPATCHER_DAEMON_AND_TIMER_EVENTS.md B2); the internal ledger feeds
209
+ // the doctor's natIp drift check (CELILO_DOCTOR_FLEET_DRIFT.md Phase 4).
210
+ // The loader is the one layer that knows both provider and consumer.
211
+ const ledgerCtx = {
212
+ db,
213
+ providerModuleId: capability.moduleId,
214
+ consumerModuleId: consumingModuleId,
215
+ };
216
+ const withLedger = (iface: unknown): unknown => {
217
+ if (capName === 'dns_registrar') {
218
+ return withDnsRegistrationLedger(iface as DnsRegistrarCapability, ledgerCtx);
219
+ }
220
+ if (capName === 'dns_internal') {
221
+ return withDnsInternalLedger(iface as DnsInternalCapability, ledgerCtx);
222
+ }
223
+ return iface;
224
+ };
212
225
 
213
226
  try {
214
227
  // Dynamically import the capability module. Try the default export
@@ -233,7 +246,7 @@ export async function loadCapabilityFunctions(
233
246
  systems: getModuleSystems(capability.moduleId, db),
234
247
  logger,
235
248
  });
236
- result[capName] = withLedgerIfDnsRegistrar(capabilityInterface);
249
+ result[capName] = withLedger(capabilityInterface);
237
250
  debugLog(`${capName}: loaded via defineCapabilityFunction`);
238
251
  continue;
239
252
  }
@@ -249,7 +262,7 @@ export async function loadCapabilityFunctions(
249
262
  );
250
263
 
251
264
  if (capabilityInterface) {
252
- result[capName] = withLedgerIfDnsRegistrar(
265
+ result[capName] = withLedger(
253
266
  wrapWithLogging(capabilityInterface as object, logger, capName),
254
267
  );
255
268
  debugLog(`${capName}: loaded via legacy factory`);
@@ -29,6 +29,7 @@ import { capabilities, moduleConfigs, modules, secrets } from '../db/schema';
29
29
  import { type ModuleManifest, getSingularSystemSpec } from '../manifest/schema';
30
30
  import { buildResolutionContext } from '../variables/context';
31
31
  import { E2E_CONFLICT_FIX, runningE2eContainers } from './e2e-guard';
32
+ import { describeCapabilityProblem, findBrokenCapabilityDerivations } from './fleet-checks';
32
33
 
33
34
  export interface PreflightResult {
34
35
  success: boolean;
@@ -232,6 +233,30 @@ export async function runPreflight(
232
233
  });
233
234
  }
234
235
  }
236
+
237
+ // 4b. Capability-derived variables resolve to a concrete value. The
238
+ // scan above only catches values that ARE present-but-templated; a
239
+ // required `source: capability` var whose chain is broken upstream is
240
+ // silently DROPPED during derivation (the hasUnresolved guard), so it's
241
+ // absent from selfConfig entirely and a template `$self:<x>` later dies
242
+ // with a cryptic "not found". Assert it here against the RESOLVED
243
+ // capabilities map so the operator gets the named missing link up front
244
+ // instead of at generate time (ISS-0095 / ISS-0115).
245
+ for (const problem of findBrokenCapabilityDerivations(
246
+ moduleId,
247
+ manifest,
248
+ context.capabilities,
249
+ )) {
250
+ errors.push({
251
+ category: problem.reason === 'no-provider' ? 'missing-capability' : 'unresolved-template',
252
+ message: describeCapabilityProblem(problem),
253
+ variable: problem.variable,
254
+ suggestion:
255
+ problem.reason === 'no-provider'
256
+ ? `Deploy a module that provides '${problem.capability}', then redeploy '${moduleId}'`
257
+ : `Redeploy '${problem.capability}'s provider so it populates ${problem.capability}.${problem.path}, then redeploy '${moduleId}'`,
258
+ });
259
+ }
235
260
  } catch (error) {
236
261
  // Resolution context may fail — that's informative too
237
262
  warnings.push({
@@ -0,0 +1,126 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
2
+ import { mkdtempSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import type { DnsRecordRequest } from '@celilo/capabilities';
6
+ import type { DbClient } from '../db/client';
7
+ import { modules } from '../db/schema';
8
+ import { setupTestDatabase } from '../test-utils/setup-test-db';
9
+ import {
10
+ listDnsInternalRecords,
11
+ recordDnsInternalRecord,
12
+ removeDnsInternalRecord,
13
+ withDnsInternalLedger,
14
+ } from './dns-internal-records';
15
+
16
+ describe('dns-internal-records ledger', () => {
17
+ let dir: string;
18
+ let dbPath: string;
19
+ let db: DbClient;
20
+
21
+ beforeEach(async () => {
22
+ dir = mkdtempSync(join(tmpdir(), 'dns-int-'));
23
+ dbPath = join(dir, 'celilo.db');
24
+ process.env.CELILO_DB_PATH = dbPath;
25
+ db = await setupTestDatabase(dbPath);
26
+ // FK targets: provider + consumer modules.
27
+ for (const id of ['technitium', 'forgejo']) {
28
+ db.insert(modules)
29
+ .values({
30
+ id,
31
+ name: id,
32
+ version: '1.0.0',
33
+ state: 'VERIFIED',
34
+ manifestData: {},
35
+ sourcePath: `/src/${id}`,
36
+ })
37
+ .run();
38
+ }
39
+ });
40
+ afterEach(() => {
41
+ db.$client.close();
42
+ process.env.CELILO_DB_PATH = undefined;
43
+ try {
44
+ rmSync(dir, { recursive: true, force: true });
45
+ } catch {
46
+ /* ignore */
47
+ }
48
+ });
49
+
50
+ const ctx = () => ({ db, providerModuleId: 'technitium', consumerModuleId: 'forgejo' });
51
+
52
+ it('records, lists, and upserts by (provider, host)', () => {
53
+ recordDnsInternalRecord(db, { ...ctx(), host: 'git-ssh.x', ip: '10.0.20.14' });
54
+ let rows = listDnsInternalRecords(db);
55
+ expect(rows).toHaveLength(1);
56
+ expect(rows[0].ip).toBe('10.0.20.14');
57
+
58
+ // Same (provider, host) updates in place — the natIp fix re-registering.
59
+ recordDnsInternalRecord(db, { ...ctx(), host: 'git-ssh.x', ip: '192.168.0.253' });
60
+ rows = listDnsInternalRecords(db);
61
+ expect(rows).toHaveLength(1);
62
+ expect(rows[0].ip).toBe('192.168.0.253');
63
+ });
64
+
65
+ it('removes a record by (provider, host)', () => {
66
+ recordDnsInternalRecord(db, { ...ctx(), host: 'a.x', ip: '1.1.1.1' });
67
+ recordDnsInternalRecord(db, { ...ctx(), host: 'b.x', ip: '2.2.2.2' });
68
+ removeDnsInternalRecord(db, { providerModuleId: 'technitium', host: 'a.x' });
69
+ const rows = listDnsInternalRecords(db);
70
+ expect(rows.map((r) => r.host)).toEqual(['b.x']);
71
+ });
72
+
73
+ describe('withDnsInternalLedger', () => {
74
+ function fakeProvider() {
75
+ const calls: Array<['register' | 'delete', DnsRecordRequest]> = [];
76
+ const iface = {
77
+ async registerRecord(req: DnsRecordRequest) {
78
+ calls.push(['register', req]);
79
+ },
80
+ async deleteRecord(req: DnsRecordRequest) {
81
+ calls.push(['delete', req]);
82
+ },
83
+ };
84
+ return { iface, calls };
85
+ }
86
+
87
+ it('records A-record registrations and passes the call through', async () => {
88
+ const { iface, calls } = fakeProvider();
89
+ const wrapped = withDnsInternalLedger(iface, ctx());
90
+ await wrapped.registerRecord({ host: 'git-ssh.x', type: 'A', value: '192.168.0.253' });
91
+ expect(calls).toHaveLength(1); // underlying provider still called
92
+ const rows = listDnsInternalRecords(db);
93
+ expect(rows).toHaveLength(1);
94
+ expect(rows[0]).toMatchObject({ host: 'git-ssh.x', ip: '192.168.0.253' });
95
+ });
96
+
97
+ it('does NOT ledger non-A records', async () => {
98
+ const { iface } = fakeProvider();
99
+ const wrapped = withDnsInternalLedger(iface, ctx());
100
+ await wrapped.registerRecord({ host: 'mail.x', type: 'MX', value: 'mx.x' });
101
+ expect(listDnsInternalRecords(db)).toHaveLength(0);
102
+ });
103
+
104
+ it('removes the ledger row on A-record delete', async () => {
105
+ const { iface } = fakeProvider();
106
+ const wrapped = withDnsInternalLedger(iface, ctx());
107
+ await wrapped.registerRecord({ host: 'git-ssh.x', type: 'A', value: '192.168.0.253' });
108
+ await wrapped.deleteRecord({ host: 'git-ssh.x', type: 'A', value: '192.168.0.253' });
109
+ expect(listDnsInternalRecords(db)).toHaveLength(0);
110
+ });
111
+
112
+ it('does not write the ledger if the underlying register throws', async () => {
113
+ const iface = {
114
+ async registerRecord(): Promise<void> {
115
+ throw new Error('resolver down');
116
+ },
117
+ async deleteRecord(): Promise<void> {},
118
+ };
119
+ const wrapped = withDnsInternalLedger(iface, ctx());
120
+ await expect(
121
+ wrapped.registerRecord({ host: 'git-ssh.x', type: 'A', value: '1.2.3.4' }),
122
+ ).rejects.toThrow('resolver down');
123
+ expect(listDnsInternalRecords(db)).toHaveLength(0);
124
+ });
125
+ });
126
+ });