-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubscribe.ts
195 lines (170 loc) · 5.74 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
187
188
189
190
191
192
193
194
195
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 LogsConnectionSubscribe extends AblyBaseCommand {
static override description = 'Stream logs from [meta]connection meta channel'
static override examples = [
'$ ably logs connection subscribe',
'$ ably logs connection subscribe --rewind 10',
'$ ably logs connection subscribe --json',
'$ ably logs connection subscribe --pretty-json'
]
static override flags = {
...AblyBaseCommand.globalFlags,
rewind: Flags.integer({
default: 0,
description: 'Number of messages to rewind when subscribing',
}),
}
async run(): Promise<void> {
const {flags} = await this.parse(LogsConnectionSubscribe)
let client: Ably.Realtime | null = null;
const channelName = '[meta]connection'
try {
// Create the Ably client
client = await this.createAblyClient(flags)
if (!client) return
const channelOptions: Ably.ChannelOptions = {}
// Configure rewind if specified
if (flags.rewind > 0) {
channelOptions.params = {
...channelOptions.params,
rewind: flags.rewind.toString(),
}
}
const channel = client.channels.get(channelName, channelOptions)
// Setup connection state change handler
client.connection.on('connected', () => {
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
status: 'connected',
success: true
}, flags))
} else {
this.log(`Subscribing to ${chalk.cyan(channelName)}...`)
this.log('Press Ctrl+C to exit')
this.log('')
}
})
client.connection.on('disconnected', () => {
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
status: 'disconnected',
success: false
}, flags))
} else {
this.log('Disconnected from Ably')
}
})
client.connection.on('failed', (err: Ably.ConnectionStateChange) => {
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
error: err.reason?.message || 'Unknown error',
status: 'failed',
success: false
}, flags))
} else {
this.error(`Connection failed: ${err.reason?.message || 'Unknown error'}`)
}
})
// Subscribe to the channel
channel.subscribe((message) => {
const timestamp = message.timestamp ? new Date(message.timestamp).toISOString() : new Date().toISOString()
const event = message.name || 'unknown'
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
clientId: message.clientId,
connectionId: message.connectionId,
data: message.data,
encoding: message.encoding,
event,
id: message.id,
success: true,
timestamp
}, flags))
return
}
// Color-code different event types
let eventColor = chalk.blue
// For connection events
if (event.includes('connected') || event.includes('online')) {
eventColor = chalk.green
} else if (event.includes('disconnected') || event.includes('offline')) {
eventColor = chalk.yellow
} else if (event.includes('failed')) {
eventColor = chalk.red
} 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('')
})
// Set up cleanup for when the process is terminated
const cleanup = () => {
if (!this.shouldOutputJson(flags)) {
this.log('\nUnsubscribing and closing connection...')
}
if (client) {
client.connection.once('closed', () => {
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
status: 'closed',
success: true
}, flags))
} else {
this.log('Connection closed')
}
})
client.close()
}
}
// Handle process termination
process.on('SIGINT', () => {
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
status: 'unsubscribed',
success: true
}, flags))
} else {
this.log('\nSubscription ended')
}
cleanup()
process.exit(0) // Reinstated: Explicit exit on signal
})
// Wait indefinitely
await new Promise(() => {})
} catch (error: unknown) {
if (this.shouldOutputJson(flags)) {
this.log(this.formatJsonOutput({
channel: channelName,
error: error instanceof Error ? error.message : String(error),
success: false
}, flags))
} else {
const err = error as Error
this.error(err.message)
}
} finally {
if (client) {
client.close()
}
}
}
}