@ably/cli
Version:
Ably CLI for Pub/Sub, Chat and Spaces
87 lines (86 loc) • 3.06 kB
JavaScript
import { ChatClient } from "@ably/chat";
import { AblyBaseCommand } from "./base-command.js";
import isTestMode from "./utils/test-mode.js";
export class ChatBaseCommand extends AblyBaseCommand {
_chatRealtimeClient = null;
_chatClient = null;
_cleanupTimeout;
/**
* finally disposes of the chat client, if there is one, which includes cleaning up any subscriptions.
*
* It also disposes of the realtime client.
*/
async finally(error) {
await Promise.race([
this._cleanup(),
new Promise((resolve) => {
this._cleanupTimeout = setTimeout(() => {
this.logCliEvent({}, "rooms", "cleanupTimeout", "Cleanup timed out after 5s, forcing completion");
resolve();
}, 5000);
}),
]);
clearTimeout(this._cleanupTimeout);
super.finally(error);
}
async _cleanup() {
// Dispose of the chat client
if (this._chatClient) {
try {
await this._chatClient.dispose();
}
catch {
// no-op
}
}
const realtime = this._chatRealtimeClient;
if (!realtime ||
realtime.connection.state === "closed" ||
realtime.connection.state === "failed") {
return;
}
await new Promise((resolve) => {
const timeout = setTimeout(() => {
resolve();
}, 2000);
const onClosedOrFailed = () => {
clearTimeout(timeout);
resolve();
};
realtime.connection.once("closed", onClosedOrFailed);
realtime.connection.once("failed", onClosedOrFailed);
realtime.close();
});
}
/**
* Create a Chat client and associated resources
*/
async createChatClient(flags) {
// We already have a client, return it
if (this._chatClient) {
return this._chatClient;
}
// Create Ably Realtime client first
const realtimeClient = await this.createAblyRealtimeClient(flags);
// Mark auth info as shown after creating the client
// to prevent duplicate "Using..." output on subsequent calls
this._authInfoShown = true;
if (!realtimeClient) {
return null;
}
// Store the realtime client for access by subclasses
this._chatRealtimeClient = realtimeClient;
if (isTestMode()) {
this.debug(`Running in test mode, using mock Ably Chat client`);
const mockChat = this.getMockAblyChat();
if (mockChat) {
// Return mock as appropriate type
this._chatClient = mockChat;
return mockChat;
}
this.error(`No mock Ably Chat client available in test mode`);
}
// Use the Ably client to create the Chat client
return (this._chatClient = new ChatClient(realtimeClient));
}
}