parent
a153fa466f
commit
c848da24c4
@ -0,0 +1,58 @@
|
||||
import {
|
||||
CONNECTION_ACK_REASON_CLOSED,
|
||||
CONNECTION_STATE_CLOSED,
|
||||
CONNECTION_STATE_CLOSING,
|
||||
CONNECTION_STATE_FAILED,
|
||||
CONNECTION_STATE_RECONNECTING,
|
||||
TIMER_KEY_RECONNECT
|
||||
} from './consts.ts';
|
||||
import type { ConnectionAckRegistry } from './acks.ts';
|
||||
import type { ConnectionStateTracker } from './connection-state.ts';
|
||||
import type { ConnectionTimerControls } from './connection-timers.ts';
|
||||
import type { ConnectionTransportRuntime } from './connection-transport-runtime.ts';
|
||||
import type { ConnectionHeartbeat } from './heartbeat.ts';
|
||||
import type { ConnectionCloseEvent, ConnectionState } from './types.ts';
|
||||
|
||||
export interface ConnectionCloseRuntime {
|
||||
readonly timers: ConnectionTimerControls;
|
||||
readonly heartbeat: ConnectionHeartbeat;
|
||||
readonly acks: ConnectionAckRegistry;
|
||||
readonly state: ConnectionStateTracker;
|
||||
readonly transport: ConnectionTransportRuntime;
|
||||
isDisposed(): boolean;
|
||||
isIntentionalClose(): boolean;
|
||||
setIntentionalClose(value: boolean): void;
|
||||
shouldReconnect(): boolean;
|
||||
scheduleReconnect(): void;
|
||||
markClosed(state: ConnectionState, cause?: unknown): void;
|
||||
}
|
||||
|
||||
export function handleConnectionTransportClose(
|
||||
event: ConnectionCloseEvent,
|
||||
runtime: ConnectionCloseRuntime
|
||||
): void {
|
||||
if (runtime.isDisposed()) return;
|
||||
if (runtime.isIntentionalClose()) {
|
||||
runtime.markClosed(CONNECTION_STATE_CLOSED);
|
||||
return;
|
||||
}
|
||||
runtime.state.setError(event);
|
||||
if (runtime.shouldReconnect()) {
|
||||
runtime.markClosed(CONNECTION_STATE_RECONNECTING, event);
|
||||
runtime.scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
runtime.markClosed(CONNECTION_STATE_FAILED, event);
|
||||
}
|
||||
|
||||
export function closeConnectionTransport(reason: string, runtime: ConnectionCloseRuntime): void {
|
||||
runtime.setIntentionalClose(true);
|
||||
runtime.timers.cancel(TIMER_KEY_RECONNECT);
|
||||
runtime.heartbeat.stop();
|
||||
runtime.acks.resolveAll({ ok: false, reason: CONNECTION_ACK_REASON_CLOSED });
|
||||
runtime.state.transition(CONNECTION_STATE_CLOSING);
|
||||
runtime.transport.close(reason);
|
||||
if (runtime.state.state !== CONNECTION_STATE_CLOSED) {
|
||||
runtime.markClosed(CONNECTION_STATE_CLOSED);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue