Fix Web Sockets. Form into library. Move demo to demo folder. Split demo between sse and websocket.

This commit is contained in:
2026-09-17 11:49:21 +00:00
parent 55d09d048e
commit 711ecba117
10 changed files with 134 additions and 96 deletions
+37
View File
@@ -0,0 +1,37 @@
import { PrivateKey } from "@xo-cash/primitives";
import { toExtendedJson } from "@xo-cash/utils";
import { SSEClient } from '../src/sse/client.js';
const testSSE = async () => {
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
const client = new SSEClient('https://v2.sync.xo.harvmaster.com', privateKey, {
onMessage: (message) => {
console.log(toExtendedJson(message));
},
onError: (error) => {
console.error(error);
},
});
// Connect to the sync server
await client.connect();
// Subscribe to the resource
await client.subscribe('test');
// Write a new value to the resource
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using SSE'});
// Read the current value of the resource
const data = await client.read('test');
console.log(data);
// If the user presses Ctrl+C, disconnect the client and exit the program
process.on('SIGINT', async () => {
await client.disconnect();
process.exit(0);
});
}
testSSE();
+37
View File
@@ -0,0 +1,37 @@
import { PrivateKey } from "@xo-cash/primitives";
import { toExtendedJson } from "@xo-cash/utils";
import { WsClient } from '../src/ws/client.js';
const testWS = async () => {
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
const client = new WsClient('https://v2.sync.xo.harvmaster.com', privateKey, {
onMessage: (message) => {
console.log(toExtendedJson(message));
},
onError: (error) => {
console.error(error);
},
});
// Connect to the sync server
await client.connect();
// Subscribe to the resource
client.subscribe('test');
// Write a new value to the resource
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using WS'});
// Read the current value of the resource
const data = await client.read('test');
console.log(data);
// If the user presses Ctrl+C, disconnect the client and exit the program
process.on('SIGINT', async () => {
await client.disconnect();
process.exit(0);
});
}
testWS();
+8 -8
View File
@@ -15,7 +15,7 @@
"zod": "^4.4.3" "zod": "^4.4.3"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^26.1.1", "@types/node": "^26.6.1",
"tsx": "^4.23.1", "tsx": "^4.23.1",
"typescript": "^7.0.2" "typescript": "^7.0.2"
} }
@@ -472,13 +472,13 @@
} }
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "26.2.0", "version": "26.6.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.1.tgz",
"integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==", "integrity": "sha512-VqGJBMCtdhqkBUCcBLvywI0NJ+KLuVzgNnlBUNFOQjqVxzo2lxLUNg1DSey8+u2u6ktswSAxg+s68QLzWHNOuA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~8.3.0" "undici-types": "~8.9.0"
} }
}, },
"node_modules/@typescript/typescript-aix-ppc64": { "node_modules/@typescript/typescript-aix-ppc64": {
@@ -989,9 +989,9 @@
} }
}, },
"node_modules/undici-types": { "node_modules/undici-types": {
"version": "8.3.0", "version": "8.9.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
+10 -3
View File
@@ -1,18 +1,25 @@
{ {
"name": "minimal-sync", "name": "@xo-cash/sync-client",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "A minimal sync client for the XO Cash Sync Server",
"main": "index.js", "main": "index.js",
"type": "module", "type": "module",
"scripts": { "scripts": {
"build": "tsc",
"start": "tsx src/index.ts", "start": "tsx src/index.ts",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"keywords": [], "keywords": [],
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"devDependencies": { "devDependencies": {
"@types/node": "^26.1.1", "@types/node": "^26.6.1",
"tsx": "^4.23.1", "tsx": "^4.23.1",
"typescript": "^7.0.2" "typescript": "^7.0.2"
}, },
+3 -52
View File
@@ -1,53 +1,4 @@
import { PrivateKey } from "@xo-cash/primitives"; export * from './shared/client.js';
import { SSEClient } from "./sse/client.js"; export * from './sse/client.js';
import { WsClient } from './ws/client.js'; export * from './ws/client.js';
const testSSE = async () => {
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
const client = new SSEClient('https://v2.sync.xo.harvmaster.com', privateKey, {
onMessage: (message) => {
console.log(message);
},
onError: (error) => {
console.error(error);
},
});
await client.subscribe('test');
// await client.connect();
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using SSE'});
const data = await client.read('test');
console.log(data);
// await client.disconnect();
}
const testWS = async () => {
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
const client = new WsClient('wss://v2.sync.xo.harvmaster.com', privateKey, {
onMessage: (message) => {
console.log(message);
},
onError: (error) => {
console.error(error);
},
});
await client.connect();
await client.subscribe('test');
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using WS'});
const data = await client.read('test');
console.log(data);
// await client.unsubscribe('test');
// await client.disconnect();
}
testSSE();
// testWS();
+7 -2
View File
@@ -79,7 +79,7 @@ export abstract class SyncClient {
// Create the payload // Create the payload
const timestamp = Date.now(); const timestamp = Date.now();
const payload = `${timestamp}${resourceId}${toExtendedJson(value)}`; const payload = `${timestamp}:${resourceId}:${toExtendedJson(value)}`;
// Sign the payload // Sign the payload
const { publicKey, signature } = this.signPayload(derivedKey, payload); const { publicKey, signature } = this.signPayload(derivedKey, payload);
@@ -103,7 +103,12 @@ export abstract class SyncClient {
static signRequest(privateKey: Uint8Array, path: string, body: unknown): AuthenticatedRequestHeaders { static signRequest(privateKey: Uint8Array, path: string, body: unknown): AuthenticatedRequestHeaders {
// Create the payload // Create the payload
const timestamp = Date.now(); const timestamp = Date.now();
const payload = `${timestamp}:${path}:${toExtendedJson(body)}`;
// Convert the body to a string if it isn't already a string
const bodyStr = typeof body === 'string' ? body : toExtendedJson(body);
// Create the payload as `Timestamp:Path:Body`
const payload = `${timestamp}:${path}:${bodyStr}`;
// Sign the payload // Sign the payload
const { publicKey, signature } = this.signPayload(privateKey, payload); const { publicKey, signature } = this.signPayload(privateKey, payload);
+17 -18
View File
@@ -1,17 +1,18 @@
import { SSESession, toExtendedJson } from '@xo-cash/utils'; import { SSESession, toExtendedJson, fromExtendedJson } from '@xo-cash/utils';
import { PrivateKey } from '@xo-cash/primitives' import { PrivateKey } from '@xo-cash/primitives'
import { SyncClient } from '../shared/client.js'; import { SyncClient } from '../shared/client.js';
export type SSEClientOptions = { export type SSEClientOptions = {
onMessage: (message: string) => void; onMessage: (message: unknown) => void;
onError: (error: Error) => void; onError: (error: Error) => void;
}; };
export class SSEClient extends SyncClient { export class SSEClient extends SyncClient {
private sseSession: SSESession; private readonly url: string;
public sseSession: SSESession;
private readonly subscriptions: Set<string> = new Set(); private readonly subscriptions: Set<string> = new Set();
private readonly messageListeners = new Set<(message: string) => void>(); private readonly messageListeners = new Set<(message: unknown) => void>();
private readonly errorListeners = new Set<(error: Error) => void>(); private readonly errorListeners = new Set<(error: Error) => void>();
private privateKey: PrivateKey; private privateKey: PrivateKey;
@@ -21,9 +22,10 @@ export class SSEClient extends SyncClient {
return `${this.url}/data/subscribe`; return `${this.url}/data/subscribe`;
} }
constructor(private readonly url: string, privateKey: PrivateKey, options: Partial<SSEClientOptions> = {}) { constructor(url: string, privateKey: PrivateKey, options: Partial<SSEClientOptions> = {}) {
super(); super();
this.url = url;
this.privateKey = privateKey; this.privateKey = privateKey;
this.sseSession = new SSESession(`${this.url}/data/subscribe`, { this.sseSession = new SSESession(`${this.url}/data/subscribe`, {
method: 'POST', method: 'POST',
@@ -53,15 +55,12 @@ export class SSEClient extends SyncClient {
// Re-create the session with the additional resource ID in the subscription list // Re-create the session with the additional resource ID in the subscription list
this.sseSession = new SSESession(this.subscriptionUrl, { this.sseSession = new SSESession(this.subscriptionUrl, {
onRequest: async (request) => { onRequest: async (request) => {
// Create the request authentication headers
const requestBody = toExtendedJson(request.body);
// Get the path from the URL // Get the path from the URL
const url = new URL(this.url); const url = new URL(this.subscriptionUrl);
const path = url.pathname; const path = url.pathname;
// Sign the request body // Sign the request body
const authHeaders = SyncClient.signRequest(this.privateKey.toBytes(), path, requestBody); const authHeaders = SyncClient.signRequest(this.privateKey.toBytes(), path, request.body);
// Initialize the request headers if they don't exist // Initialize the request headers if they don't exist
request.headers ??= {}; request.headers ??= {};
@@ -78,14 +77,14 @@ export class SSEClient extends SyncClient {
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: body, body,
method: 'POST', method: 'POST',
}); });
// Create a listener to re-emit the messages // Create a listener to re-emit the messages
this.sseSession.on('message', (message) => { this.sseSession.on('message', (message) => {
for (const listener of this.messageListeners) { for (const listener of this.messageListeners) {
listener(message.data); listener(fromExtendedJson(message.data));
} }
}); });
@@ -108,7 +107,7 @@ export class SSEClient extends SyncClient {
const valueBytes = this.textEncoder.encode(valueStr); const valueBytes = this.textEncoder.encode(valueStr);
const resource = SyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes); const resource = SyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
const bodyStr = toExtendedJson({ resources: [resource] }); const body = toExtendedJson({ resources: [resource] });
const res = await fetch(url, { const res = await fetch(url, {
method: 'POST', method: 'POST',
@@ -116,10 +115,10 @@ export class SSEClient extends SyncClient {
// Headers arent required unless we have payment service running // Headers arent required unless we have payment service running
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// ...SSEClient.authenticateRequest(this.privateKey, bodyStr), ...SyncClient.signRequest(this.privateKey.toBytes(), '/data/write', body),
}, },
body: bodyStr, body,
}); });
if (!res.ok) { if (!res.ok) {
@@ -127,7 +126,7 @@ export class SSEClient extends SyncClient {
throw new Error(`Failed to write resource [${resourceId}] (${res.statusText}): ${JSON.stringify(error)}`); throw new Error(`Failed to write resource [${resourceId}] (${res.statusText}): ${JSON.stringify(error)}`);
} }
return res.json(); return fromExtendedJson(await res.text());
} }
// Send a POST /data/read request to the server // Send a POST /data/read request to the server
@@ -139,7 +138,7 @@ export class SSEClient extends SyncClient {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// ...SSEClient.authenticateRequest(this.privateKey, body), ...SyncClient.signRequest(this.privateKey.toBytes(), '/data/get', body),
}, },
body, body,
}); });
@@ -148,7 +147,7 @@ export class SSEClient extends SyncClient {
throw new Error(`Failed to read resource: ${res.statusText}`); throw new Error(`Failed to read resource: ${res.statusText}`);
} }
return res.json(); return fromExtendedJson(await res.text());
} }
// Destroy the current SSE Session, then re-create it with the additional resource ID in the subscription list // Destroy the current SSE Session, then re-create it with the additional resource ID in the subscription list
+13 -10
View File
@@ -40,18 +40,22 @@ export type WsClientOptions = {
* here to keep the transport demo easy to follow. * here to keep the transport demo easy to follow.
*/ */
export class WsClient extends SyncClient { export class WsClient extends SyncClient {
private readonly url: string;
private readonly privateKey: PrivateKey;
private socket: WebSocket | undefined; private socket: WebSocket | undefined;
private readonly pendingRequests = new Map<string, PendingRequest>(); private readonly pendingRequests = new Map<string, PendingRequest>();
private readonly messageListeners = new Set<(message: WsMessage) => void>(); private readonly messageListeners = new Set<(message: WsMessage) => void>();
private readonly errorListeners = new Set<(error: Error) => void>(); private readonly errorListeners = new Set<(error: Error) => void>();
constructor( constructor(
private readonly url: string, url: string,
private readonly privateKey: PrivateKey, privateKey: PrivateKey,
options: Partial<WsClientOptions> = {}, options: Partial<WsClientOptions> = {},
) { ) {
super(); super();
this.url = url;
this.privateKey = privateKey;
this.messageListeners.add(options.onMessage ?? (() => {})); this.messageListeners.add(options.onMessage ?? (() => {}));
this.errorListeners.add(options.onError ?? (() => {})); this.errorListeners.add(options.onError ?? (() => {}));
} }
@@ -72,7 +76,7 @@ export class WsClient extends SyncClient {
this.handleMessage(String(event.data)); this.handleMessage(String(event.data));
}; };
socket.onerror = () => { socket.onerror = (ev) => {
const error = new Error('WebSocket connection failed'); const error = new Error('WebSocket connection failed');
this.emitError(error); this.emitError(error);
reject(error); reject(error);
@@ -134,15 +138,14 @@ export class WsClient extends SyncClient {
* been handed to the socket; future updates arrive through `onMessage`. * been handed to the socket; future updates arrive through `onMessage`.
*/ */
async subscribe(resourceId: string): Promise<void> { async subscribe(resourceId: string): Promise<void> {
this.send({ await this.request('/data/subscribe', { resourceId: [resourceId] });
path: '/data/subscribe',
body: { resourceId: [resourceId] },
});
} }
/** Remove one resource topic without closing the shared connection. */ /**
async unsubscribe(resourceId: string): Promise<unknown> { * Unsubscribe from one resource topic on the current connection.
return this.request('/data/unsubscribe', { resourceId: [resourceId] }); */
async unsubscribe(resourceId: string): Promise<void> {
await this.request('/data/unsubscribe', { resourceId: [resourceId] });
} }
/** Send a request and wait for the response carrying the same ID. */ /** Send a request and wait for the response carrying the same ID. */
-1
View File
@@ -2,7 +2,6 @@
// Visit https://aka.ms/tsconfig to read more about this file // Visit https://aka.ms/tsconfig to read more about this file
"compilerOptions": { "compilerOptions": {
// File Layout // File Layout
"rootDir": "./src",
"outDir": "./dist", "outDir": "./dist",
// Environment Settings // Environment Settings