Skip to content

Commit

Permalink
WIP OTHER
Browse files Browse the repository at this point in the history
  • Loading branch information
whyoleg committed Dec 5, 2023
1 parent 76842a1 commit 3cf5622
Show file tree
Hide file tree
Showing 24 changed files with 1,188 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import io.ktor.utils.io.pool.*
import io.rsocket.kotlin.*
import io.rsocket.kotlin.core.*
import io.rsocket.kotlin.frame.*
import io.rsocket.kotlin.internal.connection.*
import io.rsocket.kotlin.internal.operation.*
import io.rsocket.kotlin.internal.sequential.*
import io.rsocket.kotlin.transport.*
import kotlinx.coroutines.*

Expand All @@ -35,9 +38,7 @@ internal suspend inline fun connect(
@Suppress("DEPRECATION") bufferPool: ObjectPool<ChunkBuffer>,
): RSocket {
val prioritizer = Prioritizer()
val frameSender = FrameSender(prioritizer, bufferPool, maxFragmentSize)
val streamsStorage = StreamsStorage(isServer, bufferPool)
val keepAliveHandler = KeepAliveHandler(connectionConfig.keepAlive, frameSender)
val streamsStorage = StreamsStorage(isServer)

val requestJob = SupervisorJob(connection.coroutineContext[Job])
val requestContext = connection.coroutineContext + requestJob
Expand All @@ -48,12 +49,22 @@ internal suspend inline fun connect(
connectionConfig.setupPayload.close()
}

val requesterExecutor = SequentialRequesterOperationExecutor(
// requestsScope = CoroutineScope(requestContext + CoroutineName("rSocket-requester")),
streamsStorage = streamsStorage,
prioritizer = prioritizer,
maxFragmentSize = maxFragmentSize,
bufferPool = bufferPool
)
val connectionOutbound = SequentialConnectionOutbound(prioritizer)

val keepAliveHandler = KeepAliveHandler(connectionConfig.keepAlive, connectionOutbound)

val requester = interceptors.wrapRequester(
RSocketRequester(
Requester(
requestContext + CoroutineName("rSocket-requester"),
frameSender,
streamsStorage,
bufferPool
requesterExecutor,
connectionOutbound
)
)
val requestHandler = interceptors.wrapResponder(
Expand All @@ -79,6 +90,13 @@ internal suspend inline fun connect(
requestHandler.cancel("Connection closed", it)
}

val connectionInbound = DefaultConnectionInbound(
CoroutineScope(requestContext + CoroutineName("rSocket-responder")),
requestHandler,
keepAliveHandler,
)
val connectionFrameHandler = ConnectionFrameHandler(connectionInbound)

// start keepalive ticks
(connection + CoroutineName("rSocket-connection-keep-alive")).launch {
while (isActive) keepAliveHandler.tick()
Expand All @@ -93,12 +111,15 @@ internal suspend inline fun connect(
(connection + CoroutineName("rSocket-connection-receive")).launch {
while (isActive) connection.receiveFrame(bufferPool) { frame ->
when (frame.streamId) {
0 -> when (frame) {
is MetadataPushFrame -> responder.handleMetadataPush(frame.metadata)
is ErrorFrame -> connection.cancel("Error frame received on 0 stream", frame.throwable)
is KeepAliveFrame -> keepAliveHandler.mark(frame)
is LeaseFrame -> frame.close().also { error("lease isn't implemented") }
else -> frame.close()
0 -> {
connectionFrameHandler.handleFrame(frame)
// when (frame) {
// is MetadataPushFrame -> responder.handleMetadataPush(frame.metadata)
// is ErrorFrame -> connection.cancel("Error frame received on 0 stream", frame.throwable)
// is KeepAliveFrame -> keepAliveHandler.mark(frame)
// is LeaseFrame -> frame.close().also { error("lease isn't implemented") }
// else -> frame.close()
// }
}

else -> streamsStorage.handleFrame(frame, responder)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015-2022 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,31 +18,31 @@ package io.rsocket.kotlin.internal

import io.ktor.utils.io.core.*
import io.rsocket.kotlin.*
import io.rsocket.kotlin.frame.*
import io.rsocket.kotlin.internal.connection.*
import io.rsocket.kotlin.keepalive.*
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlin.time.*

internal class KeepAliveHandler(
private val keepAlive: KeepAlive,
private val sender: FrameSender,
private val outbound: ConnectionOutbound,
) {
private val initial = TimeSource.Monotonic.markNow()
private fun currentMillis() = initial.elapsedNow().inWholeMilliseconds

private val lastMark = atomic(currentMillis()) // mark initial timestamp for keepalive

suspend fun mark(frame: KeepAliveFrame) {
suspend fun mark(respond: Boolean, data: ByteReadPacket) {
lastMark.value = currentMillis()
if (frame.respond) sender.sendKeepAlive(false, 0, frame.data)
if (respond) outbound.sendKeepAlive(false, data, 0)
}

suspend fun tick() {
delay(keepAlive.intervalMillis.toLong())
if (currentMillis() - lastMark.value >= keepAlive.maxLifetimeMillis)
throw RSocketError.ConnectionError("No keep-alive for ${keepAlive.maxLifetimeMillis} ms")

sender.sendKeepAlive(true, 0, ByteReadPacket.Empty)
outbound.sendKeepAlive(true, ByteReadPacket.Empty, 0)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import kotlinx.coroutines.selects.*

private val selectFrame: suspend (Frame) -> Frame = { it }

// TODO: refactor to not use frames but packets
internal class Prioritizer {
private val priorityChannel = channelForCloseable<Frame>(Channel.UNLIMITED)
private val commonChannel = channelForCloseable<Frame>(Channel.UNLIMITED)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2015-2022 the original author or authors.
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,6 +18,7 @@ package io.rsocket.kotlin.internal

import kotlinx.atomicfu.*

// TODO: move to internal.connection
internal class StreamId(streamId: Int) {
private val streamId = atomic(streamId)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,73 +16,49 @@

package io.rsocket.kotlin.internal

import io.ktor.utils.io.core.internal.*
import io.ktor.utils.io.pool.*
import io.ktor.utils.io.core.*
import io.rsocket.kotlin.frame.*
import io.rsocket.kotlin.internal.handler.*
import io.rsocket.kotlin.internal.connection.*
import io.rsocket.kotlin.internal.operation.*
import kotlinx.atomicfu.locks.*

// TODO: move to internal.connection
internal class StreamsStorage(
private val isServer: Boolean,
@Suppress("DEPRECATION") private val pool: ObjectPool<ChunkBuffer>,
) : SynchronizedObject() {
private val streamId: StreamId = StreamId(isServer)
private val handlers: IntMap<FrameHandler> = IntMap()
private val handlers: IntMap<StreamFrameHandler> = IntMap()

fun nextId(): Int = synchronized(this) { streamId.next(handlers) }
fun save(id: Int, handler: FrameHandler) = synchronized(this) { handlers[id] = handler }
fun remove(id: Int): FrameHandler? = synchronized(this) { handlers.remove(id) }?.also(FrameHandler::close)
fun save(id: Int, handler: StreamFrameHandler) = synchronized(this) { handlers[id] = handler }
fun remove(id: Int): StreamFrameHandler? = synchronized(this) { handlers.remove(id) }?.also(Closeable::close)
fun contains(id: Int): Boolean = synchronized(this) { id in handlers }
private fun get(id: Int): FrameHandler? = synchronized(this) { handlers[id] }
private fun get(id: Int): StreamFrameHandler? = synchronized(this) { handlers[id] }

fun cleanup(error: Throwable?) {
val values = synchronized(this) {
val values = handlers.values()
handlers.clear()
values
}
values.forEach {
it.cleanup(error)
it.close()
}
values.forEach(Closeable::close)
}

fun handleFrame(frame: Frame, responder: RSocketResponder) {
fun handleFrame(frame: Frame, handler: ResponderOperationHandler) {
val id = frame.streamId
when (frame) {
is RequestNFrame -> get(id)?.handleRequestN(frame.requestN)
is CancelFrame -> get(id)?.handleCancel()
is ErrorFrame -> get(id)?.handleError(frame.throwable)
is RequestFrame -> when {
frame.type == FrameType.Payload -> get(id)?.handleRequest(frame)
is RequestFrame -> when {
frame.type == FrameType.Payload -> get(id)?.handleFrame(frame)
?: frame.close() // release on unknown stream id
isServer.xor(id % 2 != 0) -> frame.close() // request frame on wrong stream id
else -> {
val initialRequest = frame.initialRequest
val handler = when (frame.type) {
FrameType.RequestFnF -> ResponderFireAndForgetFrameHandler(id, this, responder, pool)
FrameType.RequestResponse -> ResponderRequestResponseFrameHandler(id, this, responder, pool)
FrameType.RequestStream -> ResponderRequestStreamFrameHandler(
id,
this,
responder,
initialRequest,
pool
)
FrameType.RequestChannel -> ResponderRequestChannelFrameHandler(
id,
this,
responder,
initialRequest,
pool
)
else -> error("Wrong request frame type") // should never happen
}
val handler = StreamFrameHandler(handler.handle(frame, TODO()))
save(id, handler)
handler.handleRequest(frame)
handler.handleFrame(frame)
}
}
else -> frame.close()

else -> get(id)?.handleFrame(frame) ?: frame.close() // release on unknown stream id
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.rsocket.kotlin.internal.connection

// TODO: change package to internal.transport?

// TODO?
//internal abstract class ConnectionEstablishmentHandler {
// abstract suspend fun receiveFrame(): ByteReadPacket
// abstract suspend fun sendFrame(frame: ByteReadPacket)
//}
//
///*
// Client setup:
// 1. configure
// 2. send setup frame (or resume + await resume ok frame)
// 3. done
//
// Server setup:
// 1. await setup frame (or resume)
// 2. configure
// 3. done | send error (or send resume ok frame)
// */
//
///*
// done means:
// 1. start receiving frames/streams
// 2. create requester
// */
//
//@RSocketTransportApi
//internal suspend fun RSocketClientTransport.connect(
// isClient: Boolean,
// maxFragmentSize: Int,
// interceptors: Interceptors,
// connectionConfig: ConnectionConfig,
// acceptor: ConnectionAcceptor,
//) {
// suspend fun setup(handler: ConnectionEstablishmentHandler) {
// val setupFrame = SetupFrame(
// version = Version.Current,
// honorLease = false,
// keepAlive = connectionConfig.keepAlive,
// resumeToken = null,
// payloadMimeType = connectionConfig.payloadMimeType,
// payload = connectionConfig.setupPayload.copy() //copy needed, as it can be used in acceptor
// ).toPacket(ChunkBuffer.Pool)
// handler.sendFrame(setupFrame)
// // done
// }
//
// when (val connection = connect()) {
// is RSocketTransportConnection.Multiplexed -> {
// val connectionStream = connection.createStream()
// connectionStream.prioritize()
//
// while (true) {
// val stream = connection.awaitStream()
// launch {
// val firstFrame = stream.receiveFrame()
// }
// }
// }
//
// is RSocketTransportConnection.Sequential -> {
// setup(SequentialConnectionEstablishmentHandler(connection))
//
// }
// }
//}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2015-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.rsocket.kotlin.internal.connection

import io.rsocket.kotlin.frame.*

internal class ConnectionFrameHandler(
private val inbound: ConnectionInbound,
) {
suspend fun handleFrame(frame: Frame): Boolean = when (frame) {
is MetadataPushFrame -> inbound.receiveMetadataPush(frame.metadata)
is KeepAliveFrame -> inbound.receiveKeepAlive(frame.respond, frame.data, frame.lastPosition)
is ErrorFrame -> inbound.receiveError(frame.throwable)
is LeaseFrame -> {
frame.close()
TODO("lease is not supported")
}

else -> {
frame.close()
false // wrong frame
}
}
}

Loading

0 comments on commit 3cf5622

Please sign in to comment.