How vitaliy-sk/perfunit works
Project Type & Purpose
• PerfUnit is an open-source Java Agent library that instruments running Java applications to enforce performance SLOs (limits on method invocation count/time) and report violations.
Top-Level Components
A. Host Application (any JVM process)
• Your application code (calls into instrumented methods).
• MDC (Mapped Diagnostic Context) injector (e.g., Spring Cloud Sleuth) populates a trace ID in each thread.
B. Java Agent Bootstrap
• Specified by -javaagent:perfunit.jar=perfunit.yml.
• Premain (entry point) initializes the agent.
C. Transformer Layer
• PerfUnitTransformer (src/main/java/.../transformer)
– Hooks into the JVM class-loading mechanism.
– Instruments target methods based on configuration rules.
D. Configuration Layer
• ConfigurationLoader + data classes (Configuration, Rule, Limit)
• Loads/validates perfunit.yml at startup.
E. Collector & Storage
• PerfUnitCollector receives method-entry/exit events.
• InvocationsInfo holds per-trace (MDC key) invocation data.
• PerfUnitStorage stores rolling data (up to storageLimit).
F. Validation Layer
• Validators (e.g., InvocationCountValidator, SingleInvocationTimeValidator, InvocationTotalTimeValidator)
• Enforce per-call and aggregated limits.
• Throw LimitReachedException if violated (optional).
G. Reporting Layer
• Reporter interface and implementations:
– ConsoleReporter (logs violations to console)
– FileMarkdownReporter (builds a Markdown report via Mustache templates).
– DiskSaveReportRunnable (periodically or on-exit flush to disk).
• FileService handles low-level file I/O.
H. Exception Handling
• Custom exceptions (PerfUnitException, ConfigurationException, etc.) propagate errors.
Relationships & Data Flow
1. Agent Premain reads perfunit.yml → passes to ConfigurationLoader → builds in-memory Rule objects.
2. PerfUnitTransformer intercepts class-loading → instruments matching methods by injecting calls to PerfUnitCollector.
3. At runtime, instrumented methods wrap around collector calls:
– On method entry: collector.startInvocation(traceId, methodKey)
– On exit: collector.finishInvocation(traceId, methodKey, duration)
4. Collector updates InvocationsInfo in PerfUnitStorage.
5. Validators check limits immediately or at end of “working unit” (trace scope).
– On violation: either report & continue or throw exception.
6. Reporter implementations subscribe to storage events or run periodically:
– Generate text/Markdown via Mustache templates.
– FileService writes reports to reportPath.
7. On application shutdown, DiskSaveReportRunnable triggers final report flush.
Key Architectural Patterns & Principles
• Instrumentation via JVM byte-code Transformer
• Strategy pattern for validators and reporters (pluggable implementations)
• Observer/Publisher (storage → reporter) for decoupled reporting
• Configuration-driven behavior (all rules in YAML)
• Context propagation via MDC (ContextHolder).