koigrid 0.8.0 → 0.10.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.
@@ -1,5 +1,6 @@
1
1
  import { api } from '../api.js';
2
2
  import { output, green, dim } from '../output.js';
3
+ import { network } from './network.js';
3
4
  import { proyectoDeFlags } from '../proyecto.js';
4
5
  // Tamaño legible de una copia: sirve para VER de un vistazo si la incremental está funcionando (una delta
5
6
  // ocupa un orden de magnitud menos que la completa de la que cuelga).
@@ -75,6 +76,15 @@ export async function db(a) {
75
76
  // Siempre la de `require`: la verificable exige además el fichero de la CA, y encadenada sin él fallaría.
76
77
  return console.log(r.connection.directUri);
77
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
+ }
78
88
  console.log(r.connection?.uri);
79
89
  // La del pooler va en modo TRANSACCIÓN: lo que dependa de la sesión (pg_dump/psql -f, migradores con SET o
80
90
  // advisory locks, LISTEN/NOTIFY) se rompe por ahí con errores que parecen del SQL. La directa existe para eso
@@ -86,6 +96,9 @@ export async function db(a) {
86
96
  console.log('# direct, TLS-verified (add sslrootcert=<file with caCert from --json>):', r.connection.directSslVerifiedUri);
87
97
  if (r.connection?.readUri)
88
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);
89
102
  return;
90
103
  }
91
104
  case 'connect': {
@@ -98,9 +111,60 @@ export async function db(a) {
98
111
  const res = spawnSync('psql', [uri], { stdio: 'inherit' });
99
112
  return process.exit(res.status ?? 0);
100
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
+ }
101
127
  case 'metrics':
102
128
  need();
103
129
  return console.log(JSON.stringify(await api(`/databases/${encodeURIComponent(id)}/metrics`), null, 2));
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': {
157
+ need();
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
+ }
104
168
  // `db logs` sirve el log de POSTGRES por defecto (los ERROR de tu base), no el de Patroni. `--source
105
169
  // patroni|both` cambia de capa y `--level problem` deja sólo lo que va mal. ⚠️ `note` e `ignored` se
106
170
  // IMPRIMEN: si la API se ha tragado un parámetro o ha tenido que caer a otra fuente, callarlo aquí sería
@@ -112,9 +176,16 @@ export async function db(a) {
112
176
  q.set('source', String(a.flags.source));
113
177
  if (a.flags.level)
114
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)
115
184
  const r = await api(`/databases/${encodeURIComponent(id)}/logs?${q}`);
116
185
  if (json)
117
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)` : ''}`));
118
189
  if (r.file)
119
190
  console.log(dim(`# ${r.source} · ${r.file}`));
120
191
  console.log(r.logs || '');
@@ -135,7 +206,7 @@ export async function db(a) {
135
206
  }
136
207
  const r = await api(`/databases/${encodeURIComponent(id)}/backups`);
137
208
  const l = r.backups || r || [];
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'] });
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'] });
139
210
  }
140
211
  case 'restore': {
141
212
  need();
@@ -144,6 +215,8 @@ export async function db(a) {
144
215
  body.name = a.flags.name;
145
216
  if (a.flags.time)
146
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) */;
147
220
  const r = await api(`/databases/${encodeURIComponent(id)}/restore`, { method: 'POST', body });
148
221
  return console.log(json ? JSON.stringify(r, null, 2) : green('✓ Restoring to a new cluster…'));
149
222
  }
@@ -201,6 +274,14 @@ export async function db(a) {
201
274
  }
202
275
  throw new Error('restore sigue en curso (timeout esperando)');
