Add Sockethub client service

Wrap @sockethub/client behind a shared connection that opens only while an integration needs it: consumers register with acquire/release and the socket opens on the first and closes on the last. Persists one global server URL, exposes send/sendCredentials/contextFor plus an onMessage hook, and classifies connection vs platform errors.
This commit is contained in:
raucao committed 2026-10-27 17:38:34 +04:00
1 parent 8a4143ba62
commit 89bf417d45
1 file changed
+255
+255
View File
@@ -0,0 +1,255 @@
import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { io } from 'socket.io-client';
import SockethubClient from '@sockethub/client';
import {
DEFAULT_SOCKETHUB_URL,
SOCKETHUB_INIT_TIMEOUT,
SOCKETHUB_SETTINGS_NAMESPACE,
SOCKETHUB_URL_KEY,
} from '../config/sockethub';
export const SOCKETHUB_STATUS_DISCONNECTED = 'disconnected';
export const SOCKETHUB_STATUS_CONNECTING = 'connecting';
export const SOCKETHUB_STATUS_READY = 'ready';
export const SOCKETHUB_STATUS_ERROR = 'error';
export class SockethubError extends Error {
constructor(message = 'Sockethub error') {
super(message);
this.name = 'SockethubError';
}
}
// Discovery, connection, or schema-initialization failed.
export class SockethubConnectionError extends SockethubError {
constructor(message = 'Unable to reach the Sockethub server') {
super(message);
this.name = 'SockethubConnectionError';
}
}
// A platform rejected an operation. The message is the platform's stable error
// string (e.g. `caldav:authentication-failed`) so callers can classify it.
export class SockethubPlatformError extends SockethubError {
constructor(message = 'Sockethub rejected the request') {
super(message);
this.name = 'SockethubPlatformError';
}
}
// Owns the single Sockethub connection. Integrations that need Sockethub
// register as consumers via `acquire`/`release`; the connection opens when the
// first consumer appears and closes when the last one leaves, so Dashtab only
// talks to a server while an integration that needs it is enabled.
export default class SockethubService extends Service {
@service storage;
@tracked status = SOCKETHUB_STATUS_DISCONNECTED;
@tracked error = null;
@tracked url = null;
@tracked descriptor = null;
client = null;
consumers = new Set();
connecting = null;
messageHandlers = new Set();
get connected() {
return this.status === SOCKETHUB_STATUS_READY && Boolean(this.client);
}
// Test seam: the real client discovers the server descriptor and opens a
// Socket.IO connection. `io` is passed explicitly so the client never falls
// back to its dynamic `import("socket.io-client")`, which keeps bundling
// predictable.
createClient(url) {
return SockethubClient.connect(url, {
io,
initTimeoutMs: SOCKETHUB_INIT_TIMEOUT,
});
}
async loadUrl() {
const stored = await this.storage.get(
SOCKETHUB_SETTINGS_NAMESPACE,
SOCKETHUB_URL_KEY
);
this.url = stored ?? DEFAULT_SOCKETHUB_URL;
return this.url;
}
async setUrl(url) {
this.url = url;
await this.storage.set(
SOCKETHUB_SETTINGS_NAMESPACE,
SOCKETHUB_URL_KEY,
url
);
// Reconnect so a running integration picks up the new server.
if (this.consumers.size > 0) {
await this.reconnect();
}
}
acquire(consumerId) {
this.consumers.add(consumerId);
return this.ensureConnected();
}
release(consumerId) {
this.consumers.delete(consumerId);
if (this.consumers.size === 0) {
this.disconnect();
}
}
ensureConnected() {
if (this.connected) {
return Promise.resolve(this.client);
}
if (this.connecting) {
return this.connecting;
}
this.connecting = this.connect().finally(() => {
this.connecting = null;
});
return this.connecting;
}
async connect() {
this.status = SOCKETHUB_STATUS_CONNECTING;
this.error = null;
const url = this.url ?? (await this.loadUrl());
try {
const client = await this.createClient(url);
this.attach(client);
await client.ready();
this.client = client;
this.descriptor = client.descriptor ?? null;
this.status = SOCKETHUB_STATUS_READY;
return client;
} catch (err) {
this.status = SOCKETHUB_STATUS_ERROR;
this.error = this.messageFor(err);
throw new SockethubConnectionError(this.error);
}
}
// Socket events keep the tracked status in step with the live connection.
// Incoming platform events are fanned out to any registered handlers.
attach(client) {
client.socket.on('connect', () => {
if (this.client) {
this.status = SOCKETHUB_STATUS_READY;
}
});
client.socket.on('disconnect', () => {
if (this.client) {
this.status = SOCKETHUB_STATUS_DISCONNECTED;
}
});
client.socket.on('connect_error', (err) => {
this.status = SOCKETHUB_STATUS_ERROR;
this.error = this.messageFor(err);
});
client.socket.on('init_error', (event) => {
this.status = SOCKETHUB_STATUS_ERROR;
this.error = this.messageFor(event?.error ?? event);
});
client.socket.on('message', (message) => {
for (const handler of [...this.messageHandlers]) {
handler(message);
}
});
}
disconnect() {
const client = this.client;
this.client = null;
this.descriptor = null;
this.status = SOCKETHUB_STATUS_DISCONNECTED;
this.error = null;
try {
client?.socket?.disconnect();
} catch {
// The socket may already be closed.
}
}
async reconnect() {
this.disconnect();
return this.ensureConnected();
}
contextFor(platform) {
if (!this.client) {
throw new SockethubError('Sockethub is not connected');
}
return this.client.contextFor(platform);
}
send(message) {
return this.emit('message', message);
}
sendCredentials(message) {
return this.emit('credentials', message);
}
// Resolves with the platform's acknowledgement, or rejects when it carries an
// `error` (either the platform's own stable string or a client validation
// failure).
emit(event, message) {
return new Promise((resolve, reject) => {
if (!this.client) {
reject(new SockethubError('Sockethub is not connected'));
return;
}
this.client.socket.emit(event, message, (response) => {
if (response?.error) {
reject(new SockethubPlatformError(response.error));
return;
}
resolve(response);
});
});
}
onMessage(handler) {
this.messageHandlers.add(handler);
return () => this.messageHandlers.delete(handler);
}
messageFor(err) {
if (typeof err === 'string') {
return err;
}
return err?.message ?? 'Unable to reach the Sockethub server';
}
willDestroy() {
this.disconnect();
super.willDestroy();
}
}