Skip to content

API Reference

Frody edited this page Sep 4, 2026 · 1 revision

Complete API Reference & Developer Cheat-Sheet

This reference catalogs every public class, interface, method, execution wrapper, and Spring Boot configuration property in ScopeFlow, with technical explanations and executable code samples.


Table of Contents

  1. Context Container: ScopeContext
  2. Snapshot & Activation: ScopeSnapshot
  3. Auto-Closing Guard: ScopeCloseable
  4. Executor Decorators: ScopeFlowExecutors
  5. Task Wrappers: Functional Decorators
  6. Spring Boot Configuration Reference (application.yml)

1. Context Container: ScopeContext

Package: io.github.frodygr.scopeflow.core.ScopeContext

The immutable key-value container storing context attributes for the active thread or task.

ScopeContext.current()

  • Signature: public static ScopeContext current()
  • Description: Returns the active ScopeContext bound to the calling thread. If no context is active, returns an empty context (ScopeContext.empty()). Never returns null.
ScopeContext ctx = ScopeContext.current();
String traceId = ctx.get("traceId").orElse("NO_TRACE");

ScopeContext.empty()

  • Signature: public static ScopeContext empty()
  • Description: Returns a shared, immutable empty context instance containing zero keys.
ScopeContext empty = ScopeContext.empty();

ScopeContext.of(Map<String, String> values)

  • Signature: public static ScopeContext of(Map<String, String> values)
  • Description: Creates a new immutable context populated with the given key-value mappings. Automatically filters nulls.
ScopeContext ctx = ScopeContext.of(Map.of(
    "traceId", "c0a80101-7b9e-4a8b-9d41-3b7c89f50001",
    "tenantId", "acme-corp",
    "userId", "usr-4091"
));

ScopeContext.builder()

  • Signature: public static ScopeContext.Builder builder()
  • Description: Returns a fluent builder to incrementally construct an immutable context.
ScopeContext ctx = ScopeContext.builder()
        .put("traceId", UUID.randomUUID().toString())
        .put("tenantId", tenantResolver.resolve())
        .putIfAbsent("environment", "production")
        .build();

.get(String key)

  • Signature: public Optional<String> get(String key)
  • Description: Retrieves the value associated with key as a typed java.util.Optional.
String tenant = ScopeContext.current()
        .get("tenantId")
        .orElse("default");

.getOrDefault(String key, String defaultValue)

  • Signature: public String getOrDefault(String key, String defaultValue)
  • Description: Returns the value associated with key, or defaultValue if the key is absent.
String clientIp = ctx.getOrDefault("clientIp", "0.0.0.0");

.asMap()

  • Signature: public Map<String, String> asMap()
  • Description: Returns an unmodifiable Map<String, String> view of all context attributes.
Map<String, String> allEntries = ScopeContext.current().asMap();
allEntries.forEach((k, v) -> log.debug("Context: {} = {}", k, v));

.with(String key, String value)

  • Signature: public ScopeContext with(String key, String value)
  • Description: Returns a new ScopeContext instance containing all existing entries plus the new key-value pair. Because ScopeContext is strictly immutable, the original instance remains unchanged.
ScopeContext parent = ScopeContext.current();
ScopeContext updated = parent.with("stepId", "payment-validation");

.without(String key)

  • Signature: public ScopeContext without(String key)
  • Description: Returns a new ScopeContext instance omitting the specified key.
ScopeContext sanitized = ctx.without("internalToken");

.merge(ScopeContext other)

  • Signature: public ScopeContext merge(ScopeContext other)
  • Description: Combines this context with other. In case of duplicate keys, values from other take precedence.
ScopeContext combined = baseContext.merge(requestContext);

2. Snapshot & Activation: ScopeSnapshot

Package: io.github.frodygr.scopeflow.core.ScopeSnapshot

A captured point-in-time state of the thread's context, ready to be propagated across thread pools, asynchronous stages, or virtual threads.

ScopeSnapshot.capture()

  • Signature: public static ScopeSnapshot capture()
  • Description: Captures the current thread's ScopeContext, active MDC entries, and tracing coordinates into an immutable snapshot.
// Main request thread captures context before spawning async task
ScopeSnapshot snapshot = ScopeSnapshot.capture();

CompletableFuture.runAsync(() -> {
    // In background thread: attach snapshot
    try (ScopeCloseable guard = snapshot.attach()) {
        orderService.process();
    }
});

.attach()

  • Signature: public ScopeCloseable attach()
  • Description: Activates the captured snapshot on the current thread, syncing MDC and ScopeContext. Returns a ScopeCloseable that must be closed in a try-with-resources block to restore the thread's prior context.
