koigrid 0.7.0 → 0.9.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 (56) hide show
  1. package/CHANGELOG.md +19 -2
  2. package/dist/api.js +78 -6
  3. package/dist/args.js +19 -0
  4. package/dist/commands/analytics.js +1 -1
  5. package/dist/commands/apps.js +369 -27
  6. package/dist/commands/audit.js +1 -1
  7. package/dist/commands/billing.js +87 -0
  8. package/dist/commands/bots.js +1 -1
  9. package/dist/commands/changelog.js +19 -0
  10. package/dist/commands/checks.js +4 -3
  11. package/dist/commands/config.js +9 -6
  12. package/dist/commands/connect.js +2 -2
  13. package/dist/commands/db.js +761 -17
  14. package/dist/commands/dns.js +1 -1
  15. package/dist/commands/errors.js +1 -1
  16. package/dist/commands/events.js +15 -3
  17. package/dist/commands/experiments.js +105 -0
  18. package/dist/commands/flags.js +22 -3
  19. package/dist/commands/heartbeats.js +3 -3
  20. package/dist/commands/images.js +1 -1
  21. package/dist/commands/jobs.js +39 -4
  22. package/dist/commands/links.js +59 -0
  23. package/dist/commands/logs.js +1 -1
  24. package/dist/commands/members.js +26 -1
  25. package/dist/commands/network.js +28 -0
  26. package/dist/commands/notices.js +24 -0
  27. package/dist/commands/notifications.js +2 -2
  28. package/dist/commands/otel.js +1 -1
  29. package/dist/commands/pricing.js +37 -0
  30. package/dist/commands/projects.js +1 -1
  31. package/dist/commands/queues.js +4 -3
  32. package/dist/commands/redis.js +80 -2
  33. package/dist/commands/registry.js +58 -3
  34. package/dist/commands/rewards.js +92 -14
  35. package/dist/commands/sandboxes.js +507 -2
  36. package/dist/commands/speed.js +1 -1
  37. package/dist/commands/spend.js +1 -1
  38. package/dist/commands/status.js +1 -1
  39. package/dist/commands/storage.js +51 -3
  40. package/dist/commands/support.js +47 -0
  41. package/dist/commands/tokens.js +7 -3
  42. package/dist/commands/up.js +6 -2
  43. package/dist/commands/waf.js +1 -1
  44. package/dist/commands/webhooks.js +1 -1
  45. package/dist/commands/wordpress.js +4 -3
  46. package/dist/commands/workflows.js +4 -3
  47. package/dist/esperar.js +41 -0
  48. package/dist/help.js +14 -1
  49. package/dist/index.js +26 -6
  50. package/dist/manifest.js +29 -12
  51. package/dist/output.js +1 -0
  52. package/dist/proyecto.js +6 -0
  53. package/dist/registry-flags.js +17 -0
  54. package/dist/registry.js +8 -2
  55. package/package.json +1 -1
  56. package/dist/commands/ai.js +0 -56
@@ -1,5 +1,10 @@
1
1
  import { api } from '../api.js';
2
- import { output, green } from '../output.js';
2
+ import { output, green, dim } from '../output.js';
3
+ import { network } from './network.js';
4
+ import { proyectoDeFlags } from '../proyecto.js';
5
+ // Tamaño legible de una copia: sirve para VER de un vistazo si la incremental está funcionando (una delta
6
+ // ocupa un orden de magnitud menos que la completa de la que cuelga).
7
+ const fmtBytes = (n) => (n < 1048576 ? `${(n / 1024).toFixed(0)}KB` : n < 1073741824 ? `${(n / 1048576).toFixed(1)}MB` : `${(n / 1073741824).toFixed(2)}GB`);
3
8
  const fmtCell = (v) => (v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
4
9
  export async function db(a) {
5
10
  const json = !!a.flags.json, sub = a.sub || 'ls', id = a.positionals[0];
@@ -10,32 +15,90 @@ export async function db(a) {
10
15
  case 'list': {
11
16
  const r = await api('/databases');
12
17
  const l = r.databases || r || [];
13
- return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), name: x.name, status: x.status, replicas: String(x.desiredReplicas ?? 0) })), columns: ['id', 'name', 'status', 'replicas'] });
18
+ return output(l, json, { rows: l.map((x) => ({ id: x.id.slice(0, 8), name: x.name, status: x.status, replicas: String(x.desiredReplicas ?? 0), reason: String(x.statusReason ?? '').slice(0, 60) })), columns: ['id', 'name', 'status', 'replicas', 'reason'] });
14
19
  }
15
20
  case 'create': {
16
21
  const name = a.positionals[0];
17
22
  if (!name)
18
- throw new Error('usage: koigrid db create <name> [--replicas N]');
19
- const body = { name };
23
+ throw new Error('usage: koigrid db create <name> [--replicas N] [--project <id>]');
24
+ const body = { name, ...proyectoDeFlags(a) };
20
25
  if (a.flags.replicas)
21
26
  body.replicas = Number(a.flags.replicas);
22
27
  const r = await api('/databases', { method: 'POST', body });
23
28
  return console.log(json ? JSON.stringify(r.database || r, null, 2) : green(`✓ Creating "${name}"…`));
24
29
  }
30
+ // Por defecto se toma un SNAPSHOT FINAL antes de destruir (estilo RDS): permite volver a levantar la base
31
+ // más adelante con `db restore`. `--no-final-snapshot` lo salta (más rápido, sin red de vuelta).
32
+ case 'pause': {
33
+ // Apaga el cluster conservando los datos: los volúmenes no se tocan y reanudar tarda segundos.
34
+ need();
35
+ const r = await api(`/databases/${encodeURIComponent(id)}/pause`, { method: 'POST' });
36
+ if (json)
37
+ return console.log(JSON.stringify(r, null, 2));
38
+ return console.log(green(r.alreadyPaused ? `✓ ${id} ya estaba pausada` : `✓ ${id} pausada — datos intactos, reanuda con: koigrid db resume ${id}`));
39
+ }
40
+ case 'resume': {
41
+ need();
42
+ const r = await api(`/databases/${encodeURIComponent(id)}/resume`, { method: 'POST' });
43
+ if (json)
44
+ return console.log(JSON.stringify(r, null, 2));
45
+ if (r.alreadyRunning)
46
+ return console.log(green(`✓ ${id} no estaba pausada`));
47
+ return console.log(green(`✓ ${id} reanudándose${r.recreated ? ' (algún contenedor hubo que recrearlo)' : ''} — estado: ${r.database?.status}`));
48
+ }
25
49
  case 'rm':
26
- case 'delete':
50
+ case 'delete': {
27
51
  need();
28
- await api(`/databases/${encodeURIComponent(id)}`, { method: 'DELETE' });
29
- return console.log(green(`✓ Deleted ${id}`));
52
+ const sinCopia = Boolean(a.flags['no-final-snapshot']);
53
+ let ruta = `/databases/${encodeURIComponent(id)}`;
54
+ if (sinCopia)
55
+ ruta += '?finalSnapshot=false';
56
+ const r = await api(ruta, { method: 'DELETE' });
57
+ if (json)
58
+ return console.log(JSON.stringify(r, null, 2));
59
+ // La fecha la decide el servidor (90 días con snapshot final, la ventana de retención sin él).
60
+ const hasta = r?.backupsKeptUntil ? ` hasta ${String(r.backupsKeptUntil).slice(0, 10)}` : '';
61
+ return console.log(green(`✓ Deleted ${id}${sinCopia ? ` (sin snapshot final; copias${hasta})` : ` — snapshot final en curso; restaurable${hasta} con: koigrid db restore ${id}`}`));
62
+ }
30
63
  case 'url':
