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

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

package ch.softappeal.yass2.remote

import kotlin.reflect.*

public class ServiceId @PublishedApi internal constructor(public val service: KClass, public val id: Int)

public inline fun  serviceId(id: Int): ServiceId = ServiceId(S::class, id)

public interface RemoteProxyFactory {
    public fun  create(serviceId: ServiceId): S
}

public operator fun  RemoteProxyFactory.invoke(serviceId: ServiceId): S = create(serviceId)

public class Service internal constructor(public val serviceId: ServiceId<*>, public val implementation: Any)

public operator fun  ServiceId.invoke(service: S): Service = Service(this, service)

public typealias Tunnel = suspend (request: Request) -> Reply

public typealias Invoker = suspend (request: Request, service: Service) -> Any?

public fun Invoker.tunnel(services: Collection): Tunnel {
    val id2service = services.associateBy { it.serviceId.id }
    require(id2service.size == services.size) { "duplicated service id's" }
    return { request ->
        try {
            val result = this(request, id2service[request.serviceId] ?: error("no service id ${request.serviceId}"))
            ValueReply(if (result === Unit) null else result)
        } catch (e: Exception) {
            ExceptionReply(e)
        }
    }
}

public typealias RemoteProxyFactoryCreator = (tunnel: Tunnel) -> RemoteProxyFactory

public fun missingFunction(request: Request) {
    error("no function id ${request.functionId} for service id ${request.serviceId}")
}