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.

3.1 KB
Raw Blame
import type { TopicModel } from '@/database/models/topic';

const INITIAL_RETRY_DELAY_MS = 100;
const MAX_RETRY_DELAY_MS = 1600;
const MAX_RESERVATION_ATTEMPTS = 6;

const delay = (milliseconds: number): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, milliseconds));

/**
 * The topic could not be reserved for a new run. Thrown before anything of the
 * run is written β€” no user message, no operation β€” so a caller that sees it
 * knows the dispatch never started and never will. The message is unchanged
 * for callers that still match on it.
 */
export class TopicStartReservationError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'TopicStartReservationError';
  }
}

/**
 * An interactive send found the topic driven by another member's live
 * foreground run. A send only ever retires its own sender's runs, so the
 * start is refused β€” before anything is written, like
 * {@link TopicStartReservationError} β€” instead of interrupting a teammate.
 */
export class ForeignLiveRunError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ForeignLiveRunError';
  }
}

/**
 * Claim the gap between choosing a conversation parent and publishing the
 * operation's `runningOperation` marker. Every existing-topic start uses the
 * same claim, so a foreground message and a task callback cannot both observe
 * the topic as idle and create competing continuations.
 *
 * The bounded backoff deliberately throws instead of holding a workflow
 * request indefinitely; QStash retries callback deliveries on the resulting 500
 * response. Interactive sends pass `ignoreRunningOperation` so they contend
 * only for the short reservation and practically never reach that throw β€” a
 * busy failure there is indistinguishable from the message being swallowed,
 * since the gate runs before the user message is persisted.
 */
export const acquireTopicStartReservation = async ({
  allowRunningOperationId,
  allowSameReservationReentry,
  ignoreRunningOperation,
  replacesOperationId,
  reservationId,
  topicId,
  topicModel,
}: {
  allowRunningOperationId?: string;
  allowSameReservationReentry?: boolean;
  /**
   * Serialize only on the short reservation, not on `runningOperation`. Set by
   * interactive sends β€” see `TopicModel.tryReserveTaskCallback`.
   */
  ignoreRunningOperation?: boolean;
  replacesOperationId?: string;
  reservationId: string;
  topicId: string;
  topicModel: TopicModel;
}): Promise<boolean> => {
  for (let attempt = 0; attempt < MAX_RESERVATION_ATTEMPTS; attempt += 1) {
    const reservation = await topicModel.tryReserveTaskCallback(topicId, reservationId, {
      allowRunningOperationId,
      allowSameReservationReentry,
      ignoreRunningOperation,
      replacesOperationId,
    });

    if (reservation === null) return false;
    if (reservation) return true;

    if (attempt < MAX_RESERVATION_ATTEMPTS - 1) {
      const retryDelay = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);
      await delay(retryDelay);
    }
  }

  throw new TopicStartReservationError(
    `Topic ${topicId} remained busy while starting operation ${reservationId}`,
  );
};