31
64
  case 'connection': {
32
65
  need();
33
66
  const r = await api(`/databases/${encodeURIComponent(id)}/connection`);
34
67
  if (json)
35
68
  return console.log(JSON.stringify(r.connection, null, 2));
69
+ // --direct: sólo la directa, para encadenarla (`psql "$(koigrid db url <id> --direct)" -f dump.sql`).
70
+ if (a.flags.direct) {
71
+ if (!r.connection?.directUri) {
72
+ console.error('this database has no direct endpoint');
73
+ process.exitCode = 1;
74
+ return;
75
+ }
76
+ // Siempre la de `require`: la verificable exige además el fichero de la CA, y encadenada sin él fallaría.
77
+ return console.log(r.connection.directUri);
78
+ }
79
+ // --multi-host: sólo la cadena con todos los routers (ficha ddc6cdcd), para encadenarla igual que --direct.
80
+ if (a.flags['multi-host']) {
81
+ if (!r.connection?.multiHostUri) {
82
+ console.error('this database has no multi-host connection string (it needs replicas and the public certificate)');
83
+ process.exitCode = 1;
84
+ return;
85
+ }
86
+ return console.log(r.connection.multiHostUri);
87
+ }
36
88
  console.log(r.connection?.uri);
89
+ // La del pooler va en modo TRANSACCIÓN: lo que dependa de la sesión (pg_dump/psql -f, migradores con SET o
90
+ // advisory locks, LISTEN/NOTIFY) se rompe por ahí con errores que parecen del SQL. La directa existe para eso
91
+ // (ficha c41f5b8b), y se dice aquí porque es donde se busca la URL.
92
+ if (r.connection?.directUri)
93
+ console.log('# direct (migrations, pg_dump/psql restores — keeps the session, bypasses the pooler):', r.connection.directUri);
94
+ // Verificable (ficha ef7a926d): con caCert guardado en un fichero y sslrootcert=<fichero> en la URL.
95
+ if (r.connection?.directSslVerifiedUri)
96
+ console.log('# direct, TLS-verified (add sslrootcert=<file with caCert from --json>):', r.connection.directSslVerifiedUri);
37
97
  if (r.connection?.readUri)
38
98
  console.log('# read-only:', r.connection.readUri);
99
+ // Todos los routers en una cadena: libpq, postgres.js y pgx saltan solos al siguiente host si uno no responde.
100
+ if (r.connection?.multiHostUri)
101
+ console.log('# multi-host (libpq, postgres.js, pgx — skips a dead router without waiting for DNS):', r.connection.multiHostUri);
39
102
  return;
40
103
  }
41
104
  case 'connect': {
@@ -48,21 +111,102 @@ export async function db(a) {
48
111
  const res = spawnSync('psql', [uri], { stdio: 'inherit' });
49
112
  return process.exit(res.status ?? 0);
50
113
  }
114
+ case 'info':
115
+ case 'get': {
116
+ // El detalle con el disco REAL de cada miembro (ficha 86a6e298): diskGb es el suelo del plan, no el tamaño.
117
+ need();
118
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
119
+ if (json)
120
+ return console.log(JSON.stringify(r, null, 2));
121
+ const d = r.database || {}, st = r.storage || {};
122
+ console.log(`${d.name} · ${d.status} · ${d.desiredReplicas ?? 0} replica(s) · ${d.memoryMb ?? '?'} MB · ${d.cpus ?? '?'} vCPU`);
123
+ console.log(`disk: ${st.allocatedGb ?? '?'} GB allocated · ${st.usedGb ?? '?'} GB used · plan floor ${st.includedGb ?? d.diskGb ?? '?'} GB · ${st.maxDiskGb != null ? `cap ${st.maxDiskGb} GB${st.capState ? ` (${st.capState})` : ''}` : 'no cap'}`);
124
+ const l = st.members || [];
125
+ return output(l, false, { rows: l.map((x) => ({ member: x.member, role: x.role + (x.papel === 'dr' ? ' (dr)' : ''), allocated: x.measured ? `${x.allocatedGb} GB` : 'not measured', used: x.measured ? `${x.usedGb} GB` : '', pct: x.measured ? `${x.usedPct}%` : '', ago: x.measured ? `${x.measuredAgoSec}s` : '' })), columns: ['member', 'role', 'allocated', 'used', 'pct', 'ago'] });
126
+ }
51
127
  case 'metrics':
52
128
  need();
53
129
  return console.log(JSON.stringify(await api(`/databases/${encodeURIComponent(id)}/metrics`), null, 2));
54
- case 'logs':
130
+ // Qué consultas cargan la base en una ventana (ficha 326dd9b3, como RDS Performance Insights). `notes` se imprime:
131
+ // dice lo que la respuesta no puede afirmar (totales por consulta = suelo; ventana sin muestras ≠ sin carga).
132
+ case 'top-queries': {
133
+ need();
134
+ const q = new URLSearchParams();
135
+ if (a.flags.hours)
136
+ q.set('hours', String(a.flags.hours));
137
+ if (a.flags.since)
138
+ q.set('since', String(a.flags.since));
139
+ if (a.flags.until)
140
+ q.set('until', String(a.flags.until));
141
+ if (a.flags.limit)
142
+ q.set('limit', String(a.flags.limit));
143
+ const r = await api(`/databases/${encodeURIComponent(id)}/queries${q.size ? `?${q}` : ''}`);
144
+ if (json)
145
+ return console.log(JSON.stringify(r, null, 2));
146
+ console.log(dim(`# ${r.since} → ${r.until} · ${r.intervals} intervals · ${(r.totalExecMs / 1000).toFixed(1)} s of execution · ${r.totalCalls} calls`));
147
+ if ((r.queries || []).length)
148
+ output(r.queries, false, { rows: r.queries.map((x) => ({ pct: x.pctOfDbTime === null ? '?' : `${x.pctOfDbTime}%`, total: `${(x.totalMs / 1000).toFixed(1)} s`, calls: String(x.calls), mean: x.meanMs === null ? '?' : `${x.meanMs} ms`, query: String(x.query ?? `(queryid ${x.queryId}: text no longer available)`).replace(/\s+/g, ' ').slice(0, 100) })), columns: ['pct', 'total', 'calls', 'mean', 'query'] });
149
+ for (const n of r.notes || [])
150
+ console.log(dim(`# ${n}`));
151
+ if (r.ignored?.length)
152
+ console.log(dim(`# parámetros ignorados: ${r.ignored.join(', ')}`));
153
+ return;
154
+ }
155
+ // Los slots lógicos y si sobrevivirían hoy a un cambio de líder (ficha cb62c3c4).
156
+ case 'slots': {
55
157
  need();
56
- return console.log((await api(`/databases/${encodeURIComponent(id)}/logs?tail=${a.flags.tail || 200}`)).logs || '');
158
+ const r = await api(`/databases/${encodeURIComponent(id)}/replication-slots`);
159
+ if (json)
160
+ return console.log(JSON.stringify(r, null, 2));
161
+ if (!r.measured)
162
+ return console.log('could not read the slots of the leader (try again in a minute)');
163
+ if (!(r.slots || []).length)
164
+ return console.log('no logical replication slots');
165
+ output(r.slots, false, { rows: r.slots.map((s) => ({ name: String(s.name), active: s.active ? 'yes' : 'no', retained: typeof s.retainedBytes === 'number' ? `${(s.retainedBytes / 1024 ** 2).toFixed(1)} MB` : '?', 'on replicas': Object.entries(s.retainedOnReplicas || {}).map(([m, b]) => `${m}=${typeof b === 'number' ? `${(b / 1024 ** 2).toFixed(1)} MB` : '?'}`).join(' ') || '—', wal: s.walStatus || '?', failover: s.failover ? 'yes' : 'no', protected: s.protected ? '✓' : '✗', missing: (s.missingOn || []).join(',') || '—' })), columns: ['name', 'active', 'retained', 'wal', 'on replicas', 'failover', 'protected', 'missing'] });
166
+ return console.log(`\n${r.note}`);
167
+ }
168
+ // `db logs` sirve el log de POSTGRES por defecto (los ERROR de tu base), no el de Patroni. `--source
169
+ // patroni|both` cambia de capa y `--level problem` deja sólo lo que va mal. ⚠️ `note` e `ignored` se
170
+ // IMPRIMEN: si la API se ha tragado un parámetro o ha tenido que caer a otra fuente, callarlo aquí sería
171
+ // reintroducir en el CLI el silencio que esta ficha vino a quitar de la API (f3356147).
172
+ case 'logs': {
173
+ need();
174
+ const q = new URLSearchParams({ tail: String(a.flags.tail || 200) });
175
+ if (a.flags.source)
176
+ q.set('source', String(a.flags.source));
177
+ if (a.flags.level)
178
+ q.set('level', String(a.flags.level));
179
+ if (a.flags.member)
180
+ q.set('member', String(a.flags.member)); // otro miembro: el líder caído tras un failover
181
+ for (const k of ['since', 'until'])
182
+ if (a.flags[k] && a.flags[k] !== true)
183
+ q.set(k, String(a.flags[k])); // ventana del log de Patroni (30 días)
184
+ const r = await api(`/databases/${encodeURIComponent(id)}/logs?${q}`);
185
+ if (json)
186
+ return console.log(JSON.stringify(r, null, 2));
187
+ if (r.member)
188
+ console.log(dim(`# miembro ${r.member}${r.members?.length > 1 ? ` (otros: ${r.members.filter((m) => m.name !== r.member).map((m) => `${m.name} ${m.role}`).join(', ')} → --member)` : ''}`));
189
+ if (r.file)
190
+ console.log(dim(`# ${r.source} · ${r.file}`));
191
+ console.log(r.logs || '');
192
+ if (r.note)
193
+ console.log(dim(`# ${r.note}`));
194
+ if (r.ignored?.length)
195
+ console.log(dim(`# parámetros ignorados: ${r.ignored.join(', ')}`));
196
+ return;
197
+ }
198
+ // `--full` fuerza una copia COMPLETA en vez de la incremental que tocaría por cadencia. El listado muestra
199
+ // el modo: sin esa columna, "8 copias hechas" no dice si se puede restaurar barato o hay una cadena larga.
57
200
  case 'backups': {
58
201
  need();
59
202
  if (a.positionals[1] === 'create') {
60
- await api(`/databases/${encodeURIComponent(id)}/backups`, { method: 'POST' });
61
- return console.log(green('✓ Backup started'));
203
+ const full = Boolean(a.flags.full);
204
+ await api(`/databases/${encodeURIComponent(id)}/backups`, { method: 'POST', body: full ? { full: true } : {} });
205
+ return console.log(green(`✓ Backup started${full ? ' (full)' : ''} — runs in the background; follow it with: koigrid db backups ${id}`));
62
206
  }
63
207
  const r = await api(`/databases/${encodeURIComponent(id)}/backups`);
64
208
  const l = r.backups || r || [];
65
- return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), status: x.status, at: String(x.createdAt || '').slice(0, 16) })), columns: ['id', 'status', 'at'] });
209
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), mode: x.mode || 'full', why: x.modeReason || '', size: x.sizeBytes ? fmtBytes(Number(x.sizeBytes)) : '', status: x.status, tier: x.longTermTier || '', storage: x.storage || 'hot', at: String(x.createdAt || x.startedAt || '').slice(0, 16) })), columns: ['id', 'mode', 'why', 'size', 'status', 'tier', 'storage', 'at'] });
66
210
  }
