@modelriver/cli 1.2.5 ā 2.0.0
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.
- package/README.md +198 -3
- package/package.json +29 -12
- package/src/cli.js +232 -0
- package/src/commands/listen.js +17 -8
- package/src/commands/login.js +59 -16
- package/src/commands/test-webhook.js +10 -3
- package/src/commands/tool-calls.js +138 -0
- package/src/commands/tools.js +762 -0
- package/src/commands/trigger.js +8 -3
- package/src/commands/webhook.js +8 -5
- package/src/commands/websocket.js +185 -58
- package/src/index.js +2 -166
- package/src/lib/api-client.js +116 -11
- package/src/lib/cli-websocket-client.js +381 -137
- package/src/lib/config.js +141 -13
- package/src/lib/tool-forwarder.js +325 -0
- package/src/lib/tool-session-store.js +361 -0
- package/src/lib/tool-signature.js +141 -0
- package/src/lib/webhook-verifier.js +43 -16
- package/src/lib/websocket-client.js +29 -3
- package/src/utils/logger.js +8 -7
- package/src/utils/secrets.js +44 -0
- package/src/utils/tool-approvals.js +238 -0
- package/src/utils/url-helpers.js +117 -0
- package/src/utils/webhook-payload.js +9 -6
- package/tool-signature.js +3 -0
|
@@ -1,124 +1,252 @@
|
|
|
1
1
|
const WebSocket = require('ws');
|
|
2
|
+
const Logger = require('../utils/logger');
|
|
3
|
+
const { checkWebSocketUrl, normalizeWebSocketUrl } = require('../utils/url-helpers');
|
|
2
4
|
|
|
5
|
+
const DEFAULT_PUSH_TIMEOUT_MS = 10000;
|
|
6
|
+
const HEARTBEAT_INTERVAL_MS = 30000;
|
|
7
|
+
const MAX_RECONNECT_DELAY_MS = 30000;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Error for a push the server answered with `status: "error"`, or that got no
|
|
11
|
+
* answer in time. `reply` holds the server's reply payload when there was one.
|
|
12
|
+
*/
|
|
13
|
+
class PushError extends Error {
|
|
14
|
+
constructor(message, { reply = null, reason = 'error' } = {}) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'PushError';
|
|
17
|
+
this.reply = reply;
|
|
18
|
+
this.reason = reason;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Phoenix channel client (V1 JSON serializer) used by the CLI.
|
|
24
|
+
*
|
|
25
|
+
* - `push(topic, event, payload)` sends a message with a unique ref and returns a
|
|
26
|
+
* promise settled by the matching `phx_reply` (or a timeout).
|
|
27
|
+
* - Several topics can be joined on one socket.
|
|
28
|
+
* - After an unexpected disconnect it reconnects with backoff. When a
|
|
29
|
+
* `refreshToken` function is given it is called first, so a fresh token (and
|
|
30
|
+
* WebSocket URL) is used, and every joined topic is joined again.
|
|
31
|
+
*/
|
|
3
32
|
class CLIWebSocketClient {
|
|
4
|
-
|
|
5
|
-
|
|
33
|
+
/**
|
|
34
|
+
* @param {string} websocketUrl
|
|
35
|
+
* @param {string} token
|
|
36
|
+
* @param {boolean} verbose
|
|
37
|
+
* @param {object} [options]
|
|
38
|
+
* @param {Function} [options.refreshToken] - async () => ({ws_token, websocket_url})
|
|
39
|
+
* @param {number} [options.pushTimeoutMs]
|
|
40
|
+
* @param {number} [options.maxReconnectAttempts]
|
|
41
|
+
* @param {number} [options.reconnectDelayMs] - first backoff step
|
|
42
|
+
* @param {number} [options.heartbeatIntervalMs]
|
|
43
|
+
*/
|
|
44
|
+
constructor(websocketUrl, token, verbose = false, options = {}) {
|
|
45
|
+
// ws:// on port 443 or a modelriver.com host means wss://
|
|
46
|
+
this.websocketUrl = normalizeWebSocketUrl(websocketUrl);
|
|
6
47
|
this.token = token;
|
|
7
48
|
this.verbose = verbose;
|
|
49
|
+
this.refreshToken = options.refreshToken || null;
|
|
50
|
+
this.pushTimeoutMs = options.pushTimeoutMs || DEFAULT_PUSH_TIMEOUT_MS;
|
|
51
|
+
this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5;
|
|
52
|
+
this.reconnectDelay = options.reconnectDelayMs || 1000;
|
|
53
|
+
this.heartbeatIntervalMs = options.heartbeatIntervalMs || HEARTBEAT_INTERVAL_MS;
|
|
54
|
+
|
|
8
55
|
this.ws = null;
|
|
9
|
-
this.
|
|
56
|
+
this.ref = 0;
|
|
57
|
+
this.pending = new Map(); // ref -> {resolve, reject, timer, topic, event}
|
|
58
|
+
this.topics = new Map(); // topic -> join payload
|
|
59
|
+
this.joined = new Set(); // topics joined on the current socket
|
|
10
60
|
this.listeners = {};
|
|
61
|
+
this.eventHandlers = new Map(); // event -> Set<handler(payload, topic)>
|
|
11
62
|
this.heartbeatInterval = null;
|
|
12
|
-
this.heartbeatRef = 0;
|
|
13
63
|
this.reconnectAttempts = 0;
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
64
|
+
this.reconnectTimer = null;
|
|
65
|
+
this.hasConnected = false;
|
|
66
|
+
this.closing = false;
|
|
67
|
+
|
|
68
|
+
// Kept for callers that read it (listen.js); the last topic joined.
|
|
69
|
+
this.channel = null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @returns {string} a ref not used before on this client */
|
|
73
|
+
nextRef() {
|
|
74
|
+
this.ref += 1;
|
|
75
|
+
return String(this.ref);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
buildUrl() {
|
|
79
|
+
// Throws unless the URL is wss (ws is allowed only for localhost).
|
|
80
|
+
checkWebSocketUrl(this.websocketUrl);
|
|
81
|
+
// Phoenix WebSocket endpoint requires /websocket suffix for raw WebSocket connections
|
|
82
|
+
let wsUrl = this.websocketUrl;
|
|
83
|
+
if (!wsUrl.endsWith('/websocket')) {
|
|
84
|
+
wsUrl = wsUrl.replace(/\/?$/, '/websocket');
|
|
85
|
+
}
|
|
86
|
+
const separator = wsUrl.includes('?') ? '&' : '?';
|
|
87
|
+
return `${wsUrl}${separator}token=${encodeURIComponent(this.token)}`;
|
|
16
88
|
}
|
|
17
89
|
|
|
18
90
|
/**
|
|
19
|
-
* Connect to WebSocket
|
|
91
|
+
* Connect to the WebSocket.
|
|
20
92
|
* @returns {Promise<void>}
|
|
21
93
|
*/
|
|
22
94
|
connect() {
|
|
23
95
|
return new Promise((resolve, reject) => {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
96
|
+
let url;
|
|
97
|
+
try {
|
|
98
|
+
url = this.buildUrl();
|
|
99
|
+
} catch (error) {
|
|
100
|
+
reject(error);
|
|
101
|
+
return;
|
|
28
102
|
}
|
|
29
|
-
const url = `${wsUrl}?token=${encodeURIComponent(this.token)}`;
|
|
30
103
|
|
|
31
104
|
if (this.verbose) {
|
|
32
|
-
|
|
33
|
-
Logger.info(`Connecting to WebSocket: ${url.replace(this.token, 'TOKEN')}`);
|
|
105
|
+
Logger.info(`Connecting to WebSocket: ${url.split('?')[0]}`);
|
|
34
106
|
}
|
|
35
107
|
|
|
36
|
-
|
|
108
|
+
const ws = new WebSocket(url);
|
|
109
|
+
this.ws = ws;
|
|
110
|
+
let opened = false;
|
|
37
111
|
|
|
38
|
-
|
|
112
|
+
ws.on('open', () => {
|
|
113
|
+
opened = true;
|
|
114
|
+
this.hasConnected = true;
|
|
39
115
|
this.reconnectAttempts = 0;
|
|
40
|
-
this.reconnectDelay = 1000;
|
|
41
116
|
this.startHeartbeat();
|
|
42
117
|
resolve();
|
|
43
118
|
});
|
|
44
119
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (this.reconnectAttempts === 0) {
|
|
120
|
+
ws.on('error', (error) => {
|
|
121
|
+
if (!opened) {
|
|
48
122
|
reject(error);
|
|
123
|
+
} else if (this.verbose) {
|
|
124
|
+
Logger.warning(`WebSocket error: ${error.message}`);
|
|
49
125
|
}
|
|
50
126
|
});
|
|
51
127
|
|
|
52
|
-
|
|
128
|
+
ws.on('message', (data) => {
|
|
129
|
+
// A message still arriving on an older socket (one we have replaced
|
|
130
|
+
// with a new connection) is ignored: it must not act on this one.
|
|
131
|
+
if (this.ws !== ws) return;
|
|
53
132
|
this.handleMessage(data);
|
|
54
133
|
});
|
|
55
134
|
|
|
56
|
-
|
|
135
|
+
ws.on('close', (code, reason) => {
|
|
136
|
+
if (this.ws !== ws) return; // an older socket closing late
|
|
57
137
|
this.stopHeartbeat();
|
|
138
|
+
this.joined.clear();
|
|
139
|
+
this.rejectPending('WebSocket disconnected');
|
|
140
|
+
|
|
141
|
+
if (!opened) {
|
|
142
|
+
reject(new Error(`WebSocket closed before it opened (code ${code})`));
|
|
143
|
+
}
|
|
144
|
+
|
|
58
145
|
if (this.listeners.close) {
|
|
59
146
|
this.listeners.close(code, reason);
|
|
60
147
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
148
|
+
|
|
149
|
+
// A normal close (1000) from the server is final: no reconnect.
|
|
150
|
+
const willReconnect = !this.closing && this.hasConnected && code !== 1000;
|
|
151
|
+
this.emit('close', code, reason ? reason.toString() : '', willReconnect);
|
|
152
|
+
if (willReconnect) {
|
|
153
|
+
this.scheduleReconnect();
|
|
64
154
|
}
|
|
65
155
|
});
|
|
66
156
|
});
|
|
67
157
|
}
|
|
68
158
|
|
|
69
159
|
/**
|
|
70
|
-
*
|
|
160
|
+
* Schedule one reconnect attempt with exponential backoff.
|
|
71
161
|
*/
|
|
72
|
-
|
|
73
|
-
this.
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
Logger.error(`Reconnection failed: ${err.message}`);
|
|
93
|
-
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
|
94
|
-
this.attemptReconnect();
|
|
95
|
-
}
|
|
96
|
-
});
|
|
97
|
-
}
|
|
162
|
+
scheduleReconnect() {
|
|
163
|
+
if (this.closing || this.reconnectTimer) return;
|
|
164
|
+
|
|
165
|
+
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
166
|
+
Logger.error('WebSocket reconnect failed too many times. Giving up.');
|
|
167
|
+
this.emit('reconnect_failed');
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
this.reconnectAttempts += 1;
|
|
172
|
+
const delay = Math.min(
|
|
173
|
+
this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1),
|
|
174
|
+
MAX_RECONNECT_DELAY_MS
|
|
175
|
+
);
|
|
176
|
+
const limit = Number.isFinite(this.maxReconnectAttempts) ? `/${this.maxReconnectAttempts}` : '';
|
|
177
|
+
Logger.warning(`WebSocket closed. Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}${limit})...`);
|
|
178
|
+
|
|
179
|
+
this.reconnectTimer = setTimeout(() => {
|
|
180
|
+
this.reconnectTimer = null;
|
|
181
|
+
this.reconnect();
|
|
98
182
|
}, delay);
|
|
99
183
|
}
|
|
100
184
|
|
|
185
|
+
async reconnect() {
|
|
186
|
+
if (this.closing) return;
|
|
187
|
+
|
|
188
|
+
if (this.refreshToken) {
|
|
189
|
+
try {
|
|
190
|
+
const fresh = await this.refreshToken();
|
|
191
|
+
// Check a new URL before using it; a bad one keeps the old URL and
|
|
192
|
+
// counts as a failed attempt.
|
|
193
|
+
const freshUrl = fresh && fresh.websocket_url ? normalizeWebSocketUrl(fresh.websocket_url) : null;
|
|
194
|
+
if (freshUrl) checkWebSocketUrl(freshUrl);
|
|
195
|
+
if (fresh && fresh.ws_token) this.token = fresh.ws_token;
|
|
196
|
+
if (freshUrl) this.websocketUrl = freshUrl;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
Logger.error(`Could not get a new WebSocket token: ${error.message}`);
|
|
199
|
+
this.scheduleReconnect();
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
try {
|
|
205
|
+
// A failed connect closes its socket, and the close handler schedules
|
|
206
|
+
// the next attempt.
|
|
207
|
+
await this.connect();
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (this.verbose) Logger.error(`Reconnection failed: ${error.message}`);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
Logger.success('WebSocket reconnected');
|
|
214
|
+
this.emit('reconnect');
|
|
215
|
+
|
|
216
|
+
for (const [topic, payload] of this.topics) {
|
|
217
|
+
this.rejoin(topic, payload);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
101
221
|
/**
|
|
102
|
-
*
|
|
222
|
+
* Join a topic again (after a reconnect or a channel crash). Emits "rejoin"
|
|
223
|
+
* (topic) on success and "rejoin_error" (topic, error) on failure.
|
|
103
224
|
*/
|
|
225
|
+
rejoin(topic, payload) {
|
|
226
|
+
return this.join(topic, payload).then(
|
|
227
|
+
() => this.emit('rejoin', topic),
|
|
228
|
+
(error) => {
|
|
229
|
+
Logger.error(`Failed to rejoin ${topic}: ${error.message}`);
|
|
230
|
+
this.emit('rejoin_error', topic, error);
|
|
231
|
+
}
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
104
235
|
startHeartbeat() {
|
|
236
|
+
this.stopHeartbeat();
|
|
105
237
|
this.heartbeatInterval = setInterval(() => {
|
|
106
|
-
if (this.
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}, 30000); // Every 30 seconds
|
|
238
|
+
if (!this.isOpen()) return;
|
|
239
|
+
this.push('phoenix', 'heartbeat', {}).catch((error) => {
|
|
240
|
+
if (error.reason === 'timeout' && this.ws) {
|
|
241
|
+
// No heartbeat reply: the connection is dead. Closing it starts a reconnect.
|
|
242
|
+
Logger.warning('No heartbeat reply from server; reconnecting.');
|
|
243
|
+
this.ws.terminate();
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
}, this.heartbeatIntervalMs);
|
|
247
|
+
if (this.heartbeatInterval.unref) this.heartbeatInterval.unref();
|
|
117
248
|
}
|
|
118
249
|
|
|
119
|
-
/**
|
|
120
|
-
* Stop sending heartbeats
|
|
121
|
-
*/
|
|
122
250
|
stopHeartbeat() {
|
|
123
251
|
if (this.heartbeatInterval) {
|
|
124
252
|
clearInterval(this.heartbeatInterval);
|
|
@@ -126,101 +254,204 @@ class CLIWebSocketClient {
|
|
|
126
254
|
}
|
|
127
255
|
}
|
|
128
256
|
|
|
257
|
+
isOpen() {
|
|
258
|
+
return Boolean(this.ws && this.ws.readyState === WebSocket.OPEN);
|
|
259
|
+
}
|
|
260
|
+
|
|
129
261
|
/**
|
|
130
|
-
*
|
|
131
|
-
* @param {string}
|
|
132
|
-
* @
|
|
262
|
+
* Send a message and wait for the server's reply to it.
|
|
263
|
+
* @param {string} topic
|
|
264
|
+
* @param {string} event
|
|
265
|
+
* @param {object} payload
|
|
266
|
+
* @param {object} [options]
|
|
267
|
+
* @param {number} [options.timeoutMs]
|
|
268
|
+
* @returns {Promise<object>} the reply's `response` when status is "ok"
|
|
133
269
|
*/
|
|
134
|
-
|
|
270
|
+
push(topic, event, payload = {}, { timeoutMs } = {}) {
|
|
135
271
|
return new Promise((resolve, reject) => {
|
|
136
|
-
if (!this.
|
|
137
|
-
reject(new
|
|
272
|
+
if (!this.isOpen()) {
|
|
273
|
+
reject(new PushError('WebSocket is not connected', { reason: 'disconnected' }));
|
|
138
274
|
return;
|
|
139
275
|
}
|
|
140
276
|
|
|
141
|
-
const
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
ref: joinRef
|
|
148
|
-
});
|
|
277
|
+
const ref = this.nextRef();
|
|
278
|
+
const timer = setTimeout(() => {
|
|
279
|
+
if (this.pending.delete(ref)) {
|
|
280
|
+
reject(new PushError(`No reply to "${event}" on ${topic}`, { reason: 'timeout' }));
|
|
281
|
+
}
|
|
282
|
+
}, timeoutMs || this.pushTimeoutMs);
|
|
149
283
|
|
|
150
|
-
|
|
284
|
+
this.pending.set(ref, { resolve, reject, timer, topic, event });
|
|
151
285
|
|
|
152
|
-
|
|
153
|
-
|
|
286
|
+
try {
|
|
287
|
+
this.ws.send(JSON.stringify({ topic, event, payload, ref }));
|
|
288
|
+
} catch (error) {
|
|
289
|
+
clearTimeout(timer);
|
|
290
|
+
this.pending.delete(ref);
|
|
291
|
+
reject(new PushError(`Failed to send "${event}": ${error.message}`, { reason: 'disconnected' }));
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
}
|
|
154
295
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
296
|
+
/**
|
|
297
|
+
* Join a Phoenix channel and remember it so it is joined again after a reconnect.
|
|
298
|
+
* @param {string} topic
|
|
299
|
+
* @param {object} [payload]
|
|
300
|
+
* @returns {Promise<object>} the join reply's response
|
|
301
|
+
*/
|
|
302
|
+
async join(topic, payload = {}) {
|
|
303
|
+
try {
|
|
304
|
+
this.joined.delete(topic);
|
|
305
|
+
const response = await this.push(topic, 'phx_join', payload);
|
|
306
|
+
this.topics.set(topic, payload);
|
|
307
|
+
this.joined.add(topic);
|
|
308
|
+
this.channel = topic;
|
|
309
|
+
return response;
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (error.reason === 'timeout') {
|
|
312
|
+
throw new PushError('Channel join timeout', { reason: 'timeout' });
|
|
313
|
+
}
|
|
314
|
+
const detail = error.reply ? describeReply(error.reply) : error.message;
|
|
315
|
+
throw new PushError(`Failed to join channel: ${detail}`, { reply: error.reply, reason: error.reason });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
172
318
|
|
|
173
|
-
|
|
174
|
-
|
|
319
|
+
/**
|
|
320
|
+
* Is the topic joined on the current socket (not disconnected or rejoining)?
|
|
321
|
+
* @param {string} topic
|
|
322
|
+
*/
|
|
323
|
+
isJoined(topic) {
|
|
324
|
+
return this.isOpen() && this.joined.has(topic);
|
|
325
|
+
}
|
|
175
326
|
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
});
|
|
327
|
+
/**
|
|
328
|
+
* Join a Phoenix channel (CLI webhook channel). Kept for existing callers.
|
|
329
|
+
* @param {string} channelName - e.g. "cli_webhooks:user_id"
|
|
330
|
+
* @returns {Promise<object>}
|
|
331
|
+
*/
|
|
332
|
+
joinChannel(channelName) {
|
|
333
|
+
return this.join(channelName, {});
|
|
184
334
|
}
|
|
185
335
|
|
|
186
336
|
/**
|
|
187
337
|
* Handle incoming WebSocket messages
|
|
188
|
-
* @param {Buffer} data
|
|
338
|
+
* @param {Buffer|string} data
|
|
189
339
|
*/
|
|
190
340
|
handleMessage(data) {
|
|
341
|
+
let msg;
|
|
191
342
|
try {
|
|
192
|
-
|
|
193
|
-
|
|
343
|
+
msg = JSON.parse(data.toString());
|
|
344
|
+
} catch (error) {
|
|
345
|
+
if (this.verbose) {
|
|
346
|
+
Logger.warning(`Failed to parse WebSocket message: ${error.message}`);
|
|
347
|
+
}
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
194
350
|
|
|
195
|
-
|
|
351
|
+
if (!msg || typeof msg !== 'object') return;
|
|
196
352
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (this.
|
|
208
|
-
this.
|
|
353
|
+
if (msg.event === 'phx_reply') {
|
|
354
|
+
this.handleReply(msg);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (msg.event === 'phx_error' || msg.event === 'phx_close') {
|
|
359
|
+
if (this.topics.has(msg.topic)) {
|
|
360
|
+
this.joined.delete(msg.topic);
|
|
361
|
+
Logger.warning(`Channel ${msg.topic} ${msg.event === 'phx_error' ? 'crashed' : 'was closed by the server'}`);
|
|
362
|
+
this.emit('channel_' + msg.event.replace('phx_', ''), msg.topic);
|
|
363
|
+
if (msg.event === 'phx_error' && !this.closing) {
|
|
364
|
+
this.rejoin(msg.topic, this.topics.get(msg.topic));
|
|
365
|
+
} else if (msg.event === 'phx_close') {
|
|
366
|
+
this.topics.delete(msg.topic);
|
|
209
367
|
}
|
|
210
|
-
} else if (this.verbose && msg.event !== 'heartbeat') {
|
|
211
|
-
Logger.info(`Received event: ${msg.event} on topic: ${msg.topic}`);
|
|
212
368
|
}
|
|
213
|
-
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
if (msg.event === 'webhook') {
|
|
214
373
|
if (this.verbose) {
|
|
215
|
-
|
|
216
|
-
Logger.warning(`Failed to parse WebSocket message: ${error.message}`);
|
|
374
|
+
Logger.info(`\nšØ Webhook event received on channel: ${msg.topic}`);
|
|
217
375
|
}
|
|
376
|
+
if (this.listeners.webhook) {
|
|
377
|
+
this.listeners.webhook(msg.payload);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const handlers = this.eventHandlers.get(msg.event);
|
|
382
|
+
if (handlers && handlers.size > 0) {
|
|
383
|
+
for (const handler of handlers) {
|
|
384
|
+
try {
|
|
385
|
+
handler(msg.payload, msg.topic);
|
|
386
|
+
} catch (error) {
|
|
387
|
+
Logger.error(`Error handling "${msg.event}": ${error.message}`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
} else if (this.verbose && msg.event !== 'webhook') {
|
|
391
|
+
Logger.info(`Received event: ${msg.event} on topic: ${msg.topic}`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
handleReply(msg) {
|
|
396
|
+
const entry = msg.ref != null ? this.pending.get(String(msg.ref)) : null;
|
|
397
|
+
if (!entry || entry.topic !== msg.topic) return;
|
|
398
|
+
|
|
399
|
+
this.pending.delete(String(msg.ref));
|
|
400
|
+
clearTimeout(entry.timer);
|
|
401
|
+
|
|
402
|
+
const reply = msg.payload || {};
|
|
403
|
+
if (reply.status === 'ok') {
|
|
404
|
+
// Joined from this moment. The server may send a message right behind
|
|
405
|
+
// the join reply, and it is handled before join()'s caller runs again:
|
|
406
|
+
// an answer to it must be sendable.
|
|
407
|
+
if (entry.event === 'phx_join') this.joined.add(entry.topic);
|
|
408
|
+
entry.resolve(reply.response ?? {});
|
|
409
|
+
} else {
|
|
410
|
+
entry.reject(new PushError(
|
|
411
|
+
`"${entry.event}" on ${entry.topic} was refused: ${describeReply(reply)}`,
|
|
412
|
+
{ reply, reason: reply.status || 'error' }
|
|
413
|
+
));
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
rejectPending(message) {
|
|
418
|
+
for (const [ref, entry] of this.pending) {
|
|
419
|
+
clearTimeout(entry.timer);
|
|
420
|
+
entry.reject(new PushError(message, { reason: 'disconnected' }));
|
|
421
|
+
this.pending.delete(ref);
|
|
218
422
|
}
|
|
219
423
|
}
|
|
220
424
|
|
|
425
|
+
/**
|
|
426
|
+
* Subscribe to a server event (any topic).
|
|
427
|
+
* @param {string} event
|
|
428
|
+
* @param {Function} handler - (payload, topic) => void
|
|
429
|
+
* @returns {Function} unsubscribe
|
|
430
|
+
*/
|
|
431
|
+
on(event, handler) {
|
|
432
|
+
if (!this.eventHandlers.has(event)) this.eventHandlers.set(event, new Set());
|
|
433
|
+
this.eventHandlers.get(event).add(handler);
|
|
434
|
+
return () => this.eventHandlers.get(event).delete(handler);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
emit(name, ...args) {
|
|
438
|
+
const handlers = this.eventHandlers.get(`client:${name}`);
|
|
439
|
+
if (!handlers) return;
|
|
440
|
+
for (const handler of handlers) handler(...args);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Listen for client lifecycle events: "close" (code, reason, willReconnect),
|
|
445
|
+
* "reconnect", "reconnect_failed", "rejoin" (topic), "rejoin_error" (topic, error),
|
|
446
|
+
* "channel_error" (topic), "channel_close" (topic).
|
|
447
|
+
*/
|
|
448
|
+
onClient(name, handler) {
|
|
449
|
+
return this.on(`client:${name}`, handler);
|
|
450
|
+
}
|
|
451
|
+
|
|
221
452
|
/**
|
|
222
453
|
* Listen for webhook events
|
|
223
|
-
* @param {Function} callback
|
|
454
|
+
* @param {Function} callback
|
|
224
455
|
*/
|
|
225
456
|
onWebhook(callback) {
|
|
226
457
|
this.listeners.webhook = callback;
|
|
@@ -228,22 +459,35 @@ class CLIWebSocketClient {
|
|
|
228
459
|
|
|
229
460
|
/**
|
|
230
461
|
* Listen for close events
|
|
231
|
-
* @param {Function} callback
|
|
462
|
+
* @param {Function} callback
|
|
232
463
|
*/
|
|
233
464
|
onClose(callback) {
|
|
234
465
|
this.listeners.close = callback;
|
|
235
466
|
}
|
|
236
467
|
|
|
237
468
|
/**
|
|
238
|
-
* Close WebSocket connection
|
|
469
|
+
* Close the WebSocket connection; no reconnect follows.
|
|
239
470
|
*/
|
|
240
471
|
close() {
|
|
472
|
+
this.closing = true;
|
|
473
|
+
if (this.reconnectTimer) {
|
|
474
|
+
clearTimeout(this.reconnectTimer);
|
|
475
|
+
this.reconnectTimer = null;
|
|
476
|
+
}
|
|
477
|
+
this.stopHeartbeat();
|
|
478
|
+
this.rejectPending('WebSocket closed');
|
|
241
479
|
if (this.ws) {
|
|
242
480
|
this.ws.close(1000, 'CLI shutdown');
|
|
243
|
-
this.stopHeartbeat();
|
|
244
481
|
}
|
|
245
482
|
}
|
|
246
483
|
}
|
|
247
484
|
|
|
248
|
-
|
|
485
|
+
function describeReply(reply) {
|
|
486
|
+
const response = reply && reply.response;
|
|
487
|
+
if (!response) return 'Unknown error';
|
|
488
|
+
if (typeof response === 'string') return response;
|
|
489
|
+
return response.reason || response.error || response.message || JSON.stringify(response);
|
|
490
|
+
}
|
|
249
491
|
|
|
492
|
+
module.exports = CLIWebSocketClient;
|
|
493
|
+
module.exports.PushError = PushError;
|