|
| 1 | +import type { TtlReading } from "../rpc/ttl.js"; |
| 2 | + |
| 3 | +/** Why a contract does or does not need maintenance now. */ |
| 4 | +export interface MaintenanceDecision { |
| 5 | + needed: boolean; |
| 6 | + reason: string; |
| 7 | + lowKeys: string[]; |
| 8 | + archivedKeys: string[]; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * The threshold to judge a contract by. |
| 13 | + * |
| 14 | + * A registered threshold of zero means the contract published no useful value, |
| 15 | + * so the operator's `LK_THRESHOLD` stands in. Anything positive wins, because the |
| 16 | + * contract knows its own needs better than a global default does. |
| 17 | + */ |
| 18 | +export function effectiveThreshold(registered: number, fallback: number): number { |
| 19 | + return registered > 0 ? registered : fallback; |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Decide whether a contract needs maintenance. |
| 24 | + * |
| 25 | + * Needed when any observed key is below threshold or already archived. Pure, so |
| 26 | + * the daemon's decision is testable without a network. |
| 27 | + */ |
| 28 | +export function decideMaintenance(readings: TtlReading[], threshold: number): MaintenanceDecision { |
| 29 | + if (readings.length === 0) { |
| 30 | + return { needed: false, reason: "no keys observed", lowKeys: [], archivedKeys: [] }; |
| 31 | + } |
| 32 | + |
| 33 | + const lowKeys: string[] = []; |
| 34 | + const archivedKeys: string[] = []; |
| 35 | + |
| 36 | + for (const reading of readings) { |
| 37 | + if (reading.remaining <= 0) { |
| 38 | + archivedKeys.push(reading.description); |
| 39 | + } else if (reading.remaining < threshold) { |
| 40 | + lowKeys.push(reading.description); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + const needed = lowKeys.length > 0 || archivedKeys.length > 0; |
| 45 | + const reason = needed |
| 46 | + ? `${lowKeys.length} low, ${archivedKeys.length} archived, threshold ${threshold}` |
| 47 | + : `all ${readings.length} keys above threshold ${threshold}`; |
| 48 | + |
| 49 | + return { needed, reason, lowKeys, archivedKeys }; |
| 50 | +} |
0 commit comments