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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | 7x 7x 624x 269x 269x 270x 270x 270x 265x 5x 1x 140x 140x 16x 16x 3x 3x 270x 270x 1x 1x 34x 34x 10x 10x 133x 133x 27x 27x 25x 2x 12x 12x 3x 3x 3x 14x 11x 562x 5x 7x | import { eq, and, isNull, inArray, sql } from "drizzle-orm";
import type { Database } from "@/lib/db";
import { sessionsTable } from "@/lib/db/schema";
import type { Session, SessionStatus } from "@/types";
import { generateId } from "@/lib/id";
import { allocateWithRetry } from "../allocateWithRetry";
import { isUniqueViolation } from "../pg-conflict";
/**
* Thrown when a curator already holds an IN-PROGRESS session in a (collection,
* curator) slot and tries to occupy it again. After migration 0009 the
* sessions_active_unique index is PARTIAL — it covers only in-progress rows
* (deleted_at IS NULL AND status IN ('active','paused')). Terminal (completed/
* abandoned) and soft-deleted (set-aside) rows no longer hold the slot, so they
* don't collide. This fires on create into an occupied slot AND on restore that
* would re-activate a set-aside session a newer one has since superseded. Routes
* map it to a gentle 409 — never a 500.
*/
export class CurrentSessionExistsError extends Error {
constructor() {
super("You already have a sort in progress for this collection.");
this.name = "CurrentSessionExistsError";
}
}
export class SessionRepository {
constructor(private db: Database) {}
async create(data: {
id?: string;
collectionId: string;
curatorId: string;
goal?: string;
}): Promise<Session> {
const base = {
id: data.id || generateId("sess"),
collectionId: data.collectionId,
curatorId: data.curatorId,
status: "active",
goal: data.goal || null,
createdAt: new Date(),
updatedAt: new Date(),
deletedAt: null,
};
// Auto-allocate MAX+1, retry on the UNIQUE(collection_id, number) race
// (a retry-able insert — simpler than locking the max; a transaction is available but unnecessary here).
return allocateWithRetry(async () => {
const number = await this.getNextSessionNumber(data.collectionId);
try {
const [session] = await this.db
.insert(sessionsTable)
.values({ ...base, number })
.returning();
return this.mapToSession(session);
} catch (error) {
// The (collection, curator) slot is held by an IN-PROGRESS session
// (active or paused, not soft-deleted) — the only rows the partial
// sessions_active_unique index covers after migration 0009. Terminal
// and soft-deleted rows free the slot and don't collide. Surface a
// gentle, typed 409 instead of a raw 500. Not retried — a fresh number
// won't free a slot held by the curator's live session (and the retry
// predicate below matches only the number conflict, so it propagates).
if (isCurrentSessionConflict(error)) throw new CurrentSessionExistsError();
throw error;
}
}, isSessionNumberConflict);
}
async findById(id: string): Promise<Session | null> {
const [session] = await this.db
.select()
.from(sessionsTable)
.where(and(eq(sessionsTable.id, id), isNull(sessionsTable.deletedAt)));
return session ? this.mapToSession(session) : null;
}
async findByIdIncludingDeleted(id: string): Promise<Session | null> {
const [session] = await this.db
.select()
.from(sessionsTable)
.where(eq(sessionsTable.id, id));
return session ? this.mapToSession(session) : null;
}
async findByCollectionAndNumber(
collectionId: string,
number: number,
): Promise<Session | null> {
const [session] = await this.db
.select()
.from(sessionsTable)
.where(
and(
eq(sessionsTable.collectionId, collectionId),
eq(sessionsTable.number, number),
isNull(sessionsTable.deletedAt),
),
);
return session ? this.mapToSession(session) : null;
}
async getNextSessionNumber(collectionId: string): Promise<number> {
// MAX over ALL rows (incl. soft-deleted) — a deleted session still holds its
// number in the UNIQUE(collection_id, number) index, so reusing it would
// collide. Resolution (findByCollectionAndNumber) excludes deleted rows.
const [row] = await this.db
.select({ max: sql<number | null>`max(${sessionsTable.number})` })
.from(sessionsTable)
.where(eq(sessionsTable.collectionId, collectionId));
return (row?.max ?? 0) + 1;
}
async findActive(collectionId: string, curatorId: string): Promise<Session | null> {
const [session] = await this.db
.select()
.from(sessionsTable)
.where(
and(
eq(sessionsTable.collectionId, collectionId),
eq(sessionsTable.curatorId, curatorId),
eq(sessionsTable.status, "active"),
isNull(sessionsTable.deletedAt),
),
);
return session ? this.mapToSession(session) : null;
}
// The in-progress session (active OR paused, not soft-deleted) holding the
// partial-index slot — mirrors findActive but widens status to match the
// partial predicate so restore's pre-check sees a paused holder too.
async findInProgress(collectionId: string, curatorId: string): Promise<Session | null> {
const [session] = await this.db
.select()
.from(sessionsTable)
.where(
and(
eq(sessionsTable.collectionId, collectionId),
eq(sessionsTable.curatorId, curatorId),
inArray(sessionsTable.status, ["active", "paused"]),
isNull(sessionsTable.deletedAt),
),
);
return session ? this.mapToSession(session) : null;
}
async findByCollection(collectionId: string): Promise<Session[]> {
const sessions = await this.db
.select()
.from(sessionsTable)
.where(and(eq(sessionsTable.collectionId, collectionId), isNull(sessionsTable.deletedAt)));
return sessions.map((s) => this.mapToSession(s));
}
// purses-t9l: each user sorts independently — the sort list/dashboard show only
// the current user's own sessions, never another curator's.
async findByCollectionAndCurator(
collectionId: string,
curatorId: string,
): Promise<Session[]> {
const sessions = await this.db
.select()
.from(sessionsTable)
.where(
and(
eq(sessionsTable.collectionId, collectionId),
eq(sessionsTable.curatorId, curatorId),
isNull(sessionsTable.deletedAt),
),
);
return sessions.map((s) => this.mapToSession(s));
}
async update(id: string, data: Partial<Session>): Promise<Session> {
try {
const [session] = await this.db
.update(sessionsTable)
.set({ ...data, updatedAt: new Date() })
.where(eq(sessionsTable.id, id))
.returning();
return this.mapToSession(session);
} catch (error) {
// The THIRD in-progress writer. A terminal→in-progress transition
// (e.g. PATCH a completed session back to active/paused) re-enters the
// partial sessions_active_unique predicate; if a newer in-progress
// session already holds the slot, the partial index raises 23505. Surface
// the gentle, typed 409 — mirrors create()/restore() — never a raw 500.
Eif (isCurrentSessionConflict(error)) throw new CurrentSessionExistsError();
throw error;
}
}
async softDelete(id: string): Promise<Session> {
const [session] = await this.db
.update(sessionsTable)
.set({ deletedAt: new Date(), updatedAt: new Date() })
.where(eq(sessionsTable.id, id))
.returning();
return this.mapToSession(session);
}
async restore(id: string): Promise<Session> {
try {
const [session] = await this.db
.update(sessionsTable)
.set({ deletedAt: null, status: "active", updatedAt: new Date() })
.where(eq(sessionsTable.id, id))
.returning();
return this.mapToSession(session);
} catch (error) {
// The partial index now lets a set-aside session be superseded: a newer
// in-progress session can occupy the slot while this one is soft-deleted.
// Re-activating this row would put TWO in-progress sessions in the slot,
// so the partial unique index raises 23505. Surface a gentle 409, not a
// raw 500. Mirrors create()'s conflict handling.
if (isCurrentSessionConflict(error)) throw new CurrentSessionExistsError();
throw error;
}
}
async deleteByCollection(collectionId: string): Promise<void> {
await this.db.delete(sessionsTable).where(eq(sessionsTable.collectionId, collectionId));
}
// Delete every session belonging to the given curator (across all collections).
// Caller must have already deleted child decision_events. Account-deletion only.
async deleteByCurator(curatorId: string): Promise<void> {
await this.db.delete(sessionsTable).where(eq(sessionsTable.curatorId, curatorId));
}
private mapToSession(row: typeof sessionsTable.$inferSelect): Session {
return {
id: row.id,
collectionId: row.collectionId,
curatorId: row.curatorId,
number: row.number,
status: row.status as SessionStatus,
goal: row.goal,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
};
}
}
function isSessionNumberConflict(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, "sessions_collection_number_unique");
}
function isCurrentSessionConflict(error: unknown): boolean {
// The UNIQUE(collection_id, curator_id) slot is occupied. Sibling of
// isSessionNumberConflict — NOT retried; mapped to a gentle 409.
return isUniqueViolation(error, "sessions_active_unique");
}
|