67
211
  case 'restore': {
68
212
  need();
@@ -71,9 +215,90 @@ export async function db(a) {
71
215
  body.name = a.flags.name;
72
216
  if (a.flags.time)
73
217
  body.targetTime = a.flags.time;
218
+ if (a.flags.backup)
219
+ body.backupId = a.flags.backup /* una copia semanal de largo plazo (ficha d78ec4e9) */;
74
220
  const r = await api(`/databases/${encodeURIComponent(id)}/restore`, { method: 'POST', body });
75
221
  return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Restoring to a new cluster…'));
76
222
  }
223
+ case 'restore-dump':
224
+ case 'import': {
225
+ // Managed restore (MIG-D): sube un dump .sql → lo restaura con pre-siembra de extensiones + conteo de filas.
226
+ need();
227
+ const file = (a.flags.file || a.flags.f || a.positionals[1]);
228
+ if (!file)
229
+ throw new Error('usage: koigrid db restore-dump <id> --file dump.sql [--pre-seed vector:extensions] [--wait]');
230
+ // Se sube SIEMPRE comprimido y EN STREAMING: (a) un readFileSync de un dump grande revienta el límite de
231
+ // Buffer de Node (~2 GB) y (b) gzip reduce ~8×, así un dump de 31 GB entra en el tope del servidor. Si el
232
+ // fichero ya es .gz se sube tal cual; si no, se comprime al vuelo sin escribir nada en disco.
233
+ const { createReadStream, statSync } = await import('node:fs');
234
+ const { createGzip } = await import('node:zlib');
235
+ const { Readable } = await import('node:stream');
236
+ const isGz = /\.gz$/i.test(String(file));
237
+ const srcBytes = statSync(String(file)).size;
238
+ if (!json)
239
+ console.log(`▸ subiendo ${(srcBytes / 1024 ** 3).toFixed(2)} GB${isGz ? ' (ya comprimido)' : ' (comprimiendo al vuelo…)'}`);
240
+ const up = await api(`/databases/${encodeURIComponent(id)}/restore-dump/upload-url`, { method: 'POST', body: { gzip: true } });
241
+ const raw = createReadStream(String(file));
242
+ const stream = isGz ? raw : raw.pipe(createGzip());
243
+ const put = await fetch(up.uploadUrl, {
244
+ method: 'PUT',
245
+ headers: { 'content-type': 'application/gzip' },
246
+ body: Readable.toWeb(stream),
247
+ duplex: 'half',
248
+ });
249
+ if (!put.ok)
250
+ throw new Error(`dump upload failed (HTTP ${put.status})`);
251
+ const preSeed = a.flags['pre-seed'] ? String(a.flags['pre-seed']).split(',').map((s) => { const [name, schema] = s.split(':'); return schema ? { name, schema } : { name }; }) : undefined;
252
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore-dump`, { method: 'POST', body: { dumpKey: up.key, ...(preSeed ? { preSeed } : {}) } });
253
+ const jobId = r.restore?.id;
254
+ if (!a.flags.wait)
255
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Restore started (job ${String(jobId).slice(0, 8)}). Estado: koigrid db restore-status ${id} ${jobId}`));
256
+ // ⛔ Se espera hasta el TECHO DEL SERVIDOR (6 h, `restoreTechoMs`) y no 30 min: el servidor no corta una restauración
257
+ // por lenta, sólo por parada, y un volcado de 30 GB tarda horas. Con 900 × 2 s el CLI decía «sigue en curso» y se
258
+ // iba a mitad de una restauración sana (lo vio el ensayo de vence, 2026-10-09). Sondeo cada 10 s pasada la primera hora.
259
+ const hasta = Date.now() + 6.5 * 3600_000;
260
+ for (let i = 0; Date.now() < hasta; i++) {
261
+ await new Promise((res) => setTimeout(res, i < 1800 ? 2000 : 10_000));
262
+ const s = await api(`/databases/${encodeURIComponent(id)}/restore-dump/${jobId}`);
263
+ const st = s.restore?.status;
264
+ if (st === 'done') {
265
+ if (json)
266
+ return console.log(JSON.stringify(s.restore, null, 2));
267
+ console.log(green('✓ Restore done'));
268
+ for (const t of (s.restore?.tableCounts || []).slice(0, 40))
269
+ console.log(` ${t.table} ${t.rows}`);
270
+ return;
271
+ }
272
+ if (st === 'failed')
273
+ throw new Error(`restore failed: ${s.restore?.error || 'unknown'}`);
274
+ }
275
+ throw new Error('restore sigue en curso (timeout esperando)');
276
+ }
277
+ case 'analyze': {
278
+ // ANALYZE para que el planificador tenga estadísticas: por defecto sólo las tablas que no tienen (lo que deja un
279
+ // restore o la copia de una suscripción); --all, todas. Va en segundo plano: el resultado sale en el feed.
280
+ need();
281
+ const all = Boolean(a.flags.all);
282
+ const r = await api(`/databases/${encodeURIComponent(id)}/analyze`, { method: 'POST', body: all ? { all: true } : {} });
283
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ ANALYZE started (${all ? 'all tables' : 'tables without statistics'}) — runs in the background; the result appears in the activity feed as db.analyze.done`));
284
+ }
285
+ case 'fix-ownership': {
286
+ // A2: repara una BD que un restore anterior dejó con owner=postgres (el rol de la app no podía leer nada).
287
+ need();
288
+ const r = await api(`/databases/${encodeURIComponent(id)}/fix-ownership`, { method: 'POST', body: {} });
289
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Propiedad reparada: todo pertenece ya al rol ${r.role}`));
290
+ }
291
+ case 'restore-status': {
292
+ need();
293
+ const jobId = a.positionals[1];
294
+ if (!jobId) {
295
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore-dump`);
296
+ const l = r.restores || [];
297
+ return output(l, json, { rows: l.map((x) => ({ id: String(x.id).slice(0, 8), status: x.status, tables: Array.isArray(x.tableCounts) ? x.tableCounts.length : 0, error: String(x.error || '').slice(0, 40) })), columns: ['id', 'status', 'tables', 'error'] });
298
+ }
299
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore-dump/${encodeURIComponent(jobId)}`);
300
+ return console.log(json ? JSON.stringify(r.restore, null, 2) : `status: ${r.restore?.status}` + (r.restore?.error ? `\nerror: ${r.restore.error}` : ''));
301
+ }
77
302
  case 'ext':
