412 lines
15 KiB
TypeScript
412 lines
15 KiB
TypeScript
import * as plugins from './typedsocket.plugins.js';
|
|
|
|
const publicRoleName = 'publicRoleName';
|
|
const publicRolePass = 'publicRolePass';
|
|
|
|
export type TTypedSocketSide = 'server' | 'client';
|
|
|
|
/**
|
|
* Wrapper for SmartServe's IWebSocketPeer to provide tag compatibility
|
|
* SmartServe uses Set<string> for tags, while TypedSocket uses {id, payload} format
|
|
*/
|
|
export interface ISmartServeConnectionWrapper {
|
|
peer: plugins.IWebSocketPeer;
|
|
getTagById(tagId: string): Promise<{ id: string; payload: any } | undefined>;
|
|
}
|
|
|
|
/**
|
|
* Creates a wrapper around IWebSocketPeer for tag compatibility
|
|
*/
|
|
function wrapSmartServePeer(peer: plugins.IWebSocketPeer): ISmartServeConnectionWrapper {
|
|
const TAG_PREFIX = '__typedsocket_tag__';
|
|
return {
|
|
peer,
|
|
async getTagById(tagId: string): Promise<{ id: string; payload: any } | undefined> {
|
|
if (!peer.tags.has(tagId)) {
|
|
return undefined;
|
|
}
|
|
const payload = peer.data.get(`${TAG_PREFIX}${tagId}`);
|
|
return { id: tagId, payload };
|
|
},
|
|
};
|
|
}
|
|
|
|
export class TypedSocket {
|
|
// STATIC
|
|
/**
|
|
* creates a typedsocket server
|
|
* note: this will fail in browser environments as server libs are not bundled.
|
|
*/
|
|
public static async createServer(
|
|
typedrouterArg: plugins.typedrequest.TypedRouter,
|
|
smartexpressServerArg?: any
|
|
): Promise<TypedSocket> {
|
|
const smartsocketServer = new plugins.smartsocket.Smartsocket({
|
|
alias: 'typedsocketServer',
|
|
port: 3000,
|
|
});
|
|
if (smartexpressServerArg) {
|
|
smartsocketServer.setExternalServer('smartexpress', smartexpressServerArg);
|
|
}
|
|
|
|
smartsocketServer.socketFunctions.add(
|
|
new plugins.smartsocket.SocketFunction({
|
|
funcName: 'processMessage',
|
|
funcDef: async (dataArg, socketConnectionArg) => {
|
|
return typedrouterArg.routeAndAddResponse(dataArg);
|
|
},
|
|
})
|
|
);
|
|
const typedsocket = new TypedSocket(
|
|
'server',
|
|
typedrouterArg,
|
|
async <T extends plugins.typedrequestInterfaces.ITypedRequest>(
|
|
dataArg: T,
|
|
targetConnectionArg?: plugins.smartsocket.SocketConnection
|
|
): Promise<T> => {
|
|
if (!targetConnectionArg) {
|
|
if ((smartsocketServer.socketConnections.getArray().length = 1)) {
|
|
console.log(
|
|
'Since no targetConnection was supplied and there is only one active one present, choosing that one automatically'
|
|
);
|
|
targetConnectionArg = smartsocketServer.socketConnections.getArray()[0];
|
|
} else {
|
|
throw new Error(
|
|
'you need to specify the wanted targetConnection. Currently no target is selectable automatically.'
|
|
);
|
|
}
|
|
}
|
|
const response: T = (await smartsocketServer.clientCall(
|
|
'processMessage',
|
|
dataArg,
|
|
targetConnectionArg
|
|
)) as any;
|
|
return response;
|
|
},
|
|
smartsocketServer
|
|
);
|
|
await smartsocketServer.start();
|
|
|
|
return typedsocket;
|
|
}
|
|
|
|
public static async createClient(
|
|
typedrouterArg: plugins.typedrequest.TypedRouter,
|
|
serverUrlArg: string,
|
|
aliasArg = 'clientArg'
|
|
): Promise<TypedSocket> {
|
|
const domain = new plugins.smartstring.Domain(serverUrlArg);
|
|
|
|
const socketOptions: plugins.smartsocket.ISmartsocketClientOptions = {
|
|
alias: aliasArg,
|
|
port: domain.port || 3000,
|
|
url: `${domain.nodeParsedUrl.protocol}//${domain.nodeParsedUrl.hostname}`,
|
|
autoReconnect: true,
|
|
};
|
|
console.log(`starting typedsocket with the following settings:`);
|
|
console.log(socketOptions);
|
|
const smartsocketClient = new plugins.smartsocket.SmartsocketClient(socketOptions);
|
|
smartsocketClient.addSocketFunction(
|
|
new plugins.smartsocket.SocketFunction({
|
|
funcName: 'processMessage',
|
|
funcDef: async (dataArg, socketConnectionArg) => {
|
|
return typedrouterArg.routeAndAddResponse(dataArg);
|
|
},
|
|
})
|
|
);
|
|
const typedsocket = new TypedSocket(
|
|
'client',
|
|
typedrouterArg,
|
|
async <T extends plugins.typedrequestInterfaces.ITypedRequest>(dataArg: T): Promise<T> => {
|
|
const response: T = smartsocketClient.serverCall('processMessage', dataArg) as any as T;
|
|
return response;
|
|
},
|
|
smartsocketClient
|
|
);
|
|
console.log(`typedsocket triggering smartsocket to connect...`);
|
|
const before = Date.now();
|
|
await smartsocketClient.connect();
|
|
console.log(`typedsocket triggered smartsocket connected in ${Date.now() - before}ms!!!`)
|
|
|
|
return typedsocket;
|
|
}
|
|
|
|
public static useWindowLocationOriginUrl = () => {
|
|
const windowLocationResult = plugins.smarturl.Smarturl.createFromUrl(globalThis.location.origin).toString();
|
|
return windowLocationResult;
|
|
}
|
|
|
|
/**
|
|
* Creates a TypedSocket server from an existing SmartServe instance.
|
|
* Use this when you want TypedSocket to work with SmartServe's WebSocket handling.
|
|
*
|
|
* @param smartServeArg - SmartServe instance with typedRouter configured in websocket options
|
|
* @param typedRouterArg - TypedRouter for handling requests (must match SmartServe's typedRouter)
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* const typedRouter = new TypedRouter();
|
|
* const smartServe = new SmartServe({
|
|
* port: 3000,
|
|
* websocket: {
|
|
* typedRouter,
|
|
* onConnectionOpen: (peer) => peer.tags.add('client')
|
|
* }
|
|
* });
|
|
* await smartServe.start();
|
|
* const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter);
|
|
* ```
|
|
*/
|
|
public static fromSmartServe(
|
|
smartServeArg: plugins.SmartServe,
|
|
typedRouterArg: plugins.typedrequest.TypedRouter
|
|
): TypedSocket {
|
|
const connectionWrappers = new Map<string, ISmartServeConnectionWrapper>();
|
|
|
|
// Create the postMethod for server-initiated requests
|
|
const postMethod = async <T extends plugins.typedrequestInterfaces.ITypedRequest>(
|
|
dataArg: T,
|
|
targetConnectionArg?: ISmartServeConnectionWrapper
|
|
): Promise<T> => {
|
|
if (!targetConnectionArg) {
|
|
const allConnections = smartServeArg.getWebSocketConnections();
|
|
if (allConnections.length === 1) {
|
|
console.log(
|
|
'Since no targetConnection was supplied and there is only one active one present, choosing that one automatically'
|
|
);
|
|
const peer = allConnections[0];
|
|
let wrapper = connectionWrappers.get(peer.id);
|
|
if (!wrapper) {
|
|
wrapper = wrapSmartServePeer(peer);
|
|
connectionWrappers.set(peer.id, wrapper);
|
|
}
|
|
targetConnectionArg = wrapper;
|
|
} else if (allConnections.length === 0) {
|
|
throw new Error('No WebSocket connections available');
|
|
} else {
|
|
throw new Error(
|
|
'you need to specify the wanted targetConnection. Currently no target is selectable automatically.'
|
|
);
|
|
}
|
|
}
|
|
|
|
// Register interest for the response using correlation ID
|
|
const interest = await typedRouterArg.fireEventInterestMap.addInterest(
|
|
dataArg.correlation.id,
|
|
dataArg
|
|
);
|
|
|
|
// Send the request to the client
|
|
targetConnectionArg.peer.send(plugins.smartjson.stringify(dataArg));
|
|
|
|
// Wait for the response (TypedRouter will fulfill via routeAndAddResponse when response arrives)
|
|
const response = await interest.interestFullfilled as T;
|
|
return response;
|
|
};
|
|
|
|
const typedSocket = new TypedSocket(
|
|
'server',
|
|
typedRouterArg,
|
|
postMethod as any,
|
|
null as any // No smartsocket server/client when using SmartServe
|
|
);
|
|
|
|
typedSocket.smartServeRef = smartServeArg;
|
|
typedSocket.smartServeConnectionWrappers = connectionWrappers;
|
|
|
|
return typedSocket;
|
|
}
|
|
|
|
// INSTANCE
|
|
public side: TTypedSocketSide;
|
|
public typedrouter: plugins.typedrequest.TypedRouter;
|
|
|
|
// SmartServe mode properties
|
|
private smartServeRef?: plugins.SmartServe;
|
|
private smartServeConnectionWrappers: Map<string, ISmartServeConnectionWrapper> = new Map();
|
|
|
|
public get eventSubject(): plugins.smartrx.rxjs.Subject<plugins.smartsocket.TConnectionStatus> {
|
|
if (this.smartServeRef) {
|
|
// SmartServe doesn't provide an eventSubject, return a new Subject
|
|
// In SmartServe mode, connection events are handled via onConnectionOpen/onConnectionClose hooks
|
|
console.warn('eventSubject is not fully supported in SmartServe mode. Use SmartServe hooks instead.');
|
|
return new plugins.smartrx.rxjs.Subject();
|
|
}
|
|
return this.socketServerOrClient.eventSubject;
|
|
}
|
|
private postMethod: plugins.typedrequest.IPostMethod &
|
|
((
|
|
typedRequestPostObject: plugins.typedrequestInterfaces.ITypedRequest,
|
|
socketConnectionArg?: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper
|
|
) => Promise<plugins.typedrequestInterfaces.ITypedRequest>);
|
|
private socketServerOrClient:
|
|
| plugins.smartsocket.Smartsocket
|
|
| plugins.smartsocket.SmartsocketClient;
|
|
constructor(
|
|
sideArg: TTypedSocketSide,
|
|
typedrouterArg: plugins.typedrequest.TypedRouter,
|
|
postMethodArg: plugins.typedrequest.IPostMethod,
|
|
socketServerOrClientArg: plugins.smartsocket.Smartsocket | plugins.smartsocket.SmartsocketClient
|
|
) {
|
|
this.side = sideArg;
|
|
this.typedrouter = typedrouterArg;
|
|
this.postMethod = postMethodArg;
|
|
this.socketServerOrClient = socketServerOrClientArg;
|
|
}
|
|
|
|
public addTag<T extends plugins.typedrequestInterfaces.ITag = any>(
|
|
nameArg: T['name'],
|
|
payloadArg: T['payload']
|
|
) {
|
|
if (
|
|
this.side === 'client' &&
|
|
this.socketServerOrClient instanceof plugins.smartsocket.SmartsocketClient
|
|
) {
|
|
this.socketServerOrClient.socketConnection.addTag({
|
|
id: nameArg,
|
|
payload: payloadArg,
|
|
});
|
|
} else {
|
|
throw new Error('tagging is only supported on clients');
|
|
}
|
|
}
|
|
|
|
public createTypedRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>(
|
|
methodName: T['method'],
|
|
targetConnection?: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper
|
|
): plugins.typedrequest.TypedRequest<T> {
|
|
const typedrequest = new plugins.typedrequest.TypedRequest<T>(
|
|
new plugins.typedrequest.TypedTarget({
|
|
postMethod: async (requestDataArg) => {
|
|
const result = await this.postMethod(requestDataArg, targetConnection as any);
|
|
return result;
|
|
},
|
|
}),
|
|
methodName
|
|
);
|
|
return typedrequest;
|
|
}
|
|
|
|
/**
|
|
* returns all matching target connections
|
|
* Works with both Smartsocket and SmartServe backends
|
|
* @param asyncFindFuncArg - async filter function
|
|
* @returns array of matching connections
|
|
*/
|
|
public async findAllTargetConnections(
|
|
asyncFindFuncArg: (connectionArg: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper) => Promise<boolean>
|
|
): Promise<(plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper)[]> {
|
|
// SmartServe mode
|
|
if (this.smartServeRef) {
|
|
const matchingConnections: ISmartServeConnectionWrapper[] = [];
|
|
for (const peer of this.smartServeRef.getWebSocketConnections()) {
|
|
let wrapper = this.smartServeConnectionWrappers.get(peer.id);
|
|
if (!wrapper) {
|
|
wrapper = wrapSmartServePeer(peer);
|
|
this.smartServeConnectionWrappers.set(peer.id, wrapper);
|
|
}
|
|
if (await asyncFindFuncArg(wrapper)) {
|
|
matchingConnections.push(wrapper);
|
|
}
|
|
}
|
|
return matchingConnections;
|
|
}
|
|
|
|
// Smartsocket mode
|
|
if (this.socketServerOrClient instanceof plugins.smartsocket.Smartsocket) {
|
|
const matchingSockets: plugins.smartsocket.SocketConnection[] = [];
|
|
for (const socketConnection of this.socketServerOrClient.socketConnections.getArray()) {
|
|
if (await asyncFindFuncArg(socketConnection)) {
|
|
matchingSockets.push(socketConnection);
|
|
}
|
|
}
|
|
return matchingSockets;
|
|
}
|
|
|
|
throw new Error('this method >>findTargetConnection<< is only available from the server');
|
|
}
|
|
|
|
/**
|
|
* returns a single target connection by returning the first one of all matching ones
|
|
* @param asyncFindFuncArg
|
|
* @returns
|
|
*/
|
|
public async findTargetConnection(
|
|
asyncFindFuncArg: (connectionArg: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper) => Promise<boolean>
|
|
): Promise<plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper | undefined> {
|
|
const allMatching = await this.findAllTargetConnections(asyncFindFuncArg);
|
|
return allMatching[0];
|
|
}
|
|
|
|
/**
|
|
* Find all connections that have a specific tag
|
|
* Works with both Smartsocket and SmartServe backends
|
|
*/
|
|
public async findAllTargetConnectionsByTag<
|
|
TTag extends plugins.typedrequestInterfaces.ITag = any
|
|
>(keyArg: TTag['name'], payloadArg?: TTag['payload']): Promise<(plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper)[]> {
|
|
// SmartServe mode - use native filtering for better performance
|
|
if (this.smartServeRef) {
|
|
const peers = this.smartServeRef.getWebSocketConnectionsByTag(keyArg);
|
|
const results: ISmartServeConnectionWrapper[] = [];
|
|
|
|
for (const peer of peers) {
|
|
let wrapper = this.smartServeConnectionWrappers.get(peer.id);
|
|
if (!wrapper) {
|
|
wrapper = wrapSmartServePeer(peer);
|
|
this.smartServeConnectionWrappers.set(peer.id, wrapper);
|
|
}
|
|
|
|
// If payload specified, also filter by payload stored in peer.data
|
|
if (payloadArg !== undefined) {
|
|
const tag = await wrapper.getTagById(keyArg);
|
|
if (plugins.smartjson.stringify(tag?.payload) !== plugins.smartjson.stringify(payloadArg)) {
|
|
continue;
|
|
}
|
|
}
|
|
results.push(wrapper);
|
|
}
|
|
return results;
|
|
}
|
|
|
|
// Smartsocket mode - use existing logic
|
|
return this.findAllTargetConnections(async (socketConnectionArg) => {
|
|
let result: boolean;
|
|
if (!payloadArg) {
|
|
result = !!(await (socketConnectionArg as plugins.smartsocket.SocketConnection).getTagById(keyArg));
|
|
} else {
|
|
result = !!(
|
|
plugins.smartjson.stringify((await (socketConnectionArg as plugins.smartsocket.SocketConnection).getTagById(keyArg))?.payload) ===
|
|
plugins.smartjson.stringify(payloadArg)
|
|
);
|
|
}
|
|
return result;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Find a single connection by tag
|
|
*/
|
|
public async findTargetConnectionByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(
|
|
keyArg: TTag['name'],
|
|
payloadArg?: TTag['payload']
|
|
): Promise<plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper | undefined> {
|
|
const allResults = await this.findAllTargetConnectionsByTag(keyArg, payloadArg);
|
|
return allResults[0];
|
|
}
|
|
|
|
/**
|
|
* Stop the TypedSocket server/client
|
|
* Note: In SmartServe mode, SmartServe manages its own lifecycle
|
|
*/
|
|
public async stop() {
|
|
if (this.smartServeRef) {
|
|
// SmartServe manages its own lifecycle
|
|
// Clear our connection wrappers
|
|
this.smartServeConnectionWrappers.clear();
|
|
return;
|
|
}
|
|
await this.socketServerOrClient.stop();
|
|
}
|
|
}
|