* Folds a batch's usage_rollup events into one counter per day × tool × client. * Old clients send up to 100 copies of the same `count: 1` line per request; this * turns them into one upsert instead of a hundred.
(events: StoredEvent[], receivedAt: string)
| 240 | * turns them into one upsert instead of a hundred. |
| 241 | */ |
| 242 | function foldUsage(events: StoredEvent[], receivedAt: string): UsageCounter[] { |
| 243 | const byKey = new Map<string, UsageCounter>(); |
| 244 | for (const e of events) { |
| 245 | const day = (e.ts ?? receivedAt).slice(0, 10); |
| 246 | const kind = String(e.props.kind); |
| 247 | const name = String(e.props.name); |
| 248 | const clientName = typeof e.props.client_name === 'string' ? e.props.client_name : ''; |
| 249 | const clientVersion = typeof e.props.client_version === 'string' ? e.props.client_version : ''; |
| 250 | const key = [day, kind, name, clientName, clientVersion].join('\u0000'); |
| 251 | const counter = byKey.get(key) ?? { day, kind, name, clientName, clientVersion, count: 0, errors: 0 }; |
| 252 | counter.count += typeof e.props.count === 'number' ? e.props.count : 0; |
| 253 | counter.errors += typeof e.props.error_count === 'number' ? e.props.error_count : 0; |
| 254 | byKey.set(key, counter); |
| 255 | } |
| 256 | return [...byKey.values()]; |
| 257 | } |
| 258 | |
| 259 | /** |
| 260 | * Persist a sanitized batch: one `events` row per lifecycle event, usage counters |