174 lines
6.6 KiB
TypeScript
174 lines
6.6 KiB
TypeScript
import { randomUUID } from "node:crypto"
|
|
import { flowWritePool as pool, flowWriteContext, commitFlowWrite, reconcileFlowWrite, FlowCommitUnknown } from "./traffic-flow-write-transaction.js"
|
|
import { flowBatchProof } from "./traffic-flow-batch-proof.js"
|
|
import { OwnedFlowBatch } from "./traffic-flow-owned-batch.js"
|
|
import { createSerialOperation } from "./serial-operation.js"
|
|
import { ensurePartitionFor, specForParent } from "../db/partitions.js"
|
|
import { createFlowFactAccumulator, type FactRow } from "./traffic-flow-fact-accumulator.js"
|
|
export {
|
|
FACT_ASN_TOP, FACT_TUPLE_CAP, FACT_SERVICE_MAX_LEN, UNKNOWN_COUNTRY, OTHER_SERVICE, UNKNOWN_IFACE,
|
|
hourBucketIso, normalizeFactCountry, normalizeFactService, normalizeFactIface, normalizeFactAsn,
|
|
} from "./traffic-flow-fact-accumulator.js"
|
|
export type { FactAcc, FactRow } from "./traffic-flow-fact-accumulator.js"
|
|
|
|
const liveFacts = createFlowFactAccumulator()
|
|
const ensuredParts = new Set<string>()
|
|
let ownedFacts: OwnedFlowBatch<FactRow[]> | null = null
|
|
|
|
export function hasPendingFlowFact(row:FactRow):boolean {return liveFacts.has(row)}
|
|
export function bumpFlowFact(row: FactRow): void { liveFacts.bump(row) }
|
|
export function collectCappedFacts(): FactRow[] { return liveFacts.collectCapped() }
|
|
|
|
async function ensureParentPartition(parent: string, ts: string): Promise<void> {
|
|
const spec = specForParent(parent)
|
|
if (!spec) return
|
|
const iso = ts.length === 10 ? `${ts}T00:00:00Z` : ts
|
|
const key = `${parent}:${iso.slice(0, 10)}`
|
|
const parts=flowWriteContext()?.partitions??ensuredParts
|
|
if (parts.has(key)) return
|
|
await ensurePartitionFor(pool, parent, spec.kind, new Date(iso))
|
|
parts.add(key)
|
|
}
|
|
|
|
function dayKey(bucketAt: string): string {
|
|
return bucketAt.slice(0, 10)
|
|
}
|
|
|
|
export function takePendingFlowFacts(): FactRow[] {
|
|
if(ownedFacts)throw new Error("A standalone fact batch still owns pending facts")
|
|
const rows=liveFacts.snapshot();liveFacts.clear();return rows
|
|
}
|
|
|
|
/** Caller owns the transaction and private accumulator; this never drains live state. */
|
|
export async function persistFlowFactRows(rows:FactRow[]): Promise<number> {
|
|
if(!flowWriteContext())throw new Error("Fact persistence requires a fenced transaction")
|
|
if (rows.length === 0) return 0
|
|
const hours = new Set(rows.map((r) => r.bucketAt))
|
|
const days = new Set(rows.map((r) => dayKey(r.bucketAt)))
|
|
for (const h of hours) await ensureParentPartition("flow_hour_facts", h)
|
|
for (const d of days) await ensureParentPartition("flow_daily_facts", d)
|
|
|
|
await pool.query({
|
|
text: `
|
|
INSERT INTO flow_hour_facts (
|
|
server_id, bucket_at, iface, country, service, asn, bytes, packets
|
|
)
|
|
SELECT *
|
|
FROM UNNEST(
|
|
$1::bigint[],
|
|
$2::timestamptz[],
|
|
$3::text[],
|
|
$4::char(2)[],
|
|
$5::text[],
|
|
$6::int[],
|
|
$7::bigint[],
|
|
$8::bigint[]
|
|
) AS t(server_id, bucket_at, iface, country, service, asn, bytes, packets)
|
|
ON CONFLICT (server_id, bucket_at, iface, country, service, asn)
|
|
DO UPDATE SET
|
|
bytes = flow_hour_facts.bytes + excluded.bytes,
|
|
packets = flow_hour_facts.packets + excluded.packets
|
|
`,
|
|
values: [
|
|
rows.map((r) => r.serverId),
|
|
rows.map((r) => r.bucketAt),
|
|
rows.map((r) => r.iface),
|
|
rows.map((r) => r.country),
|
|
rows.map((r) => r.service),
|
|
rows.map((r) => r.asn),
|
|
rows.map((r) => r.bytes),
|
|
rows.map((r) => r.packets),
|
|
],
|
|
})
|
|
|
|
await pool.query({
|
|
text: `
|
|
INSERT INTO flow_daily_facts (
|
|
server_id, day, iface, country, service, asn, bytes, packets
|
|
)
|
|
SELECT server_id, day, iface, country, service, asn,
|
|
sum(bytes)::bigint, sum(packets)::bigint
|
|
FROM UNNEST(
|
|
$1::bigint[],
|
|
$2::date[],
|
|
$3::text[],
|
|
$4::char(2)[],
|
|
$5::text[],
|
|
$6::int[],
|
|
$7::bigint[],
|
|
$8::bigint[]
|
|
) AS t(server_id, day, iface, country, service, asn, bytes, packets)
|
|
GROUP BY server_id, day, iface, country, service, asn
|
|
ON CONFLICT (server_id, day, iface, country, service, asn)
|
|
DO UPDATE SET
|
|
bytes = flow_daily_facts.bytes + excluded.bytes,
|
|
packets = flow_daily_facts.packets + excluded.packets
|
|
`,
|
|
values: [
|
|
rows.map((r) => r.serverId),
|
|
rows.map((r) => dayKey(r.bucketAt)),
|
|
rows.map((r) => r.iface),
|
|
rows.map((r) => r.country),
|
|
rows.map((r) => r.service),
|
|
rows.map((r) => r.asn),
|
|
rows.map((r) => r.bytes),
|
|
rows.map((r) => r.packets),
|
|
],
|
|
})
|
|
return rows.length
|
|
}
|
|
|
|
const serializeFacts=createSerialOperation()
|
|
export function flushFlowFacts():Promise<number>{return serializeFacts(flushOwnedFacts)}
|
|
async function flushOwnedFacts(): Promise<number> {
|
|
if(!ownedFacts){const raw=takePendingFlowFacts();if(!raw.length)return 0;ownedFacts=new OwnedFlowBatch(randomUUID(),"",raw)}
|
|
const batch=ownedFacts
|
|
if(!batch.sourceProof)batch.prove(flowBatchProof(batch.payload,"facts"))
|
|
batch.assertProof(flowBatchProof(batch.payload,"facts"))
|
|
batch.begin()
|
|
try {
|
|
const result=await commitFlowWrite({id:batch.id,kind:"facts",sourceProof:batch.sourceProof},async()=>{
|
|
const accumulator=createFlowFactAccumulator();for(const row of batch.payload)accumulator.bump(row)
|
|
const facts=await persistFlowFactRows(accumulator.collectCapped())
|
|
batch.assertProof(flowBatchProof(batch.payload,"facts"))
|
|
return {facts}
|
|
})
|
|
batch.committed();ownedFacts=null;return result.facts
|
|
}catch(error){if(error instanceof FlowCommitUnknown)batch.unknown();else batch.rolledBack();throw error}
|
|
}
|
|
|
|
export async function reconcilePendingFactWrite(authorize:()=>Promise<unknown>=async()=>{}) {
|
|
return serializeFacts(async()=>{
|
|
if(!ownedFacts||ownedFacts.state!=="unknown")return {state:ownedFacts?.state??"idle"}
|
|
const batch=ownedFacts,result=await reconcileFlowWrite({id:batch.id,kind:"facts",sourceProof:batch.sourceProof},authorize)
|
|
batch.reconciled(result.committed?"committed":"absent-after-barrier")
|
|
if(result.committed)ownedFacts=null
|
|
return {state:batch.state,batchId:batch.id}
|
|
})
|
|
}
|
|
|
|
export function factsPendingSize(): number {
|
|
return liveFacts.size+(ownedFacts?.payload.length??0)
|
|
}
|
|
|
|
export const resetFactsForTests = resetFactsAfterDatabaseRestore
|
|
|
|
export function assertFactsResetAllowed():void {
|
|
ownedFacts?.assertResolved()
|
|
}
|
|
export function resetFactsAfterDatabaseRestore(): void {
|
|
assertFactsResetAllowed()
|
|
liveFacts.clear()
|
|
ownedFacts=null
|
|
ensuredParts.clear()
|
|
}
|
|
|
|
export function discardPendingFacts(): void {
|
|
if(ownedFacts)throw new Error("Cannot discard an owned fact write batch")
|
|
liveFacts.clear()
|
|
}
|
|
|
|
export function factsSnapshotForTests(): FactRow[] {
|
|
return liveFacts.snapshot()
|
|
}
|