@actuallab/rpc 12.3.14 → 12.3.29

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/index.d.cts CHANGED
@@ -440,7 +440,26 @@ declare class RpcOutboundCall {
440
440
  readonly removeOnOk: boolean;
441
441
  /** The serialized wire data — stored for re-sending on reconnect. */
442
442
  serializedWireData: string | Uint8Array;
443
+ /**
444
+ * Bitfield of {@link RpcCallStage} flags indicating how far this call
445
+ * has progressed. Used by the `$sys.Reconnect` protocol to tell the
446
+ * remote peer which calls are still pending its attention.
447
+ *
448
+ * - 0: brand new, no result yet (the peer is expected to be actively processing).
449
+ * - `ResultReady` (1): `$sys.Ok` received for this call.
450
+ * - `Invalidated` (3): result was invalidated (compute calls only).
451
+ * - `Unregistered` (0x1000): removed from the tracker.
452
+ */
453
+ completedStage: number;
443
454
  constructor(callId: number, method: string, remoteExecutionMode?: number);
455
+ /**
456
+ * Returns the stage to report to the remote peer via `$sys.Reconnect`,
457
+ * or `null` if this call should not be reconciled and must be aborted.
458
+ *
459
+ * Mirrors .NET `RpcOutboundCall.GetReconnectStage` at
460
+ * src/ActualLab.Rpc/Infrastructure/RpcOutboundCall.cs.
461
+ */
462
+ getReconnectStage(isPeerChanged: boolean): number | null;
444
463
  /** Called when the connection is lost. Subclasses can override to resolve invalidation promises. */
445
464
  onDisconnect(): void;
446
465
  }
@@ -479,6 +498,55 @@ declare class RpcInboundCallTracker {
479
498
  clear(): void;
480
499
  }
481
500
 
501
+ /**
502
+ * Well-known RPC call completion stage constants, used by the
503
+ * `$sys.Reconnect` protocol to tell the peer which calls have already
504
+ * reached which stage and therefore don't need to be re-processed.
505
+ *
506
+ * Direct port of .NET `ActualLab.Rpc.Infrastructure.RpcCallStage` at
507
+ * src/ActualLab.Rpc/Infrastructure/RpcCallStage.cs.
508
+ */
509
+ declare const RpcCallStage: {
510
+ /** The call's result has been received from the peer. */
511
+ readonly ResultReady: 1;
512
+ /** The compute call's result has been invalidated (compute-call specific). */
513
+ readonly Invalidated: 3;
514
+ /**
515
+ * Bit flag added on top of ResultReady/Invalidated when the outbound
516
+ * call has been removed from the tracker (unregistered).
517
+ */
518
+ readonly Unregistered: 4096;
519
+ };
520
+ type RpcCallStage = number;
521
+
522
+ /**
523
+ * Compresses and decompresses monotonically increasing sequences of
524
+ * integers using variable-length LEB128 encoding of successive deltas.
525
+ *
526
+ * Wire-compatible with .NET `ActualLab.Rpc.Internal.IncreasingSeqCompressor`
527
+ * (src/ActualLab.Rpc/Internal/IncreasingSeqCompressor.cs) — which
528
+ * underlies the `$sys.Reconnect` protocol.
529
+ *
530
+ * Inputs MUST be sorted non-decreasing. Maximum supported value is
531
+ * 2^53 - 1 (JavaScript `Number` safe-integer limit); call IDs in TS
532
+ * never exceed this because they're generated from a 32-bit counter.
533
+ */
534
+ declare const IncreasingSeqCompressor: {
535
+ /**
536
+ * Serialize a non-decreasing sequence of non-negative integers as
537
+ * LEB128-encoded deltas.
538
+ *
539
+ * Throws `RangeError` if the input is not monotonically non-decreasing,
540
+ * or if a value exceeds `Number.MAX_SAFE_INTEGER`.
541
+ */
542
+ readonly serialize: (values: Iterable<number>) => Uint8Array;
543
+ /**
544
+ * Decode bytes produced by {@link serialize} back into the original
545
+ * sorted sequence of non-negative integers.
546
+ */
547
+ readonly deserialize: (data: Uint8Array) => number[];
548
+ };
549
+
482
550
  declare class RpcClientPeerReconnectDelayer extends RetryDelayer {
483
551
  constructor();
484
552
  }
