Skip to content

Commit 00abee4

Browse files
committed
refactor: encapsulate keyed queue ownership
1 parent b750fe6 commit 00abee4

27 files changed

Lines changed: 108 additions & 184 deletions

File tree

‎extensions/codex/src/app-server/session-binding.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
type AuthProfileStore,
1313
} from "openclaw/plugin-sdk/agent-runtime";
1414
import { type FileLockOptions, withFileLock } from "openclaw/plugin-sdk/file-lock";
15-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
15+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1616
import {
1717
CODEX_PLUGINS_MARKETPLACE_NAME,
1818
normalizeCodexServiceTier,
@@ -41,7 +41,7 @@ const CODEX_APP_SERVER_BINDING_LOCK_OPTIONS: FileLockOptions = {
4141
},
4242
stale: CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS * 2,
4343
};
44-
const bindingMutationQueues = new Map<string, Promise<void>>();
44+
const bindingMutationQueue = new KeyedAsyncQueue();
4545
const bindingMutationContext = new AsyncLocalStorage<Set<string>>();
4646

4747
type ProviderAuthAliasLookupParams = Parameters<typeof resolveProviderIdForAuth>[1];
@@ -121,14 +121,11 @@ export async function withCodexAppServerBindingLock<T>(
121121
// same-process tasks cannot slip between compare/clear/start.
122122
const nestedOwnedBindings = new Set(ownedBindings);
123123
nestedOwnedBindings.add(bindingPath);
124-
return await enqueueKeyedTask({
125-
tails: bindingMutationQueues,
126-
key: bindingPath,
127-
task: () =>
128-
bindingMutationContext.run(nestedOwnedBindings, () =>
129-
withFileLock(bindingPath, CODEX_APP_SERVER_BINDING_LOCK_OPTIONS, run),
130-
),
131-
});
124+
return await bindingMutationQueue.enqueue(bindingPath, () =>
125+
bindingMutationContext.run(nestedOwnedBindings, () =>
126+
withFileLock(bindingPath, CODEX_APP_SERVER_BINDING_LOCK_OPTIONS, run),
127+
),
128+
);
132129
}
133130

134131
/** Reads and normalizes a Codex app-server binding sidecar, returning undefined on stale data. */