78
303
  case 'extensions': {
79
304
  need();
@@ -82,7 +307,12 @@ export async function db(a) {
82
307
  const r = await api(`/databases/${encodeURIComponent(id)}/extensions`);
83
308
  return console.log(json ? JSON.stringify(r, null, 2) : 'allowed: ' + (r.allowed || []).join(', '));
84
309
  }
85
- const r = await api(`/databases/${encodeURIComponent(id)}/extensions`, { method: 'POST', body: { name } });
310
+ // `--schema` (paridad con la API): instala la extensión en ese schema. Es el camino de los ex-Supabase —
311
+ // sus dumps declaran tipos como `extensions.vector`, así que sin esto el restore falla con "type
312
+ // extensions.vector does not exist". La API lo soporta desde J7-2 y el CLI no podía pasarlo: un agente que
313
+ // usara el CLI se quedaba sin la única palanca que desbloquea a ese cliente.
314
+ const schema = typeof a.flags.schema === 'string' ? a.flags.schema : undefined;
315
+ const r = await api(`/databases/${encodeURIComponent(id)}/extensions`, { method: 'POST', body: schema ? { name, schema } : { name } });
86
316
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Extension ${name} installed`));
87
317
  }
88
318
  case 'replicas': {
@@ -95,6 +325,32 @@ export async function db(a) {
95
325
  const r = await api(`/databases/${encodeURIComponent(id)}/replicas`, { method: 'POST', body: { replicas: Number(n) } });
96
326
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Scaling to ${n} read replica(s)…`));
97
327
  }
328
+ case 'network': {
329
+ need();
330
+ return network('databases', 'db', id, a, json);
331
+ }
332
+ case 'dr-copy': {
333
+ // Copia de desastre (ficha c21ac56a): `db dr-copy <id>` muestra · `add` la pide · `rm` la retira.
334
+ need();
335
+ const act = a.positionals[1];
336
+ if (!act) {
337
+ const r = await api(`/databases/${encodeURIComponent(id)}/dr-copy`);
338
+ if (json)
339
+ return console.log(JSON.stringify(r, null, 2));
340
+ if (r.inProgress)
341
+ console.log(`in progress: ${r.inProgress.operacion}${r.inProgress.detalle ? ` · ${r.inProgress.detalle}` : ''}`);
342
+ return console.log(r.drCopy ? `${r.drCopy.member} · ${r.drCopy.provider} · ${r.drCopy.state} · promotion: ${r.drCopy.promotion}` : 'no disaster-recovery copy');
343
+ }
344
+ if (act === 'add') {
345
+ const r = await api(`/databases/${encodeURIComponent(id)}/dr-copy`, { method: 'POST' });
346
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Adding disaster-recovery copy ${r.drCopy?.member} in ${r.drCopy?.provider} (no downtime; follow with: koigrid db dr-copy ${id})`));
347
+ }
348
+ if (act === 'rm' || act === 'remove') {
349
+ const r = await api(`/databases/${encodeURIComponent(id)}/dr-copy`, { method: 'DELETE' });
350
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Removing disaster-recovery copy ${r.drCopy?.member}`));
351
+ }
352
+ throw new Error('usage: koigrid db dr-copy <id> [add|rm]');
353
+ }
98
354
  case 'pub':
