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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 29x 29x 1x 24x 24x 24x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 1x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 34x 34x 34x 34x 34x 34x 34x 34x 23x 34x 1x 5x 5x 5x 5x 5x 5x 5x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 2x 2x 24x 24x 26x 2x 2x 26x 26x 26x 22x 22x 22x 22x 22x 22x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 15x 15x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 5x 1x 1x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 1x 5x 5x 5x 5x 5x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | import { createHash } from "node:crypto";
import { RestError } from "@azure/data-tables";
import type {
Arrangement,
JobStatus,
SavedJobAnalysis,
SavedJobEntity,
SavedJobPatchBody,
SavedJobPayload,
Tier,
} from "../models/user";
import { SAVED_JOBS_CAP, SAVED_JOBS_SOFT_CAP } from "../models/user";
import {
decodeJsonProperty,
encodeJsonProperty,
ensureTable,
nowIso,
} from "./tablesService";
export { SAVED_JOBS_SOFT_CAP };
/**
* SavedJobs table CRUD (data-model.md): PK = Google sub, RK = server-computed
* sha256(canonicalUrl) — identical to the client's canonicalKey() digest, and
* recomputed here so a client cannot plant mismatched keys (research.md R3).
* Upserts are last-write-wins per record (spec concurrency edge case).
*/
const TABLE = "SavedJobs";
/**
* The partition is at its tier cap and the save would create a new row
* (data-model.md "Saved-jobs over-cap rule" — only new rows are blocked;
* a downgraded over-cap library stays read-only-for-additions, never
* truncated).
*/
export class LibraryCapError extends Error {
constructor(cap: number) {
super(`Library is at the ${cap.toLocaleString()}-posting cap.`);
}
}
/** `{key}` in the URL does not equal sha256(body.canonicalUrl). */
export class KeyMismatchError extends Error {
constructor() {
super("The job key does not match the canonical URL.");
}
}
/** PATCH tried to change an immutable field (canonicalUrl, savedAt). */
export class ImmutableFieldError extends Error {
constructor(field: string) {
super(`${field} is immutable.`);
}
}
export interface JobListFilter {
arrangement?: Arrangement;
status?: JobStatus;
}
export interface JobsExport {
schemaVersion: 1;
exportedAt: string;
jobs: SavedJobPayload[];
}
export function sha256Hex(input: string): string {
return createHash("sha256").update(input).digest("hex");
}
function isNotFound(err: unknown): boolean {
return err instanceof RestError && err.statusCode === 404;
}
function entityFromPayload(
sub: string,
key: string,
payload: SavedJobPayload,
savedAt: string,
updatedAt: string
): SavedJobEntity {
return {
partitionKey: sub,
rowKey: key,
canonicalUrl: payload.canonicalUrl,
sourceUrl: payload.sourceUrl,
title: payload.analysis.title ?? "",
company: payload.analysis.company ?? "",
arrangement: payload.analysis.arrangement,
status: payload.status,
notes: payload.notes,
analysisJson: encodeJsonProperty(payload.analysis),
savedAt,
updatedAt,
schemaVersion: payload.schemaVersion,
// Defensive default: callers that construct a payload without going
// through isSavedJobPutBody (internal tests, PATCH's echo path) still
// persist a valid discriminator (data-model.md §2.3).
source: payload.source ?? "url",
filename: payload.filename ?? "",
};
}
function payloadFromEntity(entity: SavedJobEntity): SavedJobPayload {
return {
schemaVersion: entity.schemaVersion,
canonicalUrl: entity.canonicalUrl,
sourceUrl: entity.sourceUrl,
// Back-compat: rows written before 004 have no source/filename columns
// at all (data-model.md §2.3) — default rather than surface undefined.
source: (entity.source as SavedJobPayload["source"]) ?? "url",
filename: entity.filename ?? "",
analysis: decodeJsonProperty<SavedJobAnalysis>(
entity.analysisJson,
{} as SavedJobAnalysis
),
status: entity.status as JobStatus,
notes: entity.notes,
savedAt: entity.savedAt,
updatedAt: entity.updatedAt,
};
}
async function getEntityOrNull(
sub: string,
key: string
): Promise<SavedJobEntity | null> {
const client = await ensureTable(TABLE);
try {
return await client.getEntity<SavedJobEntity>(sub, key);
} catch (err) {
if (isNotFound(err)) return null;
throw err;
}
}
export async function getJob(
sub: string,
key: string
): Promise<SavedJobPayload | null> {
const entity = await getEntityOrNull(sub, key);
return entity ? payloadFromEntity(entity) : null;
}
export async function countJobs(sub: string): Promise<number> {
const client = await ensureTable(TABLE);
let count = 0;
const rows = client.listEntities<SavedJobEntity>({
queryOptions: {
filter: `PartitionKey eq '${sub.replace(/'/g, "''")}'`,
select: ["rowKey"],
},
});
for await (const _row of rows) count++;
return count;
}
/**
* Create or full replace (LWW). Preserves the stored savedAt on replace and
* always sets updatedAt server-side. A new row beyond the tier's cap throws
* LibraryCapError; replaces are always allowed (contract PUT semantics) —
* a downgraded, over-cap library stays read-only-for-additions rather than
* losing data (data-model.md R7).
*/
export async function saveJob(
sub: string,
key: string,
payload: SavedJobPayload,
tier: Tier = "free"
): Promise<SavedJobPayload> {
if (sha256Hex(payload.canonicalUrl) !== key) {
throw new KeyMismatchError();
}
const cap = SAVED_JOBS_CAP[tier];
const existing = await getEntityOrNull(sub, key);
if (!existing && (await countJobs(sub)) >= cap) {
throw new LibraryCapError(cap);
}
const savedAt = existing ? existing.savedAt : payload.savedAt;
const updatedAt = nowIso();
const client = await ensureTable(TABLE);
await client.upsertEntity(
entityFromPayload(sub, key, payload, savedAt, updatedAt),
"Replace"
);
return { ...payload, savedAt, updatedAt };
}
export async function listJobs(
sub: string,
filter: JobListFilter
): Promise<SavedJobPayload[]> {
const client = await ensureTable(TABLE);
const clauses = [`PartitionKey eq '${sub.replace(/'/g, "''")}'`];
if (filter.arrangement) clauses.push(`arrangement eq '${filter.arrangement}'`);
if (filter.status) clauses.push(`status eq '${filter.status}'`);
const rows = client.listEntities<SavedJobEntity>({
queryOptions: { filter: clauses.join(" and ") },
});
const jobs: SavedJobPayload[] = [];
for await (const row of rows) {
jobs.push(payloadFromEntity(row));
}
// Table Storage has no server-side sort; per-user partitions are ≤ 1,000
// rows, so sorting in the handler is trivial (plan.md Risks).
jobs.sort((a, b) => Date.parse(b.savedAt) - Date.parse(a.savedAt));
return jobs;
}
/**
* Partial update of status/notes/analysis. Returns null when the record does
* not exist. canonicalUrl and savedAt are immutable: echoing the stored value
* back is tolerated, changing it throws ImmutableFieldError.
*/
export async function patchJob(
sub: string,
key: string,
patch: SavedJobPatchBody
): Promise<SavedJobPayload | null> {
const existing = await getEntityOrNull(sub, key);
if (!existing) return null;
if (patch.canonicalUrl !== undefined && patch.canonicalUrl !== existing.canonicalUrl) {
throw new ImmutableFieldError("canonicalUrl");
}
if (patch.savedAt !== undefined && patch.savedAt !== existing.savedAt) {
throw new ImmutableFieldError("savedAt");
}
const current = payloadFromEntity(existing);
const updated: SavedJobPayload = {
...current,
...(patch.status !== undefined ? { status: patch.status } : {}),
...(patch.notes !== undefined ? { notes: patch.notes } : {}),
...(patch.analysis !== undefined ? { analysis: patch.analysis } : {}),
canonicalUrl: current.canonicalUrl,
savedAt: current.savedAt,
updatedAt: nowIso(),
};
const client = await ensureTable(TABLE);
await client.upsertEntity(
entityFromPayload(sub, key, updated, updated.savedAt, updated.updatedAt),
"Replace"
);
return updated;
}
export async function deleteJob(sub: string, key: string): Promise<void> {
const client = await ensureTable(TABLE);
try {
await client.deleteEntity(sub, key);
} catch (err) {
if (isNotFound(err)) return;
throw err;
}
}
export async function exportJobs(sub: string): Promise<JobsExport> {
return {
schemaVersion: 1,
exportedAt: nowIso(),
jobs: await listJobs(sub, {}),
};
}
/** Deletes the user's oldest-savedAt archived rows, up to count. */
export async function pruneArchived(sub: string, count: number): Promise<number> {
const archived = await listJobs(sub, { status: "archived" });
const oldestFirst = [...archived].sort(
(a, b) => Date.parse(a.savedAt) - Date.parse(b.savedAt)
);
const victims = oldestFirst.slice(0, count);
for (const job of victims) {
await deleteJob(sub, sha256Hex(job.canonicalUrl));
}
return victims.length;
}
|