Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

1.9 KB
Raw Blame
// Covers the gap before a member turn marks the bot busy: woken waiters must claim in the same synchronous step, or all read the bot as free.
// One bot may hold several room threads at once; the caller decides how many with its thread limit.

export type RoomMemberReleaseListener = (botId: string) => void;

export class RoomMemberLock {
  private readonly holders = new Map<string, Set<string>>();
  private readonly listeners = new Set<RoomMemberReleaseListener>();

  threads(botId: string): string[] {
    return [...(this.holders.get(botId) ?? [])];
  }

  heldElsewhere(botId: string, threadId: string): boolean {
    return this.threads(botId).some((holder) => holder !== threadId);
  }

  claim(botId: string, threadId: string): void {
    const threads = this.holders.get(botId) ?? new Set<string>();
    threads.add(threadId);
    this.holders.set(botId, threads);
  }

  release(botId: string, threadId: string): boolean {
    const threads = this.holders.get(botId);
    if (!threads?.delete(threadId)) return false;
    if (!threads.size) this.holders.delete(botId);
    this.notify(botId);
    return true;
  }

  releaseThread(threadId: string): string[] {
    const released: string[] = [];
    for (const [botId, threads] of this.holders) {
      if (!threads.delete(threadId)) continue;
      released.push(botId);
      if (!threads.size) this.holders.delete(botId);
    }
    for (const botId of released) this.notify(botId);
    return released;
  }

  onRelease(listener: RoomMemberReleaseListener): () => void {
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }

  private notify(botId: string): void {
    // A snapshot: a woken waiter may unsubscribe, or a new one subscribe, during this loop.
    // oxlint-disable-next-line unicorn/no-useless-spread
    for (const listener of [...this.listeners]) {
      try {
        listener(botId);
      } catch {
      }
    }
  }
}