99
355
  case 'publications': {
100
356
  need();
@@ -189,21 +445,45 @@ export async function db(a) {
189
445
  if (!act || act === 'ls') {
190
446
  const r = await api(`/databases/${encodeURIComponent(id)}/roles`);
191
447
  const l = r.roles || [];
192
- return output(l, json, { rows: l.map((x) => ({ name: x.name, login: x.canLogin ? 'yes' : 'no', createdb: x.createdb ? 'yes' : 'no' })), columns: ['name', 'login', 'createdb'] });
448
+ return output(l, json, { rows: l.map((x) => ({ name: x.name, login: x.canLogin ? 'yes' : 'no', createdb: x.createdb ? 'yes' : 'no', memberOf: (x.memberOf || []).join(',') || '-', reference: x.reference || (x.reference === null ? '(set password to enable)' : '-') })), columns: ['name', 'login', 'createdb', 'memberOf', 'reference'] });
193
449
  }
194
450
  if (act === 'create') {
195
451
  if (!rname)
196
- throw new Error('usage: koigrid db roles <id> create <name> --password <pw> [--no-login] [--createdb]');
452
+ throw new Error('usage: koigrid db roles <id> create <name> --password <pw> [--no-login] [--createdb] [--read-only [--bypass-rls]] [--member-of <role>[,<role>]] [--act-as <role>]');
197
453
  const password = a.flags.password ? String(a.flags.password) : '';
198
454
  if (!password)
199
455
  throw new Error('--password required');
200
456
  const body = { name: rname, password };
457
+ if (a.flags['member-of'])
458
+ body.memberOf = String(a.flags['member-of']).split(',').map((s) => s.trim()).filter(Boolean);
459
+ if (a.flags['act-as'])
460
+ body.actAs = String(a.flags['act-as']);
201
461
  if (a.flags['no-login'])
202
462
  body.login = false;
203
463
  if (a.flags.createdb)
204
464
  body.createdb = true;
465
+ if (a.flags['read-only'])
466
+ body.readOnly = true;
467
+ if (a.flags['bypass-rls'])
468
+ body.bypassRls = true;
205
469
  const r = await api(`/databases/${encodeURIComponent(id)}/roles`, { method: 'POST', body });
206
- return console.log(json ? JSON.stringify(r.role || r, null, 2) : green(`✓ Role ${rname} created`));
470
+ return console.log(json ? JSON.stringify(r.role || r, null, 2) : green(`✓ Role ${rname} created${body.readOnly ? ' (read-only: SELECT only, writes rejected)' : ''}`));
471
+ }
472
+ if (act === 'member') {
473
+ if (!rname)
474
+ throw new Error('usage: koigrid db roles <id> member <name> [--add <role>[,<role>]] [--remove <role>[,<role>]] [--act-as <role|none>]');
475
+ const lista = (f) => (a.flags[f] ? String(a.flags[f]).split(',').map((s) => s.trim()).filter(Boolean) : []);
476
+ const body = {};
477
+ if (lista('add').length)
478
+ body.memberOf = lista('add');
479
+ if (lista('remove').length)
480
+ body.notMemberOf = lista('remove');
481
+ if (a.flags['act-as'] !== undefined)
482
+ body.actAs = a.flags['act-as'] === 'none' ? null : String(a.flags['act-as']);
483
+ if (!body.memberOf && !body.notMemberOf && body.actAs === undefined)
484
+ throw new Error('--add, --remove and/or --act-as <role|none> required');
485
+ const r = await api(`/databases/${encodeURIComponent(id)}/roles/${encodeURIComponent(rname)}`, { method: 'PATCH', body });
486
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ ${rname} is now member of: ${(r.memberOf || []).join(', ') || '(none)'}`));
207
487
  }
208
488
  if (act === 'password') {
209
489
  if (!rname)
@@ -220,7 +500,100 @@ export async function db(a) {
220
500
  await api(`/databases/${encodeURIComponent(id)}/roles/${encodeURIComponent(rname)}`, { method: 'DELETE' });
221
501
  return console.log(green(`✓ Role ${rname} dropped`));
222
502
  }
223
- throw new Error('usage: koigrid db roles <id> ls | create <name> --password <pw> [--no-login] [--createdb] | password <name> --password <pw> | rm <name>');
503
+ throw new Error('usage: koigrid db roles <id> ls | create <name> --password <pw> [--no-login] [--createdb] [--read-only [--bypass-rls]] | password <name> --password <pw> | rm <name>');
504
+ }
505
+ case 'params':
506
+ case 'parameters': {
507
+ // Parámetros de la base (ficha 98d3c3a1): con el pooler en modo transacción los timeouts que manda el cliente al
508
+ // conectar NO llegan a Postgres; fijarlos en la base sí. ms; 0 = sin límite; --unset <nombre> lo quita.
509
+ need();
510
+ const act = a.positionals[1];
511
+ const ms = (f) => (a.flags[f] === undefined ? undefined : Number(a.flags[f]));
512
+ if (!act || act === 'show') {
513
+ const r = await api(`/databases/${encodeURIComponent(id)}/parameters`);
514
+ if (json)
515
+ return console.log(JSON.stringify(r, null, 2));
516
+ const p = r.parameters || {};
517
+ console.log(`statement_timeout: ${p.statementTimeoutMs ?? 'default (no limit)'}${p.statementTimeoutMs != null ? ' ms' : ''}`);
518
+ console.log(`idle_in_transaction_session_timeout: ${p.idleInTransactionTimeoutMs ?? 'default (no limit)'}${p.idleInTransactionTimeoutMs != null ? ' ms' : ''}`);
519
+ console.log(`lock_timeout: ${p.lockTimeoutMs ?? 'default (no limit)'}${p.lockTimeoutMs != null ? ' ms' : ''}`);
520
+ console.log(`plan_cache_mode: ${p.planCacheMode ?? 'default (auto)'}`);
521
+ for (const o of r.roleOverrides || [])
522
+ console.log(`role ${o.role} overrides: ${JSON.stringify(o.parameters)}`);
523
+ return;
524
+ }
525
+ if (act === 'set') {
526
+ const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
527
+ if (ms('statement-timeout-ms') !== undefined)
528
+ body.statementTimeoutMs = ms('statement-timeout-ms');
529
+ if (ms('idle-in-transaction-timeout-ms') !== undefined)
530
+ body.idleInTransactionTimeoutMs = ms('idle-in-transaction-timeout-ms');
531
+ if (ms('lock-timeout-ms') !== undefined)
532
+ body.lockTimeoutMs = ms('lock-timeout-ms');
533
+ if (a.flags['plan-cache-mode'] !== undefined)
534
+ body.planCacheMode = String(a.flags['plan-cache-mode']);
535
+ const quitar = { 'statement-timeout': 'statementTimeoutMs', 'idle-in-transaction-timeout': 'idleInTransactionTimeoutMs', 'lock-timeout': 'lockTimeoutMs', 'plan-cache-mode': 'planCacheMode' };
536
+ if (a.flags.unset)
537
+ for (const n of String(a.flags.unset).split(',').map((x) => x.trim()).filter(Boolean)) {
538
+ if (!quitar[n])
539
+ throw new Error(`--unset: unknown parameter ${n} (statement-timeout, idle-in-transaction-timeout, lock-timeout, plan-cache-mode)`);
540
+ body[quitar[n]] = null;
541
+ }
542
+ if (!Object.keys(body).length)
543
+ throw new Error('usage: koigrid db params <id> set [--statement-timeout-ms N] [--idle-in-transaction-timeout-ms N] [--lock-timeout-ms N] [--plan-cache-mode auto|force_custom_plan|force_generic_plan] [--unset <name>[,<name>]]');
544
+ const r = await api(`/databases/${encodeURIComponent(id)}/parameters`, { method: 'PUT', body });
545
+ if (json)
546
+ return console.log(JSON.stringify(r, null, 2));
547
+ const f = r.poolerReconnect?.failed?.length ?? 0;
548
+ return console.log(green(`✓ Parameters applied: ${JSON.stringify(r.parameters)}`) + (f ? ` (${f} pooler(s) not renewed: existing pooled connections pick it up when they recycle)` : ''));
549
+ }
550
+ throw new Error('usage: koigrid db params <id> show | set [--statement-timeout-ms N] [--idle-in-transaction-timeout-ms N] [--lock-timeout-ms N] [--unset <name>]');
551
+ }
552
+ case 'pooler': {
553
+ // El cupo de conexiones del pooler (ficha 2c41fa1e): automático (75 % de las conexiones útiles de la base) o el que
554
+ // se fije, con un cupo por rol. Se aplica en caliente en cada PgBouncer, sin cortar conexiones.
555
+ need();
556
+ const act = a.positionals[1];
557
+ if (!act || act === 'show') {
558
+ const r = await api(`/databases/${encodeURIComponent(id)}/pooler`);
559
+ if (json)
560
+ return console.log(JSON.stringify(r, null, 2));
561
+ console.log(`pool: ${r.pools?.transaction?.poolSize} server connections (${r.mode}; automatic ${r.limits?.autoPoolSize}, max ${r.limits?.maxPoolSize})`);
562
+ for (const [rol, n] of Object.entries(r.pools?.transaction?.perRole || {}))
563
+ console.log(` role ${rol}: ${n}`);
564
+ console.log(`session pooler (direct URL): ${r.pools?.session?.poolSize}`);
565
+ if (r.warning)
566
+ console.log(r.warning);
567
+ for (const l of r.live || [])
568
+ console.log(` ${l.host}:${l.port} ${l.pooler}: ${l.error ? `no answer (${l.error})` : `${l.poolSize} / ${l.maxDbConnections || 'no cap'} · ${l.serverConnections} open${l.matches === false ? ' · pending' : ''}`}`);
569
+ return;
570
+ }
571
+ if (act === 'set') {
572
+ const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
573
+ if (a.flags['pool-size'] !== undefined)
574
+ body.poolSize = a.flags['pool-size'] === 'auto' ? null : Number(a.flags['pool-size']);
575
+ const rolesFlag = a.flags.role === undefined ? [] : Array.isArray(a.flags.role) ? a.flags.role : [a.flags.role];
576
+ if (rolesFlag.length) {
577
+ body.roles = {};
578
+ for (const r of rolesFlag.map(String)) {
579
+ const m = r.match(/^([a-z_][a-z0-9_]*)=(\d+)$/);
580
+ if (!m)
581
+ throw new Error(`--role ${r}: use <role>=<connections>`);
582
+ body.roles[m[1]] = Number(m[2]);
583
+ }
584
+ }
585
+ if (a.flags['no-roles'])
586
+ body.roles = null;
587
+ if (a.flags['dry-run'])
588
+ body.dryRun = true;
589
+ if (!Object.keys(body).filter((k) => k !== 'dryRun').length)
590
+ throw new Error('usage: koigrid db pooler <id> set [--pool-size N|auto] [--role <role>=N]... [--no-roles] [--dry-run]');
591
+ const r = await api(`/databases/${encodeURIComponent(id)}/pooler`, { method: 'PUT', body });
592
+ if (json)
593
+ return console.log(JSON.stringify(r, null, 2));
594
+ return console.log(green(`✓ ${r.detail}`));
595
+ }
596
+ throw new Error('usage: koigrid db pooler <id> show | set [--pool-size N|auto] [--role <role>=N]... [--no-roles] [--dry-run]');
224
597
  }
225
598
  case 'rotation': {
226
599
  need();
@@ -256,6 +629,317 @@ export async function db(a) {
256
629
  }
257
630
  throw new Error('usage: koigrid db rotation <id> show | set --interval <days|off> [--grace <days>] | rotate | migrate');
258
631
  }
632
+ case 'sub':
633
+ case 'subs': {
634
+ // J-INBOUND-REPL-MANAGED: migrar SIN ventana desde un Postgres externo, y saber cuándo se puede cambiar.
635
+ need();
636
+ const act = a.positionals[1];
637
+ if (!act || act === 'ls') {
638
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions`);
639
+ const l = r.subscriptions || [];
640
+ if (json)
641
+ return console.log(JSON.stringify(l, null, 2));
642
+ if (!l.length)
643
+ return console.log('(sin suscripciones)');
644
+ for (const s of l) {
645
+ const lag = s.lagBytes == null ? '?' : `${Math.round(s.lagBytes / 1024)} KB`;
646
+ // La COPIA va delante del retraso, y en la misma línea: un «retraso 0 KB» a solas es justo el dato
647
+ // que hizo creer que se podía migrar con 110 de 257 tablas copiadas.
648
+ const copia = s.tablas == null ? 'copia ?' : `copia ${s.tablas.listas}/${s.tablas.total}`;
649
+ // Las vistas materializadas vacías (la replicación no las copia): sin esto la línea dice «copia 268/268»
650
+ // con páginas de la app que fallarían al cambiar (ficha 6b91895c).
651
+ const vistas = Array.isArray(s.vistasSinPoblar) && s.vistasSinPoblar.length ? ` · ${s.vistasSinPoblar.length} vista(s) VACÍA(S)` : '';
652
+ console.log(`${s.cutover?.ready ? '✅' : '⏳'} ${s.name} ${s.enabled ? 'activa' : 'DESACTIVADA'} · ${copia} · retraso ${lag}${vistas}`);
653
+ console.log(` ${s.cutover?.detail ?? ''}`);
654
+ }
655
+ return;
656
+ }
657
+ // `preflight` es la comprobación SIN crear nada: las tres trampas medidas migrando de RDS (RLS sin
658
+ // BYPASSRLS, CHECK sin validar, esquema desfasado) que dan una copia incompleta sin un error que lo diga.
659
+ if (act === 'preflight' || act === 'check') {
660
+ const source = a.flags.source ? String(a.flags.source) : '';
661
+ const publication = a.flags.publication ? String(a.flags.publication) : '';
662
+ if (!source || !publication)
663
+ throw new Error("usage: koigrid db subs <id> preflight --source 'postgres://…' --publication <pub>");
664
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/preflight`, { method: 'POST', body: { source, publication } });
665
+ if (json)
666
+ return console.log(JSON.stringify(r, null, 2));
667
+ // «No se pudo comprobar» se dice con todas las letras: una lista de bloqueos vacía porque no se pudo
668
+ // preguntar se lee igual que una porque no hay nada, y significan lo contrario.
669
+ if (!r.medido)
670
+ return console.log(`⚠️ ${r.detalle}\n${r.logs ? dim(r.logs) : ''}`);
671
+ if (r.ok)
672
+ console.log(green('✅ sin problemas: la copia inicial debería traerlo todo'));
673
+ else
674
+ console.log(`⛔ ${r.detalle}`);
675
+ if (r.avisos?.length)
676
+ for (const x of r.avisos)
677
+ console.log(` ⚠️ ${x.tabla ?? ''} ${x.detalle}`);
678
+ if (r.ignorados?.length)
679
+ console.log(dim(` (parámetros del origen que el preflight no traslada: ${r.ignorados.join(', ')})`));
680
+ return;
681
+ }
682
+ // `verify` es la comprobación de DESPUÉS: cuenta filas de los dos lados. Es lo único que destapa una
683
+ // tabla copiada a cero por RLS, que por dentro consta como terminada.
684
+ if (act === 'verify') {
685
+ const source = a.flags.source ? String(a.flags.source) : '';
686
+ const publication = a.flags.publication ? String(a.flags.publication) : '';
687
+ if (!source || !publication)
688
+ throw new Error("usage: koigrid db subs <id> verify --source 'postgres://…' --publication <pub> [--count-source 'postgres://réplica…'] [--no-wait]");
689
+ const body = { source, publication };
690
+ // `--count-source`: cuenta el origen contra una RÉPLICA suya, para no cargar la principal con count(*).
691
+ if (a.flags['count-source'])
692
+ body.countSource = String(a.flags['count-source']);
693
+ let r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/verify`, { method: 'POST', body });
694
+ // Es un TRABAJO: con una base grande el POST vuelve en curso y se sondea su estado hasta que termine.
695
+ const enCurso = (x) => ['queued', 'listing', 'counting'].includes(x?.verification?.status);
696
+ if (!a.flags['no-wait']) {
697
+ while (enCurso(r)) {
698
+ if (!json)
699
+ process.stderr.write(dim(` … ${r.verification.progress.tablas}/${r.verification.progress.totalTablas ?? '?'} tablas contadas\n`));
700
+ await new Promise((res) => setTimeout(res, 10_000));
701
+ r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/verify/${encodeURIComponent(r.verification.id)}`);
702
+ }
703
+ }
704
+ if (json)
705
+ return console.log(JSON.stringify(r, null, 2));
706
+ if (enCurso(r))
707
+ return console.log(`⏳ ${r.detalle}`);
708
+ if (!r.medido)
709
+ return console.log(`⚠️ ${r.detalle}`);
710
+ console.log(r.ok ? green(`✅ ${r.detalle}`) : `⛔ ${r.detalle}`);
711
+ return;
712
+ }
713
+ if (act === 'create') {
714
+ const name = a.positionals[2];
715
+ const source = a.flags.source ? String(a.flags.source) : '';
716
+ const publication = a.flags.publication ? String(a.flags.publication) : '';
717
+ if (!name || !source || !publication)
718
+ throw new Error("usage: koigrid db subs <id> create <name> --source 'postgres://…' --publication <pub> [--no-copy] [--force]");
719
+ const body = { name, source, publication };
720
+ if (a.flags['no-copy'])
721
+ body.copyData = false;
722
+ // `--force` se salta los BLOQUEOS del preflight. No es un atajo: queda en la auditoría, y los tres
723
+ // bloqueos son formas medidas de acabar con una copia incompleta sin un error que lo diga.
724
+ if (a.flags.force)
725
+ body.force = true;
726
+ // `--origin none`: recibir sólo lo escrito en el origen (replicar en dos direcciones sin bucles).
727
+ if (a.flags.origin)
728
+ body.origin = String(a.flags.origin);
729
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions`, { method: 'POST', body });
730
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Suscripción ${name} creada desde ${r.source}`));
731
+ }
732
+ if (act === 'rm' || act === 'delete') {
733
+ const name = a.positionals[2];
734
+ if (!name)
735
+ throw new Error('need <name>');
736
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions?name=${encodeURIComponent(name)}`, { method: 'DELETE' });
737
+ if (json)
738
+ return console.log(JSON.stringify(r, null, 2));
739
+ console.log(green(`✓ Suscripción ${name} borrada`));
740
+ // Un slot que koigrid no pudo borrar en el origen le llena el disco al cliente: se dice SIEMPRE, con la orden.
741
+ if (r?.slotRemoto?.estado === 'huerfano')
742
+ console.log(`⚠️ ${r.slotRemoto.aviso}\n En el ORIGEN: ${r.slotRemoto.retirar}`);
743
+ return;
744
+ }
745
+ if (act === 'sync-sequences') {
746
+ const source = a.flags.source ? String(a.flags.source) : '';
747
+ if (!source)
748
+ throw new Error("usage: koigrid db subs <id> sync-sequences --source 'postgres://…' [--margin 1000] [--dry-run]");
749
+ const body = { source };
750
+ if (a.flags.margin !== undefined)
751
+ body.margin = Number(a.flags.margin);
752
+ if (a.flags['dry-run'])
753
+ body.dryRun = true;
754
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/sync-sequences`, { method: 'POST', body });
755
+ if (json)
756
+ return console.log(JSON.stringify(r, null, 2));
757
+ return console.log(r.ok ? green(`✓ ${r.detalle}`) : `⛔ ${r.detalle}`);
758
+ }
759
+ if (act === 'update') {
760
+ const name = a.positionals[2];
761
+ if (!name)
762
+ throw new Error('usage: koigrid db subs <id> update <name> [--origin none|any] [--enable|--disable] [--refresh [--no-copy]]');
763
+ const body = { name };
764
+ if (a.flags.origin)
765
+ body.origin = String(a.flags.origin);
766
+ if (a.flags.enable)
767
+ body.enabled = true;
768
+ if (a.flags.disable)
769
+ body.enabled = false;
770
+ // `--refresh`: incorporar las tablas que el origen añadió a la publicación (créalas antes en koigrid).
771
+ if (a.flags.refresh)
772
+ body.refresh = true;
773
+ if (a.flags.refresh && a.flags['no-copy'])
774
+ body.copyData = false;
775
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions`, { method: 'PATCH', body });
776
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Suscripción ${name} cambiada${r.origin ? ` · origin=${r.origin}` : ''}${r.enabled === null ? '' : r.enabled ? ' · activa' : ' · desactivada'}${r.refresh ? ' · publicación refrescada' : ''}`));
777
+ }
778
+ throw new Error("usage: koigrid db subs <id> ls | preflight|verify --source 'postgres://…' --publication <pub> | create <name> --source 'postgres://…' --publication <pub> [--no-copy] [--force] [--origin none] | update <name> [--origin none|any] [--enable|--disable] [--refresh [--no-copy]] | sync-sequences --source 'postgres://…' [--margin N] [--dry-run] | rm <name>");
779
+ }
780
+ case 'resize': {
781
+ // MIG-B1: redimensionar una BD ya creada. RAM/CPU = rolling (sin corte en HA); disco = al instante.
782
+ need();
783
+ const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
784
+ if (a.flags.memory !== undefined)
785
+ body.memoryMb = Number(a.flags.memory);
786
+ if (a.flags.cpus !== undefined)
787
+ body.cpus = Number(a.flags.cpus);
788
+ if (a.flags.disk !== undefined)
789
+ body.diskGb = Number(a.flags.disk);
790
+ // `--max-disk <GB|off>`: techo hasta el que crece solo el disco (ficha 579556da, MaxAllocatedStorage de RDS).
791
+ if (a.flags['max-disk'] !== undefined)
792
+ body.maxDiskGb = ['off', 'none', 'null'].includes(String(a.flags['max-disk'])) ? null : Number(a.flags['max-disk']);
793
+ // `--in-window`: RAM/CPU en la ventana de mantenimiento de la base, no ya (como RDS con ApplyImmediately=false).
794
+ if (a.flags['in-window'])
795
+ body.applyImmediately = false;
796
+ if (!Object.keys(body).length)
797
+ throw new Error('usage: koigrid db resize <id> [--memory <MB>] [--cpus <n>] [--disk <GB>] [--max-disk <GB|off>] [--in-window]');
798
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body });
799
+ if (json)
800
+ return console.log(JSON.stringify(r, null, 2));
801
+ const d = r.database || r;
802
+ console.log(green(`✓ ${d.memoryMb} MB · ${d.cpus} vCPU · ${d.diskGb} GB${d.maxDiskGb != null ? ` · disk cap ${d.maxDiskGb} GB` : ''}`));
803
+ if (r.detail && body.maxDiskGb !== undefined)
804
+ console.log(' ' + r.detail);
805
+ if (r.scheduled)
806
+ console.log(` En la ventana de mantenimiento (${r.scheduled.maintenanceWindow} UTC): ${r.scheduled.memoryMb} MB · ${r.scheduled.cpus} vCPU desde ${r.scheduled.applyAt}`);
807
+ if (r.rolling)
808
+ console.log(' Recreando los nodos uno a uno (sin corte en HA). Sigue el avance con: koigrid db patching ' + id);
809
+ if (r.warning)
810
+ console.log(' ⚠️ ' + r.warning);
811
+ return;
812
+ }
813
+ case 'apply-config': {
814
+ // Recrea los nodos para que cojan la configuración que sólo se aplica al arrancar (credenciales de backup
815
+ // acotadas, límites). Mismo motor rolling que el parcheo.
816
+ need();
817
+ const r = await api(`/databases/${encodeURIComponent(id)}/apply-config`, { method: 'POST', body: {} });
818
+ if (json)
819
+ return console.log(JSON.stringify(r, null, 2));
820
+ console.log(green(`✓ Recreando ${r.members} nodo(s) para aplicar la configuración pendiente`));
821
+ if (r.downtime)
822
+ console.log(` ⚠️ ${r.downtime}`);
823
+ return console.log(` Sigue el avance con: koigrid db patching ${id}`);
824
+ }
825
+ case 'maintenance': {
826
+ // Lo que espera a la ventana de mantenimiento de la base y cuándo se aplicará (como las pending maintenance
827
+ // actions de RDS); `apply <action>` lo aplica ya.
828
+ need();
829
+ const act = a.positionals[1];
830
+ if (act === 'defer') {
831
+ // El reinicio de la máquina de una base de un solo miembro (ficha 3f180891): se aplaza, no se adelanta.
832
+ const until = a.positionals[2];
833
+ const r = await api(`/databases/${encodeURIComponent(id)}/maintenance/defer`, { method: 'POST', body: { action: 'host_reboot', ...(until ? { until } : {}) } });
834
+ if (json)
835
+ return console.log(JSON.stringify(r, null, 2));
836
+ return console.log(green(`✓ reinicio de la máquina aplazado: no antes de ${r.deferredUntil}`));
837
+ }
838
+ if (act === 'apply') {
839
+ const action = a.positionals[2];
840
+ if (!action)
841
+ throw new Error('usage: koigrid db maintenance <id> apply <resize|replication_verify_ca|minor_upgrade|dcs_tls>');
842
+ const r = await api(`/databases/${encodeURIComponent(id)}/maintenance/apply`, { method: 'POST', body: { action } });
843
+ if (json)
844
+ return console.log(JSON.stringify(r, null, 2));
845
+ console.log(green(`✓ '${r.action}' aplicado ya, sin esperar a la ventana`));
846
+ return console.log(' ' + JSON.stringify(r.result));
847
+ }
848
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
849
+ const d = r.database || r;
850
+ const pend = (d.pendingMaintenance ?? []);
851
+ if (json)
852
+ return console.log(JSON.stringify({ maintenanceWindow: d.maintenanceWindow ?? null, pendingMaintenance: pend }, null, 2));
853
+ console.log(`maintenance window: ${d.maintenanceWindow ?? '—'} UTC`);
854
+ if (!pend.length)
855
+ return console.log('no pending maintenance');
856
+ for (const m of pend) {
857
+ console.log(`• ${m.action}: ${m.description}`);
858
+ console.log(` impact: ${m.impact}`);
859
+ if (m.action === 'host_reboot')
860
+ console.log(` happens at ${m.autoAppliesAt} (${m.window}) · defer: koigrid db maintenance ${id} defer [<ISO date>]`);
861
+ else
862
+ console.log(` applies automatically at ${m.autoAppliesAt} (window ${m.window} UTC) · now: koigrid db maintenance ${id} apply ${m.action}`);
863
+ }
864
+ return;
865
+ }
866
+ case 'sync': {
867
+ // Réplica síncrona (ficha c21ac56a): el COMMIT espera a una réplica, así que un apagado brusco del líder no pierde
868
+ // lo confirmado. No estricta: si la réplica cae, la base sigue escribiendo (en asíncrono) y la salud lo avisa.
869
+ need();
870
+ const act = a.positionals[1];
871
+ if (!act || act === 'show') {
872
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
873
+ const d = r.database || r;
874
+ if (json)
875
+ return console.log(JSON.stringify({ synchronousReplication: d.synchronousReplication, sinReplicaSincronaDesde: d.sinReplicaSincronaDesde ?? null }, null, 2));
876
+ console.log(`synchronous replication: ${d.synchronousReplication ? 'ON' : 'OFF'}`);
877
+ if (d.synchronousReplication && d.sinReplicaSincronaDesde)
878
+ console.log(` ⚠️ no synchronous replica since ${d.sinReplicaSincronaDesde}: writing asynchronously until one is back`);
879
+ return;
880
+ }
881
+ if (act !== 'on' && act !== 'off')
882
+ throw new Error('usage: koigrid db sync <id> [show|on|off]');
883
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { synchronousReplication: act === 'on' } });
884
+ if (json)
885
+ return console.log(JSON.stringify(r, null, 2));
886
+ console.log(green(`✓ synchronous replication ${act.toUpperCase()}`));
887
+ return console.log(` ${r.applied ? '' : '⚠️ '}${r.detail ?? ''}`);
888
+ }
889
+ case 'slot-cap': {
890
+ // Tope de WAL por slot (ficha 6bd00dfb): max_slot_wal_keep_size en MB. Sin tope (el defecto) un consumidor parado
891
+ // llena el disco; con tope, Postgres invalida el slot pasado ese tamaño y su consumidor tiene que resincronizar.
892
+ need();
893
+ const act = a.positionals[1];
894
+ if (!act || act === 'show') {
895
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
896
+ const d = r.database || r;
897
+ if (json)
898
+ return console.log(JSON.stringify({ slotWalCapMb: d.slotWalCapMb ?? null }, null, 2));
899
+ return console.log(d.slotWalCapMb ? `slot WAL cap: ${d.slotWalCapMb} MB` : 'slot WAL cap: none (a stalled slot keeps WAL until the disk fills)');
900
+ }
901
+ const cap = act === 'off' ? null : Number(act);
902
+ if (cap !== null && !Number.isInteger(cap))
903
+ throw new Error('usage: koigrid db slot-cap <id> [show|<MB>|off]');
904
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { slotWalCapMb: cap } });
905
+ if (json)
906
+ return console.log(JSON.stringify(r, null, 2));
907
+ console.log(green(cap === null ? '✓ slot WAL cap removed' : `✓ slot WAL cap set to ${cap} MB`));
908
+ console.log(` ${r.applied ? '' : '⚠️ '}${r.detail ?? ''}`);
909
+ if (r.warning)
910
+ console.log(` ⚠️ ${r.warning}`);
911
+ return;
912
+ }
913
+ case 'patching': {
914
+ // DB-MINOR-PATCHING: parcheo automático de minors de PostgreSQL con ventana (estilo RDS). Activado al crear
915
+ // desde el 15-oct; la ventana se cambia pero no se quita (para no parchear: --auto off).
916
+ need();
917
+ const act = a.positionals[1];
918
+ if (!act || act === 'show') {
919
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
920
+ const d = r.database || r;
921
+ if (json)
922
+ return console.log(JSON.stringify({ autoMinorUpgrade: d.autoMinorUpgrade, maintenanceWindow: d.maintenanceWindow, lastPatchedAt: d.lastPatchedAt, patching: r.patching ?? null }, null, 2));
923
+ console.log(`auto minor upgrade: ${d.autoMinorUpgrade ? 'ON' : 'OFF'}`);
924
+ console.log(`maintenance window: ${d.maintenanceWindow ?? '— (sin ventana: no se parchea solo)'} UTC`);
925
+ if (r.patchingRecommendation)
926
+ console.log(` ⚠️ ${r.patchingRecommendation}`);
927
+ console.log(`running: ${d.postgres?.running ?? '?'} available: ${d.postgres?.available ?? '?'}${d.postgres?.behind ? ' ⚠️ parche pendiente' : ''}`);
928
+ return console.log(`last patched: ${String(d.lastPatchedAt ?? '—')}`);
929
+ }
930
+ if (act === 'set') {
931
+ const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
932
+ if (a.flags.auto !== undefined) {
933
+ const v = String(a.flags.auto);
934
+ body.autoMinorUpgrade = !(v === 'off' || v === 'false');
935
+ }
936
+ if (a.flags.window !== undefined)
937
+ body.maintenanceWindow = String(a.flags.window);
938
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body });
939
+ return console.log(json ? JSON.stringify(r.database || r, null, 2) : green('✓ Patching policy updated'));
940
+ }
941
+ throw new Error("usage: koigrid db patching <id> show | set --auto <on|off> --window <sun:03:00-04:00> (the window can be changed, not removed)");
942
+ }
259
943
  case 'data': {
260
944
  need();
261
945
  const table = a.positionals[1];
@@ -351,6 +1035,66 @@ export async function db(a) {
351
1035
  const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name: nm } });
352
1036
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Database renamed to "${nm}"`));
353
1037
  }
