Repository navigation
Expand file tree
/
Copy pathindex.d.ts
More file actions
832 lines (671 loc) · 20.3 KB
/
Copy pathindex.d.ts
File metadata and controls
832 lines (671 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
// Type definitions for ZeroNode
// Project: https://github.com/sfast/zeronode
// Definitions by: ZeroNode Team
/// <reference types="node" />
import { EventEmitter } from 'events';
// ============================================================================
// Core Types
// ============================================================================
/**
* Node configuration options
*/
export interface NodeConfig {
/** Global request timeout in milliseconds (default: 10000) */
PROTOCOL_REQUEST_TIMEOUT?: number;
/** Buffer allocation strategy: 'EXACT' or 'POWER_OF_2' */
PROTOCOL_BUFFER_STRATEGY?: 'EXACT' | 'POWER_OF_2';
/** Client ping interval in milliseconds (default: 10000) */
CLIENT_PING_INTERVAL?: number;
/** Server health check interval in milliseconds (default: 30000) */
CLIENT_HEALTH_CHECK_INTERVAL?: number;
/** Client ghost timeout in milliseconds (default: 60000) */
CLIENT_GHOST_TIMEOUT?: number;
/** Enable debug logging (default: false) */
DEBUG?: boolean;
/** Custom logger instance */
logger?: any;
/** ZeroMQ reconnection interval in milliseconds */
reconnectInterval?: number;
/** ZeroMQ maximum reconnection interval in milliseconds */
reconnectMaxInterval?: number;
/** ZeroMQ heartbeat interval in milliseconds */
heartbeatInterval?: number;
/** ZeroMQ heartbeat timeout in milliseconds */
heartbeatTimeout?: number;
/** ZeroMQ heartbeat TTL in milliseconds */
heartbeatTtl?: number;
}
/**
* Node constructor options
*/
export interface NodeOptions {
/** Unique node identifier (auto-generated if not provided) */
id?: string;
/** Initial bind address (optional, can bind later) */
bind?: string;
/** Node metadata for routing and service discovery */
options?: Record<string, any>;
/** Node configuration */
config?: NodeConfig;
}
/**
* Request options
*/
export interface RequestOptions {
/** Target node ID */
to: string;
/** Event name */
event: string;
/** Request payload */
data?: any;
/** Request timeout in milliseconds (overrides global timeout) */
timeout?: number;
}
/**
* Tick (fire-and-forget) options
*/
export interface TickOptions {
/** Target node ID */
to: string;
/** Event name */
event: string;
/** Message payload */
data?: any;
}
/**
* Request with filter options
*/
export interface RequestAnyOptions {
/** Event name */
event: string;
/** Request payload */
data?: any;
/** Request timeout in milliseconds */
timeout?: number;
/** Filter object or predicate for node selection */
filter?: Record<string, any> | { predicate: (options: Record<string, any>) => boolean };
/** Search downstream nodes (default: true) */
down?: boolean;
/** Search upstream nodes (default: true) */
up?: boolean;
}
/**
* Tick with filter options
*/
export interface TickAnyOptions {
/** Event name */
event: string;
/** Message payload */
data?: any;
/** Filter object or predicate for node selection */
filter?: Record<string, any> | { predicate: (options: Record<string, any>) => boolean };
/** Search downstream nodes (default: true) */
down?: boolean;
/** Search upstream nodes (default: true) */
up?: boolean;
}
/**
* Connection options
*/
export interface ConnectOptions {
/** Server address to connect to (e.g., 'tcp://127.0.0.1:3000') */
address: string;
/** Connection timeout in milliseconds (optional) */
timeout?: number;
/** Reconnection timeout in milliseconds (optional) */
reconnectionTimeout?: number;
}
/**
* Envelope object passed to handlers
*/
export interface Envelope {
/** Envelope unique ID (BigInt) */
readonly id: bigint;
/** Envelope type: 1=TICK, 2=REQUEST, 3=RESPONSE, 4=ERROR */
readonly type: number;
/** Unix timestamp in seconds */
readonly timestamp: number;
/** Sender node ID (original requester) */
readonly owner: string;
/** Recipient node ID */
readonly recipient: string;
/** Event name */
readonly event: string;
/** Parsed message data (read-only) */
readonly data: any;
}
/**
* Reply function for request handlers
*/
export interface ReplyFunction {
/** Send successful response */
(data: any): void;
/** Send error response */
error(error: any): void;
}
/**
* Next function for middleware
*/
export interface NextFunction {
/** Continue to next handler */
(): void;
/** Pass error to error handlers */
(error: Error): void;
}
/**
* Request handler signatures
*/
export type RequestHandler =
| ((envelope: Envelope, reply: ReplyFunction) => void | Promise<void | any>)
| ((envelope: Envelope, reply: ReplyFunction, next: NextFunction) => void | Promise<void>)
| ((error: Error, envelope: Envelope, reply: ReplyFunction, next: NextFunction) => void | Promise<void>);
/**
* Tick handler signature
*/
export type TickHandler = (envelope: Envelope) => void | Promise<void>;
// ============================================================================
// Events
// ============================================================================
/**
* Node-level events
*/
export enum NodeEvent {
/** Peer joined the network */
PEER_JOINED = 'node:peer_joined',
/** Peer left the network */
PEER_LEFT = 'node:peer_left',
/** Node stopped */
STOPPED = 'node:stopped',
/** Node error */
ERROR = 'node:error'
}
/**
* Client-level events
*/
export enum ClientEvent {
/** Transport ready (can send/receive bytes) */
READY = 'client:ready',
/** Transport reported NOT_READY (lost connection, may recover) */
NOT_READY = 'client:not_ready',
/** Transport permanently closed */
CLOSED = 'client:closed',
/** Server joined (handshake complete, session established) */
SERVER_JOINED = 'client:server_joined',
/** Server left (shutdown, disconnect, timeout) */
SERVER_LEFT = 'client:server_left',
/** Client error */
ERROR = 'client:error'
}
/**
* Server-level events
*/
export enum ServerEvent {
/** Server ready to accept clients */
READY = 'server:ready',
/** Server not ready */
NOT_READY = 'server:not_ready',
/** Server closed */
CLOSED = 'server:closed',
/** Client joined */
CLIENT_JOINED = 'server:client_joined',
/** Client left */
CLIENT_LEFT = 'server:client_left'
}
/**
* Transport-level events
*/
export enum TransportEvent {
/** Transport ready */
READY = 'transport:ready',
/** Transport not ready */
NOT_READY = 'transport:not_ready',
/** Message received */
MESSAGE = 'transport:message',
/** Transport error */
ERROR = 'transport:error',
/** Transport closed */
CLOSED = 'transport:closed'
}
// ============================================================================
// Errors
// ============================================================================
/**
* Node error codes
*/
export enum NodeErrorCode {
/** Node not found */
NODE_NOT_FOUND = 'NODE_NOT_FOUND',
/** No nodes match filter */
NO_NODES_MATCH_FILTER = 'NO_NODES_MATCH_FILTER',
/** Invalid address */
INVALID_ADDRESS = 'INVALID_ADDRESS'
}
/**
* Node error class
*/
export class NodeError extends Error {
code: NodeErrorCode;
nodeId?: string;
cause?: Error;
context?: any;
constructor(options: {
code: NodeErrorCode;
message: string;
nodeId?: string;
cause?: Error;
context?: any;
});
toJSON(): any;
}
/**
* Assert that address is valid
* @throws {NodeError} If address is invalid
*/
export function assertValidAddress(address: string): void;
/**
* Protocol error codes
*/
export enum ProtocolErrorCode {
/** Protocol not ready */
NOT_READY = 'PROTOCOL_NOT_READY',
/** Request timeout */
REQUEST_TIMEOUT = 'REQUEST_TIMEOUT',
/** Invalid envelope */
INVALID_ENVELOPE = 'INVALID_ENVELOPE',
/** Invalid response */
INVALID_RESPONSE = 'INVALID_RESPONSE',
/** Invalid event */
INVALID_EVENT = 'INVALID_EVENT',
/** Handler error */
HANDLER_ERROR = 'HANDLER_ERROR'
}
/**
* Protocol error class
*/
export class ProtocolError extends Error {
code: ProtocolErrorCode;
protocolId?: string;
envelopeId?: bigint;
cause?: Error;
context?: any;
constructor(options: {
code: ProtocolErrorCode;
message: string;
protocolId?: string;
envelopeId?: bigint;
cause?: Error;
context?: any;
});
toJSON(): any;
}
/**
* Transport error codes
*/
export enum TransportErrorCode {
/** Already connected */
ALREADY_CONNECTED = 'TRANSPORT_ALREADY_CONNECTED',
/** Bind failed */
BIND_FAILED = 'TRANSPORT_BIND_FAILED',
/** Already bound */
ALREADY_BOUND = 'TRANSPORT_ALREADY_BOUND',
/** Unbind failed */
UNBIND_FAILED = 'TRANSPORT_UNBIND_FAILED',
/** Send failed */
SEND_FAILED = 'TRANSPORT_SEND_FAILED',
/** Receive failed */
RECEIVE_FAILED = 'TRANSPORT_RECEIVE_FAILED',
/** Invalid address */
INVALID_ADDRESS = 'TRANSPORT_INVALID_ADDRESS',
/** Close failed */
CLOSE_FAILED = 'TRANSPORT_CLOSE_FAILED'
}
/**
* Transport error class
*/
export class TransportError extends Error {
code: TransportErrorCode;
transportId?: string;
address?: string;
cause?: Error;
context?: any;
constructor(options: {
code: TransportErrorCode;
message: string;
transportId?: string;
address?: string;
cause?: Error;
context?: any;
});
toJSON(): any;
isCode(code: string): boolean;
isConnectionError(): boolean;
isBindError(): boolean;
isSendError(): boolean;
}
// ============================================================================
// Event Payloads
// ============================================================================
export interface PeerJoinedPayload {
peerId: string;
peerOptions: Record<string, any>;
direction: 'upstream' | 'downstream';
}
export interface PeerLeftPayload {
peerId: string;
direction: 'upstream' | 'downstream';
reason?: string;
}
export interface NodeErrorPayload {
source?: string;
stage?: string;
address?: string;
serverId?: string;
category?: string;
code?: string;
message?: string;
error?: Error;
}
export interface ClientReadyPayload {
serverId: string;
serverOptions: Record<string, any>;
}
export interface ClientDisconnectedPayload {
serverId: string;
address: string;
}
export interface ClientFailedPayload {
serverId: string;
address: string;
error?: Error;
}
export interface ClientStoppedPayload {
serverId: string;
address: string;
}
export interface ServerReadyPayload {
serverId: string;
}
export interface ServerClientJoinedPayload {
clientId: string;
clientOptions: Record<string, any>;
}
export interface ServerClientLeftPayload {
clientId: string;
}
export interface ServerClientTimeoutPayload {
clientId: string;
lastSeen: number;
timeSinceLastSeen: number;
final: boolean;
}
// ============================================================================
// Main Node Class
// ============================================================================
/**
* Node - Main class for ZeroNode network nodes
*
* A Node can simultaneously:
* - Bind as a server (accept downstream connections)
* - Connect as a client (to upstream servers)
* - Route messages between peers
* - Load balance across available nodes
*
* @example
* ```typescript
* import Node from 'zeronode';
*
* const node = new Node({
* id: 'my-service',
* options: { role: 'api', version: 1 }
* });
*
* await node.bind('tcp://0.0.0.0:3000');
*
* node.onRequest('user:get', async (envelope, reply) => {
* const user = await getUser(envelope.data.userId);
* return user;
* });
* ```
*/
export default class Node extends EventEmitter {
/**
* Create a new Node
*/
constructor(options?: NodeOptions);
// ============================================================================
// Node Identity & State
// ============================================================================
/**
* Get node ID
*/
getId(): string;
/**
* Get bind address (if server is bound)
*/
getAddress(): string | null;
/**
* Get node options (metadata)
*/
getOptions(): Record<string, any>;
/**
* Update node options (for dynamic routing)
* @returns Promise that resolves when options are updated
*/
setOptions(options: Record<string, any>): Promise<void>;
/**
* Get filtered nodes by options or predicate
* @param options - Filter criteria
* @returns Array of node IDs matching the filter
*/
getFilteredNodes(options?: {
options?: Record<string, any>;
predicate?: (nodeOptions: Record<string, any>) => boolean;
up?: boolean;
down?: boolean;
}): string[];
/**
* Get peer options by ID
* @param peerId - Peer ID
* @returns Peer options or null if peer not joined
*/
getPeerOptions(peerId: string): any | null;
/**
* Get server ID by connection address
* @param address - Server address (e.g., 'tcp://127.0.0.1:5000')
* @returns Server ID or null if not connected
*/
getServerIdByAddress(address: string): string | null;
// ============================================================================
// Connection Management
// ============================================================================
/**
* Bind as server (accept connections)
* @param address - Bind address (e.g., 'tcp://0.0.0.0:3000')
*/
bind(address: string): Promise<void>;
/**
* Unbind server (stop accepting connections)
*/
unbind(): Promise<void>;
/**
* Connect to remote server
* @param options - Connection options
*/
connect(options: ConnectOptions): Promise<void>;
/**
* Disconnect from remote server
* @param address - Server address to disconnect from
*/
disconnect(address: string): Promise<void>;
/**
* Close the node and all its connections.
*
* This permanently closes:
* - The server (if bound)
* - All client connections
* - All underlying transport sockets
*
* After closing, the node cannot be reused.
* Pending requests will be rejected.
* All handlers will be removed.
*/
close(): Promise<void>;
// ============================================================================
// Handler Registration
// ============================================================================
/**
* Register request handler
* @param pattern - Event name (string) or pattern (RegExp)
* @param handler - Request handler function
*/
onRequest(pattern: string | RegExp, handler: RequestHandler): void;
/**
* Unregister request handler
* @param pattern - Event name (string) or pattern (RegExp)
* @param handler - Handler function to remove (optional)
*/
offRequest(pattern: string | RegExp, handler?: RequestHandler): void;
/**
* Register tick handler
* @param pattern - Event name (string) or pattern (RegExp)
* @param handler - Tick handler function
*/
onTick(pattern: string | RegExp, handler: TickHandler): void;
/**
* Unregister tick handler
* @param pattern - Event name (string) or pattern (RegExp)
* @param handler - Handler function to remove (optional)
*/
offTick(pattern: string | RegExp, handler?: TickHandler): void;
// ============================================================================
// Messaging API
// ============================================================================
/**
* Send request to specific node
* @param options - Request options
* @returns Promise resolving to response data
*/
request(options: RequestOptions): Promise<any>;
/**
* Send tick (fire-and-forget) to specific node
* @param options - Tick options
*/
tick(options: TickOptions): void;
/**
* Send request to any matching node (load balanced)
* @param options - Request options with filter
* @returns Promise resolving to response data
*/
requestAny(options: RequestAnyOptions): Promise<any>;
/**
* Send request to any downstream node
* @param options - Request options with filter
* @returns Promise resolving to response data
*/
requestDownAny(options: Omit<RequestAnyOptions, 'down' | 'up'>): Promise<any>;
/**
* Send request to any upstream node
* @param options - Request options with filter
* @returns Promise resolving to response data
*/
requestUpAny(options: Omit<RequestAnyOptions, 'down' | 'up'>): Promise<any>;
/**
* Send tick to any matching node
* @param options - Tick options with filter
*/
tickAny(options: TickAnyOptions): void;
/**
* Send tick to any downstream node
* @param options - Tick options with filter
*/
tickDownAny(options: Omit<TickAnyOptions, 'down' | 'up'>): void;
/**
* Send tick to any upstream node
* @param options - Tick options with filter
*/
tickUpAny(options: Omit<TickAnyOptions, 'down' | 'up'>): void;
/**
* Send tick to all matching nodes
* @param options - Tick options with filter
* @returns Promise resolving to an array of results
*/
tickAll(options: TickAnyOptions): Promise<void[]>;
/**
* Send tick to all downstream nodes
* @param options - Tick options with filter
* @returns Promise resolving to an array of results
*/
tickDownAll(options: Omit<TickAnyOptions, 'down' | 'up'>): Promise<void[]>;
/**
* Send tick to all upstream nodes
* @param options - Tick options with filter
* @returns Promise resolving to an array of results
*/
tickUpAll(options: Omit<TickAnyOptions, 'down' | 'up'>): Promise<void[]>;
// ============================================================================
// Event Emitter (typed events)
// ============================================================================
on(event: NodeEvent.PEER_JOINED, listener: (payload: PeerJoinedPayload) => void): this;
on(event: NodeEvent.PEER_LEFT, listener: (payload: PeerLeftPayload) => void): this;
on(event: NodeEvent.STOPPED, listener: () => void): this;
on(event: NodeEvent.ERROR, listener: (payload: NodeErrorPayload) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: NodeEvent.PEER_JOINED, listener: (payload: PeerJoinedPayload) => void): this;
once(event: NodeEvent.PEER_LEFT, listener: (payload: PeerLeftPayload) => void): this;
once(event: NodeEvent.STOPPED, listener: () => void): this;
once(event: NodeEvent.ERROR, listener: (payload: NodeErrorPayload) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
off(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeAllListeners(event?: string | symbol): this;
}
// ============================================================================
// Transport Abstraction
// ============================================================================
/**
* Transport interface for custom transport implementations
*/
export interface ITransport {
createClientSocket(config?: any): any;
createServerSocket(config?: any): any;
}
/**
* Transport factory and registry
*/
export class Transport {
/**
* Register a custom transport
* @param name - Transport name
* @param transportImpl - Transport implementation
*/
static register(name: string, transportImpl: ITransport): void;
/**
* Set default transport
* @param name - Transport name
*/
static setDefault(name: string): void;
/**
* Create client socket using default transport
* @param config - Socket configuration
*/
static createClientSocket(config?: any): any;
/**
* Create server socket using default transport
* @param config - Socket configuration
*/
static createServerSocket(config?: any): any;
}
// ============================================================================
// Utilities
// ============================================================================
/**
* Build predicate function from options object
* @param options - Filter options
* @returns Predicate function
*/
export function optionsPredicateBuilder(options: Record<string, any>): (nodeOptions: Record<string, any>) => boolean;
// ============================================================================
// Module Exports
// ============================================================================
// Note: All exports are already declared with 'export' keyword above
// No need for re-export block