203
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
+ }
204
285
  case 'fix-ownership': {
205
286
  // A2: repara una BD que un restore anterior dejó con owner=postgres (el rol de la app no podía leer nada).
206
287
  need();
@@ -244,6 +325,32 @@ export async function db(a) {
244
325
  const r = await api(`/databases/${encodeURIComponent(id)}/replicas`, { method: 'POST', body: { replicas: Number(n) } });
245
326
  return console.log(json ? JSON.stringify(r, null, 2) : green(`✓ Scaling to ${n} read replica(s)…`));
246
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
+ }
247
354
  case 'pub':
248
355
  case 'publications': {
249
356
  need();
@@ -338,15 +445,19 @@ export async function db(a) {
338
445
  if (!act || act === 'ls') {
339
446
  const r = await api(`/databases/${encodeURIComponent(id)}/roles`);
340
447
  const l = r.roles || [];
341
- 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'] });
342
449
  }
343
450
  if (act === 'create') {
344
451
  if (!rname)
345
- throw new Error('usage: koigrid db roles <id> create <name> --password <pw> [--no-login] [--createdb] [--read-only [--bypass-rls]]');
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>]');
346
453
  const password = a.flags.password ? String(a.flags.password) : '';
347
454
  if (!password)
348
455
  throw new Error('--password required');
349
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']);
350
461
  if (a.flags['no-login'])
351
462
  body.login = false;
352
463
  if (a.flags.createdb)
@@ -358,6 +469,22 @@ export async function db(a) {
358
469
  const r = await api(`/databases/${encodeURIComponent(id)}/roles`, { method: 'POST', body });
359
470
  return console.log(json ? JSON.stringify(r.role || r, null, 2) : green(`✓ Role ${rname} created${body.readOnly ? ' (read-only: SELECT only, writes rejected)' : ''}`));
360
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)'}`));
487
+ }
361
488
  if (act === 'password') {
362
489
  if (!rname)
363
490
  throw new Error('need <name>');
@@ -375,6 +502,99 @@ export async function db(a) {
375
502
  }
376
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>');
377
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]');
597
+ }
378
598
  case 'rotation': {
379
599
  need();
380
600
  const act = a.positionals[1];
@@ -426,7 +646,10 @@ export async function db(a) {
426
646
  // La COPIA va delante del retraso, y en la misma línea: un «retraso 0 KB» a solas es justo el dato
427
647
  // que hizo creer que se podía migrar con 110 de 257 tablas copiadas.
428
648
  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}`);
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}`);
430
653
  console.log(` ${s.cutover?.detail ?? ''}`);
431
654
  }
432
655
  return;
@@ -510,8 +733,14 @@ export async function db(a) {
510
733
  const name = a.positionals[2];
511
734
  if (!name)
512
735
  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`));
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;
515
744
  }
516
745
  if (act === 'sync-sequences') {
517
746
  const source = a.flags.source ? String(a.flags.source) : '';
@@ -530,7 +759,7 @@ export async function db(a) {
530
759
  if (act === 'update') {
531
760
  const name = a.positionals[2];
532
761
  if (!name)
533
- throw new Error('usage: koigrid db subs <id> update <name> [--origin none|any] [--enable|--disable]');
762
+ throw new Error('usage: koigrid db subs <id> update <name> [--origin none|any] [--enable|--disable] [--refresh [--no-copy]]');
534
763
  const body = { name };
535
764
  if (a.flags.origin)
536
765
  body.origin = String(a.flags.origin);
@@ -538,10 +767,15 @@ export async function db(a) {
538
767
  body.enabled = true;
539
768
  if (a.flags.disable)
540
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;
541
775
  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'}`));
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' : ''}`));
543
777
  }
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>");
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>");
545
779
  }
546
780
  case 'resize': {
547
781
  // MIG-B1: redimensionar una BD ya creada. RAM/CPU = rolling (sin corte en HA); disco = al instante.
@@ -553,13 +787,23 @@ export async function db(a) {
553
787
  body.cpus = Number(a.flags.cpus);
554
788
  if (a.flags.disk !== undefined)
555
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;
556
796
  if (!Object.keys(body).length)
557
- throw new Error('usage: koigrid db resize <id> [--memory <MB>] [--cpus <n>] [--disk <GB>]');
797
+ throw new Error('usage: koigrid db resize <id> [--memory <MB>] [--cpus <n>] [--disk <GB>] [--max-disk <GB|off>] [--in-window]');
558
798
  const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body });
559
799
  if (json)
560
800
  return console.log(JSON.stringify(r, null, 2));
561
801
  const d = r.database || r;
