Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

3.1 KB
Raw Blame
import type { PrismaClient } from '@prisma/client'
import { logger } from '../../utils/logger.js'

/** Mongo's "not authorized" (code 13), as Prisma's raw command error carries it. */
export const notAuthorized = (error: unknown): boolean => /not authorized|Unauthorized|Code: `13`/.test(String((error as Error)?.message ?? error))

/** One index as `createIndexes` takes it. */
export type IndexSpec = { name: string; key: Record<string, number>; unique?: boolean; expireAfterSeconds?: number }

async function listIndexes(db: Pick<PrismaClient, '$runCommandRaw'>, collection: string): Promise<IndexSpec[]> {
  try {
    const answer = await db.$runCommandRaw({ listIndexes: collection, cursor: {} }) as { cursor?: { firstBatch?: IndexSpec[] } }
    return answer.cursor?.firstBatch ?? []
  } catch {
    // A collection that does not exist yet has no indexes; createIndexes creates it, and reports any real failure.
    return []
  }
}

/** What [ensureIndex] left: the index as asked, or the index without the expiry the database user may not set. */
export type IndexOutcome = 'ready' | 'expiry-refused'

const sameKey = (a: Record<string, number>, b: Record<string, number>) => JSON.stringify(Object.entries(a)) === JSON.stringify(Object.entries(b))

/**
 * Makes sure `collection` has `index`, and changes nothing when it already does. A build, a drop or an option change locks
 * the collection exclusively for a moment, and a Swarm read's transaction waits at most 5 ms for its lock (the 10-28 release);
 * listing the indexes takes no lock that reads or writes wait for. An index Prisma declares without expiry (db push builds it
 * so on a new database) gets its expiry with collMod, without a rebuild. Any other difference fails in createIndexes, as before.
 * It answers 'expiry-refused' when the database user may not run that collMod, so the caller can remove what the expiry would.
 */
export async function ensureIndex(db: Pick<PrismaClient, '$runCommandRaw'>, collection: string, index: IndexSpec): Promise<IndexOutcome> {
  const found = (await listIndexes(db, collection)).find(existing => existing.name === index.name)
  if (found && sameKey(found.key, index.key) && !!found.unique === !!index.unique) {
    if (found.expireAfterSeconds === index.expireAfterSeconds) return 'ready'
    if (index.expireAfterSeconds !== undefined) {
      try {
        await db.$runCommandRaw({ collMod: collection, index: { name: index.name, expireAfterSeconds: index.expireAfterSeconds } })
      } catch (error) {
        // Production's app user may not run collMod (10-29: the worker crash-looped on the read-mark expiry). The index
        // exists and serves reads; only its expiry waits for someone with the right to set it, so warn and carry on.
        if (!notAuthorized(error)) throw error
        logger.warn('index expiry not set: the database user may not run collMod', { collection, index: index.name, expireAfterSeconds: index.expireAfterSeconds })
        return 'expiry-refused'
      }
      return 'ready'
    }
  }
  await db.$runCommandRaw({ createIndexes: collection, indexes: [index] })
  return 'ready'
}