-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscribe.ts
More file actions
294 lines (264 loc) · 8.46 KB
/
subscribe.ts
File metadata and controls
294 lines (264 loc) · 8.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import { Flags } from "@oclif/core";
import * as Ably from "ably";
import chalk from "chalk";
import { AblyBaseCommand } from "../../../base-command.js";
import { BaseFlags } from "../../../types/cli.js";
import { waitUntilInterruptedOrTimeout } from "../../../utils/long-running.js";
export default class LogsAppSubscribe extends AblyBaseCommand {
static override description = "Subscribe to live app logs";
static override examples = [
"$ ably logs app subscribe",
"$ ably logs app subscribe --rewind 10",
"$ ably logs app subscribe --type channel.lifecycle",
"$ ably logs app subscribe --json",
"$ ably logs app subscribe --pretty-json",
"$ ably logs app subscribe --duration 30",
];
static override flags = {
...AblyBaseCommand.globalFlags,
duration: Flags.integer({
description:
"Automatically exit after the given number of seconds (0 = run indefinitely)",
char: "D",
required: false,
}),
rewind: Flags.integer({
default: 0,
description: "Number of messages to rewind when subscribing",
}),
type: Flags.string({
description: "Filter by log type",
options: [
"channel.lifecycle",
"channel.occupancy",
"channel.presence",
"connection.lifecycle",
"push.publish",
],
}),
};
private cleanupInProgress = false;
private client: Ably.Realtime | null = null;
private async properlyCloseAblyClient(): Promise<void> {
if (
!this.client ||
this.client.connection.state === "closed" ||
this.client.connection.state === "failed"
) {
return;
}
return new Promise<void>((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: Error | undefined): Promise<void> {
await this.properlyCloseAblyClient();
return super.finally(err);
}
async run(): Promise<void> {
const { flags } = await this.parse(LogsAppSubscribe);
let channel: Ably.RealtimeChannel | null = null;
let subscribedEvents: string[] = [];
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]log`;
// Configure channel options for rewind if specified
const channelOptions: Ably.ChannelOptions = {};
if (flags.rewind && flags.rewind > 0) {
this.logCliEvent(
flags,
"logs",
"rewindEnabled",
`Rewind enabled for ${logsChannelName}`,
{ channel: logsChannelName, count: flags.rewind },
);
channelOptions.params = {
...channelOptions.params,
rewind: flags.rewind.toString(),
};
}
channel = client.channels.get(logsChannelName, channelOptions);
// Set up channel state logging
this.setupChannelStateLogging(channel, flags, {
includeUserFriendlyMessages: true,
});
// Determine which log types to subscribe to
const logTypes = flags.type
? [flags.type]
: [
"channel.lifecycle",
"channel.occupancy",
"channel.presence",
"connection.lifecycle",
"push.publish",
];
this.logCliEvent(
flags,
"logs",
"subscribing",
`Subscribing to log events: ${logTypes.join(", ")}`,
{ logTypes, channel: logsChannelName },
);
if (!this.shouldOutputJson(flags)) {
this.log(
`${chalk.green("Subscribing to app logs:")} ${chalk.cyan(logTypes.join(", "))}`,
);
}
// Subscribe to specified log types
for (const logType of logTypes) {
channel.subscribe(logType, (message: Ably.Message) => {
const timestamp = message.timestamp
? new Date(message.timestamp).toISOString()
: new Date().toISOString();
const event = {
type: logType,
timestamp,
data: message.data,
id: message.id,
};
this.logCliEvent(
flags,
"logs",
"logReceived",
`Log received: ${logType}`,
event,
);
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput(event, flags));
} else {
this.log(
`${chalk.gray(`[${timestamp}]`)} ${chalk.cyan(`Type: ${logType}`)}`,
);
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
}
});
subscribedEvents.push(logType);
}
this.logCliEvent(
flags,
"logs",
"listening",
"Listening for log events. Press Ctrl+C to exit.",
);
if (!this.shouldOutputJson(flags)) {
this.log("Listening for 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 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, subscribedEvents),
new Promise<void>((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."));
}
}
}
}
private async performCleanup(
flags: BaseFlags,
channel: Ably.RealtimeChannel | null,
subscribedEvents: string[],
): Promise<void> {
// Unsubscribe from log events with timeout
if (channel && subscribedEvents.length > 0) {
for (const eventType of subscribedEvents) {
try {
await Promise.race([
Promise.resolve(channel.unsubscribe(eventType)),
new Promise<void>((resolve) => setTimeout(resolve, 1000)),
]);
this.logCliEvent(
flags,
"logs",
"unsubscribedEvent",
`Unsubscribed from ${eventType}`,
);
} catch (error) {
this.logCliEvent(
flags,
"logs",
"unsubscribeError",
`Error unsubscribing from ${eventType}: ${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.",
);
}
}