562
- console.log(green(`✓ ${d.memoryMb} MB · ${d.cpus} vCPU · ${d.diskGb} GB`));
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}`);
563
807
  if (r.rolling)
564
808
  console.log(' Recreando los nodos uno a uno (sin corte en HA). Sigue el avance con: koigrid db patching ' + id);
565
809
  if (r.warning)
@@ -578,8 +822,97 @@ export async function db(a) {
578
822
  console.log(` ⚠️ ${r.downtime}`);
579
823
  return console.log(` Sigue el avance con: koigrid db patching ${id}`);
580
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
+ }
581
913
  case 'patching': {
582
- // DB-MINOR-PATCHING: parcheo automático de minors de PostgreSQL, opt-in y con ventana (estilo RDS).
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).
583
916
  need();
584
917
  const act = a.positionals[1];
585
918
  if (!act || act === 'show') {
@@ -589,6 +922,8 @@ export async function db(a) {
589
922
  return console.log(JSON.stringify({ autoMinorUpgrade: d.autoMinorUpgrade, maintenanceWindow: d.maintenanceWindow, lastPatchedAt: d.lastPatchedAt, patching: r.patching ?? null }, null, 2));
590
923
  console.log(`auto minor upgrade: ${d.autoMinorUpgrade ? 'ON' : 'OFF'}`);
591
924
  console.log(`maintenance window: ${d.maintenanceWindow ?? '— (sin ventana: no se parchea solo)'} UTC`);
925
+ if (r.patchingRecommendation)
926
+ console.log(` ⚠️ ${r.patchingRecommendation}`);
592
927
  console.log(`running: ${d.postgres?.running ?? '?'} available: ${d.postgres?.available ?? '?'}${d.postgres?.behind ? ' ⚠️ parche pendiente' : ''}`);
593
928
  return console.log(`last patched: ${String(d.lastPatchedAt ?? '—')}`);
594
929
  }
@@ -598,14 +933,12 @@ export async function db(a) {
598
933
  const v = String(a.flags.auto);
599
934
  body.autoMinorUpgrade = !(v === 'off' || v === 'false');
600
935
  }
601
- if (a.flags.window !== undefined) {
602
- const w = String(a.flags.window);
603
- body.maintenanceWindow = (w === 'off' || w === 'none') ? null : w;
604
- }
936
+ if (a.flags.window !== undefined)
937
+ body.maintenanceWindow = String(a.flags.window);
605
938
  const r = await api(`/databases/${encodeURIComponent(id)}`, { method: 'PATCH', body });
606
939
  return console.log(json ? JSON.stringify(r.database || r, null, 2) : green('✓ Patching policy updated'));
607
940
  }
608
- throw new Error("usage: koigrid db patching <id> show | set --auto <on|off> --window <sun:03:00-04:00|off>");
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)");
609
942
  }
610
943
  case 'data': {
611
944
  need();
@@ -719,6 +1052,49 @@ export async function db(a) {
719
1052
  console.log(`⚠️ ${r.warning}`);
720
1053
  return;
721
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
+ }
722
1091
  default: throw new Error(`unknown: db ${sub}`);
723
1092
  }
724
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
+ }
@@ -1,11 +1,23 @@
1
1
  import { api } from '../api.js';
2
2
  import { output } from '../output.js';
3
+ // Filtros del feed (ficha 3e317f95): --type (repetible), --severity, --entity-type, --entity, --since/--until (ISO con
4
+ // zona), --hours, --limit, --cursor. Imprime el nextCursor para pedir la página siguiente.
3
5
  export async function events(a) {
4
6
  const json = !!a.flags.json, sub = a.sub || 'ls';
5
7
  if (sub === 'ls' || sub === 'list') {
6
- const r = await api('/events');
7
- const list = r.events || r || [];
8
- output(list, json, { rows: list.map((x) => ({ time: String(x.createdAt || '').slice(0, 16), type: x.type, message: (x.message || '').slice(0, 50) })), columns: ['time', 'type', 'message'] });
8
+ const q = new URLSearchParams();
9
+ const tipos = a.flags.type;
10
+ for (const t of Array.isArray(tipos) ? tipos : tipos != null ? [tipos] : [])
11
+ q.append('type', String(t));
12
+ const par = [['severity', 'severity'], ['entity-type', 'entityType'], ['entity', 'entityId'], ['hours', 'sinceHours'], ['since', 'since'], ['until', 'until'], ['limit', 'limit'], ['cursor', 'cursor']];
13
+ for (const [f, k] of par)
14
+ if (a.flags[f] != null && a.flags[f] !== true)
15
+ q.set(k, String(a.flags[f]));
16
+ const r = await api(`/events${q.size ? `?${q}` : ''}`);
17
+ const list = r.events || [];
18
+ output(json ? r : list, json, { rows: list.map((x) => ({ time: String(x.createdAt || '').slice(0, 19), type: x.type, message: (x.message || '').slice(0, 60) })), columns: ['time', 'type', 'message'] });
19
+ if (!json && r.nextCursor)
20
+ console.log(`\nmore: --cursor ${r.nextCursor}`);
9
21
  return;
10
22
  }
11
23
  if (sub === 'metrics') {