All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ch.softappeal.yass2.remote.Service.kt Maven / Gradle / Ivy

There is a newer version: 5.0.0
Show newest version
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)
        }
    }
}