@ably/cli
Version:
Ably CLI for Pub/Sub, Chat and Spaces
160 lines (159 loc) • 7.13 kB
JavaScript
import { Flags } from "@oclif/core";
import chalk from "chalk";
import { AblyBaseCommand } from "../../../base-command.js";
import { waitUntilInterruptedOrTimeout } from "../../../utils/long-running.js";
export default class LogsConnectionSubscribe extends AblyBaseCommand {
static description = "Subscribe to live connection logs";
static examples = [
"$ ably logs connection subscribe",
"$ ably logs connection subscribe --json",
"$ ably logs connection subscribe --pretty-json",
"$ ably logs connection subscribe --duration 30",
];
static flags = {
...AblyBaseCommand.globalFlags,
duration: Flags.integer({
description: "Automatically exit after the given number of seconds (0 = run indefinitely)",
char: "D",
required: false,
}),
};
cleanupInProgress = false;
client = null;
async properlyCloseAblyClient() {
if (!this.client ||
this.client.connection.state === "closed" ||
this.client.connection.state === "failed") {
return;
}
return new Promise((resolve) => {
const timeout = setTimeout(() => {
resolve();
}, 2000);
const onClosedOrFailed = () => {
clearTimeout(timeout);
resolve();
};
this.client.connection.once("closed", onClosedOrFailed);
this.client.connection.once("failed", onClosedOrFailed);
this.client.close();
});
}
// Override finally to ensure resources are cleaned up
async finally(err) {
await this.properlyCloseAblyClient();
return super.finally(err);
}
async run() {
const { flags } = await this.parse(LogsConnectionSubscribe);
let channel = null;
try {
this.client = await this.createAblyRealtimeClient(flags);
if (!this.client)
return;
const client = this.client;
// Set up connection state logging
this.setupConnectionStateLogging(client, flags, {
includeUserFriendlyMessages: true,
});
// Get the logs channel
const appConfig = await this.ensureAppAndKey(flags);
if (!appConfig) {
this.error("Unable to determine app configuration");
return;
}
const logsChannelName = `[meta]connection.lifecycle`;
channel = client.channels.get(logsChannelName);
// Set up channel state logging
this.setupChannelStateLogging(channel, flags, {
includeUserFriendlyMessages: true,
});
this.logCliEvent(flags, "logs", "subscribing", `Subscribing to connection logs`, { channel: logsChannelName });
if (!this.shouldOutputJson(flags)) {
this.log(`${chalk.green("Subscribing to connection logs")}`);
}
// Subscribe to connection logs
channel.subscribe((message) => {
const timestamp = message.timestamp
? new Date(message.timestamp).toISOString()
: new Date().toISOString();
const event = {
timestamp,
event: message.name || "connection.log",
data: message.data,
id: message.id,
};
this.logCliEvent(flags, "logs", "logReceived", `Connection log received`, event);
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput(event, flags));
}
else {
this.log(`${chalk.gray(`[${timestamp}]`)} ${chalk.cyan(`Event: ${event.event}`)}`);
if (message.data !== null && message.data !== undefined) {
this.log(`${chalk.green("Data:")} ${JSON.stringify(message.data, null, 2)}`);
}
this.log(""); // Empty line for better readability
}
});
this.logCliEvent(flags, "logs", "listening", "Listening for connection log events. Press Ctrl+C to exit.");
if (!this.shouldOutputJson(flags)) {
this.log("Listening for connection log events. Press Ctrl+C to exit.");
}
// Wait until the user interrupts or the optional duration elapses
const exitReason = await waitUntilInterruptedOrTimeout(flags.duration);
this.logCliEvent(flags, "logs", "runComplete", "Exiting wait loop", {
exitReason,
});
this.cleanupInProgress = exitReason === "signal";
}
catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
this.logCliEvent(flags, "logs", "fatalError", `Error during connection logs subscription: ${errorMsg}`, { error: errorMsg });
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({ error: errorMsg, success: false }, flags));
}
else {
this.error(`Error: ${errorMsg}`);
}
}
finally {
// Wrap all cleanup in a timeout to prevent hanging
await Promise.race([
this.performCleanup(flags || {}, channel),
new Promise((resolve) => {
setTimeout(() => {
this.logCliEvent(flags || {}, "logs", "cleanupTimeout", "Cleanup timed out after 5s, forcing completion");
resolve();
}, 5000);
}),
]);
if (!this.shouldOutputJson(flags || {})) {
if (this.cleanupInProgress) {
this.log(chalk.green("Graceful shutdown complete (user interrupt)."));
}
else {
this.log(chalk.green("Duration elapsed – command finished cleanly."));
}
}
}
}
async performCleanup(flags, channel) {
// Unsubscribe from connection logs with timeout
if (channel) {
try {
await Promise.race([
Promise.resolve(channel.unsubscribe()),
new Promise((resolve) => setTimeout(resolve, 1000)),
]);
this.logCliEvent(flags, "logs", "unsubscribedLogs", "Unsubscribed from connection logs");
}
catch (error) {
this.logCliEvent(flags, "logs", "unsubscribeError", `Error unsubscribing from connection logs: ${error instanceof Error ? error.message : String(error)}`);
}
}
// Close Ably client (already has internal timeout)
this.logCliEvent(flags, "connection", "closingClientFinally", "Closing Ably client.");
await this.properlyCloseAblyClient();
this.logCliEvent(flags, "connection", "clientClosedFinally", "Ably client close attempt finished.");
}
}