All files / src/server/repositories/implementations SortResultRepository.ts

100% Statements 36/36
93.75% Branches 15/16
100% Functions 22/22
100% Lines 34/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224                  563x                         376x                           372x                           306x 307x 307x         108x       108x               21x         21x               7x                 7x       373x       373x       25x       25x       10x                       10x             31x                         31x       52x                   52x       14x       14x         11x 11x         11x       16x         16x       8x       14x             12x       577x                                 19x    
import { eq, and, desc, sql } from "drizzle-orm";
import type { Database } from "@/lib/db";
import { sortResultsTable } from "@/lib/db/schema";
import type { SortResult, SortResultStatus } from "@/types";
import { generateId } from "@/lib/id";
import { allocateWithRetry } from "../allocateWithRetry";
import { isUniqueViolation } from "../pg-conflict";
 
export class SortResultRepository {
  constructor(private db: Database) {}
 
  // Single INSERT with a caller-supplied number; NO recompute, NO retry. The
  // number race is handled by callers (create's wrapper, or the service's
  // whole-transaction retry) so the two retry sites share one predicate.
  async insertWithNumber(data: {
    id?: string;
    collectionId: string;
    curatorId: string;
    name: string;
    status: "draft" | "finalized";
    number: number;
  }): Promise<SortResult> {
    const [result] = await this.db
      .insert(sortResultsTable)
      .values({
        id: data.id || generateId("result"),
        collectionId: data.collectionId,
        curatorId: data.curatorId,
        name: data.name,
        status: data.status,
        number: data.number,
        createdAt: new Date(),
        updatedAt: new Date(),
        finalizedAt: null,
      })
      .returning();
    return this.mapToResult(result);
  }
 
  async create(data: {
    id?: string;
    collectionId: string;
    curatorId: string;
    name: string;
    status: "draft" | "finalized";
  }): Promise<SortResult> {
    // Auto-allocate MAX+1, recomputing the number EACH attempt, retrying only
    // on the UNIQUE(collection_id, number) race. postgres-js autocommits each
    // statement here, so a conflicting INSERT can be retried in place. Any
    // other unique violation surfaces, not retried.
    return allocateWithRetry(async () => {
      const number = await this.getNextResultNumber(data.collectionId);
      return this.insertWithNumber({ ...data, number });
    }, isResultNumberConflict);
  }
 
  async findById(id: string): Promise<SortResult | null> {
    const [result] = await this.db
      .select()
      .from(sortResultsTable)
      .where(eq(sortResultsTable.id, id));
    return result ? this.mapToResult(result) : null;
  }
 
  // Read + row-lock (SELECT ... FOR UPDATE) so a concurrent finalize and a
  // re-rank/reset serialize on the sort_results row. MUST be called inside a
  // transaction (the lock is held until commit); use to re-assert draft status
  // in the same tx as the manual-overlay write (finalized-immutability TOCTOU).
  async findByIdForUpdate(id: string): Promise<SortResult | null> {
    const [result] = await this.db
      .select()
      .from(sortResultsTable)
      .where(eq(sortResultsTable.id, id))
      .for("update");
    return result ? this.mapToResult(result) : null;
  }
 
  async findByCollectionAndNumber(
    collectionId: string,
    number: number,
  ): Promise<SortResult | null> {
    // sort_results has no deletedAt — filter only by collectionId + number
    const [result] = await this.db
      .select()
      .from(sortResultsTable)
      .where(
        and(
          eq(sortResultsTable.collectionId, collectionId),
          eq(sortResultsTable.number, number),
        ),
      );
    return result ? this.mapToResult(result) : null;
  }
 
  async getNextResultNumber(collectionId: string): Promise<number> {
    const [row] = await this.db
      .select({ max: sql<number | null>`max(${sortResultsTable.number})` })
      .from(sortResultsTable)
      .where(eq(sortResultsTable.collectionId, collectionId));
    return (row?.max ?? 0) + 1;
  }
 
  async findByCollection(collectionId: string): Promise<SortResult[]> {
    const results = await this.db
      .select()
      .from(sortResultsTable)
      .where(eq(sortResultsTable.collectionId, collectionId));
    return results.map((r) => this.mapToResult(r));
  }
 
