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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 1x 1x 9x 9x 9x 9x 9x 9x 10x 1x 1x 8x 10x 1x 1x 1x 1x 1x 1x 1x 7x 10x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 4x 10x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 4x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
import { isAnalyzeJobRequest, MAIN_TEXT_CAP } from "../models/job";
import type { AuthenticatedUser } from "../models/user";
import { withAuth, type AuthedHandler } from "../services/auth";
import { corsHeaders, errorResponse as httpErrorResponse, requestOrigin } from "../services/http";
import {
orchestrateJobAnalysis,
JobSchemaError,
} from "../services/jobExtractionOrchestrator";
import {
checkAndIncrement,
refundOnSystemFailure,
type CheckAndIncrementResult,
} from "../services/meteringService";
import { withRateLimit } from "../services/rateLimiter";
export async function analyzeJobHandler(
request: HttpRequest,
context: InvocationContext,
user: AuthenticatedUser
): Promise<HttpResponseInit> {
const origin = requestOrigin(request);
if (request.method === "OPTIONS") {
return { status: 204, headers: corsHeaders(origin) };
}
context.log("analyze-job function triggered");
let body: unknown;
try {
body = await request.json();
} catch {
return httpErrorResponse(400, "INVALID_REQUEST", "Request body must be valid JSON.", origin);
}
if (!isAnalyzeJobRequest(body)) {
return httpErrorResponse(
400,
"INVALID_REQUEST",
"Missing or invalid extract: url, title, jsonLd, and mainText are required.",
origin
);
}
if (body.extract.mainText.length > MAIN_TEXT_CAP) {
return httpErrorResponse(
413,
"EXTRACT_TOO_LARGE",
`Page text exceeds the ${MAIN_TEXT_CAP.toLocaleString()}-character limit.`,
origin
);
}
try {
const result = await orchestrateJobAnalysis(body, user.tier, (message) =>
context.warn(message)
);
return { status: 200, headers: corsHeaders(origin), jsonBody: result };
} catch (err) {
if (err instanceof JobSchemaError) {
context.error("analyze-job schema failure:", err.message);
return httpErrorResponse(
502,
"SCHEMA_PARSE_FAILED",
"The analysis service returned an unusable result. Please try again.",
origin
);
}
context.error("orchestrateJobAnalysis failed:", err);
return httpErrorResponse(500, "SERVICE_ERROR", "Analysis failed. Please try again.", origin);
}
}
function meteringEnforced(): boolean {
return process.env.METERING_ENFORCED !== "false";
}
function formatResetDate(iso: string): string {
return new Date(iso).toLocaleDateString("en-US", {
month: "long",
day: "numeric",
timeZone: "UTC",
});
}
function usageEcho(usage: CheckAndIncrementResult) {
return {
count: usage.count,
limit: usage.limit,
resetsAt: usage.resetsAt,
tier: usage.tier,
};
}
/**
* withUsageMetering(handler) — composes as withAuth(withUsageMetering(handler))
* (contracts/metering.md): increments the caller's monthly counter BEFORE the
* wrapped handler runs (fail closed — no OpenAI spend on a 429 or a metering
* outage), echoes usage on 200, and best-effort refunds a system-caused
* failure. METERING_ENFORCED=false (rollout PR1 shadow mode, plan.md) still
* counts but never blocks — used to accrue real usage data before the public
* flag flip.
*/
export function withUsageMetering(handler: AuthedHandler): AuthedHandler {
return async (
request: HttpRequest,
context: InvocationContext,
user: AuthenticatedUser
): Promise<HttpResponseInit> => {
if (request.method === "OPTIONS") return handler(request, context, user);
const origin = requestOrigin(request);
let usage: CheckAndIncrementResult;
try {
usage = await checkAndIncrement(user.sub, user.tier);
} catch (err) {
context.error("usage metering check failed:", err);
return httpErrorResponse(
503,
"SERVICE_ERROR",
"Couldn't verify your usage allowance. Please try again.",
origin
);
}
if (!usage.allowed) {
if (!meteringEnforced()) {
// Shadow mode: count, never block (rollout PR1).
return handler(request, context, user);
}
const tierLabel = usage.tier === "premium" ? "premium" : "free";
return {
status: 429,
headers: corsHeaders(origin),
jsonBody: {
error: {
code: "USAGE_LIMIT_REACHED",
message: `You've used all ${usage.limit} ${tierLabel} analyses this month. Your allowance resets on ${formatResetDate(usage.resetsAt)}.`,
},
usage: usageEcho(usage),
},
};
}
const response = await handler(request, context, user);
if (response.status !== undefined && response.status >= 500) {
// System-caused failure after the increment — best-effort refund
// (FR-007); a lost refund is logged, never surfaced (metering.md).
refundOnSystemFailure(user.sub, user.tier).catch((err) => {
context.error("metering.refund_lost:", err);
});
} else if (response.status === 200) {
response.jsonBody = {
...(response.jsonBody as Record<string, unknown>),
usage: usageEcho(usage),
};
}
return response;
};
}
app.http("analyze-job", {
methods: ["POST"],
authLevel: "function",
route: "analyze-job",
handler: withRateLimit("analyze", withAuth(withUsageMetering(analyzeJobHandler))),
});
app.http("analyze-job-preflight", {
methods: ["OPTIONS"],
authLevel: "anonymous",
route: "analyze-job",
handler: (request: HttpRequest) => ({
status: 204,
headers: corsHeaders(requestOrigin(request)),
}),
});
|