chenyc
2025-12-09 65e034683b28d799e73c7d7e5e4769fab5b9bc9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const get_timer_1 = __importDefault(require("./get-timer"));
class KeepaliveManager {
    _keepalive;
    timerId;
    timer;
    destroyed = false;
    counter;
    client;
    _keepaliveTimeoutTimestamp;
    _intervalEvery;
    get keepaliveTimeoutTimestamp() {
        return this._keepaliveTimeoutTimestamp;
    }
    get intervalEvery() {
        return this._intervalEvery;
    }
    get keepalive() {
        return this._keepalive;
    }
    constructor(client, variant) {
        this.client = client;
        this.timer =
            typeof variant === 'object' &&
                'set' in variant &&
                'clear' in variant
                ? variant
                : (0, get_timer_1.default)(variant);
        this.setKeepalive(client.options.keepalive);
    }
    clear() {
        if (this.timerId) {
            this.timer.clear(this.timerId);
            this.timerId = null;
        }
    }
    setKeepalive(value) {
        value *= 1000;
        if (isNaN(value) || value <= 0 || value > 2147483647) {
            throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${value}`);
        }
        this._keepalive = value;
        this.reschedule();
        this.client['log'](`KeepaliveManager: set keepalive to ${value}ms`);
    }
    destroy() {
        this.clear();
        this.destroyed = true;
    }
    reschedule() {
        if (this.destroyed) {
            return;
        }
        this.clear();
        this.counter = 0;
        const keepAliveTimeout = Math.ceil(this._keepalive * 1.5);
        this._keepaliveTimeoutTimestamp = Date.now() + keepAliveTimeout;
        this._intervalEvery = Math.ceil(this._keepalive / 2);
        this.timerId = this.timer.set(() => {
            if (this.destroyed) {
                return;
            }
            this.counter += 1;
            if (this.counter === 2) {
                this.client.sendPing();
            }
            else if (this.counter > 2) {
                this.client.onKeepaliveTimeout();
            }
        }, this._intervalEvery);
    }
}
exports.default = KeepaliveManager;
//# sourceMappingURL=KeepaliveManager.js.map