koigrid 0.6.0 → 0.8.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 (50) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/dist/api.js +21 -3
  3. package/dist/args.js +19 -0
  4. package/dist/commands/analytics.js +1 -1
  5. package/dist/commands/apps.js +195 -19
  6. package/dist/commands/audit.js +1 -1
  7. package/dist/commands/billing.js +31 -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 +384 -16
  14. package/dist/commands/dns.js +1 -1
  15. package/dist/commands/errors.js +1 -1
  16. package/dist/commands/flags.js +1 -1
  17. package/dist/commands/heartbeats.js +3 -3
  18. package/dist/commands/images.js +1 -1
  19. package/dist/commands/jobs.js +39 -4
  20. package/dist/commands/links.js +59 -0
  21. package/dist/commands/logs.js +1 -1
  22. package/dist/commands/members.js +26 -1
  23. package/dist/commands/notices.js +24 -0
  24. package/dist/commands/notifications.js +2 -2
  25. package/dist/commands/otel.js +1 -1
  26. package/dist/commands/projects.js +1 -1
  27. package/dist/commands/queues.js +4 -3
  28. package/dist/commands/redis.js +18 -2
  29. package/dist/commands/registry.js +43 -3
  30. package/dist/commands/rewards.js +63 -0
  31. package/dist/commands/sandboxes.js +1 -1
  32. package/dist/commands/speed.js +1 -1
  33. package/dist/commands/spend.js +1 -1
  34. package/dist/commands/status.js +1 -1
  35. package/dist/commands/storage.js +31 -3
  36. package/dist/commands/support.js +47 -0
  37. package/dist/commands/tokens.js +2 -2
  38. package/dist/commands/up.js +6 -2
  39. package/dist/commands/waf.js +1 -1
  40. package/dist/commands/webhooks.js +1 -1
  41. package/dist/commands/wordpress.js +4 -3
  42. package/dist/commands/workflows.js +4 -3
  43. package/dist/index.js +13 -3
  44. package/dist/manifest.js +15 -10
  45. package/dist/output.js +1 -0
  46. package/dist/proyecto.js +6 -0
  47. package/dist/registry-flags.js +17 -0
  48. package/dist/registry.js +6 -2
  49. package/package.json +1 -1
  50. package/dist/commands/ai.js +0 -56
@@ -1,5 +1,9 @@
1
1
  import { api } from '../api.js';
2
- import { output, green } from '../output.js';
2
+ import { output, green, dim } from '../output.js';
3
+ import { proyectoDeFlags } from '../proyecto.js';
4
+ // Tamaño legible de una copia: sirve para VER de un vistazo si la incremental está funcionando (una delta
5
+ // ocupa un orden de magnitud menos que la completa de la que cuelga).
6
+ const fmtBytes = (n) => (n < 1048576 ? `${(n / 1024).toFixed(0)}KB` : n < 1073741824 ? `${(n / 1048576).toFixed(1)}MB` : `${(n / 1073741824).toFixed(2)}GB`);
3
7
  const fmtCell = (v) => (v === null || v === undefined ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
4
8
  export async function db(a) {
5
9
  const json = !!a.flags.json, sub = a.sub || 'ls', id = a.positionals[0];
@@ -10,30 +14,76 @@ export async function db(a) {
10
14
  case 'list': {
11
15
  const r = await api('/databases');
12
16
  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'] });
17
+ 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
18
  }
15
19
  case 'create': {
16
20
  const name = a.positionals[0];
17
21
  if (!name)
18
- throw new Error('usage: koigrid db create <name> [--replicas N]');
19
- const body = { name };
22
+ throw new Error('usage: koigrid db create <name> [--replicas N] [--project <id>]');
23
+ const body = { name, ...proyectoDeFlags(a) };
20
24
  if (a.flags.replicas)
21
25
  body.replicas = Number(a.flags.replicas);
22
26
  const r = await api('/databases', { method: 'POST', body });
23
27
  return console.log(json ? JSON.stringify(r.database || r, null, 2) : green(`✓ Creating "${name}"…`));
24
28
  }
29
+ // Por defecto se toma un SNAPSHOT FINAL antes de destruir (estilo RDS): permite volver a levantar la base
30
+ // más adelante con `db restore`. `--no-final-snapshot` lo salta (más rápido, sin red de vuelta).
31
+ case 'pause': {
32
+ // Apaga el cluster conservando los datos: los volúmenes no se tocan y reanudar tarda segundos.
33
+ need();
34
+ const r = await api(`/databases/${encodeURIComponent(id)}/pause`, { method: 'POST' });
35
+ if (json)
36
+ return console.log(JSON.stringify(r, null, 2));
37
+ return console.log(green(r.alreadyPaused ? `✓ ${id} ya estaba pausada` : `✓ ${id} pausada — datos intactos, reanuda con: koigrid db resume ${id}`));
38
+ }
39
+ case 'resume': {
40
+ need();
41
+ const r = await api(`/databases/${encodeURIComponent(id)}/resume`, { method: 'POST' });
42
+ if (json)
43
+ return console.log(JSON.stringify(r, null, 2));
44
+ if (r.alreadyRunning)
45
+ return console.log(green(`✓ ${id} no estaba pausada`));
46
+ return console.log(green(`✓ ${id} reanudándose${r.recreated ? ' (algún contenedor hubo que recrearlo)' : ''} — estado: ${r.database?.status}`));
47
+ }
25
48
  case 'rm':
26
- case 'delete':
49
+ case 'delete': {
27
50
  need();
28
- await api(`/databases/${encodeURIComponent(id)}`, { method: 'DELETE' });
29
- return console.log(green(`✓ Deleted ${id}`));
51
+ const sinCopia = Boolean(a.flags['no-final-snapshot']);
52
+ let ruta = `/databases/${encodeURIComponent(id)}`;
53
+ if (sinCopia)
54
+ ruta += '?finalSnapshot=false';
55
+ const r = await api(ruta, { method: 'DELETE' });
56
+ if (json)
57
+ return console.log(JSON.stringify(r, null, 2));
58
+ // La fecha la decide el servidor (90 días con snapshot final, la ventana de retención sin él).
59
+ const hasta = r?.backupsKeptUntil ? ` hasta ${String(r.backupsKeptUntil).slice(0, 10)}` : '';
60
+ return console.log(green(`✓ Deleted ${id}${sinCopia ? ` (sin snapshot final; copias${hasta})` : ` — snapshot final en curso; restaurable${hasta} con: koigrid db restore ${id}`}`));
61
+ }
30
62
  case 'url':
31
63
  case 'connection': {
32
64
  need();
33
65
  const r = await api(`/databases/${encodeURIComponent(id)}/connection`);
34
66
  if (json)
35
67
  return console.log(JSON.stringify(r.connection, null, 2));
68
+ // --direct: sólo la directa, para encadenarla (`psql "$(koigrid db url <id> --direct)" -f dump.sql`).
69
+ if (a.flags.direct) {
70
+ if (!r.connection?.directUri) {
71
+ console.error('this database has no direct endpoint');
72
+ process.exitCode = 1;
73
+ return;
74
+ }
75
+ // Siempre la de `require`: la verificable exige además el fichero de la CA, y encadenada sin él fallaría.
76
+ return console.log(r.connection.directUri);
77
+ }
36
78
  console.log(r.connection?.uri);
79
+ // La del pooler va en modo TRANSACCIÓN: lo que dependa de la sesión (pg_dump/psql -f, migradores con SET o
80
+ // advisory locks, LISTEN/NOTIFY) se rompe por ahí con errores que parecen del SQL. La directa existe para eso
81
+ // (ficha c41f5b8b), y se dice aquí porque es donde se busca la URL.
82
+ if (r.connection?.directUri)
83
+ console.log('# direct (migrations, pg_dump/psql restores — keeps the session, bypasses the pooler):', r.connection.directUri);
84
+ // Verificable (ficha ef7a926d): con caCert guardado en un fichero y sslrootcert=<fichero> en la URL.
85
+ if (r.connection?.directSslVerifiedUri)
86
+ console.log('# direct, TLS-verified (add sslrootcert=<file with caCert from --json>):', r.connection.directSslVerifiedUri);
37
87
  if (r.connection?.readUri)
38
88
  console.log('# read-only:', r.connection.readUri);
39
89
  return;
@@ -51,18 +101,41 @@ export async function db(a) {
51
101
  case 'metrics':
52
102
  need();
53
103
  return console.log(JSON.stringify(await api(`/databases/${encodeURIComponent(id)}/metrics`), null, 2));
54
- case 'logs':
104
+ // `db logs` sirve el log de POSTGRES por defecto (los ERROR de tu base), no el de Patroni. `--source
105
+ // patroni|both` cambia de capa y `--level problem` deja sólo lo que va mal. ⚠️ `note` e `ignored` se
106
+ // IMPRIMEN: si la API se ha tragado un parámetro o ha tenido que caer a otra fuente, callarlo aquí sería
107
+ // reintroducir en el CLI el silencio que esta ficha vino a quitar de la API (f3356147).
108
+ case 'logs': {
55
109
  need();
56
- return console.log((await api(`/databases/${encodeURIComponent(id)}/logs?tail=${a.flags.tail || 200}`)).logs || '');
110
+ const q = new URLSearchParams({ tail: String(a.flags.tail || 200) });
111
+ if (a.flags.source)
112
+ q.set('source', String(a.flags.source));
113
+ if (a.flags.level)
114
+ q.set('level', String(a.flags.level));
115
+ const r = await api(`/databases/${encodeURIComponent(id)}/logs?${q}`);
116
+ if (json)
117
+ return console.log(JSON.stringify(r, null, 2));
118
+ if (r.file)
119
+ console.log(dim(`# ${r.source} · ${r.file}`));
120
+ console.log(r.logs || '');
121
+ if (r.note)
122
+ console.log(dim(`# ${r.note}`));
123
+ if (r.ignored?.length)
124
+ console.log(dim(`# parámetros ignorados: ${r.ignored.join(', ')}`));
125
+ return;
126
+ }
127
+ // `--full` fuerza una copia COMPLETA en vez de la incremental que tocaría por cadencia. El listado muestra
128
+ // el modo: sin esa columna, "8 copias hechas" no dice si se puede restaurar barato o hay una cadena larga.
57
129
  case 'backups': {
58
130
  need();
59
131
  if (a.positionals[1] === 'create') {
60
- await api(`/databases/${encodeURIComponent(id)}/backups`, { method: 'POST' });
61
- return console.log(green('✓ Backup started'));
132
+ const full = Boolean(a.flags.full);
133
+ await api(`/databases/${encodeURIComponent(id)}/backups`, { method: 'POST', body: full ? { full: true } : {} });
134
+ return console.log(green(`✓ Backup started${full ? ' (full)' : ''} — runs in the background; follow it with: koigrid db backups ${id}`));
62
135
  }
63
136
  const r = await api(`/databases/${encodeURIComponent(id)}/backups`);
64
137
  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'] });
138
+ 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, at: String(x.createdAt || x.startedAt || '').slice(0, 16) })), columns: ['id', 'mode', 'why', 'size', 'status', 'at'] });
66
139
  }