try (ScopeCloseable scope = snapshot.attach()) {
    // Current thread has the full propagated context
    log.info("Processing with trace ID active in MDC");
}
// Context cleanly reverted to previous state

.run(Runnable task)

  • Signature: public void run(Runnable task)
  • Description: Executes the given Runnable under the context of this snapshot, automatically attaching before execution and reverting immediately upon completion.
snapshot.run(() -> notificationService.sendReceipt(orderId));

.run(Supplier<T> task)

  • Signature: public <T> T run(Supplier<T> task)
  • Description: Executes the given Supplier under the context of this snapshot, returning its value and cleaning up upon completion.
OrderResult result = snapshot.run(() -> paymentClient.authorize(payment));

3. Auto-Closing Guard: ScopeCloseable

Package: io.github.frodygr.scopeflow.core.ScopeCloseable

  • Extends: java.lang.AutoCloseable
  • Description: Returned by .attach(). Guarantees thread hygiene by restoring previous MDC and ThreadLocal / ScopedValue state when exited.
  • Throws: close() does not declare checked exceptions, allowing clean try-with-resources without try-catch bloat.
try (ScopeCloseable scope = ScopeContext.of(Map.of("requestId", reqId)).attach()) {
    executeBusinessLogic();
} // Automatically closed here

4. Executor Decorators: ScopeFlowExecutors

Package: io.github.frodygr.scopeflow.core.concurrent.ScopeFlowExecutors

Wraps standard Java executors to propagate context automatically to worker threads and virtual threads.

ScopeFlowExecutors.wrap(ExecutorService executor)

  • Signature: public static ExecutorService wrap(ExecutorService delegate)
  • Description: Wraps any standard ExecutorService (including fixed thread pools, cached pools, or Loom virtual thread executors). Every task submitted to the wrapped executor automatically captures the caller's context at submission time and restores it on the executing worker thread.
// Standard fixed pool wrapped with automatic context propagation
ExecutorService workerPool = ScopeFlowExecutors.wrap(
    Executors.newFixedThreadPool(16)
);

// Virtual thread pool wrapped with automatic propagation
ExecutorService virtualPool = ScopeFlowExecutors.wrap(
    Executors.newVirtualThreadPerTaskExecutor()
);

// Submitted task inherits MDC and traceId transparently!
workerPool.submit(() -> {
    log.info("This log contains the caller's traceId automatically!");
});

ScopeFlowExecutors.wrap(ScheduledExecutorService scheduler)

  • Signature: public static ScheduledExecutorService wrap(ScheduledExecutorService delegate)
  • Description: Wraps a ScheduledExecutorService for delayed or periodic tasks (schedule, scheduleAtFixedRate).
ScheduledExecutorService scheduler = ScopeFlowExecutors.wrap(
    Executors.newScheduledThreadPool(4)
);

scheduler.schedule(() -> checkStatus(orderId), 30, TimeUnit.SECONDS);

5. Task Wrappers: Functional Decorators

Propagate context to individual functional instances without modifying the underlying executor.

// 1. Wrap a Runnable
Runnable task = ScopeSnapshot.capture().wrap(() -> doWork());

// 2. Wrap a Callable<T>
Callable<Invoice> invoiceTask = ScopeSnapshot.capture().wrap(() -> generateInvoice());

// 3. Wrap a Supplier<T> for CompletableFuture
CompletableFuture.supplyAsync(
    ScopeSnapshot.capture().wrap(() -> externalApi.fetch())
);

// 4. Wrap a Consumer<T> for Stream pipelines
orders.parallelStream()
      .forEach(ScopeSnapshot.capture().wrap(order -> processOrder(order)));

6. Spring Boot Configuration Reference (application.yml)

When using scopeflow-spring-boot-starter, all behavior can be declared via application.yml or application.properties:

scopeflow:
  # Master toggle for ScopeFlow auto-configuration
  enabled: true

  # MDC (Mapped Diagnostic Context) synchronization
  mdc:
    enabled: true
    # Optional prefix for keys added to MDC (e.g., "scopeflow.traceId")
    # Default: "" (keys added as-is: "traceId")
    prefix: ""

  # HTTP Header propagation filter
  header-propagation:
    enabled: true
    # Header parsed to initialize the trace identifier
    trace-header: "X-Trace-Id"
    # Prefix for custom baggage headers automatically ingested into ScopeContext
    baggage-header-prefix: "X-Baggage-"
    # Paths excluded from context filter
    exclude-patterns:
      - "/actuator/**"
      - "/favicon.ico"

  # Metrics & Observability integrations
  micrometer:
    enabled: true
    # Track context propagation latency as a timer
    record-timer: false

  opentelemetry:
    # Bridge ScopeContext attributes to active OTel Span Baggage
    enabled: true

Clone this wiki locally