‎extensions/codex/src/conversation-binding.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
} from "openclaw/plugin-sdk/agent-harness-runtime";
66
import { resolveSessionAgentIds } from "openclaw/plugin-sdk/agent-runtime";
77
import { loadExecApprovals } from "openclaw/plugin-sdk/exec-approvals-runtime";
8-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
8+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
99
import type {
1010
PluginConversationBindingResolvedEvent,
1111
PluginHookInboundClaimContext,
@@ -121,7 +121,7 @@ type CodexConversationConfig = Parameters<
121121
type ResolvedCodexConversationConfig = NonNullable<CodexConversationConfig>;
122122

123123
type CodexConversationGlobalState = {
124-
queues: Map<string, Promise<void>>;
124+
queue: KeyedAsyncQueue;
125125
};
126126

127127
async function resolveConversationAppServerRuntime(params: {
@@ -170,7 +170,7 @@ function getGlobalState(): CodexConversationGlobalState {
170170
const globalState = globalThis as typeof globalThis & {
171171
[CODEX_CONVERSATION_GLOBAL_STATE]?: CodexConversationGlobalState;
172172
};
173-
globalState[CODEX_CONVERSATION_GLOBAL_STATE] ??= { queues: new Map() };
173+
globalState[CODEX_CONVERSATION_GLOBAL_STATE] ??= { queue: new KeyedAsyncQueue() };
174174
return globalState[CODEX_CONVERSATION_GLOBAL_STATE];
175175
}
176176

@@ -975,8 +975,7 @@ function isCodexThreadNotFoundError(error: unknown): boolean {
975975
}
976976

977977
function enqueueBoundTurn<T>(key: string, run: () => Promise<T>): Promise<T> {
978-
const state = getGlobalState();
979-
return enqueueKeyedTask({ tails: state.queues, key, task: run });
978+
return getGlobalState().queue.enqueue(key, run);
980979
}
981980

982981
function resolveThreadRequestModelProvider(params: {

‎extensions/discord/src/internal/command-deploy.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { createHash } from "node:crypto";
33
import path from "node:path";
44
import { ApplicationCommandType, type APIApplicationCommand } from "discord-api-types/v10";
5-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
5+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
66
import { privateFileStore } from "openclaw/plugin-sdk/security-runtime";
77
import {
88
createApplicationCommand,
@@ -34,10 +34,10 @@ type SerializedCommand = ReturnType<BaseCommand["serialize"]>;
3434
* file lock. Discord deployers only run inside the gateway process, so an
3535
* in-process mutex is sufficient for the documented concurrency surface.
3636
*/
37-
const cachePersistLocks = new Map<string, Promise<void>>();
37+
const cachePersistLocks = new KeyedAsyncQueue();
3838

3939
async function withCachePersistLock<T>(storePath: string, fn: () => Promise<T>): Promise<T> {
40-
return await enqueueKeyedTask({ tails: cachePersistLocks, key: storePath, task: fn });
40+
return await cachePersistLocks.enqueue(storePath, fn);
4141
}
4242

4343
export class DiscordCommandDeployer {

‎extensions/imessage/src/monitor/catchup.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Imessage plugin module implements catchup behavior.
22
import { createHash } from "node:crypto";
3-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
3+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
44
import type { PluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-runtime";
55
import { getIMessageRuntime } from "../runtime.js";
66

@@ -30,7 +30,7 @@ const MAX_FAILURE_RETRY_MAP_JSON_BYTES = 48_000;
3030
const textEncoder = new TextEncoder();
3131
export const IMESSAGE_CATCHUP_CURSOR_NAMESPACE = "imessage.catchup-cursors";
3232
export const IMESSAGE_CATCHUP_CURSOR_MAX_ENTRIES = 256;
33-
const cursorWriteQueues = new Map<string, Promise<void>>();
33+
const cursorWriteQueue = new KeyedAsyncQueue();
3434

3535
export type IMessageCatchupConfig = {
3636
enabled?: boolean;
@@ -120,7 +120,7 @@ function updateCatchupCursorStore(
120120

121121
function enqueueCursorWrite<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
122122
const key = resolveIMessageCatchupCursorKey(accountId);
123-
return enqueueKeyedTask({ tails: cursorWriteQueues, key, task: fn });
123+
return cursorWriteQueue.enqueue(key, fn);
124124
}
125125

126126
function sanitizeFailureRetriesInput(raw: unknown): Record<string, number> {

‎extensions/matrix/src/matrix/monitor/handler.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
resolveChannelContextVisibilityMode,
2828
} from "openclaw/plugin-sdk/context-visibility-runtime";
2929
import { isDangerousNameMatchingEnabled } from "openclaw/plugin-sdk/dangerous-name-runtime";
30-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
30+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
3131
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
3232
import {
3333
isFutureDateTimestampMs,
@@ -530,7 +530,7 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
530530
logVerboseMessage,
531531
});
532532
const roomHistoryTracker = createRoomHistoryTracker();
533-
const roomIngressTails = new Map<string, Promise<void>>();
533+
const roomIngressQueue = new KeyedAsyncQueue();
534534
const sharedDmContextNoticeRooms = new Set<string>();
535535

536536
const readStoreAllowFrom = async (): Promise<string[]> => {
@@ -577,7 +577,7 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
577577
};
578578

579579
const runRoomIngress = async <T>(roomId: string, task: () => Promise<T>): Promise<T> => {
580-
return await enqueueKeyedTask({ tails: roomIngressTails, key: roomId, task });
580+
return await roomIngressQueue.enqueue(roomId, task);
581581
};
582582

583583
return async (roomId: string, event: MatrixRawEvent) => {

‎extensions/memory-core/src/short-term-promotion.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { createHash } from "node:crypto";
33
import fs from "node:fs/promises";
44
import path from "node:path";
5-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
5+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
66
import type { MemorySearchResult } from "openclaw/plugin-sdk/memory-core-host-runtime-files";
77
import {
88
DEFAULT_MEMORY_DEEP_DREAMING_MAX_PROMOTED_SNIPPET_TOKENS,
@@ -89,7 +89,7 @@ const GENERIC_DAY_HEADING_RE =
8989
/^(?:(?:mon|monday|tue|tues|tuesday|wed|wednesday|thu|thur|thurs|thursday|fri|friday|sat|saturday|sun|sunday)(?:,\s+)?)?(?:(?:jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+\d{1,2}(?:st|nd|rd|th)?(?:,\s*\d{4})?|\d{1,2}[/-]\d{1,2}(?:[/-]\d{2,4})?|\d{4}[/-]\d{2}[/-]\d{2})$/i;
9090
const PROMOTION_LIST_MARKER_RE = /^(?:\d+\.\s+|[-*+]\s+)/;
9191
const MANAGED_DREAMING_HEADINGS = new Set(["light sleep", "rem sleep"]);
92-
const inProcessShortTermLocks = new Map<string, Promise<void>>();
92+
const inProcessShortTermLocks = new KeyedAsyncQueue();
9393

9494
type PromotionWeights = {
9595
frequency: number;
@@ -850,7 +850,7 @@ function isProcessLikelyAlive(pid: number): boolean {
850850
}
851851

852852
async function withInProcessShortTermLock<T>(lockPath: string, task: () => Promise<T>): Promise<T> {
853-
return await enqueueKeyedTask({ tails: inProcessShortTermLocks, key: lockPath, task });
853+
return await inProcessShortTermLocks.enqueue(lockPath, task);
854854
}
855855

856856
async function withShortTermLock<T>(workspaceDir: string, task: () => Promise<T>): Promise<T> {

‎extensions/msteams/src/sqlite-state.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Msteams plugin module implements sqlite state behavior.
22
import path from "node:path";
3-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
3+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
44
import { getMSTeamsRuntime } from "./runtime.js";
55
import { withFileLock } from "./store-fs.js";
66

@@ -56,10 +56,10 @@ export function resolveMSTeamsSqliteStateDir(
5656
);
5757
}
5858

59-
const sqliteMutationLocks = new Map<string, Promise<void>>();
59+
const sqliteMutationLocks = new KeyedAsyncQueue();
6060

6161
async function withProcessMutationLock<T>(lockPath: string, fn: () => Promise<T>): Promise<T> {
62-
return await enqueueKeyedTask({ tails: sqliteMutationLocks, key: lockPath, task: fn });
62+
return await sqliteMutationLocks.enqueue(lockPath, fn);
6363
}
6464

6565
export async function withMSTeamsSqliteMutationLock<T>(

‎extensions/nostr/src/nostr-profile-http.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*/
99

1010
import type { IncomingMessage, ServerResponse } from "node:http";
11-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
11+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1212
import {
1313
normalizeLowercaseStringOrEmpty,
1414
normalizeOptionalLowercaseString,
@@ -78,10 +78,10 @@ function checkRateLimit(accountId: string): boolean {
7878
// Mutex for Concurrent Publish Prevention
7979
// ============================================================================
8080

81-
const publishLocks = new Map<string, Promise<void>>();
81+
const publishLocks = new KeyedAsyncQueue();
8282

8383
async function withPublishLock<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
84-
return await enqueueKeyedTask({ tails: publishLocks, key: accountId, task: fn });
84+
return await publishLocks.enqueue(accountId, fn);
8585
}
8686

8787
// ============================================================================

‎extensions/slack/src/send.ts‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
} from "openclaw/plugin-sdk/channel-outbound";
1010
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
1111
import { withTrustedEnvProxyGuardedFetchMode } from "openclaw/plugin-sdk/fetch-runtime";
12-
import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
12+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1313
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
1414
import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
1515
import {
@@ -48,7 +48,7 @@ const SLACK_DNS_RETRY_CODES = new Set(["EAI_AGAIN", "ENOTFOUND", "UND_ERR_DNS_RE
4848
const SLACK_DNS_RETRY_ATTEMPTS = 2;
4949
const SLACK_DNS_RETRY_BASE_DELAY_MS = 250;
5050
const slackDmChannelCache = new Map<string, string>();
51-
const slackSendQueues = new Map<string, Promise<void>>();
51+
const slackSendQueue = new KeyedAsyncQueue();
5252

5353
type SlackRecipient =
5454
| {
@@ -489,7 +489,7 @@ function createSlackSendQueueKey(params: {
489489
}
490490

491491
async function runQueuedSlackSend<T>(key: string, task: () => Promise<T>): Promise<T> {
492-
return await enqueueKeyedTask({ tails: slackSendQueues, key, task });
492+
return await slackSendQueue.enqueue(key, task);
493493
}
494494

495495
function createSlackDmCacheKey(params: {
@@ -574,10 +574,6 @@ export function clearSlackDmChannelCache(): void {
574574
slackDmChannelCache.clear();
575575
}
576576

577-
export function clearSlackSendQueuesForTest(): void {
578-
slackSendQueues.clear();
579-
}
580-
581577
export function clearSlackDefaultSendIdentitiesForTest(): void {
582578
slackDefaultSendIdentities.clear();
583579
}

‎extensions/slack/src/send.upload.test.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ vi.mock("./runtime-api.js", async () => {
5454
};
5555
});
5656

57-
const { sendMessageSlack, clearSlackDmChannelCache, clearSlackSendQueuesForTest } =
58-
await import("./send.js");
57+
const { sendMessageSlack, clearSlackDmChannelCache } = await import("./send.js");
5958
const SLACK_TEST_CFG = { channels: { slack: { botToken: "xoxb-test" } } };
6059

6160
type UploadTestClient = WebClient & {
@@ -167,7 +166,6 @@ describe("sendMessageSlack file upload with user IDs", () => {
167166
fetchWithSsrFGuard.mockClear();
168167
loadOutboundMediaFromUrlMock.mockClear();
169168
clearSlackDmChannelCache();
170-
clearSlackSendQueuesForTest();
171169
clearSlackThreadParticipationCache();
172170
});
173171

0 commit comments

Comments
 (0)