67
140
  case 'restore': {
68
141
  need();
@@ -74,6 +147,77 @@ export async function db(a) {
74
147
  const r = await api(`/databases/${encodeURIComponent(id)}/restore`, { method: 'POST', body });
75
148
  return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Restoring to a new cluster…'));
76
149
  }
150
+ case 'restore-dump':
151
+ case 'import': {
152
+ // Managed restore (MIG-D): sube un dump .sql → lo restaura con pre-siembra de extensiones + conteo de filas.
153
+ need();
154
+ const file = (a.flags.file || a.flags.f || a.positionals[1]);
155
+ if (!file)
156
+ throw new Error('usage: koigrid db restore-dump <id> --file dump.sql [--pre-seed vector:extensions] [--wait]');
157
+ // Se sube SIEMPRE comprimido y EN STREAMING: (a) un readFileSync de un dump grande revienta el límite de
158
+ // Buffer de Node (~2 GB) y (b) gzip reduce ~8×, así un dump de 31 GB entra en el tope del servidor. Si el
159
+ // fichero ya es .gz se sube tal cual; si no, se comprime al vuelo sin escribir nada en disco.
160
+ const { createReadStream, statSync } = await import('node:fs');
161
+ const { createGzip } = await import('node:zlib');
162
+ const { Readable } = await import('node:stream');
163
+ const isGz = /\.gz$/i.test(String(file));
164
+ const srcBytes = statSync(String(file)).size;
165
+ if (!json)
166
+ console.log(`▸ subiendo ${(srcBytes / 1024 ** 3).toFixed(2)} GB${isGz ? ' (ya comprimido)' : ' (comprimiendo al vuelo…)'}`);
167
+ const up = await api(`/databases/${encodeURIComponent(id)}/restore-dump/upload-url`, { method: 'POST', body: { gzip: true } });
168
+ const raw = createReadStream(String(file));
169
+ const stream = isGz ? raw : raw.pipe(createGzip());
170
+ const put = await fetch(up.uploadUrl, {
171
+ method: 'PUT',
172
+ headers: { 'content-type': 'application/gzip' },
173
+ body: Readable.toWeb(stream),
174
+ duplex: 'half',
175
+ });
176
+ if (!put.ok)
177
+ throw new Error(`dump upload failed (HTTP ${put.status})`);
178
+ 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;
179
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore-dump`, { method: 'POST', body: { dumpKey: up.key, ...(preSeed ? { preSeed } : {}) } });
180
+ const jobId = r.restore?.id;
181
+ if (!a.flags.wait)
182
+ 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}`));
183
+ // ⛔ Se espera hasta el TECHO DEL SERVIDOR (6 h, `restoreTechoMs`) y no 30 min: el servidor no corta una restauración
184
+ // 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
185
+ // 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.
186
+ const hasta = Date.now() + 6.5 * 3600_000;
187
+ for (let i = 0; Date.now() < hasta; i++) {
188
+ await new Promise((res) => setTimeout(res, i < 1800 ? 2000 : 10_000));
189
+ const s = await api(`/databases/${encodeURIComponent(id)}/restore-dump/${jobId}`);
190
+ const st = s.restore?.status;
191
+ if (st === 'done') {
192
+ if (json)
193
+ return console.log(JSON.stringify(s.restore, null, 2));
194
+ console.log(green('✓ Restore done'));
195
+ for (const t of (s.restore?.tableCounts || []).slice(0, 40))
196
+ console.log(` ${t.table} ${t.rows}`);
197
+ return;
198
+ }
199
+ if (st === 'failed')
200
+ throw new Error(`restore failed: ${s.restore?.error || 'unknown'}`);
201
+ }
202
+ throw new Error('restore sigue en curso (timeout esperando)');
203
+ }
204
+ case 'fix-ownership': {
205
+ // A2: repara una BD que un restore anterior dejó con owner=postgres (el rol de la app no podía leer nada).
206
+ need();
207
+ const r = await api(`/databases/${encodeURIComponent(id)}/fix-ownership`, { method: 'POST', body: {} });
208
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Propiedad reparada: todo pertenece ya al rol ${r.role}`));
209
+ }
210
+ case 'restore-status': {
211
+ need();
212
+ const jobId = a.positionals[1];
213
+ if (!jobId) {
214
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore-dump`);
215
+ const l = r.restores || [];
216
+ 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'] });
217
+ }
218
+ const r = await api(`/databases/${encodeURIComponent(id)}/restore-dump/${encodeURIComponent(jobId)}`);
219
+ return console.log(json ? JSON.stringify(r.restore, null, 2) : `status: ${r.restore?.status}` + (r.restore?.error ? `\nerror: ${r.restore.error}` : ''));
220
+ }
77
221
  case 'ext':
