|
| 1 | +export const MUTATION_DIAGNOSTIC_SCHEMA = "wp-codebox/cloudflare-mutation-phase/v1" |
| 2 | + |
| 3 | +export class MutationRetainedBytes { |
| 4 | + current = 0 |
| 5 | + peak = 0 |
| 6 | + |
| 7 | + retain(bytes: number): void { |
| 8 | + this.current += bytes |
| 9 | + this.peak = Math.max(this.peak, this.current) |
| 10 | + } |
| 11 | + |
| 12 | + release(bytes: number): void { |
| 13 | + this.current -= bytes |
| 14 | + if (this.current < 0) throw new Error("Mutation retained-byte accounting became negative.") |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +export interface MutationRetentionShape { |
| 19 | + responseBytes: number |
| 20 | + markdownBytes: number |
| 21 | + uploadBytes: number |
| 22 | + wpContentBytes: number |
| 23 | + largestChangedFileBytes: number |
| 24 | +} |
| 25 | + |
| 26 | +export function mutationRetentionContract(shape: MutationRetentionShape): { wholeTreePeakBytes: number; incrementalPeakBytes: number } { |
| 27 | + for (const value of Object.values(shape)) { |
| 28 | + if (!Number.isSafeInteger(value) || value < 0) throw new Error("Mutation retention shape contains invalid bytes.") |
| 29 | + } |
| 30 | + return { |
| 31 | + // The previous request retained the response, all three collections, and a hash copy of the active file. |
| 32 | + wholeTreePeakBytes: shape.responseBytes + shape.markdownBytes + shape.uploadBytes + shape.wpContentBytes + shape.largestChangedFileBytes, |
| 33 | + // Persistence owns one copied file; response conversion may briefly own both PHP and Fetch bodies. |
| 34 | + incrementalPeakBytes: Math.max(shape.responseBytes + shape.largestChangedFileBytes, 2 * shape.responseBytes), |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +export function logMutationPhase(startedAt: number, phase: string, retained: MutationRetainedBytes, evidence: Record<string, number | string>): void { |
| 39 | + console.log(JSON.stringify({ |
| 40 | + schema: MUTATION_DIAGNOSTIC_SCHEMA, |
| 41 | + phase, |
| 42 | + elapsedMs: Date.now() - startedAt, |
| 43 | + retainedBytes: retained.current, |
| 44 | + peakRetainedBytes: retained.peak, |
| 45 | + ...evidence, |
| 46 | + })) |
| 47 | +} |
0 commit comments