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
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.1.0"
".": "0.0.1"
Comment thread
lusu007 marked this conversation as resolved.
Resolved
}
24 changes: 21 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,38 @@ module-core Default registry implementation, graph validation, dependency sorti

## Usage

Use type-first access for normal services:

```kotlin
val serviceKey = serviceKey<MyService>("example.my-service")
val registry = DefaultServiceRegistry()

registry.register(serviceKey, MyService())
val service = registry.require(serviceKey)
registry.register<MyService>(MyService())

val service = registry.require<MyService>()
```

Use qualified keys only when multiple services share the same contract:

```kotlin
object ExampleServiceKeys {
val Primary = qualifiedServiceKey<MyService>("example.my-service.primary")
val Secondary = qualifiedServiceKey<MyService>("example.my-service.secondary")
}

registry.register(ExampleServiceKeys.Primary, primaryService)
registry.register(ExampleServiceKeys.Secondary, secondaryService)
```

Validate module descriptors before startup:

```kotlin
val graph = ModuleGraphValidator.validate(
listOf(providerA.descriptor, providerB.descriptor)
)
```

See [Service Registry](docs/service-registry.md) for the service key rules.

## License

Licensed under the Apache License, Version 2.0.
2 changes: 1 addition & 1 deletion build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
plugins { id("gg.grounds.base-conventions") version "0.7.0" }
plugins { id("gg.grounds.base-conventions") version "0.8.0" }
65 changes: 65 additions & 0 deletions docs/service-registry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Service Registry

`library-jvm-modules` uses typed service keys so modules can publish and consume services without string lookups at call sites.

## Default: Access Services By Type

Use type-first access when there is one implementation for a service contract:

```kotlin
val registry = DefaultServiceRegistry()

registry.register<MyService>(MyServiceImpl())

val service = registry.require<MyService>()
```

For non-reified call sites, pass the Kotlin class:

```kotlin
registry.register(MyService::class, MyServiceImpl())

val service = registry.require(MyService::class)
```

## Multiple Implementations: Use Qualified Keys

Use qualified keys only when the same contract has multiple implementations:

```kotlin
object NatsServiceKeys {
val Public = qualifiedServiceKey<NatsClient>("grounds.nats.public")
val Internal = qualifiedServiceKey<NatsClient>("grounds.nats.internal")
}
```

Register and read those keys explicitly:

```kotlin
registry.register(NatsServiceKeys.Public, publicNats)
registry.register(NatsServiceKeys.Internal, internalNats)

val publicNats = registry.require(NatsServiceKeys.Public)
```

Do not create qualified keys inline at call sites. Define them once in the module API that owns the service contract.

## Module Descriptors

Use the same keys in module descriptors:

```kotlin
class MatchmakingModuleProvider : ModuleProvider<MatchmakingModule> {
override val descriptor =
ModuleDescriptor(
id = "grounds.matchmaking",
version = "1.0.0",
requires = setOf(NatsServiceKeys.Internal),
provides = setOf(serviceKey<MatchmakingService>()),
)

override fun create(): MatchmakingModule = MatchmakingModule()
}
```

`dependsOn` is for module startup order. `requires` and `provides` are for service contracts.
11 changes: 11 additions & 0 deletions module-api/src/main/kotlin/gg/grounds/modules/ModuleDescriptor.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
package gg.grounds.modules

