# vitaliy-sk/perfunit architecture

> Architecture diagram of the GitHub repository vitaliy-sk/perfunit, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-18). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/vitaliy-sk/perfunit
- Repository: https://github.com/vitaliy-sk/perfunit

## Overview

##### 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).

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Host Application Layer
    subgraph "Host Application" 
        direction TB
        App["Your Application Code"]:::host
        MDC["MDC Injector (Spring Sleuth)"]:::host
        ContextHolder["ContextHolder"]:::util
        StackUtils["StackTraceUtils"]:::util
    end

    %% Agent Bootstrap & Transformer
    subgraph "Agent Bootstrap & Transformer"
        direction TB
        Premain["PerfUnit (Premain)"]:::bootstrap
        Transformer["PerfUnitTransformer"]:::bootstrap
    end

    %% Configuration Layer
    subgraph "Configuration" 
        direction TB
        ConfigLoader["ConfigurationLoader"]:::config
        ConfigModel["Configuration"]:::config
        RuleModel["Rule"]:::config
        LimitModel["Limit"]:::config
    end

    %% Collector & Storage
    subgraph "Collector & Storage"
        direction TB
        Collector["PerfUnitCollector"]:::collector
        Invocations["InvocationsInfo"]:::collector
        Storage["PerfUnitStorage"]:::collector
    end

    %% Validation Layer
    subgraph "Validation" 
        direction TB
        ValidatorInterface["RuleValidator"]:::validation
        ValidatorCount["InvocationCountValidator"]:::validation
        ValidatorSingle["SingleInvocationTimeValidator"]:::validation
        ValidatorTotal["InvocationTotalTimeValidator"]:::validation
    end

    %% Reporting Layer
    subgraph "Reporting & I/O"
        direction TB
        ReporterIF["Reporter"]:::reporting
        ConsoleRep["ConsoleReporter"]:::reporting
        MarkdownRep["FileMarkdownReporter"]:::reporting
        DiskSave["DiskSaveReportRunnable"]:::reporting
        FileService["FileService"]:::reporting
        Templates["Markdown Templates"]:::reporting
    end

    %% Exception Handling
    subgraph "Exceptions"
        direction TB
        BaseEx["PerfUnitException"]:::exception
        ConfigEx["ConfigurationException"]:::exception
        LimitEx["LimitReachedException"]:::exception
        UnknownEx["UnknownCallerException"]:::exception
    end

    %% Integration Tests
    subgraph "Integration Tests"
        direction TB
        AgentTest["AgentIntegrationTest"]:::test
        NetworkTest["NetworkTest"]:::test
        DummyService["ExpensiveService"]:::test
    end

    %% Flows
    App -->|calls instrumented methods| Transformer
    Premain -->|reads perfunit.yml| ConfigLoader
    ConfigLoader -->|builds| ConfigModel & RuleModel & LimitModel
    Transformer -->|instruments via bytecode| Collector
    Collector -->|"startInvocation/finishInvocation"| Invocations
    Invocations --> Storage
    Storage --> ValidatorInterface
    ValidatorInterface --> ValidatorCount & ValidatorSingle & ValidatorTotal
    ValidatorCount -->|violates| LimitEx
    ValidatorSingle -->|violates| LimitEx
    ValidatorTotal -->|violates| LimitEx
    Storage --> ReporterIF
    ReporterIF --> ConsoleRep & MarkdownRep
    MarkdownRep --> Templates
    ReporterIF --> DiskSave
    DiskSave --> FileService
    FileService -->|writes report| Templates

    MDC --> App
    ContextHolder --> App
    StackUtils --> App

    ConfigLoader -->|errors| ConfigEx
    Transformer -->|errors| BaseEx
    Collector -->|errors| BaseEx

    AgentTest --> Premain
    AgentTest --> App
    NetworkTest --> Transformer
    DummyService --> App

    %% Click Events
    click Premain "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/PerfUnit.java"
    click Transformer "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/transformer/PerfUnitTransformer.java"
    click ConfigLoader "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/configuration/ConfigurationLoader.java"
    click ConfigModel "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/configuration/data/Configuration.java"
    click RuleModel "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/configuration/data/Rule.java"
    click LimitModel "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/configuration/data/Limit.java"
    click Collector "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/collector/PerfUnitCollector.java"
    click Invocations "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/collector/InvocationsInfo.java"
    click Storage "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/collector/PerfUnitStorage.java"
    click ValidatorCount "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/validator/InvocationCountValidator.java"
    click ValidatorSingle "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/validator/SingleInvocationTimeValidator.java"
    click ValidatorTotal "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/validator/InvocationTotalTimeValidator.java"
    click ValidatorInterface "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/validator/RuleValidator.java"
    click ReporterIF "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/reporter/Reporter.java"
    click ConsoleRep "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/reporter/ConsoleReporter.java"
    click MarkdownRep "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/reporter/FileMarkdownReporter.java"
    click DiskSave "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/reporter/DiskSaveReportRunnable.java"
    click FileService "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/file/FileService.java"
    click BaseEx "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/exception/PerfUnitException.java"
    click ConfigEx "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/exception/ConfigurationException.java"
    click LimitEx "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/exception/LimitReachedException.java"
    click UnknownEx "https://github.com/vitaliy-sk/perfunit/blob/master/src/main/java/dev/techh/perfunit/exception/UnknownCallerException.java"

    %% Styles
    classDef host fill:#cccccc,stroke:#333,stroke-width:1px
    classDef bootstrap fill:#cce5ff,stroke:#004085,stroke-width:1px
    classDef config fill:#e2f0d9,stroke:#2e6c2b,stroke-width:1px
    classDef collector fill:#d4edda,stroke:#155724,stroke-width:1px
    classDef validation fill:#c3e6cb,stroke:#155724,stroke-width:1px
    classDef reporting fill:#ffe5b4,stroke:#e65c00,stroke-width:1px
    classDef exception fill:#f8d7da,stroke:#721c24,stroke-width:1px
    classDef util fill:#e2e3e5,stroke:#6c757d,stroke-width:1px
    classDef test fill:#f5c6cb,stroke:#721c24,stroke-width:1px

    class ConfigModel,RuleModel,LimitModel config
    class ValidatorCount,ValidatorSingle,ValidatorTotal validation
    class Templates reporting
```
