@altertable/cli 1.14.0 → 1.15.1

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 (2) hide show
  1. package/dist/cli.js +402 -12
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -9179,7 +9179,7 @@ function redactResponseBodyForDebug(body) {
9179
9179
  }
9180
9180
 
9181
9181
  // src/version.ts
9182
- var VERSION = "1.14.0";
9182
+ var VERSION = "1.15.1";
9183
9183
  var USER_AGENT = `altertable-cli/${VERSION}`;
9184
9184
 
9185
9185
  // src/lib/http.ts
@@ -12223,12 +12223,12 @@ function tablePlainWidth(columnWidths, columnCount) {
12223
12223
  return columnWidths.reduce((sum, width) => sum + width, 0) + (columnCount - 1) * COLUMN_GAP.length;
12224
12224
  }
12225
12225
  function computeNaturalColumnWidths(columns, renderedHeaders, renderedCells) {
12226
- return columns.map((_column, columnIndex) => {
12226
+ return columns.map((column, columnIndex) => {
12227
12227
  const values = [
12228
12228
  renderedHeaders[columnIndex] ?? "",
12229
12229
  ...renderedCells.map((cells) => cells[columnIndex] ?? "")
12230
12230
  ];
12231
- return Math.max(...values.map((value) => getVisibleTextWidth(value)), 1);
12231
+ return Math.max(...values.map((value) => getVisibleTextWidth(value)), column.minWidth ?? 1);
12232
12232
  });
12233
12233
  }
12234
12234
  function shrinkFlexColumnsToFit(columns, widths, terminalWidth) {
@@ -22987,6 +22987,370 @@ var queryShowCommand = defineCommand({
22987
22987
  }
22988
22988
  });
22989
22989
 
22990
+ // src/commands/query/lib/top.ts
22991
+ var DETAIL_CONCURRENCY = 8;
22992
+ var BYTES_WIDTH = 10;
22993
+ var TABLE_CHROME_LINES = 2;
22994
+ var SORT_VALUES = {
22995
+ elapsed: (row) => row.startedAtMs === undefined ? undefined : -row.startedAtMs,
22996
+ progress: (row) => row.progress,
22997
+ rows: (row) => row.rowsProcessed,
22998
+ memory: (row) => row.memoryBytes,
22999
+ disk: (row) => row.diskBytes
23000
+ };
23001
+ var QUERY_TOP_SORT_KEYS = Object.keys(SORT_VALUES);
23002
+ async function fetchQueryTopSnapshot(execution, sortKey) {
23003
+ const listResponse = await sendHttp(buildLakehouseQueryListRequest(), execution);
23004
+ const listed = parseRunningQueries(parseApiJson(listResponse));
23005
+ const details = await mapWithConcurrency(listed, DETAIL_CONCURRENCY, (query) => fetchQueryDetails(query.id, execution));
23006
+ const queries = listed.map((query, index) => ({
23007
+ ...query,
23008
+ details: details[index] ?? null
23009
+ }));
23010
+ const sortValue = (entry) => SORT_VALUES[sortKey](toQueryTopRow(entry)) ?? -Infinity;
23011
+ queries.sort((left, right) => sortValue(right) - sortValue(left));
23012
+ return { queries };
23013
+ }
23014
+ function renderQueryTopTable(snapshot, options = {}) {
23015
+ if (snapshot.queries.length === 0) {
23016
+ return "No running queries.";
23017
+ }
23018
+ const { nowMs = Date.now(), ...tableOptions } = options;
23019
+ const columns = [
23020
+ { header: "id", cell: (row) => row.id },
23021
+ { header: "started", cell: (row) => formatClockTime(row.startedAtMs) },
23022
+ {
23023
+ header: "elapsed",
23024
+ cell: (row) => formatElapsed(row.durationMs ?? elapsedSince(row, nowMs)),
23025
+ minWidth: 9
23026
+ },
23027
+ { header: "progress", cell: (row) => formatPercentage(row.progress) },
23028
+ { header: "rows", cell: formatRowsCell, minWidth: 16 },
23029
+ { header: "compute size", cell: (row) => row.computeSize ?? "-" },
23030
+ { header: "worker", cell: (row) => row.workerSlug ?? "-" },
23031
+ {
23032
+ header: "mem",
23033
+ cell: (row) => formatBytes(row.memoryBytes),
23034
+ minWidth: BYTES_WIDTH
23035
+ },
23036
+ {
23037
+ header: "disk",
23038
+ cell: (row) => formatBytes(row.diskBytes),
23039
+ minWidth: BYTES_WIDTH
23040
+ },
23041
+ { header: "client", cell: (row) => row.userAgent ?? "-" },
23042
+ {
23043
+ header: "query",
23044
+ cell: (row) => formatStatement(row.statement),
23045
+ flex: true
23046
+ }
23047
+ ];
23048
+ return renderFixedTable(snapshot.queries.map(toQueryTopRow), columns, undefined, tableOptions);
23049
+ }
23050
+ function createQueryTopFrameRenderer(fetchSnapshot, options) {
23051
+ let snapshot = { queries: [] };
23052
+ return async (viewport) => {
23053
+ let errorMessage;
23054
+ try {
23055
+ snapshot = await fetchSnapshot();
23056
+ } catch (error) {
23057
+ errorMessage = error instanceof Error ? error.message : String(error);
23058
+ }
23059
+ return renderQueryTopFrame(snapshot, {
23060
+ ...options,
23061
+ nowMs: Date.now(),
23062
+ errorMessage,
23063
+ maxRows: viewport.rows
23064
+ });
23065
+ };
23066
+ }
23067
+ function renderQueryTopFrame(snapshot, options) {
23068
+ const { queries } = snapshot;
23069
+ const lines = [
23070
+ renderDisplayText([
23071
+ span(pluralizeLabel(queries.length, "running query", "running queries"), "strong"),
23072
+ span(` \xB7 sorted by ${options.sortKey}` + ` \xB7 refreshed ${formatClockTime(options.nowMs)}` + ` \xB7 every ${formatElapsed(options.intervalMs)} \xB7 Ctrl+C to quit`, "subtle")
23073
+ ])
23074
+ ];
23075
+ if (options.errorMessage !== undefined) {
23076
+ lines.push(renderDisplayText([span(options.errorMessage, "error")]));
23077
+ }
23078
+ lines.push("");
23079
+ const rowBudget = options.maxRows === undefined ? Infinity : Math.max(2, options.maxRows - lines.length - TABLE_CHROME_LINES);
23080
+ const overflows = queries.length > rowBudget;
23081
+ const shown = overflows ? queries.slice(0, rowBudget - 1) : queries;
23082
+ lines.push(renderQueryTopTable({ queries: shown }, { nowMs: options.nowMs }));
23083
+ if (overflows) {
23084
+ lines.push(renderDisplayText([
23085
+ span(`\u2026 ${queries.length - shown.length} more`, "subtle")
23086
+ ]));
23087
+ }
23088
+ return lines.join(`
23089
+ `);
23090
+ }
23091
+ function toQueryTopRow(entry) {
23092
+ const details = entry.details ?? {};
23093
+ const worker = isRecord(details.worker) ? details.worker : {};
23094
+ const progress = optionalNumber(details.percentage);
23095
+ return {
23096
+ id: entry.id,
23097
+ startedAtMs: optionalTimestamp(details.start_time) ?? optionalTimestamp(entry.started_at),
23098
+ durationMs: optionalNumber(details.duration_ms),
23099
+ statement: optionalString(details.query),
23100
+ progress: progress !== undefined && progress >= 0 ? progress : undefined,
23101
+ rowsProcessed: optionalNumber(details.rows_processed),
23102
+ estimatedTotalRows: optionalNumber(details.total_rows),
23103
+ computeSize: optionalString(worker.compute_size),
23104
+ workerSlug: optionalString(worker.slug),
23105
+ userAgent: optionalString(details.user_agent),
23106
+ memoryBytes: optionalNumber(worker.memory_usage_bytes),
23107
+ diskBytes: sumTemporaryStorageBytes(worker.memory_by_tag)
23108
+ };
23109
+ }
23110
+ function parseRunningQueries(data) {
23111
+ if (!isRecord(data) || !Array.isArray(data.queries)) {
23112
+ return [];
23113
+ }
23114
+ return data.queries.filter(isRecord).flatMap((query) => typeof query.id === "string" ? [
23115
+ {
23116
+ id: query.id,
23117
+ started_at: optionalString(query.started_at) ?? null
23118
+ }
23119
+ ] : []);
23120
+ }
23121
+ async function fetchQueryDetails(queryId, execution) {
23122
+ try {
23123
+ const response = await sendHttp(buildLakehouseQueryShowRequest(queryId), execution);
23124
+ const data = parseApiJson(response);
23125
+ return isRecord(data) ? data : null;
23126
+ } catch {
23127
+ return null;
23128
+ }
23129
+ }
23130
+ async function mapWithConcurrency(items, limit, mapper) {
23131
+ const results = [];
23132
+ let nextIndex = 0;
23133
+ async function worker() {
23134
+ for (let index = nextIndex++;index < items.length; index = nextIndex++) {
23135
+ results[index] = await mapper(items[index]);
23136
+ }
23137
+ }
23138
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
23139
+ return results;
23140
+ }
23141
+ function sumTemporaryStorageBytes(memoryByTag) {
23142
+ if (!Array.isArray(memoryByTag)) {
23143
+ return;
23144
+ }
23145
+ return memoryByTag.filter(isRecord).reduce((total, tag) => total + (optionalNumber(tag.temporary_storage_bytes) ?? 0), 0);
23146
+ }
23147
+ function optionalString(value) {
23148
+ return typeof value === "string" ? value : undefined;
23149
+ }
23150
+ function optionalNumber(value) {
23151
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
23152
+ }
23153
+ function optionalTimestamp(value) {
23154
+ const parsed = typeof value === "string" ? Date.parse(value) : Number.NaN;
23155
+ return Number.isNaN(parsed) ? undefined : parsed;
23156
+ }
23157
+ function elapsedSince(row, nowMs) {
23158
+ return row.startedAtMs === undefined ? undefined : Math.max(0, nowMs - row.startedAtMs);
23159
+ }
23160
+ function formatRowsCell(row) {
23161
+ if (!row.rowsProcessed && !row.estimatedTotalRows) {
23162
+ return "-";
23163
+ }
23164
+ return `${formatCount(row.rowsProcessed)} / ~${formatCount(row.estimatedTotalRows)}`;
23165
+ }
23166
+ function formatStatement(statement) {
23167
+ return statement === undefined ? "-" : statement.replace(/\s+/g, " ").trim();
23168
+ }
23169
+ function formatClockTime(timestampMs) {
23170
+ if (timestampMs === undefined) {
23171
+ return "-";
23172
+ }
23173
+ const date = new Date(timestampMs);
23174
+ return [date.getHours(), date.getMinutes(), date.getSeconds()].map((part) => String(part).padStart(2, "0")).join(":");
23175
+ }
23176
+ function formatElapsed(milliseconds) {
23177
+ if (milliseconds === undefined) {
23178
+ return "-";
23179
+ }
23180
+ if (milliseconds < 1000) {
23181
+ return `${Math.round(milliseconds)}ms`;
23182
+ }
23183
+ const totalSeconds = Math.floor(milliseconds / 1000);
23184
+ if (totalSeconds < 60) {
23185
+ return `${(milliseconds / 1000).toFixed(1).replace(/\.0$/, "")}s`;
23186
+ }
23187
+ const hours = Math.floor(totalSeconds / 3600);
23188
+ const minutes = Math.floor(totalSeconds % 3600 / 60);
23189
+ const seconds = String(totalSeconds % 60).padStart(2, "0");
23190
+ return hours > 0 ? `${hours}h${String(minutes).padStart(2, "0")}m${seconds}s` : `${minutes}m${seconds}s`;
23191
+ }
23192
+ function formatPercentage(value) {
23193
+ return value === undefined ? "-" : `${value.toFixed(1)}%`;
23194
+ }
23195
+ var COUNT_UNITS = [
23196
+ { value: 1000000000000, suffix: "T" },
23197
+ { value: 1e9, suffix: "B" },
23198
+ { value: 1e6, suffix: "M" },
23199
+ { value: 1000, suffix: "K" }
23200
+ ];
23201
+ function formatCount(value) {
23202
+ if (value === undefined) {
23203
+ return "?";
23204
+ }
23205
+ const unit = COUNT_UNITS.find((candidate) => Math.abs(value) >= candidate.value);
23206
+ if (unit === undefined) {
23207
+ return String(Math.round(value));
23208
+ }
23209
+ return `${(value / unit.value).toFixed(1).replace(/\.0$/, "")}${unit.suffix}`;
23210
+ }
23211
+ var BYTE_UNITS = ["B", "KiB", "MiB", "GiB", "TiB"];
23212
+ function formatBytes(value) {
23213
+ if (value === undefined) {
23214
+ return "-";
23215
+ }
23216
+ let scaled = value;
23217
+ let unitIndex = 0;
23218
+ while (Math.abs(scaled) >= 1024 && unitIndex < BYTE_UNITS.length - 1) {
23219
+ scaled /= 1024;
23220
+ unitIndex++;
23221
+ }
23222
+ const digits = unitIndex === 0 ? 0 : 1;
23223
+ return `${scaled.toFixed(digits)} ${BYTE_UNITS[unitIndex]}`;
23224
+ }
23225
+
23226
+ // src/ui/terminal/live-view.ts
23227
+ var CSI2 = "\x1B[";
23228
+ var ENTER_SCREEN = `${CSI2}?1049h${CSI2}?25l`;
23229
+ var LEAVE_SCREEN = `${CSI2}?25h${CSI2}?1049l`;
23230
+ async function runLiveView(options) {
23231
+ const controller = new AbortController;
23232
+ const interrupt = () => controller.abort();
23233
+ process.on("SIGINT", interrupt);
23234
+ await options.write(ENTER_SCREEN);
23235
+ try {
23236
+ while (!controller.signal.aborted) {
23237
+ const frame = await untilAborted(options.render({ rows: process.stdout.rows }), controller.signal);
23238
+ if (frame === undefined || controller.signal.aborted) {
23239
+ return;
23240
+ }
23241
+ await options.write(redrawInPlace(frame));
23242
+ await abortableSleep(options.intervalMs, controller.signal);
23243
+ }
23244
+ } finally {
23245
+ process.off("SIGINT", interrupt);
23246
+ await options.write(LEAVE_SCREEN);
23247
+ }
23248
+ }
23249
+ function redrawInPlace(frame) {
23250
+ const body = frame.split(`
23251
+ `).map((line) => `${line}${CSI2}K`).join(`
23252
+ `);
23253
+ return `${CSI2}H${body}${CSI2}J`;
23254
+ }
23255
+ async function untilAborted(promise, signal) {
23256
+ let onAbort = () => {};
23257
+ const aborted = new Promise((resolve) => {
23258
+ onAbort = () => resolve(undefined);
23259
+ if (signal.aborted)
23260
+ onAbort();
23261
+ signal.addEventListener("abort", onAbort, { once: true });
23262
+ });
23263
+ try {
23264
+ return await Promise.race([promise, aborted]);
23265
+ } finally {
23266
+ signal.removeEventListener("abort", onAbort);
23267
+ }
23268
+ }
23269
+ function abortableSleep(milliseconds, signal) {
23270
+ return new Promise((resolve) => {
23271
+ const timer = setTimeout(done, milliseconds);
23272
+ signal.addEventListener("abort", done, { once: true });
23273
+ function done() {
23274
+ clearTimeout(timer);
23275
+ signal.removeEventListener("abort", done);
23276
+ resolve();
23277
+ }
23278
+ });
23279
+ }
23280
+
23281
+ // src/commands/query/top.ts
23282
+ var queryTopCommand = defineCommand({
23283
+ metadata: {
23284
+ name: "top",
23285
+ description: "Show running queries with progress, rows, and memory; --watch refreshes live.",
23286
+ examples: [
23287
+ "altertable query top",
23288
+ "altertable query top --watch",
23289
+ "altertable query top -w --interval 5",
23290
+ "altertable query top --sort memory"
23291
+ ]
23292
+ },
23293
+ args: {
23294
+ watch: {
23295
+ type: "boolean",
23296
+ alias: "w",
23297
+ description: "Keep refreshing the view until interrupted (Ctrl+C)"
23298
+ },
23299
+ interval: {
23300
+ type: "string",
23301
+ description: "Seconds between refreshes in --watch mode",
23302
+ default: "1",
23303
+ valueHint: "SECONDS"
23304
+ },
23305
+ sort: {
23306
+ type: "enum",
23307
+ description: "Column to sort by, largest first",
23308
+ options: QUERY_TOP_SORT_KEYS,
23309
+ default: "elapsed"
23310
+ }
23311
+ },
23312
+ async run({ args, execution, sink }) {
23313
+ const intervalMs = parseIntervalMs(stringArg(args, "interval"));
23314
+ const sortKey = enumArg(args, "sort", QUERY_TOP_SORT_KEYS);
23315
+ const fetchSnapshot = () => fetchQueryTopSnapshot(execution, sortKey);
23316
+ if (!booleanArg(args, "watch")) {
23317
+ const snapshot = await fetchSnapshot();
23318
+ if (sink.json) {
23319
+ sink.writeJson(snapshot);
23320
+ return;
23321
+ }
23322
+ sink.writeHuman(renderQueryTopTable(snapshot, {
23323
+ horizontalScroll: process.stdout.isTTY !== true
23324
+ }));
23325
+ return;
23326
+ }
23327
+ if (sink.json) {
23328
+ throw new CliError("--watch cannot be combined with --json or --agent.");
23329
+ }
23330
+ if (process.stdout.isTTY !== true) {
23331
+ throw new CliError("--watch requires an interactive terminal.");
23332
+ }
23333
+ const encoder = new TextEncoder;
23334
+ await runLiveView({
23335
+ intervalMs,
23336
+ render: createQueryTopFrameRenderer(fetchSnapshot, {
23337
+ intervalMs,
23338
+ sortKey
23339
+ }),
23340
+ write: (text) => sink.writeBytes(encoder.encode(text))
23341
+ });
23342
+ }
23343
+ });
23344
+ var MIN_INTERVAL_MS = 200;
23345
+ function parseIntervalMs(value) {
23346
+ const seconds = Number(value.trim());
23347
+ const intervalMs = Math.round(seconds * 1000);
23348
+ if (!Number.isFinite(seconds) || intervalMs < MIN_INTERVAL_MS) {
23349
+ throw new CliError(`Invalid --interval: must be a number of seconds >= ${MIN_INTERVAL_MS / 1000}.`);
23350
+ }
23351
+ return intervalMs;
23352
+ }
23353
+
22990
23354
  // src/commands/query/index.ts
22991
23355
  var queryCommand = defineCommand({
22992
23356
  metadata: {
@@ -22999,13 +23363,15 @@ var queryCommand = defineCommand({
22999
23363
  'altertable query "SELECT 1" --format csv --output results.csv',
23000
23364
  "altertable query @report.sql --format csv --output results.csv",
23001
23365
  "altertable query list",
23002
- "altertable query show <query-id>"
23366
+ "altertable query show <query-id>",
23367
+ "altertable query top --watch"
23003
23368
  ]
23004
23369
  },
23005
23370
  args: queryRunArgs,
23006
23371
  subcommands: {
23007
23372
  list: queryListCommand,
23008
23373
  show: queryShowCommand,
23374
+ top: queryTopCommand,
23009
23375
  cancel: queryCancelCommand
23010
23376
  },
23011
23377
  async run({ args, rawArgs, execution, sink }) {
@@ -23405,7 +23771,8 @@ var UpdaterConfig = {
23405
23771
  sources: UpdaterSourceConfig,
23406
23772
  timeoutsMs: {
23407
23773
  automatic: 900,
23408
- manual: 1e4
23774
+ manual: 1e4,
23775
+ download: 300000
23409
23776
  },
23410
23777
  intervalsMs: UpdaterIntervalsMs,
23411
23778
  automaticCheckSkipCommands: ["completion", "doctor", "update", "upgrade"],
@@ -23684,9 +24051,33 @@ async function fetchText(url, timeoutMs, fetchImpl) {
23684
24051
  const response = await fetchResponse(url, timeoutMs, fetchImpl);
23685
24052
  return await response.text();
23686
24053
  }
23687
- async function fetchBytes(url, timeoutMs, fetchImpl) {
23688
- const response = await fetchResponse(url, timeoutMs, fetchImpl);
23689
- return new Uint8Array(await response.arrayBuffer());
24054
+ function isTimeoutAbort(error) {
24055
+ return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
24056
+ }
24057
+ function errorMessage(error) {
24058
+ return error instanceof Error ? error.message : String(error);
24059
+ }
24060
+ function downloadError(label, timeoutMs, error) {
24061
+ if (isTimeoutAbort(error)) {
24062
+ return new TimeoutError(`Timed out downloading ${label} after ${timeoutMs / 1000}s.`, { cause: error });
24063
+ }
24064
+ return new NetworkError(`Unable to download ${label}: ${errorMessage(error)}`, { cause: error });
24065
+ }
24066
+ async function fetchBytes(url, label, timeoutMs, fetchImpl) {
24067
+ let response;
24068
+ try {
24069
+ response = await fetchResponse(url, timeoutMs, fetchImpl);
24070
+ } catch (error) {
24071
+ if (error instanceof NetworkError) {
24072
+ throw downloadError(label, timeoutMs, error.cause);
24073
+ }
24074
+ throw error;
24075
+ }
24076
+ try {
24077
+ return new Uint8Array(await response.arrayBuffer());
24078
+ } catch (error) {
24079
+ throw downloadError(label, timeoutMs, error);
24080
+ }
23690
24081
  }
23691
24082
  function readStringProperty(data, key) {
23692
24083
  if (typeof data !== "object" || data === null || !(key in data)) {
@@ -23960,7 +24351,7 @@ function resolveGitHubBinaryTarget(options) {
23960
24351
  async function writeVerifiedGitHubBinaryDownload(options) {
23961
24352
  const tempPath = tempSiblingPath2(options.targetPath, "download");
23962
24353
  try {
23963
- const bytes = await fetchBytes(options.release.assetDownloadUrl, options.timeoutMs, options.fetchImpl);
24354
+ const bytes = await fetchBytes(options.release.assetDownloadUrl, options.release.assetName, options.downloadTimeoutMs, options.fetchImpl);
23964
24355
  writeFileSync3(tempPath, bytes, { mode: 493 });
23965
24356
  const checksumsText = await fetchText(options.release.checksumsDownloadUrl, options.timeoutMs, options.fetchImpl);
23966
24357
  const expectedHash = parseChecksums(checksumsText).get(options.release.assetName);
@@ -23977,9 +24368,7 @@ async function writeVerifiedGitHubBinaryDownload(options) {
23977
24368
  if (error instanceof CliError) {
23978
24369
  throw error;
23979
24370
  }
23980
- throw new CliError("Unable to install GitHub release binary.", {
23981
- cause: error
23982
- });
24371
+ throw new CliError(`Unable to install GitHub release binary: ${errorMessage(error)}`, { cause: error });
23983
24372
  }
23984
24373
  }
23985
24374
  async function installGitHubBinaryRelease(version, options = {}) {
@@ -23996,6 +24385,7 @@ async function installGitHubBinaryRelease(version, options = {}) {
23996
24385
  release,
23997
24386
  targetPath,
23998
24387
  timeoutMs,
24388
+ downloadTimeoutMs: options.downloadTimeoutMs ?? UpdaterConfig.timeoutsMs.download,
23999
24389
  fetchImpl
24000
24390
  });
24001
24391
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@altertable/cli",
3
- "version": "1.14.0",
3
+ "version": "1.15.1",
4
4
  "description": "Altertable CLI — query and manage your data platform",
5
5
  "homepage": "https://github.com/altertable-ai/altertable-cli#readme",
6
6
  "bugs": {