diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index de425030..deabdc18 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -111,6 +111,16 @@ See Logging in the https://rocketraman.github.io/bootable/[documentation]. * `JSON` no longer writes the logging context's `trace_id`, `span_id`, and `trace_flags` as fields of those names. * `JSON` and `GCLOUD` also write an existing map message's entries, such as a `StringMapMessage`'s, as top-level fields. +=== Clock + +See Clock in the https://rocketraman.github.io/bootable/[documentation]. + +* `boot-clock` binds the application's clock once, as a `kotlin.time.Clock` and a `java.time.Clock`. +* The `java.time.Clock` wraps the `kotlin.time.Clock`, in UTC, so a test that replaces one replaces both. +* The modules that take a `kotlin.time.Clock` binding, if there is one, take this one. +* `asJavaClock()` and `asKotlinClock()` wrap either clock as the other. +* Koin, Metro, and Inara flavors, and a deprecated Kodein flavor. + === HTTP clients (Ktor) See the HTTP client in the https://rocketraman.github.io/bootable/[documentation]. diff --git a/boot-clock/src/inara/kotlin/com/github/rocketraman/bootable/clock/ClockModule.kt b/boot-clock/src/inara/kotlin/com/github/rocketraman/bootable/clock/ClockModule.kt new file mode 100644 index 00000000..923103d1 --- /dev/null +++ b/boot-clock/src/inara/kotlin/com/github/rocketraman/bootable/clock/ClockModule.kt @@ -0,0 +1,25 @@ +@file:JvmName("ClockModuleInara") + +package com.github.rocketraman.bootable.clock + +import java.time.Clock as JClock +import org.kodein.di.inara.Binding +import org.kodein.di.inara.DIModule +import kotlin.time.Clock + +/** + * The Inara module that provides the application's clock, as a `kotlin.time.Clock` and as a `java.time.Clock`, for + * the application's own modules to require. Compose [clockModule], with `Clock.System`, or, in a test, with a clock + * of its own. + */ +@DIModule +interface ClockModule { + val clock: Clock + val javaClock: JClock +} + +/** A [ClockModule] on [clock], whose `java.time.Clock` is [clock] in UTC, with [asJavaClock]. */ +fun clockModule(clock: Clock = Clock.System): ClockModule = ClockModule( + clock = Binding.value(clock), + javaClock = Binding.single { this.clock.asJavaClock() }, +) diff --git a/boot-clock/src/kodein/kotlin/com/github/rocketraman/bootable/clock/ClockModule.kt b/boot-clock/src/kodein/kotlin/com/github/rocketraman/bootable/clock/ClockModule.kt new file mode 100644 index 00000000..2d1fca8e --- /dev/null +++ b/boot-clock/src/kodein/kotlin/com/github/rocketraman/bootable/clock/ClockModule.kt @@ -0,0 +1,21 @@ +package com.github.rocketraman.bootable.clock + +import java.time.Clock as JClock +import org.kodein.di.DI +import org.kodein.di.bindSingleton +import org.kodein.di.instance +import kotlin.time.Clock + +/** + * A Kodein module that binds the application's clock, [clock], `Clock.System` by default, as a `kotlin.time.Clock`, + * and the same clock as a `java.time.Clock` in UTC, with [asJavaClock]. + * + * The `java.time.Clock` binding wraps the `kotlin.time.Clock` binding, so a test that binds its own `kotlin.time.Clock`, + * with `bindSingleton(overrides = true) { testClock }`, or that imports `clockModule(testClock)`, sets both. + * The Bootable modules that take a `kotlin.time.Clock` binding, if there is one, take this one. + */ +@Deprecated("Kodein is deprecated: use the -inara flavor, or the -koin flavor for a DSL like Kodein's") +fun clockModule(clock: Clock = Clock.System): DI.Module = DI.Module("clockModule") { + bindSingleton { clock } + bindSingleton { instance().asJavaClock() } +} diff --git a/boot-clock/src/koin/kotlin/com/github/rocketraman/bootable/clock/koin/ClockModule.kt b/boot-clock/src/koin/kotlin/com/github/rocketraman/bootable/clock/koin/ClockModule.kt new file mode 100644 index 00000000..1e214f56 --- /dev/null +++ b/boot-clock/src/koin/kotlin/com/github/rocketraman/bootable/clock/koin/ClockModule.kt @@ -0,0 +1,20 @@ +package com.github.rocketraman.bootable.clock.koin + +import com.github.rocketraman.bootable.clock.asJavaClock +import java.time.Clock as JClock +import org.koin.core.module.Module +import org.koin.dsl.module +import kotlin.time.Clock + +/** + * A Koin module that defines the application's clock, [clock], `Clock.System` by default, as a `kotlin.time.Clock`, + * and the same clock as a `java.time.Clock` in UTC, with [asJavaClock]. + * + * The `java.time.Clock` definition gets the `kotlin.time.Clock` definition, so a test that defines its own + * `kotlin.time.Clock` after this module, with `single { testClock }`, or that includes `clockModule(testClock)`, + * sets both. The Bootable modules that take a `kotlin.time.Clock` definition, if there is one, take this one. + */ +fun clockModule(clock: Clock = Clock.System): Module = module { + single { clock } + single { get().asJavaClock() } +} diff --git a/boot-clock/src/main/kotlin/com/github/rocketraman/bootable/clock/Clocks.kt b/boot-clock/src/main/kotlin/com/github/rocketraman/bootable/clock/Clocks.kt new file mode 100644 index 00000000..76dea3ea --- /dev/null +++ b/boot-clock/src/main/kotlin/com/github/rocketraman/bootable/clock/Clocks.kt @@ -0,0 +1,58 @@ +package com.github.rocketraman.bootable.clock + +import java.time.Clock as JClock +import java.time.Instant as JInstant +import java.time.ZoneId +import java.time.ZoneOffset +import kotlin.time.Clock +import kotlin.time.Instant +import kotlin.time.toJavaInstant +import kotlin.time.toKotlinInstant + +/** + * Wraps the Kotlin `Clock` receiver as a `java.time.Clock` in [zone], UTC by default. + * + * The `java.time.Clock` wrapper simply delegates to the underlying Kotlin `Clock`. + * A good use case for this is to adapt a Kotlin `Clock`, such as a test clock, to a library that takes a + * `java.time.Clock`, without creating a new clock. + * + * [Clock.System] becomes `java.time.Clock.system(zone)`, such as `java.time.Clock.systemUTC()`. A receiver from + * [asKotlinClock] is unwrapped: the result is simply the original wrapped `java.time.Clock`, in [zone]. + */ +fun Clock.asJavaClock(zone: ZoneId = ZoneOffset.UTC): JClock = when (this) { + Clock.System -> JClock.system(zone) + is KotlinClockOfJava -> javaClock.withZone(zone) + else -> JavaClockOfKotlin(this, zone) +} + +/** + * Wraps the `java.time.Clock` receiver as a Kotlin `Clock`. + * + * The Kotlin `Clock` wrapper simply delegates to the underlying `java.time.Clock`. + * A good use case for this is to adapt a `java.time.Clock` to a Kotlin `Clock`, without creating a new clock, such as + * in tests. + * + * A receiver from [asJavaClock] is unwrapped: the result is simply the original wrapped Kotlin `Clock`. + * `java.time.Clock.systemUTC()`, or any other system clock, becomes [Clock.System]. + */ +fun JClock.asKotlinClock(): Clock = when { + this is JavaClockOfKotlin -> clock + this == JClock.system(zone) -> Clock.System + else -> KotlinClockOfJava(this) +} + +private class JavaClockOfKotlin(val clock: Clock, private val zone: ZoneId) : JClock() { + override fun getZone(): ZoneId = zone + override fun withZone(zone: ZoneId): JClock = if (zone == this.zone) this else JavaClockOfKotlin(clock, zone) + override fun instant(): JInstant = clock.now().toJavaInstant() + override fun equals(other: Any?) = other is JavaClockOfKotlin && other.clock == clock && other.zone == zone + override fun hashCode() = clock.hashCode() xor zone.hashCode() + override fun toString() = "JavaClock($clock, $zone)" +} + +private class KotlinClockOfJava(val javaClock: JClock) : Clock { + override fun now(): Instant = javaClock.instant().toKotlinInstant() + override fun equals(other: Any?) = other is KotlinClockOfJava && other.javaClock == javaClock + override fun hashCode() = javaClock.hashCode() + override fun toString() = "KotlinClock($javaClock)" +} diff --git a/boot-clock/src/metro/kotlin/com/github/rocketraman/bootable/clock/ClockBindings.kt b/boot-clock/src/metro/kotlin/com/github/rocketraman/bootable/clock/ClockBindings.kt new file mode 100644 index 00000000..71e77b94 --- /dev/null +++ b/boot-clock/src/metro/kotlin/com/github/rocketraman/bootable/clock/ClockBindings.kt @@ -0,0 +1,24 @@ +package com.github.rocketraman.bootable.clock + +import com.github.rocketraman.bootable.boot.BootScope +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides +import java.time.Clock as JClock +import kotlin.time.Clock + +/** + * Provides the application's clock, `Clock.System`, as a `kotlin.time.Clock`, and the same clock as a + * `java.time.Clock` in UTC, with [asJavaClock]. + * + * The `java.time.Clock` is the graph's `kotlin.time.Clock`, so a test that gives its graph another `kotlin.time.Clock`, + * such as with a binding container of its own passed to `createDynamicGraph`, sets both. The Bootable bindings that + * take the graph's `kotlin.time.Clock`, if it has one, take this one. + */ +@ContributesTo(BootScope::class) +interface ClockBindings { + companion object { + @Provides fun clock(): Clock = Clock.System + + @Provides fun javaClock(clock: Clock): JClock = clock.asJavaClock() + } +} diff --git a/boot-clock/src/test/kotlin/com/github/rocketraman/bootable/clock/ClockWiringTest.kt b/boot-clock/src/test/kotlin/com/github/rocketraman/bootable/clock/ClockWiringTest.kt new file mode 100644 index 00000000..0794f54e --- /dev/null +++ b/boot-clock/src/test/kotlin/com/github/rocketraman/bootable/clock/ClockWiringTest.kt @@ -0,0 +1,180 @@ +@file:Suppress("DEPRECATION") // the deprecated Kodein flavor is still tested + +package com.github.rocketraman.bootable.clock + +import com.github.rocketraman.bootable.boot.BootScope +import com.github.rocketraman.bootable.boot.koin.bootableModule as koinBootableModule +import com.github.rocketraman.bootable.boot.bootableModule +import com.github.rocketraman.bootable.clock.koin.clockModule as koinClockModule +import com.github.rocketraman.bootable.leader.AlwaysLeaderModule +import com.github.rocketraman.bootable.leader.LeaderElectionModule +import com.github.rocketraman.bootable.periodic.PeriodicModule +import com.github.rocketraman.bootable.periodic.PeriodicServices +import com.github.rocketraman.bootable.periodic.koin.periodicModule as koinPeriodicModule +import com.github.rocketraman.bootable.periodic.periodicModule +import com.github.rocketraman.bootable.telemetry.otel.NoopOpenTelemetryModule +import com.github.rocketraman.bootable.telemetry.otel.OpenTelemetryApiModule +import com.github.rocketraman.bootable.test.TestClock +import de.infix.testBalloon.framework.core.testSuite +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.DependencyGraph +import dev.zacsweers.metro.Provides +import dev.zacsweers.metro.createDynamicGraph +import dev.zacsweers.metro.createGraph +import java.time.Clock as JClock +import kotlin.time.Duration.Companion.hours +import org.kodein.di.DI +import org.kodein.di.bindSingleton +import org.kodein.di.direct +import org.kodein.di.inara.DIModule +import org.kodein.di.instance +import org.koin.dsl.koinApplication +import org.koin.dsl.module +import kotlin.time.Clock +import kotlin.time.toJavaInstant + +sealed interface TestScope + +@DependencyGraph(TestScope::class, additionalScopes = [BootScope::class]) +interface ClockGraph { + val clock: Clock + val javaClock: JClock + val periodicServices: PeriodicServices +} + +/** A test's clock, in place of the graph's. */ +@BindingContainer +class TestClockBindings(private val clock: TestClock) { + @Provides fun clock(): Clock = clock +} + +/** An application's module, composed as an Inara application composes it, with its clock. */ +@DIModule(composed = true) +interface ClockAppModule : ClockModule, LeaderElectionModule, OpenTelemetryApiModule, PeriodicModule + +// a call resolves to the Kodein flavor's clockModule, of the same signature; a reference of this type to Inara's +private val inaraClockModule: (Clock) -> ClockModule = ::clockModule + +private fun clockAppModule(clock: Clock = Clock.System): ClockAppModule { + val clockModule = inaraClockModule(clock) + return ClockAppModule( + clockModule = clockModule, + leaderElectionModule = AlwaysLeaderModule, + openTelemetryApiModule = NoopOpenTelemetryModule, + periodicModule = periodicModule(clockModule.clock), + ) +} + +/** Checks [javaClock] wraps [clock], by moving [clock]. */ +private fun checkWraps(javaClock: JClock, clock: TestClock) { + assert(javaClock.instant() == clock.now().toJavaInstant()) + clock.advanceBy(1.hours) + assert(javaClock.instant() == clock.now().toJavaInstant()) +} + +val ClockWiringTest by testSuite { + testSuite("kodein") { + test("binds the system clock, as both clocks, for the modules that take a clock") { + val di = DI { + import(bootableModule) + import(clockModule()) + import(periodicModule) + }.direct + assert(di.instance() == Clock.System) + assert(di.instance() == JClock.systemUTC()) + assert(di.instance().clock == Clock.System) + } + + test("a test's clock, in place of the module's, sets both clocks") { + val testClock = TestClock() + val di = DI { + import(bootableModule) + import(clockModule()) + import(periodicModule) + bindSingleton(overrides = true) { testClock } + }.direct + assert(di.instance() === testClock) + assert(di.instance().clock === testClock) + checkWraps(di.instance(), testClock) + } + + test("binds the clock it is given") { + val testClock = TestClock() + val di = DI { import(clockModule(testClock)) }.direct + assert(di.instance() === testClock) + checkWraps(di.instance(), testClock) + } + } + + testSuite("koin") { + test("defines the system clock, as both clocks, for the modules that take a clock") { + val koin = koinApplication { modules(koinBootableModule(), koinClockModule(), koinPeriodicModule()) }.koin + try { + assert(koin.get() == Clock.System) + assert(koin.get() == JClock.systemUTC()) + assert(koin.get().clock == Clock.System) + } finally { + koin.close() + } + } + + test("a test's clock, defined after the module's, sets both clocks") { + val testClock = TestClock() + val koin = koinApplication { + modules(koinBootableModule(), koinClockModule(), koinPeriodicModule(), module { single { testClock } }) + }.koin + try { + assert(koin.get() === testClock) + assert(koin.get().clock === testClock) + checkWraps(koin.get(), testClock) + } finally { + koin.close() + } + } + + test("defines the clock it is given") { + val testClock = TestClock() + val koin = koinApplication { modules(koinClockModule(testClock)) }.koin + try { + assert(koin.get() === testClock) + checkWraps(koin.get(), testClock) + } finally { + koin.close() + } + } + } + + testSuite("metro") { + test("provides the system clock, as both clocks, for the bindings that take a clock") { + val graph = createGraph() + assert(graph.clock == Clock.System) + assert(graph.javaClock == JClock.systemUTC()) + assert(graph.periodicServices.clock == Clock.System) + } + + test("a test's clock, in a dynamic graph, sets both clocks") { + val testClock = TestClock() + val graph = createDynamicGraph(TestClockBindings(testClock)) + assert(graph.clock === testClock) + assert(graph.periodicServices.clock === testClock) + checkWraps(graph.javaClock, testClock) + } + } + + testSuite("inara") { + test("provides the system clock, as both clocks") { + val module = clockAppModule() + assert(module.clock == Clock.System) + assert(module.javaClock == JClock.systemUTC()) + assert(module.periodicServices.clock == Clock.System) + } + + test("provides the clock it is given, as both clocks") { + val testClock = TestClock() + val module = clockAppModule(testClock) + assert(module.clock === testClock) + assert(module.periodicServices.clock === testClock) + checkWraps(module.javaClock, testClock) + } + } +} diff --git a/boot-clock/src/test/kotlin/com/github/rocketraman/bootable/clock/ClocksTest.kt b/boot-clock/src/test/kotlin/com/github/rocketraman/bootable/clock/ClocksTest.kt new file mode 100644 index 00000000..8c8d901b --- /dev/null +++ b/boot-clock/src/test/kotlin/com/github/rocketraman/bootable/clock/ClocksTest.kt @@ -0,0 +1,60 @@ +package com.github.rocketraman.bootable.clock + +import com.github.rocketraman.bootable.test.TestClock +import de.infix.testBalloon.framework.core.testSuite +import java.time.Clock as JClock +import java.time.ZoneId +import java.time.ZoneOffset +import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes +import kotlin.time.toJavaInstant +import kotlin.time.toKotlinInstant + +val ClocksTest by testSuite { + test("a kotlin clock as a java clock wraps the kotlin clock, in UTC") { + val clock = TestClock() + val javaClock = clock.asJavaClock() + assert(javaClock.zone == ZoneOffset.UTC) + assert(javaClock.instant() == TestClock.DEFAULT_START.toJavaInstant()) + clock.advanceBy(5.minutes) + assert(javaClock.instant() == (TestClock.DEFAULT_START + 5.minutes).toJavaInstant()) + assert(javaClock.millis() == (TestClock.DEFAULT_START + 5.minutes).toEpochMilliseconds()) + } + + test("a kotlin clock as a java clock in a zone, and in another") { + val clock = TestClock() + val toronto = ZoneId.of("America/Toronto") + val javaClock = clock.asJavaClock(toronto) + assert(javaClock.zone == toronto) + assert(javaClock.withZone(toronto) == javaClock) + val inUtc = javaClock.withZone(ZoneOffset.UTC) + assert(inUtc.zone == ZoneOffset.UTC) + assert(inUtc == clock.asJavaClock()) + assert(inUtc.instant() == javaClock.instant()) + } + + test("the system clock as a java clock is java's system clock") { + assert(Clock.System.asJavaClock() == JClock.systemUTC()) + val toronto = ZoneId.of("America/Toronto") + assert(Clock.System.asJavaClock(toronto) == JClock.system(toronto)) + } + + test("a java clock as a kotlin clock wraps the java clock") { + val javaClock = JClock.fixed(TestClock.DEFAULT_START.toJavaInstant(), ZoneOffset.UTC) + val clock = javaClock.asKotlinClock() + assert(clock.now() == TestClock.DEFAULT_START) + assert(javaClock.instant().toKotlinInstant() == clock.now()) + } + + test("java's system clock, in any zone, as a kotlin clock is the system clock") { + assert(JClock.systemUTC().asKotlinClock() == Clock.System) + assert(JClock.system(ZoneId.of("America/Toronto")).asKotlinClock() == Clock.System) + } + + test("a clock converted and converted back is the clock it was") { + val clock = TestClock() + assert(clock.asJavaClock().asKotlinClock() === clock) + val javaClock = JClock.fixed(TestClock.DEFAULT_START.toJavaInstant(), ZoneOffset.UTC) + assert(javaClock.asKotlinClock().asJavaClock() == javaClock) + } +} diff --git a/boot-test/src/main/kotlin/com/github/rocketraman/bootable/test/TestClock.kt b/boot-test/src/main/kotlin/com/github/rocketraman/bootable/test/TestClock.kt index 5679e1a5..d4193fc5 100644 --- a/boot-test/src/main/kotlin/com/github/rocketraman/bootable/test/TestClock.kt +++ b/boot-test/src/main/kotlin/com/github/rocketraman/bootable/test/TestClock.kt @@ -10,7 +10,8 @@ import kotlin.time.Instant * move from any thread. * * Bind it where the application takes a `kotlin.time.Clock`, such as `OpenTelemetryService` and - * `ServiceStartTracing`, which take their time from the `Clock` binding, with Koin, Kodein, or Metro, if there is one. For a + * `ServiceStartTracing`, which take their time from the `Clock` binding, with Koin, Kodein, or Metro, if there is one, + * such as boot-clock's, in place of that binding. boot-clock's `asJavaClock()` is it as a `java.time.Clock`. For a * monotonic `TimeSource`, use the standard library's `kotlin.time.TestTimeSource`. */ class TestClock(start: Instant = DEFAULT_START) : Clock { diff --git a/build.gradle.kts b/build.gradle.kts index 259b6580..6f211d55 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -39,6 +39,7 @@ dependencies { dokka(project(":boot-client-http-ktor-cio")) dokka(project(":boot-client-http-ktor-java")) dokka(project(":boot-client-http-ktor-otel")) + dokka(project(":boot-clock")) dokka(project(":boot-common")) dokka(project(":boot-config-common")) dokka(project(":boot-config-hoplite")) @@ -381,6 +382,36 @@ project("boot-client-http-ktor-otel") { } } +// the application's clock, as a kotlin.time.Clock and a java.time.Clock, bound once for the application and its tests +project("boot-clock") { + configureDiVariants() + dependencies { + // the metro flavor contributes to boot's BootScope + "metroApi"(project(path = ":boot", configuration = "metroElements")) + + // the tests check that the Bootable modules which take a clock take this one, in each flavor + testImplementation(project(":boot-test")) + testImplementation(project(path = ":boot", configuration = "kodeinElements")) + testImplementation(project(path = ":boot", configuration = "koinElements")) + testImplementation(project(path = ":boot", configuration = "inaraElements")) + testImplementation(project(path = ":boot", configuration = "metroElements")) + testImplementation(project(path = ":boot-config-hoplite", configuration = "metroElements")) + testImplementation(project(path = ":boot-periodic", configuration = "kodeinElements")) + testImplementation(project(path = ":boot-periodic", configuration = "koinElements")) + testImplementation(project(path = ":boot-periodic", configuration = "inaraElements")) + testImplementation(project(path = ":boot-periodic", configuration = "metroElements")) + testImplementation(project(":boot-logging-log4j2")) + } + + // the tests compose the inara flavor into a module of their own, as an application does + configurations["testImplementation"].extendsFrom(configurations["inaraApi"]) + dependencies { "kspTest"(rootProject.libs.inara.processor) } + sourceSets.named("test") { + compileClasspath += sourceSets["kodein"].output + sourceSets["koin"].output + sourceSets["metro"].output + sourceSets["inara"].output + runtimeClasspath += sourceSets["kodein"].output + sourceSets["koin"].output + sourceSets["metro"].output + sourceSets["inara"].output + } +} + project("boot-common") { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:${rootProject.libs.versions.kotlinx.coroutines.get()}") diff --git a/docs/antora.yml b/docs/antora.yml index 69c6eaeb..6d86cfd9 100644 --- a/docs/antora.yml +++ b/docs/antora.yml @@ -65,6 +65,9 @@ ext: - scan: dir: docs/snippets/metro/background/src/main/kotlin/snippets into: modules/ROOT/examples/metro + - scan: + dir: docs/snippets/metro/clock/src/main/kotlin/snippets + into: modules/ROOT/examples/metro - scan: dir: docs/snippets/metro/testing/src/main/kotlin/snippets into: modules/ROOT/examples/metro diff --git a/docs/modules.yml b/docs/modules.yml index 1ecd2968..c02dddce 100644 --- a/docs/modules.yml +++ b/docs/modules.yml @@ -63,6 +63,15 @@ functions: provides: '`environment`: the deployment environment, such as dev or prod, from config' page: environment:index.adoc +- id: clock + title: Clock + page: clock:index.adoc + groups: + - modules: + - name: boot-clock + provides: 'The application''s clock, as a `kotlin.time.Clock` and a `java.time.Clock`, bound once, for a test to replace' + page: clock:index.adoc + - id: logging title: Logging page: logging:index.adoc diff --git a/docs/modules/ROOT/nav-functions.adoc b/docs/modules/ROOT/nav-functions.adoc index 4688c2fb..241a1ed2 100644 --- a/docs/modules/ROOT/nav-functions.adoc +++ b/docs/modules/ROOT/nav-functions.adoc @@ -1,6 +1,7 @@ .Functions * xref:configuration:index.adoc[Configuration] * xref:environment:index.adoc[Environment] +* xref:clock:index.adoc[Clock] * xref:logging:index.adoc[Logging (Log4j2)] * xref:database:index.adoc[Database] ** xref:database:drivers.adoc[Drivers] diff --git a/docs/modules/clock/pages/index.adoc b/docs/modules/clock/pages/index.adoc new file mode 100644 index 00000000..c38c7520 --- /dev/null +++ b/docs/modules/clock/pages/index.adoc @@ -0,0 +1,141 @@ += Clock +:description: boot-clock: the application's clock, bound once, as a kotlin.time.Clock and a java.time.Clock, for a test to replace with its own. + +Code that reads the time takes a clock, rather than reading the system's, so that a test can set the time. +`boot-clock` binds the application's clock once, for the application's code and Bootable's modules to share, so an application doesn't bind its own, and a test replaces it in one place. + +It binds the clock as a `kotlin.time.Clock`, which Bootable's modules take, and as a `java.time.Clock`, which many Java libraries take. +The `java.time.Clock` wraps the `kotlin.time.Clock`, in UTC, so a test that replaces the `kotlin.time.Clock` replaces both. + +== Modules + +modules::clock[] + +== Install + +install::[boot-clock] + +== The clocks + +The clock is `Clock.System`, unless the application or a test gives another, such as boot-test's xref:testing:index.adoc#clock[`TestClock`]. + +Its `java.time.Clock` is `asJavaClock()` of the `kotlin.time.Clock`, in UTC unless given another zone. +It wraps the `kotlin.time.Clock` rather than copying its time, so it always tells the time the `kotlin.time.Clock` does, such as a `TestClock` a test has moved. +`Clock.System` is `java.time.Clock.systemUTC()`. +`asKotlinClock()` wraps a `java.time.Clock` the same way, such as a `java.time.Clock.fixed(...)` a test already has. + +The examples on this page wire two classes, one that takes each clock: + +[source,kotlin] +---- +include::ROOT:example$common/clock/Invoices.kt[] +---- + +== Wire + +The Bootable modules that take a `kotlin.time.Clock`, such as xref:background:periodic.adoc[`boot-periodic`], xref:background:leader.adoc[`boot-leader-k8s`], xref:background:scheduler.adoc[`boot-scheduler-db`], and xref:telemetry:index.adoc[`boot-telemetry-otel`], take the bound clock, if there is one, with Kodein, Koin, and Metro; with Inara, pass it to their builders. + +[tabs,sync-group-id=di] +====== +Vanilla:: ++ +Pass the clock to each class that takes one, and `asJavaClock()` of it to each that takes a `java.time.Clock`: ++ +[source,kotlin] +---- +include::ROOT:example$vanilla/clock/Clock.kt[tag=wire] +---- + +Kodein:: ++ +Import `clockModule(clock)`, which binds both clocks, `Clock.System` by default: ++ +[source,kotlin] +---- +include::ROOT:example$kodein/clock/Clock.kt[tag=wire] +---- ++ +The `java.time.Clock` binding wraps the `kotlin.time.Clock` binding, so a binding of a `kotlin.time.Clock` of your own, with `overrides = true`, replaces both. + +Koin:: ++ +Include `clockModule(clock)`, which defines both clocks, `Clock.System` by default: ++ +[source,kotlin] +---- +include::ROOT:example$koin/clock/Clock.kt[tag=wire] +---- ++ +The `java.time.Clock` definition gets the `kotlin.time.Clock` definition, so a definition of a `kotlin.time.Clock` of your own, after this module's, replaces both. + +Metro:: ++ +`boot-clock-metro` contributes both clocks, `Clock.System`, to the graph: ++ +[source,kotlin] +---- +include::ROOT:example$metro/clock/Clock.kt[tag=wire] +---- ++ +The `java.time.Clock` is the graph's `kotlin.time.Clock`, so a graph with another `kotlin.time.Clock` has it as both. + +Inara:: ++ +Compose `clockModule(clock)`, a `ClockModule` that provides both clocks, `Clock.System` by default, and require the `ClockModule` in the application's own modules: ++ +[source,kotlin] +---- +include::ROOT:example$inara/clock/Clock.kt[tag=wire] +---- ++ +Inara has no optional bindings, so Bootable's Inara modules take their clock as a builder parameter, such as `periodicModule(clock)`: pass them the same clock. +====== + +== Test + +A test gives the application a clock of its own, which then is both clocks. + +[tabs,sync-group-id=di] +====== +Vanilla:: ++ +[source,kotlin] +---- +include::ROOT:example$vanilla/clock/Clock.kt[tag=test] +---- + +Kodein:: ++ +[source,kotlin] +---- +include::ROOT:example$kodein/clock/Clock.kt[tag=test] +---- + +Koin:: ++ +[source,kotlin] +---- +include::ROOT:example$koin/clock/Clock.kt[tag=test] +---- + +Metro:: ++ +A dynamic graph, with a binding container of the test's own, replaces the graph's `kotlin.time.Clock`: ++ +[source,kotlin] +---- +include::ROOT:example$metro/clock/Clock.kt[tag=test] +---- + +Inara:: ++ +[source,kotlin] +---- +include::ROOT:example$inara/clock/Clock.kt[tag=test] +---- +====== + +== Reference + +* kdoc:boot-clock:com.github.rocketraman.bootable.clock.asJavaClock[]: a `kotlin.time.Clock` as a `java.time.Clock` +* kdoc:boot-clock:com.github.rocketraman.bootable.clock.asKotlinClock[]: a `java.time.Clock` as a `kotlin.time.Clock` diff --git a/docs/modules/testing/pages/index.adoc b/docs/modules/testing/pages/index.adoc index 7ccab70d..7bec6943 100644 --- a/docs/modules/testing/pages/index.adoc +++ b/docs/modules/testing/pages/index.adoc @@ -60,6 +60,7 @@ include::ROOT:example$vanilla/testing/Helpers.kt[tag=clock] ---- Pass it to whatever takes a `Clock`, such as `OpenTelemetryService`, `ServiceStartTracing`, or `PeriodicAppService`, or, with Kodein, Koin, or Metro, bind it as the `Clock`, which they then take their time from; with Inara, which has no optional bindings, pass it to each module's builder, such as `openTelemetryModule(clock)`. +With xref:clock:index.adoc[`boot-clock`], give it to the application in place of the bound clock, which makes it the application's `java.time.Clock` too; `asJavaClock()` is it as a `java.time.Clock`, for a class that takes one. For a monotonic `TimeSource`, use the standard library's `kotlin.time.TestTimeSource`. [#logs] diff --git a/docs/snippets/common/src/main/kotlin/snippets/clock/Invoices.kt b/docs/snippets/common/src/main/kotlin/snippets/clock/Invoices.kt new file mode 100644 index 00000000..de18c98c --- /dev/null +++ b/docs/snippets/common/src/main/kotlin/snippets/clock/Invoices.kt @@ -0,0 +1,18 @@ +package snippets.clock + +import java.time.Clock as JClock +import java.time.Instant as JInstant +import kotlin.time.Clock +import kotlin.time.Instant + +data class Invoice(val issuedAt: Instant) + +/** The application's own class, which dates each invoice it issues by its `kotlin.time.Clock`. */ +class Invoices(private val clock: Clock) { + fun issue(): Invoice = Invoice(issuedAt = clock.now()) +} + +/** A class, such as a library's, which takes a `java.time.Clock`. */ +class TokenSigner(private val clock: JClock) { + fun expiry(): JInstant = clock.instant().plusSeconds(3600) +} diff --git a/docs/snippets/inara/build.gradle.kts b/docs/snippets/inara/build.gradle.kts index ed6be223..c93c93fb 100644 --- a/docs/snippets/inara/build.gradle.kts +++ b/docs/snippets/inara/build.gradle.kts @@ -9,6 +9,7 @@ plugins { dependencies { implementation(project(":docs:snippets:common")) implementation(project(path = ":boot", configuration = "inaraElements")) + implementation(project(path = ":boot-clock", configuration = "inaraElements")) implementation(project(path = ":boot-config-hoplite", configuration = "inaraElements")) implementation(project(path = ":boot-env", configuration = "inaraElements")) implementation(project(path = ":boot-db-jdbc-sqlite", configuration = "inaraElements")) diff --git a/docs/snippets/inara/src/main/kotlin/snippets/clock/Clock.kt b/docs/snippets/inara/src/main/kotlin/snippets/clock/Clock.kt new file mode 100644 index 00000000..81f07db7 --- /dev/null +++ b/docs/snippets/inara/src/main/kotlin/snippets/clock/Clock.kt @@ -0,0 +1,37 @@ +package snippets.clock + +import com.github.rocketraman.bootable.clock.ClockModule +import com.github.rocketraman.bootable.clock.clockModule +import com.github.rocketraman.bootable.test.TestClock +import org.kodein.di.inara.Binding +import org.kodein.di.inara.DIModule +import kotlin.time.Clock + +// tag::wire[] +@DIModule +interface InvoicesModule : @DIModule.Required ClockModule { + val invoices: Invoices + val tokenSigner: TokenSigner +} + +val invoicesModule = InvoicesModulePart( + invoices = Binding.single { Invoices(clock) }, + tokenSigner = Binding.single { TokenSigner(javaClock) }, +) + +@DIModule(composed = true) +interface ClockAppModule : ClockModule, InvoicesModule + +/** The application's module, on [clock]: `Clock.System`, or a test's. */ +fun clockAppModule(clock: Clock = Clock.System) = ClockAppModule( + clockModule = clockModule(clock), + invoicesModule = invoicesModule, +) +// end::wire[] + +// tag::test[] +fun invoicesAreDatedByTheClock() { + val clock = TestClock() + assert(clockAppModule(clock).invoices.issue().issuedAt == clock.now()) +} +// end::test[] diff --git a/docs/snippets/kodein/build.gradle.kts b/docs/snippets/kodein/build.gradle.kts index 871938cf..9e10312f 100644 --- a/docs/snippets/kodein/build.gradle.kts +++ b/docs/snippets/kodein/build.gradle.kts @@ -7,6 +7,7 @@ plugins { dependencies { implementation(project(":docs:snippets:common")) implementation(project(path = ":boot", configuration = "kodeinElements")) + implementation(project(path = ":boot-clock", configuration = "kodeinElements")) implementation(project(path = ":boot-config-hoplite", configuration = "kodeinElements")) implementation(project(path = ":boot-env", configuration = "kodeinElements")) implementation(project(path = ":boot-db-jdbc-sqlite", configuration = "kodeinElements")) diff --git a/docs/snippets/kodein/src/main/kotlin/snippets/clock/Clock.kt b/docs/snippets/kodein/src/main/kotlin/snippets/clock/Clock.kt new file mode 100644 index 00000000..3b988bc3 --- /dev/null +++ b/docs/snippets/kodein/src/main/kotlin/snippets/clock/Clock.kt @@ -0,0 +1,32 @@ +@file:Suppress("DEPRECATION") // the Kodein flavor is deprecated + +package snippets.clock + +import com.github.rocketraman.bootable.clock.clockModule +import com.github.rocketraman.bootable.test.TestClock +import org.kodein.di.DI +import org.kodein.di.bindSingleton +import org.kodein.di.direct +import org.kodein.di.instance +import kotlin.time.Clock + +// tag::wire[] +val invoicesModule by DI.Module { + bindSingleton { Invoices(instance()) } + bindSingleton { TokenSigner(instance()) } +} + +/** The application's DI, on [clock]: `Clock.System`, or a test's. */ +fun appDI(clock: Clock = Clock.System) = DI { + import(clockModule(clock)) + import(invoicesModule) +} +// end::wire[] + +// tag::test[] +fun invoicesAreDatedByTheClock() { + val clock = TestClock() + val invoices = appDI(clock).direct.instance() + assert(invoices.issue().issuedAt == clock.now()) +} +// end::test[] diff --git a/docs/snippets/koin/build.gradle.kts b/docs/snippets/koin/build.gradle.kts index 9dd2aee6..b100b4ca 100644 --- a/docs/snippets/koin/build.gradle.kts +++ b/docs/snippets/koin/build.gradle.kts @@ -7,6 +7,7 @@ plugins { dependencies { implementation(project(":docs:snippets:common")) implementation(project(path = ":boot", configuration = "koinElements")) + implementation(project(path = ":boot-clock", configuration = "koinElements")) implementation(project(path = ":boot-config-hoplite", configuration = "koinElements")) implementation(project(path = ":boot-env", configuration = "koinElements")) implementation(project(path = ":boot-db-jdbc-sqlite", configuration = "koinElements")) diff --git a/docs/snippets/koin/src/main/kotlin/snippets/clock/Clock.kt b/docs/snippets/koin/src/main/kotlin/snippets/clock/Clock.kt new file mode 100644 index 00000000..a7959078 --- /dev/null +++ b/docs/snippets/koin/src/main/kotlin/snippets/clock/Clock.kt @@ -0,0 +1,29 @@ +package snippets.clock + +import com.github.rocketraman.bootable.clock.koin.clockModule +import com.github.rocketraman.bootable.test.TestClock +import org.koin.dsl.koinApplication +import org.koin.dsl.module +import kotlin.time.Clock + +// tag::wire[] +val invoicesModule = module { + single { Invoices(get()) } + single { TokenSigner(get()) } +} + +/** The application's modules, on [clock]: `Clock.System`, or a test's. */ +fun appModules(clock: Clock = Clock.System) = listOf(clockModule(clock), invoicesModule) +// end::wire[] + +// tag::test[] +fun invoicesAreDatedByTheClock() { + val clock = TestClock() + val koin = koinApplication { modules(appModules(clock)) }.koin + try { + assert(koin.get().issue().issuedAt == clock.now()) + } finally { + koin.close() + } +} +// end::test[] diff --git a/docs/snippets/metro/clock/build.gradle.kts b/docs/snippets/metro/clock/build.gradle.kts new file mode 100644 index 00000000..81d9d708 --- /dev/null +++ b/docs/snippets/metro/clock/build.gradle.kts @@ -0,0 +1,19 @@ +plugins { + kotlin("jvm") + id("dev.zacsweers.metro") +} + +// The Clock snippets, wired with Metro: boot-clock's metro flavor. +// In-repo that's the module's `metroElements` configuration; a downstream consumer depends on the module's +// `-metro` artifact. +// A project of its own, with only this function's modules, as an application has: a -metro module's bindings join +// every graph in the compilation, so another function's modules would need bindings these snippets don't have. +// The test helpers are on the main classpath here, so the snippets compile with the rest; an application adds them +// as test dependencies. +dependencies { + implementation(project(":docs:snippets:common")) + implementation(project(path = ":boot", configuration = "metroElements")) + implementation(project(path = ":boot-clock", configuration = "metroElements")) + // modules without DI flavours + implementation(project(":boot-test")) +} diff --git a/docs/snippets/metro/clock/src/main/kotlin/snippets/clock/Clock.kt b/docs/snippets/metro/clock/src/main/kotlin/snippets/clock/Clock.kt new file mode 100644 index 00000000..597bbd17 --- /dev/null +++ b/docs/snippets/metro/clock/src/main/kotlin/snippets/clock/Clock.kt @@ -0,0 +1,40 @@ +package snippets.clock + +import com.github.rocketraman.bootable.boot.BootScope +import com.github.rocketraman.bootable.test.TestClock +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.DependencyGraph +import dev.zacsweers.metro.Provides +import dev.zacsweers.metro.createDynamicGraph +import java.time.Clock as JClock +import kotlin.time.Clock + +sealed interface InvoicesScope + +// tag::wire[] +@DependencyGraph(InvoicesScope::class, additionalScopes = [BootScope::class], bindingContainers = [InvoicesBindings::class]) +interface InvoicesGraph { + val invoices: Invoices +} + +@BindingContainer +object InvoicesBindings { + // boot-clock-metro provides both clocks + @Provides fun invoices(clock: Clock): Invoices = Invoices(clock) + @Provides fun tokenSigner(clock: JClock): TokenSigner = TokenSigner(clock) +} +// end::wire[] + +// tag::test[] +/** A test's clock, in place of the graph's. */ +@BindingContainer +class TestClockBindings(private val clock: TestClock) { + @Provides fun clock(): Clock = clock +} + +fun invoicesAreDatedByTheClock() { + val clock = TestClock() + val graph = createDynamicGraph(TestClockBindings(clock)) + assert(graph.invoices.issue().issuedAt == clock.now()) +} +// end::test[] diff --git a/docs/snippets/vanilla/build.gradle.kts b/docs/snippets/vanilla/build.gradle.kts index 5e1817c1..5fdb3a2d 100644 --- a/docs/snippets/vanilla/build.gradle.kts +++ b/docs/snippets/vanilla/build.gradle.kts @@ -7,6 +7,7 @@ plugins { // The snippets, wired by hand: the plain coordinate of each module. dependencies { implementation(project(":docs:snippets:common")) + implementation(project(":boot-clock")) implementation(project(":boot-config-hoplite")) implementation(project(":boot-env")) implementation(project(":boot-db-jdbc-sqlite")) diff --git a/docs/snippets/vanilla/src/main/kotlin/snippets/clock/Clock.kt b/docs/snippets/vanilla/src/main/kotlin/snippets/clock/Clock.kt new file mode 100644 index 00000000..11c12511 --- /dev/null +++ b/docs/snippets/vanilla/src/main/kotlin/snippets/clock/Clock.kt @@ -0,0 +1,21 @@ +package snippets.clock + +import com.github.rocketraman.bootable.clock.asJavaClock +import com.github.rocketraman.bootable.test.TestClock +import kotlin.time.Clock + +// tag::wire[] +/** The application's components, on [clock]: `Clock.System`, or a test's. */ +class Components(clock: Clock = Clock.System) { + val invoices = Invoices(clock) + val tokenSigner = TokenSigner(clock.asJavaClock()) +} +// end::wire[] + +// tag::test[] +fun invoicesAreDatedByTheClock() { + val clock = TestClock() + val components = Components(clock) + assert(components.invoices.issue().issuedAt == clock.now()) +} +// end::test[] diff --git a/settings.gradle.kts b/settings.gradle.kts index fc79a0d5..67791cee 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,7 @@ include("boot-client-http-ktor") include("boot-client-http-ktor-cio") include("boot-client-http-ktor-java") include("boot-client-http-ktor-otel") +include("boot-clock") include("boot-common") include("boot-config-common") include("boot-config-hoplite") @@ -103,6 +104,7 @@ include(":docs:snippets:inara") include(":docs:snippets:kodein") include(":docs:snippets:koin") include(":docs:snippets:metro:background") +include(":docs:snippets:metro:clock") include(":docs:snippets:metro:concepts") include(":docs:snippets:metro:configuration") include(":docs:snippets:metro:database")