mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 08:30:05 +00:00
refactor(server): make the state ports async and route every reader through the provided store
The process-state ports were meant to let a store shared between processes replace the in-memory one, but they could not. The readers outside the container (the broadcast functions, the backup restore's permissions-cache flush, the pending-code sweep, hand-built consumers) went straight to the module-level in-memory instances, so an overridden provider was used by the gateway and the services while the broadcasts and the restore flush kept using the old store. And every port was synchronous, while a store in the database or on the network is async, so plugging one in would have changed every signature anyway. RateLimitStore, PendingCodeStore, OidcFlowStore and PermissionsCacheStore now return promises, and RateLimitService, OauthService, OidcService, PermissionsService and their callers await them. The in-memory stores still decide synchronously, so who gets a 429, a code or a cached level is unchanged. RoomRegistry stays synchronous: membership holds live sockets and broadcast() is a synchronous call every domain makes, so several processes need a fan-out in front of broadcast(), not a different place for the sets. The process-wide ports get a ProcessStoreSlot. PermissionsModule, OauthModule and RealtimeGatewayModule install the store the container resolved and release it on shutdown, and the free functions, the sweep and hand-built consumers read the slot, so overriding the provider changes every reader. Tests provide fake stores and check that the broadcasts, the restore flush and the sweep use them. Two callers needed more than an await. The transit MCP tools counted in a RateLimitService of their own that no provider could reach; they now take the one RateLimitModule provides (their mcp_transit_* buckets never overlap the REST ones). The link preview claimed its in-flight slot only after the budget check, which now yields, so simultaneous askers would each have been charged; it now claims the slot first, and an asker that joined someone out of budget asks again on its own budget. The unused putPendingCode/takePendingCode helpers are gone.
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* The store a piece of process-wide state is kept in right now.
|
||||
*
|
||||
* A store port (the permissions cache, the OAuth pending codes, the socket
|
||||
* rooms) is provided by its module, so a store shared between processes can
|
||||
* be swapped in there. Some readers cannot take it through a constructor: the
|
||||
* backup restore is plain functions, the broadcasts are free functions every
|
||||
* domain calls, and the no-Nest test harnesses build consumers by hand. They
|
||||
* read the slot instead, and the owning module installs whatever the
|
||||
* container resolved for the port, so swapping the provider changes every
|
||||
* reader, not only the injected ones.
|
||||
*
|
||||
* Starts on the in-memory default, which is also what the module provides
|
||||
* unless it is overridden, so a process that never builds the module (a
|
||||
* hand-built test) sees what it saw before.
|
||||
*/
|
||||
export class ProcessStoreSlot<T> {
|
||||
private current: T;
|
||||
|
||||
constructor(private readonly fallback: T) {
|
||||
this.current = fallback;
|
||||
}
|
||||
|
||||
/** The store every out-of-container reader uses now. */
|
||||
get(): T {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
/** Called by the owning module with the store the container resolved. */
|
||||
install(store: T): void {
|
||||
this.current = store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when that module is torn down: back to the default, unless a later
|
||||
* app has installed its own store since.
|
||||
*/
|
||||
release(store: T): void {
|
||||
if (this.current === store) this.current = this.fallback;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
|
||||
import { InMemoryRateLimitStore, RateLimitStore } from './rate-limit.store';
|
||||
|
||||
/**
|
||||
* Per-IP rate limiting for the auth-adjacent routes. `check` returns false
|
||||
* Per-IP rate limiting for the auth-adjacent routes. `check` resolves false
|
||||
* once a key exceeds `max` within `windowMs` (the caller answers 429).
|
||||
*
|
||||
* The counting lives in an injected RateLimitStore. RateLimitModule provides
|
||||
@@ -13,13 +13,13 @@ import { InMemoryRateLimitStore, RateLimitStore } from './rate-limit.store';
|
||||
export class RateLimitService {
|
||||
constructor(private readonly store: RateLimitStore = new InMemoryRateLimitStore()) {}
|
||||
|
||||
/** Returns true when the request is allowed, false when it should be rejected (429). */
|
||||
check(bucket: string, key: string, max: number, windowMs: number, now: number): boolean {
|
||||
/** Resolves true when the request is allowed, false when it should be rejected (429). */
|
||||
check(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean> {
|
||||
return this.store.hit(bucket, key, max, windowMs, now);
|
||||
}
|
||||
|
||||
/** Test helper: clear a bucket (mirrors the legacy exported maps used for resets). */
|
||||
reset(bucket?: string): void {
|
||||
this.store.reset(bucket);
|
||||
reset(bucket?: string): Promise<void> {
|
||||
return this.store.reset(bucket);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* as one process; with several, each would count on its own and a client
|
||||
* could spread its attempts over them. A store shared between processes
|
||||
* replaces InMemoryRateLimitStore in RateLimitModule without touching the
|
||||
* service or its callers.
|
||||
* service or its callers. Both methods return a promise, because such a
|
||||
* store lives in the database or on the network.
|
||||
*/
|
||||
export abstract class RateLimitStore {
|
||||
/**
|
||||
@@ -13,9 +14,9 @@ export abstract class RateLimitStore {
|
||||
* already used `max` attempts in the current `windowMs` window (the caller
|
||||
* answers 429), true otherwise.
|
||||
*/
|
||||
abstract hit(bucket: string, key: string, max: number, windowMs: number, now: number): boolean;
|
||||
abstract hit(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean>;
|
||||
/** Clear one bucket, or every bucket. */
|
||||
abstract reset(bucket?: string): void;
|
||||
abstract reset(bucket?: string): Promise<void>;
|
||||
}
|
||||
|
||||
interface Attempt {
|
||||
@@ -40,7 +41,26 @@ export class InMemoryRateLimitStore extends RateLimitStore {
|
||||
/** Last sweep per bucket, so a busy bucket doesn't keep a quiet one from being cleaned. */
|
||||
private readonly lastSweep = new Map<string, number>();
|
||||
|
||||
hit(bucket: string, key: string, max: number, windowMs: number, now: number): boolean {
|
||||
hit(bucket: string, key: string, max: number, windowMs: number, now: number): Promise<boolean> {
|
||||
return Promise.resolve(this.count(bucket, key, max, windowMs, now));
|
||||
}
|
||||
|
||||
reset(bucket?: string): Promise<void> {
|
||||
if (bucket) this.buckets.get(bucket)?.clear();
|
||||
else {
|
||||
this.buckets.clear();
|
||||
this.lastSweep.clear();
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
/** How many keys a bucket holds right now; the housekeeping is only visible here. */
|
||||
size(bucket: string): number {
|
||||
return this.buckets.get(bucket)?.size ?? 0;
|
||||
}
|
||||
|
||||
/** The window check and the count, in one synchronous step so two hits cannot interleave. */
|
||||
private count(bucket: string, key: string, max: number, windowMs: number, now: number): boolean {
|
||||
const store = this.store(bucket);
|
||||
this.sweep(bucket, store, windowMs, now);
|
||||
const record = store.get(key);
|
||||
@@ -55,19 +75,6 @@ export class InMemoryRateLimitStore extends RateLimitStore {
|
||||
return true;
|
||||
}
|
||||
|
||||
reset(bucket?: string): void {
|
||||
if (bucket) this.buckets.get(bucket)?.clear();
|
||||
else {
|
||||
this.buckets.clear();
|
||||
this.lastSweep.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** How many keys a bucket holds right now; the housekeeping is only visible here. */
|
||||
size(bucket: string): number {
|
||||
return this.buckets.get(bucket)?.size ?? 0;
|
||||
}
|
||||
|
||||
private store(bucket: string): Map<string, Attempt> {
|
||||
let s = this.buckets.get(bucket);
|
||||
if (!s) {
|
||||
|
||||
Reference in New Issue
Block a user