commonMain.ch.softappeal.yass2.remote.Service.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of yass2-jvm Show documentation
Show all versions of yass2-jvm Show documentation
Yet Another Service Solution
package ch.softappeal.yass2.remote
import kotlin.reflect.*
class ServiceId(val service: KClass, val id: Int)
inline fun serviceId(id: Int) = ServiceId(S::class, id)
interface RemoteProxyFactory {
fun create(serviceId: ServiceId): S
}
operator fun RemoteProxyFactory.invoke(serviceId: ServiceId): S = create(serviceId)
class Service internal constructor(val serviceId: ServiceId<*>, val implementation: Any)
operator fun ServiceId.invoke(service: S) = Service(this, service)
typealias Tunnel = suspend (request: Request) -> Reply
typealias Invoker = suspend (request: Request, service: Service) -> Any?
class Services(vararg services: Service) {
private val id2service = HashMap(services.size)
init {
services.forEach { service ->
require(id2service.put(service.serviceId.id, service) == null) {
"duplicated service id ${service.serviceId.id}"
}
}
}
fun tunnel(invoker: Invoker): Tunnel = { request ->
try {
val result = invoker(
request,
id2service[request.serviceId] ?: error("no service id ${request.serviceId}")
)
ValueReply(if (result === Unit) null else result)
} catch (e: Exception) {
ExceptionReply(e)
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy