starpc 0.25.1 → 0.25.2
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.
- package/dist/e2e/e2e.js +4 -3
- package/dist/srpc/channel.d.ts +6 -1
- package/dist/srpc/channel.js +43 -1
- package/dist/srpc/errors.d.ts +2 -0
- package/dist/srpc/errors.js +10 -0
- package/dist/srpc/index.d.ts +3 -2
- package/dist/srpc/index.js +2 -1
- package/dist/srpc/watchdog.d.ts +35 -0
- package/dist/srpc/watchdog.js +64 -0
- package/e2e/e2e.ts +26 -6
- package/package.json +1 -1
- package/srpc/channel.ts +63 -5
- package/srpc/errors.ts +12 -0
- package/srpc/index.ts +9 -1
- package/srpc/watchdog.ts +70 -0
package/dist/e2e/e2e.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { pipe } from 'it-pipe';
|
|
2
|
-
import { createHandler, createMux, Server, Client, StreamConn, ChannelStream, combineUint8ArrayListTransform } from '../srpc';
|
|
2
|
+
import { createHandler, createMux, Server, Client, StreamConn, ChannelStream, combineUint8ArrayListTransform, } from '../srpc';
|
|
3
3
|
import { EchoerDefinition, EchoerServer, runClientTest } from '../echo';
|
|
4
4
|
import { runAbortControllerTest, runRpcStreamTest } from '../echo/client-test';
|
|
5
5
|
async function runRPC() {
|
|
@@ -13,8 +13,9 @@ async function runRPC() {
|
|
|
13
13
|
const serverConn = new StreamConn(server, { direction: 'inbound' });
|
|
14
14
|
// pipe clientConn -> messageStream -> serverConn -> messageStream -> clientConn
|
|
15
15
|
const { port1: clientPort, port2: serverPort } = new MessageChannel();
|
|
16
|
-
const
|
|
17
|
-
const
|
|
16
|
+
const opts = { idleTimeoutMs: 250, keepAliveMs: 100 };
|
|
17
|
+
const clientChannelStream = new ChannelStream('client', clientPort, opts);
|
|
18
|
+
const serverChannelStream = new ChannelStream('server', serverPort, opts);
|
|
18
19
|
// Pipe the client traffic via the client end of the MessageChannel.
|
|
19
20
|
pipe(clientChannelStream, clientConn, combineUint8ArrayListTransform(), clientChannelStream)
|
|
20
21
|
.catch((err) => clientConn.close(err))
|
package/dist/srpc/channel.d.ts
CHANGED
|
@@ -3,7 +3,6 @@ export interface ChannelStreamMessage<T> {
|
|
|
3
3
|
from: string;
|
|
4
4
|
ack?: true;
|
|
5
5
|
opened?: true;
|
|
6
|
-
alive?: true;
|
|
7
6
|
closed?: true;
|
|
8
7
|
error?: Error;
|
|
9
8
|
data?: T;
|
|
@@ -14,6 +13,8 @@ export type ChannelPort = MessagePort | {
|
|
|
14
13
|
};
|
|
15
14
|
export interface ChannelStreamOpts {
|
|
16
15
|
remoteOpen?: boolean;
|
|
16
|
+
keepAliveMs?: number;
|
|
17
|
+
idleTimeoutMs?: number;
|
|
17
18
|
}
|
|
18
19
|
export declare class ChannelStream<T = Uint8Array> implements Duplex<AsyncGenerator<T>, Source<T>, Promise<void>> {
|
|
19
20
|
readonly channel: ChannelPort;
|
|
@@ -28,10 +29,14 @@ export declare class ChannelStream<T = Uint8Array> implements Duplex<AsyncGenera
|
|
|
28
29
|
private remoteAck;
|
|
29
30
|
readonly waitRemoteAck: Promise<void>;
|
|
30
31
|
private _remoteAck?;
|
|
32
|
+
private keepAlive?;
|
|
33
|
+
private idleWatchdog?;
|
|
31
34
|
get isAcked(): boolean;
|
|
32
35
|
get isOpen(): boolean;
|
|
33
36
|
constructor(localId: string, channel: ChannelPort, opts?: ChannelStreamOpts);
|
|
34
37
|
private postMessage;
|
|
38
|
+
private idleElapsed;
|
|
39
|
+
private keepAliveElapsed;
|
|
35
40
|
close(error?: Error): void;
|
|
36
41
|
private onLocalOpened;
|
|
37
42
|
private onRemoteAcked;
|
package/dist/srpc/channel.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { pushable } from 'it-pushable';
|
|
2
|
+
import { Watchdog } from './watchdog.js';
|
|
3
|
+
import { ERR_STREAM_IDLE } from './errors.js';
|
|
2
4
|
// ChannelStream implements a Stream over a BroadcastChannel duplex or MessagePort.
|
|
3
5
|
//
|
|
4
6
|
// NOTE: there is no way to tell if a BroadcastChannel or MessagePort is closed.
|
|
@@ -15,12 +17,13 @@ export class ChannelStream {
|
|
|
15
17
|
}
|
|
16
18
|
// remoteOpen indicates that we know the remote has already opened the stream.
|
|
17
19
|
constructor(localId, channel, opts) {
|
|
20
|
+
// initial state
|
|
18
21
|
this.localId = localId;
|
|
19
22
|
this.channel = channel;
|
|
20
|
-
this.sink = this._createSink();
|
|
21
23
|
this.localOpen = false;
|
|
22
24
|
this.remoteOpen = opts?.remoteOpen ?? false;
|
|
23
25
|
this.remoteAck = this.remoteOpen;
|
|
26
|
+
// wire up the promises for remote ack and remote open
|
|
24
27
|
if (this.remoteOpen) {
|
|
25
28
|
this.waitRemoteOpen = Promise.resolve();
|
|
26
29
|
this.waitRemoteAck = Promise.resolve();
|
|
@@ -49,9 +52,13 @@ export class ChannelStream {
|
|
|
49
52
|
});
|
|
50
53
|
this.waitRemoteAck.catch(() => { });
|
|
51
54
|
}
|
|
55
|
+
// create the sink
|
|
56
|
+
this.sink = this._createSink();
|
|
57
|
+
// create the pushable source
|
|
52
58
|
const source = pushable({ objectMode: true });
|
|
53
59
|
this.source = source;
|
|
54
60
|
this._source = source;
|
|
61
|
+
// wire up the message handlers
|
|
55
62
|
const onMessage = this.onMessage.bind(this);
|
|
56
63
|
if (channel instanceof MessagePort) {
|
|
57
64
|
// MessagePort
|
|
@@ -62,6 +69,14 @@ export class ChannelStream {
|
|
|
62
69
|
// BroadcastChannel
|
|
63
70
|
channel.rx.onmessage = onMessage;
|
|
64
71
|
}
|
|
72
|
+
// handle the keep alive or idle timeout opts
|
|
73
|
+
if (opts?.idleTimeoutMs != null) {
|
|
74
|
+
this.idleWatchdog = new Watchdog(opts.idleTimeoutMs, () => this.idleElapsed());
|
|
75
|
+
}
|
|
76
|
+
if (opts?.keepAliveMs != null) {
|
|
77
|
+
this.keepAlive = new Watchdog(opts.keepAliveMs, () => this.keepAliveElapsed());
|
|
78
|
+
}
|
|
79
|
+
// broadcast ack to start the stream
|
|
65
80
|
this.postMessage({ ack: true });
|
|
66
81
|
}
|
|
67
82
|
// postMessage writes a message to the stream.
|
|
@@ -73,6 +88,23 @@ export class ChannelStream {
|
|
|
73
88
|
else {
|
|
74
89
|
this.channel.tx.postMessage(msg);
|
|
75
90
|
}
|
|
91
|
+
if (!msg.closed) {
|
|
92
|
+
this.keepAlive?.feed();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// idleElapsed is called if the idle timeout was elapsed.
|
|
96
|
+
idleElapsed() {
|
|
97
|
+
if (this.idleWatchdog) {
|
|
98
|
+
delete this.idleWatchdog;
|
|
99
|
+
this.close(new Error(ERR_STREAM_IDLE));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// keepAliveElapsed is called if the keep alive timeout was elapsed.
|
|
103
|
+
keepAliveElapsed() {
|
|
104
|
+
if (this.keepAlive) {
|
|
105
|
+
// send a keep-alive message
|
|
106
|
+
this.postMessage({});
|
|
107
|
+
}
|
|
76
108
|
}
|
|
77
109
|
// close closes the broadcast channels.
|
|
78
110
|
close(error) {
|
|
@@ -92,6 +124,15 @@ export class ChannelStream {
|
|
|
92
124
|
if (!this.remoteAck && this._remoteAck) {
|
|
93
125
|
this._remoteAck(error || new Error('closed'));
|
|
94
126
|
}
|
|
127
|
+
if (this.idleWatchdog) {
|
|
128
|
+
this.idleWatchdog.clear();
|
|
129
|
+
delete this.idleWatchdog;
|
|
130
|
+
}
|
|
131
|
+
if (this.keepAlive) {
|
|
132
|
+
this.keepAlive.clear();
|
|
133
|
+
delete this.keepAlive;
|
|
134
|
+
}
|
|
135
|
+
this._source.end(error);
|
|
95
136
|
}
|
|
96
137
|
// onLocalOpened indicates the local side has opened the read stream.
|
|
97
138
|
onLocalOpened() {
|
|
@@ -140,6 +181,7 @@ export class ChannelStream {
|
|
|
140
181
|
if (!msg || msg.from === this.localId || !msg.from) {
|
|
141
182
|
return;
|
|
142
183
|
}
|
|
184
|
+
this.idleWatchdog?.feed();
|
|
143
185
|
if (msg.ack || msg.opened) {
|
|
144
186
|
this.onRemoteAcked();
|
|
145
187
|
}
|
package/dist/srpc/errors.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export declare const ERR_RPC_ABORT = "ERR_RPC_ABORT";
|
|
2
2
|
export declare function isAbortError(err: unknown): boolean;
|
|
3
|
+
export declare const ERR_STREAM_IDLE = "ERR_STREAM_IDLE";
|
|
4
|
+
export declare function isStreamIdleError(err: unknown): boolean;
|
|
3
5
|
export declare function castToError(err: any, defaultMsg?: string): Error;
|
package/dist/srpc/errors.js
CHANGED
|
@@ -8,6 +8,16 @@ export function isAbortError(err) {
|
|
|
8
8
|
const message = err.message;
|
|
9
9
|
return message === ERR_RPC_ABORT;
|
|
10
10
|
}
|
|
11
|
+
// ERR_STREAM_IDLE is returned if the stream idle timeout was exceeded.
|
|
12
|
+
export const ERR_STREAM_IDLE = 'ERR_STREAM_IDLE';
|
|
13
|
+
// isStreamIdleError checks if the error object is ERR_STREAM_IDLE.
|
|
14
|
+
export function isStreamIdleError(err) {
|
|
15
|
+
if (typeof err !== 'object') {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const message = err.message;
|
|
19
|
+
return message === ERR_STREAM_IDLE;
|
|
20
|
+
}
|
|
11
21
|
// castToError casts an object to an Error.
|
|
12
22
|
// if err is a string, uses it as the message.
|
|
13
23
|
// if err is undefined, returns new Error(defaultMsg)
|
package/dist/srpc/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ERR_RPC_ABORT, isAbortError, castToError } from './errors.js';
|
|
1
|
+
export { ERR_RPC_ABORT, isAbortError, ERR_STREAM_IDLE, isStreamIdleError, castToError, } from './errors.js';
|
|
2
2
|
export { Client } from './client.js';
|
|
3
3
|
export { Server } from './server.js';
|
|
4
4
|
export { StreamConn, StreamConnParams, StreamHandler } from './conn.js';
|
|
@@ -8,7 +8,7 @@ export { Handler, InvokeFn, MethodMap, StaticHandler, createHandler, } from './h
|
|
|
8
8
|
export { MethodProto, createInvokeFn } from './invoker.js';
|
|
9
9
|
export { Packet, CallStart, CallData } from './rpcproto.pb.js';
|
|
10
10
|
export { Mux, StaticMux, LookupMethod, createMux } from './mux.js';
|
|
11
|
-
export { ChannelStreamMessage, ChannelPort, ChannelStream, newBroadcastChannelStream, } from './channel.js';
|
|
11
|
+
export { ChannelStreamMessage, ChannelPort, ChannelStream, ChannelStreamOpts, newBroadcastChannelStream, } from './channel.js';
|
|
12
12
|
export { BroadcastChannelDuplex, BroadcastChannelConn, newBroadcastChannelDuplex, } from './broadcast-channel.js';
|
|
13
13
|
export { MessagePortDuplex, MessagePortConn, newMessagePortDuplex, } from './message-port.js';
|
|
14
14
|
export { MessageDefinition, DecodeMessageTransform, buildDecodeMessageTransform, EncodeMessageTransform, buildEncodeMessageTransform, memoProto, memoProtoDecode, } from './message.js';
|
|
@@ -17,3 +17,4 @@ export { combineUint8ArrayListTransform } from './array-list.js';
|
|
|
17
17
|
export { ValueCtr } from './value-ctr.js';
|
|
18
18
|
export { OpenStreamCtr } from './open-stream-ctr.js';
|
|
19
19
|
export { writeToPushable, buildPushableSink } from './pushable.js';
|
|
20
|
+
export { Watchdog } from './watchdog.js';
|
package/dist/srpc/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ERR_RPC_ABORT, isAbortError, castToError } from './errors.js';
|
|
1
|
+
export { ERR_RPC_ABORT, isAbortError, ERR_STREAM_IDLE, isStreamIdleError, castToError, } from './errors.js';
|
|
2
2
|
export { Client } from './client.js';
|
|
3
3
|
export { Server } from './server.js';
|
|
4
4
|
export { StreamConn } from './conn.js';
|
|
@@ -16,3 +16,4 @@ export { combineUint8ArrayListTransform } from './array-list.js';
|
|
|
16
16
|
export { ValueCtr } from './value-ctr.js';
|
|
17
17
|
export { OpenStreamCtr } from './open-stream-ctr.js';
|
|
18
18
|
export { writeToPushable, buildPushableSink } from './pushable.js';
|
|
19
|
+
export { Watchdog } from './watchdog.js';
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export declare class Watchdog {
|
|
2
|
+
private timeoutDuration;
|
|
3
|
+
private expiredCallback;
|
|
4
|
+
private timerId;
|
|
5
|
+
private lastFeedTimestamp;
|
|
6
|
+
/**
|
|
7
|
+
* Constructs a Watchdog instance.
|
|
8
|
+
* The Watchdog will not start ticking until feed() is called.
|
|
9
|
+
* @param timeoutDuration The duration in milliseconds after which the watchdog should expire if not fed.
|
|
10
|
+
* @param expiredCallback The callback function to be called when the watchdog expires.
|
|
11
|
+
*/
|
|
12
|
+
constructor(timeoutDuration: number, expiredCallback: () => void);
|
|
13
|
+
/**
|
|
14
|
+
* Feeds the watchdog, preventing it from expiring.
|
|
15
|
+
* This resets the timeout and reschedules the next tick.
|
|
16
|
+
*/
|
|
17
|
+
feed(): void;
|
|
18
|
+
/**
|
|
19
|
+
* Clears the current timeout, effectively stopping the watchdog.
|
|
20
|
+
* This prevents the expired callback from being called until the watchdog is fed again.
|
|
21
|
+
*/
|
|
22
|
+
clear(): void;
|
|
23
|
+
/**
|
|
24
|
+
* Schedules the next tick of the watchdog.
|
|
25
|
+
* This method calculates the delay for the next tick based on the last feed time
|
|
26
|
+
* and schedules a call to tickWatchdog after that delay.
|
|
27
|
+
*/
|
|
28
|
+
private scheduleTickWatchdog;
|
|
29
|
+
/**
|
|
30
|
+
* Handler for the watchdog tick.
|
|
31
|
+
* Checks if the time since the last feed is greater than the timeout duration.
|
|
32
|
+
* If so, it calls the expired callback. Otherwise, it reschedules the tick.
|
|
33
|
+
*/
|
|
34
|
+
private tickWatchdog;
|
|
35
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Watchdog must be fed every timeoutDuration or it will call the expired callback.
|
|
2
|
+
export class Watchdog {
|
|
3
|
+
/**
|
|
4
|
+
* Constructs a Watchdog instance.
|
|
5
|
+
* The Watchdog will not start ticking until feed() is called.
|
|
6
|
+
* @param timeoutDuration The duration in milliseconds after which the watchdog should expire if not fed.
|
|
7
|
+
* @param expiredCallback The callback function to be called when the watchdog expires.
|
|
8
|
+
*/
|
|
9
|
+
constructor(timeoutDuration, expiredCallback) {
|
|
10
|
+
this.timerId = null;
|
|
11
|
+
this.lastFeedTimestamp = null;
|
|
12
|
+
this.timeoutDuration = timeoutDuration;
|
|
13
|
+
this.expiredCallback = expiredCallback;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Feeds the watchdog, preventing it from expiring.
|
|
17
|
+
* This resets the timeout and reschedules the next tick.
|
|
18
|
+
*/
|
|
19
|
+
feed() {
|
|
20
|
+
this.lastFeedTimestamp = Date.now();
|
|
21
|
+
this.scheduleTickWatchdog(this.timeoutDuration);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Clears the current timeout, effectively stopping the watchdog.
|
|
25
|
+
* This prevents the expired callback from being called until the watchdog is fed again.
|
|
26
|
+
*/
|
|
27
|
+
clear() {
|
|
28
|
+
if (this.timerId != null) {
|
|
29
|
+
clearTimeout(this.timerId);
|
|
30
|
+
this.timerId = null;
|
|
31
|
+
}
|
|
32
|
+
this.lastFeedTimestamp = null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Schedules the next tick of the watchdog.
|
|
36
|
+
* This method calculates the delay for the next tick based on the last feed time
|
|
37
|
+
* and schedules a call to tickWatchdog after that delay.
|
|
38
|
+
*/
|
|
39
|
+
scheduleTickWatchdog(delay) {
|
|
40
|
+
if (this.timerId != null) {
|
|
41
|
+
clearTimeout(this.timerId);
|
|
42
|
+
}
|
|
43
|
+
this.timerId = setTimeout(() => this.tickWatchdog(), delay);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Handler for the watchdog tick.
|
|
47
|
+
* Checks if the time since the last feed is greater than the timeout duration.
|
|
48
|
+
* If so, it calls the expired callback. Otherwise, it reschedules the tick.
|
|
49
|
+
*/
|
|
50
|
+
tickWatchdog() {
|
|
51
|
+
this.timerId = null;
|
|
52
|
+
if (this.lastFeedTimestamp == null) {
|
|
53
|
+
this.expiredCallback();
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const elapsedSinceLastFeed = Date.now() - this.lastFeedTimestamp;
|
|
57
|
+
if (elapsedSinceLastFeed >= this.timeoutDuration) {
|
|
58
|
+
this.expiredCallback();
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
this.scheduleTickWatchdog(this.timeoutDuration - elapsedSinceLastFeed);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
package/e2e/e2e.ts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { pipe } from 'it-pipe'
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
createHandler,
|
|
4
|
+
createMux,
|
|
5
|
+
Server,
|
|
6
|
+
Client,
|
|
7
|
+
StreamConn,
|
|
8
|
+
ChannelStream,
|
|
9
|
+
combineUint8ArrayListTransform,
|
|
10
|
+
ChannelStreamOpts,
|
|
11
|
+
} from '../srpc'
|
|
3
12
|
import { EchoerDefinition, EchoerServer, runClientTest } from '../echo'
|
|
4
13
|
import { runAbortControllerTest, runRpcStreamTest } from '../echo/client-test'
|
|
5
14
|
|
|
@@ -15,17 +24,28 @@ async function runRPC() {
|
|
|
15
24
|
const serverConn = new StreamConn(server, { direction: 'inbound' })
|
|
16
25
|
|
|
17
26
|
// pipe clientConn -> messageStream -> serverConn -> messageStream -> clientConn
|
|
18
|
-
const {port1: clientPort, port2: serverPort} = new MessageChannel()
|
|
19
|
-
const
|
|
20
|
-
const
|
|
27
|
+
const { port1: clientPort, port2: serverPort } = new MessageChannel()
|
|
28
|
+
const opts: ChannelStreamOpts = { idleTimeoutMs: 250, keepAliveMs: 100 }
|
|
29
|
+
const clientChannelStream = new ChannelStream('client', clientPort, opts)
|
|
30
|
+
const serverChannelStream = new ChannelStream('server', serverPort, opts)
|
|
21
31
|
|
|
22
32
|
// Pipe the client traffic via the client end of the MessageChannel.
|
|
23
|
-
pipe(
|
|
33
|
+
pipe(
|
|
34
|
+
clientChannelStream,
|
|
35
|
+
clientConn,
|
|
36
|
+
combineUint8ArrayListTransform(),
|
|
37
|
+
clientChannelStream,
|
|
38
|
+
)
|
|
24
39
|
.catch((err: Error) => clientConn.close(err))
|
|
25
40
|
.then(() => clientConn.close())
|
|
26
41
|
|
|
27
42
|
// Pipe the server traffic via the server end of the MessageChannel.
|
|
28
|
-
pipe(
|
|
43
|
+
pipe(
|
|
44
|
+
serverChannelStream,
|
|
45
|
+
serverConn,
|
|
46
|
+
combineUint8ArrayListTransform(),
|
|
47
|
+
serverChannelStream,
|
|
48
|
+
)
|
|
29
49
|
.catch((err: Error) => serverConn.close(err))
|
|
30
50
|
.then(() => serverConn.close())
|
|
31
51
|
|
package/package.json
CHANGED
package/srpc/channel.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { Sink, Source, Duplex } from 'it-stream-types'
|
|
2
2
|
import { pushable, Pushable } from 'it-pushable'
|
|
3
|
+
import { Watchdog } from './watchdog.js'
|
|
4
|
+
import { ERR_STREAM_IDLE } from './errors.js'
|
|
3
5
|
|
|
4
6
|
// ChannelStreamMessage is a message sent over the stream.
|
|
5
7
|
export interface ChannelStreamMessage<T> {
|
|
@@ -9,9 +11,6 @@ export interface ChannelStreamMessage<T> {
|
|
|
9
11
|
ack?: true
|
|
10
12
|
// opened indicates the remote has opened the stream.
|
|
11
13
|
opened?: true
|
|
12
|
-
// alive indicates this is a keep-alive packet.
|
|
13
|
-
// not set unless keep-alives are enabled.
|
|
14
|
-
alive?: true
|
|
15
14
|
// closed indicates the stream is closed.
|
|
16
15
|
closed?: true
|
|
17
16
|
// error indicates the stream has an error.
|
|
@@ -30,6 +29,12 @@ export interface ChannelStreamOpts {
|
|
|
30
29
|
// remoteOpen indicates that the remote already knows the channel is open.
|
|
31
30
|
// this skips sending and waiting for the open+ack messages.
|
|
32
31
|
remoteOpen?: boolean
|
|
32
|
+
// keepAliveMs is the maximum time between sending before we send a keep-alive.
|
|
33
|
+
// if idleTimeoutMs is set on the remote end, this should be less by some margin.
|
|
34
|
+
keepAliveMs?: number
|
|
35
|
+
// idleTimeoutMs is the maximum time between receiving before we close the stream.
|
|
36
|
+
// if keepAliveMs is set on the remote end, this should be more by some margin.
|
|
37
|
+
idleTimeoutMs?: number
|
|
33
38
|
}
|
|
34
39
|
|
|
35
40
|
// ChannelStream implements a Stream over a BroadcastChannel duplex or MessagePort.
|
|
@@ -67,6 +72,10 @@ export class ChannelStream<T = Uint8Array>
|
|
|
67
72
|
public readonly waitRemoteAck: Promise<void>
|
|
68
73
|
// _remoteAck fulfills the waitRemoteAck promise.
|
|
69
74
|
private _remoteAck?: (err?: Error) => void
|
|
75
|
+
// keepAliveWatchdog is the transmission timeout watchdog.
|
|
76
|
+
private keepAlive?: Watchdog
|
|
77
|
+
// idleWatchdog is the receive timeout watchdog.
|
|
78
|
+
private idleWatchdog?: Watchdog
|
|
70
79
|
|
|
71
80
|
// isAcked checks if the stream is acknowledged by the remote.
|
|
72
81
|
public get isAcked() {
|
|
@@ -80,13 +89,14 @@ export class ChannelStream<T = Uint8Array>
|
|
|
80
89
|
|
|
81
90
|
// remoteOpen indicates that we know the remote has already opened the stream.
|
|
82
91
|
constructor(localId: string, channel: ChannelPort, opts?: ChannelStreamOpts) {
|
|
92
|
+
// initial state
|
|
83
93
|
this.localId = localId
|
|
84
94
|
this.channel = channel
|
|
85
|
-
this.sink = this._createSink()
|
|
86
|
-
|
|
87
95
|
this.localOpen = false
|
|
88
96
|
this.remoteOpen = opts?.remoteOpen ?? false
|
|
89
97
|
this.remoteAck = this.remoteOpen
|
|
98
|
+
|
|
99
|
+
// wire up the promises for remote ack and remote open
|
|
90
100
|
if (this.remoteOpen) {
|
|
91
101
|
this.waitRemoteOpen = Promise.resolve()
|
|
92
102
|
this.waitRemoteAck = Promise.resolve()
|
|
@@ -113,10 +123,15 @@ export class ChannelStream<T = Uint8Array>
|
|
|
113
123
|
this.waitRemoteAck.catch(() => {})
|
|
114
124
|
}
|
|
115
125
|
|
|
126
|
+
// create the sink
|
|
127
|
+
this.sink = this._createSink()
|
|
128
|
+
|
|
129
|
+
// create the pushable source
|
|
116
130
|
const source: Pushable<T> = pushable({ objectMode: true })
|
|
117
131
|
this.source = source
|
|
118
132
|
this._source = source
|
|
119
133
|
|
|
134
|
+
// wire up the message handlers
|
|
120
135
|
const onMessage = this.onMessage.bind(this)
|
|
121
136
|
if (channel instanceof MessagePort) {
|
|
122
137
|
// MessagePort
|
|
@@ -126,6 +141,20 @@ export class ChannelStream<T = Uint8Array>
|
|
|
126
141
|
// BroadcastChannel
|
|
127
142
|
channel.rx.onmessage = onMessage
|
|
128
143
|
}
|
|
144
|
+
|
|
145
|
+
// handle the keep alive or idle timeout opts
|
|
146
|
+
if (opts?.idleTimeoutMs != null) {
|
|
147
|
+
this.idleWatchdog = new Watchdog(opts.idleTimeoutMs, () =>
|
|
148
|
+
this.idleElapsed(),
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
if (opts?.keepAliveMs != null) {
|
|
152
|
+
this.keepAlive = new Watchdog(opts.keepAliveMs, () =>
|
|
153
|
+
this.keepAliveElapsed(),
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// broadcast ack to start the stream
|
|
129
158
|
this.postMessage({ ack: true })
|
|
130
159
|
}
|
|
131
160
|
|
|
@@ -137,6 +166,25 @@ export class ChannelStream<T = Uint8Array>
|
|
|
137
166
|
} else {
|
|
138
167
|
this.channel.tx.postMessage(msg)
|
|
139
168
|
}
|
|
169
|
+
if (!msg.closed) {
|
|
170
|
+
this.keepAlive?.feed()
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// idleElapsed is called if the idle timeout was elapsed.
|
|
175
|
+
private idleElapsed() {
|
|
176
|
+
if (this.idleWatchdog) {
|
|
177
|
+
delete this.idleWatchdog
|
|
178
|
+
this.close(new Error(ERR_STREAM_IDLE))
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// keepAliveElapsed is called if the keep alive timeout was elapsed.
|
|
183
|
+
private keepAliveElapsed() {
|
|
184
|
+
if (this.keepAlive) {
|
|
185
|
+
// send a keep-alive message
|
|
186
|
+
this.postMessage({})
|
|
187
|
+
}
|
|
140
188
|
}
|
|
141
189
|
|
|
142
190
|
// close closes the broadcast channels.
|
|
@@ -156,6 +204,15 @@ export class ChannelStream<T = Uint8Array>
|
|
|
156
204
|
if (!this.remoteAck && this._remoteAck) {
|
|
157
205
|
this._remoteAck(error || new Error('closed'))
|
|
158
206
|
}
|
|
207
|
+
if (this.idleWatchdog) {
|
|
208
|
+
this.idleWatchdog.clear()
|
|
209
|
+
delete this.idleWatchdog
|
|
210
|
+
}
|
|
211
|
+
if (this.keepAlive) {
|
|
212
|
+
this.keepAlive.clear()
|
|
213
|
+
delete this.keepAlive
|
|
214
|
+
}
|
|
215
|
+
this._source.end(error)
|
|
159
216
|
}
|
|
160
217
|
|
|
161
218
|
// onLocalOpened indicates the local side has opened the read stream.
|
|
@@ -209,6 +266,7 @@ export class ChannelStream<T = Uint8Array>
|
|
|
209
266
|
if (!msg || msg.from === this.localId || !msg.from) {
|
|
210
267
|
return
|
|
211
268
|
}
|
|
269
|
+
this.idleWatchdog?.feed()
|
|
212
270
|
if (msg.ack || msg.opened) {
|
|
213
271
|
this.onRemoteAcked()
|
|
214
272
|
}
|
package/srpc/errors.ts
CHANGED
|
@@ -10,6 +10,18 @@ export function isAbortError(err: unknown): boolean {
|
|
|
10
10
|
return message === ERR_RPC_ABORT
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
// ERR_STREAM_IDLE is returned if the stream idle timeout was exceeded.
|
|
14
|
+
export const ERR_STREAM_IDLE = 'ERR_STREAM_IDLE'
|
|
15
|
+
|
|
16
|
+
// isStreamIdleError checks if the error object is ERR_STREAM_IDLE.
|
|
17
|
+
export function isStreamIdleError(err: unknown): boolean {
|
|
18
|
+
if (typeof err !== 'object') {
|
|
19
|
+
return false
|
|
20
|
+
}
|
|
21
|
+
const message = (err as Error).message
|
|
22
|
+
return message === ERR_STREAM_IDLE
|
|
23
|
+
}
|
|
24
|
+
|
|
13
25
|
// castToError casts an object to an Error.
|
|
14
26
|
// if err is a string, uses it as the message.
|
|
15
27
|
// if err is undefined, returns new Error(defaultMsg)
|
package/srpc/index.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {
|
|
2
|
+
ERR_RPC_ABORT,
|
|
3
|
+
isAbortError,
|
|
4
|
+
ERR_STREAM_IDLE,
|
|
5
|
+
isStreamIdleError,
|
|
6
|
+
castToError,
|
|
7
|
+
} from './errors.js'
|
|
2
8
|
export { Client } from './client.js'
|
|
3
9
|
export { Server } from './server.js'
|
|
4
10
|
export { StreamConn, StreamConnParams, StreamHandler } from './conn.js'
|
|
@@ -23,6 +29,7 @@ export {
|
|
|
23
29
|
ChannelStreamMessage,
|
|
24
30
|
ChannelPort,
|
|
25
31
|
ChannelStream,
|
|
32
|
+
ChannelStreamOpts,
|
|
26
33
|
newBroadcastChannelStream,
|
|
27
34
|
} from './channel.js'
|
|
28
35
|
export {
|
|
@@ -61,3 +68,4 @@ export { combineUint8ArrayListTransform } from './array-list.js'
|
|
|
61
68
|
export { ValueCtr } from './value-ctr.js'
|
|
62
69
|
export { OpenStreamCtr } from './open-stream-ctr.js'
|
|
63
70
|
export { writeToPushable, buildPushableSink } from './pushable.js'
|
|
71
|
+
export { Watchdog } from './watchdog.js'
|
package/srpc/watchdog.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Watchdog must be fed every timeoutDuration or it will call the expired callback.
|
|
2
|
+
export class Watchdog {
|
|
3
|
+
private timeoutDuration: number
|
|
4
|
+
private expiredCallback: () => void
|
|
5
|
+
private timerId: NodeJS.Timeout | null = null
|
|
6
|
+
private lastFeedTimestamp: number | null = null
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Constructs a Watchdog instance.
|
|
10
|
+
* The Watchdog will not start ticking until feed() is called.
|
|
11
|
+
* @param timeoutDuration The duration in milliseconds after which the watchdog should expire if not fed.
|
|
12
|
+
* @param expiredCallback The callback function to be called when the watchdog expires.
|
|
13
|
+
*/
|
|
14
|
+
constructor(timeoutDuration: number, expiredCallback: () => void) {
|
|
15
|
+
this.timeoutDuration = timeoutDuration
|
|
16
|
+
this.expiredCallback = expiredCallback
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Feeds the watchdog, preventing it from expiring.
|
|
21
|
+
* This resets the timeout and reschedules the next tick.
|
|
22
|
+
*/
|
|
23
|
+
public feed(): void {
|
|
24
|
+
this.lastFeedTimestamp = Date.now()
|
|
25
|
+
this.scheduleTickWatchdog(this.timeoutDuration)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Clears the current timeout, effectively stopping the watchdog.
|
|
30
|
+
* This prevents the expired callback from being called until the watchdog is fed again.
|
|
31
|
+
*/
|
|
32
|
+
public clear(): void {
|
|
33
|
+
if (this.timerId != null) {
|
|
34
|
+
clearTimeout(this.timerId)
|
|
35
|
+
this.timerId = null
|
|
36
|
+
}
|
|
37
|
+
this.lastFeedTimestamp = null
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Schedules the next tick of the watchdog.
|
|
42
|
+
* This method calculates the delay for the next tick based on the last feed time
|
|
43
|
+
* and schedules a call to tickWatchdog after that delay.
|
|
44
|
+
*/
|
|
45
|
+
private scheduleTickWatchdog(delay: number): void {
|
|
46
|
+
if (this.timerId != null) {
|
|
47
|
+
clearTimeout(this.timerId)
|
|
48
|
+
}
|
|
49
|
+
this.timerId = setTimeout(() => this.tickWatchdog(), delay)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Handler for the watchdog tick.
|
|
54
|
+
* Checks if the time since the last feed is greater than the timeout duration.
|
|
55
|
+
* If so, it calls the expired callback. Otherwise, it reschedules the tick.
|
|
56
|
+
*/
|
|
57
|
+
private tickWatchdog(): void {
|
|
58
|
+
this.timerId = null
|
|
59
|
+
if (this.lastFeedTimestamp == null) {
|
|
60
|
+
this.expiredCallback()
|
|
61
|
+
return
|
|
62
|
+
}
|
|
63
|
+
const elapsedSinceLastFeed = Date.now() - this.lastFeedTimestamp
|
|
64
|
+
if (elapsedSinceLastFeed >= this.timeoutDuration) {
|
|
65
|
+
this.expiredCallback()
|
|
66
|
+
} else {
|
|
67
|
+
this.scheduleTickWatchdog(this.timeoutDuration - elapsedSinceLastFeed)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|