/**
* Static description of one module on the application classpath.
*
* Descriptors are used for graph validation and startup ordering. They do not create modules and
* they do not imply runtime classloader isolation.
*/
data class ModuleDescriptor(
/** Stable module identifier, for example `grounds.matchmaking`. */
val id: String,
/** Module version used for diagnostics and composition metadata. */
val version: String,
/** Module ids that must be started before this module. */
val dependsOn: Set<String> = emptySet(),
/** Services that must exist before this module can start. */
val requires: Set<ServiceKey<*>> = emptySet(),
/** Services this module promises to register. */
val provides: Set<ServiceKey<*>> = emptySet(),
) {
init {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package gg.grounds.modules

/**
* Factory discovered from the application classpath.
*
* Implementations are commonly loaded through Java [java.util.ServiceLoader]. The created module
* type is application-specific; this library only models discovery and dependency metadata.
*/
interface ModuleProvider<M : Any> {
/** Descriptor used for validation and startup ordering before [create] is called. */
val descriptor: ModuleDescriptor

/** Creates a new module instance. */
fun create(): M
}
68 changes: 62 additions & 6 deletions module-api/src/main/kotlin/gg/grounds/modules/ServiceKey.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,74 @@ package gg.grounds.modules

import kotlin.reflect.KClass

open class ServiceKey<T : Any>(val id: String, val type: KClass<T>) {
/**
* Typed service identifier used by [ServiceRegistry].
*
* Prefer unqualified type keys created with [serviceKey] for normal services. Use
* [qualifiedServiceKey] only when multiple services implement the same public contract and callers
* must choose one explicitly.
*/
class ServiceKey<T : Any>(val type: KClass<T>, val qualifier: String? = null) {
/**
* Stable identifier used in diagnostics and graph validation.
*
* For unqualified keys this is the service type's qualified class name. For qualified keys this
* is the explicit qualifier supplied by the API owner.
*/
val id: String =
qualifier
?: requireNotNull(type.qualifiedName) {
"service key type ${type.simpleName ?: type} must have a qualified name"
}

init {
require(id.isNotBlank()) { "service key id must not be blank" }
require(qualifier == null || qualifier.isNotBlank()) {
"service key qualifier must not be blank"
}
}

final override fun equals(other: Any?): Boolean {
return other is ServiceKey<*> && id == other.id && type == other.type
return other is ServiceKey<*> && type == other.type && qualifier == other.qualifier
}

final override fun hashCode(): Int = 31 * id.hashCode() + type.hashCode()
final override fun hashCode(): Int = 31 * type.hashCode() + qualifier.hashCode()

final override fun toString(): String = "$id:${type.qualifiedName}"
final override fun toString(): String {
val typeName = type.qualifiedName ?: type.toString()
return if (qualifier == null) {
typeName
} else {
"$qualifier:$typeName"
}
}
}

inline fun <reified T : Any> serviceKey(id: String): ServiceKey<T> = ServiceKey(id, T::class)
/**
* Creates the default key for a service type.
*
* This is the normal path for services where there is one registered implementation for [T].
*/
inline fun <reified T : Any> serviceKey(): ServiceKey<T> = serviceKey(T::class)

/**
* Creates the default key for [type].
*
* Use this overload from non-reified code.
*/
fun <T : Any> serviceKey(type: KClass<T>): ServiceKey<T> = ServiceKey(type)

/**
* Creates an explicit qualified key for a service type.
*
* Use qualified keys only when the same service contract has multiple registered implementations.
*/
inline fun <reified T : Any> qualifiedServiceKey(qualifier: String): ServiceKey<T> =
qualifiedServiceKey(T::class, qualifier)

/**
* Creates an explicit qualified key for [type].
*
* Use this overload from non-reified code.
*/
fun <T : Any> qualifiedServiceKey(type: KClass<T>, qualifier: String): ServiceKey<T> =
ServiceKey(type = type, qualifier = qualifier)
65 changes: 65 additions & 0 deletions module-api/src/main/kotlin/gg/grounds/modules/ServiceRegistry.kt
Original file line number Diff line number Diff line change
@@ -1,23 +1,88 @@
package gg.grounds.modules

import kotlin.reflect.KClass

/**
* Registry for typed module services.
*
* Implementations store services by [ServiceKey]. Consumers should normally use the type-first
* extension functions in this file, such as `registry.require<MyService>()`.
*/
interface ServiceRegistry {
/**
* Registers [service] under [key].
*
* Throws [DuplicateServiceException] if the key is already registered.
*/
fun <T : Any> register(key: ServiceKey<T>, service: T)

/** Returns the service registered under [key], or `null` when no service exists. */
fun <T : Any> get(key: ServiceKey<T>): T?

/**
* Returns the service registered under [key].
*
* Throws [MissingServiceException] when no service exists.
*/
fun <T : Any> require(key: ServiceKey<T>): T {
return get(key) ?: throw MissingServiceException(key)
}

/** Returns true when [key] has a registered service. */
fun contains(key: ServiceKey<*>): Boolean = getUntyped(key) != null

/** Returns a snapshot of currently registered service keys. */
fun keys(): Set<ServiceKey<*>>

/**
* Returns the raw service registered under [key].
*
* Prefer typed accessors for application code. This method exists for diagnostics and registry
* internals that need to inspect unknown service types.
*/
fun getUntyped(key: ServiceKey<*>): Any?
}

/** Registers [service] under the default key for [T]. */
inline fun <reified T : Any> ServiceRegistry.register(service: T) {
register(serviceKey<T>(), service)
}

/** Registers [service] under the default key for [type]. */
fun <T : Any> ServiceRegistry.register(type: KClass<T>, service: T) {
register(serviceKey(type), service)
}

/** Returns the service registered for [T], or `null`. */
inline fun <reified T : Any> ServiceRegistry.get(): T? = get(serviceKey<T>())

/** Returns the service registered for [type], or `null`. */
fun <T : Any> ServiceRegistry.get(type: KClass<T>): T? = get(serviceKey(type))

/**
* Returns the service registered for [T].
*
* Throws [MissingServiceException] when no service exists.
*/
inline fun <reified T : Any> ServiceRegistry.require(): T = require(serviceKey<T>())

/**
* Returns the service registered for [type].
*
* Throws [MissingServiceException] when no service exists.
*/
fun <T : Any> ServiceRegistry.require(type: KClass<T>): T = require(serviceKey(type))

/** Returns true when [T] has a registered service. */
inline fun <reified T : Any> ServiceRegistry.contains(): Boolean = contains(serviceKey<T>())

/** Returns true when [type] has a registered service. */
fun <T : Any> ServiceRegistry.contains(type: KClass<T>): Boolean = contains(serviceKey(type))

/** Thrown when a required service is not registered. */
class MissingServiceException(key: ServiceKey<*>) :
IllegalStateException("required service is not registered: $key")

/** Thrown when a service key is registered more than once. */
class DuplicateServiceException(key: ServiceKey<*>) :
IllegalStateException("service is already registered: $key")
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import gg.grounds.modules.ServiceKey
import gg.grounds.modules.ServiceRegistry
import java.util.concurrent.ConcurrentHashMap

/**
* Thread-safe [ServiceRegistry] backed by a concurrent map.
*
* Services are immutable bindings: a key can be registered once and duplicate registration fails.
*/
class DefaultServiceRegistry : ServiceRegistry {
private val services = ConcurrentHashMap<ServiceKey<*>, Any>()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@ package gg.grounds.modules.core
import gg.grounds.modules.ModuleDescriptor
import gg.grounds.modules.ServiceKey

/** Validated module graph in deterministic startup order. */
data class ModuleGraph(val descriptors: List<ModuleDescriptor>) {
/** Descriptors indexed by module id. */
val descriptorsById: Map<String, ModuleDescriptor> = descriptors.associateBy { it.id }
}

/** Validates module descriptors before an application starts modules. */
object ModuleGraphValidator {
/**
* Validates module ids, dependency edges, required services, and duplicate provided services.
*
* Returns a [ModuleGraph] whose descriptors are sorted so dependencies appear before
* dependants.
*/
fun validate(
descriptors: Collection<ModuleDescriptor>,
availableServices: Set<ServiceKey<*>> = emptySet(),
Expand Down Expand Up @@ -67,7 +76,13 @@ object ModuleGraphValidator {
}
}

/** Deterministically sorts module descriptors by dependency order. */
object ModuleDependencySorter {
/**
* Returns [descriptors] sorted so dependencies appear before dependants.
*
* Throws [IllegalArgumentException] when the dependency graph contains a cycle.
*/
fun sort(descriptors: Collection<ModuleDescriptor>): List<ModuleDescriptor> {
val byId = descriptors.associateBy { it.id }
val permanent = mutableSetOf<String>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ package gg.grounds.modules.core
import gg.grounds.modules.ModuleProvider
import java.util.ServiceLoader

/** Discovers module providers from Java [ServiceLoader] metadata on the application classpath. */
object ServiceLoaderModuleDiscovery {
/** Loads providers of [providerType] using [classLoader]. */
fun <P : ModuleProvider<*>> discover(
providerType: Class<P>,
classLoader: ClassLoader = Thread.currentThread().contextClassLoader,
): List<P> {
return ServiceLoader.load(providerType, classLoader).toList()
}

/** Loads providers of [P] using [classLoader]. */
inline fun <reified P : ModuleProvider<*>> discover(
classLoader: ClassLoader = Thread.currentThread().contextClassLoader
): List<P> = discover(P::class.java, classLoader)
Expand Down
Loading