Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/src/lib/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type ErrorCode =
| "FORBIDDEN"
| "NOT_FOUND"
| "CONFLICT"
| "SEARCH_CATALOG_UNAVAILABLE"
| "INTERNAL_ERROR";

export type ErrorDetails = Record<string, unknown>;
Expand Down
142 changes: 68 additions & 74 deletions backend/src/modules/jobs/cache/jobSearchCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ import {
import { jobSearchCacheKey } from "./jobSearchFingerprint";
import type { PaginationParams } from "../../../lib/pagination";
import type { ParsedJobSearchQuery } from "../types/jobSearch.types";
import { AppError } from "../../../lib/errors";

class GenerationChanged extends Error {
constructor(readonly reason = "generation_changed") { super(reason); }
}

function unavailable(reason: string): AppError {
return new AppError("SEARCH_CATALOG_UNAVAILABLE", "Catálogo de vagas temporariamente indisponível. Tente novamente.", 503, { reason });
}

export type SearchPage = { jobs: unknown[]; total: number };
export interface SearchCacheStore {
Expand All @@ -21,7 +30,7 @@ export interface SearchCacheStore {

/** Local single-flight combines simultaneous identical queries without reusing
* the scraper execution lock. Failures never remain in the in-flight map.
* Cache lookup/publication failures degrade to the normal repository query.
* Page-cache failures may degrade to a query; catalog fences must remain valid.
*/
export class JobSearchCache {
private readonly inFlight = new Map<string, Promise<SearchPage>>();
Expand All @@ -43,85 +52,70 @@ export class JobSearchCache {
rankingContext: unknown,
query: () => Promise<SearchPage>,
): Promise<SearchPage> {
let generation: string | null;
let outcome: "hit" | "miss" | "stale" | "error" = "miss";
try {
const end = searchCacheDuration.startTimer({ operation: "get" });
try {
generation = await this.store.generation();
} finally {
end();
}
} catch {
searchCacheRequests.inc({ result: "error" });
return query();
}
// null means indexes are unavailable or being rebuilt; do not cache.
if (generation === null) {
searchCacheRequests.inc({ result: "stale" });
return query();
}
const key = jobSearchCacheKey(
filters,
pagination,
generation,
rankingContext,
);
const existing = this.inFlight.get(key);
if (existing) {
searchCacheRequests.inc({ result: "hit" });
return structuredClone(await existing);
}

const pending = (async () => {
let outcome: "hit" | "miss" | "stale" | "error" = "miss";
try {
try {
const end = searchCacheDuration.startTimer({ operation: "get" });
let cached;
let current;
try {
cached = await this.store.read(key);
current = await this.store.generation();
} finally {
end();
}
if (cached && current === generation) {
outcome = "hit";
return cached;
}
outcome = cached ? "stale" : "miss";
} catch {
outcome = "error";
// A cache outage must not hide a successful persistence query.
// At most one reconstruction, shared under each generation's fingerprint.
for (let attempt = 0; attempt < 2; attempt++) {
const generation = await this.readGeneration();
const key = jobSearchCacheKey(filters, pagination, generation, rankingContext);
let pending = this.inFlight.get(key);
if (pending) outcome = "hit";
else {
pending = (async () => {
let cached: SearchPage | null = null;
const getEnd = searchCacheDuration.startTimer({ operation: "get" });
try { cached = await this.store.read(key); }
catch { outcome = "error"; }
finally { getEnd(); }
if (cached) { outcome = "hit"; return cached; }
await this.requireGeneration(generation);
const page = await query();
await this.requireGeneration(generation);
let published: boolean | undefined;
const setEnd = searchCacheDuration.startTimer({ operation: "set" });
try {
published = await this.store.writeIfGeneration(key, page, generation, this.ttlSeconds);
} catch { outcome = "error"; }
finally { setEnd(); }
if (published === false) throw new GenerationChanged("publication_rejected");
return page;
})();
this.inFlight.set(key, pending);
}
const page = await query();
try {
const end = searchCacheDuration.startTimer({ operation: "set" });
try {
const published = await this.store.writeIfGeneration(
key,
page,
generation,
this.ttlSeconds,
);
if (!published && outcome !== "error") outcome = "stale";
} finally {
end();
}
} catch {
outcome = "error";
// The query remains useful; the next request can repopulate the cache.
const page = structuredClone(await pending);
// Also fences hits, shared results and changes during publication.
await this.requireGeneration(generation);
return page;
} catch (error) {
if (!(error instanceof GenerationChanged)) throw error;
outcome = "stale";
if (attempt === 1) throw unavailable(error.reason);
} finally {
if (this.inFlight.get(key) === pending) this.inFlight.delete(key);
}
return page;
} finally {
searchCacheRequests.inc({ result: outcome });
}
})();
this.inFlight.set(key, pending);
try {
return structuredClone(await pending);
throw unavailable("generation_changed");
} catch (error) {
if (error instanceof AppError && error.details?.reason === "catalog_unavailable") outcome = "stale";
else if (!(error instanceof AppError && ["generation_changed", "publication_rejected"].includes(String(error.details?.reason)))) outcome = "error";
throw error;
} finally {
this.inFlight.delete(key);
searchCacheRequests.inc({ result: outcome });
}
}

private async readGeneration(): Promise<string> {
const end = searchCacheDuration.startTimer({ operation: "get" });
let generation: string | null;
try { generation = await this.store.generation(); }
catch { throw unavailable("generation_read_failed"); }
finally { end(); }
if (generation === null) throw unavailable("catalog_unavailable");
return generation;
}

private async requireGeneration(expected: string): Promise<void> {
if (await this.readGeneration() !== expected) throw new GenerationChanged();
}
}
63 changes: 32 additions & 31 deletions backend/src/modules/jobs/filters/jobSearch.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,36 +68,33 @@ function inferJobLevel(title: string): string {
return "pleno";
}

// Match the separator run that normalizeComparable would turn into one space.
// Do not use \s: punctuation and Unicode separators must keep matching too.
const HOME_OFFICE_PATTERN = /home[^\p{L}\p{N}]+office/u;

function inferJobType(job: SearchJob): string {
const normalized = normalizeComparable(
[job.title, job.location, job.modality, job.description]
.filter(Boolean)
.join(" "),
);
// Stems contain only letters: replacing separators cannot create a match.
// Keep the full description and hybrid precedence, including conflicting fields.
const normalized = [job.title, job.location, job.modality, job.description]
.filter(Boolean)
.join(" ")
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase();

if (normalized.includes("hibrid") || normalized.includes("hybrid")) {
return "hibrido";
}
if (
normalized.includes("remot") ||
normalized.includes("home office") ||
HOME_OFFICE_PATTERN.test(normalized) ||
normalized.includes("teletrabalho") ||
normalized.includes("anywhere") ||
normalized.includes("worldwide")
) {
return "remoto";
}
if (
normalized.includes("presencial") ||
normalized.includes("onsite") ||
normalized.includes("on site") ||
normalized.includes("on-site") ||
normalized.includes("in office") ||
normalized.includes("escritorio")
) {
return "presencial";
}

// All explicit onsite aliases and documents without evidence use this fallback.
return "presencial";
}

Expand Down Expand Up @@ -242,15 +239,10 @@ export function inferJobLocationParts(location: string): JobLocationParts {
return parts;
}

function inferLocationCountry(location: string): string {
return inferJobLocationParts(location).country;
}

function matchesLocationFilter(jobLocation: string, location: string): boolean {
function matchesLocationFilter(jobLocation: string, location: string, inferredCountry: string): boolean {
if (!location) return true;

const normalizedLocation = normalizeComparable(jobLocation);
const inferredCountry = inferLocationCountry(jobLocation);
if (inferredCountry) return inferredCountry === location;

return normalizedLocation.includes(location);
Expand Down Expand Up @@ -296,6 +288,14 @@ export function filterJobs(
jobs: unknown[],
filters: ParsedJobSearchQuery,
): unknown[] {
return prepareJobFilter(filters)(jobs);
}

/** Request-local preparation: reuse normalized filters across hydrated batches. */
export function prepareJobFilter(
filters: ParsedJobSearchQuery,
): (jobs: unknown[]) => unknown[] {
const familyMode = filters.familyMode;
const level = normalizeLevelFilter(filters.level);
const seniority = normalizeLevelFilter(filters.seniority);
const location = normalizeComparable(filters.country || filters.location);
Expand All @@ -307,6 +307,7 @@ export function filterJobs(
const families = filters.families.map(normalizeComparable);
const technologies = filters.technology.map(normalizeComparable);
const companies = filters.company.map(normalizeComparable);
const needsLocation = Boolean(location || continent || state || city);

if (
!level &&
Expand All @@ -321,18 +322,18 @@ export function filterJobs(
technologies.length === 0 &&
companies.length === 0
) {
return jobs;
return (jobs) => jobs;
}

return jobs.filter((job) => {
return (jobs) => jobs.filter((job) => {
const candidate = job as SearchJob;
const title = candidate.title ?? "";
const jobLocation = candidate.location ?? "";
const jobCompany = normalizeComparable(candidate.company ?? "");
const classification = candidate.classification;
const classifiedFamilies = [
classification?.primaryFamily,
...(filters.familyMode === "any" ? classification?.relatedFamilies ?? [] : []),
...(familyMode === "any" ? classification?.relatedFamilies ?? [] : []),
]
.filter(Boolean)
.map((value) => normalizeComparable(String(value)));
Expand All @@ -348,20 +349,20 @@ export function filterJobs(
!seniority ||
classifiedSeniority === seniority ||
inferJobLevel(title) === seniority;
const locationParts = inferJobLocationParts(jobLocation);
const matchesLocation = matchesLocationFilter(jobLocation, location);
const locationParts = needsLocation ? inferJobLocationParts(jobLocation) : undefined;
const matchesLocation = matchesLocationFilter(jobLocation, location, locationParts?.country ?? "");
const matchesContinent = matchesLocationPart(
locationParts.continent,
locationParts?.continent ?? "",
jobLocation,
continent,
);
const matchesState = matchesLocationPart(
locationParts.state,
locationParts?.state ?? "",
jobLocation,
state,
);
const matchesCity = matchesLocationPart(
locationParts.city,
locationParts?.city ?? "",
jobLocation,
city,
);
Expand Down
Loading
Loading