Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix: avoid sync peak (#17305)

LobeHub Bot783d983514dd
diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
index cae403fb2fa..09c316a5587 100644
--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts
@@ -233,6 +233,8 @@ describe('GatewayService', () => {
mockGatewayEnv.MESSAGE_GATEWAY_ENABLED = '1';
mockGatewayClient.isConfigured = true;
mockGatewayClient.isEnabled = true;
+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });
});
it('skips webhook-mode providers', async () => {
@@ -252,47 +254,7 @@ describe('GatewayService', () => {
expect(mockGatewayClient.connect).not.toHaveBeenCalled();
});
- it('skips already connected providers', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
- mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockResolvedValue({
- state: { status: 'connected' },
- });
-
- await service.ensureRunning();
-
- expect(mockGatewayClient.connect).not.toHaveBeenCalled();
- });
-
- it('skips connecting providers', async () => {
- mockFindEnabledByPlatform.mockResolvedValue([
- {
- applicationId: 'app-1',
- credentials: { token: 'x' },
- id: 'prov-1',
- settings: {},
- userId: 'u1',
- },
- ]);
- mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockResolvedValue({
- state: { status: 'connecting' },
- });
-
- await service.ensureRunning();
-
- expect(mockGatewayClient.connect).not.toHaveBeenCalled();
- });
-
- it('skips providers in error state', async () => {
+ it('skips providers already present in the registered-id snapshot without probing status', async () => {
mockFindEnabledByPlatform.mockResolvedValue([
{
applicationId: 'app-1',
@@ -303,12 +265,11 @@ describe('GatewayService', () => {
},
]);
mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockResolvedValue({
- state: { error: 'Session expired (errcode -14)', status: 'error' },
- });
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });
await service.ensureRunning();
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
expect(mockGatewayClient.connect).not.toHaveBeenCalled();
});
@@ -327,9 +288,6 @@ describe('GatewayService', () => {
: [],
);
mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockResolvedValue({
- state: { status: 'disconnected' },
- });
mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });
await service.ensureRunning();
@@ -365,9 +323,6 @@ describe('GatewayService', () => {
: [],
);
mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockResolvedValue({
- state: { status: 'disconnected' },
- });
mockGatewayClient.connect.mockResolvedValue({ status: 'dormant' });
await service.ensureRunning();
@@ -396,6 +351,7 @@ describe('GatewayService', () => {
);
mockResolveConnectionMode.mockReturnValue('polling');
mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });
await service.ensureRunning();
@@ -417,6 +373,42 @@ describe('GatewayService', () => {
);
});
+ it.each([
+ { snapshot: 'stats-only', statsUnavailable: false },
+ { snapshot: 'unavailable', statsUnavailable: true },
+ ])(
+ 'disconnects a paid-gated provider when the registry snapshot is $snapshot',
+ async ({ statsUnavailable }) => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
+ platform === 'wechat'
+ ? [
+ {
+ applicationId: 'wechat-app',
+ credentials: { botToken: 'token' },
+ id: 'wechat-provider',
+ settings: {},
+ userId: 'free-user',
+ },
+ ]
+ : [],
+ );
+ mockResolveConnectionMode.mockReturnValue('polling');
+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
+ mockGatewayClient.getRegisteredIds.mockRejectedValue(
+ new Error('registered-ids unavailable'),
+ );
+ if (statsUnavailable) {
+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));
+ }
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
+ },
+ );
+
it('sets connected status for sync connect result', async () => {
mockFindEnabledByPlatform.mockResolvedValue([
{
@@ -428,7 +420,6 @@ describe('GatewayService', () => {
},
]);
mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockRejectedValue(new Error('not found'));
mockGatewayClient.connect.mockResolvedValue({ status: 'connected' });
await service.ensureRunning();
@@ -438,7 +429,7 @@ describe('GatewayService', () => {
);
});
- it('tries to connect when status check fails', async () => {
+ it('defers desired providers when the gateway snapshot is unavailable', async () => {
mockFindEnabledByPlatform.mockResolvedValue([
{
applicationId: 'app-1',
@@ -449,12 +440,13 @@ describe('GatewayService', () => {
},
]);
mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockRejectedValue(new Error('DO not found'));
- mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });
+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));
+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered-ids unavailable'));
await service.ensureRunning();
- expect(mockGatewayClient.connect).toHaveBeenCalled();
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
});
it('handles connect failure gracefully', async () => {
@@ -468,9 +460,6 @@ describe('GatewayService', () => {
},
]);
mockResolveConnectionMode.mockReturnValue('websocket');
- mockGatewayClient.getStatus.mockResolvedValue({
- state: { status: 'disconnected' },
- });
mockGatewayClient.connect.mockRejectedValue(new Error('timeout'));
// Should not throw
@@ -494,12 +483,41 @@ describe('GatewayService', () => {
);
mockResolveConnectionMode.mockReturnValue('polling');
mockIsBotFeatureAccessAllowed.mockRejectedValue(new Error('subscription service down'));
- mockGatewayClient.getStatus.mockResolvedValue({ state: { status: 'connected' } });
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });
await service.ensureRunning();
// Fail-open: no disconnect, provider stays in the desired set.
expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
+ });
+
+ it('does not repeatedly disconnect a gated provider absent from the gateway snapshot', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
+ platform === 'wechat'
+ ? [
+ {
+ applicationId: 'wechat-app',
+ credentials: { botToken: 'token' },
+ id: 'wechat-provider',
+ settings: {},
+ userId: 'free-user',
+ },
+ ]
+ : [],
+ );
+ mockResolveConnectionMode.mockReturnValue('polling');
+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(
+ expect.objectContaining({
+ applicationId: 'wechat-app',
+ status: 'failed',
+ }),
+ );
});
});
@@ -643,9 +661,8 @@ describe('GatewayService', () => {
it('still cleans live stale connections when registered-ids is unavailable', async () => {
// Mid-rollout: gateway without /api/admin/registered-ids. The stats
// snapshot alone must keep the stale pass alive for live connections,
- // while desired providers missing from the partial snapshot fall back
- // to per-connection status checks instead of being treated as
- // disconnected (which would wake dormant DOs).
+ // while desired providers missing from the partial snapshot are deferred
+ // instead of waking dormant DOs or being treated as disconnected.
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
platform === 'discord' ? [provider] : [],
);
@@ -667,9 +684,7 @@ describe('GatewayService', () => {
await service.ensureRunning();
expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('stale-live');
- // prov-1 missing from the incomplete snapshot β†’ ask the DO, find it
- // dormant, leave it alone.
- expect(mockGatewayClient.getStatus).toHaveBeenCalledWith('prov-1');
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
expect(mockGatewayClient.connect).not.toHaveBeenCalled();
expect(mockGatewayClient.disconnect).not.toHaveBeenCalledWith('prov-1');
});
@@ -848,17 +863,97 @@ describe('GatewayService', () => {
);
});
- it('asks the DO for status when the id is registered but pruned from stats', async () => {
+ it('keeps registered-only ids without waking their connection DOs', async () => {
mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
platform === 'discord' ? [provider] : [],
);
mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });
mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });
- mockGatewayClient.getStatus.mockResolvedValue({ state: { status: 'dormant' } });
await service.ensureRunning();
- expect(mockGatewayClient.getStatus).toHaveBeenCalledWith('prov-1');
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
+ });
+
+ it('reconnects a desired connection reported disconnected by stats without probing its DO', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
+ platform === 'discord' ? [provider] : [],
+ );
+ mockGatewayClient.getStats.mockResolvedValue({
+ byPlatform: {},
+ connections: [
+ {
+ connectionId: 'prov-1',
+ platform: 'discord',
+ state: { status: 'disconnected' },
+ userId: 'u1',
+ },
+ ],
+ total: 1,
+ });
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });
+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(
+ expect.objectContaining({ connectionId: 'prov-1' }),
+ { ensure: true },
+ );
+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
+ });
+
+ it('reconciles 2,000 registered connections with two snapshot requests and no per-connection probes', async () => {
+ const providers = Array.from({ length: 2000 }, (_, index) => ({
+ ...provider,
+ applicationId: `app-${index}`,
+ id: `prov-${index}`,
+ }));
+
+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
+ platform === 'discord' ? providers : [],
+ );
+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({
+ ids: providers.map(({ id }) => id),
+ });
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.getStats).toHaveBeenCalledTimes(1);
+ expect(mockGatewayClient.getRegisteredIds).toHaveBeenCalledTimes(1);
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
+ });
+
+ it('uses registered ids as a complete existence snapshot when stats is unavailable', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
+ platform === 'discord' ? [provider] : [],
+ );
+ mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['prov-1'] });
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
+ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
+ });
+
+ it('defers missing desired ids when registered ids are unavailable', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>
+ platform === 'discord' ? [provider] : [],
+ );
+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });
+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registered unavailable'));
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.getStatus).not.toHaveBeenCalled();
expect(mockGatewayClient.connect).not.toHaveBeenCalled();
expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();
});
diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.ts
index 6dec62fd202..987fab4ab03 100644
--- a/apps/server/src/services/gateway/index.ts
+++ b/apps/server/src/services/gateway/index.ts
@@ -75,8 +75,9 @@ interface DesiredGatewayConnection {
interface ActualConnectionsSnapshot {
/**
- * False when the registered-ids call failed and the snapshot only covers
- * live stats β€” dormant/hibernated connections may be missing from the map.
+ * True when registered ids were loaded successfully, making absence from
+ * `connections` authoritative. False means the snapshot only covers live
+ * stats, so dormant/hibernated connections may be missing from the map.
*/
complete: boolean;
/** connectionId β†’ gateway status, or null for registered-only (pruned) ids. */
@@ -189,19 +190,23 @@ export class GatewayService {
const { desired, desiredComplete, gated } = await this.buildDesiredConnections(
serverDB,
gateKeeper,
- client,
);
- // Fetch actual AFTER the gated disconnects above so those ids have already
- // dropped out of the gateway's view and don't get double-counted as stale.
const actual = await this.fetchActualConnections(client);
+ const gatedDisconnected = await this.disconnectGatedConnections(client, actual, gated);
// A partial desired set would make healthy connections look stale, so only
// run the disconnect pass when every platform loaded successfully. A
// partial ACTUAL set is fine β€” the pass only disconnects ids it can see.
let stale = 0;
if (actual && desiredComplete) {
- stale = await this.disconnectStaleConnections(client, serverDB, actual.connections, desired);
+ stale = await this.disconnectStaleConnections(
+ client,
+ serverDB,
+ actual.connections,
+ desired,
+ gated,
+ );
} else if (actual) {
log('Gateway sync: desired set incomplete, skipping stale-connection cleanup this round');
}
@@ -209,6 +214,7 @@ export class GatewayService {
// ── desired βˆ’ actual β†’ connect ──
let connected = 0;
+ let deferred = 0;
let skipped = 0;
let failed = 0;
@@ -225,28 +231,29 @@ export class GatewayService {
return;
}
- const status = await this.resolveGatewayStatus(client, provider.id, actual);
-
- if (status === 'connected' || status === 'connecting') {
+ // Registered ids are the gateway's authoritative existence set. Use
+ // the status already present in live stats to recover an explicitly
+ // disconnected connection, but never wake registered-only DOs merely
+ // to inspect their runtime status.
+ const exists = actual?.connections.has(provider.id) ?? false;
+ const snapshotStatus = actual?.connections.get(provider.id);
+ if (exists && snapshotStatus !== 'disconnected') {
skipped++;
- log('Gateway sync: %s already %s, skipping', provider.id, status);
+ log('Gateway sync: %s already registered, skipping', provider.id);
return;
}
- // Dormant: gateway is running sparse alarm-driven polling and will
- // self-wake when a message arrives. Reconnecting here would defeat
- // the purpose β€” only manual reconnect (startClient) should override.
- if (status === 'dormant') {
- skipped++;
- log('Gateway sync: %s dormant, skipping (DO is sparse-polling)', provider.id);
+
+ // Without a complete registry snapshot, absence from live stats does
+ // not prove the connection is missing. Fail safe and retry next round
+ // instead of degrading to an unbounded per-DO status probe fan-out.
+ if (!exists && !actual?.complete) {
+ deferred++;
+ log('Gateway sync: %s absent from incomplete snapshot, deferring', provider.id);
return;
}
- // "error" means credential/config issue (e.g. WeChat session expired
- // because the account connected elsewhere). Auto-retry is pointless β€”
- // only user action (saving new credentials) can fix it.
- if (status === 'error') {
- skipped++;
- log('Gateway sync: %s in error state, skipping', provider.id);
- return;
+
+ if (snapshotStatus === 'disconnected') {
+ log('Gateway sync: %s reported disconnected in stats, reconnecting', provider.id);
}
const webhookPath = `/api/agent/webhooks/${platform}/${provider.applicationId}`;
@@ -292,13 +299,16 @@ export class GatewayService {
);
log(
- 'Gateway sync complete in %dms: desired=%d actual=%s connected=%d skipped=%d gated=%d stale=%d failed=%d',
+ 'Gateway sync complete in %dms: desired=%d actual=%s snapshotComplete=%s connected=%d skipped=%d deferred=%d gated=%d gatedDisconnected=%d stale=%d failed=%d',
Date.now() - startedAt,
desired.size,
actual ? actual.connections.size : 'unavailable',
+ actual?.complete ?? false,
connected,
skipped,
- gated,
+ deferred,
+ gated.size,
+ gatedDisconnected,
stale,
failed,
);
@@ -308,24 +318,22 @@ export class GatewayService {
* Build the set of connections that SHOULD exist on the gateway: enabled
* persistent-mode providers whose owner passes the bot feature gate.
*
- * Paid-gated providers are disconnected inline (the generic stale pass
- * can't produce their user-facing blocked message) and excluded from the
- * desired set. If the gate check itself errors, the provider is kept in
- * desired β€” a flaky subscription lookup must not tear down a healthy
- * connection.
+ * Paid-gated providers are tracked separately and excluded from the desired
+ * set so the caller can disconnect only ids the gateway still holds. If the
+ * gate check itself errors, the provider is kept in desired β€” a flaky
+ * subscription lookup must not tear down a healthy connection.
*/
private async buildDesiredConnections(
serverDB: Awaited<ReturnType<typeof getServerDB>>,
gateKeeper: KeyVaultsGateKeeper,
- client: ReturnType<typeof getMessageGatewayClient>,
): Promise<{
desired: Map<string, DesiredGatewayConnection>;
desiredComplete: boolean;
- gated: number;
+ gated: Set<string>;
}> {
const desired = new Map<string, DesiredGatewayConnection>();
let desiredComplete = true;
- let gated = 0;
+ const gated = new Set<string>();
for (const definition of platformRegistry.listPlatforms()) {
const platform = definition.id;
@@ -366,12 +374,7 @@ export class GatewayService {
}
if (!allowed) {
- gated++;
- try {
- await client.disconnect(provider.id);
- } catch (err) {
- log('Gateway sync: paid-gated disconnect failed %s: %O', provider.id, err);
- }
+ gated.add(provider.id);
await updateBotRuntimeStatus({
applicationId: provider.applicationId,
errorMessage: getBotFeatureBlockedMessage(
@@ -381,7 +384,11 @@ export class GatewayService {
platform,
status: BOT_RUNTIME_STATUSES.failed,
});
- log('Gateway sync: paid-gated %s:%s, disconnected', platform, provider.applicationId);
+ log(
+ 'Gateway sync: paid-gated %s:%s, excluded from desired set',
+ platform,
+ provider.applicationId,
+ );
continue;
}
@@ -396,47 +403,78 @@ export class GatewayService {
return { desired, desiredComplete, gated };
}
+ /**
+ * With a complete registry snapshot, disconnect paid-gated providers only
+ * when the connection still exists. When the snapshot is partial or
+ * unavailable, preserve access enforcement by falling back to disconnecting
+ * every gated id; that bounded set is independent of the desired-connection
+ * status fan-out this reconciliation avoids.
+ */
+ private async disconnectGatedConnections(
+ client: ReturnType<typeof getMessageGatewayClient>,
+ actual: ActualConnectionsSnapshot | null,
+ gated: Set<string>,
+ ): Promise<number> {
+ const connectionIds = actual?.complete
+ ? [...gated].filter((id) => actual.connections.has(id))
+ : [...gated];
+ let disconnected = 0;
+
+ await pMap(
+ connectionIds,
+ async (id) => {
+ try {
+ await client.disconnect(id);
+ disconnected++;
+ log('Gateway sync: paid-gated connection %s disconnected', id);
+ } catch (err) {
+ log('Gateway sync: paid-gated disconnect failed %s: %O', id, err);
+ }
+ },
+ { concurrency: GATEWAY_SYNC_CONCURRENCY },
+ );
+
+ return disconnected;
+ }
+
/**
* Snapshot the gateway's view of existing connections: live stats (with
* status) unioned with registered ids (dormant/hibernated connections the
* AdminDO stats already pruned β€” status unknown, hence `null`).
*
- * Returns null when stats are unavailable; callers then fall back to
- * per-connection status checks and skip stale-connection cleanup. The
- * registered-ids call is best-effort: an older gateway without the admin
- * endpoint (mid-rollout) or a transient failure must not disable
- * reconciliation for the live connections stats already covers β€” the stale
- * pass only ever disconnects ids present in the snapshot, so a partial
- * snapshot just cleans up less. `complete: false` marks the partial case so
- * status resolution won't treat "missing from snapshot" as disconnected.
+ * Registered ids are the authoritative existence set, so a successful call
+ * produces a complete snapshot even when stats are unavailable. When only
+ * stats succeed, the partial snapshot can still drive safe stale cleanup,
+ * but desired ids missing from it are deferred rather than probed one by one.
+ * Returns null only when neither endpoint is available.
*/
private async fetchActualConnections(
client: ReturnType<typeof getMessageGatewayClient>,
): Promise<ActualConnectionsSnapshot | null> {
const connections = new Map<string, string | null>();
+ let statsAvailable = false;
try {
const stats = await client.getStats();
+ statsAvailable = true;
for (const conn of stats.connections) {
connections.set(conn.connectionId, conn.state.status);
}
} catch (err) {
log('Gateway sync: failed to fetch gateway stats snapshot: %O', err);
- return null;
}
- let complete = true;
try {
const { ids } = await client.getRegisteredIds();
for (const id of ids) {
if (!connections.has(id)) connections.set(id, null);
}
+ return { complete: true, connections };
} catch (err) {
- complete = false;
log('Gateway sync: registered-ids unavailable, using stats-only snapshot: %O', err);
}
- return { complete, connections };
+ return statsAvailable ? { complete: false, connections } : null;
}
/**
@@ -451,9 +489,10 @@ export class GatewayService {
serverDB: Awaited<ReturnType<typeof getServerDB>>,
actual: Map<string, string | null>,
desired: Map<string, DesiredGatewayConnection>,
+ gated: Set<string>,
): Promise<number> {
const allStaleIds = [...actual.keys()].filter(
- (id) => !desired.has(id) && !isMessengerConnectionId(id),
+ (id) => !desired.has(id) && !gated.has(id) && !isMessengerConnectionId(id),
);
if (allStaleIds.length === 0) return 0;
@@ -530,39 +569,6 @@ export class GatewayService {
return disconnected;
}
- /**
- * Resolve a connection's gateway status from the reconciliation snapshot,
- * falling back to a per-connection status call when the snapshot is missing
- * (admin endpoints down) or only knows the id from the registered set.
- * Returns undefined when the status can't be determined β€” callers treat
- * that as "attempt connect" (the gateway upserts on connectionId, so a
- * redundant connect is safe).
- */
- private async resolveGatewayStatus(
- client: ReturnType<typeof getMessageGatewayClient>,
- connectionId: string,
- actual: ActualConnectionsSnapshot | null,
- ): Promise<string | undefined> {
- if (actual) {
- const snapshot = actual.connections.get(connectionId);
- // Unknown to the gateway entirely β†’ connect. Only trustworthy when the
- // snapshot is complete β€” a stats-only snapshot misses dormant ids, and
- // treating those as disconnected would reconnect sparse-polling DOs.
- if (snapshot === undefined && actual.complete) return 'disconnected';
- // Known status from stats.
- if (snapshot !== undefined && snapshot !== null) return snapshot;
- // Registered but pruned from stats (likely dormant), or missing from an
- // incomplete snapshot β€” ask the DO itself.
- }
-
- try {
- const status = await client.getStatus(connectionId);
- return status.state.status;
- } catch {
- return undefined;
- }
- }
-
async stop(): Promise<void> {
const manager = getGatewayManager();
if (!manager) return;