-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubscribe.ts
186 lines (157 loc) · 6.87 KB
/
subscribe.ts
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
import {Flags} from '@oclif/core'
import * as Ably from 'ably'
import chalk from 'chalk'
import {AblyBaseCommand} from '../../../base-command.js'
import { formatJson, isJsonData } from '../../../utils/json-formatter.js'
export default class LogsConnectionLifecycleSubscribe extends AblyBaseCommand {
static override description = 'Stream logs from [meta]connection.lifecycle meta channel'
static override examples = [
'$ ably logs connection-lifecycle subscribe',
'$ ably logs connection-lifecycle subscribe --rewind 10',
'$ ably logs connection-lifecycle subscribe --json',
'$ ably logs connection-lifecycle subscribe --pretty-json'
]
static override flags = {
...AblyBaseCommand.globalFlags,
rewind: Flags.integer({
default: 0,
description: 'Number of messages to rewind when subscribing',
}),
}
private client: Ably.Realtime | null = null;
// Override finally to ensure resources are cleaned up
async finally(err: Error | undefined): Promise<void> {
if (this.client && this.client.connection.state !== 'closed' && // Check state before closing to avoid errors if already closed
this.client.connection.state !== 'failed') {
this.client.close();
}
return super.finally(err);
}
async run(): Promise<void> {
const {flags} = await this.parse(LogsConnectionLifecycleSubscribe)
const channelName = '[meta]connection.lifecycle'
try {
// Create the Ably client
this.client = await this.createAblyClient(flags)
if (!this.client) return
const {client} = this; // local const
const channelOptions: Ably.ChannelOptions = {}
// Add listeners for connection state changes (important for understanding meta channel behavior)
client.connection.on((stateChange: Ably.ConnectionStateChange) => {
this.logCliEvent(flags, 'connection', stateChange.current, `Connection state changed to ${stateChange.current}`, { reason: stateChange.reason });
});
// Configure rewind if specified
if (flags.rewind > 0) {
this.logCliEvent(flags, 'logs', 'rewindEnabled', `Rewind enabled for ${channelName}`, { channel: channelName, count: flags.rewind });
channelOptions.params = {
...channelOptions.params,
rewind: flags.rewind.toString(),
}
}
const channel = client.channels.get(channelName, channelOptions)
// Listen to channel state changes (for the meta channel itself)
channel.on((stateChange: Ably.ChannelStateChange) => {
this.logCliEvent(flags, 'channel', stateChange.current, `Meta channel '${channelName}' state changed to ${stateChange.current}`, { channel: channelName, reason: stateChange.reason });
});
this.logCliEvent(flags, 'logs', 'subscribing', `Subscribing to ${channelName}...`);
if (!this.shouldOutputJson(flags)) {
this.log(`Subscribing to ${chalk.cyan(channelName)}...`);
this.log('Press Ctrl+C to exit');
this.log('');
}
// Subscribe to the channel
channel.subscribe((message) => {
const timestamp = message.timestamp ? new Date(message.timestamp).toISOString() : new Date().toISOString()
const event = message.name || 'unknown'
const logEvent = {
channel: channelName,
clientId: message.clientId,
connectionId: message.connectionId,
data: message.data,
encoding: message.encoding,
event,
id: message.id,
success: true,
timestamp
};
this.logCliEvent(flags, 'logs', 'logReceived', `Log received on ${channelName}`, logEvent);
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput(logEvent, flags))
return
}
// Color-code different event types
let eventColor = chalk.blue
// For connection lifecycle events
if (event.includes('connection.opened') || event.includes('transport.opened')) {
eventColor = chalk.green
} else if (event.includes('connection.closed') || event.includes('transport.closed')) {
eventColor = chalk.yellow
} else if (event.includes('failed')) {
eventColor = chalk.red
} else if (event.includes('disconnected')) {
eventColor = chalk.magenta
} else if (event.includes('suspended')) {
eventColor = chalk.gray
}
// Format the log output
this.log(`${chalk.dim(`[${timestamp}]`)} Channel: ${chalk.cyan(channelName)} | Event: ${eventColor(event)}`)
if (message.data) {
if (isJsonData(message.data)) {
this.log('Data:')
this.log(formatJson(message.data))
} else {
this.log(`Data: ${message.data}`)
}
}
this.log('')
})
this.logCliEvent(flags, 'logs', 'subscribed', `Successfully subscribed to ${channelName}`);
// Set up cleanup for when the process is terminated
const cleanup = () => {
this.logCliEvent(flags, 'logs', 'cleanupInitiated', 'Cleanup initiated (Ctrl+C pressed)');
if (!this.shouldOutputJson(flags)) {
this.log('\nUnsubscribing and closing connection...')
}
if (client) {
this.logCliEvent(flags, 'connection', 'closing', 'Closing Ably connection.');
client.connection.once('closed', () => {
this.logCliEvent(flags, 'connection', 'closed', 'Connection closed gracefully.');
if (!this.shouldOutputJson(flags)) {
this.log('Connection closed')
}
})
client.close()
}
}
// Handle process termination
process.on('SIGINT', () => {
if (!this.shouldOutputJson(flags)) {
this.log('\nSubscription ended');
}
cleanup();
process.exit(0); // Reinstated: Explicit exit on signal
});
process.on('SIGTERM', () => {
cleanup();
process.exit(0); // Reinstated: Explicit exit on signal
});
this.logCliEvent(flags, 'logs', 'listening', 'Listening for logs...');
// Wait indefinitely
await new Promise(() => {})
} catch (error: unknown) {
const err = error as Error
this.logCliEvent(flags, 'logs', 'fatalError', `Error during log subscription: ${err.message}`, { channel: channelName, error: err.message });
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({ channel: channelName, error: err.message, success: false }, flags))
} else {
this.error(err.message)
}
} finally {
// Ensure client is closed
if (this.client && this.client.connection.state !== 'closed') {
this.logCliEvent(flags || {}, 'connection', 'finalCloseAttempt', 'Ensuring connection is closed in finally block.');
this.client.close();
}
}
}
}