API @deepkit/rpc
npm install @deepkit/rpc
This direct client includes in each outgoing/incoming message an async hop making
the communication asynchronous. A RpcClient that connects via WebSocket transport. Spreads the calls of its controllers over several clients, for example one per worker thread, so that the work
runs in parallel. Each call goes to the client with the fewest calls in flight. A call that returns an Observable or Collection stays with its client. Calls of one controller are not ordered
among each other, since they may run on different clients. Collects the frames written in one tick into one message. Every message is a new buffer of the exact size,
so that channels can transfer it to the other side instead of copying it. Connects to a RpcKernel on the other side of a channel. The channel can carry one connection at a time. After a disconnect the client connects again over the same channel. A channel between two threads over shared memory, without messages: the sender copies the frames directly into
a ring buffer, the receiver reads them from there. It's the fastest channel between threads, in node's
The memory doesn't tell when the other thread ends: call close() of the channel then, for example on the
This is a reference implementation and only works in a single process.
A real-life implementation would use an external message-bus, like Redis & co. The kernel is responsible for parsing the message header, redirecting to peer if necessary, loading the body parser,
and encode/send outgoing messages. Maps numeric action ids to controller actions and holds the schema that is sent to clients in the handshake.
Ids are never reassigned: a client may be connected while a controller is registered later. A value serialized once, to be sent in many messages. It is what preSerialize() returns.
The bytes are identical to serializing the value in place. internal note: This is aligned with Splits the byte stream into frames. Frames are passed on with no copy and nothing allocated: the owner sets
onRawFrame and decodes what it needs inside the call. Chunked frames are put together here. This class acts as a layer between kernel/client and a connection writer.
It automatically chunks long messages into multiple smaller one using the RpcType.Chunks type. todo:
It keeps track of the back-pressure and sends only when the pressure is not too big.
It automatically saves big buffer to the file system and streams data from there to not
block valuable memory. Context ids from here on are calls to the connection itself (see ControlOp) and schema requests. They are a range of
their own so that they don't disturb the implicit counting of TypeAction. The proxy behind client.controller Returns the WebSocket URL for the given base URL and allows port mapping.
Default port-mapping maps Angular server :4200 to :8080 Creates a provider for RpcWebSocketClient that is compatible with Angular and Deepkit.
baseUrl needs to be absolute. Serves the RpcKernel to the other side of a channel, where a RpcClient connects with RpcChannelClientAdapter. Each connection gets its own scope A channel over a MessagePort, a MessageChannel's port, a Worker, or Other messages may share the port: messages that are not a Uint8Array are ignored. A channel over the IPC channel of a forked child process: the ChildProcess in the parent,
and Other messages may share the channel: messages that are not a Uint8Array are ignored.
createStreamChannel() over an extra pipe of the child is faster. A channel over a byte stream, for example an extra pipe of a child process: A stream carries one connection: ending it ends the stream. Creates the shared memory for createSharedMemoryChannel(). Pass it to the other thread, for example as
Reads the arguments into an array that is reused for every call unless there is a rest parameter, so the
caller has to be done with it before the next call. Must not be called re-entrantly. How the body of a message of the given type is written: the values of its properties one after the other in the
order they are declared, exactly like the arguments of a call. A property that isn't given keeps its position, see
setSerializerCode. Any other type is a single value. Whether the frame carries a context id: ContextExisting or ContextEnd. The bytes that route data takes at the start of the frame at start. Offset of the body of a frame. For TypeChannel and TypeControl that is the offset of their type header. The peer a frame routed via peer goes to. Copy of a frame that outlives the read buffer. A Buffer's own slice() would only be a view. The context id of a frame that has one, without route data. The context id of a frame, 0 when it has none. The memory the frames are written to: a frame is the range 0 to the size returned by the write function.
Only valid until the next frame is written. A copy of the frame that was just written, which stays valid after the next one is written. Has to be called when something still holds on to the memory of a frame. The value of the varint at the offset. The offset after the varint at the offset. The offset of the value of a TypeChannel frame, given the offset of its sub byte. The subscription of a TypeChannel frame that is a value. The frames are written into the shared buffer, see frameMemory. They return the size of the frame. A value the server sends on the connection without the client having called anything for it, for protocols built on
RPC that push many small values. There is no stream to set up and no context: A control frame, with a body written by the given serializer, if any. A control frame whose body is a subscription or token. The error of a TypeError frame, at the offset of its body. The error of one subscription of a stream, or of the stream when it is a subject. A result that was serialized once with preSerialize(). One value of an observable that was serialized once with preSerialize(). The first frame of a connection: Also how a controller of the other side or of a peer asks for its action schema, then with a route and a context. The offset of the version of a TypeSchema frame. Serializes Sends the frames of the fast path. Transports without a binary socket get their own copy,
as they may hold on to the memory. Create a Subject with teardown function that is called when
client disconnects or completes the subject. The producer is called in the next tick, no matter if the client
subscribes to the subject or not. This is fundamentally different
from Observables, where the producer is only called when the Observable
is subscribed to. Teardown is also called when the producer errors or completes. You should normally prefer using Observables (with instantObservable)
over Subjects, as Subjects are not lazy and start emitting values
immediately when created. Returns a Subject that is immediately subscribed to the given producer. The producer can be a Promise or a function that returns a Promise. Note that the Subject will be requested from the Promise right away. A transport that calls actions by name, one request per call, without a connection or streams. A connection between two sides that are not connected over the network: a worker thread, a Web Worker,
a forked child process, or any other message port or byte stream. RPC frames are sent over it, one
side runs a RpcKernel with serveRpcChannel() and the other a RpcClient with RpcChannelClientAdapter. Use createMessagePortChannel(), createProcessChannel() or createStreamChannel(), or implement it for other channels. The parts of a MessagePort, Worker, or the global scope of a Web Worker ( The parts of a ChildProcess or of The parts of a node Duplex stream the channel uses, like a net.Socket. Bytes of a parameter that are a view on the received frame instead of a copy.
Only valid during the synchronous part of the action: for what is forwarded or read right away, not for what is kept. Sent to the client in the handshake. The types stay serialized until an action is used for the first time. Sends the frame in the range 0 to size of the buffer, which may be the shared message buffer:
it is written and given up during the call. All times are in milliseconds (using performance.now()).Classes
export class RpcControllerState {
peerId?: string;
constructor(public controller: string);
getState(method: string): ControllerStateActionState;
}
export class RpcActionClient {
entityState;
fastHost?: RpcFastHost;
/** A transfer was aborted: nothing will be answered anymore. */
abort(id: number, error: Error): void;
/**
* The connection is gone, nothing on it can be answered anymore.
*/
onDisconnect(error?: Error): void;
/**
* A call to the connection itself: authentication, peers and the like.
*/
systemCall(op: ControlOp, serialize?: AutoBufferSerializer, value?: any, deserialize?: ReturnDeserializer): Promise<any>;
action<T>(controller: RpcControllerState, method: string, args: any[], options: {
timeout?: number;
dontWaitForConnection?: true;
typeReuseDisabled?: boolean;
} = {}): Promise<any>;
/** The types of an action, as they are described by the server. */
async loadActionTypes(controller: RpcControllerState, method: string, options: {
timeout?: number;
dontWaitForConnection?: true;
typeReuseDisabled?: boolean;
} = {}): Promise<ControllerStateActionTypes>;
}
export class DirectClient extends RpcClient {
constructor(rpcKernel: RpcKernel, injector?: InjectorContext);
}
export class RpcDirectClientAdapter implements ClientTransportAdapter {
constructor(public rpcKernel: RpcKernel, protected injector?: InjectorContext);
async connect(connection: TransportClientConnection);
}
export class AsyncDirectClient extends RpcClient {
constructor(rpcKernel: RpcKernel, injector?: InjectorContext);
}
export class RpcAsyncDirectClientAdapter implements ClientTransportAdapter {
constructor(public rpcKernel: RpcKernel, protected injector?: InjectorContext);
async connect(connection: TransportClientConnection);
}
export class RpcWebSocketClient extends RpcClient {
constructor(url: string);
static fromCurrentHost<T extends ClassType<RpcClient>>(this: T, baseUrl: string = ): InstanceType<T>;
}
export class DeepkitClient extends RpcWebSocketClient {
}
export class RpcWebSocketClientAdapter implements ClientTransportAdapter {
constructor(public url: string, protected webSocketConstructor: typeof WebSocket = WebSocket);
async getWebSocketConstructor(): Promise<typeof WebSocket>;
async connect(connection: TransportClientConnection);
}
export class RpcClientToken {
constructor(protected token: any);
get();
set(v: any);
has();
}
export class RpcClientTransporter {
connectionId: number;
writerOptions: TransportOptions;
id?: Uint8Array;
/**
* When the connection is established (including handshake and authentication).
*/
readonly connection;
/**
* When the connection was reconnected. This is not called for the very first connection.
*/
readonly reconnected;
/**
* When the connection was disconnected (due to error or close).
* This increases the connectionId by one.
*/
readonly disconnected;
/**
* Triggered for any onError call from the transporter.
* Right after this event, onDisconnect is called (and thus connection.next(false) and disconnected.next()).
*/
readonly errored;
reader;
/** Hash of the action schema the handshake delivered, to not transfer it again. */
schemaHash: number;
constructor(public transport: ClientTransportAdapter, protected stats: RpcStats);
bufferedAmount(): number;
clientAddress(): string;
/**
* True when fully connected (after successful handshake and authentication)
*/
isConnected(): boolean;
onClose(error?: Error);
/**
* Optional handshake.
* When peer messages are allowed, this needs to request the client id and returns id.
*/
async onHandshake(): Promise<Uint8Array | undefined>;
async onAuthenticate(token?: any): Promise<void>;
/**
* Receives all frames that are not chunks. The buffer is only valid during this call.
*/
onFrame(buffer: Uint8Array, start: number, end: number): void;
onSchema(mapping: ParsedSchemaMapping, hash: number): void;
/**
* Reads the handshake reply: the protocol version of the server, and the action schema if it is new to us.
*/
onHelloReply(buffer: Uint8Array, start: number, end: number): void;
/** Whether a connection exists to send frames on. */
canSend(): boolean;
/** Asks for the actions of the server again. */
async refreshSchema(): Promise<void>;
/**
* Sends the frame in the range 0 to size of the buffer, see RpcFrameSender.
*/
sendFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
async disconnect();
/**
* Simply connect with login using the token, without auto re-connect.
*/
async connect(token?: any): Promise<void>;
}
export class RpcClientPeer {
constructor(protected actionClient: RpcActionClient, protected peerId: string, protected onDisconnect: (peerId: string) => void);
controller<T>(nameOrDefinition: string | ControllerDefinition<T>, options: {
timeout?: number;
dontWaitForConnection?: true;
} = {}): RemoteController<T>;
disconnect();
}
export class RpcBaseClient implements RpcFastHost {
clientStats: RpcStats;
actionClient;
readonly token;
readonly transporter: RpcClientTransporter;
username?: string;
typeReuseDisabled: boolean;
events;
constructor(protected transport: ClientTransportAdapter);
onFrame(buffer: Uint8Array, start: number, end: number): void;
/**
* Receives the frames of a push channel, see writePushFrameTransient. The range of the values is only valid during the call.
*/
onPush(channel: number, handler: RpcPushHandler): void;
getSchemaMapping(): ParsedSchemaMapping | undefined;
getSchemaEpoch(): number;
isActionReady(dontWaitForConnection?: boolean): boolean;
getContexts(): SequentialContextDispatcher<FrameHandler>;
getChunkSize(): number;
sendActionFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
registerDownloadProgress(id: number, progress: SingleProgress): void;
isObserved(): boolean;
emitEvent(event: RpcClientEvent): void;
connectForAction(): Promise<unknown>;
refreshSchema(): Promise<unknown>;
hasBinaryTransport(): boolean;
getHttpTransport(): RpcHttpTransport | undefined;
getToken(): any;
currentConnectionId(): number;
getRoute(): RouteFlag;
onClose(error?: Error);
/**
* Per default entity types with a name (@entity.name()) will be reused. If a entity with a given name
* was not loaded and error is thrown. This to ensure nominal typing (object instanceof T).
* Use this method to disable this behavior and construct new nominal types if an entity is not loaded.
*/
disableTypeReuse(): this;
getId(): Uint8Array;
debug();
async connect(): Promise<this>;
async disconnect();
}
export class RpcClient extends RpcBaseClient {
/**
* For server->client (us) communication.
* This is automatically created when registerController is called.
* Set this property earlier to work with a custom RpcKernel.
*/
clientKernel?: RpcKernel;
/**
* For peer->client(us) communication.
* This is automatically created when registerAsPeer is called.
* Set this property earlier to work with a custom RpcKernel.
*/
peerKernel?: RpcKernel;
async ping(): Promise<void>;
getPeerRoute(peerId: string): Uint8Array;
getId(): Uint8Array;
/**
* Registers a new controller for the peer's RPC kernel.
* Use `registerAsPeer` first.
*/
registerPeerController<T>(classType: ClassType<T>, nameOrDefinition: string | ControllerDefinition<T>);
/**
* Registers a new controller for the server's RPC kernel.
* This is when the server wants to communicate actively with the client (us).
*/
registerController<T>(classType: ClassType<T>, nameOrDefinition: string | ControllerDefinition<T>);
async registerAsPeer(id: string);
/**
* Creates a new peer connection, or re-uses an existing non-disconnected one.
*
* Make sure to call disconnect() on it once you're done using it, otherwise the peer
* will leak memory. (connection will be dropped if idle for too long automatically tough)
*/
peer(peerId: string): RpcClientPeer;
controller<T>(nameOrDefinition: string | ControllerDefinition<T>, options: {
timeout?: number;
dontWaitForConnection?: true;
typeReuseDisabled?: boolean;
} = {}): RemoteController<T>;
}
export class RpcClientPool {
constructor(public readonly clients: RpcClient[]);
/** Calls in flight per client. */
get load(): readonly number[];
controller<T>(nameOrDefinition: string | ControllerDefinition<T>, options?: {
timeout?: number;
dontWaitForConnection?: true;
}): RemoteController<T>;
async disconnect(): Promise<void>;
}
const pool = new RpcClientPool(
Array.from({ length: 4 }, () => {
const worker = new Worker('./server.js');
return new RpcClient(new RpcChannelClientAdapter(createMessagePortChannel(worker)));
}),
);
const image = pool.controller<ImageController>('image');
await Promise.all(files.map(file => image.resize(file, 200)));
export class RpcHttpFetch implements RpcHttpInterface {
constructor(private baseUrl: string | ((url: string) => string) = );
async fetch(url: string, options: {
headers: {
[name: string]: string;
};
method: string;
body: any;
}): Promise<RpcHttpResponseInterface>;
}
export class RpcHttpClientAdapter implements ClientTransportAdapter, RpcHttpTransport {
constructor(public url: string, public headers: {
[name: string]: string;
} = {}, public http: RpcHttpInterface = new RpcHttpFetch());
supportsPeers();
supportsAuthentication();
httpTransport(): RpcHttpTransport;
async connect(connection: TransportClientConnection): Promise<void>;
requestTypes(controller: string, method: string, token: any): Promise<RpcHttpActionTypes>;
requestCall(controller: string, method: string, args: any[], token: any): Promise<any>;
}
export class RpcChannelMessageWriter implements BinarySocket {
readonly writableLength;
constructor(protected send: (data: Uint8Array) => void, protected capacity: number = * );
write(buffer: Uint8Array): void;
writeRange(buffer: Uint8Array, start: number, end: number): void;
flush(): void;
}
export class RpcChannelClientAdapter implements ClientTransportAdapter {
constructor(public channel: RpcChannel);
async connect(connection: TransportClientConnection): Promise<void>;
}
const worker = new Worker('./server.js');
const client = new RpcClient(new RpcChannelClientAdapter(createMessagePortChannel(worker)));
export class SharedMemoryChannel implements RpcChannel {
readonly name;
readonly binarySocket: BinarySocket;
constructor(memory: SharedArrayBuffer, side: | , options: SharedMemoryChannelOptions = {});
send(data: Uint8Array): void;
end(): void;
listen(onData: (data: Uint8Array, bytes?: number) => void, onEnd: (reason: string) => void): () => void;
/** Ends listening and the current connection, when the other thread is gone. */
close(): void;
}
worker_threads as in the browser's Web Workers. In the browser, SharedArrayBuffer needs a page with
cross-origin isolation (the headers Cross-Origin-Opener-Policy: same-origin and
Cross-Origin-Embedder-Policy: require-corp), and both sides need Atomics.waitAsync.// main thread
const memory = createRpcSharedMemory();
const worker = new Worker('./server.js', { workerData: { memory } });
const client = new RpcClient(new RpcChannelClientAdapter(createSharedMemoryChannel(memory, 'client')));
// worker
serveRpcChannel(kernel, createSharedMemoryChannel(workerData.memory, 'server'));
exit event of the worker.export class EntitySubjectStore<T extends IdVersionInterface> {
store;
onCreation;
constructor(protected classType: ClassType);
isRegistered(id: IdType): boolean;
register(item: T): void;
deregister(id: IdType): void;
getItem(id: IdType): T | undefined;
onDelete(id: IdType): void;
onSet(id: IdType, item: T): void;
onPatch(id: IdType, version: number, patch: EntityPatch): void;
/**
* Before calling createFork you must be sure the item is already registered.
*/
createFork(id: IdType): EntitySubject<T>;
getForkCount(id: IdType): number;
getEntitySubjectCount(): number;
}
export class EntityState {
getStore<T extends IdVersionInterface>(classType: ClassType<T>): EntitySubjectStore<T>;
getStoreByName<T extends IdVersionInterface>(name: string): EntitySubjectStore<T>;
onEntityPatch(body: rpcEntityPatch): void;
onEntityRemove(body: rpcEntityRemove): void;
}
export class RpcServerAction {
constructor(protected stats: RpcStats, protected cache: RpcCache, protected connection: RpcKernelBaseConnection, protected controllers: Map<string, {
controller: ClassType;
module?: InjectorModule;
}>, protected injector: InjectorContext, protected eventDispatcher: EventDispatcher, protected security: RpcKernelSecurity, protected sessionState: SessionState, protected logger: LoggerInterface, protected dispatcher?: ActionDispatcher);
/**
* Frees everything held for a stream context. Returns false when nothing was held,
* which also means the context already ended and no end frame must be sent again.
*/
closeContext(id: number): boolean;
async onClose();
/** A control frame of a stream. The frame is only valid during this call. */
handleControl(op: ControlOp, id: number, buffer: Uint8Array, offset: number, end: number): void;
/**
* Runs the action of a fast path frame. Everything needed from the frame is read synchronously.
*/
execute(buffer: Uint8Array, id: number, actionId: number, bodyOffset: number, end: number): void;
/**
* Calls an action with everything that observes or guards it. An error is what should be sent to the client.
*/
async invoke(cache: RpcCacheAction, args: any[], decodeError?: any): Promise<any>;
/** An action called over HTTP: the arguments are JSON, and so is what is returned. */
async invokeJson(controllerName: string, methodName: string, args: any[]): Promise<{
value: any;
type: Type;
}>;
/** What the HTTP client needs to know to call an action, without the handshake a connection has. */
jsonTypes(controllerName: string, methodName: string): ActionTypes;
}
export class RpcPeerExchange {
async isRegistered(id: string): Promise<boolean>;
async deregister(id: string | Uint8Array): Promise<void>;
register(id: string | Uint8Array, writer: TransportConnection): void;
/** Sends a whole frame on to where its route data says, nothing of it is read. */
redirect(frame: Uint8Array);
}
export abstract class RpcKernelBaseConnection implements RpcFastHost {
sessionState;
/**
* Statistics about the server->client communication.
*/
clientStats: RpcStats;
transportOptions: TransportOptions;
readonly onClose: Promise<void>;
closed: boolean;
/** The route data frames of this connection need, set when it answers a peer. */
routeData?: Uint8Array;
constructor(public stats: RpcStats, protected logger: Logger, public transportConnection: TransportConnection, protected connections: RpcKernelConnections, protected injector: InjectorContext, protected eventDispatcher: EventDispatcher);
/**
* Sends a frame. Valid only for transports with a binary connection.
*/
sendFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
get routeFlag(): RouteFlag;
/** Tells the client entities changed. */
sendEntityPatch(patch: rpcEntityPatch): void;
sendEntityRemove(remove: rpcEntityRemove): void;
clientAddress(): string | undefined;
/**
* Creates a regular timer using setTimeout() and automatically cancel it once the connection breaks or server stops.
*/
setTimeout(cb: () => void, timeout: number): any;
close(reason: string | Error = ): void;
feed(buffer: Uint8Array, bytes?: number): void;
/** A frame from an already split up stream. The buffer is only valid during this call. */
feedFrame(buffer: Uint8Array, start: number, end: number): void;
getSchemaMapping(): ParsedSchemaMapping | undefined;
getSchemaEpoch(): number;
isActionReady(): boolean;
getContexts(): SequentialContextDispatcher<FrameHandler>;
getChunkSize(): number;
sendActionFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
isObserved(): boolean;
emitEvent(event: any): void;
/** The other side may have registered controllers since it was last asked. */
refreshSchema(): Promise<unknown>;
connectForAction(): Promise<unknown>;
hasBinaryTransport(): boolean;
currentConnectionId(): number;
getRoute(): RouteFlag;
onRequest(basePath: string, request: RpcHttpRequest, response: RpcHttpResponse): void | Promise<void>;
controller<T>(nameOrDefinition: string | ControllerDefinition<T>, timeoutInSeconds = ): RemoteController<T>;
}
export class RpcKernelConnections {
connections: RpcKernelBaseConnection[];
stats: RpcTransportStats;
}
export class RpcCache {
actionsTypes: {
[id: string]: ActionTypes;
};
actions: {
[id: string]: RpcCacheAction;
};
}
export class RpcKernelConnection extends RpcKernelBaseConnection {
myPeerId?: string;
routeType: MessageFlag.RouteClient | MessageFlag.RouteServer;
constructor(stats: RpcStats, logger: Logger, transport: TransportConnection, connections: RpcKernelConnections, injector: InjectorContext, eventDispatcher: EventDispatcher, protected cache: RpcCache, protected controllers: Map<string, {
controller: ClassType;
module?: InjectorModule;
}>, protected security = new RpcKernelSecurity(), protected peerExchange: RpcPeerExchange, protected actionDispatcher?: ActionDispatcher);
close(): void;
get routeFlag(): RouteFlag;
async onRequest(basePath: string, request: RpcHttpRequest, response: RpcHttpResponse);
}
export class RpcKernel {
readonly controllers;
stats;
injector: InjectorContext;
constructor(injector?: InjectorContext | NormalizedProvider[], protected logger: Logger = new Logger());
/**
* Register a new event listener for given token.
*
* order: The lower the order, the sooner the listener is called. Default is 0.
*/
listen<T extends EventToken<any>>(eventToken: T, callback: EventListenerCallback<T>, order: number = ): EventDispatcherUnsubscribe;
getEventDispatcher(): EventDispatcher;
onConnection(callback: OnConnectionCallback);
/**
* This registers the controller and when no custom InjectorContext was given adds it as provider to the injector.
*
* Note: Controllers can not be added to the injector when the injector was already built.
*/
registerController(controller: ClassType, id?: string | ControllerDefinition<any>, module?: InjectorModule);
createConnection(transport: TransportConnection, injector?: InjectorContext): RpcKernelBaseConnection;
}
export class Session {
constructor(public readonly username: string, public readonly token: any);
isAnonymous(): boolean;
}
export class RpcKernelSecurity {
async hasControllerAccess(session: Session, controllerAccess: RpcControllerAccess, connection: RpcKernelBaseConnection): Promise<boolean>;
async isAllowedToRegisterAsPeer(session: Session, peerId: string): Promise<boolean>;
async isAllowedToSendToPeer(session: Session, peerId: string): Promise<boolean>;
async authenticate(token: any, connection: RpcKernelBaseConnection): Promise<Session>;
transformError(err: Error);
}
export class SessionState {
setSession(session: Session);
getSession(): Session;
}
export class ActionDispatcher {
entries: ActionEntry[];
/** Set by the kernel: rebuilds when a controller was registered since the last build. */
rebuild?: () => void;
schemaMessage: Uint8Array;
schemaHash: number;
build(controllers: Iterable<[
string,
{
controller: ClassType;
module?: InjectorModule;
}
]>, loadTypes: (controller: string, method: string) => ActionTypes): void;
prepare(entry: ActionEntry, cache: RpcCacheAction, strict: boolean): void;
}
export class PreSerialized {
/** BSON element for key "v": type byte, key, value. */
constructor(public readonly element: Uint8Array);
}
export class CollectionQueryModel<T> implements CollectionQueryModelInterface<T> {
filter?: FilterQuery<T>;
skip?: number;
itemsPerPage: number;
limit?: number;
parameters: {
[name: string]: any;
};
sort?: Sort<T>;
readonly change;
set(model: CollectionQueryModelInterface<any>);
changed(): void;
hasSort(): boolean;
/**
* Whether limit/skip is activated.
*/
hasPaging(): boolean;
}
export class CollectionState {
/**
* Total count in the database for the current query, regardless of paging (skip/limit) count.
*
* Use count() to get the items count on the current page (which is equal to all().length)
*/
total: number;
}
export class Collection<T extends IdInterface> extends ReplaySubject<T[]> {
readonly event: Subject<CollectionEvent<T>>;
readonly removed;
readonly added;
state: CollectionState;
readonly deepChange;
model: CollectionQueryModel<T>;
readonly entitySubjects;
constructor(public readonly classType: ClassType<T>);
getTotal();
getItemsPerPage();
getPages();
getSort();
getParameter(name: string);
setParameter(name: string, value: any): this;
orderByField(name: keyof T & string, order: SORT_ORDER = );
setPage(page: number);
getPage();
apply();
getEntitySubject(idOrItem: string | number | T): EntitySubject<T> | undefined;
has(id: string | number);
get(id: string | number): T | undefined;
setState(state: CollectionState);
setSort(ids: (string | number)[]);
/**
* Resolves when next change happened.
*/
get nextStateChange(): Promise<void>;
unsubscribe();
addTeardown(teardown: TeardownLogic);
index(item: T): number;
/**
* Returns the page zero-based of the current item.
*/
getPageOf(item: T, itemsPerPage = ): number;
reset();
all(): T[];
/**
* Count of current page if paging is used, otherwise total count.
*/
count();
ids(): (string | number)[];
empty();
/**
* All items from id -> value map.
*/
map();
loaded();
set(items: T[], withEvent = true);
removeMany(ids: (string | number)[], withEvent = true);
update(items: T | T[], withEvent = true);
add(items: T | T[], withEvent = true);
remove(ids: (string | number) | (string | number)[], withEvent = true);
}
export class RpcController {
name: string;
classType?: ClassType;
definition?: ControllerDefinition<any>;
strictSerialization: boolean;
logValidationErrors: boolean;
actions;
getPath(): string;
}
export class RpcAction {
name: string;
classType: ClassType;
category: string;
description: string;
strictSerialization?: boolean;
logValidationErrors?: boolean;
groups: string[];
data: {
[name: string]: any;
};
}
export class RpcTransportStats {
readonly incomingBytes: number;
readonly outgoingBytes: number;
/**
* Amount of incoming and outgoing messages.
*/
readonly incoming: number;
readonly outgoing: number;
increase(name: NumericKeys<RpcTransportStats>, count: number);
/** One incoming message. The same as increase(), without looking up a property by name per message. */
addIncoming(): void;
/** One outgoing message of the given size. */
addOutgoing(bytes: number): void;
}
export class ActionStats {
readonly observables: number;
readonly subjects: number;
readonly behaviorSubjects: number;
readonly progressTrackers: number;
readonly subscriptions: number;
increase(name: NumericKeys<ActionStats>, count: number);
}
export class ForwardedActionStats extends ActionStats {
constructor(protected forward: ActionStats);
increase(name: NumericKeys<ActionStats>, count: number);
}
export class RpcStats extends RpcTransportStats {
readonly connections: number;
readonly totalConnections: number;
/**
* How many actions have been executed.
*/
readonly actions: number;
readonly active: ActionStats;
readonly total: ActionStats;
increase(name: NumericKeys<RpcStats>, count: number);
/** One executed action. */
addAction(): void;
}
export class ForwardedRpcStats extends RpcStats {
readonly active;
readonly total;
constructor(protected forward: RpcStats);
increase(name: NumericKeys<RpcStats>, count: number);
addIncoming(): void;
addOutgoing(bytes: number): void;
addAction(): void;
}
export class StreamBehaviorSubject<T> extends BehaviorSubject<T> {
readonly appendSubject;
constructor(item: T, teardown?: TeardownLogic);
isUnsubscribed(): boolean;
get nextStateChange();
addTearDown(teardown: TeardownLogic);
/**
* This method differs to BehaviorSubject in the way that this does not throw an error
* when the subject is closed/unsubscribed.
*/
getValue(): T;
next(value: T): void;
activateNextOnAppend();
toUTF8();
append(value: T): void;
unsubscribe(): void;
}
export class EntitySubject<T extends IdInterface> extends StreamBehaviorSubject<T> {
/**
* Patches are in class format.
*/
readonly patches;
readonly delete;
[IsEntitySubject];
deleted: boolean;
get id(): string | number;
get onDeletion(): Observable<void>;
next(value: T | undefined): void;
}
export class ControllerDefinition<T> {
constructor(public path: string, public entities: ClassType[] = []);
}
@entity.name()
export class JSONError {
constructor(public readonly json: any);
}
export class RpcBinaryMessageReader extends FrameReader {
/**
* Receives every frame except chunks. Only valid during the call.
*/
onRawFrame?: (buffer: Uint8Array, start: number, end: number) => void;
/** A transfer of the context was aborted. */
onAbort?: (id: number, error: Error) => void;
constructor(protected readonly onChunk?: (id: number, abort: boolean, route: RouteFlag) => void);
cleanUp();
onChunkAck(id: number, callback: (active: boolean) => void, route: RouteFlag = MessageFlag.RouteClient);
removeChunkAck(id: number, aborted = false, route: RouteFlag = MessageFlag.RouteClient);
registerProgress(id: number, progress: SingleProgress);
feed(buffer: Uint8Array, length: number = buffer.byteLength);
}
export class SingleProgress extends Subject<SingleProgress> {
done;
total;
current;
stats;
abortController: AbortController;
finished;
constructor();
/**
* Aborts the current progress (either upload or download).
*/
abort();
get aborted();
/**
* Acts like a BehaviorSubject.
*/
_subscribe(subscriber: Subscriber<SingleProgress>): Subscription;
setStart(total: number);
setBatch(size: number);
get progress(): number;
set(total: number, current: number);
}
export class Progress extends BehaviorSubject<number> {
readonly upload;
readonly download;
/**
* Aborts both upload and download progress.
*/
abort();
constructor();
}
export class ClientProgress {
static nextProgress?: Progress;
/**
* Returns the current stack and sets a new one.
*/
static getNext(): Progress | undefined;
/**
* Sets up a new Progress object for the next API request to be made.
* Only the very next API call will be tracked.
*
* @example
* ```typescript
*
* const progress = ClientProgress.track();
* await api.myMethod();
*
* ```
*/
static track(): Progress;
}
export class TransportOptions {
/**
* Stores big buffers to the file system and stream it from there.
* In bytes.
* note: not implemented yet
*/
cacheOnFileSystemWhenSizeIsAtLeast: number;
/**
* When back-pressure is bigger than this value, we wait with sending new data.
* In bytes.
* note: not implemented yet
*/
stepBackWhenBackPressureBiggerThan: number;
/**
* Chunk size.
* In bytes.
*/
chunkSize: number;
/**
* How long a client waits for the reply to its handshake before it gives up.
* In milliseconds, 0 disables it.
*/
handshakeTimeout: number;
}
export class TransportBinaryMessageChunkWriter {
constructor(protected reader: RpcBinaryMessageReader, protected options: TransportOptions);
/**
* A small message has to wait as well while a large one of its context is sent in chunks, or it would overtake it.
*/
needsWriteFull(size: number): boolean;
/**
* Writes a message buffer to the connection and chunks if necessary.
*/
write(writer: RpcBinaryWriter, message: Uint8Array, progress?: SingleProgress): void;
async writeFull(writer: RpcBinaryWriter, buffer: Uint8Array, progress?: SingleProgress): Promise<void>;
}
Events
EventTokenSync<DataEvent<RpcConnectionEvent>>
EventTokenSync<DataEvent<RpcConnectionCloseEvent>>
EventTokenSync<DataEvent<RpcActionEvent>>
EventToken<DataEvent<RpcAuthEvent>>
EventToken<DataEvent<RpcControllerAccessEvent>>
Errors
export class RpcError extends CustomError {
}
export class AuthenticationError extends CustomError {
}
export class RpcProtocolVersionError extends RpcError {
}
Const
string[]
65535Type
TypeTuple
{ encode: BSONSerializer; decode: BSONDeserializer<SchemaMapping>; }
312112522261440{ exposeStack: boolean; exposeCause: boolean; }
Functions
<T>(actionClient: RpcActionClient, controller: RpcControllerState, options: { timeout?: number; dontWaitForConnection?: true; typeReuseDisabled?: boolean; }): T
(baseUrl: string, portMapping?: { [name: number]: number; }): string
(baseUrl?: string, portMapping?: { [name: number]: number; }): { provide: typeof RpcWebSocketClient; useFactory: () => RpcWebSocketClient; }
(baseUrl?: string, headers?: { [name: string]: string; }, http?: RpcHttpInterface): { provide: typeof RpcClient; useFactory: () => RpcClient; }
(kernel: RpcKernel, channel: RpcChannel, injector?: InjectorContext): RpcChannelServer
// in the worker
import { parentPort } from 'node:worker_threads';
serveRpcChannel(kernel, createMessagePortChannel(parentPort!));
rpc of the kernel's injector, unless an injector is given.(port: RpcMessagePortLike, name?: string): RpcChannel
self in a Web Worker,
of the browser or of node's worker_threads. Messages are transferred, not copied.(process: RpcProcessLike, name?: string): RpcChannel
process in the child. The child has to be started with serialization: 'advanced',
so that bytes are sent as bytes:const child = fork('./server.js', { serialization: 'advanced' });
const client = new RpcClient(new RpcChannelClientAdapter(createProcessChannel(child)));
(stream: RpcStreamLike, name?: string): RpcChannel
// parent
const child = spawn('node', ['server.js'], { stdio: ['inherit', 'inherit', 'inherit', 'pipe'] });
const client = new RpcClient(new RpcChannelClientAdapter(createStreamChannel(child.stdio[3] as Socket)));
// child
serveRpcChannel(kernel, createStreamChannel(new Socket({ fd: 3, readable: true, writable: true })));
(capacity?: number): SharedArrayBuffer
workerData or with postMessage().(memory: SharedArrayBuffer, side: "client" | "server", options?: SharedMemoryChannelOptions): SharedMemoryChannel
(cache: RpcCache, controllers: Map<string, { controller: ClassType; module?: InjectorModule; }>, controller: string, methodName: string): ActionTypes
(types: ActionTypes): Type
(parameters: TypeTuple): AutoBufferSerializer
(parameters: TypeTuple): ParameterDeserializer
(type: Type): AutoBufferSerializer
(type: Type): ReturnDeserializer
(type: Type): BodyCodec
(buffer: Uint8Array): number
(mapping: SchemaMapping): ParsedSchemaMapping
<T>(target: ClassType<T>): Map<string, RpcAction>
ClassDecoratorResult<typeof RpcClass>
PropertyDecoratorResult<typeof RpcProperty>
FluidDecorator<RpcClass, ClassDecoratorFn> & ClassDecoratorFn & { _fetch: (classType: AbstractClassType, property?: string | undefined, parameterIndexOrDescriptor?: any) => RpcController | undefined; } & FluidDecorator<...> & PropertyDecoratorFn & { ...; }
(v: any): v is EntitySubject<any>
<T>(path: string, entities?: ClassType[]): ControllerDefinition<T>
(flags: number, route: RouteFlag): boolean
(flags: number, context: ContextFlag): boolean
(flags: number): boolean
(flags: number, type: TypeFlag): boolean
(buffer: Uint8Array, route: RouteFlag, start?: number): void
(buffer: Uint8Array, context: ContextFlag, start?: number): void
(buffer: Uint8Array, type: TypeFlag, start?: number): void
(buffer: Uint8Array, offset: number, value: number): void
(buffer: Uint8Array, offset: number): number
(buffer: Uint8Array, offset?: number): number
(buffer: Uint8Array, start?: number): number
(buffer: Uint8Array, start?: number): number
(buffer: Uint8Array, start?: number): number
(buffer: Uint8Array, start?: number): number
(buffer: Uint8Array, start?: number): number
(buffer: Uint8Array, start?: number): number
(buffer: Uint8Array, start?: number): string
(buffer: Uint8Array, start: number, end: number): Uint8Array
(buffer: Uint8Array): number
(buffer: Uint8Array, start?: number): number
(): Uint8Array
(size: number): Uint8Array
(): void
(): void
(buffer: Uint8Array, offset: number): number
(buffer: Uint8Array, offset: number): number
(buffer: Uint8Array, offset: number): number
(buffer: Uint8Array, offset: number): number
(id: number, action: number, serialize: ValueSerializer, args: any[], context?: ContextFlag, route?: RouteFlag, routeData?: Uint8Array): number
(id: number, route: RouteFlag, serialize: ValueSerializer, value: any, routeData?: Uint8Array): number
(id: number, route: RouteFlag, subscription: number, serialize: ValueSerializer, value: any, routeData?: Uint8Array): number
(id: number, route: RouteFlag, kind: ChannelSubType, routeData?: Uint8Array): number
(channel: number, serialize: ValueSerializer, values: any[]): number
(id: number, route: RouteFlag, op: ControlOp, serialize?: ValueSerializer, value?: any, routeData?: Uint8Array, context?: ContextFlag): number
(id: number, route: RouteFlag, op: ControlOp, value: number, routeData?: Uint8Array): number
(buffer: Uint8Array, offset: number, end: number): EncodedError
(error: EncodedErrorTuple): EncodedError
(id: number, route: RouteFlag, error: EncodedError, routeData?: Uint8Array): number
(id: number, route: RouteFlag, subscription: number, error: EncodedError, routeData?: Uint8Array): number
(id: number, route: RouteFlag, routeData?: Uint8Array): number
(id: number, route: RouteFlag, value: PreSerialized, tuple?: boolean, routeData?: Uint8Array): number
(id: number, route: RouteFlag, subscription: number, value: PreSerialized, tuple?: boolean, routeData?: Uint8Array): number
(schemaHash: number, route?: RouteFlag, id?: number, routeData?: Uint8Array): number
(version: number, schemaHash: number, schema?: Uint8Array, route?: RouteFlag, id?: number, routeData?: Uint8Array): number
(buffer: Uint8Array, start?: number): number
(id: number, route: RouteFlag, seq: number, total: number, bytes: Uint8Array, start: number, end: number): number
(id: number, route: RouteFlag, op: ChunkOp): number
<T>(value: T, type?: ReceiveType<T>): PreSerialized
value once, to be sent as the result of an action or as a value of an observable
without serializing it again, for example the same value to many connections.(error: Error | string, depth?: number): EncodedError
(error: EncodedError): Error
(transport: TransportConnection, chunkWriter: TransportBinaryMessageChunkWriter, options: TransportOptions, stats: RpcTransportStats): RpcFrameSender | undefined
<T>(producer: (subject: Subject<T>) => void | Promise<void>, teardown?: () => void): Subject<T>
class Controller {
<T>(producer: InstanceProducer<Subject<T>>): Subject<T>
const client = new RpcClient();
const controller = client.controller<MyController>('controller');
// normally you would do this:
const subject = await controller.subscribeChats('asd');
// but with instantSubject you can do this, allowing you to get
// a Subject in a synchronous way.
const subject = instantSubject(controller.subscribeChats('asd'));
Types
interface RpcFastHost {
getSchemaMapping(): ParsedSchemaMapping | undefined;
getSchemaEpoch(): number;
isActionReady(dontWaitForConnection?: boolean): boolean;
getContexts(): SequentialContextDispatcher<FrameCallback>;
getChunkSize(): number;
sendActionFrame(buffer: Uint8Array, size: number, progress?: SingleProgress): void;
/** Whether somebody listens to client.events, which is built for that only. */
isObserved(): boolean;
emitEvent(event: any): void;
connectForAction(): Promise<unknown>;
hasBinaryTransport(): boolean;
currentConnectionId(): number;
/** The route of what this side sends: client to server, or server to client. */
getRoute(): RouteFlag;
/** Controllers can be registered while connected, this asks for the actions again. */
refreshSchema?(): Promise<unknown>;
registerDownloadProgress?(id: number, progress: SingleProgress): void;
/** <source:16><peerId>\0 for a frame to the given peer. */
getPeerRoute?(peerId: string): Uint8Array;
getHttpTransport?(): RpcHttpTransport | undefined;
getToken?(): any;
}
interface RpcHttpActionTypes {
mode: ActionMode;
type: any;
parameters: any;
}
interface RpcHttpTransport {
requestTypes(controller: string, method: string, token: any): Promise<RpcHttpActionTypes>;
requestCall(controller: string, method: string, args: any[], token: any): Promise<any>;
}
type RemoteController<T> = {
[P in keyof T]: T[P] extends (...args: any[]) => any ? PromisifyFn<T[P]> : never;
};
interface ClientTransportAdapter {
connect(connection: TransportClientConnection): Promise<void> | void;
/**
* Whether ClientId call is needed to get a client id.
* This is disabled for http adapter.
*/
supportsPeers?(): boolean;
/**
* Whether Authentication call is needed to authenticate the client.
* This is disabled for http adapter (Authorization header is used).
*/
supportsAuthentication?(): boolean;
/** When set, actions are called through this instead of frames on a connection. */
httpTransport?(): RpcHttpTransport;
}
type RpcPushHandler = (buffer: Uint8Array, offset: number, end: number) => void;
type RpcEventMessage = { id: number; date: Date; type: string; body: any };
type RpcClientEventIncomingMessage = { event: 'incoming' } & RpcEventMessage;
type RpcClientEventOutgoingMessage = { event: 'outgoing' } & RpcEventMessage;
type RpcClientEvent = RpcClientEventIncomingMessage | RpcClientEventOutgoingMessage;
interface RpcHttpResponseInterface {
status: number;
headers: { [name: string]: string };
body?: any;
}
interface RpcHttpInterface {
fetch(
url: string,
options: {
headers: { [name: string]: string };
method: string;
body?: string;
},
): Promise<RpcHttpResponseInterface>;
}
interface RpcChannel {
/**
* Sends bytes. The buffer belongs to the channel afterwards, it may transfer it to the other side.
*/
send(data: Uint8Array): void;
/**
* Ends the current connection. The other side gets onEnd. A message channel can carry the next connection afterwards.
*/
end(): void;
/**
* Receives bytes until the returned function is called. onEnd is called when the other side ended the
* connection or the channel closed. The buffer is only valid during the call.
*/
listen(onData: (data: Uint8Array, bytes?: number) => void, onEnd: (reason: string) => void): () => void;
/**
* Channels of a byte stream write the frames directly to this socket instead of send(), which
* collects the frames of one tick into one message.
*/
binarySocket?: BinarySocket;
/** Shown as address of the client. */
readonly name?: string;
}
interface RpcChannelServer {
/** The connection that currently runs over the channel. */
readonly connection?: RpcKernelBaseConnection;
/** Stops listening and closes the current connection. */
close(): void;
}
interface RpcMessagePortLike {
postMessage(message: any, transfer?: any[]): void;
on?(event: string, listener: (...args: any[]) => void): unknown;
off?(event: string, listener: (...args: any[]) => void): unknown;
addEventListener?(event: string, listener: (event: any) => void): unknown;
removeEventListener?(event: string, listener: (event: any) => void): unknown;
start?(): void;
}
self) the channel uses.
In node these are MessagePort, Worker and parentPort of worker_threads.interface RpcProcessLike {
send?(message: any, ...rest: any[]): boolean;
readonly connected?: boolean;
on(event: string, listener: (...args: any[]) => void): unknown;
off(event: string, listener: (...args: any[]) => void): unknown;
}
process in the child the channel uses.interface RpcStreamLike {
write(data: Uint8Array): unknown;
end(): unknown;
readonly writableLength: number;
readonly destroyed: boolean;
on(event: string, listener: (...args: any[]) => void): unknown;
off(event: string, listener: (...args: any[]) => void): unknown;
}
interface SharedMemoryChannelOptions {
/**
* How long the receiving side polls for new data, in each turn of the event loop, before it goes to sleep, in
* microseconds. An answer that arrives meanwhile is read right away instead of after a wake-up of the thread,
* which takes 20-30µs. The core is busy while polling. 0 disables it. Default 100.
*/
spin?: number;
}
type ActionTypes = {
strictSerialization: boolean;
parametersValidate: Guard<any>;
parameters: TypeTuple;
mode: ActionMode;
type: Type; //the type T of Collection<T>, EntitySubject<T>, Observable<T>, or return type of the function if mode=arbitrary
resultSchema: TypeObjectLiteral; //with v as property
observableNextSchema?: TypeObjectLiteral; //with v as property
collectionItems?: Type; //T[]
collectionQueryModel?: Type;
noTypeWarned: boolean;
/** Writes one observable value on the fast path. */
nextValueEncoder?: AutoBufferSerializer;
};
interface RpcServerActionObservableSubject {
subject: Subject<any>;
trackingType: NumericKeys<ActionStats>;
completed: boolean;
completedByClient: boolean;
subscription: Subscription;
subscribe: () => Subscription;
}
interface RpcCacheAction {
controller: RpcControllerAccess;
fn: Function;
types: ActionTypes;
action: RpcAction;
resolver: Resolver<any>;
label: string; //controller.action
}
type OnConnectionCallback = (
connection: RpcKernelConnection,
injector: InjectorContext,
logger: LoggerInterface,
) => void;
interface RpcControllerAccess {
controllerName: string;
controllerClassType: ClassType;
actionName: string;
actionGroups: string[];
actionData: { [name: string]: any };
}
interface ActionEntry {
id: number;
controllerName: string;
methodName: string;
classType: ClassType;
module?: InjectorModule;
mode: ActionMode;
parameters: TypeTuple;
type: Type;
cache?: RpcCacheAction;
/** The returned array is reused by the next call. */
decode?: ParameterDeserializer;
/** Indexes of the parameters that are views on the frame, see TransientBytes. */
transient?: number[];
/** The decoder already guarantees the parameter types, there is nothing a validator could add. */
validate: boolean;
encodeResult?: AutoBufferSerializer;
warnResultType: boolean;
}
type TransientBytes = Uint8Array & TypeAnnotation<'rpcTransientBytes'>;
type ParameterDeserializer = (message: Uint8Array, offset: number, frameEnd: number) => any[];
type ReturnDeserializer = (message: Uint8Array, offset: number, frameEnd: number) => any;
type BodySerializer = AutoBufferSerializer;
interface BodyCodec {
serialize: BodySerializer;
deserialize: ReturnDeserializer;
}
type SchemaMapping = {
[controllerName: string]: [actionName: string, action: number, mode: ActionMode, parameters: any, type: any][];
};
type ParsedSchemaEntry = { action: number; mode: ActionMode; parameters: any; type: any };
type ParsedSchemaMapping = { [controllerName: string]: { [actionName: string]: ParsedSchemaEntry } };
type FilterParameters = { [name: string]: any | undefined };
type QuerySelector<T> = {
// Comparison
$eq?: T;
$gt?: T;
$gte?: T;
$in?: T[];
$lt?: T;
$lte?: T;
$ne?: T;
$nin?: T[];
// Logical
$not?: T extends string ? (QuerySelector<T> | RegExp) : QuerySelector<T>;
$regex?: T extends string ? (RegExp | string) : never;
//special deepkit/type type
$parameter?: string;
};
type RootQuerySelector<T> = {
$and?: Array<FilterQuery<T>>;
$nor?: Array<FilterQuery<T>>;
$or?: Array<FilterQuery<T>>;
// we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
// this will mark all unrecognized properties as any (including nested queries)
[key: string]: any;
};
type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>;
type FilterQuery<T> = {
[P in keyof T & string]?: Condition<T[P]>;
} &
RootQuerySelector<T>;
type SORT_ORDER = 'asc' | 'desc' | any;
type Sort<T, ORDER extends SORT_ORDER = SORT_ORDER> = { [P in keyof T & string]?: ORDER };
interface CollectionEventAdd<T> {
type: 'add';
items: T[];
}
interface CollectionEventState {
type: 'state';
state: CollectionState;
}
interface CollectionEventRemove {
type: 'remove';
ids: (string | number)[];
}
interface CollectionEventSet {
type: 'set';
items: any[];
}
interface CollectionEventUpdate {
type: 'update';
items: any[];
}
interface CollectionSetSort {
type: 'sort';
ids: (string | number)[];
}
type CollectionEvent<T> = CollectionEventAdd<T> | CollectionEventRemove | CollectionEventSet | CollectionEventState | CollectionEventUpdate | CollectionSetSort;
type CollectionSortDirection = 'asc' | 'desc';
interface CollectionSort {
field: string;
direction: CollectionSortDirection;
}
interface CollectionEntitySubjectFetcher {
fetch<T extends IdInterface>(classType: ClassType<T>, id: string | number): EntitySubject<T>;
}
interface CollectionQueryModelInterface<T> {
filter?: FilterQuery<T>;
skip?: number;
itemsPerPage: number;
limit?: number;
parameters: { [name: string]: any };
sort?: Sort<T>;
}
type IdType = string | number;
interface IdInterface {
id: IdType;
}
interface IdVersionInterface extends IdInterface {
version: number;
}
type NumericKeys<T> = {
[K in keyof T]: T[K] extends number ? K : never;
}[keyof T];
type ActionMode = 'arbitrary' | 'collection' | 'entitySubject' | 'observable';
interface rpcCollectionRemove {
ids: (string | number)[];
}
interface rpcCollectionSort {
ids: (string | number)[];
}
interface rpcEntityRemove {
entityName: string;
ids: (string | number)[];
}
interface EntityPatch {
$set?: { [path: string]: any };
$unset?: { [path: string]: number };
$inc?: { [path: string]: number };
}
interface rpcEntityPatch {
entityName: string;
id: string | number;
version: number;
patch: {
$set?: Record<string, any>;
$unset?: Record<string, number>;
$inc?: Record<string, number>;
};
}
type RouteFlag =
| MessageFlag.RouteClient
| MessageFlag.RouteServer
| MessageFlag.RouteSourceDest
| MessageFlag.RoutePeer;
type ContextFlag =
| MessageFlag.ContextNone
| MessageFlag.ContextNew
| MessageFlag.ContextExisting
| MessageFlag.ContextEnd;
type TypeFlag =
| MessageFlag.TypeAction
| MessageFlag.TypeAck
| MessageFlag.TypeChunk
| MessageFlag.TypeError
| MessageFlag.TypeSchema
| MessageFlag.TypeResult
| MessageFlag.TypeControl
| MessageFlag.TypeChannel;
type EncodedErrorTuple = [
classType: string,
properties: { [name: string]: any },
stack: string,
message: string,
/** The tuple of error.cause, only when rpcErrorSettings.exposeCause is set. Older peers ignore it. */
cause?: any,
];
interface EncodedError {
classType: string;
message: string;
stack: string;
properties?: { [name: string]: any };
cause?: EncodedError;
}
interface TransportConnection {
/**
* Sends a frame. Large frames are chunked before they get here.
*/
writeBinary?(message: Uint8Array): void;
/**
* A socket to write to instead of writeBinary. Its bytes are copied by the kernel during write(), so
* messages can be sent from one reused buffer without copying them first.
*/
binarySocket?: BinarySocket;
bufferedAmount?(): number;
clientAddress?(): string;
close(): void;
}
interface TransportClientConnection {
token?: any;
onConnected(established: TransportConnection): void;
onClose(reason: string): void;
onError(error: Error): void;
readBinary(message: Uint8Array, bytes?: number): void;
}
type RpcBinaryWriter = (buffer: Uint8Array) => void;
interface BinarySocket {
write(buffer: Uint8Array): unknown;
/** Writes a range of the buffer without a view on it, where the socket supports that. */
writeRange?(buffer: Uint8Array, start: number, end: number): unknown;
/** Bytes the socket could not hand to the kernel yet, and whose memory it still needs. */
readonly writableLength: number;
}
type RpcFrameSender = (buffer: Uint8Array, size: number, progress?: SingleProgress) => void;
type InstanceProducer<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
type WithFail<T> = Omit<T, 'phase'> & { phase: 'fail'; error: Error };
interface RpcConnectionEvent {
context: {
connection: RpcKernelBaseConnection;
injector: InjectorContext;
};
}
interface RpcConnectionCloseEvent extends RpcConnectionEvent {
/**
* There could be multiple reasons why a connection is closed. This could be a normal
* close, an error, or a timeout.
* If the connection was closed because of an error, this property contains the error object.
*/
reason: string | Error;
}
interface RpcActionTimings {
/**
* The start of the action (performance.now())
*/
start: number;
/**
* The end of the action (performance.now())
*/
end: number;
/**
* Time it took to check the controller access (since start)
*/
types?: number;
/**
* Time it took to parse the body (since start)
*/
parseBody?: number;
/**
* Time it took to validate the parameters (since start)
*/
validate?: number;
/**
* Time it took to check the controller access (since start)
*/
controllerAccess?: number;
}
interface RpcActionEventBase extends RpcConnectionEvent {
phase: 'start' | 'success';
controller: RpcControllerAccess;
timing: RpcActionTimings;
}
type RpcActionEvent = RpcActionEventBase | WithFail<RpcActionEventBase>;
interface RpcAuthEventStart extends RpcConnectionEvent {
token: any;
phase: 'start';
/**
* Set this to the session object if the authentication was successful.
* If set this will bypass RpcKernelSecurity and directly use this session.
*/
session?: Session;
}
interface RpcAuthEventSuccess extends RpcConnectionEvent {
token: any;
phase: 'success';
session: Session;
}
type RpcAuthEvent = RpcAuthEventStart | RpcAuthEventSuccess | WithFail<RpcAuthEventStart>;
interface RpcControllerAccessEventStart extends RpcConnectionEvent {
phase: 'start';
session: Session;
controller: RpcControllerAccess;
/**
* Set this to true if you want to grant access to the controller.
* If set this will bypass RpcKernelSecurity and directly grant access.
*/
granted?: boolean;
}
interface RpcControllerAccessEventBase extends RpcConnectionEvent {
phase: 'success' | 'denied';
session: Session;
controller: RpcControllerAccess;
}
type RpcControllerAccessEvent = RpcControllerAccessEventStart | RpcControllerAccessEventBase | WithFail<RpcControllerAccessEventBase>;