1038
+ case 'retention': {
1039
+ // Cambia cuántos días se guardan los backups. Bajarlo BORRA los que queden fuera en la próxima purga.
1040
+ const raw = a.positionals[0] === id ? a.positionals[1] : a.positionals[0];
1041
+ if (!id)
1042
+ throw new Error('usage: koigrid db retention <id> [días] (sin días: muestra la actual)');
1043
+ if (raw === undefined) {
1044
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
1045
+ return console.log(json ? JSON.stringify(r, null, 2) : `${r.database?.backupRetentionDays ?? 7} días`);
1046
+ }
1047
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { backupRetentionDays: Number(raw) } });
1048
+ if (json)
1049
+ return console.log(JSON.stringify(r, null, 2));
1050
+ console.log(green(`✓ Retención de backups: ${raw} días`));
1051
+ if (r.warning)
1052
+ console.log(`⚠️ ${r.warning}`);
1053
+ return;
1054
+ }
1055
+ case 'weekly': {
1056
+ // Copias completas semanales de largo plazo, además del PITR (0 = apagado, hasta 52). Bajarlo BORRA las que sobren.
1057
+ const raw = a.positionals[0] === id ? a.positionals[1] : a.positionals[0];
1058
+ if (!id)
1059
+ throw new Error('usage: koigrid db weekly <id> [semanas 0-52] (sin número: muestra la actual)');
1060
+ if (raw === undefined) {
1061
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
1062
+ return console.log(json ? JSON.stringify(r, null, 2) : `${r.database?.backupWeeklyKept ?? 0} copias semanales`);
1063
+ }
1064
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { backupWeeklyKept: Number(raw) } });
1065
+ if (json)
1066
+ return console.log(JSON.stringify(r, null, 2));
1067
+ console.log(green(`✓ Copias semanales de largo plazo: ${raw} (surte efecto en la poda de esta noche)`));
1068
+ if (r.warning)
1069
+ console.log(`⚠️ ${r.warning}`);
1070
+ costeDeCopiasLargas(r.longTermBackupCost);
1071
+ return;
1072
+ }
1073
+ case 'monthly': {
1074
+ // Copias completas MENSUALES de largo plazo (ficha c30b3491; 0 = apagado, hasta 24). Bajarlo BORRA las que sobren.
1075
+ const raw = a.positionals[0] === id ? a.positionals[1] : a.positionals[0];
1076
+ if (!id)
1077
+ throw new Error('usage: koigrid db monthly <id> [meses 0-24] (sin número: muestra la actual)');
1078
+ if (raw === undefined) {
1079
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
1080
+ return console.log(json ? JSON.stringify(r, null, 2) : `${r.database?.backupMonthlyKept ?? 0} copias mensuales`);
1081
+ }
1082
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { backupMonthlyKept: Number(raw) } });
1083
+ if (json)
1084
+ return console.log(JSON.stringify(r, null, 2));
1085
+ console.log(green(`✓ Copias mensuales de largo plazo: ${raw} (surte efecto en la poda de esta noche)`));
1086
+ if (r.warning)
1087
+ console.log(`⚠️ ${r.warning}`);
1088
+ costeDeCopiasLargas(r.longTermBackupCost);
1089
+ return;
1090
+ }
354
1091
  default: throw new Error(`unknown: db ${sub}`);
355
1092
  }
356
1093
  }
1094
+ /** El coste de las copias de largo plazo que devuelve el PATCH (ficha c30b3491): antes de que la poda las marque. */
1095
+ function costeDeCopiasLargas(c) {
1096
+ if (!c)
1097
+ return;
1098
+ const est = c.estimatedUsdMonth == null ? 'sin estimación (aún no hay copia completa medida)' : `~${c.estimatedGb} GB ≈ $${c.estimatedUsdMonth}/mes`;
1099
+ console.log(`💲 Copias de largo plazo: $${c.usdPerGbMonth}/GB-mes · ${est} · ${c.chargedFrom ? `se cobran desde ${c.chargedFrom}` : 'se miden, aún no se cobran'}`);
1100
+ }