Core
reaktor-core is the module every other Reaktor module imports. It holds four things: Feature slots, which let shared code ask for a platform service without checking which platform it runs on; Capability, a marker for resources that must be closed; Adapter, a weak handle through which shared code drives a platform controller; and a few primitives for time, dispatchers, logging, atomics and JSON. Core does nothing a higher layer could do instead: it does no dependency injection and knows nothing about the graph.
Overview#
Read the picture from left to right. Each platform's start-up code installs the services it can provide, shared code picks each one up once at the edge of the app, and from there the graph hands it to the nodes that need it. Core holds only these hand-off points. Everything that decides how an app is wired lives a layer up.
What it contains#
| Piece | Where | Notes |
|---|---|---|
Feature slot registry and CreateSlot<T> | framework/Feature.kt | About 21 slots, used by BestBuds and most Reaktor modules |
Capability and AtomicCapability | capabilities/Capability.kt | close() runs once, guarded by an atomic compare-and-set |
Adapter<Controller> | framework/Adapter.kt | Holds the controller through a WeakRef |
WeakRef, AtomicInt, ConcurrentHashMap | framework/Expectations.kt, structs/ | expect/actual per target; WeakRef on JS keeps a strong reference |
epochTime(), Dispatch, Kermit logging, atomicfu | utils/, framework/Dispatch.kt | Thin wrappers over the kotlinx libraries |
| JSON defaults | framework/Json.kt | encodeDefaults, ignoreUnknownKeys, classDiscriminator = "type" |
| Platform code | src/{android,ios,jvm,js}Main | Android registers adapters with BaseActivity.connect(...) |
Paths are under reaktor-core/src/commonMain/kotlin/dev/shibasis/reaktor/core/.
Feature slots#
A module declares a slot, the platform start-up code fills it, and shared code reads it:
var Feature.Database by CreateSlot<ObjectDatabase>()
Feature.Database = sqlDelightDatabase()
val database = Feature.Database
Feature is a process-wide map from an integer slot id to the installed object, with lock-free reads and writes. A slot reads as null until something fills it, and setting it to null empties it again, which lets a test or a shutting-down shell remove what it installed. The slots in use include Auth, Database, Sql, GraphQl, Camera, Gallery, the speech recogniser and synthesiser, GooglePubSub, Work, Theme, Location, Compression, File, Permission, Storage, Analytics, Crashlytics, Telemetry and Dependency.
A slot registry is a service locator, with a service locator's cost: a missing registration fails when it is used, not at start-up. So read a slot at the edge of the app, at start-up or in a platform adapter, and pass the object on from there. Graph nodes get their collaborators through ports, never through Feature. Dependency injection belongs to Koin, reached through the Feature.Dependency slot.
Capability: a resource to close#
interface Capability : AutoCloseable
abstract class AtomicCapability : Capability {
private val closed = atomic(false)
final override fun close() {
if (closed.compareAndSet(expect = false, update = true)) doClose()
}
protected abstract fun doClose()
}
Holding a Capability means owning its lifecycle, nothing more. Closing twice is safe. The owner of a coroutine scope owns the cleanup of what runs in it: cancel the job and its resources close, and use { } closes on an exception too.
The word "capability" means different things across Reaktor, and none of them is a security token:
| In | Capability means |
|---|---|
reaktor-core | A resource that must be closed |
reaktor-graph, reaktor-graph-port | A behaviour a node composes, such as LifecycleCapability, DependencyScopeCapability or PortCapability |
| The capability runtime design | What the device or network can do right now, as a tier |
None of them grants authority, so read Reaktor's "capability" as one of these, not as the object-capability security model.
Adapter: a weak platform handle#
open class Adapter<Controller>(controller: Controller) : Component {
val ref: WeakRef<Controller> = WeakRef(controller)
val controller: Controller? get() = ref.get()
operator fun <R> invoke(fn: Controller.() -> R?): R?
suspend fun <R> suspended(fn: suspend Controller.() -> R?): R?
open fun handle(event: ControllerEvent) { }
}
Shared code drives an Android activity, an iOS view controller or a browser global through an adapter, without owning it or keeping it alive. A call returns null when the controller is gone, and invokeResult and suspendedResult return a Result instead. PermissionAdapter, StorageAdapter, CameraAdapter and AuthAdapter subclass it to do the platform work.
Adapters are registered by hand: on Android, BaseActivity.connect(listOf(permissionAdapter, …)) ties them to the activity's lifecycle, and a forgotten registration fails when the adapter is first used. The iOS BaseController is a stub.
Primitives#
- Time:
epochTime()over kotlinx-datetime's system clock. - Dispatchers:
Dispatch.Main,Dispatch.IOandDispatch.Default, withDispatchers.Asyncchosen per platform: IO on Android, iOS and the JVM, Default on JS. - Logging: a thin wrapper over Kermit.
- Atomics and maps: kotlinx-atomicfu, and a lock-free
ConcurrentHashMapwritten for Reaktor because JS and Kotlin/Native have no shared one. It is slower thanjava.util.concurrent's, and portable. - JSON: kotlinx.serialization with
encodeDefaults = true,ignoreUnknownKeys = trueandclassDiscriminator = "type", which every sealed hierarchy in the framework relies on. The globaljsonis a mutable variable: read it anywhere, but do not reconfigure it while other code runs.
Device tiers: a design#
A capability runtime would extend Feature from "which implementation runs here" to "at what quality, right now". It is designed and not built. It would install through one more slot:
var Feature.Capability by CreateSlot<CapabilityRuntime>()
interface CapabilityRuntime : AutoCloseable {
val environment: StateFlow<EnvironmentSnapshot>
suspend fun resolve(request: CapabilityRequest): CapabilityDecision
}
Collectors, written as adapters, would read raw platform signals. A normaliser would fold them into one EnvironmentSnapshot of tiers: PerformanceClass, MemoryClass, NetworkQuality, NetworkCost, ThermalClass, PowerMode and FormFactor. A strategy selector would then choose an implementation by tier and policy, and record why.
Product code would branch on tiers, never on a raw model string, vendor ID, user-agent string or hardware score. The platforms already push the same way: browsers reduce the user agent and round deviceMemory to a power of two, Android computes a Media Performance Class, and iOS exposes thermal state and low-power mode for the app to bucket itself. An unknown signal resolves to the most conservative tier, so the default code path is the one that works on the weakest device. Nothing enforces this yet; the web code still reads a raw user agent.
What core improves#
| Usual approach | What goes wrong | Core's approach |
|---|---|---|
An expect/actual pair for every platform service | Every service needs an actual on every target, and expect class is still Beta in Kotlin | One Feature slot per service: shared code reads an interface, and each platform's start-up code installs its own implementation |
| Shared code that holds an Android activity or an iOS view controller | The shared object keeps the screen alive after the platform has destroyed it, and memory leaks | An Adapter holds the controller through a weak reference, and a call returns null once the controller is gone |
| A hand-written "closed" flag on each resource | Closing twice, or from two threads at once, runs the cleanup twice | AtomicCapability.close() runs its cleanup once, guarded by an atomic compare-and-set |
| A different concurrent map on each platform | JavaScript and Kotlin/Native have no shared concurrent map, so common code cannot use one | A lock-free ConcurrentHashMap that runs on every target |
Limitations#
- A slot registry is a service locator: a slot that nothing filled fails where it is read, not at start-up.
- Adapters are registered by hand, and a forgotten registration fails when the adapter is first used. The iOS
BaseControlleris a stub. - The global
jsonconfiguration is a mutable variable that any code could change. - On JavaScript,
WeakRefkeeps a strong reference, so an adapter there does not let its controller go. - The portable
ConcurrentHashMapis slower thanjava.util.concurrent's on the JVM. - Device tiers are a design. Nothing builds them yet.
Open work#
- Fail at start-up when a required slot is missing, instead of at first use.
- Register adapters automatically per platform, and finish the iOS
BaseController. - Make the JSON configuration immutable, or scoped, instead of a global variable.
- Prefer an interface with an injected implementation over
expect class, which is still Beta. - Decide whether core's
Capabilityshould be renamed, for example toResource, before the capability runtime adds a third meaning of the word. - Build the capability runtime as its own module,
reaktor-capability, starting with the tier enums and the snapshot.
Related docs#
- Service layer: typed services, built on core.
- Actors: actors are nodes that close their resources and read slots at the edge.
- FFI: the native bridge.
- FlexBuffer: the binary format beside core's JSON defaults.