@@ -686,8 +754,14 @@ declare abstract class RpcPeer {
686
754
  get connection(): RpcConnection | undefined;
687
755
  get isConnected(): boolean;
688
756
  protected setupConnection(conn: RpcConnection): void;
689
- /** The serialization format used by this peer. Override in subclasses. */
757
+ /**
758
+ * The serialization format used by this peer for outgoing messages.
759
+ * If not set explicitly, defaults to the resolver's default (JSON /
760
+ * json5np). Subclasses can pre-assign in their constructor.
761
+ */
762
+ private _format;
690
763
  get format(): RpcSerializationFormat;
764
+ set format(value: RpcSerializationFormat);
691
765
  call(method: string, args?: unknown[], options?: RpcCallOptions): RpcOutboundCall;
692
766
  callNoWait(method: string, args?: unknown[]): void;
693
767
  close(): void;
@@ -714,6 +788,12 @@ declare class RpcClientPeer extends RpcPeer {
714
788
  private _connectionKind;
715
789
  private _tryIndex;
716
790
  private _handshakeIndex;
791
+ /** Index from the MOST RECENTLY RECEIVED server handshake — sent back
792
+ * to the server in `$sys.Reconnect:3` so the server can verify we're
793
+ * talking about the current connection. Mirrors .NET's
794
+ * `connectionState.Handshake.Index` path in
795
+ * `RpcOutboundCallTracker.TryReconnect`. */
796
+ private _remoteHandshakeIndex;
717
797
  private _lastRemoteHubId;
718
798
  private _pendingHandshake;
719
799
  private _reconnectsAt;
@@ -736,22 +816,50 @@ declare class RpcClientPeer extends RpcPeer {
736
816
  readonly reconnectsAtChanged: EventHandlerSet<void>;
737
817
  get reconnectsAt(): number;
738
818
  private _setReconnectsAt;
739
- private _format;
740
819
  constructor(hub: RpcHub, url: string, serializationFormat?: string);
741
- get format(): RpcSerializationFormat;
742
820
  get connectionKind(): RpcPeerConnectionKind;
743
- /** One-shot connection for tests — no reconnection loop, no handshake. */
744
- connectWith(conn: RpcConnection): void;
821
+ /** One-shot connection for tests — no reconnection loop, no handshake.
822
+ * @param isPeerChanged Whether to treat this as a peer-identity change
823
+ * (default `true` — no handshake was exchanged, so stage-3 compute calls
824
+ * self-invalidate and remote/shared objects are disposed). Pass `false`
825
+ * to simulate a same-peer reconnect in tests. */
826
+ connectWith(conn: RpcConnection, isPeerChanged?: boolean): void;
745
827
  /** Start the reconnection loop — runs until disposed. */
746
828
  run(wsFactory?: (url: string) => WebSocketLike): Promise<void>;
747
- /** Re-send outbound calls after reconnection + flush pending sends.
748
- * Stage-3 compute calls are always self-invalidated: without $sys.Reconnect
749
- * protocol, the server's invalidation tracking is lost on disconnect, and
750
- * re-sending would get a duplicate $sys.Ok that is ignored (PromiseSource
751
- * already resolved). Self-invalidation forces a fresh recompute that
752
- * establishes new invalidation tracking on the new connection.
753
- * Regular in-flight calls are re-sent transparently. */
829
+ /**
830
+ * Reconcile outbound calls after reconnection, then flush pending sends.
831
+ *
832
+ * On peer change (different server hubId) or with binary wire format —
833
+ * we blind-resend every eligible call.
834
+ *
835
+ * On a same-peer reconnect with JSON transport, first call
836
+ * `$sys.Reconnect` to ask the server which call IDs it no longer
837
+ * recognizes (e.g. inbound tracker was cleared, or the call never
838
+ * reached the server). Only those get resent; the rest stay in the
839
+ * tracker awaiting their $sys.Ok. This prevents duplicate server-side
840
+ * invocation of in-flight streaming calls on every transient
841
+ * reconnect — mirrors .NET `RpcOutboundCallTracker.Reconnect` at
842
+ * src/ActualLab.Rpc/Infrastructure/RpcCallTrackers.cs:209-279.
843
+ *
844
+ * Stage-3 compute calls (result already resolved, awaiting invalidation)
845
+ * are always self-invalidated — TS doesn't track compute-call stages
846
+ * across reconnect, so the safest behavior is to force a fresh compute.
847
+ */
754
848
  private _reconnect;
849
+ /**
850
+ * Ask the server which call IDs in `eligible` it no longer recognizes
851
+ * via `$sys.Reconnect:3`. Returns the set of call IDs that need to be
852
+ * resent. On any failure, falls back to "resend everything".
853
+ *
854
+ * Wire format of the `completedStages` argument is chosen per wire format:
855
+ * - JSON (json5np): plain object `{"<stage>": "<base64-of-bytes>"}` —
856
+ * matches .NET `System.Text.Json`'s default for `Dictionary<int, byte[]>`.
857
+ * - MessagePack (msgpack6/msgpack6c): `Map<number, Uint8Array>` —
858
+ * the patched encoder (see `./msgpack-map-patch.ts`) writes this as a
859
+ * native msgpack `map<int, bin>`, matching .NET MessagePack-CSharp's
860
+ * default for `Dictionary<int, byte[]>`.
861
+ */
862
+ private _reconcileReconnect;
755
863
  protected _onHandshakeReceived(handshake: RemoteHandshake): void;
756
864
  close(): void;
757
865
  }
@@ -766,6 +874,18 @@ declare class RpcServerPeer extends RpcPeer {
766
874
  /** Handles incoming system call messages — class-based equivalent of the former standalone function. */
767
875
  declare class RpcSystemCallHandler {
768
876
  handle(message: RpcMessage, args: unknown[], peer: RpcPeer): void;
877
+ /**
878
+ * Server-side handler for the `$sys.Reconnect` call. Parses the peer's
879
+ * report of in-flight call IDs (grouped by stage, IncreasingSeqCompressor-
880
+ * encoded, base64-wrapped for JSON transport), computes the subset this
881
+ * peer does not recognize, and replies with a compressed byte[] of the
882
+ * unknown IDs wrapped in `$sys.Ok`.
883
+ *
884
+ * @param relatedId The outbound call ID the client used for this
885
+ * `$sys.Reconnect` invocation — we send `$sys.Ok` back
886
+ * with the same `RelatedId`.
887
+ */
888
+ private _handleReconnect;
769
889
  }
770
890
 
771
891
  /** Parsed stream reference from the server's result payload. */
@@ -810,6 +930,15 @@ declare function parseStreamRef(value: unknown): RpcStreamRef | null;
810
930
  * This mirrors the .NET RpcStream<T> design where the same type serves both roles.
811
931
  */
812
932
  declare class RpcStream<T> implements AsyncIterable<T>, IRpcObject {
933
+ /**
934
+ * Grace period (ms) given to a factory-form local source to honor its
935
+ * AbortSignal and exit naturally before the sender force-closes the
936
+ * iterator via `iterator.return()`.
937
+ *
938
+ * Only applies to sources provided as `(abortSignal) => AsyncIterable<T>`.
939
+ * Plain `AsyncIterable<T>` sources are force-closed immediately on disconnect.
940
+ */
941
+ static disconnectGracePeriodMs: number;
813
942
  readonly id: RpcObjectId;
814
943
  readonly kind: RpcObjectKind;
815
944
  readonly allowReconnect: boolean;
@@ -887,6 +1016,17 @@ declare function resolveStreamRefs(value: unknown, peer: RpcPeer): unknown;
887
1016
  * - Client acks every ackPeriod items for flow control
888
1017
  * - Server sends End to signal completion (with optional error)
889
1018
  * - Client sends AckEnd to acknowledge completion
1019
+ *
1020
+ * The pump is ACK-driven: the main loop blocks on `_whenAckReady` until a
1021
+ * client ACK is queued, processes it (updating `_lastAckedIndex`, rewinding
1022
+ * `_index` on mustReset, trimming the replay buffer), then sends items up
1023
+ * to `ack.nextIndex + ackAdvance`. While the peer is disconnected no ACKs
1024
+ * arrive, so the source is never pulled — the sender naturally pauses
1025
+ * instead of spinning.
1026
+ *
1027
+ * Direct port of .NET `RpcSharedStream<T>` at
1028
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs — including the
1029
+ * separate non-real-time / real-time pump variants.
890
1030
  */
891
1031
  declare class RpcStreamSender<T> implements IRpcObject {
892
1032
  private static readonly _emptyGuid;
@@ -898,43 +1038,83 @@ declare class RpcStreamSender<T> implements IRpcObject {
898
1038
  readonly peer: RpcPeer;
899
1039
  readonly ackPeriod: number;
900
1040
  readonly ackAdvance: number;
1041
+ /**
1042
+ * If true, the source was produced by a factory `(abortSignal) => AsyncIterable<T>`
1043
+ * and may honor the AbortSignal to exit gracefully. `disconnect()` first aborts
1044
+ * the signal and gives the source up to `RpcStream.disconnectGracePeriodMs` ms
1045
+ * before force-closing via `iterator.return()`.
1046
+ *
1047
+ * If false, the source is a plain AsyncIterable that cannot observe the signal,
1048
+ * so `disconnect()` force-closes immediately.
1049
+ */
1050
+ readonly sourceUsesAbortSignal: boolean;
1051
+ /** Next stream index that will be sent (matches .NET's `index`). */
901
1052
  private _nextIndex;
902
1053
  private _ended;
903
1054
  private _started;
1055
+ /** Highest `nextIndex` observed in an ACK so far (matches .NET's `lastAckNextIndex` idiom). */
904
1056
  private _lastAckedIndex;
905
- private _ackWaiting;
906
- private _resetRequested;
907
1057
  private _abortController;
908
1058
  private _iterator;
909
- constructor(peer: RpcPeer, ackPeriod?: number, ackAdvance?: number, allowReconnect?: boolean, isRealTime?: boolean, canSkipTo?: (item: T) => boolean);
1059
+ private _acks;
1060
+ private _whenAckReady;
1061
+ constructor(peer: RpcPeer, ackPeriod?: number, ackAdvance?: number, allowReconnect?: boolean, isRealTime?: boolean, canSkipTo?: (item: T) => boolean, sourceUsesAbortSignal?: boolean);
910
1062
  /** AbortSignal that is aborted when the sender is disconnected. */
911
1063
  get abortSignal(): AbortSignal;
912
1064
  /** Returns the stream reference string for the $sys.Ok response. */
913
1065
  toRef(): string;
914
- /** Called by system call handler when $sys.Ack is received from the client. */
1066
+ /**
1067
+ * Called by system call handler when $sys.Ack is received from the client.
1068
+ *
1069
+ * Mirrors .NET `RpcSharedStream<T>.OnAck` at
1070
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:68-101.
1071
+ */
915
1072
  onAck(nextIndex: number, hostId: string): void;
916
1073
  /** Called by system call handler when $sys.AckEnd is received from the client. */
917
1074
  onAckEnd(_hostId: string): void;
918
- /** Send a single item to the client. */
1075
+ /**
1076
+ * Send a single item to the client at the current `_nextIndex`.
1077
+ *
1078
+ * Advances `_nextIndex` unconditionally — even if the peer is disconnected
1079
+ * the item is considered "sent" from the pump's perspective so the replay
1080
+ * buffer indexing stays consistent. If a connection is absent, the wire
1081
+ * message is dropped; the item will be resent from the replay buffer
1082
+ * after a reconnect (client sends `Ack(N, mustReset=true)`).
1083
+ */
919
1084
  sendItem(item: T): void;
920
- /** Send a batch of items to the client. */
1085
+ /** Send a batch of items to the client. See {@link sendItem} for disconnect semantics. */
921
1086
  sendBatch(items: T[]): void;
922
1087
  /** Signal stream completion to the client. */
923
1088
  sendEnd(error?: Error | null): void;
924
1089
  /**
925
1090
  * Consume an AsyncIterable and send all items to the client.
926
- * Waits for the client's initial Ack before starting to pump items.
927
1091
  *
928
- * When `isRealTime` is true, applies flow control based on `ackAdvance`:
929
- * if the sender is `ackAdvance` items ahead of the last ACK, it enters
930
- * skip mode — draining the source and discarding items until it finds
931
- * one where `canSkipTo` returns true.
1092
+ * Dispatches to the non-real-time or real-time pump, matching .NET
1093
+ * `RpcSharedStream<T>.OnRun` at
1094
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:105-108.
932
1095
  */
933
1096
  writeFrom(source: AsyncIterable<T>): Promise<void>;
934
- /** Wait until _nextIndex < _lastAckedIndex + ackAdvance. */
935
- private _waitForAckBudget;
1097
+ /**
1098
+ * Non-real-time pump — back-pressure through buffered ACKs.
1099
+ *
1100
+ * Direct port of .NET `OnRunNonRealTime` at
1101
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:110-217.
1102
+ */
1103
+ private _runNonRealTime;
1104
+ /**
1105
+ * Real-time pump — drops stale items to stay close to the source's head.
1106
+ *
1107
+ * Direct port of .NET `OnRunRealTime` at
1108
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:219-420.
1109
+ */
1110
+ private _runRealTime;
1111
+ /** Drain all queued ACKs, returning the most recent one (or null if none). */
1112
+ private _tryProcessAcks;
1113
+ /** Wait for the ACK queue to have at least one entry (or `_ended`). */
1114
+ private _waitAckReady;
936
1115
  reconnect(): void;
937
1116
  disconnect(): void;
1117
+ private _forceCloseIterator;
938
1118
  }
939
1119
 
940
1120
  /** Creates a typed RPC client proxy — intercepts method calls and sends them over RPC. */
@@ -1002,4 +1182,4 @@ declare function xxh3_64str(input: string, seed?: bigint): bigint;
1002
1182
  */
1003
1183
  declare function computeMethodHash(methodName: string): number;
1004
1184
 
1005
- export { ARG_DELIMITER, ENVELOPE_DELIMITER, FRAME_DELIMITER, type IRpcObject, type MethodMeta, RPC_CLOSE_CODE_UNSUPPORTED_FORMAT, type RemoteHandshake, type RpcCallOptions, RpcCallTypeId, RpcClientPeer, RpcClientPeerReconnectDelayer, type RpcConnection, type RpcConnectionUrlResolver, type RpcDeserializedMessage, type RpcDispatchContext, RpcHub, RpcInboundCall, RpcInboundCallTracker, RpcJsonSerializationFormat, type RpcMessage, RpcMessageChannelConnection, RpcMessagePackCompactSerializationFormat, RpcMessagePackSerializationFormat, type RpcMethodDef, type RpcMethodDefInput, RpcMethodRegistry, type RpcObjectId, RpcObjectKind, RpcOutboundCall, RpcOutboundCallTracker, RpcPeer, RpcPeerConnectionKind, type RpcPeerState, RpcPeerStateKind, RpcPeerStateMonitor, type RpcReceivedMessage, RpcRemoteExecutionMode, RpcRemoteObjectTracker, RpcSerializationFormat, RpcSerializationFormatResolver, RpcServerPeer, type RpcServiceDef, RpcServiceHost, type RpcServiceImpl, RpcSharedObjectTracker, RpcStream, type RpcStreamOptions, type RpcStreamRef, RpcStreamSender, type RpcStreamSource, RpcSystemCallHandler, RpcSystemCallSender, RpcSystemCalls, RpcType, RpcWebSocketConnection, type RpcWireData, type ServiceMeta, type WebSocketLike, type WebSocketServer, WebSocketState, computeMethodHash, createBinaryEncoder, createMessageChannelPair, createRpcClient, defaultBinaryDecoder, defaultBinaryEncoder, defaultConnectionUrlResolver, defineRpcService, deserializeBinaryMessage, deserializeCompactBinaryMessage, deserializeMessage, getMethodsMeta, getServiceMeta, getStateDescription, isConnected, likelyConnected, parseStreamRef, resolveStreamRefs, rpcMethod, rpcService, serializeBinaryFrame, serializeBinaryMessage, serializeCompactBinaryMessage, serializeFrame, serializeMessage, splitBinaryFrame, splitCompactBinaryFrame, splitFrame, wireMethodName, xxh3_64, xxh3_64str };
1185
+ export { ARG_DELIMITER, ENVELOPE_DELIMITER, FRAME_DELIMITER, type IRpcObject, IncreasingSeqCompressor, type MethodMeta, RPC_CLOSE_CODE_UNSUPPORTED_FORMAT, type RemoteHandshake, type RpcCallOptions, RpcCallStage, RpcCallTypeId, RpcClientPeer, RpcClientPeerReconnectDelayer, type RpcConnection, type RpcConnectionUrlResolver, type RpcDeserializedMessage, type RpcDispatchContext, RpcHub, RpcInboundCall, RpcInboundCallTracker, RpcJsonSerializationFormat, type RpcMessage, RpcMessageChannelConnection, RpcMessagePackCompactSerializationFormat, RpcMessagePackSerializationFormat, type RpcMethodDef, type RpcMethodDefInput, RpcMethodRegistry, type RpcObjectId, RpcObjectKind, RpcOutboundCall, RpcOutboundCallTracker, RpcPeer, RpcPeerConnectionKind, type RpcPeerState, RpcPeerStateKind, RpcPeerStateMonitor, type RpcReceivedMessage, RpcRemoteExecutionMode, RpcRemoteObjectTracker, RpcSerializationFormat, RpcSerializationFormatResolver, RpcServerPeer, type RpcServiceDef, RpcServiceHost, type RpcServiceImpl, RpcSharedObjectTracker, RpcStream, type RpcStreamOptions, type RpcStreamRef, RpcStreamSender, type RpcStreamSource, RpcSystemCallHandler, RpcSystemCallSender, RpcSystemCalls, RpcType, RpcWebSocketConnection, type RpcWireData, type ServiceMeta, type WebSocketLike, type WebSocketServer, WebSocketState, computeMethodHash, createBinaryEncoder, createMessageChannelPair, createRpcClient, defaultBinaryDecoder, defaultBinaryEncoder, defaultConnectionUrlResolver, defineRpcService, deserializeBinaryMessage, deserializeCompactBinaryMessage, deserializeMessage, getMethodsMeta, getServiceMeta, getStateDescription, isConnected, likelyConnected, parseStreamRef, resolveStreamRefs, rpcMethod, rpcService, serializeBinaryFrame, serializeBinaryMessage, serializeCompactBinaryMessage, serializeFrame, serializeMessage, splitBinaryFrame, splitCompactBinaryFrame, splitFrame, wireMethodName, xxh3_64, xxh3_64str };
package/dist/index.d.ts CHANGED
@@ -440,7 +440,26 @@ declare class RpcOutboundCall {
440
440
  readonly removeOnOk: boolean;
441
441
  /** The serialized wire data — stored for re-sending on reconnect. */
442
442
  serializedWireData: string | Uint8Array;
443
+ /**
444
+ * Bitfield of {@link RpcCallStage} flags indicating how far this call
445
+ * has progressed. Used by the `$sys.Reconnect` protocol to tell the
446
+ * remote peer which calls are still pending its attention.
447
+ *
448
+ * - 0: brand new, no result yet (the peer is expected to be actively processing).
449
+ * - `ResultReady` (1): `$sys.Ok` received for this call.
450
+ * - `Invalidated` (3): result was invalidated (compute calls only).
451
+ * - `Unregistered` (0x1000): removed from the tracker.
452
+ */
453
+ completedStage: number;
443
454
  constructor(callId: number, method: string, remoteExecutionMode?: number);
455
+ /**
456
+ * Returns the stage to report to the remote peer via `$sys.Reconnect`,
457
+ * or `null` if this call should not be reconciled and must be aborted.
458
+ *
459
+ * Mirrors .NET `RpcOutboundCall.GetReconnectStage` at
460
+ * src/ActualLab.Rpc/Infrastructure/RpcOutboundCall.cs.
461
+ */
462
+ getReconnectStage(isPeerChanged: boolean): number | null;
444
463
  /** Called when the connection is lost. Subclasses can override to resolve invalidation promises. */
445
464
  onDisconnect(): void;
446
465
  }
@@ -479,6 +498,55 @@ declare class RpcInboundCallTracker {
479
498
  clear(): void;
480
499
  }
481
500
 
501
+ /**
502
+ * Well-known RPC call completion stage constants, used by the
503
+ * `$sys.Reconnect` protocol to tell the peer which calls have already
504
+ * reached which stage and therefore don't need to be re-processed.
505
+ *
506
+ * Direct port of .NET `ActualLab.Rpc.Infrastructure.RpcCallStage` at
507
+ * src/ActualLab.Rpc/Infrastructure/RpcCallStage.cs.
508
+ */
509
+ declare const RpcCallStage: {
510
+ /** The call's result has been received from the peer. */
511
+ readonly ResultReady: 1;
512
+ /** The compute call's result has been invalidated (compute-call specific). */
513
+ readonly Invalidated: 3;
514
+ /**
515
+ * Bit flag added on top of ResultReady/Invalidated when the outbound
516
+ * call has been removed from the tracker (unregistered).
517
+ */
518
+ readonly Unregistered: 4096;
519
+ };
520
+ type RpcCallStage = number;
521
+
522
+ /**
523
+ * Compresses and decompresses monotonically increasing sequences of
524
+ * integers using variable-length LEB128 encoding of successive deltas.
525
+ *
526
+ * Wire-compatible with .NET `ActualLab.Rpc.Internal.IncreasingSeqCompressor`
527
+ * (src/ActualLab.Rpc/Internal/IncreasingSeqCompressor.cs) — which
528
+ * underlies the `$sys.Reconnect` protocol.
529
+ *
530
+ * Inputs MUST be sorted non-decreasing. Maximum supported value is
531
+ * 2^53 - 1 (JavaScript `Number` safe-integer limit); call IDs in TS
532
+ * never exceed this because they're generated from a 32-bit counter.
533
+ */
534
+ declare const IncreasingSeqCompressor: {
535
+ /**
536
+ * Serialize a non-decreasing sequence of non-negative integers as
537
+ * LEB128-encoded deltas.
538
+ *
539
+ * Throws `RangeError` if the input is not monotonically non-decreasing,
540
+ * or if a value exceeds `Number.MAX_SAFE_INTEGER`.
541
+ */
542
+ readonly serialize: (values: Iterable<number>) => Uint8Array;
543
+ /**
544
+ * Decode bytes produced by {@link serialize} back into the original
545
+ * sorted sequence of non-negative integers.
546
+ */
547
+ readonly deserialize: (data: Uint8Array) => number[];
548
+ };
549
+
482
550
  declare class RpcClientPeerReconnectDelayer extends RetryDelayer {
483
551
  constructor();
484
552
  }
@@ -686,8 +754,14 @@ declare abstract class RpcPeer {
686
754
  get connection(): RpcConnection | undefined;
687
755
  get isConnected(): boolean;
688
756
  protected setupConnection(conn: RpcConnection): void;
689
- /** The serialization format used by this peer. Override in subclasses. */
757
+ /**
758
+ * The serialization format used by this peer for outgoing messages.
759
+ * If not set explicitly, defaults to the resolver's default (JSON /
760
+ * json5np). Subclasses can pre-assign in their constructor.
761
+ */
762
+ private _format;
690
763
  get format(): RpcSerializationFormat;
764
+ set format(value: RpcSerializationFormat);
691
765
  call(method: string, args?: unknown[], options?: RpcCallOptions): RpcOutboundCall;
692
766
  callNoWait(method: string, args?: unknown[]): void;
693
767
  close(): void;
@@ -714,6 +788,12 @@ declare class RpcClientPeer extends RpcPeer {
714
788
  private _connectionKind;
715
789
  private _tryIndex;
716
790
  private _handshakeIndex;
791
+ /** Index from the MOST RECENTLY RECEIVED server handshake — sent back
792
+ * to the server in `$sys.Reconnect:3` so the server can verify we're
793
+ * talking about the current connection. Mirrors .NET's
794
+ * `connectionState.Handshake.Index` path in
795
+ * `RpcOutboundCallTracker.TryReconnect`. */
796
+ private _remoteHandshakeIndex;
717
797
  private _lastRemoteHubId;
718
798
  private _pendingHandshake;
719
799
  private _reconnectsAt;
@@ -736,22 +816,50 @@ declare class RpcClientPeer extends RpcPeer {
736
816
  readonly reconnectsAtChanged: EventHandlerSet<void>;
737
817
  get reconnectsAt(): number;
738
818
  private _setReconnectsAt;
739
- private _format;
740
819
  constructor(hub: RpcHub, url: string, serializationFormat?: string);
741
- get format(): RpcSerializationFormat;
742
820
  get connectionKind(): RpcPeerConnectionKind;
743
- /** One-shot connection for tests — no reconnection loop, no handshake. */
744
- connectWith(conn: RpcConnection): void;
821
+ /** One-shot connection for tests — no reconnection loop, no handshake.
822
+ * @param isPeerChanged Whether to treat this as a peer-identity change
823
+ * (default `true` — no handshake was exchanged, so stage-3 compute calls
824
+ * self-invalidate and remote/shared objects are disposed). Pass `false`
825
+ * to simulate a same-peer reconnect in tests. */
826
+ connectWith(conn: RpcConnection, isPeerChanged?: boolean): void;
745
827
  /** Start the reconnection loop — runs until disposed. */
746
828
  run(wsFactory?: (url: string) => WebSocketLike): Promise<void>;
747
- /** Re-send outbound calls after reconnection + flush pending sends.
748
- * Stage-3 compute calls are always self-invalidated: without $sys.Reconnect
749
- * protocol, the server's invalidation tracking is lost on disconnect, and
750
- * re-sending would get a duplicate $sys.Ok that is ignored (PromiseSource
751
- * already resolved). Self-invalidation forces a fresh recompute that
752
- * establishes new invalidation tracking on the new connection.
753
- * Regular in-flight calls are re-sent transparently. */
829
+ /**
830
+ * Reconcile outbound calls after reconnection, then flush pending sends.
831
+ *
832
+ * On peer change (different server hubId) or with binary wire format —
833
+ * we blind-resend every eligible call.
834
+ *
835
+ * On a same-peer reconnect with JSON transport, first call
836
+ * `$sys.Reconnect` to ask the server which call IDs it no longer
837
+ * recognizes (e.g. inbound tracker was cleared, or the call never
838
+ * reached the server). Only those get resent; the rest stay in the
839
+ * tracker awaiting their $sys.Ok. This prevents duplicate server-side
840
+ * invocation of in-flight streaming calls on every transient
841
+ * reconnect — mirrors .NET `RpcOutboundCallTracker.Reconnect` at
842
+ * src/ActualLab.Rpc/Infrastructure/RpcCallTrackers.cs:209-279.
843
+ *
844
+ * Stage-3 compute calls (result already resolved, awaiting invalidation)
845
+ * are always self-invalidated — TS doesn't track compute-call stages
846
+ * across reconnect, so the safest behavior is to force a fresh compute.
847
+ */
754
848
  private _reconnect;
849
+ /**
850
+ * Ask the server which call IDs in `eligible` it no longer recognizes
851
+ * via `$sys.Reconnect:3`. Returns the set of call IDs that need to be
852
+ * resent. On any failure, falls back to "resend everything".
853
+ *
854
+ * Wire format of the `completedStages` argument is chosen per wire format:
855
+ * - JSON (json5np): plain object `{"<stage>": "<base64-of-bytes>"}` —
856
+ * matches .NET `System.Text.Json`'s default for `Dictionary<int, byte[]>`.
857
+ * - MessagePack (msgpack6/msgpack6c): `Map<number, Uint8Array>` —
858
+ * the patched encoder (see `./msgpack-map-patch.ts`) writes this as a
859
+ * native msgpack `map<int, bin>`, matching .NET MessagePack-CSharp's
860
+ * default for `Dictionary<int, byte[]>`.
861
+ */
862
+ private _reconcileReconnect;
755
863
  protected _onHandshakeReceived(handshake: RemoteHandshake): void;
756
864
  close(): void;
757
865
  }
@@ -766,6 +874,18 @@ declare class RpcServerPeer extends RpcPeer {
766
874
  /** Handles incoming system call messages — class-based equivalent of the former standalone function. */
767
875
  declare class RpcSystemCallHandler {
768
876
  handle(message: RpcMessage, args: unknown[], peer: RpcPeer): void;
877
+ /**
878
+ * Server-side handler for the `$sys.Reconnect` call. Parses the peer's
879
+ * report of in-flight call IDs (grouped by stage, IncreasingSeqCompressor-
880
+ * encoded, base64-wrapped for JSON transport), computes the subset this
881
+ * peer does not recognize, and replies with a compressed byte[] of the
882
+ * unknown IDs wrapped in `$sys.Ok`.
883
+ *
884
+ * @param relatedId The outbound call ID the client used for this
885
+ * `$sys.Reconnect` invocation — we send `$sys.Ok` back
886
+ * with the same `RelatedId`.
887
+ */
888
+ private _handleReconnect;
769
889
  }
770
890
 
771
891
  /** Parsed stream reference from the server's result payload. */
@@ -810,6 +930,15 @@ declare function parseStreamRef(value: unknown): RpcStreamRef | null;
810
930
  * This mirrors the .NET RpcStream<T> design where the same type serves both roles.
811
931
  */
812
932
  declare class RpcStream<T> implements AsyncIterable<T>, IRpcObject {
933
+ /**
934
+ * Grace period (ms) given to a factory-form local source to honor its
935
+ * AbortSignal and exit naturally before the sender force-closes the
936
+ * iterator via `iterator.return()`.
937
+ *
938
+ * Only applies to sources provided as `(abortSignal) => AsyncIterable<T>`.
939
+ * Plain `AsyncIterable<T>` sources are force-closed immediately on disconnect.
940
+ */
941
+ static disconnectGracePeriodMs: number;
813
942
  readonly id: RpcObjectId;
814
943
  readonly kind: RpcObjectKind;
815
944
  readonly allowReconnect: boolean;
@@ -887,6 +1016,17 @@ declare function resolveStreamRefs(value: unknown, peer: RpcPeer): unknown;
887
1016
  * - Client acks every ackPeriod items for flow control
888
1017
  * - Server sends End to signal completion (with optional error)
889
1018
  * - Client sends AckEnd to acknowledge completion
1019
+ *
1020
+ * The pump is ACK-driven: the main loop blocks on `_whenAckReady` until a
1021
+ * client ACK is queued, processes it (updating `_lastAckedIndex`, rewinding
1022
+ * `_index` on mustReset, trimming the replay buffer), then sends items up
1023
+ * to `ack.nextIndex + ackAdvance`. While the peer is disconnected no ACKs
1024
+ * arrive, so the source is never pulled — the sender naturally pauses
1025
+ * instead of spinning.
1026
+ *
1027
+ * Direct port of .NET `RpcSharedStream<T>` at
1028
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs — including the
1029
+ * separate non-real-time / real-time pump variants.
890
1030
  */
891
1031
  declare class RpcStreamSender<T> implements IRpcObject {
892
1032
  private static readonly _emptyGuid;
@@ -898,43 +1038,83 @@ declare class RpcStreamSender<T> implements IRpcObject {
898
1038
  readonly peer: RpcPeer;
899
1039
  readonly ackPeriod: number;
900
1040
  readonly ackAdvance: number;
1041
+ /**
1042
+ * If true, the source was produced by a factory `(abortSignal) => AsyncIterable<T>`
1043
+ * and may honor the AbortSignal to exit gracefully. `disconnect()` first aborts
1044
+ * the signal and gives the source up to `RpcStream.disconnectGracePeriodMs` ms
1045
+ * before force-closing via `iterator.return()`.
1046
+ *
1047
+ * If false, the source is a plain AsyncIterable that cannot observe the signal,
1048
+ * so `disconnect()` force-closes immediately.
1049
+ */
1050
+ readonly sourceUsesAbortSignal: boolean;
1051
+ /** Next stream index that will be sent (matches .NET's `index`). */
901
1052
  private _nextIndex;
902
1053
  private _ended;
903
1054
  private _started;
1055
+ /** Highest `nextIndex` observed in an ACK so far (matches .NET's `lastAckNextIndex` idiom). */
904
1056
  private _lastAckedIndex;
905
- private _ackWaiting;
906
- private _resetRequested;
907
1057
  private _abortController;
908
1058
  private _iterator;
909
- constructor(peer: RpcPeer, ackPeriod?: number, ackAdvance?: number, allowReconnect?: boolean, isRealTime?: boolean, canSkipTo?: (item: T) => boolean);
1059
+ private _acks;
1060
+ private _whenAckReady;
1061
+ constructor(peer: RpcPeer, ackPeriod?: number, ackAdvance?: number, allowReconnect?: boolean, isRealTime?: boolean, canSkipTo?: (item: T) => boolean, sourceUsesAbortSignal?: boolean);
910
1062
  /** AbortSignal that is aborted when the sender is disconnected. */
911
1063
  get abortSignal(): AbortSignal;
912
1064
  /** Returns the stream reference string for the $sys.Ok response. */
913
1065
  toRef(): string;
914
- /** Called by system call handler when $sys.Ack is received from the client. */
1066
+ /**
1067
+ * Called by system call handler when $sys.Ack is received from the client.
1068
+ *
1069
+ * Mirrors .NET `RpcSharedStream<T>.OnAck` at
1070
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:68-101.
1071
+ */
915
1072
  onAck(nextIndex: number, hostId: string): void;
916
1073
  /** Called by system call handler when $sys.AckEnd is received from the client. */
917
1074
  onAckEnd(_hostId: string): void;
918
- /** Send a single item to the client. */
1075
+ /**
1076
+ * Send a single item to the client at the current `_nextIndex`.
1077
+ *
1078
+ * Advances `_nextIndex` unconditionally — even if the peer is disconnected
1079
+ * the item is considered "sent" from the pump's perspective so the replay
1080
+ * buffer indexing stays consistent. If a connection is absent, the wire
1081
+ * message is dropped; the item will be resent from the replay buffer
1082
+ * after a reconnect (client sends `Ack(N, mustReset=true)`).
1083
+ */
919
1084
  sendItem(item: T): void;
920
- /** Send a batch of items to the client. */
1085
+ /** Send a batch of items to the client. See {@link sendItem} for disconnect semantics. */
921
1086
  sendBatch(items: T[]): void;
922
1087
  /** Signal stream completion to the client. */
923
1088
  sendEnd(error?: Error | null): void;
924
1089
  /**
925
1090
  * Consume an AsyncIterable and send all items to the client.
926
- * Waits for the client's initial Ack before starting to pump items.
927
1091
  *
928
- * When `isRealTime` is true, applies flow control based on `ackAdvance`:
929
- * if the sender is `ackAdvance` items ahead of the last ACK, it enters
930
- * skip mode — draining the source and discarding items until it finds
931
- * one where `canSkipTo` returns true.
1092
+ * Dispatches to the non-real-time or real-time pump, matching .NET
1093
+ * `RpcSharedStream<T>.OnRun` at
1094
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:105-108.
932
1095
  */
933
1096
  writeFrom(source: AsyncIterable<T>): Promise<void>;
934
- /** Wait until _nextIndex < _lastAckedIndex + ackAdvance. */
935
- private _waitForAckBudget;
1097
+ /**
1098
+ * Non-real-time pump — back-pressure through buffered ACKs.
1099
+ *
1100
+ * Direct port of .NET `OnRunNonRealTime` at
1101
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:110-217.
1102
+ */
1103
+ private _runNonRealTime;
1104
+ /**
1105
+ * Real-time pump — drops stale items to stay close to the source's head.
1106
+ *
1107
+ * Direct port of .NET `OnRunRealTime` at
1108
+ * src/ActualLab.Rpc/Infrastructure/RpcSharedStream.cs:219-420.
1109
+ */
1110
+ private _runRealTime;
1111
+ /** Drain all queued ACKs, returning the most recent one (or null if none). */
1112
+ private _tryProcessAcks;
1113
+ /** Wait for the ACK queue to have at least one entry (or `_ended`). */
1114
+ private _waitAckReady;
936
1115
  reconnect(): void;
937
1116
  disconnect(): void;
1117
+ private _forceCloseIterator;
938
1118
  }
939
1119
 
940
1120
  /** Creates a typed RPC client proxy — intercepts method calls and sends them over RPC. */
@@ -1002,4 +1182,4 @@ declare function xxh3_64str(input: string, seed?: bigint): bigint;
1002
1182
  */
1003
1183
  declare function computeMethodHash(methodName: string): number;
1004
1184
 
1005
- export { ARG_DELIMITER, ENVELOPE_DELIMITER, FRAME_DELIMITER, type IRpcObject, type MethodMeta, RPC_CLOSE_CODE_UNSUPPORTED_FORMAT, type RemoteHandshake, type RpcCallOptions, RpcCallTypeId, RpcClientPeer, RpcClientPeerReconnectDelayer, type RpcConnection, type RpcConnectionUrlResolver, type RpcDeserializedMessage, type RpcDispatchContext, RpcHub, RpcInboundCall, RpcInboundCallTracker, RpcJsonSerializationFormat, type RpcMessage, RpcMessageChannelConnection, RpcMessagePackCompactSerializationFormat, RpcMessagePackSerializationFormat, type RpcMethodDef, type RpcMethodDefInput, RpcMethodRegistry, type RpcObjectId, RpcObjectKind, RpcOutboundCall, RpcOutboundCallTracker, RpcPeer, RpcPeerConnectionKind, type RpcPeerState, RpcPeerStateKind, RpcPeerStateMonitor, type RpcReceivedMessage, RpcRemoteExecutionMode, RpcRemoteObjectTracker, RpcSerializationFormat, RpcSerializationFormatResolver, RpcServerPeer, type RpcServiceDef, RpcServiceHost, type RpcServiceImpl, RpcSharedObjectTracker, RpcStream, type RpcStreamOptions, type RpcStreamRef, RpcStreamSender, type RpcStreamSource, RpcSystemCallHandler, RpcSystemCallSender, RpcSystemCalls, RpcType, RpcWebSocketConnection, type RpcWireData, type ServiceMeta, type WebSocketLike, type WebSocketServer, WebSocketState, computeMethodHash, createBinaryEncoder, createMessageChannelPair, createRpcClient, defaultBinaryDecoder, defaultBinaryEncoder, defaultConnectionUrlResolver, defineRpcService, deserializeBinaryMessage, deserializeCompactBinaryMessage, deserializeMessage, getMethodsMeta, getServiceMeta, getStateDescription, isConnected, likelyConnected, parseStreamRef, resolveStreamRefs, rpcMethod, rpcService, serializeBinaryFrame, serializeBinaryMessage, serializeCompactBinaryMessage, serializeFrame, serializeMessage, splitBinaryFrame, splitCompactBinaryFrame, splitFrame, wireMethodName, xxh3_64, xxh3_64str };
1185
+ export { ARG_DELIMITER, ENVELOPE_DELIMITER, FRAME_DELIMITER, type IRpcObject, IncreasingSeqCompressor, type MethodMeta, RPC_CLOSE_CODE_UNSUPPORTED_FORMAT, type RemoteHandshake, type RpcCallOptions, RpcCallStage, RpcCallTypeId, RpcClientPeer, RpcClientPeerReconnectDelayer, type RpcConnection, type RpcConnectionUrlResolver, type RpcDeserializedMessage, type RpcDispatchContext, RpcHub, RpcInboundCall, RpcInboundCallTracker, RpcJsonSerializationFormat, type RpcMessage, RpcMessageChannelConnection, RpcMessagePackCompactSerializationFormat, RpcMessagePackSerializationFormat, type RpcMethodDef, type RpcMethodDefInput, RpcMethodRegistry, type RpcObjectId, RpcObjectKind, RpcOutboundCall, RpcOutboundCallTracker, RpcPeer, RpcPeerConnectionKind, type RpcPeerState, RpcPeerStateKind, RpcPeerStateMonitor, type RpcReceivedMessage, RpcRemoteExecutionMode, RpcRemoteObjectTracker, RpcSerializationFormat, RpcSerializationFormatResolver, RpcServerPeer, type RpcServiceDef, RpcServiceHost, type RpcServiceImpl, RpcSharedObjectTracker, RpcStream, type RpcStreamOptions, type RpcStreamRef, RpcStreamSender, type RpcStreamSource, RpcSystemCallHandler, RpcSystemCallSender, RpcSystemCalls, RpcType, RpcWebSocketConnection, type RpcWireData, type ServiceMeta, type WebSocketLike, type WebSocketServer, WebSocketState, computeMethodHash, createBinaryEncoder, createMessageChannelPair, createRpcClient, defaultBinaryDecoder, defaultBinaryEncoder, defaultConnectionUrlResolver, defineRpcService, deserializeBinaryMessage, deserializeCompactBinaryMessage, deserializeMessage, getMethodsMeta, getServiceMeta, getStateDescription, isConnected, likelyConnected, parseStreamRef, resolveStreamRefs, rpcMethod, rpcService, serializeBinaryFrame, serializeBinaryMessage, serializeCompactBinaryMessage, serializeFrame, serializeMessage, splitBinaryFrame, splitCompactBinaryFrame, splitFrame, wireMethodName, xxh3_64, xxh3_64str };