@olane/o-node 0.7.12 → 0.7.13-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/src/connection/interfaces/o-node-connection-manager.config.d.ts +1 -0
  2. package/dist/src/connection/interfaces/o-node-connection-manager.config.d.ts.map +1 -1
  3. package/dist/src/connection/o-node-connection.d.ts +0 -1
  4. package/dist/src/connection/o-node-connection.d.ts.map +1 -1
  5. package/dist/src/connection/o-node-connection.js +0 -8
  6. package/dist/src/connection/o-node-connection.manager.d.ts +33 -4
  7. package/dist/src/connection/o-node-connection.manager.d.ts.map +1 -1
  8. package/dist/src/connection/o-node-connection.manager.js +153 -44
  9. package/dist/src/connection/stream-handler.d.ts.map +1 -1
  10. package/dist/src/connection/stream-handler.js +0 -2
  11. package/dist/src/managers/o-connection-heartbeat.manager.d.ts.map +1 -1
  12. package/dist/src/managers/o-connection-heartbeat.manager.js +15 -1
  13. package/dist/src/managers/o-reconnection.manager.d.ts.map +1 -1
  14. package/dist/src/managers/o-reconnection.manager.js +12 -7
  15. package/dist/src/o-node.d.ts +5 -0
  16. package/dist/src/o-node.d.ts.map +1 -1
  17. package/dist/src/o-node.js +46 -8
  18. package/dist/src/o-node.tool.d.ts.map +1 -1
  19. package/dist/src/o-node.tool.js +5 -0
  20. package/dist/src/router/o-node.router.d.ts.map +1 -1
  21. package/dist/src/router/o-node.router.js +16 -6
  22. package/dist/src/router/o-node.routing-policy.d.ts.map +1 -1
  23. package/dist/src/router/o-node.routing-policy.js +4 -0
  24. package/dist/test/connection-management.spec.d.ts +2 -0
  25. package/dist/test/connection-management.spec.d.ts.map +1 -0
  26. package/dist/test/connection-management.spec.js +370 -0
  27. package/dist/test/helpers/connection-spy.d.ts +124 -0
  28. package/dist/test/helpers/connection-spy.d.ts.map +1 -0
  29. package/dist/test/helpers/connection-spy.js +229 -0
  30. package/dist/test/helpers/index.d.ts +6 -0
  31. package/dist/test/helpers/index.d.ts.map +1 -0
  32. package/dist/test/helpers/index.js +12 -0
  33. package/dist/test/helpers/network-builder.d.ts +109 -0
  34. package/dist/test/helpers/network-builder.d.ts.map +1 -0
  35. package/dist/test/helpers/network-builder.js +309 -0
  36. package/dist/test/helpers/simple-node-builder.d.ts +50 -0
  37. package/dist/test/helpers/simple-node-builder.d.ts.map +1 -0
  38. package/dist/test/helpers/simple-node-builder.js +66 -0
  39. package/dist/test/helpers/test-environment.d.ts +140 -0
  40. package/dist/test/helpers/test-environment.d.ts.map +1 -0
  41. package/dist/test/helpers/test-environment.js +184 -0
  42. package/dist/test/helpers/test-node.tool.d.ts +31 -0
  43. package/dist/test/helpers/test-node.tool.d.ts.map +1 -1
  44. package/dist/test/helpers/test-node.tool.js +49 -0
  45. package/dist/test/network-communication.spec.d.ts +2 -0
  46. package/dist/test/network-communication.spec.d.ts.map +1 -0
  47. package/dist/test/network-communication.spec.js +256 -0
  48. package/dist/test/o-node.spec.d.ts +2 -0
  49. package/dist/test/o-node.spec.d.ts.map +1 -0
  50. package/dist/test/o-node.spec.js +247 -0
  51. package/dist/test/parent-child-registration.spec.d.ts +2 -0
  52. package/dist/test/parent-child-registration.spec.d.ts.map +1 -0
  53. package/dist/test/parent-child-registration.spec.js +177 -0
  54. package/dist/test/search-resolver.spec.d.ts +2 -0
  55. package/dist/test/search-resolver.spec.d.ts.map +1 -0
  56. package/dist/test/search-resolver.spec.js +648 -0
  57. package/package.json +12 -7
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Spy that monitors libp2p connections and streams for testing
3
+ */
4
+ export class ConnectionSpy {
5
+ constructor(node) {
6
+ this.events = [];
7
+ this.listeners = new Map();
8
+ this.isMonitoring = false;
9
+ this.node = node;
10
+ }
11
+ /**
12
+ * Start monitoring connection events
13
+ */
14
+ start() {
15
+ if (this.isMonitoring) {
16
+ return;
17
+ }
18
+ this.isMonitoring = true;
19
+ // Monitor peer events
20
+ const peerConnectListener = (event) => {
21
+ this.events.push({
22
+ type: 'peer:connect',
23
+ timestamp: Date.now(),
24
+ peerId: event.detail.toString(),
25
+ });
26
+ };
27
+ this.node.p2pNode.addEventListener('peer:connect', peerConnectListener);
28
+ this.listeners.set('peer:connect', peerConnectListener);
29
+ const peerDisconnectListener = (event) => {
30
+ this.events.push({
31
+ type: 'peer:disconnect',
32
+ timestamp: Date.now(),
33
+ peerId: event.detail.toString(),
34
+ });
35
+ };
36
+ this.node.p2pNode.addEventListener('peer:disconnect', peerDisconnectListener);
37
+ this.listeners.set('peer:disconnect', peerDisconnectListener);
38
+ // Monitor connection events
39
+ const connectionOpenListener = (event) => {
40
+ const connection = event.detail;
41
+ this.events.push({
42
+ type: 'connection:open',
43
+ timestamp: Date.now(),
44
+ peerId: connection.remotePeer.toString(),
45
+ remoteAddr: connection.remoteAddr.toString(),
46
+ metadata: {
47
+ status: connection.status,
48
+ direction: connection.direction,
49
+ },
50
+ });
51
+ };
52
+ this.node.p2pNode.addEventListener('connection:open', connectionOpenListener);
53
+ this.listeners.set('connection:open', connectionOpenListener);
54
+ const connectionCloseListener = (event) => {
55
+ const connection = event.detail;
56
+ this.events.push({
57
+ type: 'connection:close',
58
+ timestamp: Date.now(),
59
+ peerId: connection.remotePeer.toString(),
60
+ remoteAddr: connection.remoteAddr.toString(),
61
+ });
62
+ };
63
+ this.node.p2pNode.addEventListener('connection:close', connectionCloseListener);
64
+ this.listeners.set('connection:close', connectionCloseListener);
65
+ }
66
+ /**
67
+ * Stop monitoring
68
+ */
69
+ stop() {
70
+ if (!this.isMonitoring) {
71
+ return;
72
+ }
73
+ this.isMonitoring = false;
74
+ for (const [event, listener] of this.listeners.entries()) {
75
+ this.node.p2pNode.removeEventListener(event, listener);
76
+ }
77
+ this.listeners.clear();
78
+ }
79
+ /**
80
+ * Clear all captured events
81
+ */
82
+ clear() {
83
+ this.events = [];
84
+ }
85
+ /**
86
+ * Get all captured events
87
+ */
88
+ getEvents() {
89
+ return [...this.events];
90
+ }
91
+ /**
92
+ * Get events of a specific type
93
+ */
94
+ getEventsByType(type) {
95
+ return this.events.filter((e) => e.type === type);
96
+ }
97
+ /**
98
+ * Get events for a specific peer
99
+ */
100
+ getEventsForPeer(peerId) {
101
+ return this.events.filter((e) => e.peerId === peerId);
102
+ }
103
+ /**
104
+ * Get current connection statistics
105
+ */
106
+ getConnectionStats() {
107
+ const stats = [];
108
+ const connections = this.node.p2pNode.getConnections();
109
+ for (const conn of connections) {
110
+ const streamStats = conn.streams.map((stream) => ({
111
+ protocol: stream.protocol || 'unknown',
112
+ status: stream.status,
113
+ writeStatus: stream.writeStatus,
114
+ readStatus: stream.readStatus,
115
+ created: Date.now(), // Approximate
116
+ }));
117
+ stats.push({
118
+ peerId: conn.remotePeer.toString(),
119
+ status: conn.status,
120
+ remoteAddr: conn.remoteAddr.toString(),
121
+ streams: streamStats,
122
+ created: Date.now(), // Approximate
123
+ });
124
+ }
125
+ return stats;
126
+ }
127
+ /**
128
+ * Get total stream count across all connections
129
+ */
130
+ getTotalStreamCount() {
131
+ const connections = this.node.p2pNode.getConnections();
132
+ return connections.reduce((sum, conn) => sum + conn.streams.length, 0);
133
+ }
134
+ /**
135
+ * Get stream count for a specific protocol
136
+ */
137
+ getStreamCountByProtocol(protocol) {
138
+ const connections = this.node.p2pNode.getConnections();
139
+ let count = 0;
140
+ for (const conn of connections) {
141
+ count += conn.streams.filter((s) => s.protocol === protocol).length;
142
+ }
143
+ return count;
144
+ }
145
+ /**
146
+ * Check if a connection exists to a peer
147
+ */
148
+ hasConnectionToPeer(peerId) {
149
+ const connections = this.node.p2pNode.getConnections();
150
+ return connections.some((conn) => conn.remotePeer.toString() === peerId);
151
+ }
152
+ /**
153
+ * Get connection to a specific peer
154
+ */
155
+ getConnectionToPeer(peerId) {
156
+ const connections = this.node.p2pNode.getConnections();
157
+ return connections.find((conn) => conn.remotePeer.toString() === peerId);
158
+ }
159
+ /**
160
+ * Get all streams for a specific peer
161
+ */
162
+ getStreamsForPeer(peerId) {
163
+ const connection = this.getConnectionToPeer(peerId);
164
+ return connection ? connection.streams : [];
165
+ }
166
+ /**
167
+ * Wait for a specific event to occur
168
+ */
169
+ async waitForEvent(type, timeoutMs = 5000) {
170
+ const startTime = Date.now();
171
+ while (Date.now() - startTime < timeoutMs) {
172
+ const events = this.getEventsByType(type);
173
+ if (events.length > 0) {
174
+ return events[events.length - 1];
175
+ }
176
+ await new Promise((resolve) => setTimeout(resolve, 50));
177
+ }
178
+ throw new Error(`Timeout waiting for event: ${type}`);
179
+ }
180
+ /**
181
+ * Wait for connection to a specific peer
182
+ */
183
+ async waitForConnectionToPeer(peerId, timeoutMs = 5000) {
184
+ const startTime = Date.now();
185
+ while (Date.now() - startTime < timeoutMs) {
186
+ const connection = this.getConnectionToPeer(peerId);
187
+ if (connection && connection.status === 'open') {
188
+ return connection;
189
+ }
190
+ await new Promise((resolve) => setTimeout(resolve, 50));
191
+ }
192
+ throw new Error(`Timeout waiting for connection to peer: ${peerId}`);
193
+ }
194
+ /**
195
+ * Wait for stream count to reach expected value
196
+ */
197
+ async waitForStreamCount(expectedCount, timeoutMs = 5000) {
198
+ const startTime = Date.now();
199
+ while (Date.now() - startTime < timeoutMs) {
200
+ const currentCount = this.getTotalStreamCount();
201
+ if (currentCount === expectedCount) {
202
+ return;
203
+ }
204
+ await new Promise((resolve) => setTimeout(resolve, 50));
205
+ }
206
+ const actualCount = this.getTotalStreamCount();
207
+ throw new Error(`Timeout waiting for stream count. Expected: ${expectedCount}, Actual: ${actualCount}`);
208
+ }
209
+ /**
210
+ * Get summary of connection activity
211
+ */
212
+ getSummary() {
213
+ return {
214
+ totalEvents: this.events.length,
215
+ connectionOpens: this.getEventsByType('connection:open').length,
216
+ connectionCloses: this.getEventsByType('connection:close').length,
217
+ peerConnects: this.getEventsByType('peer:connect').length,
218
+ peerDisconnects: this.getEventsByType('peer:disconnect').length,
219
+ currentConnections: this.node.p2pNode.getConnections().length,
220
+ currentStreams: this.getTotalStreamCount(),
221
+ };
222
+ }
223
+ }
224
+ /**
225
+ * Create a connection spy for a node
226
+ */
227
+ export function createConnectionSpy(node) {
228
+ return new ConnectionSpy(node);
229
+ }
@@ -0,0 +1,6 @@
1
+ export * from './test-environment.js';
2
+ export * from './simple-node-builder.js';
3
+ export * from './network-builder.js';
4
+ export * from './connection-spy.js';
5
+ export * from './test-node.tool.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../test/helpers/index.ts"],"names":[],"mappings":"AAOA,cAAc,uBAAuB,CAAC;AACtC,cAAc,0BAA0B,CAAC;AAGzC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,12 @@
1
+ // Test helpers barrel export
2
+ // These utilities are available for other packages during development and testing
3
+ // Core test environment and builders (moved from @olane/o-test)
4
+ // Note: Leader-related utilities have been removed to avoid circular dependencies
5
+ // with @olane/o-leader. Packages needing leader functionality should implement
6
+ // their own test utilities.
7
+ export * from './test-environment.js';
8
+ export * from './simple-node-builder.js';
9
+ // o-node specific helpers
10
+ export * from './network-builder.js';
11
+ export * from './connection-spy.js';
12
+ export * from './test-node.tool.js';
@@ -0,0 +1,109 @@
1
+ import { oNodeTool } from '../../src/o-node.tool.js';
2
+ import { oNodeAddress } from '../../src/router/o-node.address.js';
3
+ import { oNodeToolConfig } from '../../src/interfaces/o-node.tool-config.js';
4
+ import { oRequest } from '@olane/o-core';
5
+ import { Libp2pConfig } from '@olane/o-config';
6
+ /**
7
+ * Simple test tool for network communication testing
8
+ */
9
+ export declare class TestTool extends oNodeTool {
10
+ callCount: number;
11
+ constructor(config: oNodeToolConfig & {
12
+ address: oNodeAddress;
13
+ });
14
+ configure(): Promise<Libp2pConfig>;
15
+ registerParent(): Promise<void>;
16
+ _tool_echo(request: oRequest): Promise<any>;
17
+ _tool_get_info(request: oRequest): Promise<any>;
18
+ _tool_stream(request: oRequest): AsyncGenerator<any>;
19
+ }
20
+ /**
21
+ * Configuration for a node in the network
22
+ */
23
+ export interface NodeConfig {
24
+ address: string;
25
+ parent?: string;
26
+ seed?: string;
27
+ disableHeartbeat?: boolean;
28
+ }
29
+ /**
30
+ * Simplified network topology builder for testing node-to-node communication
31
+ * Focuses on peer connections and parent-child relationships without leader abstractions
32
+ */
33
+ export declare class NetworkBuilder {
34
+ private nodes;
35
+ private startedNodes;
36
+ /**
37
+ * Add a node to the network
38
+ * If parentAddress is provided, the node will register as a child
39
+ */
40
+ addNode(address: string, parentAddress?: string, config?: Partial<NodeConfig>): Promise<TestTool>;
41
+ /**
42
+ * Start a specific node
43
+ */
44
+ startNode(address: string): Promise<void>;
45
+ /**
46
+ * Stop a specific node
47
+ */
48
+ stopNode(address: string): Promise<void>;
49
+ /**
50
+ * Stop all nodes in the network
51
+ * Stops in reverse dependency order: children first, then parents
52
+ */
53
+ stopAll(): Promise<void>;
54
+ /**
55
+ * Get a node by address
56
+ */
57
+ getNode(address: string): TestTool | undefined;
58
+ /**
59
+ * Get all nodes
60
+ */
61
+ getAllNodes(): Map<string, TestTool>;
62
+ /**
63
+ * Sort nodes by hierarchy depth (root nodes first)
64
+ */
65
+ private getSortedNodesByDepth;
66
+ /**
67
+ * Wait for a node to have transports available
68
+ */
69
+ private waitForTransports;
70
+ /**
71
+ * Clean up all nodes
72
+ */
73
+ cleanup(): Promise<void>;
74
+ }
75
+ /**
76
+ * Quick network topology builders for common test scenarios
77
+ * All topologies use simple parent-child relationships without leader abstractions
78
+ * Note: "leader" in address names is just a convention, not a special node type
79
+ */
80
+ export declare class NetworkTopologies {
81
+ /**
82
+ * Create a simple two-node network (parent-child)
83
+ * Addresses: o://leader (root), o://child
84
+ */
85
+ static twoNode(): Promise<NetworkBuilder>;
86
+ /**
87
+ * Create a three-node hierarchy (leader → parent → child)
88
+ * Addresses: o://leader (root), o://parent, o://child
89
+ */
90
+ static threeNode(): Promise<NetworkBuilder>;
91
+ /**
92
+ * Create a five-node hierarchy with two branches
93
+ * Structure: leader → parent1 → child1, child2
94
+ * → parent2
95
+ */
96
+ static fiveNode(): Promise<NetworkBuilder>;
97
+ /**
98
+ * Create two standalone nodes (peer-to-peer)
99
+ */
100
+ static twoStandalone(): Promise<NetworkBuilder>;
101
+ /**
102
+ * Create a complex hierarchy for integration testing
103
+ * Structure: leader → parent1 → child1, child2
104
+ * → parent2 → child3, child4
105
+ * → parent3 → child5, child6
106
+ */
107
+ static complex(): Promise<NetworkBuilder>;
108
+ }
109
+ //# sourceMappingURL=network-builder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-builder.d.ts","sourceRoot":"","sources":["../../../test/helpers/network-builder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,4CAA4C,CAAC;AAC7E,OAAO,EAAY,QAAQ,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C;;GAEG;AACH,qBAAa,QAAS,SAAQ,SAAS;IAC9B,SAAS,SAAK;gBAET,MAAM,EAAE,eAAe,GAAG;QAAE,OAAO,EAAE,YAAY,CAAA;KAAE;IAIzD,SAAS,IAAI,OAAO,CAAC,YAAY,CAAC;IAelC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAwC/B,UAAU,CAAC,OAAO,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAS3C,cAAc,CAAC,OAAO,EAAE,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAS9C,YAAY,CAAC,OAAO,EAAE,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC;CAY5D;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B;AAED;;;GAGG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,KAAK,CAAoC;IACjD,OAAO,CAAC,YAAY,CAA0B;IAE9C;;;OAGG;IACG,OAAO,CACX,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,MAAM,EACtB,MAAM,GAAE,OAAO,CAAC,UAAU,CAAM,GAC/B,OAAO,CAAC,QAAQ,CAAC;IAqCpB;;OAEG;IACG,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkB/C;;OAEG;IACG,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAc9C;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAU9B;;OAEG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS;IAI9C;;OAEG;IACH,WAAW,IAAI,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC;IAIpC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAyC7B;;OAEG;YACW,iBAAiB;IAkB/B;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAK/B;AAED;;;;GAIG;AACH,qBAAa,iBAAiB;IAC5B;;;OAGG;WACU,OAAO,IAAI,OAAO,CAAC,cAAc,CAAC;IAO/C;;;OAGG;WACU,SAAS,IAAI,OAAO,CAAC,cAAc,CAAC;IAQjD;;;;OAIG;WACU,QAAQ,IAAI,OAAO,CAAC,cAAc,CAAC;IAUhD;;OAEG;WACU,aAAa,IAAI,OAAO,CAAC,cAAc,CAAC;IAOrD;;;;;OAKG;WACU,OAAO,IAAI,OAAO,CAAC,cAAc,CAAC;CAmBhD"}
@@ -0,0 +1,309 @@
1
+ import { oNodeTool } from '../../src/o-node.tool.js';
2
+ import { oNodeAddress } from '../../src/router/o-node.address.js';
3
+ import { oAddress } from '@olane/o-core';
4
+ /**
5
+ * Simple test tool for network communication testing
6
+ */
7
+ export class TestTool extends oNodeTool {
8
+ constructor(config) {
9
+ super(config);
10
+ this.callCount = 0;
11
+ }
12
+ async configure() {
13
+ const config = await super.configure();
14
+ config.connectionGater = {
15
+ denyDialPeer: (peerId) => {
16
+ return false;
17
+ },
18
+ // who can call us?
19
+ denyInboundEncryptedConnection: (peerId, maConn) => {
20
+ return false;
21
+ },
22
+ };
23
+ return config;
24
+ }
25
+ // NEED TO OVERRIDE to ensure that we can test fully without a proper leader node
26
+ async registerParent() {
27
+ if (!this.parent) {
28
+ this.logger.warn('no parent, skipping registration');
29
+ return;
30
+ }
31
+ if (!this.parent?.libp2pTransports?.length) {
32
+ this.logger.debug('Parent has no transports, waiting for reconnection & leader ack');
33
+ if (this.parent?.toString() === oAddress.leader().toString()) {
34
+ this.parent.setTransports(this.leader?.libp2pTransports || []);
35
+ }
36
+ else {
37
+ this.logger.debug('Waiting for parent and reconnecting...');
38
+ await this.reconnectionManager?.waitForParentAndReconnect();
39
+ }
40
+ }
41
+ // if no parent transports, register with the parent to get them
42
+ // TODO: should we remove the transports check to make this more consistent?
43
+ if (this.config.parent) {
44
+ this.logger.debug('Registering node with parent...', this.config.parent?.toString());
45
+ // avoid transports to ensure we do not try direct connection, we need to route via the leader for proper access controls
46
+ await this.use(this.config.parent, {
47
+ method: 'child_register',
48
+ params: {
49
+ address: this.address.toString(),
50
+ transports: this.transports.map((t) => t.toString()),
51
+ peerId: this.peerId.toString(),
52
+ _token: this.config.joinToken,
53
+ },
54
+ });
55
+ this.setKeepAliveTag(this.parent);
56
+ }
57
+ }
58
+ async _tool_echo(request) {
59
+ this.callCount++;
60
+ return {
61
+ message: request.params.message || 'echo',
62
+ nodeAddress: this.address.toString(),
63
+ timestamp: Date.now(),
64
+ };
65
+ }
66
+ async _tool_get_info(request) {
67
+ return {
68
+ address: this.address.toString(),
69
+ parent: this.parent?.toString(),
70
+ children: this.getChildren().map((c) => c.toString()),
71
+ callCount: this.callCount,
72
+ };
73
+ }
74
+ async *_tool_stream(request) {
75
+ const count = request.params.count || 5;
76
+ for (let i = 0; i < count; i++) {
77
+ yield {
78
+ chunk: i + 1,
79
+ total: count,
80
+ nodeAddress: this.address.toString(),
81
+ timestamp: Date.now(),
82
+ };
83
+ await new Promise((resolve) => setTimeout(resolve, 10));
84
+ }
85
+ }
86
+ }
87
+ /**
88
+ * Simplified network topology builder for testing node-to-node communication
89
+ * Focuses on peer connections and parent-child relationships without leader abstractions
90
+ */
91
+ export class NetworkBuilder {
92
+ constructor() {
93
+ this.nodes = new Map();
94
+ this.startedNodes = new Set();
95
+ }
96
+ /**
97
+ * Add a node to the network
98
+ * If parentAddress is provided, the node will register as a child
99
+ */
100
+ async addNode(address, parentAddress, config = {}) {
101
+ const seed = config.seed || `node-seed-${address}-${Date.now()}`;
102
+ let parentNode;
103
+ let parentRef = null;
104
+ if (parentAddress) {
105
+ parentNode = this.nodes.get(parentAddress);
106
+ if (!parentNode) {
107
+ throw new Error(`Parent node not found: ${parentAddress}`);
108
+ }
109
+ // Wait for parent to have transports
110
+ // await this.waitForTransports(parentNode);
111
+ parentRef = new oNodeAddress(parentNode.address.toString(), parentNode.address.libp2pTransports);
112
+ }
113
+ const node = new TestTool({
114
+ address: new oNodeAddress(address),
115
+ parent: parentRef,
116
+ leader: null, // No leader abstraction in o-node tests
117
+ seed,
118
+ connectionHeartbeat: {
119
+ enabled: !config.disableHeartbeat,
120
+ checkChildren: parentAddress ? false : true, // Only root monitors children
121
+ },
122
+ });
123
+ this.nodes.set(address, node);
124
+ await this.startNode(address);
125
+ return node;
126
+ }
127
+ /**
128
+ * Start a specific node
129
+ */
130
+ async startNode(address) {
131
+ const node = this.nodes.get(address);
132
+ if (!node) {
133
+ throw new Error(`Node not found: ${address}`);
134
+ }
135
+ if (this.startedNodes.has(address)) {
136
+ return; // Already started
137
+ }
138
+ await node.start();
139
+ this.startedNodes.add(address);
140
+ // Wait for transports to be available
141
+ // await this.waitForTransports(node);
142
+ }
143
+ /**
144
+ * Stop a specific node
145
+ */
146
+ async stopNode(address) {
147
+ const node = this.nodes.get(address);
148
+ if (!node) {
149
+ throw new Error(`Node not found: ${address}`);
150
+ }
151
+ if (!this.startedNodes.has(address)) {
152
+ return; // Not started
153
+ }
154
+ await node.stop();
155
+ this.startedNodes.delete(address);
156
+ }
157
+ /**
158
+ * Stop all nodes in the network
159
+ * Stops in reverse dependency order: children first, then parents
160
+ */
161
+ async stopAll() {
162
+ const sortedNodes = this.getSortedNodesByDepth().reverse();
163
+ for (const address of sortedNodes) {
164
+ if (this.startedNodes.has(address)) {
165
+ await this.stopNode(address);
166
+ }
167
+ }
168
+ }
169
+ /**
170
+ * Get a node by address
171
+ */
172
+ getNode(address) {
173
+ return this.nodes.get(address);
174
+ }
175
+ /**
176
+ * Get all nodes
177
+ */
178
+ getAllNodes() {
179
+ return new Map(this.nodes);
180
+ }
181
+ /**
182
+ * Sort nodes by hierarchy depth (root nodes first)
183
+ */
184
+ getSortedNodesByDepth() {
185
+ const depths = new Map();
186
+ const addresses = Array.from(this.nodes.keys());
187
+ // Calculate depth for each node
188
+ const calculateDepth = (address) => {
189
+ if (depths.has(address)) {
190
+ return depths.get(address);
191
+ }
192
+ const node = this.nodes.get(address);
193
+ if (!node.parent) {
194
+ depths.set(address, 0);
195
+ return 0;
196
+ }
197
+ // Find parent address in our map
198
+ const parentAddress = Array.from(this.nodes.entries()).find(([_, n]) => n.address.toString() === node.parent?.toString())?.[0];
199
+ if (!parentAddress) {
200
+ depths.set(address, 0);
201
+ return 0;
202
+ }
203
+ const depth = calculateDepth(parentAddress) + 1;
204
+ depths.set(address, depth);
205
+ return depth;
206
+ };
207
+ addresses.forEach((addr) => calculateDepth(addr));
208
+ // Sort by depth (ascending)
209
+ return addresses.sort((a, b) => {
210
+ const depthA = depths.get(a) || 0;
211
+ const depthB = depths.get(b) || 0;
212
+ return depthA - depthB;
213
+ });
214
+ }
215
+ /**
216
+ * Wait for a node to have transports available
217
+ */
218
+ async waitForTransports(node, timeoutMs = 5000) {
219
+ const startTime = Date.now();
220
+ while (Date.now() - startTime < timeoutMs) {
221
+ if (node.address.libp2pTransports.length > 0) {
222
+ return;
223
+ }
224
+ await new Promise((resolve) => setTimeout(resolve, 50));
225
+ }
226
+ throw new Error(`Timeout waiting for transports on ${node.address.toString()}`);
227
+ }
228
+ /**
229
+ * Clean up all nodes
230
+ */
231
+ async cleanup() {
232
+ await this.stopAll();
233
+ this.nodes.clear();
234
+ this.startedNodes.clear();
235
+ }
236
+ }
237
+ /**
238
+ * Quick network topology builders for common test scenarios
239
+ * All topologies use simple parent-child relationships without leader abstractions
240
+ * Note: "leader" in address names is just a convention, not a special node type
241
+ */
242
+ export class NetworkTopologies {
243
+ /**
244
+ * Create a simple two-node network (parent-child)
245
+ * Addresses: o://leader (root), o://child
246
+ */
247
+ static async twoNode() {
248
+ const builder = new NetworkBuilder();
249
+ await builder.addNode('o://leader');
250
+ await builder.addNode('o://child', 'o://leader');
251
+ return builder;
252
+ }
253
+ /**
254
+ * Create a three-node hierarchy (leader → parent → child)
255
+ * Addresses: o://leader (root), o://parent, o://child
256
+ */
257
+ static async threeNode() {
258
+ const builder = new NetworkBuilder();
259
+ await builder.addNode('o://leader');
260
+ await builder.addNode('o://parent', 'o://leader');
261
+ await builder.addNode('o://child', 'o://parent');
262
+ return builder;
263
+ }
264
+ /**
265
+ * Create a five-node hierarchy with two branches
266
+ * Structure: leader → parent1 → child1, child2
267
+ * → parent2
268
+ */
269
+ static async fiveNode() {
270
+ const builder = new NetworkBuilder();
271
+ await builder.addNode('o://leader');
272
+ await builder.addNode('o://parent1', 'o://leader');
273
+ await builder.addNode('o://parent2', 'o://leader');
274
+ await builder.addNode('o://child1', 'o://parent1');
275
+ await builder.addNode('o://child2', 'o://parent1');
276
+ return builder;
277
+ }
278
+ /**
279
+ * Create two standalone nodes (peer-to-peer)
280
+ */
281
+ static async twoStandalone() {
282
+ const builder = new NetworkBuilder();
283
+ await builder.addNode('o://node1');
284
+ await builder.addNode('o://node2');
285
+ return builder;
286
+ }
287
+ /**
288
+ * Create a complex hierarchy for integration testing
289
+ * Structure: leader → parent1 → child1, child2
290
+ * → parent2 → child3, child4
291
+ * → parent3 → child5, child6
292
+ */
293
+ static async complex() {
294
+ const builder = new NetworkBuilder();
295
+ await builder.addNode('o://leader');
296
+ // Add three parent nodes
297
+ await builder.addNode('o://parent1', 'o://leader');
298
+ await builder.addNode('o://parent2', 'o://leader');
299
+ await builder.addNode('o://parent3', 'o://leader');
300
+ // Add children to each parent
301
+ await builder.addNode('o://parent1-child1', 'o://parent1');
302
+ await builder.addNode('o://parent1-child2', 'o://parent1');
303
+ await builder.addNode('o://parent2-child1', 'o://parent2');
304
+ await builder.addNode('o://parent2-child2', 'o://parent2');
305
+ await builder.addNode('o://parent3-child1', 'o://parent3');
306
+ await builder.addNode('o://parent3-child2', 'o://parent3');
307
+ return builder;
308
+ }
309
+ }