@mtcute/dispatcher 0.16.7 → 0.16.13
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/callback-data-builder.d.ts → callback-data-builder.d.ts} +2 -2
- package/callback-data-builder.test.d.ts +1 -0
- package/{esm/context → context}/base.d.ts +2 -2
- package/{esm/context → context}/business-message.d.ts +5 -6
- package/{esm/context → context}/callback-query.d.ts +6 -7
- package/{cjs/context → context}/chat-join-request.d.ts +3 -3
- package/{esm/context → context}/chosen-inline-result.d.ts +3 -3
- package/{esm/context → context}/inline-query.d.ts +4 -5
- package/{cjs/context → context}/message.d.ts +11 -6
- package/{cjs/context → context}/parse.d.ts +3 -3
- package/{esm/context → context}/pre-checkout-query.d.ts +3 -3
- package/{esm/context → context}/scene-transition.d.ts +1 -1
- package/{cjs/dispatcher.d.ts → dispatcher.d.ts} +9 -10
- package/{cjs/filters → filters}/bots.d.ts +4 -4
- package/filters/bots.test.d.ts +1 -0
- package/{cjs/filters → filters}/chat.d.ts +3 -3
- package/{esm/filters → filters}/group.d.ts +4 -4
- package/{cjs/filters → filters}/logic.d.ts +1 -1
- package/filters/logic.test.d.ts +1 -0
- package/{esm/filters → filters}/message.d.ts +9 -5
- package/{cjs/filters → filters}/state.d.ts +2 -2
- package/{esm/filters → filters}/text.d.ts +3 -3
- package/{cjs/filters → filters}/types.d.ts +2 -2
- package/{cjs/filters → filters}/updates.d.ts +2 -2
- package/{cjs/filters → filters}/user.d.ts +3 -4
- package/{cjs/handler.d.ts → handler.d.ts} +5 -5
- package/index.cjs +2534 -0
- package/index.d.ts +8 -1
- package/index.js +2529 -1
- package/package.json +28 -24
- package/{cjs/state → state}/key.d.ts +3 -3
- package/state/provider.d.ts +5 -0
- package/{cjs/state → state}/providers/memory.d.ts +3 -4
- package/{esm/state → state}/providers/sqlite.d.ts +3 -3
- package/{cjs/state → state}/repository.d.ts +1 -1
- package/{esm/state → state}/service.d.ts +2 -2
- package/{cjs/state → state}/update-state.d.ts +2 -2
- package/{esm/wizard.d.ts → wizard.d.ts} +5 -6
- package/cjs/callback-data-builder.js +0 -141
- package/cjs/callback-data-builder.js.map +0 -1
- package/cjs/context/base.d.ts +0 -9
- package/cjs/context/base.js +0 -3
- package/cjs/context/base.js.map +0 -1
- package/cjs/context/business-message.d.ts +0 -61
- package/cjs/context/business-message.js +0 -146
- package/cjs/context/business-message.js.map +0 -1
- package/cjs/context/callback-query.d.ts +0 -63
- package/cjs/context/callback-query.js +0 -109
- package/cjs/context/callback-query.js.map +0 -1
- package/cjs/context/chat-join-request.js +0 -35
- package/cjs/context/chat-join-request.js.map +0 -1
- package/cjs/context/chosen-inline-result.d.ts +0 -22
- package/cjs/context/chosen-inline-result.js +0 -36
- package/cjs/context/chosen-inline-result.js.map +0 -1
- package/cjs/context/index.js +0 -25
- package/cjs/context/index.js.map +0 -1
- package/cjs/context/inline-query.d.ts +0 -16
- package/cjs/context/inline-query.js +0 -23
- package/cjs/context/inline-query.js.map +0 -1
- package/cjs/context/message.js +0 -171
- package/cjs/context/message.js.map +0 -1
- package/cjs/context/parse.js +0 -42
- package/cjs/context/parse.js.map +0 -1
- package/cjs/context/pre-checkout-query.d.ts +0 -17
- package/cjs/context/pre-checkout-query.js +0 -27
- package/cjs/context/pre-checkout-query.js.map +0 -1
- package/cjs/context/scene-transition.d.ts +0 -24
- package/cjs/context/scene-transition.js +0 -52
- package/cjs/context/scene-transition.js.map +0 -1
- package/cjs/dispatcher.js +0 -908
- package/cjs/dispatcher.js.map +0 -1
- package/cjs/filters/bots.js +0 -135
- package/cjs/filters/bots.js.map +0 -1
- package/cjs/filters/bundle.js +0 -27
- package/cjs/filters/bundle.js.map +0 -1
- package/cjs/filters/chat.js +0 -56
- package/cjs/filters/chat.js.map +0 -1
- package/cjs/filters/group.d.ts +0 -26
- package/cjs/filters/group.js +0 -69
- package/cjs/filters/group.js.map +0 -1
- package/cjs/filters/index.js +0 -29
- package/cjs/filters/index.js.map +0 -1
- package/cjs/filters/logic.js +0 -112
- package/cjs/filters/logic.js.map +0 -1
- package/cjs/filters/message.d.ts +0 -215
- package/cjs/filters/message.js +0 -191
- package/cjs/filters/message.js.map +0 -1
- package/cjs/filters/state.js +0 -33
- package/cjs/filters/state.js.map +0 -1
- package/cjs/filters/text.d.ts +0 -64
- package/cjs/filters/text.js +0 -136
- package/cjs/filters/text.js.map +0 -1
- package/cjs/filters/types.js +0 -3
- package/cjs/filters/types.js.map +0 -1
- package/cjs/filters/updates.js +0 -40
- package/cjs/filters/updates.js.map +0 -1
- package/cjs/filters/user.js +0 -77
- package/cjs/filters/user.js.map +0 -1
- package/cjs/handler.js +0 -4
- package/cjs/handler.js.map +0 -1
- package/cjs/index.js +0 -31
- package/cjs/index.js.map +0 -1
- package/cjs/package.json +0 -3
- package/cjs/propagation.js +0 -27
- package/cjs/propagation.js.map +0 -1
- package/cjs/state/index.js +0 -22
- package/cjs/state/index.js.map +0 -1
- package/cjs/state/key.js +0 -43
- package/cjs/state/key.js.map +0 -1
- package/cjs/state/provider.d.ts +0 -5
- package/cjs/state/provider.js +0 -3
- package/cjs/state/provider.js.map +0 -1
- package/cjs/state/providers/index.js +0 -19
- package/cjs/state/providers/index.js.map +0 -1
- package/cjs/state/providers/memory.js +0 -81
- package/cjs/state/providers/memory.js.map +0 -1
- package/cjs/state/providers/sqlite.d.ts +0 -28
- package/cjs/state/providers/sqlite.js +0 -100
- package/cjs/state/providers/sqlite.js.map +0 -1
- package/cjs/state/repository.js +0 -3
- package/cjs/state/repository.js.map +0 -1
- package/cjs/state/service.d.ts +0 -20
- package/cjs/state/service.js +0 -70
- package/cjs/state/service.js.map +0 -1
- package/cjs/state/update-state.js +0 -219
- package/cjs/state/update-state.js.map +0 -1
- package/cjs/wizard.d.ts +0 -65
- package/cjs/wizard.js +0 -105
- package/cjs/wizard.js.map +0 -1
- package/esm/callback-data-builder.d.ts +0 -49
- package/esm/callback-data-builder.js +0 -137
- package/esm/callback-data-builder.js.map +0 -1
- package/esm/context/base.js +0 -2
- package/esm/context/base.js.map +0 -1
- package/esm/context/business-message.js +0 -142
- package/esm/context/business-message.js.map +0 -1
- package/esm/context/callback-query.js +0 -103
- package/esm/context/callback-query.js.map +0 -1
- package/esm/context/chat-join-request.d.ts +0 -17
- package/esm/context/chat-join-request.js +0 -31
- package/esm/context/chat-join-request.js.map +0 -1
- package/esm/context/chosen-inline-result.js +0 -32
- package/esm/context/chosen-inline-result.js.map +0 -1
- package/esm/context/index.d.ts +0 -9
- package/esm/context/index.js +0 -9
- package/esm/context/index.js.map +0 -1
- package/esm/context/inline-query.js +0 -19
- package/esm/context/inline-query.js.map +0 -1
- package/esm/context/message.d.ts +0 -77
- package/esm/context/message.js +0 -167
- package/esm/context/message.js.map +0 -1
- package/esm/context/parse.d.ts +0 -13
- package/esm/context/parse.js +0 -39
- package/esm/context/parse.js.map +0 -1
- package/esm/context/pre-checkout-query.js +0 -23
- package/esm/context/pre-checkout-query.js.map +0 -1
- package/esm/context/scene-transition.js +0 -48
- package/esm/context/scene-transition.js.map +0 -1
- package/esm/dispatcher.d.ts +0 -881
- package/esm/dispatcher.js +0 -904
- package/esm/dispatcher.js.map +0 -1
- package/esm/filters/bots.d.ts +0 -64
- package/esm/filters/bots.js +0 -131
- package/esm/filters/bots.js.map +0 -1
- package/esm/filters/bundle.d.ts +0 -10
- package/esm/filters/bundle.js +0 -11
- package/esm/filters/bundle.js.map +0 -1
- package/esm/filters/chat.d.ts +0 -27
- package/esm/filters/chat.js +0 -51
- package/esm/filters/chat.js.map +0 -1
- package/esm/filters/group.js +0 -65
- package/esm/filters/group.js.map +0 -1
- package/esm/filters/index.d.ts +0 -4
- package/esm/filters/index.js +0 -3
- package/esm/filters/index.js.map +0 -1
- package/esm/filters/logic.d.ts +0 -29
- package/esm/filters/logic.js +0 -105
- package/esm/filters/logic.js.map +0 -1
- package/esm/filters/message.js +0 -168
- package/esm/filters/message.js.map +0 -1
- package/esm/filters/state.d.ts +0 -15
- package/esm/filters/state.js +0 -28
- package/esm/filters/state.js.map +0 -1
- package/esm/filters/text.js +0 -129
- package/esm/filters/text.js.map +0 -1
- package/esm/filters/types.d.ts +0 -91
- package/esm/filters/types.js +0 -2
- package/esm/filters/types.js.map +0 -1
- package/esm/filters/updates.d.ts +0 -39
- package/esm/filters/updates.js +0 -34
- package/esm/filters/updates.js.map +0 -1
- package/esm/filters/user.d.ts +0 -25
- package/esm/filters/user.js +0 -71
- package/esm/filters/user.js.map +0 -1
- package/esm/handler.d.ts +0 -41
- package/esm/handler.js +0 -3
- package/esm/handler.js.map +0 -1
- package/esm/index.d.ts +0 -8
- package/esm/index.js +0 -9
- package/esm/index.js.map +0 -1
- package/esm/propagation.d.ts +0 -22
- package/esm/propagation.js +0 -24
- package/esm/propagation.js.map +0 -1
- package/esm/state/index.d.ts +0 -5
- package/esm/state/index.js +0 -6
- package/esm/state/index.js.map +0 -1
- package/esm/state/key.d.ts +0 -24
- package/esm/state/key.js +0 -39
- package/esm/state/key.js.map +0 -1
- package/esm/state/provider.d.ts +0 -5
- package/esm/state/provider.js +0 -2
- package/esm/state/provider.js.map +0 -1
- package/esm/state/providers/index.d.ts +0 -2
- package/esm/state/providers/index.js +0 -3
- package/esm/state/providers/index.js.map +0 -1
- package/esm/state/providers/memory.d.ts +0 -30
- package/esm/state/providers/memory.js +0 -77
- package/esm/state/providers/memory.js.map +0 -1
- package/esm/state/providers/sqlite.js +0 -96
- package/esm/state/providers/sqlite.js.map +0 -1
- package/esm/state/repository.d.ts +0 -62
- package/esm/state/repository.js +0 -2
- package/esm/state/repository.js.map +0 -1
- package/esm/state/service.js +0 -66
- package/esm/state/service.js.map +0 -1
- package/esm/state/update-state.d.ts +0 -151
- package/esm/state/update-state.js +0 -214
- package/esm/state/update-state.js.map +0 -1
- package/esm/wizard.js +0 -101
- package/esm/wizard.js.map +0 -1
- /package/{cjs/context → context}/index.d.ts +0 -0
- /package/{cjs/filters → filters}/bundle.d.ts +0 -0
- /package/{cjs/filters → filters}/index.d.ts +0 -0
- /package/{cjs/index.d.ts → index.d.cts} +0 -0
- /package/{cjs/propagation.d.ts → propagation.d.ts} +0 -0
- /package/{cjs/state → state}/index.d.ts +0 -0
- /package/{cjs/state → state}/providers/index.d.ts +0 -0
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MemoryStateStorage = void 0;
|
|
4
|
-
const core_1 = require("@mtcute/core");
|
|
5
|
-
class MemoryStateRepository {
|
|
6
|
-
_driver;
|
|
7
|
-
state;
|
|
8
|
-
rl;
|
|
9
|
-
constructor(_driver) {
|
|
10
|
-
this._driver = _driver;
|
|
11
|
-
this.state = this._driver.getState('dispatcher_fsm', () => new Map());
|
|
12
|
-
this.rl = this._driver.getState('rl', () => new Map());
|
|
13
|
-
}
|
|
14
|
-
setState(key, state, ttl) {
|
|
15
|
-
this.state.set(key, {
|
|
16
|
-
value: state,
|
|
17
|
-
expiresAt: ttl ? Date.now() + ttl * 1000 : undefined,
|
|
18
|
-
});
|
|
19
|
-
}
|
|
20
|
-
getState(key, now) {
|
|
21
|
-
const state = this.state.get(key);
|
|
22
|
-
if (!state)
|
|
23
|
-
return null;
|
|
24
|
-
if (state.expiresAt && state.expiresAt < now) {
|
|
25
|
-
this.state.delete(key);
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
return state.value;
|
|
29
|
-
}
|
|
30
|
-
deleteState(key) {
|
|
31
|
-
this.state.delete(key);
|
|
32
|
-
}
|
|
33
|
-
vacuum(now) {
|
|
34
|
-
for (const [key, state] of this.state.entries()) {
|
|
35
|
-
if (state.expiresAt && state.expiresAt < now) {
|
|
36
|
-
this.state.delete(key);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
for (const [key, state] of this.rl.entries()) {
|
|
40
|
-
if (state.reset < now) {
|
|
41
|
-
this.rl.delete(key);
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
getRateLimit(key, now, limit, window) {
|
|
46
|
-
// leaky bucket
|
|
47
|
-
const item = this.rl.get(key);
|
|
48
|
-
if (!item) {
|
|
49
|
-
const state = {
|
|
50
|
-
reset: now + window * 1000,
|
|
51
|
-
remaining: limit,
|
|
52
|
-
};
|
|
53
|
-
this.rl.set(key, state);
|
|
54
|
-
return [state.remaining, state.reset];
|
|
55
|
-
}
|
|
56
|
-
if (item.reset < now) {
|
|
57
|
-
// expired
|
|
58
|
-
const state = {
|
|
59
|
-
reset: now + window * 1000,
|
|
60
|
-
remaining: limit,
|
|
61
|
-
};
|
|
62
|
-
this.rl.set(key, state);
|
|
63
|
-
return [state.remaining, state.reset];
|
|
64
|
-
}
|
|
65
|
-
item.remaining = item.remaining > 0 ? item.remaining - 1 : 0;
|
|
66
|
-
return [item.remaining, item.reset];
|
|
67
|
-
}
|
|
68
|
-
resetRateLimit(key) {
|
|
69
|
-
this.rl.delete(key);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
class MemoryStateStorage {
|
|
73
|
-
driver;
|
|
74
|
-
state;
|
|
75
|
-
constructor(driver = new core_1.MemoryStorageDriver()) {
|
|
76
|
-
this.driver = driver;
|
|
77
|
-
this.state = new MemoryStateRepository(this.driver);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
exports.MemoryStateStorage = MemoryStateStorage;
|
|
81
|
-
//# sourceMappingURL=memory.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"memory.js","sourceRoot":"","sources":["../../../../src/state/providers/memory.ts"],"names":[],"mappings":";;;AACA,uCAAkD;AAelD,MAAM,qBAAqB;IAGF;IAFZ,KAAK,CAAuB;IAC5B,EAAE,CAA2B;IACtC,YAAqB,OAA4B;QAA5B,YAAO,GAAP,OAAO,CAAqB;QAC7C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAwB,gBAAgB,EAAE,GAAG,EAAE,CAAC,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A;IACvC,CAAC;IAED,cAAc,CAAC,GAAW;QACtB,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;CACJ;AAED,MAAa,kBAAkB;IAGN;IAFZ,KAAK,CAAuB;IAErC,YAAqB,SAA8B,IAAI,0BAAmB,EAAE;QAAvD,WAAM,GAAN,MAAM,CAAiD;QACxE,IAAI,CAAC,KAAK,GAAG,IAAI,qBAAqB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACvD,CAAC;CACJ;AAND,gDAMC","sourcesContent":["import type { MaybePromise } from '@mtcute/core'\nimport { MemoryStorageDriver } from '@mtcute/core'\n\nimport type { IStateStorageProvider } from '../provider.js'\nimport type { IStateRepository } from '../repository.js'\n\ninterface StateDto {\n value: string\n expiresAt?: number\n}\n\ninterface RateLimitDto {\n reset: number\n remaining: number\n}\n\nclass MemoryStateRepository implements IStateRepository {\n readonly state: Map<string, StateDto>\n readonly rl: Map<string, RateLimitDto>\n constructor(readonly _driver: MemoryStorageDriver) {\n this.state = this._driver.getState<Map<string, StateDto>>('dispatcher_fsm', () => new Map())\n this.rl = this._driver.getState<Map<string, RateLimitDto>>('rl', () => new Map())\n }\n\n setState(key: string, state: string, ttl?: number | undefined): void {\n this.state.set(key, {\n value: state,\n expiresAt: ttl ? Date.now() + ttl * 1000 : undefined,\n })\n }\n\n getState(key: string, now: number): string | null {\n const state = this.state.get(key)\n if (!state) return null\n\n if (state.expiresAt && state.expiresAt < now) {\n this.state.delete(key)\n\n return null\n }\n\n return state.value\n }\n\n deleteState(key: string): void {\n this.state.delete(key)\n }\n\n vacuum(now: number): void {\n for (const [key, state] of this.state.entries()) {\n if (state.expiresAt && state.expiresAt < now) {\n this.state.delete(key)\n }\n }\n\n for (const [key, state] of this.rl.entries()) {\n if (state.reset < now) {\n this.rl.delete(key)\n }\n }\n }\n\n getRateLimit(key: string, now: number, limit: number, window: number): [number, number] {\n // leaky bucket\n const item = this.rl.get(key)\n\n if (!item) {\n const state: RateLimitDto = {\n reset: now + window * 1000,\n remaining: limit,\n }\n\n this.rl.set(key, state)\n\n return [state.remaining, state.reset]\n }\n\n if (item.reset < now) {\n // expired\n\n const state: RateLimitDto = {\n reset: now + window * 1000,\n remaining: limit,\n }\n\n this.rl.set(key, state)\n\n return [state.remaining, state.reset]\n }\n\n item.remaining = item.remaining > 0 ? item.remaining - 1 : 0\n\n return [item.remaining, item.reset]\n }\n\n resetRateLimit(key: string): MaybePromise<void> {\n this.rl.delete(key)\n }\n}\n\nexport class MemoryStateStorage implements IStateStorageProvider {\n readonly state: MemoryStateRepository\n\n constructor(readonly driver: MemoryStorageDriver = new MemoryStorageDriver()) {\n this.state = new MemoryStateRepository(this.driver)\n }\n}\n"]}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import type { BaseSqliteStorage, BaseSqliteStorageDriver, MaybePromise } from '@mtcute/core';
|
|
2
|
-
import type { IStateStorageProvider } from '../provider.js';
|
|
3
|
-
import type { IStateRepository } from '../repository.js';
|
|
4
|
-
declare class SqliteStateRepository implements IStateRepository {
|
|
5
|
-
readonly _driver: BaseSqliteStorageDriver;
|
|
6
|
-
constructor(_driver: BaseSqliteStorageDriver);
|
|
7
|
-
private _setState;
|
|
8
|
-
setState(key: string, state: string, ttl?: number | undefined): MaybePromise<void>;
|
|
9
|
-
private _getState;
|
|
10
|
-
getState(key: string, now: number): MaybePromise<string | null>;
|
|
11
|
-
private _deleteState;
|
|
12
|
-
deleteState(key: string): MaybePromise<void>;
|
|
13
|
-
private _deleteOldState;
|
|
14
|
-
private _deleteOldRl;
|
|
15
|
-
vacuum(now: number): MaybePromise<void>;
|
|
16
|
-
private _setRl;
|
|
17
|
-
private _getRl;
|
|
18
|
-
private _deleteRl;
|
|
19
|
-
getRateLimit(key: string, now: number, limit: number, window: number): [number, number];
|
|
20
|
-
resetRateLimit(key: string): MaybePromise<void>;
|
|
21
|
-
}
|
|
22
|
-
export declare class SqliteStateStorage implements IStateStorageProvider {
|
|
23
|
-
readonly driver: BaseSqliteStorageDriver;
|
|
24
|
-
readonly state: SqliteStateRepository;
|
|
25
|
-
constructor(driver: BaseSqliteStorageDriver);
|
|
26
|
-
static from(provider: BaseSqliteStorage): SqliteStateStorage;
|
|
27
|
-
}
|
|
28
|
-
export {};
|
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SqliteStateStorage = void 0;
|
|
4
|
-
class SqliteStateRepository {
|
|
5
|
-
_driver;
|
|
6
|
-
constructor(_driver) {
|
|
7
|
-
this._driver = _driver;
|
|
8
|
-
_driver.registerMigration('state', 1, (db) => {
|
|
9
|
-
db.exec(`
|
|
10
|
-
create table fsm_state (
|
|
11
|
-
key text primary key,
|
|
12
|
-
value text not null,
|
|
13
|
-
expires_at integer
|
|
14
|
-
);
|
|
15
|
-
create table rl_state (
|
|
16
|
-
key text primary key,
|
|
17
|
-
reset integer not null,
|
|
18
|
-
remaining integer not null
|
|
19
|
-
);
|
|
20
|
-
`);
|
|
21
|
-
});
|
|
22
|
-
_driver.onLoad(() => {
|
|
23
|
-
this._setState = _driver.db.prepare('insert or replace into fsm_state (key, value, expires_at) values (?, ?, ?)');
|
|
24
|
-
this._getState = _driver.db.prepare('select value, expires_at from fsm_state where key = ?');
|
|
25
|
-
this._deleteState = _driver.db.prepare('delete from fsm_state where key = ?');
|
|
26
|
-
this._deleteOldState = _driver.db.prepare('delete from fsm_state where expires_at < ?');
|
|
27
|
-
this._setRl = _driver.db.prepare('insert or replace into rl_state (key, reset, remaining) values (?, ?, ?)');
|
|
28
|
-
this._getRl = _driver.db.prepare('select reset, remaining from rl_state where key = ?');
|
|
29
|
-
this._deleteRl = _driver.db.prepare('delete from rl_state where key = ?');
|
|
30
|
-
this._deleteOldRl = _driver.db.prepare('delete from rl_state where reset < ?');
|
|
31
|
-
});
|
|
32
|
-
_driver.registerLegacyMigration('state', (db) => {
|
|
33
|
-
// not too important information, just drop the table
|
|
34
|
-
db.exec('drop table state');
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
_setState;
|
|
38
|
-
setState(key, state, ttl) {
|
|
39
|
-
this._setState.run(key, state, ttl ? Date.now() + ttl * 1000 : undefined);
|
|
40
|
-
}
|
|
41
|
-
_getState;
|
|
42
|
-
getState(key, now) {
|
|
43
|
-
const res_ = this._getState.get(key);
|
|
44
|
-
if (!res_)
|
|
45
|
-
return null;
|
|
46
|
-
const res = res_;
|
|
47
|
-
if (res.expires_at && res.expires_at < now) {
|
|
48
|
-
this._deleteState.run(key);
|
|
49
|
-
return null;
|
|
50
|
-
}
|
|
51
|
-
return res.value;
|
|
52
|
-
}
|
|
53
|
-
_deleteState;
|
|
54
|
-
deleteState(key) {
|
|
55
|
-
this._deleteState.run(key);
|
|
56
|
-
}
|
|
57
|
-
_deleteOldState;
|
|
58
|
-
_deleteOldRl;
|
|
59
|
-
vacuum(now) {
|
|
60
|
-
this._deleteOldState.run(now);
|
|
61
|
-
this._deleteOldRl.run(now);
|
|
62
|
-
}
|
|
63
|
-
_setRl;
|
|
64
|
-
_getRl;
|
|
65
|
-
_deleteRl;
|
|
66
|
-
getRateLimit(key, now, limit, window) {
|
|
67
|
-
const val = this._getRl.get(key);
|
|
68
|
-
// hot path. rate limit fsm entries always have an expiration date
|
|
69
|
-
if (!val || val.reset < now) {
|
|
70
|
-
// expired or does not exist
|
|
71
|
-
const item = {
|
|
72
|
-
reset: now + window * 1000,
|
|
73
|
-
remaining: limit,
|
|
74
|
-
};
|
|
75
|
-
this._setRl.run(key, item.reset, item.remaining);
|
|
76
|
-
return [item.remaining, item.reset];
|
|
77
|
-
}
|
|
78
|
-
if (val.remaining > 0) {
|
|
79
|
-
val.remaining -= 1;
|
|
80
|
-
this._setRl.run(key, val.reset, val.remaining);
|
|
81
|
-
}
|
|
82
|
-
return [val.remaining, val.reset];
|
|
83
|
-
}
|
|
84
|
-
resetRateLimit(key) {
|
|
85
|
-
this._deleteRl.run(key);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
class SqliteStateStorage {
|
|
89
|
-
driver;
|
|
90
|
-
state;
|
|
91
|
-
constructor(driver) {
|
|
92
|
-
this.driver = driver;
|
|
93
|
-
this.state = new SqliteStateRepository(driver);
|
|
94
|
-
}
|
|
95
|
-
static from(provider) {
|
|
96
|
-
return new SqliteStateStorage(provider.driver);
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
exports.SqliteStateStorage = SqliteStateStorage;
|
|
100
|
-
//# sourceMappingURL=sqlite.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../../src/state/providers/sqlite.ts"],"names":[],"mappings":";;;AAeA,MAAM,qBAAqB;IACF;IAArB,YAAqB,OAAgC;QAAhC,YAAO,GAAP,OAAO,CAAyB;QACjD,OAAO,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE;YACzC,EAAE,CAAC,IAAI,CAAC;;;;;;;;;;;aAWP,CAAC,CAAA;QACN,CAAC,CAAC,CAAA;QACF,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE;YAChB,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,CAC/B,4EAA4E,CAC/E,CAAA;YACD,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,uDAAuD,CAAC,CAAA;YAC5F,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,qCAAqC,CAAC,CAAA;YAC7E,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,4CAA4C,CAAC,CAAA;YAEvF,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,0EAA0E,CAAC,CAAA;YAC5G,IAAI,CAAC,MAAM,GAAG,OAAO,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N;IADZ,KAAK,CAAuB;IACrC,YAAqB,MAA+B;QAA/B,WAAM,GAAN,MAAM,CAAyB;QAChD,IAAI,CAAC,KAAK,GAAG,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAA;IAClD,CAAC;IAED,MAAM,CAAC,IAAI,CAAC,QAA2B;QACnC,OAAO,IAAI,kBAAkB,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAA;IAClD,CAAC;CACJ;AATD,gDASC","sourcesContent":["import type { BaseSqliteStorage, BaseSqliteStorageDriver, ISqliteStatement, MaybePromise } from '@mtcute/core'\n\nimport type { IStateStorageProvider } from '../provider.js'\nimport type { IStateRepository } from '../repository.js'\n\ninterface StateDto {\n value: string\n expires_at: number | null\n}\n\ninterface RateLimitDto {\n reset: number\n remaining: number\n}\n\nclass SqliteStateRepository implements IStateRepository {\n constructor(readonly _driver: BaseSqliteStorageDriver) {\n _driver.registerMigration('state', 1, (db) => {\n db.exec(`\n create table fsm_state (\n key text primary key,\n value text not null,\n expires_at integer\n );\n create table rl_state (\n key text primary key,\n reset integer not null,\n remaining integer not null\n );\n `)\n })\n _driver.onLoad(() => {\n this._setState = _driver.db.prepare(\n 'insert or replace into fsm_state (key, value, expires_at) values (?, ?, ?)',\n )\n this._getState = _driver.db.prepare('select value, expires_at from fsm_state where key = ?')\n this._deleteState = _driver.db.prepare('delete from fsm_state where key = ?')\n this._deleteOldState = _driver.db.prepare('delete from fsm_state where expires_at < ?')\n\n this._setRl = _driver.db.prepare('insert or replace into rl_state (key, reset, remaining) values (?, ?, ?)')\n this._getRl = _driver.db.prepare('select reset, remaining from rl_state where key = ?')\n this._deleteRl = _driver.db.prepare('delete from rl_state where key = ?')\n this._deleteOldRl = _driver.db.prepare('delete from rl_state where reset < ?')\n })\n _driver.registerLegacyMigration('state', (db) => {\n // not too important information, just drop the table\n db.exec('drop table state')\n })\n }\n\n private _setState!: ISqliteStatement\n setState(key: string, state: string, ttl?: number | undefined): MaybePromise<void> {\n this._setState.run(key, state, ttl ? Date.now() + ttl * 1000 : undefined)\n }\n\n private _getState!: ISqliteStatement\n getState(key: string, now: number): MaybePromise<string | null> {\n const res_ = this._getState.get(key)\n if (!res_) return null\n const res = res_ as StateDto\n\n if (res.expires_at && res.expires_at < now) {\n this._deleteState.run(key)\n\n return null\n }\n\n return res.value\n }\n\n private _deleteState!: ISqliteStatement\n deleteState(key: string): MaybePromise<void> {\n this._deleteState.run(key)\n }\n\n private _deleteOldState!: ISqliteStatement\n private _deleteOldRl!: ISqliteStatement\n vacuum(now: number): MaybePromise<void> {\n this._deleteOldState.run(now)\n this._deleteOldRl.run(now)\n }\n\n private _setRl!: ISqliteStatement\n private _getRl!: ISqliteStatement\n private _deleteRl!: ISqliteStatement\n\n getRateLimit(key: string, now: number, limit: number, window: number): [number, number] {\n const val = this._getRl.get(key) as RateLimitDto | undefined\n\n // hot path. rate limit fsm entries always have an expiration date\n\n if (!val || val.reset < now) {\n // expired or does not exist\n const item: RateLimitDto = {\n reset: now + window * 1000,\n remaining: limit,\n }\n\n this._setRl.run(key, item.reset, item.remaining)\n\n return [item.remaining, item.reset]\n }\n\n if (val.remaining > 0) {\n val.remaining -= 1\n\n this._setRl.run(key, val.reset, val.remaining)\n }\n\n return [val.remaining, val.reset]\n }\n\n resetRateLimit(key: string): MaybePromise<void> {\n this._deleteRl.run(key)\n }\n}\n\nexport class SqliteStateStorage implements IStateStorageProvider {\n readonly state: SqliteStateRepository\n constructor(readonly driver: BaseSqliteStorageDriver) {\n this.state = new SqliteStateRepository(driver)\n }\n\n static from(provider: BaseSqliteStorage): SqliteStateStorage {\n return new SqliteStateStorage(provider.driver)\n }\n}\n"]}
|
package/cjs/state/repository.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"repository.js","sourceRoot":"","sources":["../../../src/state/repository.ts"],"names":[],"mappings":"","sourcesContent":["import type { MaybePromise } from '@mtcute/core'\n\n/**\n * Interface for FSM storage for the dispatcher.\n *\n * All of the officially supported storages already implement\n * this interface, so you can just re-use it.\n *\n * Current scene is a special case of a `string` state,\n * Most of the time you can just store it the same way\n * as normal state, prefixing with something like `$current_state_`\n * (scene name can't start with `$`).\n * Alternatively, you can store them as simple strings\n */\nexport interface IStateRepository {\n /**\n * Retrieve state from the storage\n * If state is not found or has expired, return `null`\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n getState: (key: string, now: number) => MaybePromise<string | null>\n\n /**\n * Save state to the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n * @param state String representing the state\n * @param ttl TTL for the state, in seconds\n */\n setState: (key: string, state: string, ttl?: number) => MaybePromise<void>\n\n /**\n * Delete state from the storage\n *\n * @param key Key of the state, as defined by {@link StateKeyDelegate}\n */\n deleteState: (key: string) => MaybePromise<void>\n\n /**\n * Clean up expired states and rate limits.\n *\n * @param now Current unix time in ms\n */\n vacuum: (now: number) => MaybePromise<void>\n\n /**\n * Get information about a rate limit.\n *\n * It is recommended that you use sliding window or leaky bucket\n * to implement rate limiting ([learn more](https://konghq.com/blog/how-to-design-a-scalable-rate-limiting-algorithm/)),\n *\n * @param key Key of the rate limit\n * @param now Current unix time in ms\n * @param limit Maximum number of requests in `window`\n * @param window Window size in seconds\n * @returns Tuple containing the number of remaining and\n * unix time in ms when the user can try again\n */\n getRateLimit: (key: string, now: number, limit: number, window: number) => MaybePromise<[number, number]>\n\n /**\n * Reset a rate limit.\n *\n * @param key Key of the rate limit\n */\n resetRateLimit: (key: string) => MaybePromise<void>\n}\n"]}
|
package/cjs/state/service.d.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import type { MaybePromise } from '@mtcute/core';
|
|
2
|
-
import type { IStateStorageProvider } from './provider.js';
|
|
3
|
-
export declare class StateService {
|
|
4
|
-
readonly provider: IStateStorageProvider;
|
|
5
|
-
constructor(provider: IStateStorageProvider);
|
|
6
|
-
private _cache;
|
|
7
|
-
private _vacuumTimer?;
|
|
8
|
-
private _loaded;
|
|
9
|
-
private _load;
|
|
10
|
-
load(): Promise<void>;
|
|
11
|
-
destroy(): Promise<void>;
|
|
12
|
-
getState<T>(key: string): Promise<T | null>;
|
|
13
|
-
setState<T>(key: string, state: T, ttl?: number): Promise<void>;
|
|
14
|
-
deleteState(key: string): Promise<void>;
|
|
15
|
-
getCurrentScene(key: string): Promise<string | null>;
|
|
16
|
-
setCurrentScene(key: string, scene: string, ttl?: number): Promise<void>;
|
|
17
|
-
deleteCurrentScene(key: string): Promise<void>;
|
|
18
|
-
getRateLimit(key: string, limit: number, window: number): MaybePromise<[number, number]>;
|
|
19
|
-
resetRateLimit(key: string): MaybePromise<void>;
|
|
20
|
-
}
|
package/cjs/state/service.js
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.StateService = void 0;
|
|
4
|
-
const utils_js_1 = require("@mtcute/core/utils.js");
|
|
5
|
-
const makeCurrentSceneKey = (key) => `$current_scene_${key}`;
|
|
6
|
-
class StateService {
|
|
7
|
-
provider;
|
|
8
|
-
constructor(provider) {
|
|
9
|
-
this.provider = provider;
|
|
10
|
-
}
|
|
11
|
-
_cache = new utils_js_1.LruMap(100);
|
|
12
|
-
_vacuumTimer;
|
|
13
|
-
_loaded = false;
|
|
14
|
-
_load = (0, utils_js_1.asyncResettable)(async () => {
|
|
15
|
-
await this.provider.driver.load?.();
|
|
16
|
-
this._loaded = true;
|
|
17
|
-
});
|
|
18
|
-
async load() {
|
|
19
|
-
await this._load.run();
|
|
20
|
-
this._vacuumTimer = setInterval(() => {
|
|
21
|
-
Promise.resolve(this.provider.state.vacuum(Date.now())).catch(() => { });
|
|
22
|
-
}, 300_000);
|
|
23
|
-
}
|
|
24
|
-
async destroy() {
|
|
25
|
-
await this.provider.driver.save?.();
|
|
26
|
-
await this.provider.driver.destroy?.();
|
|
27
|
-
clearInterval(this._vacuumTimer);
|
|
28
|
-
this._loaded = false;
|
|
29
|
-
}
|
|
30
|
-
async getState(key) {
|
|
31
|
-
if (!this._loaded)
|
|
32
|
-
await this.load();
|
|
33
|
-
const cached = this._cache.get(key);
|
|
34
|
-
if (cached)
|
|
35
|
-
return cached;
|
|
36
|
-
const state = await this.provider.state.getState(key, Date.now());
|
|
37
|
-
if (!state)
|
|
38
|
-
return null;
|
|
39
|
-
return JSON.parse(state);
|
|
40
|
-
}
|
|
41
|
-
async setState(key, state, ttl) {
|
|
42
|
-
if (!this._loaded)
|
|
43
|
-
await this.load();
|
|
44
|
-
this._cache.set(key, state);
|
|
45
|
-
await this.provider.state.setState(key, JSON.stringify(state), ttl);
|
|
46
|
-
}
|
|
47
|
-
async deleteState(key) {
|
|
48
|
-
if (!this._loaded)
|
|
49
|
-
await this.load();
|
|
50
|
-
this._cache.delete(key);
|
|
51
|
-
await this.provider.state.deleteState(key);
|
|
52
|
-
}
|
|
53
|
-
getCurrentScene(key) {
|
|
54
|
-
return this.getState(makeCurrentSceneKey(key));
|
|
55
|
-
}
|
|
56
|
-
setCurrentScene(key, scene, ttl) {
|
|
57
|
-
return this.setState(makeCurrentSceneKey(key), scene, ttl);
|
|
58
|
-
}
|
|
59
|
-
deleteCurrentScene(key) {
|
|
60
|
-
return this.deleteState(makeCurrentSceneKey(key));
|
|
61
|
-
}
|
|
62
|
-
getRateLimit(key, limit, window) {
|
|
63
|
-
return this.provider.state.getRateLimit(key, Date.now(), limit, window);
|
|
64
|
-
}
|
|
65
|
-
resetRateLimit(key) {
|
|
66
|
-
return this.provider.state.resetRateLimit(key);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
exports.StateService = StateService;
|
|
70
|
-
//# sourceMappingURL=service.js.map
|
package/cjs/state/service.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../../src/state/service.ts"],"names":[],"mappings":";;;AAAA,oDAA+D;AAK/D,MAAM,mBAAmB,GAAG,CAAC,GAAW,EAAE,EAAE,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IAAI,CAAC,WAAW,CAAC,mBAAmB,CAAC,GAAG,CAAC,CAAC,CAAA;IACrD,CAAC;IAED,YAAY,CAAC,GAAW,EAAE,KAAa,EAAE,MAAc;QACnD,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;IAC3E,CAAC;IAED,cAAc,CAAC,GAAW;QACtB,OAAO,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAA;IAClD,CAAC;CACJ;AAvED,oCAuEC","sourcesContent":["import { LruMap, asyncResettable } from '@mtcute/core/utils.js'\nimport type { MaybePromise } from '@mtcute/core'\n\nimport type { IStateStorageProvider } from './provider.js'\n\nconst makeCurrentSceneKey = (key: string) => `$current_scene_${key}`\n\nexport class StateService {\n constructor(readonly provider: IStateStorageProvider) {}\n\n private _cache: LruMap<string, unknown> = new LruMap(100)\n private _vacuumTimer?: NodeJS.Timeout\n\n private _loaded = false\n private _load = asyncResettable(async () => {\n await this.provider.driver.load?.()\n this._loaded = true\n })\n\n async load(): Promise<void> {\n await this._load.run()\n this._vacuumTimer = setInterval(() => {\n Promise.resolve(this.provider.state.vacuum(Date.now())).catch(() => {})\n }, 300_000)\n }\n\n async destroy(): Promise<void> {\n await this.provider.driver.save?.()\n await this.provider.driver.destroy?.()\n clearInterval(this._vacuumTimer)\n this._loaded = false\n }\n\n async getState<T>(key: string): Promise<T | null> {\n if (!this._loaded) await this.load()\n\n const cached = this._cache.get(key)\n if (cached) return cached as T\n\n const state = await this.provider.state.getState(key, Date.now())\n if (!state) return null\n\n return JSON.parse(state) as T\n }\n\n async setState<T>(key: string, state: T, ttl?: number): Promise<void> {\n if (!this._loaded) await this.load()\n\n this._cache.set(key, state)\n await this.provider.state.setState(key, JSON.stringify(state), ttl)\n }\n\n async deleteState(key: string): Promise<void> {\n if (!this._loaded) await this.load()\n\n this._cache.delete(key)\n await this.provider.state.deleteState(key)\n }\n\n getCurrentScene(key: string): Promise<string | null> {\n return this.getState(makeCurrentSceneKey(key))\n }\n\n setCurrentScene(key: string, scene: string, ttl?: number): Promise<void> {\n return this.setState(makeCurrentSceneKey(key), scene, ttl)\n }\n\n deleteCurrentScene(key: string): Promise<void> {\n return this.deleteState(makeCurrentSceneKey(key))\n }\n\n getRateLimit(key: string, limit: number, window: number): MaybePromise<[number, number]> {\n return this.provider.state.getRateLimit(key, Date.now(), limit, window)\n }\n\n resetRateLimit(key: string): MaybePromise<void> {\n return this.provider.state.resetRateLimit(key)\n }\n}\n"]}
|
|
@@ -1,219 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.UpdateState = exports.RateLimitError = void 0;
|
|
4
|
-
const core_1 = require("@mtcute/core");
|
|
5
|
-
const utils_js_1 = require("@mtcute/core/utils.js");
|
|
6
|
-
/**
|
|
7
|
-
* Error thrown by `.rateLimit()`
|
|
8
|
-
*/
|
|
9
|
-
class RateLimitError extends core_1.MtcuteError {
|
|
10
|
-
reset;
|
|
11
|
-
constructor(reset) {
|
|
12
|
-
super('You are being rate limited.');
|
|
13
|
-
this.reset = reset;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
exports.RateLimitError = RateLimitError;
|
|
17
|
-
/**
|
|
18
|
-
* State of the current update.
|
|
19
|
-
*
|
|
20
|
-
* @template State Type that represents the state
|
|
21
|
-
* @template SceneName Possible scene names
|
|
22
|
-
*/
|
|
23
|
-
class UpdateState {
|
|
24
|
-
_key;
|
|
25
|
-
_localKey;
|
|
26
|
-
_storage;
|
|
27
|
-
_scene;
|
|
28
|
-
_scoped;
|
|
29
|
-
_cached;
|
|
30
|
-
_localStorage;
|
|
31
|
-
_localKeyBase;
|
|
32
|
-
constructor(storage, key, scene, scoped, customStorage, customKey) {
|
|
33
|
-
this._storage = storage;
|
|
34
|
-
this._key = key;
|
|
35
|
-
this._scene = scene;
|
|
36
|
-
this._scoped = scoped;
|
|
37
|
-
this._localStorage = customStorage ?? storage;
|
|
38
|
-
this._localKeyBase = customKey ?? key;
|
|
39
|
-
this._updateLocalKey();
|
|
40
|
-
}
|
|
41
|
-
/** Name of the current scene */
|
|
42
|
-
get scene() {
|
|
43
|
-
return this._scene;
|
|
44
|
-
}
|
|
45
|
-
_updateLocalKey() {
|
|
46
|
-
if (!this._scoped) {
|
|
47
|
-
this._localKey = this._localKeyBase;
|
|
48
|
-
}
|
|
49
|
-
else {
|
|
50
|
-
this._localKey = this._scene ? `${this._scene}_${this._localKeyBase}` : this._localKeyBase;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
async get(fallback, force) {
|
|
54
|
-
if (typeof fallback === 'boolean') {
|
|
55
|
-
force = fallback;
|
|
56
|
-
fallback = undefined;
|
|
57
|
-
}
|
|
58
|
-
if (!force && this._cached !== undefined) {
|
|
59
|
-
if (!this._cached && fallback) {
|
|
60
|
-
return typeof fallback === 'function' ? fallback() : fallback;
|
|
61
|
-
}
|
|
62
|
-
return this._cached;
|
|
63
|
-
}
|
|
64
|
-
let res = (await this._localStorage.getState(this._localKey));
|
|
65
|
-
if (!res && fallback) {
|
|
66
|
-
res = typeof fallback === 'function' ? fallback() : fallback;
|
|
67
|
-
}
|
|
68
|
-
this._cached = res;
|
|
69
|
-
return res;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Set new state to the storage
|
|
73
|
-
*
|
|
74
|
-
* @param state New state
|
|
75
|
-
* @param ttl TTL for the new state (in seconds)
|
|
76
|
-
*/
|
|
77
|
-
async set(state, ttl) {
|
|
78
|
-
this._cached = state;
|
|
79
|
-
await this._localStorage.setState(this._localKey, state, ttl);
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Merge the given object to the current state.
|
|
83
|
-
*
|
|
84
|
-
* > **Note**: If the storage currently has no state,
|
|
85
|
-
* > then `fallback` must be provided.
|
|
86
|
-
*
|
|
87
|
-
* Basically a shorthand to calling `.get()`,
|
|
88
|
-
* modifying and then calling `.set()`
|
|
89
|
-
*
|
|
90
|
-
* @param state State to be merged
|
|
91
|
-
* @param fallback Default state
|
|
92
|
-
* @param ttl TTL for the new state (in seconds)
|
|
93
|
-
* @param forceLoad Whether to force load the old state from storage
|
|
94
|
-
*/
|
|
95
|
-
async merge(state, params = {}) {
|
|
96
|
-
const { fallback, ttl, forceLoad } = params;
|
|
97
|
-
const old = await this.get(forceLoad);
|
|
98
|
-
if (!old) {
|
|
99
|
-
if (!fallback) {
|
|
100
|
-
throw new core_1.MtArgumentError('Cannot use merge on empty state without fallback.');
|
|
101
|
-
}
|
|
102
|
-
const fallback_ = typeof fallback === 'function' ? fallback() : fallback;
|
|
103
|
-
await this.set({ ...fallback_, ...state }, ttl);
|
|
104
|
-
}
|
|
105
|
-
else {
|
|
106
|
-
await this.set({ ...old, ...state }, ttl);
|
|
107
|
-
}
|
|
108
|
-
// _cached is set by .set()
|
|
109
|
-
return this._cached;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Delete the state from the storage
|
|
113
|
-
*/
|
|
114
|
-
async delete() {
|
|
115
|
-
this._cached = null;
|
|
116
|
-
await this._localStorage.deleteState(this._localKey);
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Enter some scene
|
|
120
|
-
*/
|
|
121
|
-
async enter(scene, params) {
|
|
122
|
-
const { with: with_, ttl, reset = true } = params ?? {};
|
|
123
|
-
if (reset && this._scoped)
|
|
124
|
-
await this.delete();
|
|
125
|
-
if (!scene['_scene']) {
|
|
126
|
-
throw new core_1.MtArgumentError('Cannot enter a non-scene Dispatcher');
|
|
127
|
-
}
|
|
128
|
-
if (!scene['_parent']) {
|
|
129
|
-
throw new core_1.MtArgumentError('This scene has not been registered');
|
|
130
|
-
}
|
|
131
|
-
this._scene = scene['_scene'];
|
|
132
|
-
this._scoped = scene['_sceneScoped'];
|
|
133
|
-
this._updateLocalKey();
|
|
134
|
-
await this._storage.setCurrentScene(this._key, this._scene, ttl);
|
|
135
|
-
if (with_) {
|
|
136
|
-
if (scene['_customStateKeyDelegate']) {
|
|
137
|
-
throw new core_1.MtArgumentError('Cannot use `with` parameter when the scene uses a custom state key delegate');
|
|
138
|
-
}
|
|
139
|
-
await scene.getState(this._key).set(with_, ttl);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Exit from current scene to the root
|
|
144
|
-
*
|
|
145
|
-
* @param reset
|
|
146
|
-
* Whether to reset scene state (only applicable in case this is a scoped scene)
|
|
147
|
-
*/
|
|
148
|
-
async exit(reset = true) {
|
|
149
|
-
if (reset && this._scoped)
|
|
150
|
-
await this.delete();
|
|
151
|
-
this._scene = null;
|
|
152
|
-
this._updateLocalKey();
|
|
153
|
-
await this._storage.deleteCurrentScene(this._key);
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Rate limit some handler.
|
|
157
|
-
*
|
|
158
|
-
* When the rate limit exceeds, {@link RateLimitError} is thrown.
|
|
159
|
-
*
|
|
160
|
-
* This is a simple rate-limiting solution that uses
|
|
161
|
-
* the same key as the state. If you need something more
|
|
162
|
-
* sophisticated and/or customizable, you'll have to implement
|
|
163
|
-
* your own rate-limiter.
|
|
164
|
-
*
|
|
165
|
-
* > **Note**: `key` is used to prefix the local key
|
|
166
|
-
* > derived using the given key delegate.
|
|
167
|
-
*
|
|
168
|
-
* @param key Key of the rate limit
|
|
169
|
-
* @param limit Maximum number of requests in `window`
|
|
170
|
-
* @param window Window size in seconds
|
|
171
|
-
* @returns Tuple containing the number of remaining and
|
|
172
|
-
* unix time in ms when the user can try again
|
|
173
|
-
*/
|
|
174
|
-
async rateLimit(key, limit, window) {
|
|
175
|
-
const [remaining, reset] = await this._localStorage.getRateLimit(`${key}:${this._localKey}`, limit, window);
|
|
176
|
-
if (!remaining) {
|
|
177
|
-
throw new RateLimitError(reset);
|
|
178
|
-
}
|
|
179
|
-
return [remaining - 1, reset];
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* Throttle some handler.
|
|
183
|
-
*
|
|
184
|
-
* When the rate limit exceeds, this function waits for it to reset.
|
|
185
|
-
*
|
|
186
|
-
* This is a simple wrapper over {@link rateLimit}, and follows the same logic.
|
|
187
|
-
*
|
|
188
|
-
* > **Note**: `key` is used to prefix the local key
|
|
189
|
-
* > derived using the given key delegate.
|
|
190
|
-
*
|
|
191
|
-
* @param key Key of the rate limit
|
|
192
|
-
* @param limit Maximum number of requests in `window`
|
|
193
|
-
* @param window Window size in seconds
|
|
194
|
-
* @returns Tuple containing the number of remaining and
|
|
195
|
-
* unix time in ms when the user can try again
|
|
196
|
-
*/
|
|
197
|
-
async throttle(key, limit, window) {
|
|
198
|
-
try {
|
|
199
|
-
return await this.rateLimit(key, limit, window);
|
|
200
|
-
}
|
|
201
|
-
catch (e) {
|
|
202
|
-
if (e instanceof RateLimitError) {
|
|
203
|
-
await (0, utils_js_1.sleep)(e.reset - Date.now());
|
|
204
|
-
return this.throttle(key, limit, window);
|
|
205
|
-
}
|
|
206
|
-
throw e;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Reset the rate limit
|
|
211
|
-
*
|
|
212
|
-
* @param key Key of the rate limit
|
|
213
|
-
*/
|
|
214
|
-
async resetRateLimit(key) {
|
|
215
|
-
await this._localStorage.resetRateLimit(`${key}:${this._localKey}`);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
exports.UpdateState = UpdateState;
|
|
219
|
-
//# sourceMappingURL=update-state.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"update-state.js","sourceRoot":"","sources":["../../../src/state/update-state.ts"],"names":[],"mappings":";;;AAAA,uCAA2D;AAC3D,oDAA6C;AAM7C;;GAEG;AACH,MAAa,cAAe,SAAQ,kBAAW;IACtB;IAArB,YAAqB,KAAa;QAC9B,KAAK,CAAC,6BAA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AE,MAAc;QACrD,IAAI,CAAC;YACD,OAAO,MAAM,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;QACnD,CAAC;QAAC,OAAO,CAAU,EAAE,CAAC;YAClB,IAAI,CAAC,YAAY,cAAc,EAAE,CAAC;gBAC9B,MAAM,IAAA,gBAAK,EAAC,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;gBAEjC,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,CAAA;YAC5C,CAAC;YAED,MAAM,CAAC,CAAA;QACX,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,cAAc,CAAC,GAAW;QAC5B,MAAM,IAAI,CAAC,aAAa,CAAC,cAAc,CAAC,GAAG,GAAG,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,CAAA;IACvE,CAAC;CACJ;AA7RD,kCA6RC","sourcesContent":["import { MtArgumentError, MtcuteError } from '@mtcute/core'\nimport { sleep } from '@mtcute/core/utils.js'\n\nimport type { Dispatcher } from '../dispatcher.js'\n\nimport type { StateService } from './service.js'\n\n/**\n * Error thrown by `.rateLimit()`\n */\nexport class RateLimitError extends MtcuteError {\n constructor(readonly reset: number) {\n super('You are being rate limited.')\n }\n}\n\n/**\n * State of the current update.\n *\n * @template State Type that represents the state\n * @template SceneName Possible scene names\n */\nexport class UpdateState<State extends object> {\n private _key: string\n private _localKey!: string\n\n private _storage: StateService\n\n private _scene: string | null\n private _scoped?: boolean\n private _cached?: State | null\n\n private _localStorage: StateService\n private _localKeyBase: string\n\n constructor(\n storage: StateService,\n key: string,\n scene: string | null,\n scoped?: boolean,\n customStorage?: StateService,\n customKey?: string,\n ) {\n this._storage = storage\n this._key = key\n this._scene = scene\n this._scoped = scoped\n\n this._localStorage = customStorage ?? storage\n this._localKeyBase = customKey ?? key\n\n this._updateLocalKey()\n }\n\n /** Name of the current scene */\n get scene(): string | null {\n return this._scene\n }\n\n private _updateLocalKey(): void {\n if (!this._scoped) {\n this._localKey = this._localKeyBase\n } else {\n this._localKey = this._scene ? `${this._scene}_${this._localKeyBase}` : this._localKeyBase\n }\n }\n\n /**\n * Retrieve the state from the storage, falling back to default\n * if not found\n *\n * @param fallback Default state value\n * @param force Whether to ignore cached state (def. `false`)\n */\n async get(fallback: State | (() => State), force?: boolean): Promise<State>\n\n /**\n * Retrieve the state from the storage, falling back to default\n * if not found\n *\n * @param fallback Default state value\n * @param force Whether to ignore cached state (def. `false`)\n */\n async get(fallback?: State | (() => State), force?: boolean): Promise<State | null>\n /**\n * Retrieve the state from the storage\n *\n * @param force Whether to ignore cached state (def. `false`)\n */\n async get(force?: boolean): Promise<State | null>\n async get(fallback?: State | (() => State) | boolean, force?: boolean): Promise<State | null> {\n if (typeof fallback === 'boolean') {\n force = fallback\n fallback = undefined\n }\n\n if (!force && this._cached !== undefined) {\n if (!this._cached && fallback) {\n return typeof fallback === 'function' ? fallback() : fallback\n }\n\n return this._cached\n }\n\n let res = (await this._localStorage.getState(this._localKey)) as State | null\n\n if (!res && fallback) {\n res = typeof fallback === 'function' ? fallback() : fallback\n }\n this._cached = res\n\n return res\n }\n\n /**\n * Set new state to the storage\n *\n * @param state New state\n * @param ttl TTL for the new state (in seconds)\n */\n async set(state: State, ttl?: number): Promise<void> {\n this._cached = state\n await this._localStorage.setState(this._localKey, state, ttl)\n }\n\n /**\n * Merge the given object to the current state.\n *\n * > **Note**: If the storage currently has no state,\n * > then `fallback` must be provided.\n *\n * Basically a shorthand to calling `.get()`,\n * modifying and then calling `.set()`\n *\n * @param state State to be merged\n * @param fallback Default state\n * @param ttl TTL for the new state (in seconds)\n * @param forceLoad Whether to force load the old state from storage\n */\n async merge(\n state: Partial<State>,\n params: {\n fallback?: State | (() => State)\n ttl?: number\n forceLoad?: boolean\n } = {},\n ): Promise<State> {\n const { fallback, ttl, forceLoad } = params\n\n const old = await this.get(forceLoad)\n\n if (!old) {\n if (!fallback) {\n throw new MtArgumentError('Cannot use merge on empty state without fallback.')\n }\n\n const fallback_ = typeof fallback === 'function' ? fallback() : fallback\n\n await this.set({ ...fallback_, ...state }, ttl)\n } else {\n await this.set({ ...old, ...state }, ttl)\n }\n\n // _cached is set by .set()\n\n return this._cached!\n }\n\n /**\n * Delete the state from the storage\n */\n async delete(): Promise<void> {\n this._cached = null\n await this._localStorage.deleteState(this._localKey)\n }\n\n /**\n * Enter some scene\n */\n async enter<SceneState extends object, Scene extends Dispatcher<SceneState>>(\n scene: Scene,\n params?: {\n /**\n * Initial state for the scene\n *\n * Note that this will only work if the scene uses the same key delegate as this state.\n */\n with?: SceneState\n\n /** TTL for the scene (in seconds) */\n ttl?: number\n\n /**\n * If currently in a scoped scene, whether to reset the state\n *\n * @default true\n */\n reset?: boolean\n },\n ): Promise<void> {\n const { with: with_, ttl, reset = true } = params ?? {}\n\n if (reset && this._scoped) await this.delete()\n\n if (!scene['_scene']) {\n throw new MtArgumentError('Cannot enter a non-scene Dispatcher')\n }\n\n if (!scene['_parent']) {\n throw new MtArgumentError('This scene has not been registered')\n }\n\n this._scene = scene['_scene']\n this._scoped = scene['_sceneScoped']\n this._updateLocalKey()\n\n await this._storage.setCurrentScene(this._key, this._scene, ttl)\n\n if (with_) {\n if (scene['_customStateKeyDelegate']) {\n throw new MtArgumentError('Cannot use `with` parameter when the scene uses a custom state key delegate')\n }\n\n await scene.getState(this._key).set(with_, ttl)\n }\n }\n\n /**\n * Exit from current scene to the root\n *\n * @param reset\n * Whether to reset scene state (only applicable in case this is a scoped scene)\n */\n async exit(reset = true): Promise<void> {\n if (reset && this._scoped) await this.delete()\n this._scene = null\n this._updateLocalKey()\n await this._storage.deleteCurrentScene(this._key)\n }\n\n /**\n * Rate limit some handler.\n *\n * When the rate limit exceeds, {@link RateLimitError} is thrown.\n *\n * This is a simple rate-limiting solution that uses\n * the same key as the state. If you need something more\n * sophisticated and/or customizable, you'll have to implement\n * your own rate-limiter.\n *\n * > **Note**: `key` is used to prefix the local key\n * > derived using the given key delegate.\n *\n * @param key Key of the rate limit\n * @param limit Maximum number of requests in `window`\n * @param window Window size in seconds\n * @returns Tuple containing the number of remaining and\n * unix time in ms when the user can try again\n */\n async rateLimit(key: string, limit: number, window: number): Promise<[number, number]> {\n const [remaining, reset] = await this._localStorage.getRateLimit(`${key}:${this._localKey}`, limit, window)\n\n if (!remaining) {\n throw new RateLimitError(reset)\n }\n\n return [remaining - 1, reset]\n }\n\n /**\n * Throttle some handler.\n *\n * When the rate limit exceeds, this function waits for it to reset.\n *\n * This is a simple wrapper over {@link rateLimit}, and follows the same logic.\n *\n * > **Note**: `key` is used to prefix the local key\n * > derived using the given key delegate.\n *\n * @param key Key of the rate limit\n * @param limit Maximum number of requests in `window`\n * @param window Window size in seconds\n * @returns Tuple containing the number of remaining and\n * unix time in ms when the user can try again\n */\n async throttle(key: string, limit: number, window: number): Promise<[number, number]> {\n try {\n return await this.rateLimit(key, limit, window)\n } catch (e: unknown) {\n if (e instanceof RateLimitError) {\n await sleep(e.reset - Date.now())\n\n return this.throttle(key, limit, window)\n }\n\n throw e\n }\n }\n\n /**\n * Reset the rate limit\n *\n * @param key Key of the rate limit\n */\n async resetRateLimit(key: string): Promise<void> {\n await this._localStorage.resetRateLimit(`${key}:${this._localKey}`)\n }\n}\n"]}
|