Skip to content

Commit c2fc7aa

Browse files
authored
refactor: consolidate exact keyed async queues (#99691)
* refactor: consolidate keyed async queues * chore: refresh merge-ref CI * refactor: encapsulate keyed queue ownership
1 parent 7608d38 commit c2fc7aa

30 files changed

Lines changed: 136 additions & 456 deletions

File tree

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

Lines changed: 6 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +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 { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1516
import {
1617
CODEX_PLUGINS_MARKETPLACE_NAME,
1718
normalizeCodexServiceTier,
@@ -40,7 +41,7 @@ const CODEX_APP_SERVER_BINDING_LOCK_OPTIONS: FileLockOptions = {
4041
},
4142
stale: CODEX_APP_SERVER_BINDING_GUARDED_REQUEST_TIMEOUT_MS * 2,
4243
};
43-
const bindingMutationQueues = new Map<string, Promise<void>>();
44+
const bindingMutationQueue = new KeyedAsyncQueue();
4445
const bindingMutationContext = new AsyncLocalStorage<Set<string>>();
4546

4647
type ProviderAuthAliasLookupParams = Parameters<typeof resolveProviderIdForAuth>[1];
@@ -118,30 +119,13 @@ export async function withCodexAppServerBindingLock<T>(
118119
// The SDK file lock is process-reentrant, so pair it with a local queue.
119120
// Nested writes from the same guarded mutation can proceed, but unrelated
120121
// same-process tasks cannot slip between compare/clear/start.
121-
const previous = bindingMutationQueues.get(bindingPath) ?? Promise.resolve();
122-
let releaseCurrent!: () => void;
123-
const current = new Promise<void>((resolve) => {
124-
releaseCurrent = resolve;
125-
});
126-
const queued = previous.then(
127-
() => current,
128-
() => current,
129-
);
130-
bindingMutationQueues.set(bindingPath, queued);
131-
await previous.catch(() => undefined);
132-
133122
const nestedOwnedBindings = new Set(ownedBindings);
134123
nestedOwnedBindings.add(bindingPath);
135-
try {
136-
return await bindingMutationContext.run(nestedOwnedBindings, () =>
124+
return await bindingMutationQueue.enqueue(bindingPath, () =>
125+
bindingMutationContext.run(nestedOwnedBindings, () =>
137126
withFileLock(bindingPath, CODEX_APP_SERVER_BINDING_LOCK_OPTIONS, run),
138-
);
139-
} finally {
140-
releaseCurrent();
141-
if (bindingMutationQueues.get(bindingPath) === queued) {
142-
bindingMutationQueues.delete(bindingPath);
143-
}
144-
}
127+
),
128+
);
145129
}
146130

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

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

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +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 { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
89
import type {
910
PluginConversationBindingResolvedEvent,
1011
PluginHookInboundClaimContext,
@@ -120,7 +121,7 @@ type CodexConversationConfig = Parameters<
120121
type ResolvedCodexConversationConfig = NonNullable<CodexConversationConfig>;
121122

122123
type CodexConversationGlobalState = {
123-
queues: Map<string, Promise<void>>;
124+
queue: KeyedAsyncQueue;
124125
};
125126

126127
async function resolveConversationAppServerRuntime(params: {
@@ -169,7 +170,7 @@ function getGlobalState(): CodexConversationGlobalState {
169170
const globalState = globalThis as typeof globalThis & {
170171
[CODEX_CONVERSATION_GLOBAL_STATE]?: CodexConversationGlobalState;
171172
};
172-
globalState[CODEX_CONVERSATION_GLOBAL_STATE] ??= { queues: new Map() };
173+
globalState[CODEX_CONVERSATION_GLOBAL_STATE] ??= { queue: new KeyedAsyncQueue() };
173174
return globalState[CODEX_CONVERSATION_GLOBAL_STATE];
174175
}
175176

@@ -974,22 +975,7 @@ function isCodexThreadNotFoundError(error: unknown): boolean {
974975
}
975976

976977
function enqueueBoundTurn<T>(key: string, run: () => Promise<T>): Promise<T> {
977-
const state = getGlobalState();
978-
const previous = state.queues.get(key) ?? Promise.resolve();
979-
const next = previous.then(run, run);
980-
const queued = next.then(
981-
() => undefined,
982-
() => undefined,
983-
);
984-
state.queues.set(key, queued);
985-
void next
986-
.finally(() => {
987-
if (state.queues.get(key) === queued) {
988-
state.queues.delete(key);
989-
}
990-
})
991-
.catch(() => undefined);
992-
return next;
978+
return getGlobalState().queue.enqueue(key, run);
993979
}
994980

995981
function resolveThreadRequestModelProvider(params: {

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

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +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 { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
56
import { privateFileStore } from "openclaw/plugin-sdk/security-runtime";
67
import {
78
createApplicationCommand,
@@ -33,25 +34,10 @@ type SerializedCommand = ReturnType<BaseCommand["serialize"]>;
3334
* file lock. Discord deployers only run inside the gateway process, so an
3435
* in-process mutex is sufficient for the documented concurrency surface.
3536
*/
36-
const cachePersistLocks = new Map<string, Promise<void>>();
37+
const cachePersistLocks = new KeyedAsyncQueue();
3738

3839
async function withCachePersistLock<T>(storePath: string, fn: () => Promise<T>): Promise<T> {
39-
const previous = cachePersistLocks.get(storePath) ?? Promise.resolve();
40-
let release: () => void = () => {};
41-
const next = new Promise<void>((resolve) => {
42-
release = resolve;
43-
});
44-
const chained = previous.then(() => next);
45-
cachePersistLocks.set(storePath, chained);
46-
try {
47-
await previous;
48-
return await fn();
49-
} finally {
50-
release();
51-
if (cachePersistLocks.get(storePath) === chained) {
52-
cachePersistLocks.delete(storePath);
53-
}
54-
}
40+
return await cachePersistLocks.enqueue(storePath, fn);
5541
}
5642

5743
export class DiscordCommandDeployer {

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

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

@@ -29,7 +30,7 @@ const MAX_FAILURE_RETRY_MAP_JSON_BYTES = 48_000;
2930
const textEncoder = new TextEncoder();
3031
export const IMESSAGE_CATCHUP_CURSOR_NAMESPACE = "imessage.catchup-cursors";
3132
export const IMESSAGE_CATCHUP_CURSOR_MAX_ENTRIES = 256;
32-
const cursorWriteQueues = new Map<string, Promise<unknown>>();
33+
const cursorWriteQueue = new KeyedAsyncQueue();
3334

3435
export type IMessageCatchupConfig = {
3536
enabled?: boolean;
@@ -119,17 +120,7 @@ function updateCatchupCursorStore(
119120

120121
function enqueueCursorWrite<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
121122
const key = resolveIMessageCatchupCursorKey(accountId);
122-
const prev = cursorWriteQueues.get(key) ?? Promise.resolve();
123-
const next = prev.then(fn, fn);
124-
cursorWriteQueues.set(key, next);
125-
next
126-
.finally(() => {
127-
if (cursorWriteQueues.get(key) === next) {
128-
cursorWriteQueues.delete(key);
129-
}
130-
})
131-
.catch(() => {});
132-
return next;
123+
return cursorWriteQueue.enqueue(key, fn);
133124
}
134125

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

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

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +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 { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
3031
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
3132
import {
3233
isFutureDateTimestampMs,
@@ -529,7 +530,7 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
529530
logVerboseMessage,
530531
});
531532
const roomHistoryTracker = createRoomHistoryTracker();
532-
const roomIngressTails = new Map<string, Promise<void>>();
533+
const roomIngressQueue = new KeyedAsyncQueue();
533534
const sharedDmContextNoticeRooms = new Set<string>();
534535

535536
const readStoreAllowFrom = async (): Promise<string[]> => {
@@ -576,22 +577,7 @@ export function createMatrixRoomMessageHandler(params: MatrixMonitorHandlerParam
576577
};
577578

578579
const runRoomIngress = async <T>(roomId: string, task: () => Promise<T>): Promise<T> => {
579-
const previous = roomIngressTails.get(roomId) ?? Promise.resolve();
580-
let releaseCurrent!: () => void;
581-
const current = new Promise<void>((resolve) => {
582-
releaseCurrent = resolve;
583-
});
584-
const chain = previous.catch(() => {}).then(() => current);
585-
roomIngressTails.set(roomId, chain);
586-
await previous.catch(() => {});
587-
try {
588-
return await task();
589-
} finally {
590-
releaseCurrent();
591-
if (roomIngressTails.get(roomId) === chain) {
592-
roomIngressTails.delete(roomId);
593-
}
594-
}
580+
return await roomIngressQueue.enqueue(roomId, task);
595581
};
596582

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

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

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { createHash } from "node:crypto";
33
import fs from "node:fs/promises";
44
import path from "node:path";
5+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
56
import type { MemorySearchResult } from "openclaw/plugin-sdk/memory-core-host-runtime-files";
67
import {
78
DEFAULT_MEMORY_DEEP_DREAMING_MAX_PROMOTED_SNIPPET_TOKENS,
@@ -88,7 +89,7 @@ const GENERIC_DAY_HEADING_RE =
8889
/^(?:(?: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;
8990
const PROMOTION_LIST_MARKER_RE = /^(?:\d+\.\s+|[-*+]\s+)/;
9091
const MANAGED_DREAMING_HEADINGS = new Set(["light sleep", "rem sleep"]);
91-
const inProcessShortTermLocks = new Map<string, Promise<void>>();
92+
const inProcessShortTermLocks = new KeyedAsyncQueue();
9293

9394
type PromotionWeights = {
9495
frequency: number;
@@ -849,23 +850,7 @@ function isProcessLikelyAlive(pid: number): boolean {
849850
}
850851

851852
async function withInProcessShortTermLock<T>(lockPath: string, task: () => Promise<T>): Promise<T> {
852-
const previous = inProcessShortTermLocks.get(lockPath) ?? Promise.resolve();
853-
let releaseCurrent!: () => void;
854-
const current = new Promise<void>((resolve) => {
855-
releaseCurrent = resolve;
856-
});
857-
const queued = previous.catch(() => undefined).then(() => current);
858-
inProcessShortTermLocks.set(lockPath, queued);
859-
860-
await previous.catch(() => undefined);
861-
try {
862-
return await task();
863-
} finally {
864-
releaseCurrent();
865-
if (inProcessShortTermLocks.get(lockPath) === queued) {
866-
inProcessShortTermLocks.delete(lockPath);
867-
}
868-
}
853+
return await inProcessShortTermLocks.enqueue(lockPath, task);
869854
}
870855

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

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

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

@@ -55,28 +56,10 @@ export function resolveMSTeamsSqliteStateDir(
5556
);
5657
}
5758

58-
const sqliteMutationLocks = new Map<string, Promise<unknown>>();
59+
const sqliteMutationLocks = new KeyedAsyncQueue();
5960

6061
async function withProcessMutationLock<T>(lockPath: string, fn: () => Promise<T>): Promise<T> {
61-
const previous = sqliteMutationLocks.get(lockPath) ?? Promise.resolve();
62-
let release: () => void = () => {};
63-
const next = new Promise<void>((resolve) => {
64-
release = resolve;
65-
});
66-
const chained = previous.then(
67-
() => next,
68-
() => next,
69-
);
70-
sqliteMutationLocks.set(lockPath, chained);
71-
await previous.catch(() => undefined);
72-
try {
73-
return await fn();
74-
} finally {
75-
release();
76-
if (sqliteMutationLocks.get(lockPath) === chained) {
77-
sqliteMutationLocks.delete(lockPath);
78-
}
79-
}
62+
return await sqliteMutationLocks.enqueue(lockPath, fn);
8063
}
8164

8265
export async function withMSTeamsSqliteMutationLock<T>(

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

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

1010
import type { IncomingMessage, ServerResponse } from "node:http";
11+
import { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1112
import {
1213
normalizeLowercaseStringOrEmpty,
1314
normalizeOptionalLowercaseString,
@@ -77,31 +78,10 @@ function checkRateLimit(accountId: string): boolean {
7778
// Mutex for Concurrent Publish Prevention
7879
// ============================================================================
7980

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

8283
async function withPublishLock<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
83-
// Atomic mutex using promise chaining - prevents TOCTOU race condition
84-
const prev = publishLocks.get(accountId) ?? Promise.resolve();
85-
let resolve: () => void;
86-
const next = new Promise<void>((r) => {
87-
resolve = r;
88-
});
89-
// Atomically replace the lock before awaiting - any concurrent request
90-
// will now wait on our `next` promise
91-
publishLocks.set(accountId, next);
92-
93-
// Wait for previous operation to complete
94-
await prev.catch(() => {});
95-
96-
try {
97-
return await fn();
98-
} finally {
99-
resolve!();
100-
// Clean up if we're the last in chain
101-
if (publishLocks.get(accountId) === next) {
102-
publishLocks.delete(accountId);
103-
}
104-
}
84+
return await publishLocks.enqueue(accountId, fn);
10585
}
10686

10787
// ============================================================================

‎extensions/slack/src/send.ts‎

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +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 { KeyedAsyncQueue } from "openclaw/plugin-sdk/keyed-async-queue";
1213
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
1314
import { requireRuntimeConfig } from "openclaw/plugin-sdk/plugin-config-runtime";
1415
import {
@@ -47,7 +48,7 @@ const SLACK_DNS_RETRY_CODES = new Set(["EAI_AGAIN", "ENOTFOUND", "UND_ERR_DNS_RE
4748
const SLACK_DNS_RETRY_ATTEMPTS = 2;
4849
const SLACK_DNS_RETRY_BASE_DELAY_MS = 250;
4950
const slackDmChannelCache = new Map<string, string>();
50-
const slackSendQueues = new Map<string, Promise<void>>();
51+
const slackSendQueue = new KeyedAsyncQueue();
5152

5253
type SlackRecipient =
5354
| {
@@ -488,22 +489,7 @@ function createSlackSendQueueKey(params: {
488489
}
489490

490491
async function runQueuedSlackSend<T>(key: string, task: () => Promise<T>): Promise<T> {
491-
const previous = slackSendQueues.get(key) ?? Promise.resolve();
492-
let releaseCurrent!: () => void;
493-
const current = new Promise<void>((resolve) => {
494-
releaseCurrent = resolve;
495-
});
496-
const queuedCurrent = previous.catch(() => undefined).then(() => current);
497-
slackSendQueues.set(key, queuedCurrent);
498-
await previous.catch(() => undefined);
499-
try {
500-
return await task();
501-
} finally {
502-
releaseCurrent();
503-
if (slackSendQueues.get(key) === queuedCurrent) {
504-
slackSendQueues.delete(key);
505-
}
506-
}
492+
return await slackSendQueue.enqueue(key, task);
507493
}
508494

509495
function createSlackDmCacheKey(params: {
@@ -602,10 +588,6 @@ export function clearSlackDmChannelCache(): void {
602588
slackDmChannelCache.clear();
603589
}
604590

605-
export function clearSlackSendQueuesForTest(): void {
606-
slackSendQueues.clear();
607-
}
608-
609591
export function clearSlackDefaultSendIdentitiesForTest(): void {
610592
slackDefaultSendIdentities.clear();
611593
}

0 commit comments

Comments
 (0)