-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
This reference catalogs every public class, interface, method, execution wrapper, and Spring Boot configuration property in ScopeFlow, with technical explanations and executable code samples.
- Context Container:
ScopeContext - Snapshot & Activation:
ScopeSnapshot - Auto-Closing Guard:
ScopeCloseable - Executor Decorators:
ScopeFlowExecutors - Task Wrappers: Functional Decorators
- Spring Boot Configuration Reference (
application.yml)
Package: io.github.frodygr.scopeflow.core.ScopeContext
The immutable key-value container storing context attributes for the active thread or task.
-
Signature:
public static ScopeContext current() -
Description: Returns the active
ScopeContextbound to the calling thread. If no context is active, returns an empty context (ScopeContext.empty()). Never returnsnull.
ScopeContext ctx = ScopeContext.current();
String traceId = ctx.get("traceId").orElse("NO_TRACE");-
Signature:
public static ScopeContext empty() - Description: Returns a shared, immutable empty context instance containing zero keys.
ScopeContext empty = ScopeContext.empty();-
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"
));-
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();-
Signature:
public Optional<String> get(String key) -
Description: Retrieves the value associated with
keyas a typedjava.util.Optional.
String tenant = ScopeContext.current()
.get("tenantId")
.orElse("default");-
Signature:
public String getOrDefault(String key, String defaultValue) -
Description: Returns the value associated with
key, ordefaultValueif the key is absent.
String clientIp = ctx.getOrDefault("clientIp", "0.0.0.0");-
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));-
Signature:
public ScopeContext with(String key, String value) -
Description: Returns a new
ScopeContextinstance containing all existing entries plus the new key-value pair. BecauseScopeContextis strictly immutable, the original instance remains unchanged.
ScopeContext parent = ScopeContext.current();
ScopeContext updated = parent.with("stepId", "payment-validation");-
Signature:
public ScopeContext without(String key) -
Description: Returns a new
ScopeContextinstance omitting the specified key.
ScopeContext sanitized = ctx.without("internalToken");-
Signature:
public ScopeContext merge(ScopeContext other) -
Description: Combines this context with
other. In case of duplicate keys, values fromothertake precedence.
ScopeContext combined = baseContext.merge(requestContext);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.
-
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();
}
});-
Signature:
public ScopeCloseable attach() -
Description: Activates the captured snapshot on the current thread, syncing MDC and ScopeContext. Returns a
ScopeCloseablethat 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-
Signature:
public void run(Runnable task) -
Description: Executes the given
Runnableunder the context of this snapshot, automatically attaching before execution and reverting immediately upon completion.
snapshot.run(() -> notificationService.sendReceipt(orderId));-
Signature:
public <T> T run(Supplier<T> task) -
Description: Executes the given
Supplierunder the context of this snapshot, returning its value and cleaning up upon completion.
OrderResult result = snapshot.run(() -> paymentClient.authorize(payment));Package: io.github.frodygr.scopeflow.core.ScopeCloseable
-
Extends:
java.lang.AutoCloseable -
Description: Returned by
.attach(). Guarantees thread hygiene by restoring previous MDC andThreadLocal/ScopedValuestate 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 herePackage: io.github.frodygr.scopeflow.core.concurrent.ScopeFlowExecutors
Wraps standard Java executors to propagate context automatically to worker threads and virtual threads.
-
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!");
});-
Signature:
public static ScheduledExecutorService wrap(ScheduledExecutorService delegate) -
Description: Wraps a
ScheduledExecutorServicefor delayed or periodic tasks (schedule,scheduleAtFixedRate).
ScheduledExecutorService scheduler = ScopeFlowExecutors.wrap(
Executors.newScheduledThreadPool(4)
);
scheduler.schedule(() -> checkStatus(orderId), 30, TimeUnit.SECONDS);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)));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: trueScopeFlow • Distributed Context & Tracing Propagation • Licensed under Apache-2.0