{"id":33485017,"url":"https://github.com/fluxzero-io/fluxzero-sdk-java","last_synced_at":"2026-07-03T12:01:44.184Z","repository":{"id":313874160,"uuid":"1051005492","full_name":"fluxzero-io/fluxzero-sdk-java","owner":"fluxzero-io","description":"Client libraries to interface with Fluxzero Runtime","archived":false,"fork":false,"pushed_at":"2026-06-29T06:07:47.000Z","size":521207,"stargazers_count":18,"open_issues_count":7,"forks_count":2,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-29T08:24:57.832Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fluxzero-io.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-09-05T09:41:44.000Z","updated_at":"2026-06-29T06:02:49.000Z","dependencies_parsed_at":"2026-02-26T05:00:24.185Z","dependency_job_id":"93dac883-1110-4b99-9c50-a8e75513c0ed","html_url":"https://github.com/fluxzero-io/fluxzero-sdk-java","commit_stats":null,"previous_names":["fluxzero-io/fluxzero-sdk-java"],"tags_count":464,"template":false,"template_full_name":null,"purl":"pkg:github/fluxzero-io/fluxzero-sdk-java","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluxzero-io%2Ffluxzero-sdk-java","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluxzero-io%2Ffluxzero-sdk-java/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluxzero-io%2Ffluxzero-sdk-java/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluxzero-io%2Ffluxzero-sdk-java/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fluxzero-io","download_url":"https://codeload.github.com/fluxzero-io/fluxzero-sdk-java/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fluxzero-io%2Ffluxzero-sdk-java/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35084820,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-03T02:00:05.635Z","response_time":110,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-11-25T16:00:34.249Z","updated_at":"2026-07-03T12:01:44.147Z","avatar_url":"https://github.com/fluxzero-io.png","language":"Java","funding_links":[],"categories":["微服务库"],"sub_categories":[],"readme":"\u003ca href=\"https://fluxzero.io\"\u003e\n    \u003cimg src=\"https://fluxzero.io/assets/fluxzero/fluxzero-logo.png\" alt=\"Fluxzero logo\" title=\"Fluxzero\" align=\"right\" height=\"60\" /\u003e\n\u003c/a\u003e\n\n# Fluxzero Java SDK\n\n[![Build](https://github.com/fluxzero-io/fluxzero-sdk-java/actions/workflows/deploy.yml/badge.svg)](https://github.com/fluxzero-io/fluxzero-sdk-java/actions)\n[![Maven Central](https://img.shields.io/maven-central/v/io.fluxzero/fluxzero-sdk-java)](https://central.sonatype.com/artifact/io.fluxzero/fluxzero-sdk-java?smo=true)\n[![Javadoc](https://img.shields.io/badge/javadoc-main-blue)](https://fluxzero-io.github.io/fluxzero-sdk-java/javadoc/apidocs/)\n[![Cheatsheet](https://img.shields.io/badge/cheatsheet-PDF-red.svg)](https://raw.githubusercontent.com/fluxzero-io/fluxzero-sdk-java/refs/heads/main/docs/cheatsheet.pdf)\n[![License](https://img.shields.io/badge/license-Apache%202.0-green.svg)](https://www.apache.org/licenses/LICENSE-2.0)\n\nThis repository contains the official Java SDK for [Fluxzero](https://fluxzero.io). For a short overview of \nfunctionalities, check out this [cheatsheet](docs/cheatsheet.pdf).\n\n---\n\n## Installation\n\n### Maven Users\n\nImport the [Fluxzero BOM](https://mvnrepository.com/artifact/io.fluxzero/fluxzero-bom) in your\n`dependencyManagement` section to centralize version management:\n\n```xml\n\n\u003cdependencyManagement\u003e\n    \u003cdependencies\u003e\n        \u003cdependency\u003e\n            \u003cgroupId\u003eio.fluxzero\u003c/groupId\u003e\n            \u003cartifactId\u003efluxzero-bom\u003c/artifactId\u003e\n            \u003cversion\u003e${fluxzero.version}\u003c/version\u003e \u003c!-- See version badge above --\u003e\n            \u003ctype\u003epom\u003c/type\u003e\n            \u003cscope\u003eimport\u003c/scope\u003e\n        \u003c/dependency\u003e\n    \u003c/dependencies\u003e\n\u003c/dependencyManagement\u003e\n```\n\nThen declare only the dependencies you actually need (no version required):\n\n```xml\n\n\u003cdependencies\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eio.fluxzero\u003c/groupId\u003e\n        \u003cartifactId\u003ejava-client\u003c/artifactId\u003e\n    \u003c/dependency\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eio.fluxzero\u003c/groupId\u003e\n        \u003cartifactId\u003ejava-client\u003c/artifactId\u003e\n        \u003cclassifier\u003etests\u003c/classifier\u003e\n        \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eio.fluxzero\u003c/groupId\u003e\n        \u003cartifactId\u003etest-server\u003c/artifactId\u003e\n        \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n    \u003cdependency\u003e\n        \u003cgroupId\u003eio.fluxzero\u003c/groupId\u003e\n        \u003cartifactId\u003eproxy\u003c/artifactId\u003e\n        \u003cscope\u003etest\u003c/scope\u003e\n    \u003c/dependency\u003e\n\u003c/dependencies\u003e\n```\n\n\u003e 💡 **Note:** The `test-server` and `proxy` modules are **optional**, and can be included if you want to test your\n\u003e application locally against an **in-memory Flux server**.\n\n---\n\n### Gradle Users\n\nUse [platform BOM support](https://docs.gradle.org/current/userguide/platforms.html) to align dependency versions\nautomatically:\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eKotlin DSL (build.gradle.kts)\u003c/strong\u003e\u003c/summary\u003e\n\n```kotlin\ndependencies {\n    implementation(platform(\"io.fluxzero:fluxzero-bom:${fluxzeroVersion}\"))\n    implementation(\"io.fluxzero:java-client\")\n    testImplementation(\"io.fluxzero:java-client\", classifier = \"tests\")\n    testImplementation(\"io.fluxzero:test-server\")\n    testImplementation(\"io.fluxzero:proxy\")\n}\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eGroovy DSL (build.gradle)\u003c/strong\u003e\u003c/summary\u003e\n\n```groovy\ndependencies {\n    implementation platform(\"io.fluxzero:fluxzero-bom:${fluxzeroVersion}\")\n    implementation 'io.fluxzero:java-client'\n    testImplementation('io.fluxzero:java-client') {\n        classifier = 'tests'\n    }\n    testImplementation 'io.fluxzero:test-server'\n    testImplementation 'io.fluxzero:proxy'\n}\n```\n\n\u003c/details\u003e\n\n---\n\n\u003e 🔖 **Tip:** You only need to update the version number **once** in the BOM reference. All included modules will\n\u003e automatically align\n\u003e with it.\n\n---\n\n## Basic example\n\nCreate a new project and add an event class:\n\n```java\npublic record HelloWorld() {\n}\n```\n\nCreate a handler for the event:\n\n```java\npublic class HelloWorldEventHandler {\n    @HandleEvent\n    void handle(HelloWorld event) {\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\nPublish the event:\n\n```java\npublic class ExampleMain {\n    public static void main(final String[] args) {\n        var fluxzero = DefaultFluxzero.builder()\n                .build(LocalClient.newInstance());\n        fluxzero.registerHandlers(new HelloWorldEventHandler());\n        fluxzero.eventGateway().publish(new HelloWorld());\n    }\n}\n```\n\nOutput:\n\n```\nHello World!\n```\n\n### With Spring\n\nFluxzero integrates seamlessly with Spring. Here’s how the above example looks with Spring Boot:\n\n```java\n\n@SpringBootApplication\npublic class ExampleMain {\n    public static void main(String... args) {\n        SpringApplication.run(ExampleMain.class, args);\n        Fluxzero.publishEvent(new HelloWorld());\n    }\n}\n```\n\nAnd annotate your handler with `@Component`:\n\n```java\n\n@Component\npublic class HelloWorldEventHandler {\n    @HandleEvent\n    void handle(HelloWorld event) {\n        System.out.println(\"Hello World!\");\n    }\n}\n```\n\n\u003e ⚠️ Using Spring non-Boot? Add `@Import(FluxzeroSpringConfig.class)` to register Fluxzero and related beans.\n\n### Testing your handler\n\nFluxzero includes a powerful TestFixture utility for testing your handlers without needing a full application\nor infrastructure setup.\n\nHere’s how to test our HelloWorldEventHandler from earlier:\n\n```java\nclass HelloWorldEventHandlerTest {\n\n    @Test\n    void testHelloWorldHandler() {\n        TestFixture.create(new HelloWorldEventHandler())\n                .whenEvent(new HelloWorld())\n                .expectThat(fc -\u003e System.out.println(\n                        \"Event handled successfully!\"));\n    }\n}\n```\n\nThis will invoke your handler exactly like Fluxzero would in production, but entirely in memory and synchronously\nby default.\n\n\u003e ✅ We’ll explore more powerful testing patterns — including assertions on results, published commands, exceptions,\n\u003e and full event flows — later in this guide.\n\n---\n\n# Features\n\nThe java client supports all features of Fluxzero but also offers plenty of additional functionality.\nWhat follows is a summary of the most important features.\n\n## Table of Contents\n\n### Messaging\n\n- [Message Handling](#message-handling)\n- [Tracking Messages](#tracking-messages)\n- [Message Replays](#message-replays)\n- [Dynamic Dead Letter Queue (DLQ)](#dynamic-dead-letter-queue-dlq)\n- [Fluxzero Error Codes](#fluxzero-error-codes)\n- [Local Handlers](#local-handlers)\n- [Payload Validation](#payload-validation)\n- [User and Role-Based Access Control](#user-and-role-based-access-control)\n- [Scheduling](#scheduling)\n- [User-defined message logs](#user-defined-message-logs)\n- [Dispatching Messages](#dispatching-messages)\n- [Testing your Handlers](#testing-your-handlers)\n- [Handling Web Requests](#handling-web-requests)\n- [Serving Static Files](#serving-static-files)\n- [Handling WebSocket Messages](#handling-websocket-messages)\n- [Testing Web Endpoint Behavior](#testing-web-endpoint-behavior)\n- [Outbound Web Requests](#outbound-web-requests)\n- [Metrics Messages](#metrics-messages)\n\n### Domain Modeling, Persistence, and Search\n\n- [Domain Modeling](#domain-modeling)\n- [Applying Updates to Entities](#applying-updates-to-entities)\n- [Nested Entities](#nested-entities)\n- [Model Persistence](#model-persistence)\n- [Stateful Handlers](#stateful-handlers)\n- [Document Indexing and Search](#document-indexing-and-search)\n- [Tracking and Updating Documents](#tracking-and-updating-documents)\n\n### Data Handling and Serialization\n\n- [Protecting Sensitive Data](#protecting-sensitive-data)\n- [Serialization, Upcasting, and Downcasting](#serialization-upcasting-and-downcasting)\n- [Filtering Object Content](#filtering-object-content)\n- [Kotlin Support](#kotlin-support)\n\n### Configuration and Extensibility\n\n- [Configuring Application Properties](#configuring-application-properties)\n- [Parameter Injection with Custom Resolvers](#parameter-injection-with-custom-resolvers)\n- [Interceptors: Dispatching, Handling, and Batching](#interceptors-dispatching-handling-and-batching)\n- [Configuring Fluxzero](#configuring-fluxzero)\n- [WebSocketClient: Connect to the Fluxzero Runtime](#websocketclient-connect-to-the-fluxzero-runtime)\n- [Compatibility and Dependencies](#compatibility-and-dependencies)\n\n---\n\n## Message Handling\n\nFluxzero is centered around sending and receiving messages — such as __commands__, __events__, __queries__, and\n__web requests__. These messages can originate from your own application or any other client connected to the same\nFluxzero Runtime.\n\nHandlers are simply methods annotated with `@HandleCommand`, `@HandleEvent`, `@HandleQuery`, etc. Here’s a basic example\nof an event handler that dispatches a command to send a welcome email when a user is created:\n\n```java\nclass UserEventHandler {\n    @HandleEvent\n    void handle(CreateUser event) {\n        Fluxzero.sendCommand(\n                new SendWelcomeEmail(event.getUserProfile()));\n    }\n}\n```\n\nThis handler uses the static `sendCommand` method on Fluxzero, which works because the client is automatically\ninjected into the thread-local context before message handling begins. This approach eliminates the need to inject\n`Fluxzero` into every handler.\n\nTo receive that command, you would define a corresponding command handler:\n\n```java\nclass EmailCommandHandler {\n    @HandleCommand\n    void handle(SendWelcomeEmail command) {\n        //send welcome email to user\n    }\n}\n```\n\nHandlers can return a result (e.g. from queries or commands), which will automatically be published as a __Result__\nmessage and sent back to the originating client:\n\n```java\nclass UserQueryHandler {\n    @HandleQuery\n    UserProfile handle(GetUserProfile query) {\n        //return the user profile\n    }\n}\n```\n\nTo perform a query and wait for its result synchronously, you can use:\n\n```java\nclass UserEventHandler {\n    @HandleEvent\n    void handle(ResetPassword event) {\n        UserProfile userProfile = Fluxzero\n                .queryAndWait(new GetUserProfile(event.getUserId()));\n        // Perform reset using userProfile\n    }\n}\n```\n\n### Returning Futures\n\nHandler methods may also return a `CompletableFuture\u003cT\u003e` instead of a direct value. In that case, Fluxzero will\npublish the result to the result log once the future completes:\n\n```java\n\n@HandleQuery\nCompletableFuture\u003cUserProfile\u003e handle(GetUserProfile query) {\n    return userService.fetchAsync(query.getUserId());\n}\n```\n\nThis can be useful when calling asynchronous services (e.g. via HTTP or database drivers).\n\n\u003e ⚠️ **Caution:** While supported, returning a future means Flux will consider the message *handled* as soon as the\n\u003e handler returns the future—not when the future completes. This can be problematic if:\n\u003e\n\u003e - The operation must be guaranteed to complete (e.g. business-critical updates),\n\u003e - You rely on message acknowledgment for progress tracking,\n\u003e - Or you need back-pressure to avoid overloading the system.\n\u003e\n\u003e For most handlers, **synchronous return types are recommended**, or use `.join()` to explicitly block when necessary.\n\nThis pattern works best for non-critical side effects or purely read-oriented queries that can tolerate eventual\ncompletion.\n\n### Handler Matching and Passive Handlers\n\nFluxzero dynamically resolves which handler method(s) should respond to a message based on **handler specificity**\nand **message type**. This resolution behavior is consistent across all message types — including **commands**,\n**queries**, **events**, **errors**, **metrics**, and more.\n\n#### Most Specific Handler Wins (Per Class)\n\nIf multiple handler methods in the *same class* can handle a message (e.g. a `CreateUser` event), **only the most\nspecific method** is invoked. This allows you to define fallback methods at a more general level if no exact match is\nfound.\n\n```java\n\n@HandleEvent\nvoid handle(Object event) {\n    log.info(\"Generic fallback\");\n}\n\n@HandleEvent\nvoid handle(CreateUser event) {\n    log.info(\"Handling specific CreateUser event\");\n}\n```\n\n➡️ In this example, only the `handle(CreateUser)` method runs when a `CreateUser` event is dispatched.\n\n#### Multiple Handler Classes Are Invoked\n\nWhen the same message is handled by **different classes**, all eligible handlers are invoked independently.\n\n```java\npublic class BusinessHandler {\n    @HandleEvent\n    void handle(CreateUser event) {\n        // perform business logic\n    }\n}\n\npublic class LoggingHandler {\n    @HandleEvent\n    void logEvent(Object event) {\n        log.info(\"Observed event {}\", event);\n    }\n}\n```\n\n➡️ Here, both handlers are invoked when a `CreateUser` event is dispatched.\n\n#### Requests Prefer a Single Active Handler\n\nFor **request-like messages** — such as commands, queries and web requests — only **one handler** class is\nexpected to produce a response. If multiple are eligible, only the ones marked as **non-passive** will be considered for\nproducing the result.\n\nAdditional handlers may still be registered using `passive = true`, e.g., for logging, auditing, metrics, or outbox\npatterns.\n\n```java\npublic class UserHandler {\n    @HandleQuery\n    UserAccount handle(GetUser query) {\n        return userRepository.find(query.getUserId());\n    }\n}\n\npublic class QueryMetricsHandler {\n    @HandleQuery(passive = true)\n    void record(Object query) {\n        metrics.increment(\"queries.\" + query.getClass().getSimpleName());\n    }\n}\n```\n\n➡️ In this case:\n\n- The `handle(...)` method produces the result.\n- The `record(...)` method logs the query,\n\nBy combining **handler specificity**, **class-level isolation**, and the `passive` flag, Fluxzero gives you\nprecise control over how messages are processed — even across mixed concerns like logging, read models, business logic,\nand cross-cutting concerns.\n\n### Metadata Support\n\nMessages can include **metadata**, which are contextual key-value pairs (typically of a technical nature). These are\nuseful for passing user context, correlation IDs, request info, etc.\n\nFor example, sending a command with metadata:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.sendCommand(\n    new CreateUser(...),\n    Metadata.of(\"userAgent\", userAgent)\n);\n```\n[//]: # (@formatter:on)\n\nReading metadata in a handler is just as easy:\n\n```java\nclass UserCommandHandler {\n    @HandleCommand\n    void handle(CreateUser command, Metadata metadata) {\n        String userAgent = metadata.get(\"userAgent\");\n        ...\n    }\n}\n```\n\n## Tracking Messages\n\nFluxzero handles message dispatch asynchronously by default. When a message such as a command is published:\n\n1. It is sent to the Fluxzero Runtime.\n2. The Runtime logs the message and notifies all subscribed consumers.\n3. Consumers stream these messages to the relevant handler methods.\n\n### Default Consumer Behavior\n\nHandlers without an explicit `@Consumer` or matching custom `ConsumerConfiguration` are assigned according to the\nconfigured unconfigured-handler consumer mode. If no mode is configured explicitly, `fluxzero.defaults.version`\nselects the default behavior.\n\nFor defaults versions `2026.05.20` and newer, the default behavior is `perHandler`:\n\n```properties\nfluxzero.defaults.version=2026.05.20\n# equivalent explicit setting:\nfluxzero.tracking.unconfiguredHandlerConsumerMode=perHandler\n```\n\nWith this defaults version, Fluxzero creates an isolated default consumer per handler class. The generated consumer uses\nthe default consumer configuration for the message type as its template and is named after the application and handler\nclass, for example `my-app_MyHandler`.\n\nExisting applications without `fluxzero.defaults.version`, or with an older defaults version, keep the compatibility\ndefault: unconfigured handlers join the shared application default consumer for the message type. You can choose either\nbehavior explicitly:\n\n```properties\nfluxzero.tracking.unconfiguredHandlerConsumerMode=perHandler\n# or\nfluxzero.tracking.unconfiguredHandlerConsumerMode=defaultAppConsumer\n```\n\nFor example:\n\n```java\nclass MyHandler {\n    @HandleCommand\n    void handle(SomeCommand command) {\n        ...\n    }\n}\n```\n\nWith `perHandler`, this handler gets its own generated command consumer. With `defaultAppConsumer`, it joins the shared\ndefault command consumer. A matching custom `ConsumerConfiguration` or explicit `@Consumer` remains more specific and\ntakes precedence.\n\nThe practical difference is that `perHandler` gives each unconfigured handler its own tracking position and error\nisolation. With `defaultAppConsumer`, unconfigured handlers for the same message type move together through one shared\nconsumer, which preserves the original compatibility behavior for existing applications.\n\n### Custom Consumers with @Consumer\n\nYou can override the default behavior using the @Consumer annotation:\n\n```java\n\n@Consumer(name = \"MyConsumer\")\nclass MyHandler {\n    @HandleCommand\n    void handle(SomeCommand command) {\n        ...\n    }\n}\n```\n\nTo apply this to an entire package (and its subpackages), add a package-info.java file:\n\n```java\n@Consumer(name = \"MyConsumer\")\npackage com.example.handlers;\n```\n\n### Customizing Consumer Configuration\n\nYou can tune the behavior using additional attributes on the @Consumer annotation:\n\n```java\n\n@Consumer(name = \"MyConsumer\", threads = 2, maxFetchSize = 100, maxFetchBytes = 104_857_600)\nclass MyHandler {\n    @HandleCommand\n    void handle(SomeCommand command) {\n        ...\n    }\n}\n```\n\n- threads = 2: Two threads per application instance will fetch commands.\n- maxFetchSize = 100: Up to 100 messages fetched per request, helping apply backpressure.\n- maxFetchBytes = 104_857_600: Up to 100 MiB of serialized payload bytes fetched per request. Set `0` to disable the\n  byte limit. Omit it, or set `-1`, to inherit the global default.\n\nEach thread runs a **tracker**. If you deploy the app multiple times, Flux automatically load-balances messages across\nall available trackers.\n\nYou can set the global default with:\n\n```properties\nfluxzero.tracking.maxFetchBytes=104857600\n```\n\n### Default Consumer Settings\n\n| Setting       | Default Value             |\n|---------------|---------------------------|\n| threads       | 1                         |\n| maxFetchSize  | 1024                      |\n| maxFetchBytes | -1 (inherits 104857600 bytes / 100 MiB) |\n\nThese defaults are sufficient for most scenarios. You can always override them for improved performance or control.\n\n---\n\n## Message Replays\n\nFluxzero allows you to **replay past messages** by tracking from an earlier index in the message log.  \nThis is useful for:\n\n- Rebuilding projections or read models\n- Repairing missed or failed messages\n- Retrospectively introducing new functionality\n\nSince message logs — including **commands**, **events**, **errors**, etc. — are durably stored (with **events** retained\nindefinitely by default), replays are usually available.\n\n#### Replaying from the Past\n\nThe most common way to initiate a replay is to define a **new consumer** using the `@Consumer` annotation with a\n`minIndex`.\n\n```java\n\n@Consumer(name = \"auditReplay\", minIndex = 111677748019200000L)\npublic class AuditReplayHandler {\n\n    @HandleEvent\n    void on(CreateUser event) {\n        ...\n    }\n}\n```\n\nIn this example, the consumer `auditReplay` will process all events starting from **January 1st, 2024**.\n\n\u003e ℹ️ The `minIndex` value specifies the *inclusive* starting point for the message log.  \n\u003e Index values are based on time and can be derived using `IndexUtils`:\n\n```java\nlong index = IndexUtils.indexFromTimestamp(\n        Instant.parse(\"2024-01-01T00:00:00Z\"));\n// returns: 111677748019200000L\n```\n\nThis approach is perfect for:\n\n- Starting **fresh consumers** for replays\n- Bootstrapping projections without interfering with live handlers\n- Keeping logic encapsulated and isolated\n\n#### Resetting Existing Consumers\n\nIf you want to reset an existing consumer to an earlier point in the log:\n\n[//]: # (@formatter:off)\n```java\nlong replayIndex = 111677748019200000L;\nFluxzero.client()\n    .getTrackingClient(MessageType.EVENT)\n    .resetPosition(\"myConsumer\", replayIndex, Guarantee.STORED);\n```\n[//]: # (@formatter:on)\n\nThis restarts the consumer from the given index and causes old messages to be redelivered and reprocessed.\n\n\u003e ⚠️ Replaying over existing handlers may require extra caution (e.g. to avoid duplicating side effects).\n\n#### 🔁 Parallel Replays with `exclusive = false`\n\nSometimes you want to **re-use the same handler class** for both:\n\n- **Live processing** (e.g. default consumer)\n- **Replaying past messages** (e.g. rebuilding projections)\n\nTo achieve this, annotate the handler with `exclusive = false`. This tells Flux that the handler may participate in\n**multiple consumers simultaneously**:\n\n```java\n\n@Consumer(name = \"live\", exclusive = false)\npublic class OrderProcessor {\n    @HandleCommand\n    void handle(SendOrder command) {\n        //submit an order\n    }\n}\n```\n\nNow, register a **second consumer** at runtime for the **same handler** using a different tracking position:\n\n[//]: # (@formatter:off)\n```java\nfluxzeroBuilder.addConsumerConfiguration(\n    ConsumerConfiguration.builder()\n        .name(\"replay\") // A new consumer\n        .handlerFilter(handler -\u003e handler instanceof OrderProcessor) // same class\n        .minIndex(111677748019200000L) // Start of replay window\n        .maxIndex(111853279641600000L) // End of replay window\n        .build(),\n    MessageType.COMMAND\n);\n```\n[//]: # (@formatter:on)\n\nThis will spin up a **parallel tracker** that replays all commands since **2024-01-01T00:00:00Z**\nuntil **2024-02-01T00:00:00Z**, while the original `live` consumer continues uninterrupted. In this example, orders\nsent during the month of January 2024 will be resubmitted.\n\n\u003e ✅ This is ideal for **bootstrapping read models** or **running repair jobs** without affecting production flow\n\u003e or duplicating a handler class.\n\n---\n\n### Handling Failures by Replaying from the Error Log\n\nFluxzero automatically logs **all message handling errors** to a dedicated **error log**. This includes failures\nfor:\n\n- Commands\n- Queries\n- WebRequests\n- Schedule messages\n- Events (if a handler throws)\n- And more\n\nEach error message includes detailed **stack traces**, **metadata**, and most importantly, a **reference to the original\nmessage** that caused the failure.\n\n### Error Handling with `@HandleError`\n\nTo react to failures programmatically, define a handler method with the `@HandleError` annotation:\n\n```java\n\n@HandleError\nvoid onError(Throwable error) {\n    log.warn(\"Something went wrong!\", error);\n}\n```\n\nYou can inject the **failed message** using the `@Trigger` annotation:\n\n```java\n\n@HandleError\nvoid onError(Throwable error, @Trigger SomeCommand failedCommand) {\n    log.warn(\"Failed to process {}: {}\", failedCommand, error.getMessage());\n}\n```\n\n\u003e ℹ️ The trigger can be the payload, or a full `Message` or `DeserializingMessage`.\n\nYou can also **filter** error handlers by trigger type, message type, or originating consumer:\n\n```java\n\n@HandleError\n@Trigger(messageType = MessageType.COMMAND, consumer = \"my-app\")\nvoid retryFailedCommand(MyCommand failed) {\n    Fluxzero.sendCommand(failed);\n}\n```\n\n---\n\n## Dynamic Dead Letter Queue (DLQ)\n\nThe **error log is durable** and **replayable**, which means you can treat it as a **powerful, dynamic DLQ**.\n\nHere’s how:\n\n1. **Deploy a special consumer** that tracks the error log.\n2. Use `@Trigger` to access and inspect failed messages.\n3. Filter and replay failures based on time, payload type, or originating app.\n\n### Example: Retrying Failed Commands from the Past\n\nLet’s assume a bug caused command processing to fail in January 2024. The following setup reprocesses those failed\ncommands:\n\n```java\n\n@Consumer(name = \"command-dlq\",\n        minIndex = 111677748019200000L, maxIndexExclusive = 111853279641600000L) // 2024-01-01 to 2024-02-01 \nclass CommandReplayHandler {\n\n    @HandleError\n    @Trigger(messageType = MessageType.COMMAND)\n    void retry(MyCommand failed) {\n        Fluxzero.sendCommand(failed);\n    }\n}\n```\n\n\u003e ✅ The original `MyCommand` payload is restored and retried transparently.\n\n\u003e 🧠 You can combine this with logic that deduplicates, transforms, or **selectively suppresses** retries.\n\n### When to Use the Error Log\n\n| Use Case                       | How the Error Log Helps              |\n|--------------------------------|--------------------------------------|\n| 🛠 Fix a bug retroactively     | Replay failed commands from the past |\n| 🚧 Validate new handler logic  | Test it against real-world errors    |\n| 🔁 Retry transient failures    | Re-issue requests with retry logic   |\n| 🧹 Clean up or suppress errors | Filter out known false-positives     |\n\nThe error log acts as a **time-travel debugger** — it gives you full control over how and when to address failures, now\nor in the future.\n\n---\n\n### Fluxzero Error Codes\n\nSome SDK exceptions include a stable Fluxzero error code in their message and, where the exception type supports it,\nvia `getErrorCode()` and `getDocumentationUrl()`. The explanatory text can improve over time, but the code should\nremain stable so logs, support notes, and docs can all point at the same problem.\nOnce published, error codes are treated as part of the SDK support contract: new categories get new codes, existing\ncodes are not reused for a different meaning.\n\nTo keep repeated failures from flooding logs, the SDK renders the full multi-line explanation for the first 100\noccurrences of a code in a JVM. Later occurrences use a short message with the same error code and documentation URL.\n\n| Code          | Meaning                                      | Typical fix |\n|---------------|----------------------------------------------|-------------|\n| `FZ-SDK-0001` | No Fluxzero instance is available            | Create a Fluxzero instance and run the code inside `fluxzero.apply(...)`, or set `Fluxzero.applicationInstance`. |\n| `FZ-SDK-0002` | Request timed out while waiting for a result | Register/start the matching handler, check namespace/topic/routing, or use fire-and-forget for commands that do not return a result. |\n| `FZ-SDK-0003` | Handler invocation failed                    | Inspect the cause and stack trace; use `FunctionalException` for expected business rejections. |\n| `FZ-SDK-0004` | Response dispatch failed                     | Check response serialization, dispatch interceptors, and result/web-response log connectivity. |\n| `FZ-SDK-0005` | Thread interrupted while waiting             | Check caller shutdown, cancellation, or timeout behavior and decide whether to retry. |\n| `FZ-SDK-0006` | Message dispatch failed                      | Check dispatch interceptors, serialization, topic/namespace configuration, and client connectivity. |\n| `FZ-SDK-0007` | No `UserProvider` is configured              | Configure `Fluxzero#userProvider`, set `UserProvider.defaultUserProvider`, or remove `Message.addUser(...)`. |\n| `FZ-SDK-0008` | Tracking consumer configuration is invalid   | Make consumer names unique, register handlers before tracking starts, or add a matching `@Consumer`/`ConsumerConfiguration`. |\n| `FZ-SDK-0009` | Periodic schedule configuration is invalid   | Add a cron expression or positive delay to `@Periodic`, or disable it explicitly with `Periodic.DISABLED`. |\n| `FZ-SDK-0010` | Tracking failed during runtime               | Check the original cause, client/message-store connectivity, and whether shutdown or interruption was expected. |\n\nEach code links to `https://fluxzero.io/docs/errors#\u003ccode\u003e` in formatted SDK messages.\n\n---\n\n### Routing with `@RoutingKey`\n\nIn Fluxzero, routing is used to assign messages to **segments** using consistent hashing. This ensures that\nmessages about the same entity — for example, all events for a given `OrderId` — are always handled by the **same\nconsumer**, in **the correct order**.\n\nThis is critical when you're handling messages **in parallel**, but still want to ensure **per-entity consistency**.\n\n#### Declaring the Routing Key\n\nBy default, the routing key is derived from the message ID. But you can override this by annotating a field, getter, or\nmethod in your **payload class** with `@RoutingKey`.\n\n```java\npublic record ShipOrder(@RoutingKey OrderId orderId) {\n}\n```\n\nOr explicitly reference a nested property:\n\n```java\n\n@RoutingKey(\"customer/id\")\npublic record OrderPlaced(Customer customer) {\n}\n```\n\nThis instructs Flux to extract `customer.id` and use it as the routing key when publishing or consuming the message.\n\n#### Handler-Level Routing Keys\n\nIn more advanced cases, you may want to **override routing at the handler level**, regardless of how the message was\npublished. You can place `@RoutingKey(...)` on the handler method itself:\n\n```java\n\n@HandleEvent\n@RoutingKey(\"organisationId\")\nvoid handle(OrganisationUpdate event) {\n    // Will route based on organisationId in metadata or payload\n}\n```\n\n\u003e ⚠️ When doing this, be sure to declare your consumer with `ignoreSegment = true`. Otherwise, this routing override\n\u003e may cause certain messages to be silently skipped.\n\n```java\n\n@Consumer(ignoreSegment = true)\npublic class OrganisationHandler {\n    ...\n}\n```\n\n#### Metadata-Based Routing\n\nRouting keys can also be extracted from **message metadata**. For example:\n\n```java\n\n@RoutingKey(\"userId\")\npublic class AuditLogEntry { ...\n}\n```\n\nThis will first try to extract `userId` from metadata, and fall back to the payload if not present.\n\n#### Summary\n\n| Placement      | Meaning                                                               |\n|----------------|-----------------------------------------------------------------------|\n| Field/getter   | Use the property's value as routing key                               |\n| Class-level    | Use the named property in metadata or payload                         |\n| Handler method | Overrides routing key used during handling (requires `ignoreSegment`) |\n\n---\n\n## Local handlers\n\nFluxzero supports both asynchronous and local (synchronous) message handling. **Local handlers** process messages\nin the same thread that published them, bypassing the message dispatch infrastructure entirely. This typically results\nin faster response times and is ideal for simple or time-sensitive use cases.\n\nTo define a local handler, annotate the handler method, class, or its enclosing package with `@LocalHandler`:\n\n```java\n\n@LocalHandler(logMetrics = true)\npublic class SomeLocalHandler {\n    @HandleEvent\n    void handle(ApplicationStarted event) {\n        //do something\n    }\n}\n```\n\n\u003e 💡 Use logMetrics = true to track performance metrics even for local handlers.\n\n### Self-handling messages\n\nInstead of defining message handlers externally, you can embed handler logic directly in the message payload. This is\noften useful for queries or simple commands.\n\n```java\npublic class GetUserProfile {\n    String userId;\n\n    @HandleQuery\n    UserProfile handle() {\n        //fetch the user profile and return\n    }\n}\n```\n\nBy default, such handlers are treated as local. To process them asynchronously (i.e., as part of a consumer),\nannotate the class with `@TrackSelf`:\n\n```java\n\n@TrackSelf\n@Consumer(name = \"user-management\")\npublic class GetUserProfile {\n    String userId;\n\n    @HandleQuery\n    UserProfile handle() {\n        // Async handler\n    }\n}\n```\n\nWhen component-scanned (e.g., via Spring), `@TrackSelf` classes will be automatically discovered and registered.\nThis works even if the annotation is placed on an interface rather than the concrete class—allowing for reusable handler\npatterns.\n\nFor example, a generic command handler interface can be tracked and reused:\n\n```java\n\n@TrackSelf\npublic interface UserUpdate {\n    @HandleCommand\n    default void handle() {\n        //default behavior\n    }\n}\n```\n\nImplementations of this interface will then be handled asynchronously, using the configured consumer (or the default\none if unspecified).\n\n### Response typing with Request\u003cR\u003e\n\nFluxzero allows you to formalize the expected return type of commands and queries by implementing the `Request\u003cR\u003e`\ninterface. This lets the framework:\n\n- Infer the response type at runtime and during testing.\n- Validate handler methods at compile-time (e.g., `@HandleQuery` must return an R).\n- Simplify `queryAndWait(...)` or `sendCommand(...)` invocations.\n\nHere’s an example for a query:\n\n```java\n\n@Value\npublic class GetUserProfile implements Request\u003cUserProfile\u003e {\n    String userId;\n\n    @HandleQuery\n    UserProfile handle() {\n        return loadProfile(userId);\n    }\n}\n```\n\nNow, when calling this query, the return type is automatically known:\n\n```java\nUserProfile profile = Fluxzero.queryAndWait(new GetUserProfile(\"123\"));\n```\n\nWhen implementing Request\u003cR\u003e, the expected result type (R) is automatically inferred during testing and execution. This\nenables type-safe tests like:\n\n[//]: # (@formatter:off)\n```java\ntestFixture.whenQuery(new GetUserProfile(\"123\"))\n        .expectResult(profile -\u003e profile.getUserId().equals(\"123\"));\n```\n[//]: # (@formatter:on)\n\nIf a class implements `Request\u003cR\u003e`, Flux will use its declared generic type (R) to check that:\n\n- A compatible handler exists\n- The handler returns the correct result type\n- The correct response is expected during testing\n\n\u003e This pattern is highly recommended for queries, as it reduces boilerplate and improves correctness.\n\n---\n\n## Payload Validation\n\nFluxzero automatically validates incoming request payloads using a built-in\n[Jakarta Validation](https://jakarta.ee/specifications/bean-validation/3.1/) implementation. Hibernate Validator is\nnot required for normal SDK payload validation.\n\nThis includes support for:\n\n- standard Jakarta constraints such as `@NotNull`, `@NotBlank`, `@Size`, `@Pattern`, numeric constraints and temporal\n  constraints\n- Fluxzero convenience constraints such as `@Length`, `@Range`, `@URL`, `@UUID`, `@CreditCardNumber`, and\n  `@UniqueElements`\n- `@Valid` on nested objects and container/type-use validation for arrays, `List`, `Map`, `Optional`, and registered\n  custom value extractors\n- validation groups, group sequences, group conversion, and custom constraint validators\n- executable parameter and return-value validation\n- contextual method constraints such as `@AssertTrue` methods that inject parameters via Fluxzero's configured\n  `ParameterResolver`s\n- Constraint violations in command/query/webrequest payloads\n\nThe supported profile is aimed at SDK usage, not at being a drop-in provider for every Jakarta Validation TCK edge\ncase. XML mappings, `validation.xml`, CDI lifecycle integration, TraversableResolver reachability rules, and full\nExpression Language message evaluation are intentionally not supported.\n\nIf a constraint is violated, the handler method is **never called**. Instead, a `ValidationException`,\nis thrown before the handler is invoked.\n\n```java\n\npublic record CreateUser(@NotBlank String userId,\n                         @NotNull @Valid UserProfile profile) {\n}\n```\n\nConstraint methods on a payload may also request contextual parameters that the SDK's default validator can inject while\na message is being handled. It uses the same resolver set as handler method injection, so values such as `User`,\n`Message`, `DeserializingMessage`, `Metadata`, and custom resolver values can be used without reaching for thread-local\nhelpers.\n\n```java\npublic record CreateUser(@NotBlank String userId) {\n    @AssertTrue(message = \"Only admins may create admin users\")\n    boolean allowedBy(User user, Message message) {\n        return !userId.startsWith(\"admin-\") || user != null \u0026\u0026 user.hasRole(\"admin\");\n    }\n}\n```\n\nIf a constrained method declares parameters that cannot be resolved in the current validation context, Fluxzero skips\nthat method for that validation run. Keep required structural checks on fields or no-argument constraint methods when a\nrule must also apply outside message handling.\n\nYou can disable this validation entirely by calling:\n\n[//]: # (@formatter:off)\n```java\nDefaultFluxzero.builder().disablePayloadValidation();\n```\n[//]: # (@formatter:on)\n\nOf course, it is also easy to provide your own validation if desired. Use `replaceValidator(...)` on the\n`FluxzeroBuilder` to replace the configured validator. Convenience methods on `ValidationUtils` delegate to the\nvalidator of the current `Fluxzero` instance when one is bound, and otherwise fall back to\n`ValidationUtils.defaultValidator`.\n\n\u003e 💡 **Tip**: Fluxzero automatically correlates errors with the triggering message (e.g.: command or event).\n\u003e\n\u003e This means you don’t need to log extra context like the message payload or user ID — that information is already\n\u003e available in the audit trail in Fluxzero Runtime. This also encourages using **clear, user-facing error messages**\n\u003e without leaking internal details.\n\n---\n\n## User and Role-Based Access Control\n\nFluxzero allows you to restrict message handling based on the authenticated user's roles. This access control\nhappens **before** the message reaches the handler — similar to how payload validation is enforced.\n\nThere are several annotations for declaring user and role requirements:\n\n### `@RequiresAnyRole`\n\nUse this annotation to ensure that a handler is only invoked if the user has **at least one** of the\nspecified roles.\n\n```java\n\n@HandleCommand\n@RequiresAnyRole({\"admin\", \"editor\"})\nvoid handle(UpdateArticle command) { ...}\n```\n\n```java\n\n@RequiresAnyRole(\"admin\")\npublic record DeleteAccount(String userId) {\n}\n```\n\n### `@ForbidsAnyRole`\n\nThis annotation works the other way around — it **prevents** message handling if the user has any of the specified\nroles.\n\n```java\n\n@ForbidsAnyRole(\"guest\")\n@HandleCommand\nvoid handle(SensitiveOperation command) { ...}\n```\n\n### `@RequiresUser`\n\nEnsures that a message can only be handled if an **authenticated user** is present. If no user is found, the message is\nrejected with an `UnauthenticatedException`.\n\nThis is useful for requiring login in scenarios like user account updates, sensitive commands, or personal data access.\n\n```java\n\n@RequiresUser\n@HandleCommand\nvoid handle(UpdateProfile command) { ...}\n```\n\n### `@NoUserRequired`\n\nAllows a message to be processed even if **no authenticated user** is present — ideal for public APIs, or health checks.\n\n```java\n\n@NoUserRequired\n@HandleCommand\nvoid handle(SignUpUser command) { ...}\n```\n\n### `@ForbidsUser`\n\nPrevents message handling if an **authenticated user is present**. This is useful for restricting certain flows to\nunauthenticated users — such as registration endpoints, or guest-only operations.\n\n```java\n@ForbidsUser\n@HandleCommand\nvoid handle(SignUpAsGuest command) { ... }\n```\n\n---\n\n### Controlling Behavior on Unauthorized Access\n\nAll authorization annotations include an optional `throwIfUnauthorized()` property (default: `true`) that controls what\nhappens when access is denied:\n\n- If `throwIfUnauthorized = true`:\n    - If a user is required but **not present**, an `UnauthenticatedException` is thrown.\n    - If a user is present but **lacks the required roles**, an `UnauthorizedException` is thrown.\n\n- If `throwIfUnauthorized = false`:\n    - The handler or message is silently **skipped**, allowing delegation to other eligible handlers (if any).\n\nThis mechanism allows fine-grained control over how authentication and authorization failures are handled across your\nsystem.\n\n---\n\n### Role annotations support nesting and overrides\n\nFlux evaluates these annotations hierarchically. For example:\n\n- If `@RequiresAnyRole(\"admin\")` is placed on a **package**, it applies to all handlers and payloads in that package by\n  default.\n- You can override that requirement on a specific method or class using `@RequiresAnyRole(...)`, `@ForbidsAnyRole(...)`,\n  or `@NoUserRequired`.\n\n```java\n// package-info.java\n@RequiresUser\npackage com.myapp.handlers;\n```\n\n```java\n\n@NoUserRequired\n@HandleCommand\nvoid handle(PublicPing ping) { ...} // Overrides the package-level requirement\n```\n\nThis allows you to apply coarse-grained defaults and override them where needed.\n\n---\n\n### Enum-based role annotations (meta-annotations)\n\nFor more structure, you can define **custom annotations** using enums or strongly typed roles. For example:\n\n```java\npublic enum Role {\n    ADMIN, EDITOR, USER\n}\n```\n\n```java\n\n@RequiresAnyRole\n@Target({ElementType.TYPE, ElementType.METHOD})\npublic @interface RequiresRole {\n    Role[] value();\n}\n```\n\nYou can now annotate your handlers like this:\n\n```java\n\n@HandleCommand\n@RequiresRole(Role.ADMIN)\nvoid handle(DeleteAccount command) { ...}\n```\n\nFlux will interpret the enum-based annotation through the underlying `@RequiresAnyRole`.\n\n---\n\n### Best Practices\n\n- Use role annotations on **payload classes** to guarantee strict access checks in all environments.\n- Use them on **handlers** to control fallback behavior or define role-specific processing.\n- Set security defaults on **packages** or base classes, and override selectively.\n- Define **custom annotations** to avoid scattering string-based role declarations.\n\n---\n\n\u003e 💡 **Tip:** Access control is enforced transparently — there’s no need to log or repeat the user or message context.\n\u003e Flux automatically maintains correlation metadata between the original request and any errors, logs, or events that\n\u003e follow.\n\n---\n\n### Where does user info come from?\n\nUser roles are resolved by the configured `UserProvider`, which extracts the current user from message metadata (e.g.,\nauthentication tokens, headers, etc.). By default, Fluxzero uses a pluggable SPI to register this provider.\n\n\u003e 💡 You can override or mock this provider in tests using the TestFixture API.\n\n---\n\n### Providing Your Own User Logic\n\nYou can implement a custom `UserProvider` to extract users from headers, JWT tokens, cookies, etc.\n\n```java\npublic class MyUserProvider extends AbstractUserProvider {\n    public MyUserProvider() {\n        super(\"Authorization\", MyUser.class); // metadata key and user type\n    }\n\n    @Override\n    public User fromMessage(HasMessage message) {\n        if (message.toMessage() instanceof WebRequest request) {\n            return decodeToken(request.getHeader(\"Authorization\"));\n        }\n        return super.fromMessage(message);\n    }\n\n    private User decodeToken(String header) {\n        // Implement your own token decoding and verification logic here\n        return ...;\n    }\n}\n```\n\nThis allows you to inject meaningful, application-specific `User` objects into your handlers.\n\n---\n\n### System and Testing Support\n\nYour `UserProvider` implementation can also support testing and system behavior by implementing:\n\n- `getSystemUser()` — returns a default **system-level user**, used:\n    - as the default actor in tests,\n    - when publishing system-side effects (e.g. from scheduled handlers).\n- `getUserById(...)` — resolves a user by ID, used in test utilities like `fixture.whenCommandByUser(...)`.\n\nThis ensures your custom user logic is consistently applied, even in automated tests and background execution.\n\n---\n\n### 🔧 Registering your UserProvider\n\nTo enable your custom `UserProvider` (e.g., for authenticating users via headers or tokens), register it using Java's\nService Provider mechanism.\n\nCreate the file:\n\n```\nsrc/main/resources/META-INF/services/io.fluxzero.sdk.tracking.handling.authentication.UserProvider\n```\n\nList your implementation classes (one per line) in order of preference:\n\n```\ncom.example.authentication.SenderProvider\ncom.example.authentication.SystemUserProvider\n```\n\nFluxzero will automatically discover and register them at startup.\n\n\u003e 💡 If you're using Spring, your `UserProvider` can also be exposed as a bean — Fluxzero will pick it up\n\u003e automatically.\n\u003e\n\u003e ⚠️ However, tests **not using Spring** will not pick up the bean. For test scenarios or CLI usage, the SPI mechanism\n\u003e is still the easiest.\n\n---\n\n## Scheduling\n\nFluxzero allows scheduling messages for future delivery using the `MessageScheduler`.\n\nHere’s an example that schedules a termination event 30 days after an account is closed:\n\n```java\nclass UserLifecycleHandler {\n    @HandleEvent\n    void handle(AccountClosed event) {\n        Fluxzero.schedule(\n                new TerminateAccount(\n                        event.getUserId()),\n                \"AccountClosed-\" + event.getUserId(),\n                Duration.ofDays(30)\n        );\n    }\n\n    @HandleEvent\n    void handle(AccountReopened event) {\n        Fluxzero.cancelSchedule(\n                \"AccountClosed-\" + event.getUserId());\n    }\n\n    @HandleSchedule\n    void handle(TerminateAccount schedule) {\n        // Perform termination\n    }\n}\n```\n\nAlternatively, you can schedule commands using `scheduleCommand`:\n\n```java\nclass UserLifecycleHandler {\n    @HandleEvent\n    void handle(AccountClosed event) {\n        Fluxzero.scheduleCommand(\n                new TerminateAccount(\n                        event.getUserId()),\n                \"AccountClosed-\" + event.getUserId(),\n                Duration.ofDays(30));\n    }\n\n    @HandleEvent\n    void handle(AccountReopened event) {\n        Fluxzero.cancelSchedule(\"AccountClosed-\" + event.getUserId());\n    }\n}\n```\n\n### Periodic scheduling\n\nFluxzero supports recurring message schedules via the `@Periodic` annotation. This makes it easy to run tasks on a\nfixed interval or cron-based schedule — useful for polling, maintenance, background processing, and more.\n\nYou can apply `@Periodic` to either a `Schedule` payload or a `@HandleSchedule` method:\n\n```java\n\n@Periodic(delay = 5, timeUnit = TimeUnit.MINUTES)\npublic record RefreshData(String index) {\n}\n```\n\nThis schedules RefreshData to run every 5 minutes.\n\nOr, to use a cron expression:\n\n```java\n\n@Periodic(cron = \"0 0 * * MON\", timeZone = \"Europe/Amsterdam\")\n@HandleSchedule\nvoid weeklySync(PollData schedule) {\n    ...\n}\n```\n\nThis example triggers the `weeklySync` method every Monday at 00:00 in the Amsterdam time zone.\n\nSchedule handlers can also be local. Add `@LocalHandler` to a schedule handler, or put the `@HandleSchedule` method\ndirectly on the scheduled payload type without `@TrackSelf`. In those cases Fluxzero uses its `TaskScheduler` to trigger\nthe schedule in the current application, which makes `@HandleSchedule`/`@Periodic` useful as an alternative to Spring's\n`@Scheduled` for Fluxzero-aware local jobs.\n\n#### Behavior and advanced options\n\n- `@Periodic` works only for scheduled messages (see `@HandleSchedule`).\n- The schedule **automatically reschedules** itself after each invocation unless canceled.\n- You may:\n    - Return `void` or `null` to continue with the same schedule.\n    - Return a `Duration` or `Instant` to override the next deadline.\n    - Return a new payload or `Schedule` to customize the next cycle.\n- If an error occurs:\n    - The schedule continues by default (`continueOnError = true`).\n    - You may specify a fallback delay via `delayAfterError`.\n    - Throw `CancelPeriodic` from the handler to stop the schedule completely.\n- To prevent startup activation, use `@Periodic(autoStart = false)`.\n- `initialDelay = -1` means no explicit initial delay. With compatibility defaults, Fluxzero treats that implicit value\n  as `0` to preserve immediate autostart. With `fluxzero.defaults.version \u003e= 2026.05.21` or\n  `fluxzero.scheduling.periodic.useDefaultInitialDelay=true`, fixed-delay schedules first run after `delay` and cron\n  schedules first run at the next cron match. For example, `@Periodic(delay = 60_000)` first runs after 60 seconds,\n  while `@Periodic(cron = \"*/5 * * * *\")` first runs at the next five-minute boundary. Set `initialDelay = 0` when the\n  first run should be immediate.\n- The schedule ID defaults to the class name, but can be customized with `scheduleId`.\n\nHere's an example of robust polling with error fallback:\n\n```java\n\n@Periodic(delay = 60, timeUnit = TimeUnit.MINUTES, delayAfterError = 10)\n@HandleSchedule\nvoid pollExternalService(PollTask pollTask) {\n    try {\n        externalService.fetchData();\n    } catch (Exception e) {\n        log.warn(\"Polling failed, will retry in 10 minutes\", e);\n        throw e;\n    }\n}\n```\n\nIn this case:\n\n- The task runs every hour normally.\n- If it fails, it retries after 10 minutes.\n- It resumes the original schedule if the next invocation succeeds.\n\n---\n\n## User-defined message logs\n\nFluxzero supports **custom message logs** in addition to built-in ones like commands, events, and queries.\n\nMost applications won't need custom message logs — but they can be very useful in advanced scenarios:\n\n- To **track external systems or integrations**, while keeping the main event log clean.\n- To **store batches of updates** for external consumers that poll infrequently.\n- To **segment logic** or apply different retention guarantees per topic.\n\nFluxzero lets you publish and handle custom messages by assigning them to **user-defined topics**. These messages\nare written to their own durable logs and can be tracked just like commands or events.\n\n### Custom Handlers\n\nTo receive messages from a custom log, annotate your method with `@HandleCustom` and specify the topic name:\n\n```java\n\n@HandleCustom(\"metering-points\")\nvoid on(MeteringPoint event) {\n    log.info(\"Metering point: {}\", event);\n}\n```\n\nLike other handlers, this can be:\n\n- **Stateless or stateful**\n- Attached to a **custom consumer**\n- Used to **return a result** if the message is a request\n- **Passive**, meaning it won’t emit result messages\n\n\u003e ✅ Custom logs are fully integrated with Flux tracking and delivery infrastructure.\n\n### 📬 Publishing to a Custom Log\n\nYou can publish messages manually to any custom topic:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.get()\n    .customGateway(\"third-party-events\")\n    .sendAndForget(new AuditEntry(\"User login\"));\n```\n[//]: # (@formatter:on)\n\nThis makes it easy to introduce new asynchronous workflows, specialized event types, or low-frequency control signals.\n\n### 🧹 Setting Retention Time\n\nEach message log in Flux retains messages independently. You can configure how long messages in your **custom log**\nshould be retained:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.get()\n    .customGateway(\"third-party-events\")\n    .setRetentionTime(Duration.ofDays(90));\n```\n[//]: # (@formatter:on)\n\nRetention can also be set for built-in logs like commands or results — though it's advisable to configure it only\nfor custom topics.\n\n---\n\n## Dispatching Messages\n\nFluxzero provides a unified and transparent way to send messages of all types—**commands**, **events**,\n**queries**, **schedules**, **web requests**, **metrics**, and more. All message types are routed through a shared\ndispatch\ninfrastructure, with built-in support for:\n\n- **Location transparency**: Message destinations are resolved dynamically. Handlers may live within the current\n  process or in a remote application across the globe—as long as it's connected to the same Fluxzero Runtime.\n- **Dispatch interceptors** for metadata enrichment, authorization, logging, or suppression.\n- **Local-first handling**: If a handler exists in the local process, it will receive the message immediately.\n- **Automatic forwarding** to the Fluxzero Runtime when no local handlers consume the message.\n- **Serialization and correlation**: All messages are serialized, tagged with tracing data, and routed by type and\n  topic.\n\n### Sending a Message\n\nThe easiest way to dispatch messages is via static methods on the `Fluxzero` class:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.sendCommand(new CreateUser(\"Alice\"));  // Asynchronously send a command\nFluxzero.queryAndWait(new GetUserById(\"user-123\"));  // Query and block for response\nFluxzero.publishEvent(new UserSignUp(...));  // Fire-and-forget event\nFluxzero.schedule(new RetryPayment(...), Duration.ofMinutes(5));  // Delayed message\n```\n[//]: # (@formatter:on)\n\nEach message can also include optional metadata:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.sendCommand(new CreateUser(\"Bob\"),\n                          Metadata.of(\"source\",\"admin-ui\"));\n```\n[//]: # (@formatter:on)\n\n\u003e ⚠️ Messages are **not routed to a specific destination**. Instead, any number of matching handlers may receive the\n\u003e message, whether they run locally or remotely. Fluxzero abstracts the transport so that handler location is\n\u003e irrelevant.\n\nFor a deeper look at message handling, see the [Message Handling](#message-handling) section.\n\n---\n\n### Commands\n\nCommands are used to trigger state changes or domain logic. They may return a result or be fire-and-forget.\n\n**Send and forget:**\n\n[//]: # (@formatter:off)\n```java\nFluxzero.sendAndForgetCommand(new CreateUser(\"Alice\"));\n```\n[//]: # (@formatter:on)\n\n**Send and wait (async or blocking):**\n\n[//]: # (@formatter:off)\n```java\nCompletableFuture\u003cUserId\u003e future \n        = Fluxzero.sendCommand(new CreateUser(\"Bob\"));\n\nUserId id = Fluxzero.sendCommandAndWait(\n        new CreateUser(\"Charlie\"));\n```\n[//]: # (@formatter:on)\n\n---\n\n### Queries\n\nQueries retrieve data from read models or projections.\n\n**Async:**\n\n[//]: # (@formatter:off)\n```java\nCompletableFuture\u003cUserProfile\u003e result = Fluxzero.query(new GetUserProfile(\"user123\"));\n```\n[//]: # (@formatter:on)\n\n**Blocking:**\n\n[//]: # (@formatter:off)\n```java\nUserProfile profile = Fluxzero.queryAndWait(new GetUserProfile(\"user456\"));\n```\n[//]: # (@formatter:on)\n\n---\n\n### Events\n\nEvents can be published via:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.publishEvent(new UserLoggedIn(\"user789\"));\n```\n[//]: # (@formatter:on)\n\nBy default:\n\n- ✅ **Events are persisted** in the global event log, making them available for downstream processing, projections, or\n  analytics.\n- ⚠️ **Exception:** If a **local handler** exists the event will not be forwarded or stored, unless\n  `@LocalHandler(logMessage = true)`.\n\n\u003e For aggregate-related domain events, use `Entity#apply(...)` instead. This ensures the event is applied to the entity\n\u003e and conditionally published and logged, depending on the aggregate configuration.\n\n---\n\n### Schedules\n\nYou can schedule messages or commands for later delivery:\n\n[//]: # (@formatter:off)\n```java\n// Schedule a message to be handled in 5 minutes using @HandleSchedule\nFluxzero.schedule(new ReminderFired(), Duration.ofMinutes(5));\n\n// Fire a periodic schedule every hour\nFluxzero.schedulePeriodic(new PollExternalApi());\n```\n[//]: # (@formatter:on)\n\n---\n\n### Web Requests\n\nSend an outbound HTTP call via the proxy mechanism in Fluxzero Runtime:\n\n[//]: # (@formatter:off)\n```java\nWebRequest request = WebRequest\n        .get(\"https://api.example.com/data\").build();\nWebResponse response = Fluxzero.get()\n        .webRequestGateway().sendAndWait(request);\n```\n[//]: # (@formatter:on)\n\n---\n\n### Metrics\n\nYou can publish custom metrics to the Fluxzero Runtime:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.publishMetrics(\n        new SystemLoadMetric(cpu, memory));\n```\n[//]: # (@formatter:on)\n\n---\n\n### What Happens After You Dispatch?\n\nOnce you dispatch a message using any of the above methods, Flux goes through the following pipeline:\n\n#### 1. **Dispatch Interceptors (Pre-Serialization)**\n\nBefore the message is serialized, all applicable `DispatchInterceptor`s are given a chance to:\n\n- Inject metadata (e.g. correlation IDs, timestamps)\n- Modify or validate the message\n- Suppress or block dispatch entirely\n\n#### 2. **Local Handlers**\n\nIf any handlers (e.g. `@HandleCommand`, `@HandleQuery`) are registered for this message type and topic, they will be\ninvoked **locally**.\n\n- If the handler is annotated with `@LocalHandler(logMessage = true)`, the message is still forwarded to the \n  Fluxzero Runtime.\n- If the handler **fully consumes** the message, it won't be forwarded.\n\n#### 3. **Serialization**\n\nThe message is converted to a `SerializedMessage`, typically using Jackson. This is where versioning and up/downcasting\nmay apply.\n\n#### 4. **Dispatch Interceptors (Post-Serialization)**\n\nAfter serialization, interceptors may again modify the message—for example, to inject correlation headers based on the\nserialized form.\n\n#### 5. **Forwarding to Fluxzero Runtime**\n\nIf no local handler consumes the message, it is published to the Fluxzero Runtime via the configured `Client` (e.g.\n`WebSocketClient`).\n\n- Topics and routing are determined by message type and metadata\n- Runtime-side logic (like deduplication, retries, rate limits) may apply\n\n---\n\n### Request Timeouts\n\nThe `@Timeout` annotation allows developers to specify how long Flux should wait for a **command** or **query** to\ncomplete when using synchronous (`sendAndWait`) APIs.\n\nThis is especially useful for time-sensitive interactions where you want to fail fast or have specific SLA expectations\nfor certain request types.\n\n### Usage\n\nApply `@Timeout` to a **payload class** (typically a command or query):\n\n[//]: # (@formatter:off)\n```java\n@Timeout(value = 3, timeUnit = TimeUnit.SECONDS)\npublic record CalculatePremium(UserProfile profile) implements Request\u003cBigDecimal\u003e {}\n```\n[//]: # (@formatter:on)\n\nWhen this message is sent using a blocking gateway call, the configured timeout is respected:\n\n[//]: # (@formatter:off)\n```java\nBigDecimal result = Fluxzero\n        .sendAndWait(new CalculatePremium(user));\n```\n[//]: # (@formatter:on)\n\nIf the timeout elapses before a response is received, a `TimeoutException` is thrown.\n\n### Notes\n\n- The timeout only applies to blocking calls (e.g., `sendAndWait`). If you use non-blocking `send(...)` methods that\n  return a `CompletableFuture`, **no timeout is enforced** unless you manually attach one:\n\n  [//]: # (@formatter:off)\n  ```java\n  CompletableFuture\u003cBigDecimal\u003e future \n        = Fluxzero.send(new CalculatePremium(user));\n  future.orTimeout(3, TimeUnit.SECONDS);\n  ```\n  [//]: # (@formatter:on)\n\n- The default timeout for blocking operations (when `@Timeout` is not present) is **1 minute**.\n- To configure timeouts for `WebRequest` calls, use `WebRequestSettings#timeout`.\n\n---\n\n## Testing your Handlers\n\nFluxzero comes with a flexible, expressive testing framework based on the given-when-then pattern. This enables\nwriting behavioral tests for your handlers without needing to mock the infrastructure.\n\nHere’s a basic example:\n\n```java\nTestFixture testFixture = TestFixture.create(new UserEventHandler());\n\n@Test\nvoid newUserGetsWelcomeEmail() {\n    testFixture.whenEvent(new CreateUser(userId, myUserProfile))\n            .expectCommands(new SendWelcomeEmail(myUserProfile));\n}\n```\n\nThis test ensures that when a `CreateUser` event occurs, a `SendWelcomeEmail` command is issued by the handler.\n\n### Testing complete workflows\n\nYou can test full workflows across multiple handlers:\n\n```java\nTestFixture fixture = TestFixture.create(new UserCommandHandler(), new UserEventHandler());\n\n@Test\nvoid creatingUserTriggersEmail() {\n    fixture.whenCommand(new CreateUser(userProfile))\n            .expectCommands(new SendWelcomeEmail(userProfile));\n}\n```\n\nUse `expectOnlyCommands()` to assert that **only** the expected command was issued:\n\n[//]: # (@formatter:off)\n```java\nfixture.whenCommand(new CreateUser(userProfile))\n       .expectOnlyCommands(new SendWelcomeEmail(userProfile));\n```\n[//]: # (@formatter:on)\n\nYou can also match by class, predicate, or Hamcrest matcher:\n\n[//]: # (@formatter:off)\n```java\nfixture.whenCommand(new CreateUser(userProfile))\n       .expectCommands(SendWelcomeEmail.class, \n                       isA(AddUserToOrganization.class));\n```\n[//]: # (@formatter:on)\n\n### Chained expectations\n\nMultiple expectations can be chained to test the full sequence of events and commands:\n\n[//]: # (@formatter:off)\n```java\nfixture.whenCommand(new CreateUser(userProfile))\n       .expectCommands(new SendWelcomeEmail(userProfile))\n       .expectEvents(new UserStatsUpdated(...));\n```\n[//]: # (@formatter:on)\n\nYou can also chain multiple **inputs** using `.andThen()` to simulate a sequence of events, commands, or queries:\n\n[//]: # (@formatter:off)\n```java\nfixture.whenCommand(new CreateUser(userProfile))\n       .expectCommands(new SendWelcomeEmail(userProfile))\n       .andThen()\n       .whenQuery(new GetUser(userId))\n       .expectResult(userProfile);\n```\n[//]: # (@formatter:on)\n\nThis example first triggers a `CreateUser` command, expects a `SendWelcomeEmail` event, and then issues a `GetUser`\nquery,\nasserting that it returns the expected result.\n\n### Using givenXxx() for preconditions\n\nUse `givenCommands`, `givenEvents`, etc., to simulate preconditions:\n\n[//]: # (@formatter:off)\n```java\nfixture.givenCommands(new CreateUser(userProfile), new ResetPassword(...))\n       .whenCommand(new UpdatePassword(...))\n       .expectEvents(UpdatePassword.class);\n```\n[//]: # (@formatter:on)\n\n### Providing External JSON Files\n\nTest fixtures support loading inputs from external JSON resources. This allows you to keep your tests clean and reuse\nstructured input data.\n\nAny `givenXyz(...)`, `whenXzy(...)`, or `expectXyz(...)` method argument that is a `String` ending with `.json` will be\ninterpreted as a **classpath resource path**, and deserialized accordingly.\n\nFor example:\n\n[//]: # (@formatter:off)\n```java\nfixture.givenCommands(\"create-user.json\")\n    .whenQuery(new GetUser(userId))\n    .expectResult(\"user-profile.json\");\n```\n[//]: # (@formatter:on)\n\nIf your test class is in the `org.example` package, this will resolve to `/org/example/create-user.json` in the\nclasspath, unless the JSON path is absolute (starts with `/`), e.g.:\n\n```java\nfixture.givenCommands(\"/users/create-user.json\");\n```\n\n#### Class Resolution with `@class`\n\nEach JSON file must include a `@class` property to enable deserialization:\n\n```json\n{\n  \"@class\": \"org.example.CreateUser\",\n  \"userId\": \"3290328\",\n  \"email\": \"foo.bar@example.com\"\n}\n```\n\nIf your classes or packages are annotated with `@RegisterType`, you can use **simple class names**:\n\n```json\n{\n  \"@class\": \"CreateUser\"\n}\n```\n\nOr partial paths:\n\n```json\n{\n  \"@class\": \"example.CreateUser\"\n}\n```\n\n\u003e This enables readable and concise references while still resolving to the correct type.\n\nFor Kotlin projects, use `kapt` to run the Java annotation processor. Because Kotlin typically does not use\n`package-info.java`, you can register a whole package with a marker type:\n\n```kotlin\n@RegisterType(root = \"com.example.messages\")\nobject TypeRegistryMarker\n```\n\n#### Inheriting from Other JSON Files\n\nJSON resources can **extend** other resources using the `@extends` keyword:\n\n```json\n{\n  \"@extends\": \"create-user.json\",\n  \"details\": {\n    \"lastName\": \"Johnson\"\n  }\n}\n```\n\nThis will recursively merge the referenced file (`/org/example/create-user.json`) with the current one, allowing you\nto override or augment deeply nested structures.\n\n\u003e 🧠 This is especially useful for composing test scenarios with shared defaults or inheritance-like setups.\n\n---\n\n### Adding or asserting metadata\n\nWrap your payload in a Message to add or assert metadata:\n\n```java\n\n@Test\nvoid newAdminGetsAdditionalEmail() {\n    testFixture.whenCommand(new Message(new CreateUser(...),\n    Metadata.of(\"roles\", Arrays.asList(\"Customer\", \"Admin\"))))\n        .expectCommands(new SendWelcomeEmail(...),\n    new SendAdminEmail(...));\n}\n```\n\n### Result and exception assertions\n\nYou can assert the result returned by a command or query:\n\n[//]: # (@formatter:off)\n```java\nfixture.givenCommands(new CreateUser(userProfile))\n       .whenQuery(new GetUser(userId))\n       .expectResult(userProfile);\n```\n[//]: # (@formatter:on)\n\nTo assert an exception:\n\n[//]: # (@formatter:off)\n```java\nfixture.givenCommands(new CreateUser(userProfile))\n        .whenCommand(new CreateUser(userProfile))\n        .expectExceptionalResult(IllegalCommandException.class);\n```\n[//]: # (@formatter:on)\n\n### User-aware tests\n\nYou can also simulate a command from a specific user:\n\n[//]: # (@formatter:off)\n```java\nvar user = new MyUser(\"pete\");\n\nfixture.whenCommandByUser(user, \"confirm-user.json\")\n       .expectExceptionalResult(UnauthorizedException.class);\n```\n[//]: # (@formatter:on)\n\nYou can also pass a user ID string directly instead of a full User object. The test fixture will resolve it using the\nconfigured `UserProvider` (by default loaded via Java's `ServiceLoader`):\n\n[//]: # (@formatter:off)\n```java\nfixture\n    .givenCommands(\"create-user-pete.json\")\n    .whenCommandByUser(\"pete\", \"confirm-user.json\")\n    .expectExceptionalResult(UnauthorizedException.class);\n```\n[//]: # (@formatter:on)\n\nIn this example, the string \"pete\" is resolved to a `User` instance using the active `UserProvider`, and the test\nasserts\nthat the confirmation is unauthorized.\n\n### Verifying side effects\n\nUse `expectThat()` or `expectTrue()` to assert custom logic or verify interactions (e.g., using Mockito):\n\n[//]: # (@formatter:off)\n```java\nfixture.whenCommand(\"create-user-pete.json\")\n       .expectThat(fc -\u003e Mockito.verify(emailService).sendEmail(...));\n```\n[//]: # (@formatter:on)\n\n### Triggering side effects manually\n\nUse `whenExecuting()` to test code outside of message dispatching, like HTTP calls:\n\n[//]: # (@formatter:off)\n```java\nfixture.whenExecuting(fc -\u003e httpClient.put(\"/user\", \"/users/user-profile-pete.json\"))\n       .expectEvents(\"create-user-pete.json\");\n```\n[//]: # (@formatter:on)\n\n### Asynchronous tests\n\nBy default, `TestFixture.create(...)` creates synchronous fixtures where handlers are executed locally in the same\nthread\nthat publishes the message. This provides fast, deterministic behavior ideal for most unit tests.\n\nHowever, in production your handlers are typically dispatched asynchronously by consumers running on separate threads.\nTo better simulate this behavior in tests — especially when testing event-driven flows or stateful consumers — you can\nuse an asynchronous fixture instead.\n\n```java\nTestFixture fixture = TestFixture.createAsync(new MyHandler(), MyStatefulHandler.class);\n```\n\nThis ensures that:\n\n- Handlers are tracked via the same consumer infrastructure used in production.\n- Behavior involving asynchronous dispatch, retries, or stateful models is tested realistically.\n- Eventual consistency is respected (e.g., expect...() calls will wait for outcomes to materialize).\n\n\u003e **Note:** Handlers annotated with `@LocalHandler` are executed synchronously, even in async fixtures, just as they\n\u003e would in production.\n\n### Using Test Fixtures in Spring\n\nFluxzero provides seamless integration with Spring Boot for testing. You can inject a `TestFixture` directly:\n\n```java\n\n@SpringBootTest\nclass AsyncAppTest {\n\n    @Autowired\n    TestFixture fixture;\n\n    @Test\n    void testSomething() {\n        fixture.whenCommand(\"commands/my-command.json\")\n                .expectEvents(\"events/expected-event.json\");\n    }\n}\n```\n\n- ✅ **Spring Boot**: No manual setup needed—`TestFixture` is auto-configured.\n- ⚠️ **Spring Core (non-Boot)**: Manually import the test configuration:\n\n  ```java\n  @Import(FluxzeroTestConfig.class)\n  ```\n\n  This ensures the `TestFixture` and related infrastructure are available in the Spring context.\n\n---\n\n#### Switching to Synchronous Mode\n\nBy default, the injected fixture is **asynchronous**. To use a **synchronous** fixture instead:\n\n##### Globally via `application.properties`:\n\n```properties\nfluxzero.test.sync=true\n```\n\n##### Or per test class:\n\n```java\n\n@TestPropertySource(properties = \"fluxzero.test.sync=true\")\n@SpringBootTest\nclass SyncAppTest {\n\n    @Autowired\n    TestFixture fixture;\n\n    // test logic...\n}\n```\n\n### Testing schedules\n\nFluxzero’s scheduling engine makes it easy to test time-based workflows. Scheduled messages are handled just\nlike any other message, except they are delayed until their due time.\n\nUse the `TestFixture` to simulate the passage of time and trigger scheduled actions. Here’s a typical example:\n\n```java\nTestFixture testFixture = TestFixture.create(new UserCommandHandler(), new UserLifecycleHandler());\n\n@Test\nvoid accountIsTerminatedAfterClosing() {\n    testFixture\n            .givenCommands(new CreateUser(myUserProfile),\n                           new CloseAccount(userId))\n            .whenTimeElapses(Duration.ofDays(30))\n            .expectEvents(new AccountTerminated(userId));\n}\n```\n\nIn this test:\n\n- We schedule the AccountTerminated message as a result of the CloseAccount command.\n- Then we simulate that 30 days have passed using whenTimeElapses(...).\n- Finally, we verify that the expected AccountTerminated event was published.\n\nYou can also test cancellation logic:\n\n```java\n\n@Test\nvoid accountReopeningCancelsTermination() {\n    testFixture\n            .givenCommands(new CreateUser(myUserProfile),\n                           new CloseAccount(userId),\n                           new ReopenAccount(userId))\n            .whenTimeElapses(Duration.ofDays(30))\n            .expectNoEventsLike(AccountTerminated.class);\n}\n```\n\nIf needed, you can advance time to an absolute timestamp using:\n\n[//]: # (@formatter:off)\n```java\nfixture.whenTimeAdvancesTo(Instant.parse(\"2050-12-31T00:00:00Z\"));\n```\n[//]: # (@formatter:on)\n\nThis is especially useful for workflows tied to specific deadlines or calendar dates.\n\n---\n\n## Handling Web Requests\n\nFluxzero supports first-class **WebRequest handling** via the `@HandleWeb` annotation and its HTTP-specific\nvariants such as `@HandleGet`, `@HandlePost`, `@HandleDelete`, etc.\n\nInstead of exposing a public HTTP server per application, Fluxzero uses a central Web Gateway that **proxies all external\nHTTP(S) and WebSocket traffic into the Runtime as `WebRequest` messages**. These messages are:\n\n- **Logged** for traceability and auditing\n- **Routed to client applications** using the same handler system as for commands, events, and queries\n- **Handled by consumer applications** which return a `WebResponse`\n\n#### Why This Design?\n\nThis architecture enables several key benefits:\n\n- ✅ **Zero exposure**: client apps do not require a public-facing HTTP server and are thus *invisible* to attackers\n- ✅ **Back-pressure support**: applications control load by polling their own messages\n- ✅ **Audit-friendly**: every incoming request is automatically logged and correlated to its response\n- ✅ **Multiple consumers possible**: multiple handlers can react to a WebRequest, though typically only one produces the\n  response (others use `passive = true`)\n\n#### Example\n\n```java\n\n@HandleGet(\"/users\")\npublic List\u003cUserAccount\u003e listUsers() {\n    return userService.getAllUsers();\n}\n```\n\nThis will match incoming GET requests to `/users` and return a list of users. The response is published back as a\n`WebResponse`.\n\nYou can use the general `@HandleWeb` if you want to match multiple paths or methods or define a custom HTTP method:\n\n```java\n\n@HandleWeb(value = \"/users/{userId}\", method = {\"GET\", \"DELETE\"})\npublic CompletableFuture\u003c?\u003e handleUserRequest(WebRequest request, @PathParam String userId) {\n    return switch (request.getMethod()) {\n        case \"GET\" -\u003e Fluxzero.query(new GetUser(userId));\n        case \"DELETE\" -\u003e Fluxzero.sendCommand(new DeleteUser(userId));\n        default -\u003e throw new UnsupportedOperationException();\n    };\n}\n```\n\n\u003e 💡 **Tip:** To match any HTTP method without listing them explicitly, use `HttpRequestMethod.ANY`.\n\u003e This is equivalent to `\"*\"` and will match all incoming requests for the given path.\n\n```java\n\n@HandleWeb(value = \"/users/{userId}\", method = HttpRequestMethod.ANY)\npublic CompletableFuture\u003c?\u003e handleAllUserMethods(\n        WebRequest request, @PathParam String userId) {\n    // Handle any method (GET, POST, DELETE, etc.)\n    ...\n}\n```\n\n#### Suppressing a Response\n\nIf you want to listen to a WebRequest without generating a response (e.g. for auditing or monitoring), use\n`passive = true`:\n\n```java\n\n@HandlePost(value = \"/log\", passive = true)\npublic void log(WebRequest request) {\n    logService.store(request);\n}\n```\n\n#### Dynamic Path Parameters\n\nUse the `@PathParam` annotation to extract dynamic segments from the URI path into handler method parameters:\n\n```java\n\n@HandleGet(\"/users/{id}\")\npublic UserAccount getUser(@PathParam String id) {\n    return userService.get(id);\n}\n```\n\nIf the `value` is left empty, the framework will use the parameter name (`id` in this case).\n\n#### Route Matching Specificity\n\nRoute patterns support literal segments, `{name}` path parameters, `{name:regex}` constrained parameters, and `*`\nwildcards. A non-final `*` matches within a single path segment, so routes like `/meters/*/readings` are valid. A final\n`*` matches the rest of the path and is mainly useful for static or SPA fallback routes.\nOptional path fragments can be wrapped in square brackets, for example `/users[/{id}]` matches both `/users` and\n`/users/42`.\nTrailing slashes on non-root paths are ignored, so `/users` and `/users/` match the same route.\n\nWhen multiple web handlers match the same request, Fluxzero selects the most specific route: literal segments win over\npath parameters, constrained parameters win over plain parameters, and wildcard/catch-all routes are treated as\nfallbacks. For example, `/api/projects/active` wins over `/api/projects/{id:[a-z]+}`, which wins over\n`/api/projects/{id}`, which wins over `/api/projects/*`.\n\n#### Automatic HEAD and OPTIONS\n\nFluxzero can derive common HTTP helper responses from your declared routes:\n\n- A `HEAD` request can be routed to the matching `GET` handler when no explicit `@HandleHead`, `@HandleWeb(method =\n  \"HEAD\")`, or `ANY` route matches. The response keeps the GET status and headers but has no body.\n- An `OPTIONS` request can return `204 No Content` with an `Allow` header when no explicit `@HandleOptions`,\n  `@HandleWeb(method = \"OPTIONS\")`, or `ANY` route matches.\n\nExplicit handlers always win, including wildcard handlers registered in another handler class in the same application.\nIn multi-service setups, another application can still provide the explicit `HEAD` or `OPTIONS` handler. Disable the\nderived helpers on the route that should not claim them:\n\n```java\n@HandleGet(value = \"/meters/{id}/readings\", autoHead = false, autoOptions = false)\npublic MeterReadings readings(@PathParam String id) {\n    return service.readings(id);\n}\n```\n\nWhen requests enter through `fluxzero-proxy`, configured and allowed CORS preflight requests are answered by the proxy\nbefore they reach the runtime. The automatic `OPTIONS` helper only applies to `OPTIONS` requests that are actually\nforwarded as `WebRequest`s.\n\n#### API Documentation and OpenAPI\n\nFluxzero can extract a format-neutral API documentation catalog from web handlers and render it as OpenAPI 3.0.1 JSON.\nOpenAPI 3.1 can be enabled when needed.\nMost route, parameter, request body, and response type information is inferred from existing `@Handle...`, `@Path`,\nand parameter annotations:\n\n```java\nApiDocCatalog catalog = ApiDocExtractor.extract(MeterEndpoint.class);\nString openApiJson = OpenApiRenderer.renderPrettyJson(\n        catalog, new OpenApiOptions(\"Meters API\", \"1.0.0\", \"\", List.of(\"https://api.example.com\")));\n```\n\nWhen annotation processing is enabled, Fluxzero also generates `META-INF/fluxzero/openapi.json` during compilation if\nthe module contains web handlers opted in with `@ApiDoc`. Configure global document metadata with javac options such as\n`-Afluxzero.openapi.title=\"Meters API\"`, `-Afluxzero.openapi.version=1.0.0`, and\n`-Afluxzero.openapi.servers=https://api.example.com`. The generated path can be changed with\n`-Afluxzero.openapi.output=...`, the OpenAPI version with `-Afluxzero.openapi.specVersion=3.1.0`, and generation can\nbe disabled with `-Afluxzero.openapi.enabled=false`.\n\nFor dependency-free document metadata in source, place `@ApiDocInfo` on a package or handler type:\n\n```java\n@ApiDocInfo(\n        title = \"Meters API\",\n        version = \"1.0.0\",\n        description = \"Public meter endpoints.\",\n        contactName = \"API support\",\n        contactEmail = \"support@example.com\",\n        logoUrl = \"https://example.com/logo.png\",\n        logoAltText = \"Example logo\",\n        servers = @ApiDocServer(url = \"https://api.example.com\", description = \"Production\"),\n        security = \"bearerAuth\",\n        components = {\n                @ApiDocComponent(path = \"responses.error\", json = \"\"\"\n                        {\"description\":\"Invalid request\"}\n                        \"\"\"),\n                @ApiDocComponent(path = \"securitySchemes.bearerAuth\", json = \"\"\"\n                        {\"type\":\"http\",\"scheme\":\"bearer\"}\n                        \"\"\")\n        })\npackage com.example.meters;\n```\n\nSet `serveOpenApi = true` on `@ApiDocInfo` to expose the generated document through Fluxzero web handling. The default\nendpoint is `openapi.json` relative to the `@Path` value on the same package or handler type, so a package annotated\nwith `@Path(\"/v1\")` serves `/v1/openapi.json`. Override this with `openApiPath`; absolute paths start at the\napplication root. The generated endpoint is registered internally and uses `@NoUserRequired`. For class-based handler\nregistration it can serve the compiled `META-INF/fluxzero/openapi.json` resource when available; for handler instances\nit renders the document from the runtime handler scope.\n\nSet `serveApiReference = true` to expose a small HTML API reference page for the same document. The default endpoint is\n`docs` relative to the same `@Path`, so `@Path(\"/v1\")` serves `/v1/docs` and automatically also serves\n`/v1/openapi.json`. Redoc is the default renderer; use `apiReferenceRenderer = ApiReferenceRenderer.SCALAR` or\n`SWAGGER_UI` to use Scalar or Swagger UI instead. The SDK does not bundle renderer frontend assets. It references\ndefault CDN URLs, which can be replaced with `apiReferenceScriptUrl` and `apiReferenceStylesheetUrl` for self-hosted\nassets.\n\nOnly web handlers opted in with `@ApiDoc` are included in generated API documentation. Place `@ApiDoc` on a package,\nhandler class, or handler method; empty `@ApiDoc` is enough when all metadata should be inferred. Use it for\nhuman-authored metadata such as summaries, descriptions, operation ids, tags, operation security requirements, and\nschema hints that cannot be inferred. It can also be placed on fields, parameters, record components, and type\narguments, for example\n`List\u003c@ApiDoc(description = \"Connection item\") Connection\u003e` to document array items without OpenAPI-specific\nannotations. Optional schema hints include `type`, `format`, `example`, `defaultValue`, `minimum`, `maximum`,\n`allowableValues`, `required`, and `implementation`. Jakarta validation annotations such as `@NotNull`, `@Min`,\n`@Size`, `@Pattern`, and `@Email` are reflected in endpoint parameter and model schemas when present. Use repeatable\n`@ApiDocResponse` annotations for additional error/status responses, or to describe an inferred response without\nrepeating its body type; `@ApiDocResponse(status = 400, ref = \"error\")` references\n`#/components/responses/error`. Array properties in response models are documented as required by default; input models\nonly use explicit `@ApiDoc(required = true)` or validation metadata for required properties. Use `@ApiDocExclude` to\nexclude a package, class, method, parameter, field, record component, or type use from generated documentation without\ndisabling the runtime endpoint or model. Use `@ApiDocInfo.security` for top-level security requirements and\n`@ApiDocComponent` through `@ApiDocInfo.components` for shared OpenAPI components such as reusable responses or\nsecurity schemes when automatic inference is not enough.\n\n#### Other Parameter Annotations\n\nIn addition to `@PathParam`, you can extract other values from the request using:\n\n- `@QueryParam` – extract query string values\n- `@HeaderParam` – extract HTTP headers\n- `@CookieParam` – extract cookie values\n- `@FormParam` – extract URL-encoded form values or multipart form parts\n\nFor `multipart/form-data`, use `@FormParam String` for text fields, `@FormParam byte[]` or\n`@FormParam InputStream` for file contents, or `@FormParam WebFormPart` when you also need the filename, content type,\nor part headers.\n\nEach of these annotations supports the same rules:\n\n- If no name is given, the method parameter name is used\n- Values are automatically converted to the target parameter type\n\n#### Response Content Negotiation\n\nWhen a web handler returns a regular value, Fluxzero uses the request's `Accept` header to choose a response\n`Content-Type` where possible. Object payloads can be returned as `application/json`, `String` payloads can be returned\nas `text/plain` or JSON strings, and `byte[]`/`InputStream` payloads can be returned as `application/octet-stream`.\nExplicit `WebResponse` content types always win. If no supported representation matches the `Accept` header, Fluxzero\nkeeps the existing default instead of returning `406 Not Acceptable`.\n\n#### URI Prefixing and Composition with `@Path`\n\nThe `@Path` annotation can be used at the **package**, **class**, **method**, or **property** level to construct URI\npath segments. Paths are chained together from the outermost package to the innermost handler method. If a path segment\nstarts with `/`, it resets the chain from that point downward.\n\n- Empty path values use the simple name of the package.\n- If placed on a field or getter, the property value is used as the path segment (enabling dynamic routing).\n\n```java\n@Path\npackage my.example.api;\n\n@Path(\"users\")\npublic class UserHandler {\n\n    @Path(\"{id}\")\n    @HandleGet\n    public User getUser(@PathParam String id) { ...}\n}\n```\n\nThis matches `/api/users/{id}`. If the class annotation had started with a `/`, i.e.: had been `@Path(\"/users\")`, the\npattern would have become `/users/{id}`.\n\n---\n\n## Serving Static Files\n\nFluxzero supports serving static files directly from a handler class by using the `@ServeStatic` annotation.\nThis allows client applications to expose static resources (HTML, JS, CSS, images, etc.) without needing an external web\nserver.\n\n```java\n\n@ServeStatic(value = \"/web\", resourcePath = \"/static\")\npublic class WebAssets {\n}\n```\n\nThis will serve all files under `/static` (from the classpath or file system) under the URI path `/web`.\n\n### Features\n\n- Supports both **file system** and **classpath** resources\n- Optional **fallback file** (e.g. for single-page apps)\n- Clean URLs for statically exported routes\n- Automatic `Cache-Control` headers\n- Compression via Brotli and GZIP (if precompressed variants exist)\n\n### Annotation Reference\n\n```java\n@ServeStatic(\n        value = \"/assets\",\n        resourcePath = \"/public\",\n        fallbackFile = \"index.html\",\n        cleanUrls = true,\n        immutableCandidateExtensions = {\"js\", \"css\", \"svg\"},\n        maxAgeSeconds = 86400\n)\n```\n\n#### Parameters:\n\n- `value`: Web path(s) where static content is served. Relative paths are prefixed by `@Path` values.\n- `resourcePath`: The resource root (either on the file system or classpath).\n- `fallbackFile`: A file to serve when the requested path doesn’t exist (e.g. `index.html`). Set to `\"\"` to disable.\n- `cleanUrls`: Whether extensionless paths first try `\u003cpath\u003e.html` and `\u003cpath\u003e/index.html` before the fallback. Set to\n  `false` to disable.\n- `immutableCandidateExtensions`: Extensions that are eligible for aggressive caching if fingerprinted (e.g.\n  `main.123abc.js`).\n- `maxAgeSeconds`: Default cache duration for non-immutable resources.\n\n### Example: Serving a React App\n\n```java\n\n@ServeStatic(value = \"/app\", resourcePath = \"/static\", fallbackFile = \"index.html\")\npublic class WebFrontend { ...\n}\n```\n\nThis will serve files under `/app/**` and fallback to `index.html` for unknown paths—ideal for single-page apps.\nRequests without a file extension also support statically exported clean URLs: `/app/onboarding` tries the exact path,\nthen `/app/onboarding.html`, then `/app/onboarding/index.html`, and only then the configured fallback.\n\n\u003e 📁 Files in `/static` on the classpath (e.g. under `resources/static/`) or `/static` on disk will be served.\n\n\u003e When both file system and classpath contain a file, the **file system takes precedence**.\n\n\u003e If the `resourcePath` starts with `classpath:`, **only classpath resources** are served.  \n\u003e If it starts with `file:`, **only file system resources** are served.\n\nThis allows precise control over where content is loaded from and ensures classpath-only or file-system-only resolution\ndepending on the use case.\n\n#### Combining Static and Dynamic Handlers\n\nYou can freely combine `@ServeStatic` with dynamic handler methods in the same class or package.\n\nThis is especially useful when your application serves a combination of:\n\n- **Static assets** like HTML, JS, CSS\n- **Dynamic endpoints** like REST APIs or view-rendered pages\n\n```java\n\n@Path(\"/app\")\n@ServeStatic(\"static\") // serves static files from the /static resource directory for web paths /app/static/**\npublic class AppController {\n\n    @HandleGet(\"/status\")\n    Status getStatus() {\n        return new Status(\"OK\", Instant.now());\n    }\n\n    @HandlePost(\"/submit\")\n    SubmissionResult submitForm(FormData data) {\n        return formService.handle(data);\n    }\n}\n```\n\nThis will:\n\n- Serve `/app/static/index.html`, `/app/static/styles.css`, etc. from the `static/` resource directory\n- Also respond to `/app/status` and `/app/submit` dynamically\n\nThe static file handling applies to all routes **not matched** by other methods in the class. This makes it ideal for\ncombining SPAs or hybrid web apps with API endpoints under a shared route prefix.\n\n---\n\n## Handling WebSocket Messages\n\nFluxzero provides first-class support for **WebSocket communication**, enabling stateful or stateless message\nhandling using the same annotation-based model as other requests.\n\nWebSocket requests are published to the **WebRequest** log after being reverse-forwarded from the Fluxzero Runtime, and can\nbe consumed and responded to like any other request type.\n\n---\n\n### Two Styles of WebSocket Handling\n\n#### 1. **Stateless Handlers** (Singleton Style)\n\nUse annotations like `@HandleSocketOpen`, `@HandleSocketMessage`, and `@HandleSocketClose` directly on singleton handler\nclasses:\n\n```java\n\n@HandleSocketOpen(\"/chat\")\npublic String onOpen() {\n    return \"Welcome!\";\n}\n\n@HandleSocketMessage(\"/chat\")\npublic String onMessage(String incoming) {\n    return \"Echo: \" + incoming;\n}\n\n@HandleSocketClose(\"/chat\")\npublic void onClose(SocketSession session) {\n    System.out.println(\"Socket closed: \" + session.sessionId());\n}\n```\n\nResponses can be returned directly from `@HandleSocketMessage` and `@HandleSocketOpen` methods. For more control, you\ncan inject the `SocketSession` parameter and send messages manually.\n\nOther available annotations:\n\n- `@HandleSocketPong` — handle pong responses\n- `@HandleSocketHandshake` — override the default handshake logic\n\n#### 2. **Stateful Sessions with `@SocketEndpoint`**\n\nIf you need to maintain per-session state, use `@SocketEndpoint`. Each WebSocket session will instantiate a fresh\nhandler object:\n\n```java\n\n@SocketEndpoint\n@Path(\"/chat\")\npublic class ChatSession {\n\n    private final List\u003cString\u003e messages = new ArrayList\u003c\u003e();\n\n    @HandleSocketOpen\n    public String onOpen() {\n        return \"Connected!\";\n    }\n\n    @HandleSocketMessage\n    public void onMessage(String text, SocketSession session) {\n        messages.add(text);\n        session.sendMessage(\"Stored message: \" + text);\n    }\n\n    @HandleSocketClose\n    public void onClose() {\n        System.out.println(\"Messages in this session: \" + messages.size());\n    }\n}\n```\n\nStateful sessions are useful for flows involving authentication, message accumulation, or temporal context (e.g. cursor,\nbuffer, sequence).\n\n\u003e ✅ `@SocketEndpoint` handlers are prototype-scoped, meaning they're constructed once per session.\n\n\u003e ℹ️ Like other handlers, socket endpoints may be annotated with `@Consumer` for tracking isolation.\n\n---\n\n### Automatic Ping-Pong \u0026 Keep-Alive\n\nWhen using `@SocketEndpoint`, Fluxzero automatically manages **keep-alive pings**:\n\n- Pings are sent at regular intervals (default: every 60s)\n- If a `pong` is not received within a timeout, the session is closed\n- You can customize this behavior via the `aliveCheck` attribute on `@SocketEndpoint`\n\n```java\n\n@SocketEndpoint(aliveCheck = @SocketEndpoint.AliveCheck(pingDelay = 30, pingTimeout = 15))\npublic class MySession { ...\n}\n```\n\n---\n\n### Summary\n\n| Annotation                 | Description                                        |\n|----------------------------|----------------------------------------------------|\n| `@HandleSocketOpen`        | Handles WebSocket connection open                  |\n| `@HandleSocketMessage`     | Handles incoming text or binary WebSocket messages |\n| `@HandleSocketPong`        | Handles pong responses (usually for health checks) |\n| `@HandleSocketClose`       | Handles WebSocket session closing                  |\n| `@HandleSocketHandshake`   | Allows customizing the handshake phase             |\n| `@SocketEndpoint`          | Declares a per-session WebSocket handler class     |\n| `SocketSession` (injected) | Controls sending messages, pinging, and closing    |\n\nFluxzero makes WebSocket communication secure, observable, and composable—integrated seamlessly into your\ndistributed, event-driven architecture.\n\n---\n\n## Testing Web Endpoint Behavior\n\nFluxzero allows you to simulate and verify HTTP interactions as part of your test flows. Web requests\ncan be tested like any other command, query, or event.\n\nHere’s a complete test for a `POST /games` handler that accepts a JSON request and publishes a command:\n\n```java\n\n@Test\nvoid registerGame() {\n    testFixture\n            .whenPost(\"/games\", \"/game/game-details.json\")  // Simulates POST with payload\n            .expectResult(GameId.class)                     // Asserts a result is returned\n            .expectEvents(RegisterGame.class);              // Asserts a command was published\n}\n```\n\nThe corresponding handler is:\n\n```java\n\n@HandlePost(\"/games\")\nCompletableFuture\u003cGameId\u003e addGame(GameDetails details) {\n    return Fluxzero.sendCommand(new RegisterGame(details));\n}\n```\n\nAs always, the `.json` file is automatically loaded from the classpath, allowing you to cleanly separate test data:\n\n📄 `/game/game-details.json`\n\n```json\n{\n  \"title\": \"Legend of the Skylands\",\n  \"description\": \"An epic singleplayer adventure with puzzles and secrets.\",\n  \"releaseDate\": \"2025-11-12T00:00:00Z\",\n  \"tags\": [\n    \"adventure\",\n    \"puzzle\",\n    \"singleplayer\"\n  ]\n}\n```\n\n---\n\n### Example: Querying with `GET`\n\nYou can test GET endpoints just as easily. This example first registers a game via `POST /games`, then fetches the list\nof all games via `GET /games` and checks the result:\n\n```java\n\n@Test\nvoid getGames() {\n    testFixture\n            .givenPost(\"/games\", \"/game/game-details.json\")   // Precondition: register a game\n            .whenGet(\"/games\")                                // Perform GET request\n            .\u003cList\u003cGame\u003e\u003eexpectResult(r -\u003e r.size() == 1)     // Assert one game is returned\n            .expectWebResponse(r -\u003e r.getStatus() == 200);    // Assert the status of the response\n}\n```\n\nThis corresponds to the following handler method:\n\n```java\n\n@HandleGet\n@Path(\"/games\")\nCompletableFuture\u003cList\u003cGame\u003e\u003e getGames(@QueryParam String term) {\n    return Fluxzero.query(new FindGames(term));\n}\n```\n\n---\n\n### Testing Error Responses and Exceptions\n\nFluxzero also allows you to verify how your web endpoints handle exceptional scenarios. This includes asserting\nthe type of exception thrown as well as inspecting the resulting HTTP status code or response body.\n\nHere’s a test that triggers a `403 Forbidden` error by throwing an `IllegalCommandException`:\n\n```java\n\n@Test\nvoid postReturnsError() {\n    testFixture\n            .whenPost(\"/error\", \"body\")                              // Simulate POST request\n            .expectExceptionalResult(IllegalCommandException.class)  // Assert thrown exception\n            .expectWebResponse(r -\u003e r.getStatus() == 403);           // Assert HTTP 403 response\n}\n```\n\nThe corresponding handler might look like:\n\n```java\n\n@HandlePost(\"/error\")\nvoid postForError(String body) {\n    throw new IllegalCommandException(\"error: \" + body);\n}\n```\n\nThis enables robust testing of both successful and failure paths for all your web request handlers.\n\n---\n\n### Path Parameter Substitution in Tests\n\nWhen simulating web requests, Fluxzero automatically substitutes `{...}` placeholders in the request path using\nresults from previous steps:\n\n- The result of the **first `when...()` step** is saved when `.andThen()` is called.\n- If a subsequent path (e.g. `/games/{gameId}/buy`) contains placeholders, Fluxzero will:\n- Attempt to replace each placeholder (like `{gameId}`) with the string value of a previously returned result.\n- Track all resolved placeholders across steps. This allows chaining:\n\n[//]: # (@formatter:off)\n```java\ntestFixture.whenPost(\"/games\", \"/game/game-details.json\") // returns gameId\n     .andThen()\n     .whenPost(\"/games/{gameId}/buy\") // uses gameId, returns orderId\n     .andThen()\n     .whenPost(\"/games/{gameId}/refund/{orderId}\"); // uses gameId from step 1, orderId from step 2\n```\n[//]: # (@formatter:on)\n\nSubstitutions are based purely on the order of results, not types or field names. The `.toString()` value of each result\nis used to fill the next unresolved placeholder.\n\nThis keeps tests expressive and avoids boilerplate, especially for flows that involve chained resource creation (e.g.\n`POST /games → POST /games/{gameId}/buy → ...`).\n\n---\n\n## Outbound Web Requests\n\nFluxzero provides a unified API for sending HTTP requests through the `WebRequestGateway`.\n\nUnlike traditional HTTP clients, Flux logs outbound requests as `WebRequest` messages. These are then handled by:\n\n- A **local handler** that tracks requests if the URL is **relative**, or\n- A **connected remote client or proxy**, if the URL is **absolute**.\n\n### Sending a Request\n\n```java\nWebRequest request = WebRequest.get(\"https://api.example.com/data\")\n        .header(\"Authorization\", \"Bearer token123\")\n        .build();\n\nWebResponse response = Fluxzero.get()\n        .webRequestGateway().sendAndWait(request);\n\nString body = response.getBodyString();\n```\n\n\u003e ✅ All outbound traffic is logged and traceable in the Fluxzero Runtime.\n\n### Asynchronous and Fire-and-Forget\n\nYou can send requests asynchronously:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.get().webRequestGateway()\n        .send(request)\n        .thenAccept(response -\u003e log\n              .info(\"Received: {}\",response.getBodyString()));\n```\n[//]: # (@formatter:off)\n\nOr fire-and-forget:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.get().webRequestGateway()\n        .sendAndForget(Guarantee.STORED, request);\n```\n[//]: # (@formatter:on)\n\n### Relative vs Absolute URLs\n\nFlux supports both local and remote handling:\n\n- **Absolute URLs** (e.g., `https://...`): The request is forwarded via the Flux **Web Proxy** and executed externally.\n- **Relative URLs** (e.g., `/internal/doSomething`): The request is routed to a handler within another connected Flux\n  application.\n\nThis allows decoupled request-response workflows across services and environments.\n\n### Isolating Traffic with `consumer`\n\nYou can specify a `consumer` in the request settings:\n\n```java\nWebRequestSettings settings = WebRequestSettings.builder()\n        .consumer(\"external-api-xyz\")\n        .timeout(Duration.ofSeconds(5))\n        .build();\n```\n\nWhen set, the Flux Web Proxy will isolate this request in its own internal processing pipeline. This is useful when you:\n\n- Want to isolate third-party integrations (e.g., API rate limits)\n- Need different retry or error handling strategies per destination\n- Want fault isolation between outgoing endpoints\n\n### Mocking External Endpoints in Tests\n\nFlux makes it easy to test full workflows—including outbound `WebRequest` calls—by **mocking** the response during\ntests:\n\n```java\nstatic class EndpointMock {\n    @HandleGet(\"https://api.example.com/1.1/locations\")\n    WebResponse handleLocations() {\n        return WebResponse.builder()\n                .header(\"X-Limit\", \"100\")\n                .payload(\"/example-api/get-locations.json\")\n                .build();\n    }\n}\n\n@Test\nvoid testGetLocations() {\n    TestFixture.create(new EndpointMock())\n            .whenGet(\"https://api.example.com/1.1/locations\")\n            .\u003cList\u003cExampleLocation\u003e\u003eexpectResult(r -\u003e r.size() == 2);\n}\n```\n\nYou can match requests by:\n\n- Method and URL\n- Headers, body, or any other property\n\n\u003e ✅ This gives you **full end-to-end test coverage**, even when integrating with external APIs.\n\n---\n\n### Summary\n\n- ✅ Use `WebRequest` for centralized, traceable outbound HTTP calls.\n- ✅ Automatically routes to a proxy or local handler depending on URL.\n- ✅ Supports timeouts, consumers, and structured request settings.\n- ✅ Easily mock remote endpoints for testing full business flows.\n\n---\n\n## Metrics Messages\n\nFluxzero supports a built-in message type for metrics: `MessageType.METRICS`.  \nThese messages provide a powerful way to observe and trace system behavior across clients, handlers, and infrastructure.\n\nMetrics messages are:\n\n- Lightweight, structured, and traceable\n- Logged like any other message\n- Routable to handlers (via `@HandleMetrics`)\n- Stored by default for **1 month** due to volume\n\n---\n\n### Publishing Metrics\n\nYou can publish metrics manually using the `Fluxzero.publishMetrics(...)` method:\n\n```java\nFluxzero.publishMetrics(new SystemMetrics(\"slowProjection\", \"thresholdExceeded\"));\n```\n\nThis emits a structured metrics message to the metrics topic.\n\nAll metrics are wrapped in a regular `Message`, so you can include metadata or delivery guarantees:\n\n[//]: # (@formatter:off)\n```java\nFluxzero.get()\n    .metricsGateway()\n    .publish(new MyMetric(\"foo\"), \n             Metadata.of(\"critical\",\"true\"),\n             Guarantee.STORED);\n```\n[//]: # (@formatter:off)\n\n---\n\n### Automatic Metrics from Clients\n\nMany metrics are automatically emitted by the Flux Java client:\n\n- **Connect / Disconnect events** when clients (re)connect\n- **Tracking updates** (throughput, handler times, latency)\n- **Search / state / document store operations**\n- **Web request round-trip timings**\n\nThese are particularly helpful in troubleshooting or auditing system performance.\n\n---\n\n### Consuming Metrics\n\nYou can treat metrics like any other message type:\n\n```java\n\n@HandleMetrics\nvoid on(MetricEvent event) {\n    log.debug(\"Observed metric: {}\", event);\n}\n```\n\nUse this to power custom dashboards, counters, diagnostics, or trigger alerts.\n\n---\n\n### Disabling Metrics\n\nTo reduce noise or overhead, you can selectively disable automatic metrics:\n\n#### Disable per handler or batch using an interceptor\n\n```java\n\n@Consumer(handlerInterceptors = DisableMetrics.class)\npublic class SilentHandler {\n    @HandleEvent\n    void on(MyEvent event) { ... }\n}\n```\n\nYou can also use `batchInterceptors` to disable metrics for an entire consumer instance.\n\n#### Disable globally per client\n\nIf you're instantiating a `WebSocketClient`, you can pass `disableMetrics = true` via the client config.\n\n#### Use programmatic interceptors\n\nIf needed, you can suppress metric dispatch programmatically using:\n\n[//]: # (@formatter:off)\n```java\nAdhocDispatchInterceptor.runWithAdhocInterceptor(() -\u003e {\n    // your code here\n}, (message, messageType, topic) -\u003e null, MessageType.METRICS);\n```\n[//]: # (@formatter:on)\n\n---\n\n### Common Use Cases\n\n- **Audit debugging**: trace which handler caused a slowdown\n- **Observability**: track real-time stats like search throughput\n- **Dashboards**: expose per-entity or per-consumer metrics\n- **Trigger alerting**: when retries or handler delays exceed thresholds\n\nMetrics messages provide lightweight hooks into system behavior — use them for visibility without overhead.\n\n---\n\n## Domain Modeling\n\nFluxzero allows you to model the state of your domain using entities that evolve over time by applying updates.\nThese entities — such as users, orders, etc. — maintain state and enforce invariants through controlled updates,\ntypically driven by commands.\n\n### Defining the Aggregate Entity\n\nTo define a stateful domain object, annotate it with `@Aggregate`:\n\n```java\n\n@Aggregate\n@Builder(toBuilder = true)\npublic record UserAccount(@EntityId UserId userId,\n                          UserProfile profile,\n                          boolean accountClosed) {\n}\n```\n\nT","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffluxzero-io%2Ffluxzero-sdk-java","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffluxzero-io%2Ffluxzero-sdk-java","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffluxzero-io%2Ffluxzero-sdk-java/lists"}