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.

⚡️ perf(gateway): check desired-set feature gates concurrently (#23059)

Rdmclin260b7dda33fe0
diff --git a/apps/server/src/services/gateway/index.sync.test.ts b/apps/server/src/services/gateway/index.sync.test.ts
index aff28c86eb0..6f58956a68b 100644
--- a/apps/server/src/services/gateway/index.sync.test.ts
+++ b/apps/server/src/services/gateway/index.sync.test.ts
@@ -6,6 +6,7 @@ import {
mockFindEnabledByPlatform,
mockGatewayClient,
mockGatewayEnv,
+ mockGetBotRuntimeStatus,
mockIsBotFeatureAccessAllowed,
mockResolveConnectionMode,
mockUpdateBotRuntimeStatus,
@@ -268,5 +269,99 @@ describe('GatewayService', () => {
}),
);
});
+
+ describe('paid-gate checks across a fleet', () => {
+ const wechatFleet = (count: number, userId = (i: number) => `user-${i}`) =>
+ Array.from({ length: count }, (_, i) => ({
+ applicationId: `wechat-app-${i}`,
+ credentials: { botToken: 'token' },
+ id: `wechat-provider-${i}`,
+ settings: {},
+ userId: userId(i),
+ }));
+
+ beforeEach(() => {
+ mockResolveConnectionMode.mockReturnValue('polling');
+ });
+
+ it('checks gates concurrently, but never more than a bounded number at once', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
+ platform === 'wechat' ? wechatFleet(40) : [],
+ );
+ let inFlight = 0;
+ let maxInFlight = 0;
+ mockIsBotFeatureAccessAllowed.mockImplementation(async () => {
+ inFlight++;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ inFlight--;
+ return false;
+ });
+
+ await service.ensureRunning();
+
+ expect(mockIsBotFeatureAccessAllowed).toHaveBeenCalledTimes(40);
+ expect(maxInFlight).toBeGreaterThan(1);
+ expect(maxInFlight).toBeLessThanOrEqual(16);
+ });
+
+ it('does not rewrite a gated status that already says the same thing', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
+ platform === 'wechat' ? [createWechatProvider('free-user')] : [],
+ );
+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
+ mockGetBotRuntimeStatus.mockResolvedValue({
+ errorMessage: 'This bot channel requires a paid plan.',
+ status: 'failed',
+ });
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider'] });
+
+ await service.ensureRunning();
+
+ expect(mockUpdateBotRuntimeStatus).not.toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'failed' }),
+ );
+ // The verdict itself is unchanged: still excluded and disconnected.
+ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider');
+ expect(mockGatewayClient.connect).not.toHaveBeenCalled();
+ });
+
+ it('rewrites a gated status that changed since the last sync', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
+ platform === 'wechat' ? [createWechatProvider('free-user')] : [],
+ );
+ mockIsBotFeatureAccessAllowed.mockResolvedValue(false);
+ mockGetBotRuntimeStatus.mockResolvedValue({ status: 'connected' });
+
+ await service.ensureRunning();
+
+ expect(mockUpdateBotRuntimeStatus).toHaveBeenCalledWith(
+ expect.objectContaining({
+ applicationId: 'wechat-app',
+ errorMessage: 'This bot channel requires a paid plan.',
+ status: 'failed',
+ }),
+ );
+ });
+
+ it('still connects allowed bots when recording a gated status fails', async () => {
+ mockFindEnabledByPlatform.mockImplementation(async (_db, platform) =>
+ platform === 'wechat' ? wechatFleet(2, (i) => (i === 0 ? 'free-user' : 'paid-user')) : [],
+ );
+ mockIsBotFeatureAccessAllowed.mockImplementation(
+ async ({ userId }: { userId: string }) => userId === 'paid-user',
+ );
+ mockUpdateBotRuntimeStatus.mockRejectedValue(new Error('redis down'));
+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: ['wechat-provider-0'] });
+
+ await service.ensureRunning();
+
+ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith('wechat-provider-0');
+ expect(mockGatewayClient.connect).toHaveBeenCalledWith(
+ expect.objectContaining({ connectionId: 'wechat-provider-1' }),
+ expect.anything(),
+ );
+ });
+ });
});
});
diff --git a/apps/server/src/services/gateway/sync/state.ts b/apps/server/src/services/gateway/sync/state.ts
index b108f86b317..979c5312b81 100644
--- a/apps/server/src/services/gateway/sync/state.ts
+++ b/apps/server/src/services/gateway/sync/state.ts
@@ -3,6 +3,7 @@
* says should exist, what each gateway host holds, and per-host slices.
*/
import debug from 'debug';
+import pMap from 'p-map';
import {
getBotFeatureBlockedMessage,
@@ -19,7 +20,11 @@ import {
resolveMessageGatewayHost,
} from '../MessageGatewayClient';
import { resolveReplyConnectionHost } from '../replyConnectionHost';
-import { BOT_RUNTIME_STATUSES, updateBotRuntimeStatus } from '../runtimeStatus';
+import {
+ BOT_RUNTIME_STATUSES,
+ getBotRuntimeStatus,
+ updateBotRuntimeStatus,
+} from '../runtimeStatus';
import type { ActualConnectionsSnapshot, DesiredGatewayConnection } from './types';
const log = debug('lobe-server:service:gateway');
@@ -61,6 +66,50 @@ export function hostGatedSlice(gated: Map<string, string>, host: MessageGatewayH
);
}
+/**
+ * How many providers' feature gates are checked at once while building the
+ * desired set. High enough that a fleet-sized platform finishes in seconds,
+ * low enough not to monopolise the connection pool behind the gate.
+ */
+const FEATURE_GATE_CONCURRENCY = 16;
+
+/**
+ * Record on a paid-gated provider why it is not connected.
+ *
+ * Written only when it differs from what is stored: every sync re-derives the
+ * same verdict for the same gated bots, and rewriting an identical status
+ * each round costs a Redis write per bot and keeps resetting its `updatedAt`
+ * for no change in what it says.
+ *
+ * Best-effort: the status is a label for the UI, and a Redis hiccup must not
+ * fail the platform's whole desired set — that would be read as incomplete and
+ * hold back every other connection's reconcile.
+ */
+async function markGated(
+ platform: string,
+ provider: { applicationId: string; id: string; workspaceId?: string | null },
+): Promise<void> {
+ const errorMessage = getBotFeatureBlockedMessage(
+ platform,
+ provider.workspaceId ? 'workspace' : 'personal',
+ );
+
+ try {
+ const current = await getBotRuntimeStatus(platform, provider.applicationId);
+ if (current?.status === BOT_RUNTIME_STATUSES.failed && current.errorMessage === errorMessage)
+ return;
+
+ await updateBotRuntimeStatus({
+ applicationId: provider.applicationId,
+ errorMessage,
+ platform,
+ status: BOT_RUNTIME_STATUSES.failed,
+ });
+ } catch (err) {
+ log('Gateway sync: could not record paid-gate status for %s: %O', provider.id, err);
+ }
+}
+
/**
* Build the set of connections that SHOULD exist on the gateway: enabled
* persistent-mode providers whose owner passes the bot feature gate.
@@ -113,43 +162,50 @@ export async function buildDesiredConnections(
{ includeUndecryptable: true },
);
- let gatedOnPlatform = 0;
- for (const provider of providers) {
+ // Webhook-mode platforms don't need persistent gateway connections.
+ // The webhook URL is set once when the user saves the bot config
+ // (via startClientViaGateway). No action needed during periodic sync.
+ const persistent = providers.flatMap((provider) => {
const connectionMode = resolveConnectionMode(definition, provider.settings);
+ return connectionMode === 'webhook' ? [] : [{ connectionMode, provider }];
+ });
- // Webhook-mode platforms don't need persistent gateway connections.
- // The webhook URL is set once when the user saves the bot config
- // (via startClientViaGateway). No action needed during periodic sync.
- if (connectionMode === 'webhook') continue;
-
- let allowed = true;
- try {
- allowed = await isBotFeatureAccessAllowed({
- applicationId: provider.applicationId,
- platform,
- userId: provider.userId,
- workspaceId: provider.workspaceId ?? undefined,
- });
- } catch (err) {
- log(
- 'Gateway sync: feature gate check failed %s, keeping connection: %O',
- provider.id,
- err,
- );
- }
+ // Bounded concurrency, not one provider at a time. Regression: each
+ // check is a lookup of its own, and checking a large platform in series
+ // made this build slow enough for a gateway's boot pull to time out on
+ // every attempt. `pMap` keeps result order, so the desired set is
+ // filled in the same order as before.
+ const checked = await pMap(
+ persistent,
+ async ({ connectionMode, provider }) => {
+ let allowed = true;
+ try {
+ allowed = await isBotFeatureAccessAllowed({
+ applicationId: provider.applicationId,
+ platform,
+ userId: provider.userId,
+ workspaceId: provider.workspaceId ?? undefined,
+ });
+ } catch (err) {
+ log(
+ 'Gateway sync: feature gate check failed %s, keeping connection: %O',
+ provider.id,
+ err,
+ );
+ }
+
+ if (!allowed) await markGated(platform, provider);
+
+ return { allowed, connectionMode, provider };
+ },
+ { concurrency: FEATURE_GATE_CONCURRENCY },
+ );
+ let gatedOnPlatform = 0;
+ for (const { allowed, connectionMode, provider } of checked) {
if (!allowed) {
gated.set(provider.id, platform);
gatedOnPlatform++;
- await updateBotRuntimeStatus({
- applicationId: provider.applicationId,
- errorMessage: getBotFeatureBlockedMessage(
- platform,
- provider.workspaceId ? 'workspace' : 'personal',
- ),
- platform,
- status: BOT_RUNTIME_STATUSES.failed,
- });
continue;
}