Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,6 @@ import scala.concurrent.duration._

object ProcessInstanceLogger {

import org.joda.time.format.PeriodFormatterBuilder

val durationFormatter = new PeriodFormatterBuilder()
.appendDays.appendSuffix("d")
.appendSeparator(" ")
.appendHours.appendSuffix("h")
.appendSeparator(" ")
.appendMinutes.appendSuffix("m")
.appendSeparator(" ")
.appendSeconds.appendSuffix("s")
.appendSeparator(" ")
.appendMillis.appendSuffix("ms")
.appendSeparator(" ")
.toFormatter

implicit class LoggingAdapterFns(log: DiagnosticLoggingAdapter) {

val bakerLogging: BakerLogging = BakerLogging.default
Expand Down
84 changes: 84 additions & 0 deletions core/baker-interface-in-memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,87 @@ fun main() = runBlocking {
- `KotlinBaker` mirrors the Kotlin adapter shape from `baker-interface-kotlin`.
- It supports `suspend` APIs and selected `CompletableFuture` wrappers such as `javaAsync`, `bakeAsync`, and `awaitCompletedAsync`.

## OpenTelemetry tracing

The in-memory runtime emits spans using OpenTelemetry when built through `InMemoryBaker`.

### What is traced

- Build lifecycle: `baker.build`
- Recipe lifecycle: `baker.recipe-instance.created`
- Event flow: `baker.event.received`, `baker.event.fired`
- Interaction execution: `baker.interaction.<interactionName>`

Interaction spans are created as children of the latest event span for the same recipe instance.

### Ambient context inside interactions

The interaction span is started on the very thread that invokes your interaction implementation, so
`Span.current()` and the SLF4J `MDC` are valid and belong to *that* invocation, also under heavy concurrency:

```java
public class ValidateOrderImpl implements ValidateOrder {
@Override
public ValidateOrderOutcome apply(String recipeInstanceId, String order) {
Span.current().addEvent("validating"); // the baker.interaction.ValidateOrder span
log.info("validating"); // MDC contains trace_id, span_id and recipeInstanceId
return new OrderValid();
}
}
```

Baker runs interactions on a shared pool. Before and after every invocation the registered context propagators are
cleared, so a pooled thread can never expose the context of a previous execution. If your interaction spawns its own
threads, propagate the context explicitly (for example with `Context.current().wrap(runnable)`).

For a `CompletableFuture`-returning interaction the span is ended when the future completes; for a blocking
interaction it is ended when the method returns.

### Common attributes

- `baker.recipe.id`
- `baker.recipe.name`
- `baker.recipe.instance.id`

Depending on the span type, additional attributes are set:

- `baker.event.name`
- `baker.interaction.name`
- `baker.correlation.id`
- `baker.failure.count`
- `error.type` (for failed interactions)

### Injecting a custom tracer

By default, Baker uses `GlobalOpenTelemetry.getTracer(...)`. You can provide your own tracer:

```kotlin
import com.ing.baker.runtime.inmemory.InMemoryBaker
import com.ing.baker.runtime.model.BakerConfig
import io.opentelemetry.api.GlobalOpenTelemetry

val tracer = GlobalOpenTelemetry.getTracer("my-service.baker")
val baker = InMemoryBaker.java(BakerConfig.default(), emptyList(), tracer)
```

For async Java factory usage:

```kotlin
val tracer = GlobalOpenTelemetry.getTracer("my-service.baker")
val bakerFuture = InMemoryBaker.javaAsync(BakerConfig.default(), emptyList(), tracer)
```


### Where the OpenTelemetry code lives

The OpenTelemetry-specific code is isolated in the `baker-interface-otel` module:

- `OpenTelemetryContextPropagator` — propagates the OTel `Context` to Baker's interaction pool. It is discovered
automatically through `META-INF/services`, so simply having the module on the classpath is enough.
- `OpenTelemetryInteractionInstrumentation` — starts, scopes and ends the `baker.interaction.<name>` span.
- `RecipeInstanceTraceContexts` — per-baker mapping of recipe instance to the context the interaction span is parented to.

`baker-interface` itself stays free of OpenTelemetry. It only exposes the SPIs
`com.ing.baker.runtime.model.propagation.ExecutionContextPropagator` (propagate any thread-bound context) and
`com.ing.baker.runtime.model.InteractionInstrumentation` (wrap every interaction invocation), which you can implement
to plug in a different tracing or diagnostics stack.
22 changes: 22 additions & 0 deletions core/baker-interface-in-memory/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-api</artifactId>
<version>${opentelemetry.version}</version>
</dependency>
<dependency>
<groupId>com.ing.baker</groupId>
<artifactId>baker-interface-otel</artifactId>
<version>${project.version}</version>
</dependency>

<!-- Provided dependencies -->
<dependency>
Expand Down Expand Up @@ -120,6 +130,18 @@
<version>${mockito.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk</artifactId>
<version>${opentelemetry.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.opentelemetry</groupId>
<artifactId>opentelemetry-sdk-testing</artifactId>
<version>${opentelemetry.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ import com.ing.baker.runtime.model.BakerConfig
import com.ing.baker.runtime.model.BakerF
import com.ing.baker.runtime.model.BakerLogging
import com.ing.baker.runtime.model.InteractionInstance
import com.ing.baker.runtime.model.InteractionInstrumentation
import com.ing.baker.runtime.otel.BakerEventTracingListener
import com.ing.baker.runtime.otel.OpenTelemetryInteractionInstrumentation
import com.ing.baker.runtime.otel.RecipeInstanceTraceContexts
import io.opentelemetry.api.GlobalOpenTelemetry
import io.opentelemetry.api.trace.StatusCode
import io.opentelemetry.api.trace.Tracer
import java.util.concurrent.CompletableFuture
import com.ing.baker.runtime.defaultinteractions.`package$`.`MODULE$` as defaultinteractions
import com.ing.baker.runtime.javadsl.Baker as JavaBaker
Expand All @@ -20,25 +27,46 @@ import scala.collection.immutable.List as ScalaList
@Suppress("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "UNCHECKED_CAST")
class InMemoryBaker(
private val bakerConfig: BakerConfig,
components: BakerComponents<CompletableFuture<*>>
components: BakerComponents<CompletableFuture<*>>,
private val tracer: Tracer = defaultTracer(),
private val traceContexts: RecipeInstanceTraceContexts = RecipeInstanceTraceContexts()
) : BakerF<CompletableFuture<*>>(
components,
InMemoryEffects.asyncSupportAny(),
InMemoryEffects.asyncSupportAny()
) {

init {
registerTracingListener()
}

companion object {

private const val INSTRUMENTATION_NAME = "com.ing.baker.runtime.inmemory.InMemoryBaker"

private fun defaultTracer(): Tracer =
GlobalOpenTelemetry.getTracer(INSTRUMENTATION_NAME)

@JvmStatic
fun build(implementations: ScalaList<*>): CompletableFuture<BakerF<CompletableFuture<*>>> =
build(BakerConfig.default(), implementations)
build(BakerConfig.default(), implementations, defaultTracer())

@JvmStatic
@Suppress("UNCHECKED_CAST")
fun build(
config: BakerConfig,
implementations: ScalaList<*>
): CompletableFuture<BakerF<CompletableFuture<*>>> =
build(config, implementations, defaultTracer())

@JvmStatic
@Suppress("UNCHECKED_CAST")
fun build(
config: BakerConfig,
implementations: ScalaList<*>,
tracer: Tracer
): CompletableFuture<BakerF<CompletableFuture<*>>> {
val buildSpan = tracer.spanBuilder("baker.build").startSpan()
val ioAsyncSupport = InMemoryEffects.asyncSupportAny()
val ioClassTag = InMemoryEffects.classTagAny()
val builtinInteractions =
Expand All @@ -54,25 +82,50 @@ class InMemoryBaker(
val recipeManager = InMemoryRecipeManager()
val eventStream = InMemoryEventStream()
val interactions = InMemoryInteractionManager(interactionInstances)
val traceContexts = RecipeInstanceTraceContexts()
val components = BakerComponents(
interactions,
recipeInstanceManager,
recipeManager,
eventStream,
BakerLogging.default()
)
return InMemoryEffects.pure(
InMemoryBaker(config, components)
BakerLogging.default(),
OpenTelemetryInteractionInstrumentation(tracer, traceContexts) as InteractionInstrumentation
)
return try {
val bakerFuture: CompletableFuture<BakerF<CompletableFuture<*>>> =
InMemoryEffects.pure(
InMemoryBaker(config, components, tracer, traceContexts) as BakerF<CompletableFuture<*>>
)

bakerFuture.whenComplete { _, throwable ->
if (throwable != null) {
buildSpan.recordException(throwable)
buildSpan.setStatus(StatusCode.ERROR)
} else {
buildSpan.setStatus(StatusCode.OK)
}
buildSpan.end()
}
} catch (throwable: Throwable) {
buildSpan.recordException(throwable)
buildSpan.setStatus(StatusCode.ERROR)
buildSpan.end()
throw throwable
}
}

@JvmStatic
fun java(config: BakerConfig, implementations: List<Any>): JavaBaker {
return java(config, implementations, defaultTracer())
}

@JvmStatic
fun java(config: BakerConfig, implementations: List<Any>, tracer: Tracer): JavaBaker {
val futureToCompletableFuture = InMemoryEffects.futureToCompletableFuture()
val completableFutureToFuture = InMemoryEffects.completableFutureToFuture()
val scalaInteractions = InMemoryEffects.toScalaCompletableFutureInteractions(implementations)

return build(config, scalaInteractions)
return build(config, scalaInteractions, tracer)
.let { InMemoryEffects.runSync(it) }
.asDeprecatedFutureImplementation(completableFutureToFuture, futureToCompletableFuture)
.let { JavaBaker(it) }
Expand All @@ -83,11 +136,16 @@ class InMemoryBaker(
*/
@JvmStatic
fun javaAsync(config: BakerConfig, implementations: List<Any>): CompletableFuture<JavaBaker> {
return javaAsync(config, implementations, defaultTracer())
}

@JvmStatic
fun javaAsync(config: BakerConfig, implementations: List<Any>, tracer: Tracer): CompletableFuture<JavaBaker> {
val futureToCompletableFuture = InMemoryEffects.futureToCompletableFuture()
val completableFutureToFuture = InMemoryEffects.completableFutureToFuture()
val scalaInteractions = InMemoryEffects.toScalaCompletableFutureInteractions(implementations)

return build(config, scalaInteractions)
return build(config, scalaInteractions, tracer)
.thenApply { bakerF ->
JavaBaker(bakerF.asDeprecatedFutureImplementation(completableFutureToFuture, futureToCompletableFuture))
}
Expand Down Expand Up @@ -115,5 +173,17 @@ class InMemoryBaker(
/**
* Attempts to gracefully shutdown the baker system.
*/
override fun gracefulShutdown(): CompletableFuture<Any> = InMemoryEffects.unit()
override fun gracefulShutdown(): CompletableFuture<Any> {
traceContexts.clear()
return InMemoryEffects.unit()
}

private fun registerTracingListener() {
try {
InMemoryEffects.runSync(registerBakerEventListener(BakerEventTracingListener(tracer, traceContexts)))
} catch (_: Throwable) {
// Tracing must never prevent Baker startup.
}
}

}
Loading
Loading