78
222
  case 'extensions': {
79
223
  need();
@@ -82,7 +226,12 @@ export async function db(a) {
82
226
  const r = await api(`/databases/${encodeURIComponent(id)}/extensions`);
83
227
  return console.log(json ? JSON.stringify(r, null, 2) : 'allowed: ' + (r.allowed || []).join(', '));
84
228
  }
85
- const r = await api(`/databases/${encodeURIComponent(id)}/extensions`, { method: 'POST', body: { name } });
229
+ // `--schema` (paridad con la API): instala la extensión en ese schema. Es el camino de los ex-Supabase —
230
+ // sus dumps declaran tipos como `extensions.vector`, así que sin esto el restore falla con "type
231
+ // extensions.vector does not exist". La API lo soporta desde J7-2 y el CLI no podía pasarlo: un agente que
232
+ // usara el CLI se quedaba sin la única palanca que desbloquea a ese cliente.
233
+ const schema = typeof a.flags.schema === 'string' ? a.flags.schema : undefined;
234
+ const r = await api(`/databases/${encodeURIComponent(id)}/extensions`, { method: 'POST', body: schema ? { name, schema } : { name } });
86
235
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Extension ${name} installed`));
87
236
  }
88
237
  case 'replicas': {
@@ -193,7 +342,7 @@ export async function db(a) {
193
342
  }
194
343
  if (act === 'create') {
195
344
  if (!rname)
196
- throw new Error('usage: koigrid db roles <id> create <name> --password <pw> [--no-login] [--createdb]');
345
+ throw new Error('usage: koigrid db roles <id> create <name> --password <pw> [--no-login] [--createdb] [--read-only [--bypass-rls]]');
197
346
  const password = a.flags.password ? String(a.flags.password) : '';
198
347
  if (!password)
199
348
  throw new Error('--password required');
@@ -202,8 +351,12 @@ export async function db(a) {
202
351
  body.login = false;
203
352
  if (a.flags.createdb)
204
353
  body.createdb = true;
354
+ if (a.flags['read-only'])
355
+ body.readOnly = true;
356
+ if (a.flags['bypass-rls'])
357
+ body.bypassRls = true;
205
358
  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`));
359
+ return console.log(json ? JSON.stringify(r.role || r, null, 2) : green(`✓ Role ${rname} created${body.readOnly ? ' (read-only: SELECT only, writes rejected)' : ''}`));
207
360
  }
208
361
  if (act === 'password') {
209
362
  if (!rname)
@@ -220,7 +373,7 @@ export async function db(a) {
220
373
  await api(`/databases/${encodeURIComponent(id)}/roles/${encodeURIComponent(rname)}`, { method: 'DELETE' });
221
374
  return console.log(green(`✓ Role ${rname} dropped`));
222
375
  }
223
- throw new Error('usage: koigrid db roles <id> ls | create <name> --password <pw> [--no-login] [--createdb] | password <name> --password <pw> | rm <name>');
376
+ 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>');
224
377
  }
225
378
  case 'rotation': {
226
379
  need();
@@ -256,6 +409,204 @@ export async function db(a) {
256
409
  }
257
410
  throw new Error('usage: koigrid db rotation <id> show | set --interval <days|off> [--grace <days>] | rotate | migrate');
258
411
  }
412
+ case 'sub':
413
+ case 'subs': {
414
+ // J-INBOUND-REPL-MANAGED: migrar SIN ventana desde un Postgres externo, y saber cuándo se puede cambiar.
415
+ need();
416
+ const act = a.positionals[1];
417
+ if (!act || act === 'ls') {
418
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions`);
419
+ const l = r.subscriptions || [];
420
+ if (json)
421
+ return console.log(JSON.stringify(l, null, 2));
422
+ if (!l.length)
423
+ return console.log('(sin suscripciones)');
424
+ for (const s of l) {
425
+ const lag = s.lagBytes == null ? '?' : `${Math.round(s.lagBytes / 1024)} KB`;
426
+ // La COPIA va delante del retraso, y en la misma línea: un «retraso 0 KB» a solas es justo el dato
427
+ // que hizo creer que se podía migrar con 110 de 257 tablas copiadas.
428
+ const copia = s.tablas == null ? 'copia ?' : `copia ${s.tablas.listas}/${s.tablas.total}`;
429
+ console.log(`${s.cutover?.ready ? '✅' : '⏳'} ${s.name} ${s.enabled ? 'activa' : 'DESACTIVADA'} · ${copia} · retraso ${lag}`);
430
+ console.log(` ${s.cutover?.detail ?? ''}`);
431
+ }
432
+ return;
433
+ }
434
+ // `preflight` es la comprobación SIN crear nada: las tres trampas medidas migrando de RDS (RLS sin
435
+ // BYPASSRLS, CHECK sin validar, esquema desfasado) que dan una copia incompleta sin un error que lo diga.
436
+ if (act === 'preflight' || act === 'check') {
437
+ const source = a.flags.source ? String(a.flags.source) : '';
438
+ const publication = a.flags.publication ? String(a.flags.publication) : '';
439
+ if (!source || !publication)
440
+ throw new Error("usage: koigrid db subs <id> preflight --source 'postgres://…' --publication <pub>");
441
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/preflight`, { method: 'POST', body: { source, publication } });
442
+ if (json)
443
+ return console.log(JSON.stringify(r, null, 2));
444
+ // «No se pudo comprobar» se dice con todas las letras: una lista de bloqueos vacía porque no se pudo
445
+ // preguntar se lee igual que una porque no hay nada, y significan lo contrario.
446
+ if (!r.medido)
447
+ return console.log(`⚠️ ${r.detalle}\n${r.logs ? dim(r.logs) : ''}`);
448
+ if (r.ok)
449
+ console.log(green('✅ sin problemas: la copia inicial debería traerlo todo'));
450
+ else
451
+ console.log(`⛔ ${r.detalle}`);
452
+ if (r.avisos?.length)
453
+ for (const x of r.avisos)
454
+ console.log(` ⚠️ ${x.tabla ?? ''} ${x.detalle}`);
455
+ if (r.ignorados?.length)
456
+ console.log(dim(` (parámetros del origen que el preflight no traslada: ${r.ignorados.join(', ')})`));
457
+ return;
458
+ }
459
+ // `verify` es la comprobación de DESPUÉS: cuenta filas de los dos lados. Es lo único que destapa una
460
+ // tabla copiada a cero por RLS, que por dentro consta como terminada.
461
+ if (act === 'verify') {
462
+ const source = a.flags.source ? String(a.flags.source) : '';
463
+ const publication = a.flags.publication ? String(a.flags.publication) : '';
464
+ if (!source || !publication)
465
+ throw new Error("usage: koigrid db subs <id> verify --source 'postgres://…' --publication <pub> [--count-source 'postgres://réplica…'] [--no-wait]");
466
+ const body = { source, publication };
467
+ // `--count-source`: cuenta el origen contra una RÉPLICA suya, para no cargar la principal con count(*).
468
+ if (a.flags['count-source'])
469
+ body.countSource = String(a.flags['count-source']);
470
+ let r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/verify`, { method: 'POST', body });
471
+ // Es un TRABAJO: con una base grande el POST vuelve en curso y se sondea su estado hasta que termine.
472
+ const enCurso = (x) => ['queued', 'listing', 'counting'].includes(x?.verification?.status);
473
+ if (!a.flags['no-wait']) {
474
+ while (enCurso(r)) {
475
+ if (!json)
476
+ process.stderr.write(dim(` … ${r.verification.progress.tablas}/${r.verification.progress.totalTablas ?? '?'} tablas contadas\n`));
477
+ await new Promise((res) => setTimeout(res, 10_000));
478
+ r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/verify/${encodeURIComponent(r.verification.id)}`);
479
+ }
480
+ }
481
+ if (json)
482
+ return console.log(JSON.stringify(r, null, 2));
483
+ if (enCurso(r))
484
+ return console.log(`⏳ ${r.detalle}`);
485
+ if (!r.medido)
486
+ return console.log(`⚠️ ${r.detalle}`);
487
+ console.log(r.ok ? green(`✅ ${r.detalle}`) : `⛔ ${r.detalle}`);
488
+ return;
489
+ }
490
+ if (act === 'create') {
491
+ const name = a.positionals[2];
492
+ const source = a.flags.source ? String(a.flags.source) : '';
493
+ const publication = a.flags.publication ? String(a.flags.publication) : '';
494
+ if (!name || !source || !publication)
495
+ throw new Error("usage: koigrid db subs <id> create <name> --source 'postgres://…' --publication <pub> [--no-copy] [--force]");
496
+ const body = { name, source, publication };
497
+ if (a.flags['no-copy'])
498
+ body.copyData = false;
499
+ // `--force` se salta los BLOQUEOS del preflight. No es un atajo: queda en la auditoría, y los tres
500
+ // bloqueos son formas medidas de acabar con una copia incompleta sin un error que lo diga.
501
+ if (a.flags.force)
502
+ body.force = true;
503
+ // `--origin none`: recibir sólo lo escrito en el origen (replicar en dos direcciones sin bucles).
504
+ if (a.flags.origin)
505
+ body.origin = String(a.flags.origin);
506
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions`, { method: 'POST', body });
507
+ return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Suscripción ${name} creada desde ${r.source}`));
508
+ }
509
+ if (act === 'rm' || act === 'delete') {
510
+ const name = a.positionals[2];
511
+ if (!name)
512
+ throw new Error('need <name>');
513
+ await api(`/databases/${encodeURIComponent(id)}/subscriptions?name=${encodeURIComponent(name)}`, { method: 'DELETE' });
514
+ return console.log(green(`✓ Suscripción ${name} borrada`));
515
+ }
516
+ if (act === 'sync-sequences') {
517
+ const source = a.flags.source ? String(a.flags.source) : '';
518
+ if (!source)
519
+ throw new Error("usage: koigrid db subs <id> sync-sequences --source 'postgres://…' [--margin 1000] [--dry-run]");
520
+ const body = { source };
521
+ if (a.flags.margin !== undefined)
522
+ body.margin = Number(a.flags.margin);
523
+ if (a.flags['dry-run'])
524
+ body.dryRun = true;
525
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions/sync-sequences`, { method: 'POST', body });
526
+ if (json)
527
+ return console.log(JSON.stringify(r, null, 2));
528
+ return console.log(r.ok ? green(`✓ ${r.detalle}`) : `⛔ ${r.detalle}`);
529
+ }
530
+ if (act === 'update') {
531
+ const name = a.positionals[2];
532
+ if (!name)
533
+ throw new Error('usage: koigrid db subs <id> update <name> [--origin none|any] [--enable|--disable]');
534
+ const body = { name };
535
+ if (a.flags.origin)
536
+ body.origin = String(a.flags.origin);
537
+ if (a.flags.enable)
538
+ body.enabled = true;
539
+ if (a.flags.disable)
540
+ body.enabled = false;
541
+ const r = await api(`/databases/${encodeURIComponent(id)}/subscriptions`, { method: 'PATCH', body });
542
+ 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'}`));
543
+ }
544
+ 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] | sync-sequences --source 'postgres://…' [--margin N] [--dry-run] | rm <name>");
545
+ }
546
+ case 'resize': {
547
+ // MIG-B1: redimensionar una BD ya creada. RAM/CPU = rolling (sin corte en HA); disco = al instante.
548
+ need();
549
+ const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
550
+ if (a.flags.memory !== undefined)
551
+ body.memoryMb = Number(a.flags.memory);
552
+ if (a.flags.cpus !== undefined)
553
+ body.cpus = Number(a.flags.cpus);
554
+ if (a.flags.disk !== undefined)
555
+ body.diskGb = Number(a.flags.disk);
556
+ if (!Object.keys(body).length)
557
+ throw new Error('usage: koigrid db resize <id> [--memory <MB>] [--cpus <n>] [--disk <GB>]');
558
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body });
559
+ if (json)
560
+ return console.log(JSON.stringify(r, null, 2));
561
+ const d = r.database || r;
562
+ console.log(green(`✓ ${d.memoryMb} MB · ${d.cpus} vCPU · ${d.diskGb} GB`));
563
+ if (r.rolling)
564
+ console.log(' Recreando los nodos uno a uno (sin corte en HA). Sigue el avance con: koigrid db patching ' + id);
565
+ if (r.warning)
566
+ console.log(' ⚠️ ' + r.warning);
567
+ return;
568
+ }
569
+ case 'apply-config': {
570
+ // Recrea los nodos para que cojan la configuración que sólo se aplica al arrancar (credenciales de backup
571
+ // acotadas, límites). Mismo motor rolling que el parcheo.
572
+ need();
573
+ const r = await api(`/databases/${encodeURIComponent(id)}/apply-config`, { method: 'POST', body: {} });
574
+ if (json)
575
+ return console.log(JSON.stringify(r, null, 2));
576
+ console.log(green(`✓ Recreando ${r.members} nodo(s) para aplicar la configuración pendiente`));
577
+ if (r.downtime)
578
+ console.log(` ⚠️ ${r.downtime}`);
579
+ return console.log(` Sigue el avance con: koigrid db patching ${id}`);
580
+ }
581
+ case 'patching': {
582
+ // DB-MINOR-PATCHING: parcheo automático de minors de PostgreSQL, opt-in y con ventana (estilo RDS).
583
+ need();
584
+ const act = a.positionals[1];
585
+ if (!act || act === 'show') {
586
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
587
+ const d = r.database || r;
588
+ if (json)
589
+ return console.log(JSON.stringify({ autoMinorUpgrade: d.autoMinorUpgrade, maintenanceWindow: d.maintenanceWindow, lastPatchedAt: d.lastPatchedAt, patching: r.patching ?? null }, null, 2));
590
+ console.log(`auto minor upgrade: ${d.autoMinorUpgrade ? 'ON' : 'OFF'}`);
591
+ console.log(`maintenance window: ${d.maintenanceWindow ?? '— (sin ventana: no se parchea solo)'} UTC`);
592
+ console.log(`running: ${d.postgres?.running ?? '?'} available: ${d.postgres?.available ?? '?'}${d.postgres?.behind ? ' ⚠️ parche pendiente' : ''}`);
593
+ return console.log(`last patched: ${String(d.lastPatchedAt ?? '—')}`);
594
+ }
595
+ if (act === 'set') {
596
+ const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
597
+ if (a.flags.auto !== undefined) {
598
+ const v = String(a.flags.auto);
599
+ body.autoMinorUpgrade = !(v === 'off' || v === 'false');
600
+ }
601
+ if (a.flags.window !== undefined) {
602
+ const w = String(a.flags.window);
603
+ body.maintenanceWindow = (w === 'off' || w === 'none') ? null : w;
604
+ }
605
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body });
606
+ return console.log(json ? JSON.stringify(r.database || r, null, 2) : green('✓ Patching policy updated'));
607
+ }
608
+ throw new Error("usage: koigrid db patching <id> show | set --auto <on|off> --window <sun:03:00-04:00|off>");
609
+ }
259
610
  case 'data': {
260
611
  need();
261
612
  const table = a.positionals[1];
@@ -351,6 +702,23 @@ export async function db(a) {
351
702
  const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { name: nm } });
352
703
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Database renamed to "${nm}"`));
353
704
  }
705
+ case 'retention': {
706
+ // Cambia cuántos días se guardan los backups. Bajarlo BORRA los que queden fuera en la próxima purga.
707
+ const raw = a.positionals[0] === id ? a.positionals[1] : a.positionals[0];
708
+ if (!id)
709
+ throw new Error('usage: koigrid db retention <id> [días] (sin días: muestra la actual)');
710
+ if (raw === undefined) {
711
+ const r = await api(`/databases/${encodeURIComponent(id)}`);
712
+ return console.log(json ? JSON.stringify(r, null, 2) : `${r.database?.backupRetentionDays ?? 7} días`);
713
+ }
714
+ const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body: { backupRetentionDays: Number(raw) } });
715
+ if (json)
716
+ return console.log(JSON.stringify(r, null, 2));
717
+ console.log(green(`✓ Retención de backups: ${raw} días`));
718
+ if (r.warning)
719
+ console.log(`⚠️ ${r.warning}`);
720
+ return;
721
+ }
354
722
  default: throw new Error(`unknown: db ${sub}`);
355
723
  }
356
724
  }
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid dns — DNS Management (BYO: conecta tu zona + CRUD de records). Ver docs/DNS.md.
3
+ // koigrid dns — DNS Management (BYO: conecta tu zona + CRUD de records). Ver docs/products/DNS.md.
4
4
  export async function dns(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'zones';
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid errors — error tracking (Sentry-lite). Ver docs/ERRORS.md.
3
+ // koigrid errors — error tracking (Sentry-lite). Ver docs/products/ERRORS.md.
4
4
  export async function errors(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'ls';
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid flags — feature flags (activar/desactivar + rollout gradual). Ver docs/FLAGS.md.
3
+ // koigrid flags — feature flags (activar/desactivar + rollout gradual). Ver docs/products/FLAGS.md.
4
4
  export async function flags(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'ls';
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
- // koigrid heartbeats — cron monitoring (dead-man's switch). Ver docs/HEARTBEATS.md.
3
+ // koigrid heartbeats — cron monitoring (dead-man's switch). Ver docs/products/HEARTBEATS.md.
4
4
  export async function heartbeats(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'ls';
@@ -15,7 +15,7 @@ export async function heartbeats(a) {
15
15
  if (sub === 'create') {
16
16
  const name = a.positionals[0];
17
17
  if (!name)
18
- throw new Error('usage: koigrid heartbeats create "<name>" [--period 3600] [--grace 300] [--webhook URL]');
18
+ throw new Error('usage: koigrid heartbeats create "<name>" [--period 3600] [--grace 300] [--webhook URL] (grace ≤ max(86400, period))');
19
19
  const body = { name };
20
20
  if (a.flags.period !== undefined)
21
21
  body.periodSeconds = Number(a.flags.period);
@@ -36,7 +36,7 @@ export async function heartbeats(a) {
36
36
  if (sub === 'update') {
37
37
  const id = a.positionals[0];
38
38
  if (!id)
39
- throw new Error("usage: koigrid heartbeats update <id> [--period N] [--grace N] [--webhook URL] [--json '{…}']");
39
+ throw new Error("usage: koigrid heartbeats update <id> [--period N] [--grace N] [--webhook URL] [--json '{…}'] (grace ≤ max(86400, period))");
40
40
  const body = a.flags.json && a.flags.json !== true ? JSON.parse(String(a.flags.json)) : {};
41
41
  if (a.flags.period !== undefined)
42
42
  body.periodSeconds = Number(a.flags.period);
@@ -1,6 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { green } from '../output.js';
3
- // koigrid images — optimización de imágenes (allowlist anti-SSRF + token). Ver docs/IMAGES.md.
3
+ // koigrid images — optimización de imágenes (allowlist anti-SSRF + token). Ver docs/products/IMAGES.md.
4
4
  export async function images(a) {
5
5
  const json = !!a.flags.json;
6
6
  const sub = a.sub || 'config';
@@ -1,5 +1,36 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green } from '../output.js';
3
+ import { credencialRegistryDeFlags, AYUDA_REGISTRY } from '../registry-flags.js';
4
+ import { proyectoDeFlags } from '../proyecto.js';
5
+ /** Opciones de recursos y entorno de un job (create y update). Lo que traen las tareas programadas de ECS. */
6
+ function opcionesComunes(a) {
7
+ const b = {};
8
+ if (a.flags.timezone)
9
+ b.timezone = String(a.flags.timezone);
10
+ if (a.flags.memory !== undefined)
11
+ b.memoryMb = Number(a.flags.memory);
12
+ if (a.flags.cpus !== undefined)
13
+ b.cpus = Number(a.flags.cpus);
14
+ if (a.flags.timeout !== undefined)
15
+ b.timeoutSec = Number(a.flags.timeout);
16
+ if (a.flags['max-retries'] !== undefined)
17
+ b.maxRetries = Number(a.flags['max-retries']);
18
+ Object.assign(b, proyectoDeFlags(a));
19
+ if (a.flags.enabled !== undefined)
20
+ b.enabled = a.flags.enabled === 'true' || a.flags.enabled === true;
21
+ const envs = [].concat(a.flags.env ?? []);
22
+ if (envs.length) {
23
+ const env = {};
24
+ for (const kv of envs) {
25
+ const i = kv.indexOf('=');
26
+ if (i <= 0)
27
+ throw new Error(`--env needs K=V (got "${kv}")`);
28
+ env[kv.slice(0, i)] = kv.slice(i + 1);
29
+ }
30
+ b.env = env;
31
+ }
32
+ return b;
33
+ }
3
34
  export async function jobs(a) {
4
35
  const json = !!a.flags.json, sub = a.sub || 'ls';
5
36
  if (sub === 'ls' || sub === 'list') {
@@ -14,7 +45,7 @@ export async function jobs(a) {
14
45
  const image = a.flags.image;
15
46
  const url = a.flags.url;
16
47
  if (!name || !schedule || (!image && !url))
17
- throw new Error('usage: koigrid jobs create <name> --schedule "<cron>" (--image <img> [--command "..."] | --url <url> [--method POST] [--header "K: V"])');
48
+ throw new Error(`usage: koigrid jobs create <name> --schedule "<cron>" (--image <img> [--command "..."] ${AYUDA_REGISTRY} | --url <url> [--method POST] [--header "K: V"]) [--timezone Europe/Madrid] [--memory MB] [--cpus N] [--timeout s] [--max-retries N] [--env K=V]… [--project <id>] [--enabled false]`);
18
49
  const body = { name, schedule };
19
50
  if (url) {
20
51
  // Job HTTP: pega a una URL según el cron (no un contenedor). --header repetible ("K: V").
@@ -36,7 +67,9 @@ export async function jobs(a) {
36
67
  body.image = image;
37
68
  if (a.flags.command)
38
69
  body.command = a.flags.command;
70
+ Object.assign(body, credencialRegistryDeFlags(a)); // imagen privada (ECR/GHCR/…)
39
71
  }
72
+ Object.assign(body, opcionesComunes(a));
40
73
  const r = await api('/jobs', { method: 'POST', body });
41
74
  if (json)
42
75
  console.log(JSON.stringify(r, null, 2));
@@ -72,7 +105,7 @@ export async function jobs(a) {
72
105
  if (sub === 'update') {
73
106
  const id = a.positionals[0];
74
107
  if (!id)
75
- throw new Error('usage: koigrid jobs update <id> [--schedule ..] [--image ..] [--enabled true|false]');
108
+ throw new Error(`usage: koigrid jobs update <id> [--schedule ..] [--image ..] [--command ..] ${AYUDA_REGISTRY} [--registry-clear] [--timezone ..] [--memory MB] [--cpus N] [--timeout s] [--max-retries N] [--env K=V]… [--enabled true|false]`);
76
109
  const body = {};
77
110
  if (a.flags.schedule)
78
111
  body.schedule = a.flags.schedule;
@@ -80,8 +113,10 @@ export async function jobs(a) {
80
113
  body.image = a.flags.image;
81
114
  if (a.flags.command)
82
115
  body.command = a.flags.command;
83
- if (a.flags.enabled !== undefined)
84
- body.enabled = a.flags.enabled === 'true' || a.flags.enabled === true;
116
+ Object.assign(body, credencialRegistryDeFlags(a), opcionesComunes(a));
117
+ if (a.flags['registry-clear'])
118
+ body.registryClear = true;
119
+ delete body.projectId;
85
120
  const r = await api(`/jobs/${encodeURIComponent(id)}`, { method: 'PATCH', body });
86
121
  console.log(json ? JSON.stringify(r, null, 2) : green('✓ Job updated'));
87
122
  return;