39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
type CanvasCapabilityQueueState = {
|
|
tails: Map<string, Promise<unknown>>;
|
|
};
|
|
|
|
declare global {
|
|
var __canvasCapabilityQueueState: CanvasCapabilityQueueState | undefined;
|
|
}
|
|
|
|
function getQueueState() {
|
|
if (!globalThis.__canvasCapabilityQueueState) {
|
|
globalThis.__canvasCapabilityQueueState = { tails: new Map() };
|
|
}
|
|
return globalThis.__canvasCapabilityQueueState;
|
|
}
|
|
|
|
export async function enqueueCanvasCapabilityExecution<T>(params: {
|
|
projectId: string;
|
|
execute: () => Promise<T>;
|
|
}): Promise<T> {
|
|
const state = getQueueState();
|
|
const previous = state.tails.get(params.projectId) || Promise.resolve();
|
|
const execution = previous.catch(() => undefined).then(params.execute);
|
|
const settledExecution = execution.then(
|
|
() => undefined,
|
|
() => undefined
|
|
);
|
|
const tail = settledExecution.finally(() => {
|
|
if (state.tails.get(params.projectId) === tail) {
|
|
state.tails.delete(params.projectId);
|
|
}
|
|
});
|
|
state.tails.set(params.projectId, tail);
|
|
return execution;
|
|
}
|
|
|
|
export function getCanvasCapabilityQueueDepth(projectId: string) {
|
|
return getQueueState().tails.has(projectId) ? 1 : 0;
|
|
}
|