Add experiment encyption clients. Rewrite demos. Reduce implementation code. Add value decoding. Rename to base-client. Type inference and generics

This commit is contained in:
2026-10-22 14:51:46 +00:00
parent 2f9e46f659
commit df2c42e024
11 changed files with 923 additions and 283 deletions
+113 -46
View File
@@ -1,9 +1,9 @@
import { SSESession, toExtendedJson, fromExtendedJson } from '@xo-cash/utils';
import { PrivateKey } from '@xo-cash/primitives'
import { SyncClient } from '../shared/client.js';
import { BaseSyncClient, type ResourcesRecord } from '../shared/base-client.js';
export class SSEClient extends SyncClient {
export class SSEClient<PayloadType = unknown> extends BaseSyncClient<PayloadType> {
private readonly url: string;
public sseSession: SSESession | undefined;
private readonly subscriptions: Set<string> = new Set();
@@ -15,6 +15,11 @@ export class SSEClient extends SyncClient {
return `${this.url}/data/subscribe`;
}
/**
* Creates a new SSE client
* @param url - The URL of the server
* @param privateKey - The private key to use for authentication
*/
constructor(url: string, privateKey: PrivateKey) {
super();
@@ -29,6 +34,9 @@ export class SSEClient extends SyncClient {
}, 25);
}
/**
* Connects to the server
*/
async connect() {
// The server rejects a subscribe request with no resource IDs, so there is nothing to connect to yet.
// subscribe() connects once there is a subscription. read() and write() are plain fetches and don't need a session.
@@ -41,10 +49,16 @@ export class SSEClient extends SyncClient {
await this.sseSession.connect();
}
/**
* Disconnects from the server
*/
async disconnect() {
await this.sseSession?.disconnect();
}
/**
* Reconnects to the server
*/
async reconnect() {
// Close the current session. Its subscription list is fixed in the request body, so it can't be reused
this.sseSession?.close();
@@ -54,6 +68,10 @@ export class SSEClient extends SyncClient {
await this.connect();
}
/**
* Creates a new SSE session
* @returns The SSE session
*/
private createSession() {
// Build the request body
const body = toExtendedJson({ resourceId: [ ...this.subscriptions ] });
@@ -66,7 +84,7 @@ export class SSEClient extends SyncClient {
const path = url.pathname;
// Sign the request body
const authHeaders = SyncClient.signRequest(this.privateKey.toBytes(), path, request.body);
const authHeaders = BaseSyncClient.signRequest(this.privateKey.toBytes(), path, request.body);
// Initialize the request headers if they don't exist
request.headers ??= {};
@@ -95,12 +113,15 @@ export class SSEClient extends SyncClient {
// Create a listener to re-emit the messages
session.on('message', (message) => {
const parsedMessage = SyncClient.messageSchema.safeParse(fromExtendedJson(message.data));
const parsedMessage = BaseSyncClient.resourceInstanceSchema.safeParse(fromExtendedJson(message.data));
if (!parsedMessage.success) {
return;
}
this.emit('message', parsedMessage.data);
this.emit('resource-instance-updated', {
...parsedMessage.data,
value: fromExtendedJson(new TextDecoder().decode(parsedMessage.data.blob)) as PayloadType,
});
});
// Create a listener to re-emit the errors
@@ -112,69 +133,70 @@ export class SSEClient extends SyncClient {
return session;
}
// Send a POST /data/write request to the server
async write(resourceId: string, value: Record<string, unknown>) {
const url = `${this.url}/data/write`;
const valueStr = toExtendedJson(value);
const valueBytes = this.textEncoder.encode(valueStr);
const resource = SyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
const body = toExtendedJson({ resources: [resource] });
const res = await fetch(url, {
method: 'POST',
// Headers arent required unless we have payment service running
headers: {
'Content-Type': 'application/json',
...SyncClient.signRequest(this.privateKey.toBytes(), '/data/write', body),
},
body,
/**
* Send a POST /data/write request to the server
* @param resources - The resources to write
* @returns The Resource Object with the decoded value
*/
async writeMany(resources: Record<string, PayloadType>): Promise<ResourcesRecord<PayloadType>> {
// Sign the resource write requests
const signedResources = Object.entries(resources).map(([resourceId, value]) => {
const valueStr = toExtendedJson(value);
const valueBytes = this.textEncoder.encode(valueStr);
return BaseSyncClient.signWriteRequest(this.privateKey.toBytes(), resourceId, valueBytes);
});
// Send the resource write requests to the server
const res = await this.sendRequest('/data/write', { resources: signedResources });
// If the response is not ok, throw an error
if (!res.ok) {
const error = await res.json();
throw new Error(`Failed to write resource [${resourceId}] (${res.statusText}): ${JSON.stringify(error)}`);
throw new Error(`Failed to write resources [${Object.keys(resources).join(', ')}] (${res.statusText}): ${JSON.stringify(error)}`);
}
const text = fromExtendedJson(await res.text()) as { blob: ArrayBuffer, signature: string, publicKey: string, timestamp: number }[];
// Decode the response and return the resources
const decodedResources = await this.decodeResponse(res);
return text;
// Return the decoded resources
return decodedResources;
}
// Send a POST /data/read request to the server
async read(resourceId: string) {
const url = `${this.url}/data/get`;
const body = toExtendedJson({ resourceId: [ resourceId ] });
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...SyncClient.signRequest(this.privateKey.toBytes(), '/data/get', body),
},
body,
});
/**
* Send a POST /data/read request to the server
* @param resourceIds - The resource IDs to read
* @returns The resources with the read values
*/
async readMany(resourceIds: string[]): Promise<ResourcesRecord<PayloadType>> {
// Send the resource read requests to the server
const res = await this.sendRequest('/data/get', { resourceId: resourceIds });
// If the response is not ok, throw an error
if (!res.ok) {
throw new Error(`Failed to read resource: ${res.statusText}`);
throw new Error(`Failed to read resources [${resourceIds.join(', ')}] (${res.statusText})`);
}
const text = fromExtendedJson(await res.text()) as { blob: ArrayBuffer, signature: string, publicKey: string, timestamp: number }[];
// Decode the response and return the resources
const decodedResources = await this.decodeResponse(res);
return text;
// Return the decoded resources
return decodedResources;
}
// 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
* @param resourceId - The resource ID to add to the subscription list
*/
async subscribe(resourceId: string) {
this.subscriptions.add(resourceId);
this.emit('subscriptions-updated', this.subscriptions);
}
// 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 without the resource ID in the subscription list
* @param resourceId - The resource ID to remove from the subscription list
*/
async unsubscribe(resourceId: string) {
this.subscriptions.delete(resourceId);
@@ -184,4 +206,49 @@ export class SSEClient extends SyncClient {
async handleOnConnectionUpdated(value: 'connected' | 'disconnected') {
this.emit('connection-updated', value);
}
/**
* Sends a request to the server
* @param path - The path to send the request to
* @param body - The body of the request
* @returns The response from the server
*/
private async sendRequest(path: string, body: unknown): Promise<Response> {
// Build the URL
const url = `${this.url}${path}`;
// Format the body as Extended JSON
const formattedBody = toExtendedJson(body);
// Send the request to the server
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...BaseSyncClient.signRequest(this.privateKey.toBytes(), path, body),
},
body: formattedBody,
});
// Return the response
return res;
}
/**
* Decodes the blobs on the response body to the type T
* @param response - The response to decode
* @returns The decoded resources
*/
private async decodeResponse(response: Response): Promise<ResourcesRecord<PayloadType>> {
// Decode the response from Extended JSON
const text = fromExtendedJson(await response.text())
// Parse the response as a record of resources
const resources = BaseSyncClient.resourcesResponseSchema.parse(text);
// Decode the blobs and convert them from extended json to the type T
const decodedResources = BaseSyncClient.decodeResourcesResponse<PayloadType>(resources);
return decodedResources;
}
}