feat(ops): /ops/v1/summary med ai/aktivering/engagemang/betalning/jobb/sakerhet + canary
- Nya toppnivåblock i /ops/v1/summary: ai_scan, aktivering, engagemang, betalning, jobb, sakerhet. Alla värden läses från DB/cache; null där data saknas, inga påhittade värden. - AI-kostnad i USD mikrocent (native); intäkter fortsatt SEK-öre. - product_analytics_events är källa för volym, latens, lyckandegrad, felfrekvens, aktivering, retention och engagemang. - Nya händelser: scan_started (API) och scan_failed/scan_completed med latencyMs + felkod (worker). latencyMs flödar nu in i scan_completed. - Safety canary-jobb varje timme: re-härleder allergener för alla recept, räknar överifierade publika recept och food-safety-lint; skriver EN rad till ops_safety_canary. Endpointen läser endast sista raden. - Cache-refresh-jobb var 60 s skriver hela summariet till Redis; endpointen serverar cachen med 503 vid cache-miss. - Bearer-token-skydd med OPS_TOKEN; HTTPS-tvång i produktion; ingen PII. - Tester för endpoint, auth, cache-miss och safety canary.
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { errors } from "../lib/errors.js";
|
||||
|
||||
const CACHE_KEY = "ops:summary:cache";
|
||||
const CACHE_TS_KEY = "ops:summary:computed_at";
|
||||
|
||||
function requireOpsToken(app: FastifyInstance) {
|
||||
return async (req: FastifyRequest, reply: FastifyReply): Promise<void> => {
|
||||
if (app.config.NODE_ENV === "production" && req.protocol !== "https") {
|
||||
return reply
|
||||
.status(403)
|
||||
.send({ error: { code: "HTTPS_REQUIRED", message: "Ops-endpointen kräver HTTPS." } });
|
||||
}
|
||||
|
||||
const header = req.headers.authorization ?? "";
|
||||
const match = /^Bearer\s+(.+)$/.exec(header);
|
||||
const provided = match?.[1] ?? "";
|
||||
const expected = app.config.OPS_TOKEN ?? "";
|
||||
|
||||
if (!expected || expected.length < 20 || provided.length !== expected.length) {
|
||||
throw errors.unauthorized();
|
||||
}
|
||||
|
||||
const ok = timingSafeEqual(Buffer.from(provided), Buffer.from(expected));
|
||||
if (!ok) throw errors.unauthorized();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Operations summary endpoint: read-only, token-protected, served from cache.
|
||||
* Heavy computation is done by the REFRESH_OPS_SUMMARY_CACHE worker job.
|
||||
*/
|
||||
export async function opsRoutes(app: FastifyInstance) {
|
||||
const preHandler = [requireOpsToken(app)];
|
||||
|
||||
app.get("/ops/v1/summary", { preHandler }, async (_req, reply) => {
|
||||
const [json, ts] = await app.redis.mget(CACHE_KEY, CACHE_TS_KEY);
|
||||
if (!json) {
|
||||
return reply.status(503).send({
|
||||
error: {
|
||||
code: "CACHE_MISS",
|
||||
message: "Sammanfattningen är inte färdigberäknad än. Vänta på nästa canary-/cache-jobb.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let summary: Record<string, unknown>;
|
||||
try {
|
||||
summary = JSON.parse(json) as Record<string, unknown>;
|
||||
} catch {
|
||||
return reply
|
||||
.status(500)
|
||||
.send({ error: { code: "CACHE_INVALID", message: "Cachen innehåller ogiltig JSON." } });
|
||||
}
|
||||
|
||||
return reply.send({
|
||||
...summary,
|
||||
cached_at: ts ?? summary.as_of,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||
import { markMilestone, schema } from "@app/database";
|
||||
import { markMilestone, schema, trackProductAnalytics } from "@app/database";
|
||||
import { scanStarted } from "@app/analytics";
|
||||
import type { JobType, ScanType } from "@app/shared-types";
|
||||
import { confirmScanInputSchema, createScanInputSchema, idParamSchema } from "@app/validation";
|
||||
import { errors, parse } from "../lib/errors.js";
|
||||
@@ -108,6 +109,16 @@ export async function scanRoutes(app: FastifyInstance) {
|
||||
jobType: job.jobType,
|
||||
correlationId: req.correlationId,
|
||||
});
|
||||
|
||||
await trackProductAnalytics(app.db, req.userId, {
|
||||
...scanStarted(),
|
||||
householdId: job.householdId ?? undefined,
|
||||
properties: {
|
||||
scanType: job.scanType,
|
||||
jobType: job.jobType,
|
||||
},
|
||||
});
|
||||
|
||||
return { ok: true, status: "queued" };
|
||||
});
|
||||
|
||||
@@ -353,7 +364,8 @@ function extractProposals(job: { result: unknown }): ProposalItem[] {
|
||||
unit: it.unit ?? null,
|
||||
bestBeforeDate: it.bestBeforeDate ?? null,
|
||||
confidence: typeof it.confidence === "number" ? it.confidence : null,
|
||||
requiresConfirmation: typeof it.requiresConfirmation === "boolean" ? it.requiresConfirmation : null,
|
||||
requiresConfirmation:
|
||||
typeof it.requiresConfirmation === "boolean" ? it.requiresConfirmation : null,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user