63 lines
3.7 KiB
TypeScript
63 lines
3.7 KiB
TypeScript
import type { LogFilters, LogLevel } from "@mmapp/contracts"
|
|
import type { RosLogEntry } from "../types/server.js"
|
|
import { createHash } from "node:crypto"
|
|
|
|
export function logLevel(topics: string[]): LogLevel {
|
|
return (["critical", "error", "warning", "info", "debug"] as const).find(level => topics.includes(level)) ?? "unknown"
|
|
}
|
|
export function logSignature(entry: RosLogEntry): string {
|
|
return createHash("sha256").update(JSON.stringify([entry[".id"], entry.time, entry.topics, entry.message])).digest("hex")
|
|
}
|
|
/** Longest suffix/prefix overlap, linear in buffer size. Signatures include RouterOS identity. */
|
|
export function reconcileLogSnapshot(previous: string[], current: string[]) {
|
|
if (!previous.length) return { offset: 0, gap: false }
|
|
if (!current.length) return { offset: 0, gap: true }
|
|
const combined: (string | null)[] = [...current, null, ...previous]
|
|
const pi = new Array<number>(combined.length).fill(0)
|
|
for (let i = 1; i < combined.length; i++) {
|
|
let j = pi[i - 1]
|
|
while (j && combined[i] !== combined[j]) j = pi[j - 1]
|
|
if (combined[i] === combined[j]) j++
|
|
pi[i] = j
|
|
}
|
|
const offset = pi[pi.length - 1]
|
|
return { offset, gap: offset === 0 }
|
|
}
|
|
export function parseLogTime(raw: string): string | null {
|
|
// RouterOS timestamps without an explicit offset cannot be interpreted as UTC safely.
|
|
if (!/^\d{4}-\d\d-\d\d[T ]\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(raw)) return null
|
|
const date = raw.slice(0, 10), calendar = new Date(date + "T00:00:00Z")
|
|
if (!Number.isFinite(calendar.getTime()) || calendar.toISOString().slice(0, 10) !== date || Number(raw.slice(11, 13)) > 23) return null
|
|
const ms = Date.parse(raw.replace(" ", "T"))
|
|
return Number.isFinite(ms) ? new Date(ms).toISOString() : null
|
|
}
|
|
type LogServerScope = Pick<LogFilters, "serverId"> & { allowedServerIds?: number[] }
|
|
|
|
export function logServerConditions({ allowedServerIds, serverId }: LogServerScope, bind: (value: unknown) => string) {
|
|
const clauses: string[] = []
|
|
if (allowedServerIds !== undefined) clauses.push(`server_id = ANY(${bind(allowedServerIds)}::bigint[])`)
|
|
if (serverId) clauses.push(`server_id = ${bind(serverId)}`)
|
|
return clauses
|
|
}
|
|
|
|
export function logWhere(filters: LogFilters & LogServerScope, extra: string[] = [], initial: unknown[] = []) {
|
|
const values = [...initial], clauses = [...extra]
|
|
const bind = (value: unknown) => { values.push(value); return `$${values.length}` }
|
|
clauses.push(...logServerConditions(filters, bind))
|
|
if (filters.from) clauses.push(`effective_at >= ${bind(filters.from)}::timestamptz`)
|
|
if (filters.to) clauses.push(`effective_at <= ${bind(filters.to)}::timestamptz`)
|
|
if (filters.levels) clauses.push(`level = ANY(${bind(filters.levels.split(","))}::text[])`)
|
|
if (filters.topics) clauses.push(`topics && ${bind(filters.topics.split(",").map(t => t.trim()).filter(Boolean))}::text[]`)
|
|
if (filters.q) clauses.push(`strpos(lower(message), lower(${bind(filters.q)})) > 0`)
|
|
if (filters.preset === "login-failure") clauses.push(`(lower(message) LIKE '%login failure%' OR lower(message) LIKE '%login failed%' OR lower(message) LIKE '%authentication failed%')`)
|
|
if (filters.preset === "interfaces") clauses.push(`topics && ARRAY['interface','bridge','ethernet','wireless','wifi']::text[]`)
|
|
if (filters.preset === "routing") clauses.push(`topics && ARRAY['route','routing','bgp','ospf','bfd']::text[]`)
|
|
if (filters.preset === "firewall") clauses.push(`'firewall' = ANY(topics)`)
|
|
return { sql: clauses.length ? clauses.join(" AND ") : "TRUE", values }
|
|
}
|
|
export function csvCell(value: unknown): string {
|
|
let text = String(value ?? "")
|
|
if (/^(?:\s*[=+\-@]|[\t\r])/.test(text)) text = "'" + text
|
|
return '"' + text.replaceAll('"', '""') + '"'
|
|
}
|