  async findDraft(collectionId: string, curatorId: string): Promise<SortResult | null> {
    const [result] = await this.db
      .select()
      .from(sortResultsTable)
      .where(
        and(
          eq(sortResultsTable.collectionId, collectionId),
          eq(sortResultsTable.curatorId, curatorId),
          eq(sortResultsTable.status, "draft"),
        ),
      )
      .orderBy(desc(sortResultsTable.createdAt), desc(sortResultsTable.id))
      .limit(1);
    return result ? this.mapToResult(result) : null;
  }
 
  // The curator's open draft for the collection, row-locked. Callers hold the
  // (collection, curator) advisory lock, so this is the only draft writer at a time.
  // Newest first, so the pick is deterministic.
  async findDraftForUpdate(collectionId: string, curatorId: string): Promise<SortResult | null> {
    const [row] = await this.db
      .select()
      .from(sortResultsTable)
      .where(
        and(
          eq(sortResultsTable.collectionId, collectionId),
          eq(sortResultsTable.curatorId, curatorId),
          eq(sortResultsTable.status, "draft"),
        ),
      )
      .orderBy(desc(sortResultsTable.createdAt), desc(sortResultsTable.id))
      .limit(1)
      .for("update");
    return row ? this.mapToResult(row) : null;
  }
 
  async findDrafts(collectionId: string, curatorId: string): Promise<SortResult[]> {
    const rows = await this.db
      .select()
      .from(sortResultsTable)
      .where(
        and(
          eq(sortResultsTable.collectionId, collectionId),
          eq(sortResultsTable.curatorId, curatorId),
          eq(sortResultsTable.status, "draft"),
        ),
      );
    return rows.map((r) => this.mapToResult(r));
  }
 
  async findBySaveKey(curatorId: string, saveKey: string): Promise<SortResult | null> {
    const [row] = await this.db
      .select()
      .from(sortResultsTable)
      .where(and(eq(sortResultsTable.curatorId, curatorId), eq(sortResultsTable.saveKey, saveKey)));
    return row ? this.mapToResult(row) : null;
  }
 
  // Save-and-share's finalize: name, status, timestamp and the idempotency key in one write.
  async markSaved(id: string, name: string, saveKey: string): Promise<SortResult> {
    const now = new Date();
    const [row] = await this.db
      .update(sortResultsTable)
      .set({ name, saveKey, status: "finalized", finalizedAt: now, updatedAt: now })
      .where(eq(sortResultsTable.id, id))
      .returning();
    return this.mapToResult(row);
  }
 
  async update(id: string, data: Partial<SortResult>): Promise<SortResult> {
    const [result] = await this.db
      .update(sortResultsTable)
      .set({ ...data, updatedAt: new Date() })
      .where(eq(sortResultsTable.id, id))
      .returning();
    return this.mapToResult(result);
  }
 
  async delete(id: string): Promise<void> {
    await this.db.delete(sortResultsTable).where(eq(sortResultsTable.id, id));
  }
 
  async deleteByCollection(collectionId: string): Promise<void> {
    await this.db.delete(sortResultsTable).where(eq(sortResultsTable.collectionId, collectionId));
  }
 
  // Delete every sort_result belonging to the given curator (across all collections).
  // Caller must have already deleted child sort_result_shares and sort_result_items.
  // Account-deletion only.
  async deleteByCurator(curatorId: string): Promise<void> {
    await this.db.delete(sortResultsTable).where(eq(sortResultsTable.curatorId, curatorId));
  }
 
  private mapToResult(row: typeof sortResultsTable.$inferSelect): SortResult {
    return {
      id: row.id,
      collectionId: row.collectionId,
      curatorId: row.curatorId,
      number: row.number,
      status: row.status as SortResultStatus,
      name: row.name,
      createdAt: row.createdAt,
      updatedAt: row.updatedAt,
      finalizedAt: row.finalizedAt,
    };
  }
}
 
export function isResultNumberConflict(error: unknown): boolean {
  // Retry ONLY the UNIQUE(collection_id, number) race — any other unique
  // violation is a real condition and must surface.
  return isUniqueViolation(error, "sort_results_collection_number_unique");
}