@mtcute/core 0.15.2 → 0.16.0
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/cjs/highlevel/base.d.ts +3 -3
- package/cjs/highlevel/base.js.map +1 -1
- package/cjs/highlevel/methods/files/download-iterable.js +1 -1
- package/cjs/highlevel/methods/files/download-iterable.js.map +1 -1
- package/cjs/highlevel/methods/users/resolve-peer-many.js +1 -1
- package/cjs/highlevel/methods/users/resolve-peer-many.js.map +1 -1
- package/cjs/highlevel/types/messages/dialog.d.ts +4 -2
- package/cjs/highlevel/types/messages/dialog.js +4 -2
- package/cjs/highlevel/types/messages/dialog.js.map +1 -1
- package/cjs/highlevel/types/messages/message-action.d.ts +15 -1
- package/cjs/highlevel/types/messages/message-action.js +10 -0
- package/cjs/highlevel/types/messages/message-action.js.map +1 -1
- package/cjs/highlevel/types/peers/full-chat.d.ts +2 -0
- package/cjs/highlevel/types/peers/full-chat.js +4 -0
- package/cjs/highlevel/types/peers/full-chat.js.map +1 -1
- package/cjs/highlevel/updates/manager.js +3 -3
- package/cjs/highlevel/updates/manager.js.map +1 -1
- package/cjs/highlevel/worker/invoker.js +2 -1
- package/cjs/highlevel/worker/invoker.js.map +1 -1
- package/cjs/highlevel/worker/port.js +4 -3
- package/cjs/highlevel/worker/port.js.map +1 -1
- package/cjs/highlevel/worker/protocol.d.ts +10 -5
- package/cjs/highlevel/worker/protocol.js +66 -0
- package/cjs/highlevel/worker/protocol.js.map +1 -1
- package/cjs/highlevel/worker/worker.js +6 -5
- package/cjs/highlevel/worker/worker.js.map +1 -1
- package/cjs/network/client.d.ts +0 -16
- package/cjs/network/client.js +0 -2
- package/cjs/network/client.js.map +1 -1
- package/cjs/network/index.d.ts +2 -1
- package/cjs/network/index.js +1 -0
- package/cjs/network/index.js.map +1 -1
- package/cjs/network/middlewares/bundle.d.ts +3 -0
- package/cjs/network/middlewares/bundle.js +20 -0
- package/cjs/network/middlewares/bundle.js.map +1 -0
- package/cjs/network/middlewares/default.d.ts +8 -0
- package/cjs/network/middlewares/default.js +10 -0
- package/cjs/network/middlewares/default.js.map +1 -0
- package/cjs/network/middlewares/flood-waiter.d.ts +37 -0
- package/cjs/network/middlewares/flood-waiter.js +70 -0
- package/cjs/network/middlewares/flood-waiter.js.map +1 -0
- package/cjs/network/middlewares/index.d.ts +2 -0
- package/cjs/network/middlewares/index.js +29 -0
- package/cjs/network/middlewares/index.js.map +1 -0
- package/cjs/network/middlewares/internal-errors.d.ts +17 -0
- package/cjs/network/middlewares/internal-errors.js +41 -0
- package/cjs/network/middlewares/internal-errors.js.map +1 -0
- package/cjs/network/middlewares/on-error.d.ts +30 -0
- package/cjs/network/middlewares/on-error.js +44 -0
- package/cjs/network/middlewares/on-error.js.map +1 -0
- package/cjs/network/middlewares/on-method.d.ts +39 -0
- package/cjs/network/middlewares/on-method.js +45 -0
- package/cjs/network/middlewares/on-method.js.map +1 -0
- package/cjs/network/mtproto-session.js +1 -1
- package/cjs/network/mtproto-session.js.map +1 -1
- package/cjs/network/multi-session-connection.js +1 -1
- package/cjs/network/multi-session-connection.js.map +1 -1
- package/cjs/network/network-manager.d.ts +23 -6
- package/cjs/network/network-manager.js +55 -102
- package/cjs/network/network-manager.js.map +1 -1
- package/cjs/network/persistent-connection.js +5 -5
- package/cjs/network/persistent-connection.js.map +1 -1
- package/cjs/network/session-connection.js +6 -6
- package/cjs/network/session-connection.js.map +1 -1
- package/cjs/storage/driver.js +1 -1
- package/cjs/storage/driver.js.map +1 -1
- package/cjs/storage/storage.js +1 -1
- package/cjs/storage/storage.js.map +1 -1
- package/cjs/utils/abort-signal.d.ts +1 -0
- package/cjs/utils/abort-signal.js +13 -0
- package/cjs/utils/abort-signal.js.map +1 -0
- package/cjs/utils/composer.d.ts +3 -0
- package/cjs/utils/composer.js +22 -0
- package/cjs/utils/composer.js.map +1 -0
- package/cjs/utils/error-reporting.js +1 -1
- package/cjs/utils/error-reporting.js.map +1 -1
- package/cjs/utils/index.d.ts +1 -0
- package/cjs/utils/index.js +1 -0
- package/cjs/utils/index.js.map +1 -1
- package/cjs/utils/logger.js +15 -3
- package/cjs/utils/logger.js.map +1 -1
- package/esm/highlevel/base.d.ts +3 -3
- package/esm/highlevel/base.js.map +1 -1
- package/esm/highlevel/methods/files/download-iterable.js +1 -1
- package/esm/highlevel/methods/files/download-iterable.js.map +1 -1
- package/esm/highlevel/methods/users/resolve-peer-many.js +1 -1
- package/esm/highlevel/methods/users/resolve-peer-many.js.map +1 -1
- package/esm/highlevel/types/messages/dialog.d.ts +4 -2
- package/esm/highlevel/types/messages/dialog.js +4 -2
- package/esm/highlevel/types/messages/dialog.js.map +1 -1
- package/esm/highlevel/types/messages/message-action.d.ts +15 -1
- package/esm/highlevel/types/messages/message-action.js +10 -0
- package/esm/highlevel/types/messages/message-action.js.map +1 -1
- package/esm/highlevel/types/peers/full-chat.d.ts +2 -0
- package/esm/highlevel/types/peers/full-chat.js +4 -0
- package/esm/highlevel/types/peers/full-chat.js.map +1 -1
- package/esm/highlevel/updates/manager.js +3 -3
- package/esm/highlevel/updates/manager.js.map +1 -1
- package/esm/highlevel/worker/invoker.js +2 -1
- package/esm/highlevel/worker/invoker.js.map +1 -1
- package/esm/highlevel/worker/port.js +4 -3
- package/esm/highlevel/worker/port.js.map +1 -1
- package/esm/highlevel/worker/protocol.d.ts +10 -5
- package/esm/highlevel/worker/protocol.js +60 -1
- package/esm/highlevel/worker/protocol.js.map +1 -1
- package/esm/highlevel/worker/worker.js +6 -5
- package/esm/highlevel/worker/worker.js.map +1 -1
- package/esm/network/client.d.ts +0 -16
- package/esm/network/client.js +0 -2
- package/esm/network/client.js.map +1 -1
- package/esm/network/index.d.ts +2 -1
- package/esm/network/index.js +1 -0
- package/esm/network/index.js.map +1 -1
- package/esm/network/middlewares/bundle.d.ts +3 -0
- package/esm/network/middlewares/bundle.js +4 -0
- package/esm/network/middlewares/bundle.js.map +1 -0
- package/esm/network/middlewares/default.d.ts +8 -0
- package/esm/network/middlewares/default.js +6 -0
- package/esm/network/middlewares/default.js.map +1 -0
- package/esm/network/middlewares/flood-waiter.d.ts +37 -0
- package/esm/network/middlewares/flood-waiter.js +66 -0
- package/esm/network/middlewares/flood-waiter.js.map +1 -0
- package/esm/network/middlewares/index.d.ts +2 -0
- package/esm/network/middlewares/index.js +3 -0
- package/esm/network/middlewares/index.js.map +1 -0
- package/esm/network/middlewares/internal-errors.d.ts +17 -0
- package/esm/network/middlewares/internal-errors.js +37 -0
- package/esm/network/middlewares/internal-errors.js.map +1 -0
- package/esm/network/middlewares/on-error.d.ts +30 -0
- package/esm/network/middlewares/on-error.js +40 -0
- package/esm/network/middlewares/on-error.js.map +1 -0
- package/esm/network/middlewares/on-method.d.ts +39 -0
- package/esm/network/middlewares/on-method.js +41 -0
- package/esm/network/middlewares/on-method.js.map +1 -0
- package/esm/network/mtproto-session.js +1 -1
- package/esm/network/mtproto-session.js.map +1 -1
- package/esm/network/multi-session-connection.js +1 -1
- package/esm/network/multi-session-connection.js.map +1 -1
- package/esm/network/network-manager.d.ts +23 -6
- package/esm/network/network-manager.js +57 -104
- package/esm/network/network-manager.js.map +1 -1
- package/esm/network/persistent-connection.js +5 -5
- package/esm/network/persistent-connection.js.map +1 -1
- package/esm/network/session-connection.js +6 -6
- package/esm/network/session-connection.js.map +1 -1
- package/esm/storage/driver.js +1 -1
- package/esm/storage/driver.js.map +1 -1
- package/esm/storage/storage.js +1 -1
- package/esm/storage/storage.js.map +1 -1
- package/esm/utils/abort-signal.d.ts +1 -0
- package/esm/utils/abort-signal.js +9 -0
- package/esm/utils/abort-signal.js.map +1 -0
- package/esm/utils/composer.d.ts +3 -0
- package/esm/utils/composer.js +18 -0
- package/esm/utils/composer.js.map +1 -0
- package/esm/utils/error-reporting.js +1 -1
- package/esm/utils/error-reporting.js.map +1 -1
- package/esm/utils/index.d.ts +1 -0
- package/esm/utils/index.js +1 -0
- package/esm/utils/index.js.map +1 -1
- package/esm/utils/logger.js +15 -3
- package/esm/utils/logger.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,20 +1,12 @@
|
|
|
1
|
-
import { tl } from '@mtcute/tl';
|
|
2
1
|
import { getPlatform } from '../platform.js';
|
|
3
|
-
import { MtArgumentError, MtcuteError,
|
|
4
|
-
import {
|
|
2
|
+
import { MtArgumentError, MtcuteError, MtUnsupportedError } from '../types/index.js';
|
|
3
|
+
import { composeMiddlewares } from '../utils/composer.js';
|
|
4
|
+
import { createControllablePromise } from '../utils/index.js';
|
|
5
5
|
import { assertTypeIs, isTlRpcError } from '../utils/type-assertions.js';
|
|
6
|
+
import { basic as defaultMiddlewares } from './middlewares/default.js';
|
|
6
7
|
import { MultiSessionConnection } from './multi-session-connection.js';
|
|
7
8
|
import { defaultReconnectionStrategy } from './reconnection.js';
|
|
8
9
|
import { ServerSaltManager } from './server-salt.js';
|
|
9
|
-
const CLIENT_ERRORS = {
|
|
10
|
-
[tl.RpcError.BAD_REQUEST]: 1,
|
|
11
|
-
[tl.RpcError.UNAUTHORIZED]: 1,
|
|
12
|
-
[tl.RpcError.FORBIDDEN]: 1,
|
|
13
|
-
[tl.RpcError.NOT_FOUND]: 1,
|
|
14
|
-
[tl.RpcError.FLOOD]: 1,
|
|
15
|
-
[tl.RpcError.SEE_OTHER]: 1,
|
|
16
|
-
[tl.RpcError.NOT_ACCEPTABLE]: 1,
|
|
17
|
-
};
|
|
18
10
|
const defaultConnectionCountDelegate = (kind, dcId, isPremium) => {
|
|
19
11
|
switch (kind) {
|
|
20
12
|
case 'main':
|
|
@@ -127,7 +119,7 @@ export class DcConnectionManager {
|
|
|
127
119
|
this.downloadSmall.notifyKeyChange();
|
|
128
120
|
})
|
|
129
121
|
.catch((e) => {
|
|
130
|
-
this.manager._log.warn('failed to save auth key for dc %d: %
|
|
122
|
+
this.manager._log.warn('failed to save auth key for dc %d: %e', this.dcId, e);
|
|
131
123
|
this.manager.params.emitError(e);
|
|
132
124
|
});
|
|
133
125
|
});
|
|
@@ -148,7 +140,7 @@ export class DcConnectionManager {
|
|
|
148
140
|
this.downloadSmall.notifyKeyChange();
|
|
149
141
|
})
|
|
150
142
|
.catch((e) => {
|
|
151
|
-
this.manager._log.warn('failed to save temp auth key %d for dc %d: %
|
|
143
|
+
this.manager._log.warn('failed to save temp auth key %d for dc %d: %e', idx, this.dcId, e);
|
|
152
144
|
this.manager.params.emitError(e);
|
|
153
145
|
});
|
|
154
146
|
});
|
|
@@ -263,7 +255,7 @@ export class NetworkManager {
|
|
|
263
255
|
_: 'initConnection',
|
|
264
256
|
deviceModel,
|
|
265
257
|
systemVersion: '1.0',
|
|
266
|
-
appVersion: '0.
|
|
258
|
+
appVersion: '0.16.0',
|
|
267
259
|
systemLangCode: 'en',
|
|
268
260
|
langPack: '', // "langPacks are for official apps only"
|
|
269
261
|
langCode: 'en',
|
|
@@ -276,6 +268,7 @@ export class NetworkManager {
|
|
|
276
268
|
this._reconnectionStrategy = params.reconnectionStrategy ?? defaultReconnectionStrategy;
|
|
277
269
|
this._connectionCount = params.connectionCount ?? defaultConnectionCountDelegate;
|
|
278
270
|
this._updateHandler = params.onUpdate;
|
|
271
|
+
this.call = this._composeCall(params.middlewares);
|
|
279
272
|
this._onConfigChanged = this._onConfigChanged.bind(this);
|
|
280
273
|
config.onReload(this._onConfigChanged);
|
|
281
274
|
this._log = params.log.create('network');
|
|
@@ -474,32 +467,28 @@ export class NetworkManager {
|
|
|
474
467
|
await this._storage.dcs.store(options);
|
|
475
468
|
await this._switchPrimaryDc(this._dcConnections.get(newDc));
|
|
476
469
|
}
|
|
477
|
-
|
|
478
|
-
|
|
470
|
+
call;
|
|
471
|
+
_composeCall = (middlewares) => {
|
|
472
|
+
if (!middlewares) {
|
|
473
|
+
middlewares = defaultMiddlewares();
|
|
474
|
+
}
|
|
475
|
+
if (!middlewares.length) {
|
|
476
|
+
return this._call;
|
|
477
|
+
}
|
|
478
|
+
const final = async (ctx) => {
|
|
479
|
+
return this._call(ctx.request, ctx.params);
|
|
480
|
+
};
|
|
481
|
+
const composed = composeMiddlewares(middlewares, final);
|
|
482
|
+
return async (message, params) => composed({
|
|
483
|
+
request: message,
|
|
484
|
+
manager: this,
|
|
485
|
+
params,
|
|
486
|
+
});
|
|
487
|
+
};
|
|
488
|
+
_call = async (message, params) => {
|
|
479
489
|
if (!this._primaryDc) {
|
|
480
490
|
throw new MtcuteError('Not connected to any DC');
|
|
481
491
|
}
|
|
482
|
-
const floodSleepThreshold = params?.floodSleepThreshold ?? this.params.floodSleepThreshold;
|
|
483
|
-
const maxRetryCount = params?.maxRetryCount ?? this.params.maxRetryCount;
|
|
484
|
-
const throw503 = params?.throw503 ?? false;
|
|
485
|
-
// do not send requests that are in flood wait
|
|
486
|
-
if (this._floodWaitedRequests.has(message._)) {
|
|
487
|
-
const delta = this._floodWaitedRequests.get(message._) - Date.now();
|
|
488
|
-
if (delta <= 3000) {
|
|
489
|
-
// flood waits below 3 seconds are "ignored"
|
|
490
|
-
this._floodWaitedRequests.delete(message._);
|
|
491
|
-
}
|
|
492
|
-
else if (delta <= this.params.floodSleepThreshold) {
|
|
493
|
-
await sleepWithAbort(delta, this.params.stopSignal);
|
|
494
|
-
this._floodWaitedRequests.delete(message._);
|
|
495
|
-
}
|
|
496
|
-
else {
|
|
497
|
-
const err = tl.RpcError.create(tl.RpcError.FLOOD, 'FLOOD_WAIT_%d');
|
|
498
|
-
err.seconds = Math.ceil(delta / 1000);
|
|
499
|
-
throw err;
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
let lastError = null;
|
|
503
492
|
const kind = params?.kind ?? 'main';
|
|
504
493
|
let manager;
|
|
505
494
|
if (params?.manager) {
|
|
@@ -512,78 +501,42 @@ export class NetworkManager {
|
|
|
512
501
|
manager = this._primaryDc;
|
|
513
502
|
}
|
|
514
503
|
let multi = manager[kind];
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
if (err === 'WORKER_BUSY_TOO_LONG_RETRY') {
|
|
529
|
-
// according to tdlib, "it is dangerous to resend query without timeout, so use 1"
|
|
530
|
-
await sleepWithAbort(1000, this.params.stopSignal);
|
|
531
|
-
}
|
|
532
|
-
continue;
|
|
533
|
-
}
|
|
534
|
-
if (err.startsWith('FLOOD_WAIT_') ||
|
|
535
|
-
err.startsWith('SLOWMODE_WAIT_') ||
|
|
536
|
-
err.startsWith('FLOOD_TEST_PHONE_WAIT_')) {
|
|
537
|
-
let seconds = Number(err.lastIndexOf('_') + 1);
|
|
538
|
-
if (Number.isNaN(seconds)) {
|
|
539
|
-
this._log.warn('invalid flood wait error received: %s, ignoring', err);
|
|
504
|
+
let res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId);
|
|
505
|
+
if (!isTlRpcError(res)) {
|
|
506
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
507
|
+
return res;
|
|
508
|
+
}
|
|
509
|
+
const err = res.errorMessage;
|
|
510
|
+
if (manager === this._primaryDc) {
|
|
511
|
+
if (err.startsWith('PHONE_MIGRATE_') ||
|
|
512
|
+
err.startsWith('NETWORK_MIGRATE_') ||
|
|
513
|
+
err.startsWith('USER_MIGRATE_')) {
|
|
514
|
+
const newDc = Number(err.slice(err.lastIndexOf('_') + 1));
|
|
515
|
+
if (Number.isNaN(newDc)) {
|
|
516
|
+
this._log.warn('invalid migrate error received: %s, ignoring', err);
|
|
540
517
|
return res;
|
|
541
518
|
}
|
|
542
|
-
if (
|
|
543
|
-
|
|
544
|
-
this._floodWaitedRequests.set(message._, Date.now() + seconds * 1000);
|
|
519
|
+
if (params?.localMigrate) {
|
|
520
|
+
manager = await this._getOtherDc(newDc);
|
|
545
521
|
}
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
}
|
|
551
|
-
if (seconds <= floodSleepThreshold) {
|
|
552
|
-
this._log.warn('%s resulted in a flood wait, will retry in %d seconds', message._, seconds);
|
|
553
|
-
await sleepWithAbort(seconds * 1000, this.params.stopSignal);
|
|
554
|
-
continue;
|
|
522
|
+
else {
|
|
523
|
+
this._log.info('received %s, migrating to dc %d', err, newDc);
|
|
524
|
+
await this.changePrimaryDc(newDc);
|
|
525
|
+
manager = this._primaryDc;
|
|
555
526
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
if (err.startsWith('PHONE_MIGRATE_') ||
|
|
559
|
-
err.startsWith('NETWORK_MIGRATE_') ||
|
|
560
|
-
err.startsWith('USER_MIGRATE_')) {
|
|
561
|
-
const newDc = Number(err.slice(err.lastIndexOf('_') + 1));
|
|
562
|
-
if (Number.isNaN(newDc)) {
|
|
563
|
-
this._log.warn('invalid migrate error received: %s, ignoring', err);
|
|
564
|
-
return res;
|
|
565
|
-
}
|
|
566
|
-
if (params?.localMigrate) {
|
|
567
|
-
manager = await this._getOtherDc(newDc);
|
|
568
|
-
}
|
|
569
|
-
else {
|
|
570
|
-
this._log.info('Migrate error, new dc = %d', newDc);
|
|
571
|
-
await this.changePrimaryDc(newDc);
|
|
572
|
-
manager = this._primaryDc;
|
|
573
|
-
}
|
|
574
|
-
multi = manager[kind];
|
|
575
|
-
continue;
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
else if (err === 'AUTH_KEY_UNREGISTERED') {
|
|
579
|
-
// we can try re-exporting auth from the primary connection
|
|
580
|
-
this._log.warn('exported auth key error, trying re-exporting..');
|
|
581
|
-
await this._exportAuthTo(manager);
|
|
582
|
-
continue;
|
|
527
|
+
multi = manager[kind];
|
|
528
|
+
res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId);
|
|
583
529
|
}
|
|
584
530
|
}
|
|
585
|
-
|
|
586
|
-
|
|
531
|
+
else if (err === 'AUTH_KEY_UNREGISTERED') {
|
|
532
|
+
// we can try re-exporting auth from the primary connection
|
|
533
|
+
this._log.warn('exported auth key error, trying re-exporting..');
|
|
534
|
+
await this._exportAuthTo(manager);
|
|
535
|
+
res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId);
|
|
536
|
+
}
|
|
537
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
538
|
+
return res;
|
|
539
|
+
};
|
|
587
540
|
changeTransport(factory) {
|
|
588
541
|
for (const dc of this._dcConnections.values()) {
|
|
589
542
|
dc.main.changeTransport(factory);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-manager.js","sourceRoot":"","sources":["../../../src/network/network-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAO,EAAE,EAAE,MAAM,YAAY,CAAA;AAGpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAE5C,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAA;AACpG,OAAO,EAEH,yBAAyB,EAIzB,cAAc,GACjB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAA;AAExE,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAA;AAEtE,OAAO,EAAE,2BAA2B,EAAwB,MAAM,mBAAmB,CAAA;AACrF,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAA;AAMpD,MAAM,aAAa,GAAG;IAClB,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;IAC5B,CAAC,EAAE,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;IAC7B,CAAC,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;IAC1B,CAAC,EAAE,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;IAC1B,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;IACtB,CAAC,EAAE,CAAC,Q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esContent":["import { mtp, tl } from '@mtcute/tl'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { getPlatform } from '../platform.js'\nimport { StorageManager } from '../storage/storage.js'\nimport { MtArgumentError, MtcuteError, MtTimeoutError, MtUnsupportedError } from '../types/index.js'\nimport {\n ControllablePromise,\n createControllablePromise,\n DcOptions,\n ICryptoProvider,\n Logger,\n sleepWithAbort,\n} from '../utils/index.js'\nimport { assertTypeIs, isTlRpcError } from '../utils/type-assertions.js'\nimport { ConfigManager } from './config-manager.js'\nimport { MultiSessionConnection } from './multi-session-connection.js'\nimport { PersistentConnectionParams } from './persistent-connection.js'\nimport { defaultReconnectionStrategy, ReconnectionStrategy } from './reconnection.js'\nimport { ServerSaltManager } from './server-salt.js'\nimport { SessionConnection, SessionConnectionParams } from './session-connection.js'\nimport { TransportFactory } from './transports/index.js'\n\nexport type ConnectionKind = 'main' | 'upload' | 'download' | 'downloadSmall'\n\nconst CLIENT_ERRORS = {\n [tl.RpcError.BAD_REQUEST]: 1,\n [tl.RpcError.UNAUTHORIZED]: 1,\n [tl.RpcError.FORBIDDEN]: 1,\n [tl.RpcError.NOT_FOUND]: 1,\n [tl.RpcError.FLOOD]: 1,\n [tl.RpcError.SEE_OTHER]: 1,\n [tl.RpcError.NOT_ACCEPTABLE]: 1,\n}\n\n/**\n * Params passed into {@link NetworkManager} by {@link TelegramClient}.\n * This type is intended for internal usage only.\n */\nexport interface NetworkManagerParams {\n storage: StorageManager\n crypto: ICryptoProvider\n log: Logger\n\n enableErrorReporting: boolean\n apiId: number\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n transport: TransportFactory\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n floodSleepThreshold: number\n maxRetryCount: number\n disableUpdates?: boolean\n testMode: boolean\n layer: number\n useIpv6: boolean\n readerMap: TlReaderMap\n writerMap: TlWriterMap\n isPremium: boolean\n emitError: (err: Error, connection?: SessionConnection) => void\n onUpdate: (upd: tl.TypeUpdates) => void\n onUsable: () => void\n onConnecting: () => void\n onNetworkChanged: (connected: boolean) => void\n stopSignal: AbortSignal\n}\n\nexport type ConnectionCountDelegate = (kind: ConnectionKind, dcId: number, isPremium: boolean) => number\n\nconst defaultConnectionCountDelegate: ConnectionCountDelegate = (kind, dcId, isPremium) => {\n switch (kind) {\n case 'main':\n return 0\n case 'upload':\n return isPremium || (dcId !== 2 && dcId !== 4) ? 8 : 4\n case 'download':\n return isPremium ? 8 : 2\n case 'downloadSmall':\n return 2\n }\n}\n\n/**\n * Additional params passed into {@link NetworkManager} by the user\n * that customize the behavior of the manager\n */\nexport interface NetworkManagerExtraParams {\n /**\n * Whether to use PFS (Perfect Forward Secrecy) for all connections.\n * This is disabled by default\n */\n usePfs?: boolean\n\n /**\n * Connection count for each connection kind.\n * The function should be pure to avoid unexpected behavior.\n *\n * Defaults to TDLib logic:\n * - main: 0 (which stands for \"handle internally, based on tmp_sessions value\")\n * - upload: if premium or dc id is other than 2 or 4, then 8, otherwise 4\n * - download: if premium then 8, otherwise 2\n * - downloadSmall: 2\n *\n * Non-zero value for `main` is **for advanced users only**\n * as it may lead to unexpected behavior, and is generally not recommended\n * because of unnecessary extra load on both the server and the client as well as\n * increased possibility of encountering AUTH_KEY_DUPLICATED errors.\n */\n connectionCount?: ConnectionCountDelegate\n\n /**\n * Idle timeout for non-main connections, in ms\n *\n * @default 60000 (60 seconds).\n */\n inactivityTimeout?: number\n}\n\n/** Options that can be customized when making an RPC call */\nexport interface RpcCallOptions {\n /**\n * If the call results in a `FLOOD_WAIT_X` error,\n * the maximum amount of time to wait before retrying.\n *\n * If set to `0`, the call will not be retried.\n *\n * @default {@link BaseTelegramClientOptions.floodSleepThreshold}\n */\n floodSleepThreshold?: number\n\n /**\n * If the call results in an internal server error or a flood wait,\n * the maximum amount of times to retry the call.\n *\n * @default {@link BaseTelegramClientOptions.maxRetryCount}\n */\n maxRetryCount?: number\n\n /**\n * Timeout for the call, in milliseconds.\n *\n * @default Infinity\n */\n timeout?: number\n\n /**\n * **ADVANCED**\n *\n * Kind of connection to use for this call.\n *\n * @default 'main'\n */\n kind?: ConnectionKind\n\n /**\n * **ADVANCED**\n *\n * ID of the DC to use for this call\n */\n dcId?: number\n\n /**\n * **ADVANCED**\n *\n * DC connection manager to use for this call.\n * Overrides `dcId` if set.\n */\n manager?: DcConnectionManager\n\n /**\n * Abort signal for the call.\n */\n abortSignal?: AbortSignal\n\n /**\n * Whether we should not retry on -503 errors and throw {@link MtTimeoutError} immediately instead.\n *\n * Useful for methods like `messages.getBotCallbackAnswer` that reliably return\n * -503 in case the upstream bot failed to respond.\n */\n throw503?: boolean\n\n /**\n * Whether the `X_MIGRATE_%d` errors should be handled locally on request level\n * instead of changing the default datacenter for the entire client.\n *\n * Useful for `invokeWithBusinessConnection`, as it returns a `USER_MIGRATE_%d` error\n * that is in fact not related to the user, but to the specific request.\n */\n localMigrate?: boolean\n\n /**\n * Some requests should be processed consecutively, and not in parallel.\n * Using the same `chainId` for multiple requests will ensure that they are processed in the order\n * of calling `.call()`.\n *\n * Particularly useful for `messages.sendMessage` and alike.\n */\n chainId?: string | number\n}\n\n/**\n * Wrapper over all connection pools for a single DC.\n */\nexport class DcConnectionManager {\n private _salts = new ServerSaltManager()\n private _log\n\n /** Main connection pool */\n main: MultiSessionConnection\n /** Upload connection pool */\n upload: MultiSessionConnection\n /** Download connection pool */\n download: MultiSessionConnection\n /** Download connection pool (for small files) */\n downloadSmall: MultiSessionConnection\n\n private get _mainCountOverride() {\n return this.manager.params.connectionCount?.('main', this.dcId, this.manager.params.isPremium) ?? 0\n }\n\n constructor(\n /** Network manager instance */\n readonly manager: NetworkManager,\n /** DC ID */\n readonly dcId: number,\n /** DC options to use */\n readonly _dcs: DcOptions,\n /** Whether this DC is the primary one */\n public isPrimary = false,\n ) {\n this._log = this.manager._log.create('dc-manager')\n this._log.prefix = `[DC ${dcId}] `\n\n const baseConnectionParams = (): SessionConnectionParams => ({\n crypto: this.manager.params.crypto,\n initConnection: this.manager._initConnectionParams,\n transportFactory: this.manager._transportFactory,\n dc: this._dcs.media,\n testMode: this.manager.params.testMode,\n reconnectionStrategy: this.manager._reconnectionStrategy,\n layer: this.manager.params.layer,\n disableUpdates: this.manager.params.disableUpdates,\n readerMap: this.manager.params.readerMap,\n writerMap: this.manager.params.writerMap,\n usePfs: this.manager.params.usePfs,\n isMainConnection: false,\n isMainDcConnection: this.isPrimary,\n inactivityTimeout: this.manager.params.inactivityTimeout ?? 60_000,\n enableErrorReporting: this.manager.params.enableErrorReporting,\n salts: this._salts,\n })\n\n const mainParams = baseConnectionParams()\n mainParams.isMainConnection = true\n mainParams.dc = _dcs.main\n\n if (isPrimary) {\n mainParams.inactivityTimeout = undefined\n }\n\n let mainCount\n\n if (this.isPrimary) {\n mainCount = this._mainCountOverride\n\n if (mainCount === 0) {\n mainCount = this.manager.config.getNow()?.tmpSessions ?? 1\n }\n } else {\n mainCount = 1\n }\n\n this.main = new MultiSessionConnection(mainParams, mainCount, this._log, 'MAIN')\n this.upload = new MultiSessionConnection(\n baseConnectionParams(),\n this.manager._connectionCount('upload', this.dcId, this.manager.params.isPremium),\n this._log,\n 'UPLOAD',\n )\n this.download = new MultiSessionConnection(\n baseConnectionParams(),\n this.manager._connectionCount('download', this.dcId, this.manager.params.isPremium),\n this._log,\n 'DOWNLOAD',\n )\n this.downloadSmall = new MultiSessionConnection(\n baseConnectionParams(),\n this.manager._connectionCount('downloadSmall', this.dcId, this.manager.params.isPremium),\n this._log,\n 'DOWNLOAD_SMALL',\n )\n\n this._setupMulti('main')\n this._setupMulti('upload')\n this._setupMulti('download')\n this._setupMulti('downloadSmall')\n }\n\n private _setupMulti(kind: ConnectionKind): void {\n const connection = this[kind]\n\n connection.on('key-change', (idx, key: Uint8Array | null) => {\n if (kind !== 'main') {\n // main connection is responsible for authorization,\n // and keys are then sent to other connections\n this.manager._log.warn('got key-change from non-main connection, ignoring')\n\n return\n }\n\n this.manager._log.debug('key change for dc %d from connection %d', this.dcId, idx)\n\n // send key to other connections\n this.upload.setAuthKey(key)\n this.download.setAuthKey(key)\n this.downloadSmall.setAuthKey(key)\n Promise.resolve(this.manager._storage.provider.authKeys.set(this.dcId, key))\n .then(() => {\n this.upload.notifyKeyChange()\n this.download.notifyKeyChange()\n this.downloadSmall.notifyKeyChange()\n })\n .catch((e: Error) => {\n this.manager._log.warn('failed to save auth key for dc %d: %s', this.dcId, e)\n this.manager.params.emitError(e)\n })\n })\n connection.on('tmp-key-change', (idx: number, key: Uint8Array | null, expires: number) => {\n if (kind !== 'main') {\n this.manager._log.warn('got tmp-key-change from non-main connection, ignoring')\n\n return\n }\n\n this.manager._log.debug('temp key change for dc %d from connection %d', this.dcId, idx)\n\n // send key to other connections\n this.upload.setAuthKey(key, true)\n this.download.setAuthKey(key, true)\n this.downloadSmall.setAuthKey(key, true)\n\n Promise.resolve(this.manager._storage.provider.authKeys.setTemp(this.dcId, idx, key, expires * 1000))\n .then(() => {\n this.upload.notifyKeyChange()\n this.download.notifyKeyChange()\n this.downloadSmall.notifyKeyChange()\n })\n .catch((e: Error) => {\n this.manager._log.warn('failed to save temp auth key %d for dc %d: %s', idx, this.dcId, e)\n this.manager.params.emitError(e)\n })\n })\n connection.on('future-salts', (salts: mtp.RawMt_future_salt[]) => {\n Promise.resolve(this.manager._storage.salts.store(this.dcId, salts)).catch((e: Error) =>\n this.manager.params.emitError(e),\n )\n })\n\n connection.on('auth-begin', () => {\n // we need to propagate auth-begin to all connections\n // to avoid them sending requests before auth is complete\n if (kind !== 'main') {\n this.manager._log.warn('got auth-begin from non-main connection, ignoring')\n\n return\n }\n\n // reset key on non-main connections\n // this event was already propagated to additional main connections\n this.upload.resetAuthKeys()\n this.download.resetAuthKeys()\n this.downloadSmall.resetAuthKeys()\n })\n\n connection.on('request-auth', () => {\n this.main.requestAuth()\n })\n\n // fucking awesome architecture, but whatever\n connection.on('request-keys', (promise: ControllablePromise<void>) => {\n this.loadKeys(true)\n .then(() => promise.resolve())\n .catch((e: Error) => promise.reject(e))\n })\n\n connection.on('error', (err: Error, conn: SessionConnection) => {\n this.manager.params.emitError(err, conn)\n })\n }\n\n setIsPrimary(isPrimary: boolean): void {\n if (this.isPrimary === isPrimary) return\n this.isPrimary = isPrimary\n this.main.params.isMainDcConnection = isPrimary\n\n if (isPrimary) {\n this.main.setInactivityTimeout(undefined)\n } else {\n this.main.setInactivityTimeout(this.manager.params.inactivityTimeout ?? 60_000)\n }\n }\n\n setIsPremium(isPremium: boolean): void {\n this.upload.setCount(this.manager._connectionCount('upload', this.dcId, isPremium))\n this.download.setCount(this.manager._connectionCount('download', this.dcId, isPremium))\n this.downloadSmall.setCount(this.manager._connectionCount('downloadSmall', this.dcId, isPremium))\n }\n\n async loadKeys(forcePfs = false): Promise<boolean> {\n const [permanent, salts] = await Promise.all([\n this.manager._storage.provider.authKeys.get(this.dcId),\n this.manager._storage.salts.fetch(this.dcId),\n ])\n\n this.main.setAuthKey(permanent)\n this.upload.setAuthKey(permanent)\n this.download.setAuthKey(permanent)\n this.downloadSmall.setAuthKey(permanent)\n\n if (salts) {\n this._salts.setFutureSalts(salts)\n }\n\n if (!permanent) {\n return false\n }\n\n if (this.manager.params.usePfs || forcePfs) {\n const now = Date.now()\n await Promise.all(\n this.main._sessions.map(async (_, i) => {\n const temp = await this.manager._storage.provider.authKeys.getTemp(this.dcId, i, now)\n this.main.setAuthKey(temp, true, i)\n\n if (i === 0) {\n this.upload.setAuthKey(temp, true)\n this.download.setAuthKey(temp, true)\n this.downloadSmall.setAuthKey(temp, true)\n }\n }),\n )\n }\n\n return true\n }\n\n setMainConnectionCount(count: number): void {\n if (this._mainCountOverride > 0) return\n\n this.main.setCount(count)\n }\n\n async destroy() {\n await this.main.destroy()\n await this.upload.destroy()\n await this.download.destroy()\n await this.downloadSmall.destroy()\n this._salts.destroy()\n }\n}\n\n/**\n * Class that manages all connections to Telegram servers.\n */\nexport class NetworkManager {\n readonly _log\n readonly _storage\n\n readonly _initConnectionParams: tl.RawInitConnectionRequest\n readonly _transportFactory: TransportFactory\n readonly _reconnectionStrategy: ReconnectionStrategy<PersistentConnectionParams>\n readonly _connectionCount: ConnectionCountDelegate\n\n protected readonly _dcConnections = new Map<number, DcConnectionManager>()\n protected _primaryDc?: DcConnectionManager\n\n private _updateHandler: (upd: tl.TypeUpdates, fromClient: boolean) => void\n\n constructor(\n readonly params: NetworkManagerParams & NetworkManagerExtraParams,\n readonly config: ConfigManager,\n ) {\n const deviceModel = `mtcute on ${getPlatform().getDeviceModel()}`\n\n this._initConnectionParams = {\n _: 'initConnection',\n deviceModel,\n systemVersion: '1.0',\n appVersion: '%VERSION%',\n systemLangCode: 'en',\n langPack: '', // \"langPacks are for official apps only\"\n langCode: 'en',\n ...(params.initConnectionOptions ?? {}),\n apiId: params.apiId,\n // eslint-disable-next-line\n query: null as any,\n }\n\n this._transportFactory = params.transport\n this._reconnectionStrategy = params.reconnectionStrategy ?? defaultReconnectionStrategy\n this._connectionCount = params.connectionCount ?? defaultConnectionCountDelegate\n this._updateHandler = params.onUpdate\n\n this._onConfigChanged = this._onConfigChanged.bind(this)\n config.onReload(this._onConfigChanged)\n\n this._log = params.log.create('network')\n this._storage = params.storage\n }\n\n private async _findDcOptions(dcId: number): Promise<DcOptions> {\n const main = await this.config.findOption({\n dcId,\n allowIpv6: this.params.useIpv6,\n preferIpv6: this.params.useIpv6,\n allowMedia: false,\n cdn: false,\n })\n\n const media = await this.config.findOption({\n dcId,\n allowIpv6: this.params.useIpv6,\n preferIpv6: this.params.useIpv6,\n allowMedia: true,\n preferMedia: true,\n cdn: false,\n })\n\n if (!main || !media) {\n throw new MtArgumentError(`Could not find DC ${dcId}`)\n }\n\n return { main, media }\n }\n\n private _resetOnNetworkChange?: () => void\n\n private _switchPrimaryDc(dc: DcConnectionManager) {\n if (this._primaryDc && this._primaryDc !== dc) {\n this._primaryDc.setIsPrimary(false)\n }\n\n this._primaryDc = dc\n dc.setIsPrimary(true)\n\n this.params.onConnecting()\n\n dc.main.on('usable', () => {\n if (dc !== this._primaryDc) return\n this.params.onUsable()\n })\n dc.main.on('wait', () => {\n if (dc !== this._primaryDc) return\n this.params.onConnecting()\n })\n dc.main.on('update', (update: tl.TypeUpdates) => {\n this._updateHandler(update, false)\n })\n\n return dc.loadKeys().then(() => dc.main.ensureConnected())\n }\n\n private _dcCreationPromise = new Map<number, Promise<void>>()\n async _getOtherDc(dcId: number): Promise<DcConnectionManager> {\n if (!this._dcConnections.has(dcId)) {\n if (this._dcCreationPromise.has(dcId)) {\n this._log.debug('waiting for DC %d to be created', dcId)\n await this._dcCreationPromise.get(dcId)\n\n return this._dcConnections.get(dcId)!\n }\n\n const promise = createControllablePromise<void>()\n this._dcCreationPromise.set(dcId, promise)\n\n this._log.debug('creating new DC %d', dcId)\n\n try {\n const dcOptions = await this._findDcOptions(dcId)\n\n const dc = new DcConnectionManager(this, dcId, dcOptions)\n\n if (!(await dc.loadKeys())) {\n dc.main.requestAuth()\n }\n\n this._dcConnections.set(dcId, dc)\n promise.resolve()\n } catch (e) {\n promise.reject(e)\n }\n }\n\n return this._dcConnections.get(dcId)!\n }\n\n /**\n * Perform initial connection to the default DC\n *\n * @param defaultDcs Default DCs to connect to\n */\n async connect(defaultDcs: DcOptions): Promise<void> {\n if (defaultDcs.main.id !== defaultDcs.media.id) {\n throw new MtArgumentError('Default DCs must be the same')\n }\n\n if (this._dcConnections.has(defaultDcs.main.id)) {\n // shouldn't happen\n throw new MtArgumentError('DC manager already exists')\n }\n\n this._resetOnNetworkChange = getPlatform().onNetworkChanged?.(this.notifyNetworkChanged.bind(this))\n\n const dc = new DcConnectionManager(this, defaultDcs.main.id, defaultDcs, true)\n this._dcConnections.set(defaultDcs.main.id, dc)\n await this._switchPrimaryDc(dc)\n }\n\n private _pendingExports: Record<number, Promise<void>> = {}\n private async _exportAuthTo(manager: DcConnectionManager): Promise<void> {\n if (manager.dcId in this._pendingExports) {\n this._log.debug('waiting for auth export to dc %d', manager.dcId)\n\n return this._pendingExports[manager.dcId]\n }\n\n this._log.debug('exporting auth to dc %d', manager.dcId)\n const promise = createControllablePromise<void>()\n this._pendingExports[manager.dcId] = promise\n\n try {\n const auth = await this.call({\n _: 'auth.exportAuthorization',\n dcId: manager.dcId,\n })\n\n if (isTlRpcError(auth)) {\n throw new MtcuteError(`Failed to export (${auth.errorCode}: ${auth.errorMessage})`)\n }\n\n const res = await this.call(\n {\n _: 'auth.importAuthorization',\n id: auth.id,\n bytes: auth.bytes,\n },\n { manager },\n )\n\n if (isTlRpcError(res)) {\n throw new MtcuteError(`Failed to import (${res.errorCode}: ${res.errorMessage})`)\n }\n\n assertTypeIs('auth.importAuthorization', res, 'auth.authorization')\n\n promise.resolve()\n delete this._pendingExports[manager.dcId]\n } catch (e) {\n this._log.warn('failed to export auth to dc %d: %s', manager.dcId, e)\n promise.reject(e)\n throw e\n }\n }\n\n setIsPremium(isPremium: boolean): void {\n this._log.debug('setting isPremium to %s', isPremium)\n this.params.isPremium = isPremium\n\n for (const dc of this._dcConnections.values()) {\n dc.setIsPremium(isPremium)\n }\n }\n\n notifyLoggedIn(auth: tl.auth.TypeAuthorization | tl.RawUser): tl.RawUser {\n if (auth._ === 'auth.authorizationSignUpRequired') {\n throw new MtUnsupportedError(\n 'Signup is no longer supported by Telegram for non-official clients. Please use your mobile device to sign up.',\n )\n }\n\n let user: tl.RawUser\n\n if (auth._ === 'auth.authorization') {\n if (auth.tmpSessions) {\n this._primaryDc?.setMainConnectionCount(auth.tmpSessions)\n }\n\n user = auth.user as tl.RawUser\n } else {\n if (auth.bot) {\n // bots may receive tmpSessions, which we should respect\n this.config.update(true).catch((e: Error) => this.params.emitError(e))\n }\n\n user = auth\n }\n\n this.setIsPremium(user.premium!)\n\n // telegram ignores invokeWithoutUpdates for auth methods\n if (auth._ === 'auth.authorization' && this.params.disableUpdates) {\n this.resetSessions()\n }\n\n return user\n }\n\n notifyLoggedOut(): void {\n this.setIsPremium(false)\n this.resetSessions()\n }\n\n notifyNetworkChanged(connected: boolean): void {\n this._log.debug('network changed: %s', connected ? 'connected' : 'disconnected')\n this.params.onNetworkChanged(connected)\n\n for (const dc of this._dcConnections.values()) {\n dc.main.notifyNetworkChanged(connected)\n dc.upload.notifyNetworkChanged(connected)\n dc.download.notifyNetworkChanged(connected)\n dc.downloadSmall.notifyNetworkChanged(connected)\n }\n }\n\n resetSessions(): void {\n const dc = this._primaryDc\n if (!dc) return\n\n dc.main.resetSessions()\n dc.upload.resetSessions()\n dc.download.resetSessions()\n dc.downloadSmall.resetSessions()\n }\n\n private _onConfigChanged(config: tl.RawConfig): void {\n if (config.tmpSessions) {\n this._primaryDc?.setMainConnectionCount(config.tmpSessions)\n }\n }\n\n async changePrimaryDc(newDc: number): Promise<void> {\n if (newDc === this._primaryDc?.dcId) return\n\n const options = await this._findDcOptions(newDc)\n\n if (!this._dcConnections.has(newDc)) {\n this._dcConnections.set(newDc, new DcConnectionManager(this, newDc, options, true))\n }\n\n await this._storage.dcs.store(options)\n\n await this._switchPrimaryDc(this._dcConnections.get(newDc)!)\n }\n\n private _floodWaitedRequests = new Map<string, number>()\n async call<T extends tl.RpcMethod>(\n message: T,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']] | mtp.RawMt_rpc_error> {\n if (!this._primaryDc) {\n throw new MtcuteError('Not connected to any DC')\n }\n\n const floodSleepThreshold = params?.floodSleepThreshold ?? this.params.floodSleepThreshold\n const maxRetryCount = params?.maxRetryCount ?? this.params.maxRetryCount\n const throw503 = params?.throw503 ?? false\n\n // do not send requests that are in flood wait\n if (this._floodWaitedRequests.has(message._)) {\n const delta = this._floodWaitedRequests.get(message._)! - Date.now()\n\n if (delta <= 3000) {\n // flood waits below 3 seconds are \"ignored\"\n this._floodWaitedRequests.delete(message._)\n } else if (delta <= this.params.floodSleepThreshold) {\n await sleepWithAbort(delta, this.params.stopSignal)\n this._floodWaitedRequests.delete(message._)\n } else {\n const err = tl.RpcError.create(tl.RpcError.FLOOD, 'FLOOD_WAIT_%d')\n err.seconds = Math.ceil(delta / 1000)\n throw err\n }\n }\n\n let lastError: mtp.RawMt_rpc_error | null = null\n\n const kind = params?.kind ?? 'main'\n let manager: DcConnectionManager\n\n if (params?.manager) {\n manager = params.manager\n } else if (params?.dcId && params.dcId !== this._primaryDc.dcId) {\n manager = await this._getOtherDc(params.dcId)\n } else {\n manager = this._primaryDc\n }\n\n let multi = manager[kind]\n\n for (let i = 0; i < maxRetryCount; i++) {\n const res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId)\n\n if (!isTlRpcError(res)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n lastError = res\n\n const err = res.errorMessage\n\n if (!(res.errorCode in CLIENT_ERRORS)) {\n if (throw503 && res.errorCode === -503) {\n throw new MtTimeoutError()\n }\n\n this._log.warn('Telegram is having internal issues: %d:%s, retrying', res.errorCode, err)\n\n if (err === 'WORKER_BUSY_TOO_LONG_RETRY') {\n // according to tdlib, \"it is dangerous to resend query without timeout, so use 1\"\n await sleepWithAbort(1000, this.params.stopSignal)\n }\n continue\n }\n\n if (\n err.startsWith('FLOOD_WAIT_') ||\n err.startsWith('SLOWMODE_WAIT_') ||\n err.startsWith('FLOOD_TEST_PHONE_WAIT_')\n ) {\n let seconds = Number(err.lastIndexOf('_') + 1)\n\n if (Number.isNaN(seconds)) {\n this._log.warn('invalid flood wait error received: %s, ignoring', err)\n\n return res\n }\n\n if (!err.startsWith('SLOWMODE_WAIT_')) {\n // SLOW_MODE_WAIT is chat-specific, not request-specific\n this._floodWaitedRequests.set(message._, Date.now() + seconds * 1000)\n }\n\n // In test servers, FLOOD_WAIT_0 has been observed, and sleeping for\n // such a short amount will cause retries very fast leading to issues\n if (seconds === 0) {\n seconds = 1\n }\n\n if (seconds <= floodSleepThreshold) {\n this._log.warn('%s resulted in a flood wait, will retry in %d seconds', message._, seconds)\n await sleepWithAbort(seconds * 1000, this.params.stopSignal)\n continue\n }\n }\n\n if (manager === this._primaryDc) {\n if (\n err.startsWith('PHONE_MIGRATE_') ||\n err.startsWith('NETWORK_MIGRATE_') ||\n err.startsWith('USER_MIGRATE_')\n ) {\n const newDc = Number(err.slice(err.lastIndexOf('_') + 1))\n\n if (Number.isNaN(newDc)) {\n this._log.warn('invalid migrate error received: %s, ignoring', err)\n\n return res\n }\n\n if (params?.localMigrate) {\n manager = await this._getOtherDc(newDc)\n } else {\n this._log.info('Migrate error, new dc = %d', newDc)\n\n await this.changePrimaryDc(newDc)\n manager = this._primaryDc!\n }\n\n multi = manager[kind]\n\n continue\n }\n } else if (err === 'AUTH_KEY_UNREGISTERED') {\n // we can try re-exporting auth from the primary connection\n this._log.warn('exported auth key error, trying re-exporting..')\n\n await this._exportAuthTo(manager)\n continue\n }\n }\n\n return lastError!\n }\n\n changeTransport(factory: TransportFactory): void {\n for (const dc of this._dcConnections.values()) {\n dc.main.changeTransport(factory)\n dc.upload.changeTransport(factory)\n dc.download.changeTransport(factory)\n dc.downloadSmall.changeTransport(factory)\n }\n }\n\n getPoolSize(kind: ConnectionKind, dcId?: number) {\n const dc = dcId ? this._dcConnections.get(dcId) : this._primaryDc\n\n if (!dc) {\n if (!this._primaryDc) {\n throw new MtcuteError('Not connected to any DC')\n }\n\n // guess based on the provided delegate. it is most likely correct,\n // but we should give actual values if possible\n return this._connectionCount(kind, dcId ?? this._primaryDc.dcId, this.params.isPremium)\n }\n\n return dc[kind].getPoolSize()\n }\n\n getPrimaryDcId() {\n if (!this._primaryDc) throw new MtcuteError('Not connected to any DC')\n\n return this._primaryDc.dcId\n }\n\n async destroy(): Promise<void> {\n for (const dc of this._dcConnections.values()) {\n await dc.destroy()\n }\n this._dcConnections.clear()\n this.config.offReload(this._onConfigChanged)\n this._resetOnNetworkChange?.()\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"network-manager.js","sourceRoot":"","sources":["../../../src/network/network-manager.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAE,MAAM,gBA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C,CAAC,CAAC,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAA;QAEjE,IAAI,CAAC,EAAE,EAAE,CAAC;YACN,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;gBACnB,MAAM,IAAI,WAAW,CAAC,yBAAyB,CAAC,CAAA;YACpD,CAAC;YAED,mEAAmE;YACnE,+CAA+C;YAC/C,OAAO,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAA;QAC3F,CAAC;QAED,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,CAAA;IACjC,CAAC;IAED,cAAc;QACV,IAAI,CAAC,IAAI,CAAC,UAAU;YAAE,MAAM,IAAI,WAAW,CAAC,yBAAyB,CAAC,CAAA;QAEtE,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAA;IAC/B,CAAC;IAED,KAAK,CAAC,OAAO;QACT,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,EAAE,CAAC;YAC5C,MAAM,EAAE,CAAC,OAAO,EAAE,CAAA;QACtB,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAA;QAC3B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAA;QAC5C,IAAI,CAAC,qBAAqB,EAAE,EAAE,CAAA;IAClC,CAAC;CACJ","sourcesContent":["import { mtp, tl } from '@mtcute/tl'\nimport { TlReaderMap, TlWriterMap } from '@mtcute/tl-runtime'\n\nimport { getPlatform } from '../platform.js'\nimport { StorageManager } from '../storage/storage.js'\nimport { MtArgumentError, MtcuteError, MtUnsupportedError } from '../types/index.js'\nimport { ComposedMiddleware, composeMiddlewares, Middleware } from '../utils/composer.js'\nimport { ControllablePromise, createControllablePromise, DcOptions, ICryptoProvider, Logger } from '../utils/index.js'\nimport { assertTypeIs, isTlRpcError } from '../utils/type-assertions.js'\nimport { ConfigManager } from './config-manager.js'\nimport { basic as defaultMiddlewares } from './middlewares/default.js'\nimport { MultiSessionConnection } from './multi-session-connection.js'\nimport { PersistentConnectionParams } from './persistent-connection.js'\nimport { defaultReconnectionStrategy, ReconnectionStrategy } from './reconnection.js'\nimport { ServerSaltManager } from './server-salt.js'\nimport { SessionConnection, SessionConnectionParams } from './session-connection.js'\nimport { TransportFactory } from './transports/index.js'\n\nexport type ConnectionKind = 'main' | 'upload' | 'download' | 'downloadSmall'\n\n/**\n * Params passed into {@link NetworkManager} by {@link TelegramClient}.\n * This type is intended for internal usage only.\n */\nexport interface NetworkManagerParams {\n storage: StorageManager\n crypto: ICryptoProvider\n log: Logger\n\n enableErrorReporting: boolean\n apiId: number\n initConnectionOptions?: Partial<Omit<tl.RawInitConnectionRequest, 'apiId' | 'query'>>\n transport: TransportFactory\n reconnectionStrategy?: ReconnectionStrategy<PersistentConnectionParams>\n disableUpdates?: boolean\n testMode: boolean\n layer: number\n useIpv6: boolean\n readerMap: TlReaderMap\n writerMap: TlWriterMap\n isPremium: boolean\n emitError: (err: Error, connection?: SessionConnection) => void\n onUpdate: (upd: tl.TypeUpdates) => void\n onUsable: () => void\n onConnecting: () => void\n onNetworkChanged: (connected: boolean) => void\n stopSignal: AbortSignal\n}\n\nexport type ConnectionCountDelegate = (kind: ConnectionKind, dcId: number, isPremium: boolean) => number\n\nconst defaultConnectionCountDelegate: ConnectionCountDelegate = (kind, dcId, isPremium) => {\n switch (kind) {\n case 'main':\n return 0\n case 'upload':\n return isPremium || (dcId !== 2 && dcId !== 4) ? 8 : 4\n case 'download':\n return isPremium ? 8 : 2\n case 'downloadSmall':\n return 2\n }\n}\n\n/**\n * Additional params passed into {@link NetworkManager} by the user\n * that customize the behavior of the manager\n */\nexport interface NetworkManagerExtraParams {\n /**\n * Whether to use PFS (Perfect Forward Secrecy) for all connections.\n * This is disabled by default\n */\n usePfs?: boolean\n\n /**\n * Connection count for each connection kind.\n * The function should be pure to avoid unexpected behavior.\n *\n * Defaults to TDLib logic:\n * - main: 0 (which stands for \"handle internally, based on tmp_sessions value\")\n * - upload: if premium or dc id is other than 2 or 4, then 8, otherwise 4\n * - download: if premium then 8, otherwise 2\n * - downloadSmall: 2\n *\n * Non-zero value for `main` is **for advanced users only**\n * as it may lead to unexpected behavior, and is generally not recommended\n * because of unnecessary extra load on both the server and the client as well as\n * increased possibility of encountering AUTH_KEY_DUPLICATED errors.\n */\n connectionCount?: ConnectionCountDelegate\n\n /**\n * Idle timeout for non-main connections, in ms\n *\n * @default 60000 (60 seconds).\n */\n inactivityTimeout?: number\n\n /**\n * List of middlewares to use for the network manager\n *\n * > **Note**: these middlewares apply to **outgoing requests only**.\n * > If you need to handle incoming updates, use a {@link Dispatcher} instead.\n */\n middlewares?: Middleware<RpcCallMiddlewareContext, unknown>[]\n}\n\n/** Options that can be customized when making an RPC call */\nexport interface RpcCallOptions {\n /**\n * If the call results in a `FLOOD_WAIT_X` error,\n * the maximum amount of time to wait before retrying.\n *\n * If set to `0`, the call will not be retried.\n *\n * Only applies when the flood waiter middleware is enabled.\n */\n floodSleepThreshold?: number\n\n /**\n * If the call results in an internal server error or a flood wait,\n * the maximum amount of times to retry the call.\n *\n * Only applies when the flood waiter middleware and/or\n * internal errors handler middleware is enabled.\n */\n maxRetryCount?: number\n\n /**\n * Timeout for the call, in milliseconds.\n *\n * @default Infinity\n */\n timeout?: number\n\n /**\n * **ADVANCED**\n *\n * Kind of connection to use for this call.\n *\n * @default 'main'\n */\n kind?: ConnectionKind\n\n /**\n * **ADVANCED**\n *\n * ID of the DC to use for this call\n */\n dcId?: number\n\n /**\n * **ADVANCED**\n *\n * DC connection manager to use for this call.\n * Overrides `dcId` if set.\n */\n manager?: DcConnectionManager\n\n /**\n * Abort signal for the call.\n */\n abortSignal?: AbortSignal\n\n /**\n * Whether we should not retry on -503 errors and throw {@link MtTimeoutError} immediately instead.\n *\n * Useful for methods like `messages.getBotCallbackAnswer` that reliably return\n * -503 in case the upstream bot failed to respond.\n *\n * Only applies if the internal error handler middleware is enabled,\n * otherwise -503 is always thrown.\n */\n throw503?: boolean\n\n /**\n * Whether the `X_MIGRATE_%d` errors should be handled locally on request level\n * instead of changing the default datacenter for the entire client.\n *\n * Useful for `invokeWithBusinessConnection`, as it returns a `USER_MIGRATE_%d` error\n * that is in fact not related to the user, but to the specific request.\n */\n localMigrate?: boolean\n\n /**\n * Some requests should be processed consecutively, and not in parallel.\n * Using the same `chainId` for multiple requests will ensure that they are processed in the order\n * of calling `.call()`.\n *\n * Particularly useful for `messages.sendMessage` and alike.\n */\n chainId?: string | number\n}\n\nexport interface RpcCallMiddlewareContext {\n request: tl.RpcMethod\n manager: NetworkManager\n params?: RpcCallOptions\n}\nexport type RpcCallMiddleware<Result = unknown> = Middleware<RpcCallMiddlewareContext, Result>\n\n/**\n * Wrapper over all connection pools for a single DC.\n */\nexport class DcConnectionManager {\n private _salts = new ServerSaltManager()\n private _log\n\n /** Main connection pool */\n main: MultiSessionConnection\n /** Upload connection pool */\n upload: MultiSessionConnection\n /** Download connection pool */\n download: MultiSessionConnection\n /** Download connection pool (for small files) */\n downloadSmall: MultiSessionConnection\n\n private get _mainCountOverride() {\n return this.manager.params.connectionCount?.('main', this.dcId, this.manager.params.isPremium) ?? 0\n }\n\n constructor(\n /** Network manager instance */\n readonly manager: NetworkManager,\n /** DC ID */\n readonly dcId: number,\n /** DC options to use */\n readonly _dcs: DcOptions,\n /** Whether this DC is the primary one */\n public isPrimary = false,\n ) {\n this._log = this.manager._log.create('dc-manager')\n this._log.prefix = `[DC ${dcId}] `\n\n const baseConnectionParams = (): SessionConnectionParams => ({\n crypto: this.manager.params.crypto,\n initConnection: this.manager._initConnectionParams,\n transportFactory: this.manager._transportFactory,\n dc: this._dcs.media,\n testMode: this.manager.params.testMode,\n reconnectionStrategy: this.manager._reconnectionStrategy,\n layer: this.manager.params.layer,\n disableUpdates: this.manager.params.disableUpdates,\n readerMap: this.manager.params.readerMap,\n writerMap: this.manager.params.writerMap,\n usePfs: this.manager.params.usePfs,\n isMainConnection: false,\n isMainDcConnection: this.isPrimary,\n inactivityTimeout: this.manager.params.inactivityTimeout ?? 60_000,\n enableErrorReporting: this.manager.params.enableErrorReporting,\n salts: this._salts,\n })\n\n const mainParams = baseConnectionParams()\n mainParams.isMainConnection = true\n mainParams.dc = _dcs.main\n\n if (isPrimary) {\n mainParams.inactivityTimeout = undefined\n }\n\n let mainCount\n\n if (this.isPrimary) {\n mainCount = this._mainCountOverride\n\n if (mainCount === 0) {\n mainCount = this.manager.config.getNow()?.tmpSessions ?? 1\n }\n } else {\n mainCount = 1\n }\n\n this.main = new MultiSessionConnection(mainParams, mainCount, this._log, 'MAIN')\n this.upload = new MultiSessionConnection(\n baseConnectionParams(),\n this.manager._connectionCount('upload', this.dcId, this.manager.params.isPremium),\n this._log,\n 'UPLOAD',\n )\n this.download = new MultiSessionConnection(\n baseConnectionParams(),\n this.manager._connectionCount('download', this.dcId, this.manager.params.isPremium),\n this._log,\n 'DOWNLOAD',\n )\n this.downloadSmall = new MultiSessionConnection(\n baseConnectionParams(),\n this.manager._connectionCount('downloadSmall', this.dcId, this.manager.params.isPremium),\n this._log,\n 'DOWNLOAD_SMALL',\n )\n\n this._setupMulti('main')\n this._setupMulti('upload')\n this._setupMulti('download')\n this._setupMulti('downloadSmall')\n }\n\n private _setupMulti(kind: ConnectionKind): void {\n const connection = this[kind]\n\n connection.on('key-change', (idx, key: Uint8Array | null) => {\n if (kind !== 'main') {\n // main connection is responsible for authorization,\n // and keys are then sent to other connections\n this.manager._log.warn('got key-change from non-main connection, ignoring')\n\n return\n }\n\n this.manager._log.debug('key change for dc %d from connection %d', this.dcId, idx)\n\n // send key to other connections\n this.upload.setAuthKey(key)\n this.download.setAuthKey(key)\n this.downloadSmall.setAuthKey(key)\n Promise.resolve(this.manager._storage.provider.authKeys.set(this.dcId, key))\n .then(() => {\n this.upload.notifyKeyChange()\n this.download.notifyKeyChange()\n this.downloadSmall.notifyKeyChange()\n })\n .catch((e: Error) => {\n this.manager._log.warn('failed to save auth key for dc %d: %e', this.dcId, e)\n this.manager.params.emitError(e)\n })\n })\n connection.on('tmp-key-change', (idx: number, key: Uint8Array | null, expires: number) => {\n if (kind !== 'main') {\n this.manager._log.warn('got tmp-key-change from non-main connection, ignoring')\n\n return\n }\n\n this.manager._log.debug('temp key change for dc %d from connection %d', this.dcId, idx)\n\n // send key to other connections\n this.upload.setAuthKey(key, true)\n this.download.setAuthKey(key, true)\n this.downloadSmall.setAuthKey(key, true)\n\n Promise.resolve(this.manager._storage.provider.authKeys.setTemp(this.dcId, idx, key, expires * 1000))\n .then(() => {\n this.upload.notifyKeyChange()\n this.download.notifyKeyChange()\n this.downloadSmall.notifyKeyChange()\n })\n .catch((e: Error) => {\n this.manager._log.warn('failed to save temp auth key %d for dc %d: %e', idx, this.dcId, e)\n this.manager.params.emitError(e)\n })\n })\n connection.on('future-salts', (salts: mtp.RawMt_future_salt[]) => {\n Promise.resolve(this.manager._storage.salts.store(this.dcId, salts)).catch((e: Error) =>\n this.manager.params.emitError(e),\n )\n })\n\n connection.on('auth-begin', () => {\n // we need to propagate auth-begin to all connections\n // to avoid them sending requests before auth is complete\n if (kind !== 'main') {\n this.manager._log.warn('got auth-begin from non-main connection, ignoring')\n\n return\n }\n\n // reset key on non-main connections\n // this event was already propagated to additional main connections\n this.upload.resetAuthKeys()\n this.download.resetAuthKeys()\n this.downloadSmall.resetAuthKeys()\n })\n\n connection.on('request-auth', () => {\n this.main.requestAuth()\n })\n\n // fucking awesome architecture, but whatever\n connection.on('request-keys', (promise: ControllablePromise<void>) => {\n this.loadKeys(true)\n .then(() => promise.resolve())\n .catch((e: Error) => promise.reject(e))\n })\n\n connection.on('error', (err: Error, conn: SessionConnection) => {\n this.manager.params.emitError(err, conn)\n })\n }\n\n setIsPrimary(isPrimary: boolean): void {\n if (this.isPrimary === isPrimary) return\n this.isPrimary = isPrimary\n this.main.params.isMainDcConnection = isPrimary\n\n if (isPrimary) {\n this.main.setInactivityTimeout(undefined)\n } else {\n this.main.setInactivityTimeout(this.manager.params.inactivityTimeout ?? 60_000)\n }\n }\n\n setIsPremium(isPremium: boolean): void {\n this.upload.setCount(this.manager._connectionCount('upload', this.dcId, isPremium))\n this.download.setCount(this.manager._connectionCount('download', this.dcId, isPremium))\n this.downloadSmall.setCount(this.manager._connectionCount('downloadSmall', this.dcId, isPremium))\n }\n\n async loadKeys(forcePfs = false): Promise<boolean> {\n const [permanent, salts] = await Promise.all([\n this.manager._storage.provider.authKeys.get(this.dcId),\n this.manager._storage.salts.fetch(this.dcId),\n ])\n\n this.main.setAuthKey(permanent)\n this.upload.setAuthKey(permanent)\n this.download.setAuthKey(permanent)\n this.downloadSmall.setAuthKey(permanent)\n\n if (salts) {\n this._salts.setFutureSalts(salts)\n }\n\n if (!permanent) {\n return false\n }\n\n if (this.manager.params.usePfs || forcePfs) {\n const now = Date.now()\n await Promise.all(\n this.main._sessions.map(async (_, i) => {\n const temp = await this.manager._storage.provider.authKeys.getTemp(this.dcId, i, now)\n this.main.setAuthKey(temp, true, i)\n\n if (i === 0) {\n this.upload.setAuthKey(temp, true)\n this.download.setAuthKey(temp, true)\n this.downloadSmall.setAuthKey(temp, true)\n }\n }),\n )\n }\n\n return true\n }\n\n setMainConnectionCount(count: number): void {\n if (this._mainCountOverride > 0) return\n\n this.main.setCount(count)\n }\n\n async destroy() {\n await this.main.destroy()\n await this.upload.destroy()\n await this.download.destroy()\n await this.downloadSmall.destroy()\n this._salts.destroy()\n }\n}\n\n/**\n * Class that manages all connections to Telegram servers.\n */\nexport class NetworkManager {\n readonly _log\n readonly _storage\n\n readonly _initConnectionParams: tl.RawInitConnectionRequest\n readonly _transportFactory: TransportFactory\n readonly _reconnectionStrategy: ReconnectionStrategy<PersistentConnectionParams>\n readonly _connectionCount: ConnectionCountDelegate\n\n protected readonly _dcConnections = new Map<number, DcConnectionManager>()\n protected _primaryDc?: DcConnectionManager\n\n private _updateHandler: (upd: tl.TypeUpdates, fromClient: boolean) => void\n\n constructor(\n readonly params: NetworkManagerParams & NetworkManagerExtraParams,\n readonly config: ConfigManager,\n ) {\n const deviceModel = `mtcute on ${getPlatform().getDeviceModel()}`\n\n this._initConnectionParams = {\n _: 'initConnection',\n deviceModel,\n systemVersion: '1.0',\n appVersion: '%VERSION%',\n systemLangCode: 'en',\n langPack: '', // \"langPacks are for official apps only\"\n langCode: 'en',\n ...(params.initConnectionOptions ?? {}),\n apiId: params.apiId,\n // eslint-disable-next-line\n query: null as any,\n }\n\n this._transportFactory = params.transport\n this._reconnectionStrategy = params.reconnectionStrategy ?? defaultReconnectionStrategy\n this._connectionCount = params.connectionCount ?? defaultConnectionCountDelegate\n this._updateHandler = params.onUpdate\n\n this.call = this._composeCall(params.middlewares)\n\n this._onConfigChanged = this._onConfigChanged.bind(this)\n config.onReload(this._onConfigChanged)\n\n this._log = params.log.create('network')\n this._storage = params.storage\n }\n\n private async _findDcOptions(dcId: number): Promise<DcOptions> {\n const main = await this.config.findOption({\n dcId,\n allowIpv6: this.params.useIpv6,\n preferIpv6: this.params.useIpv6,\n allowMedia: false,\n cdn: false,\n })\n\n const media = await this.config.findOption({\n dcId,\n allowIpv6: this.params.useIpv6,\n preferIpv6: this.params.useIpv6,\n allowMedia: true,\n preferMedia: true,\n cdn: false,\n })\n\n if (!main || !media) {\n throw new MtArgumentError(`Could not find DC ${dcId}`)\n }\n\n return { main, media }\n }\n\n private _resetOnNetworkChange?: () => void\n\n private _switchPrimaryDc(dc: DcConnectionManager) {\n if (this._primaryDc && this._primaryDc !== dc) {\n this._primaryDc.setIsPrimary(false)\n }\n\n this._primaryDc = dc\n dc.setIsPrimary(true)\n\n this.params.onConnecting()\n\n dc.main.on('usable', () => {\n if (dc !== this._primaryDc) return\n this.params.onUsable()\n })\n dc.main.on('wait', () => {\n if (dc !== this._primaryDc) return\n this.params.onConnecting()\n })\n dc.main.on('update', (update: tl.TypeUpdates) => {\n this._updateHandler(update, false)\n })\n\n return dc.loadKeys().then(() => dc.main.ensureConnected())\n }\n\n private _dcCreationPromise = new Map<number, Promise<void>>()\n async _getOtherDc(dcId: number): Promise<DcConnectionManager> {\n if (!this._dcConnections.has(dcId)) {\n if (this._dcCreationPromise.has(dcId)) {\n this._log.debug('waiting for DC %d to be created', dcId)\n await this._dcCreationPromise.get(dcId)\n\n return this._dcConnections.get(dcId)!\n }\n\n const promise = createControllablePromise<void>()\n this._dcCreationPromise.set(dcId, promise)\n\n this._log.debug('creating new DC %d', dcId)\n\n try {\n const dcOptions = await this._findDcOptions(dcId)\n\n const dc = new DcConnectionManager(this, dcId, dcOptions)\n\n if (!(await dc.loadKeys())) {\n dc.main.requestAuth()\n }\n\n this._dcConnections.set(dcId, dc)\n promise.resolve()\n } catch (e) {\n promise.reject(e)\n }\n }\n\n return this._dcConnections.get(dcId)!\n }\n\n /**\n * Perform initial connection to the default DC\n *\n * @param defaultDcs Default DCs to connect to\n */\n async connect(defaultDcs: DcOptions): Promise<void> {\n if (defaultDcs.main.id !== defaultDcs.media.id) {\n throw new MtArgumentError('Default DCs must be the same')\n }\n\n if (this._dcConnections.has(defaultDcs.main.id)) {\n // shouldn't happen\n throw new MtArgumentError('DC manager already exists')\n }\n\n this._resetOnNetworkChange = getPlatform().onNetworkChanged?.(this.notifyNetworkChanged.bind(this))\n\n const dc = new DcConnectionManager(this, defaultDcs.main.id, defaultDcs, true)\n this._dcConnections.set(defaultDcs.main.id, dc)\n await this._switchPrimaryDc(dc)\n }\n\n private _pendingExports: Record<number, Promise<void>> = {}\n private async _exportAuthTo(manager: DcConnectionManager): Promise<void> {\n if (manager.dcId in this._pendingExports) {\n this._log.debug('waiting for auth export to dc %d', manager.dcId)\n\n return this._pendingExports[manager.dcId]\n }\n\n this._log.debug('exporting auth to dc %d', manager.dcId)\n const promise = createControllablePromise<void>()\n this._pendingExports[manager.dcId] = promise\n\n try {\n const auth = await this.call({\n _: 'auth.exportAuthorization',\n dcId: manager.dcId,\n })\n\n if (isTlRpcError(auth)) {\n throw new MtcuteError(`Failed to export (${auth.errorCode}: ${auth.errorMessage})`)\n }\n\n const res = await this.call(\n {\n _: 'auth.importAuthorization',\n id: auth.id,\n bytes: auth.bytes,\n },\n { manager },\n )\n\n if (isTlRpcError(res)) {\n throw new MtcuteError(`Failed to import (${res.errorCode}: ${res.errorMessage})`)\n }\n\n assertTypeIs('auth.importAuthorization', res, 'auth.authorization')\n\n promise.resolve()\n delete this._pendingExports[manager.dcId]\n } catch (e) {\n this._log.warn('failed to export auth to dc %d: %s', manager.dcId, e)\n promise.reject(e)\n throw e\n }\n }\n\n setIsPremium(isPremium: boolean): void {\n this._log.debug('setting isPremium to %s', isPremium)\n this.params.isPremium = isPremium\n\n for (const dc of this._dcConnections.values()) {\n dc.setIsPremium(isPremium)\n }\n }\n\n notifyLoggedIn(auth: tl.auth.TypeAuthorization | tl.RawUser): tl.RawUser {\n if (auth._ === 'auth.authorizationSignUpRequired') {\n throw new MtUnsupportedError(\n 'Signup is no longer supported by Telegram for non-official clients. Please use your mobile device to sign up.',\n )\n }\n\n let user: tl.RawUser\n\n if (auth._ === 'auth.authorization') {\n if (auth.tmpSessions) {\n this._primaryDc?.setMainConnectionCount(auth.tmpSessions)\n }\n\n user = auth.user as tl.RawUser\n } else {\n if (auth.bot) {\n // bots may receive tmpSessions, which we should respect\n this.config.update(true).catch((e: Error) => this.params.emitError(e))\n }\n\n user = auth\n }\n\n this.setIsPremium(user.premium!)\n\n // telegram ignores invokeWithoutUpdates for auth methods\n if (auth._ === 'auth.authorization' && this.params.disableUpdates) {\n this.resetSessions()\n }\n\n return user\n }\n\n notifyLoggedOut(): void {\n this.setIsPremium(false)\n this.resetSessions()\n }\n\n notifyNetworkChanged(connected: boolean): void {\n this._log.debug('network changed: %s', connected ? 'connected' : 'disconnected')\n this.params.onNetworkChanged(connected)\n\n for (const dc of this._dcConnections.values()) {\n dc.main.notifyNetworkChanged(connected)\n dc.upload.notifyNetworkChanged(connected)\n dc.download.notifyNetworkChanged(connected)\n dc.downloadSmall.notifyNetworkChanged(connected)\n }\n }\n\n resetSessions(): void {\n const dc = this._primaryDc\n if (!dc) return\n\n dc.main.resetSessions()\n dc.upload.resetSessions()\n dc.download.resetSessions()\n dc.downloadSmall.resetSessions()\n }\n\n private _onConfigChanged(config: tl.RawConfig): void {\n if (config.tmpSessions) {\n this._primaryDc?.setMainConnectionCount(config.tmpSessions)\n }\n }\n\n async changePrimaryDc(newDc: number): Promise<void> {\n if (newDc === this._primaryDc?.dcId) return\n\n const options = await this._findDcOptions(newDc)\n\n if (!this._dcConnections.has(newDc)) {\n this._dcConnections.set(newDc, new DcConnectionManager(this, newDc, options, true))\n }\n\n await this._storage.dcs.store(options)\n\n await this._switchPrimaryDc(this._dcConnections.get(newDc)!)\n }\n\n readonly call: <T extends tl.RpcMethod>(\n message: T,\n params?: RpcCallOptions,\n ) => Promise<tl.RpcCallReturn[T['_']] | mtp.RawMt_rpc_error>\n\n private _composeCall = (middlewares?: Middleware<RpcCallMiddlewareContext, unknown>[]) => {\n if (!middlewares) {\n middlewares = defaultMiddlewares()\n }\n\n if (!middlewares.length) {\n return this._call\n }\n\n const final: ComposedMiddleware<RpcCallMiddlewareContext, unknown> = async (ctx) => {\n return this._call(ctx.request, ctx.params)\n }\n const composed = composeMiddlewares(middlewares, final)\n\n return async <T extends tl.RpcMethod>(message: T, params?: RpcCallOptions): Promise<tl.RpcCallReturn[T['_']]> =>\n composed({\n request: message,\n manager: this,\n params,\n })\n }\n\n private _call = async <T extends tl.RpcMethod>(\n message: T,\n params?: RpcCallOptions,\n ): Promise<tl.RpcCallReturn[T['_']] | mtp.RawMt_rpc_error> => {\n if (!this._primaryDc) {\n throw new MtcuteError('Not connected to any DC')\n }\n\n const kind = params?.kind ?? 'main'\n let manager: DcConnectionManager\n\n if (params?.manager) {\n manager = params.manager\n } else if (params?.dcId && params.dcId !== this._primaryDc.dcId) {\n manager = await this._getOtherDc(params.dcId)\n } else {\n manager = this._primaryDc\n }\n\n let multi = manager[kind]\n\n let res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId)\n\n if (!isTlRpcError(res)) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n const err = res.errorMessage\n\n if (manager === this._primaryDc) {\n if (\n err.startsWith('PHONE_MIGRATE_') ||\n err.startsWith('NETWORK_MIGRATE_') ||\n err.startsWith('USER_MIGRATE_')\n ) {\n const newDc = Number(err.slice(err.lastIndexOf('_') + 1))\n\n if (Number.isNaN(newDc)) {\n this._log.warn('invalid migrate error received: %s, ignoring', err)\n\n return res\n }\n\n if (params?.localMigrate) {\n manager = await this._getOtherDc(newDc)\n } else {\n this._log.info('received %s, migrating to dc %d', err, newDc)\n\n await this.changePrimaryDc(newDc)\n manager = this._primaryDc!\n }\n\n multi = manager[kind]\n\n res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId)\n }\n } else if (err === 'AUTH_KEY_UNREGISTERED') {\n // we can try re-exporting auth from the primary connection\n this._log.warn('exported auth key error, trying re-exporting..')\n\n await this._exportAuthTo(manager)\n\n res = await multi.sendRpc(message, params?.timeout, params?.abortSignal, params?.chainId)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return res\n }\n\n changeTransport(factory: TransportFactory): void {\n for (const dc of this._dcConnections.values()) {\n dc.main.changeTransport(factory)\n dc.upload.changeTransport(factory)\n dc.download.changeTransport(factory)\n dc.downloadSmall.changeTransport(factory)\n }\n }\n\n getPoolSize(kind: ConnectionKind, dcId?: number) {\n const dc = dcId ? this._dcConnections.get(dcId) : this._primaryDc\n\n if (!dc) {\n if (!this._primaryDc) {\n throw new MtcuteError('Not connected to any DC')\n }\n\n // guess based on the provided delegate. it is most likely correct,\n // but we should give actual values if possible\n return this._connectionCount(kind, dcId ?? this._primaryDc.dcId, this.params.isPremium)\n }\n\n return dc[kind].getPoolSize()\n }\n\n getPrimaryDcId() {\n if (!this._primaryDc) throw new MtcuteError('Not connected to any DC')\n\n return this._primaryDc.dcId\n }\n\n async destroy(): Promise<void> {\n for (const dc of this._dcConnections.values()) {\n await dc.destroy()\n }\n this._dcConnections.clear()\n this.config.offReload(this._onConfigChanged)\n this._resetOnNetworkChange?.()\n }\n}\n"]}
|
|
@@ -39,7 +39,7 @@ export class PersistentConnection extends EventEmitter {
|
|
|
39
39
|
changeTransport(factory) {
|
|
40
40
|
if (this._transport) {
|
|
41
41
|
Promise.resolve(this._transport.close()).catch((err) => {
|
|
42
|
-
this.log.warn('error closing previous transport: %
|
|
42
|
+
this.log.warn('error closing previous transport: %e', err);
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
45
|
this._transport = factory();
|
|
@@ -62,7 +62,7 @@ export class PersistentConnection extends EventEmitter {
|
|
|
62
62
|
.send(data)
|
|
63
63
|
.then(sendNext)
|
|
64
64
|
.catch((err) => {
|
|
65
|
-
this.log.error('error sending queued data: %
|
|
65
|
+
this.log.error('error sending queued data: %e', err);
|
|
66
66
|
this._sendOnceConnected.unshift(data);
|
|
67
67
|
});
|
|
68
68
|
};
|
|
@@ -100,7 +100,7 @@ export class PersistentConnection extends EventEmitter {
|
|
|
100
100
|
const wait = this.params.reconnectionStrategy(this.params, this._lastError, this._consequentFails, this._previousWait);
|
|
101
101
|
if (wait === false) {
|
|
102
102
|
this.destroy().catch((err) => {
|
|
103
|
-
this.log.warn('error destroying connection: %
|
|
103
|
+
this.log.warn('error destroying connection: %e', err);
|
|
104
104
|
});
|
|
105
105
|
return;
|
|
106
106
|
}
|
|
@@ -138,7 +138,7 @@ export class PersistentConnection extends EventEmitter {
|
|
|
138
138
|
if (this.isConnected) {
|
|
139
139
|
this._shouldReconnectImmediately = true;
|
|
140
140
|
Promise.resolve(this._transport.close()).catch((err) => {
|
|
141
|
-
this.log.error('error closing transport: %
|
|
141
|
+
this.log.error('error closing transport: %e', err);
|
|
142
142
|
});
|
|
143
143
|
return;
|
|
144
144
|
}
|
|
@@ -172,7 +172,7 @@ export class PersistentConnection extends EventEmitter {
|
|
|
172
172
|
this._inactive = true;
|
|
173
173
|
this._inactivityTimeout = null;
|
|
174
174
|
Promise.resolve(this._transport.close()).catch((err) => {
|
|
175
|
-
this.log.warn('error closing transport: %
|
|
175
|
+
this.log.warn('error closing transport: %e', err);
|
|
176
176
|
});
|
|
177
177
|
}
|
|
178
178
|
setInactivityTimeout(timeout) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persistent-connection.js","sourceRoot":"","sources":["../../../src/network/persistent-connection.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,QAAQ,CAAA;AAEjC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAG/C,OAAO,EAAwC,cAAc,EAAE,MAAM,uBAAuB,CAAA;AAW5F,IAAI,iBAAiB,GAAG,CAAC,CAAA;AAEzB;;;;GAIG;AACH,MAAM,OAAgB,oBAAqB,SAAQ,YAAY;IA+B9C;IA9BL,IAAI,GAAG,iBAAiB,EAAE,CAAA;IAEzB,MAAM,CAA4B;IACjC,UAAU,CAAqB;IAEjC,kBAAkB,GAAiB,EAAE,CAAA;IAE7C,eAAe;IACP,UAAU,GAAiB,IAAI,CAAA;IAC/B,gBAAgB,GAAG,CAAC,CAAA;IACpB,aAAa,GAAkB,IAAI,CAAA;IACnC,oBAAoB,GAA0B,IAAI,CAAA;IAClD,2BAA2B,GAAG,KAAK,CAAA;IACjC,qBAAqB,GAAG,KAAK,CAAA;IAEvC,qBAAqB;IACb,kBAAkB,GAA0B,IAAI,CAAA;IAChD,SAAS,GAAG,IAAI,CAAA;IAExB,UAAU,GAAG,KAAK,CAAA;IAClB,OAAO,GAAG,KAAK,CAAA;IAQf,YACI,MAAkC,EACzB,GAAW;QAEpB,KAAK,EAAE,CAAA;QAFE,QAAG,GAAH,GAAG,CAAQ;QAGpB,IAAI,CAAC,MAAM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1B,YAAY,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;QACzC,CAAC;QAED,IAAI,OAAO,EAAE,CAAC;YACV,IAAI,CAAC,qBAAqB,EAAE,CAAA;QAChC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,IAAgB;QACvB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACjB,IAAI,CAAC,OAAO,EAAE,CAAA;QAClB,CAAC;QAED,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,KAAK,cAAc,CAAC,KAAK,EAAE,CAAC;YACnD,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACpC,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACtC,CAAC;IACL,CAAC;CACJ","sourcesContent":["import EventEmitter from 'events'\n\nimport { MtcuteError } from '../types/index.js'\nimport { BasicDcOption, ICryptoProvider, Logger } from '../utils/index.js'\nimport { ReconnectionStrategy } from './reconnection.js'\nimport { ITelegramTransport, TransportFactory, TransportState } from './transports/index.js'\n\nexport interface PersistentConnectionParams {\n crypto: ICryptoProvider\n transportFactory: TransportFactory\n dc: BasicDcOption\n testMode: boolean\n reconnectionStrategy: ReconnectionStrategy<PersistentConnectionParams>\n inactivityTimeout?: number\n}\n\nlet nextConnectionUid = 0\n\n/**\n * Base class for persistent connections.\n * Only used for {@link PersistentConnection} and used as a mean of code splitting.\n * This class doesn't know anything about MTProto, it just manages the transport.\n */\nexport abstract class PersistentConnection extends EventEmitter {\n private _uid = nextConnectionUid++\n\n readonly params: PersistentConnectionParams\n protected _transport!: ITelegramTransport\n\n private _sendOnceConnected: Uint8Array[] = []\n\n // reconnection\n private _lastError: Error | null = null\n private _consequentFails = 0\n private _previousWait: number | null = null\n private _reconnectionTimeout: NodeJS.Timeout | null = null\n private _shouldReconnectImmediately = false\n protected _disconnectedManually = false\n\n // inactivity timeout\n private _inactivityTimeout: NodeJS.Timeout | null = null\n private _inactive = true\n\n _destroyed = false\n _usable = false\n\n protected abstract onConnected(): void\n\n protected abstract onError(err: Error): void\n\n protected abstract onMessage(data: Uint8Array): void\n\n protected constructor(\n params: PersistentConnectionParams,\n readonly log: Logger,\n ) {\n super()\n this.params = params\n this.changeTransport(params.transportFactory)\n\n this.log.prefix = `[UID ${this._uid}] `\n\n this._onInactivityTimeout = this._onInactivityTimeout.bind(this)\n }\n\n get isConnected(): boolean {\n return this._transport.state() !== TransportState.Idle\n }\n\n changeTransport(factory: TransportFactory): void {\n if (this._transport) {\n Promise.resolve(this._transport.close()).catch((err) => {\n this.log.warn('error closing previous transport: %s', err)\n })\n }\n\n this._transport = factory()\n this._transport.setup?.(this.params.crypto, this.log)\n\n this._transport.on('ready', this.onTransportReady.bind(this))\n this._transport.on('message', this.onMessage.bind(this))\n this._transport.on('error', this.onTransportError.bind(this))\n this._transport.on('close', this.onTransportClose.bind(this))\n }\n\n onTransportReady(): void {\n // transport ready does not mean actual mtproto is ready\n if (this._sendOnceConnected.length) {\n const sendNext = () => {\n if (!this._sendOnceConnected.length) {\n this.onConnected()\n\n return\n }\n\n const data = this._sendOnceConnected.shift()!\n this._transport\n .send(data)\n .then(sendNext)\n .catch((err) => {\n this.log.error('error sending queued data: %s', err)\n this._sendOnceConnected.unshift(data)\n })\n }\n\n sendNext()\n\n return\n }\n\n this.onConnected()\n }\n\n protected onConnectionUsable(): void {\n const isReconnection = this._consequentFails > 0\n\n // reset reconnection related state\n this._lastError = null\n this._consequentFails = 0\n this._previousWait = null\n this._usable = true\n this.emit('usable', isReconnection)\n this._rescheduleInactivity()\n }\n\n onTransportError(err: Error): void {\n this._lastError = err\n this.onError(err)\n // transport is expected to emit `close` after `error`\n }\n\n onTransportClose(): void {\n // transport closed because of inactivity\n // obviously we dont want to reconnect then\n if (this._inactive || this._disconnectedManually) return\n\n if (this._shouldReconnectImmediately) {\n this._shouldReconnectImmediately = false\n this.connect()\n\n return\n }\n\n this._consequentFails += 1\n\n const wait = this.params.reconnectionStrategy(\n this.params,\n this._lastError,\n this._consequentFails,\n this._previousWait,\n )\n\n if (wait === false) {\n this.destroy().catch((err) => {\n this.log.warn('error destroying connection: %s', err)\n })\n\n return\n }\n\n this.emit('wait', wait)\n\n this._previousWait = wait\n\n if (this._reconnectionTimeout != null) {\n clearTimeout(this._reconnectionTimeout)\n }\n this._reconnectionTimeout = setTimeout(() => {\n if (this._destroyed) return\n this._reconnectionTimeout = null\n this.connect()\n }, wait)\n }\n\n connect(): void {\n if (this.isConnected) {\n throw new MtcuteError('Connection is already opened!')\n }\n if (this._destroyed) {\n throw new MtcuteError('Connection is already destroyed!')\n }\n\n if (this._reconnectionTimeout != null) {\n clearTimeout(this._reconnectionTimeout)\n this._reconnectionTimeout = null\n }\n\n this._inactive = false\n this._disconnectedManually = false\n this._transport.connect(this.params.dc, this.params.testMode)\n }\n\n reconnect(): void {\n if (this._inactive) return\n\n // if we are already connected\n if (this.isConnected) {\n this._shouldReconnectImmediately = true\n Promise.resolve(this._transport.close()).catch((err) => {\n this.log.error('error closing transport: %s', err)\n })\n\n return\n }\n\n // if reconnection timeout is pending, it will be cancelled in connect()\n this.connect()\n }\n\n async disconnectManual(): Promise<void> {\n this._disconnectedManually = true\n await this._transport.close()\n }\n\n async destroy(): Promise<void> {\n if (this._reconnectionTimeout != null) {\n clearTimeout(this._reconnectionTimeout)\n }\n if (this._inactivityTimeout != null) {\n clearTimeout(this._inactivityTimeout)\n }\n\n await this._transport.close()\n this._transport.removeAllListeners()\n this._destroyed = true\n }\n\n protected _rescheduleInactivity(): void {\n if (!this.params.inactivityTimeout) return\n if (this._inactivityTimeout) clearTimeout(this._inactivityTimeout)\n this._inactivityTimeout = setTimeout(this._onInactivityTimeout, this.params.inactivityTimeout)\n }\n\n protected _onInactivityTimeout(): void {\n this.log.info('disconnected because of inactivity for %d', this.params.inactivityTimeout)\n this._inactive = true\n this._inactivityTimeout = null\n Promise.resolve(this._transport.close()).catch((err) => {\n this.log.warn('error closing transport: %s', err)\n })\n }\n\n setInactivityTimeout(timeout?: number): void {\n this.params.inactivityTimeout = timeout\n\n if (this._inactivityTimeout) {\n clearTimeout(this._inactivityTimeout)\n }\n\n if (timeout) {\n this._rescheduleInactivity()\n }\n }\n\n async send(data: Uint8Array): Promise<void> {\n if (this._inactive) {\n this.connect()\n }\n\n if (this._transport.state() === TransportState.Ready) {\n await this._transport.send(data)\n } else {\n this._sendOnceConnected.push(data)\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"persistent-connection.js","sourceRoot":"","sources":["../../../src/network/persistent-connection.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,QAAQ,CAAA;AAEjC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAG/C,OAAO,EAAwC,cAAc,EAAE,MAAM,uBAAuB,CAAA;AAW5F,IAAI,iBAAiB,GAAG,CAAC,CAAA;AAEzB;;;;GAIG;AACH,MAAM,OAAgB,oBAAqB,SAAQ,YAAY;IA+B9C;IA9BL,IAAI,GAAG,iBAAiB,EAAE,CAAA;IAEzB,MAAM,CAA4B;IACjC,UAAU,CAAqB;IAEjC,kBAAkB,GAAiB,EAAE,CAAA;IAE7C,eAAe;IACP,UAAU,GAAiB,IAAI,CAAA;IAC/B,gBAAgB,GAAG,CAAC,CAAA;IACpB,aAAa,GAAkB,IAAI,CAAA;IACnC,oBAAoB,GAA0B,IAAI,CAAA;IAClD,2BAA2B,GAAG,KAAK,CAAA;IACjC,qBAAqB,GAAG,KAAK,CAAA;IAEvC,qBAAqB;IACb,kBAAkB,GAA0B,IAAI,CAAA;IAChD,SAAS,GAAG,IAAI,CAAA;IAExB,UAAU,GAAG,KAAK,CAAA;IAClB,OAAO,GAAG,KAAK,CAAA;IAQf,YACI,MAAkC,EACzB,GAAW;QAEpB,KAAK,EAAE,CAAA;QAFE,QAAG,GAAH,GAAG,CAAQ;QAGpB,IAAI,CAAC,MAAM,GAAG,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Y,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAA;QACzC,CAAC;QAED,IAAI,OAAO,EAAE,CAAC;YACV,IAAI,CAAC,qBAAqB,EAAE,CAAA;QAChC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,IAAgB;QACvB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACjB,IAAI,CAAC,OAAO,EAAE,CAAA;QAClB,CAAC;QAED,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,KAAK,cAAc,CAAC,KAAK,EAAE,CAAC;YACnD,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACpC,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QACtC,CAAC;IACL,CAAC;CACJ","sourcesContent":["import EventEmitter from 'events'\n\nimport { MtcuteError } from '../types/index.js'\nimport { BasicDcOption, ICryptoProvider, Logger } from '../utils/index.js'\nimport { ReconnectionStrategy } from './reconnection.js'\nimport { ITelegramTransport, TransportFactory, TransportState } from './transports/index.js'\n\nexport interface PersistentConnectionParams {\n crypto: ICryptoProvider\n transportFactory: TransportFactory\n dc: BasicDcOption\n testMode: boolean\n reconnectionStrategy: ReconnectionStrategy<PersistentConnectionParams>\n inactivityTimeout?: number\n}\n\nlet nextConnectionUid = 0\n\n/**\n * Base class for persistent connections.\n * Only used for {@link PersistentConnection} and used as a mean of code splitting.\n * This class doesn't know anything about MTProto, it just manages the transport.\n */\nexport abstract class PersistentConnection extends EventEmitter {\n private _uid = nextConnectionUid++\n\n readonly params: PersistentConnectionParams\n protected _transport!: ITelegramTransport\n\n private _sendOnceConnected: Uint8Array[] = []\n\n // reconnection\n private _lastError: Error | null = null\n private _consequentFails = 0\n private _previousWait: number | null = null\n private _reconnectionTimeout: NodeJS.Timeout | null = null\n private _shouldReconnectImmediately = false\n protected _disconnectedManually = false\n\n // inactivity timeout\n private _inactivityTimeout: NodeJS.Timeout | null = null\n private _inactive = true\n\n _destroyed = false\n _usable = false\n\n protected abstract onConnected(): void\n\n protected abstract onError(err: Error): void\n\n protected abstract onMessage(data: Uint8Array): void\n\n protected constructor(\n params: PersistentConnectionParams,\n readonly log: Logger,\n ) {\n super()\n this.params = params\n this.changeTransport(params.transportFactory)\n\n this.log.prefix = `[UID ${this._uid}] `\n\n this._onInactivityTimeout = this._onInactivityTimeout.bind(this)\n }\n\n get isConnected(): boolean {\n return this._transport.state() !== TransportState.Idle\n }\n\n changeTransport(factory: TransportFactory): void {\n if (this._transport) {\n Promise.resolve(this._transport.close()).catch((err) => {\n this.log.warn('error closing previous transport: %e', err)\n })\n }\n\n this._transport = factory()\n this._transport.setup?.(this.params.crypto, this.log)\n\n this._transport.on('ready', this.onTransportReady.bind(this))\n this._transport.on('message', this.onMessage.bind(this))\n this._transport.on('error', this.onTransportError.bind(this))\n this._transport.on('close', this.onTransportClose.bind(this))\n }\n\n onTransportReady(): void {\n // transport ready does not mean actual mtproto is ready\n if (this._sendOnceConnected.length) {\n const sendNext = () => {\n if (!this._sendOnceConnected.length) {\n this.onConnected()\n\n return\n }\n\n const data = this._sendOnceConnected.shift()!\n this._transport\n .send(data)\n .then(sendNext)\n .catch((err) => {\n this.log.error('error sending queued data: %e', err)\n this._sendOnceConnected.unshift(data)\n })\n }\n\n sendNext()\n\n return\n }\n\n this.onConnected()\n }\n\n protected onConnectionUsable(): void {\n const isReconnection = this._consequentFails > 0\n\n // reset reconnection related state\n this._lastError = null\n this._consequentFails = 0\n this._previousWait = null\n this._usable = true\n this.emit('usable', isReconnection)\n this._rescheduleInactivity()\n }\n\n onTransportError(err: Error): void {\n this._lastError = err\n this.onError(err)\n // transport is expected to emit `close` after `error`\n }\n\n onTransportClose(): void {\n // transport closed because of inactivity\n // obviously we dont want to reconnect then\n if (this._inactive || this._disconnectedManually) return\n\n if (this._shouldReconnectImmediately) {\n this._shouldReconnectImmediately = false\n this.connect()\n\n return\n }\n\n this._consequentFails += 1\n\n const wait = this.params.reconnectionStrategy(\n this.params,\n this._lastError,\n this._consequentFails,\n this._previousWait,\n )\n\n if (wait === false) {\n this.destroy().catch((err) => {\n this.log.warn('error destroying connection: %e', err)\n })\n\n return\n }\n\n this.emit('wait', wait)\n\n this._previousWait = wait\n\n if (this._reconnectionTimeout != null) {\n clearTimeout(this._reconnectionTimeout)\n }\n this._reconnectionTimeout = setTimeout(() => {\n if (this._destroyed) return\n this._reconnectionTimeout = null\n this.connect()\n }, wait)\n }\n\n connect(): void {\n if (this.isConnected) {\n throw new MtcuteError('Connection is already opened!')\n }\n if (this._destroyed) {\n throw new MtcuteError('Connection is already destroyed!')\n }\n\n if (this._reconnectionTimeout != null) {\n clearTimeout(this._reconnectionTimeout)\n this._reconnectionTimeout = null\n }\n\n this._inactive = false\n this._disconnectedManually = false\n this._transport.connect(this.params.dc, this.params.testMode)\n }\n\n reconnect(): void {\n if (this._inactive) return\n\n // if we are already connected\n if (this.isConnected) {\n this._shouldReconnectImmediately = true\n Promise.resolve(this._transport.close()).catch((err) => {\n this.log.error('error closing transport: %e', err)\n })\n\n return\n }\n\n // if reconnection timeout is pending, it will be cancelled in connect()\n this.connect()\n }\n\n async disconnectManual(): Promise<void> {\n this._disconnectedManually = true\n await this._transport.close()\n }\n\n async destroy(): Promise<void> {\n if (this._reconnectionTimeout != null) {\n clearTimeout(this._reconnectionTimeout)\n }\n if (this._inactivityTimeout != null) {\n clearTimeout(this._inactivityTimeout)\n }\n\n await this._transport.close()\n this._transport.removeAllListeners()\n this._destroyed = true\n }\n\n protected _rescheduleInactivity(): void {\n if (!this.params.inactivityTimeout) return\n if (this._inactivityTimeout) clearTimeout(this._inactivityTimeout)\n this._inactivityTimeout = setTimeout(this._onInactivityTimeout, this.params.inactivityTimeout)\n }\n\n protected _onInactivityTimeout(): void {\n this.log.info('disconnected because of inactivity for %d', this.params.inactivityTimeout)\n this._inactive = true\n this._inactivityTimeout = null\n Promise.resolve(this._transport.close()).catch((err) => {\n this.log.warn('error closing transport: %e', err)\n })\n }\n\n setInactivityTimeout(timeout?: number): void {\n this.params.inactivityTimeout = timeout\n\n if (this._inactivityTimeout) {\n clearTimeout(this._inactivityTimeout)\n }\n\n if (timeout) {\n this._rescheduleInactivity()\n }\n }\n\n async send(data: Uint8Array): Promise<void> {\n if (this._inactive) {\n this.connect()\n }\n\n if (this._transport.state() === TransportState.Ready) {\n await this._transport.send(data)\n } else {\n this._sendOnceConnected.push(data)\n }\n }\n}\n"]}
|