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
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,19 @@ whether the request provably never left the device (`requestNeverSent`), which m
| `untrusted` | -1201 to -1204, certificate rejected | `net::` certificate errors -200 to -299, or a pin mismatch (-150) |
| `other` | Everything else, timeouts and dropped connections included | Any failure after `onStreamReady` |

No exception in the package should crash the app or leave a call hanging. Failures end the one call they concern:

- **A request the platform stack rejects** fails that call as `notSent`. For example, Cronet throws on a header value
with a line break.
- **A method call the plugin can't parse** gets an error reply instead of a force-unwrap (iOS) or an uncaught
exception (Android). Uncaught exceptions on the Android bridge's thread would otherwise kill the process.
- **A malformed event** fails its own call with `internal`.
- **An exception from `onResponse`** goes to `FlutterError.onError`, like other errors that have no caller. The call
carries on.

`NativeHttpClient.create` throws a `PlatformException` if the platform can't create a client, for example when Cronet's
native library fails to load.

## Server and infrastructure requirements

The clients only reach HTTP/3, and only keep bidi working, if the server side meets these requirements. Each was
Expand Down Expand Up @@ -227,7 +240,8 @@ Neither platform finishes a stream on its own while the client still has its req

- **Android (`android/src/androidTest`, instrumented):** writes sent before Cronet is ready go out once it is; a
write after the server finished the call is dropped instead of crashing; shutting an engine down lets its calls
finish and refuses new ones.
finish and refuses new ones; a header Cronet rejects fails its call as never sent; an empty write is skipped.
- Both platforms' suites also check that malformed method calls get an error reply and leave the bridge working.
- **`example/integration_test/public_server_test.dart`:** HTTP/3 on Android against a server with a public
certificate. It also checks that `quicIdleTimeout` ends a quiet connection, against a control without it. It is
opt-in because it needs the internet:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,24 +68,85 @@ class CronetBridgeTest {
assertEquals(false, refused["streamReady"])
}

private fun invoke(method: String, arguments: Map<String, Any?>): Any? {
// Cronet throws from start() on a header it rejects. On the bridge's thread that would have killed the app.
@Test
fun aHeaderCronetRejectsFailsTheCallAsNeverSent() {
val engine = createEngine()
open(engine, 1, SAY, "application/proto", extraHeaders = listOf(listOf("authorization", "Bearer x\r\ny")))
val outcome = awaitOutcome(1)
assertEquals("failed", outcome["type"])
assertEquals(false, outcome["streamReady"])
assertSayWorks(engine, 2)
}

// Cronet throws on an empty write before the end of the stream.
@Test
fun anEmptyWriteIsSkipped() {
val engine = createEngine()
open(engine, 1, SAY, "application/proto")
invoke("write", mapOf("callId" to 1, "data" to ByteArray(0)))
invoke("write", mapOf("callId" to 1, "data" to sentence("hi")))
invoke("end", mapOf("callId" to 1))
assertEquals("done", awaitOutcome(1)["type"])
assertTrue(received(1).contains("say: hi"))
}

@Test
fun malformedArgumentsAreRefusedInsteadOfCrashing() {
val engine = createEngine()
val malformed: List<Pair<String, Map<String, Any?>>> = listOf(
"open" to emptyMap<String, Any?>(),
"open" to mapOf("engineId" to "1", "callId" to 1),
"write" to mapOf("callId" to 1, "data" to "not bytes"),
"end" to mapOf("callId" to null),
"cancel" to emptyMap<String, Any?>(),
"shutdownEngine" to mapOf("engineId" to 1.5),
)
for ((method, arguments) in malformed) {
val reply = reply(method, arguments)
assertTrue("$method $arguments: $reply", reply is CronetBridge.Reply.Error)
}
val badHints = reply("createEngine", mapOf("quicHints" to listOf(listOf("localhost"))))
assertTrue("createEngine with a bad hint: $badHints", badHints is CronetBridge.Reply.Error)
assertSayWorks(engine, 1)
}

private fun assertSayWorks(engine: Int, callId: Int) {
open(engine, callId, SAY, "application/proto")
invoke("write", mapOf("callId" to callId, "data" to sentence("again")))
invoke("end", mapOf("callId" to callId))
assertEquals("done", awaitOutcome(callId)["type"])
assertTrue(received(callId).contains("say: again"))
}

private fun reply(method: String, arguments: Map<String, Any?>): CronetBridge.Reply {
val result = CompletableFuture<CronetBridge.Reply>()
bridge.handle(method, arguments) { result.complete(it) }
return when (val reply = result.get(3, TimeUnit.SECONDS)) {
return result.get(3, TimeUnit.SECONDS)
}

private fun invoke(method: String, arguments: Map<String, Any?>): Any? =
when (val reply = reply(method, arguments)) {
is CronetBridge.Reply.Success -> reply.value
else -> throw AssertionError("$method: $reply")
}
}

private fun createEngine(): Int = invoke("createEngine", mapOf("quicHints" to emptyList<Any>())) as Int

private fun open(engine: Int, callId: Int, path: String, contentType: String) {
private fun open(
engine: Int,
callId: Int,
path: String,
contentType: String,
extraHeaders: List<List<String>> = emptyList(),
) {
invoke("open", mapOf(
"engineId" to engine,
"callId" to callId,
"url" to serverUrl + path,
"method" to "POST",
"headers" to listOf(listOf("content-type", contentType), listOf("connect-protocol-version", "1")),
"headers" to listOf(listOf("content-type", contentType), listOf("connect-protocol-version", "1")) +
extraHeaders,
))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.agtonomy.connect_native_http
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import org.chromium.net.BidirectionalStream
import org.chromium.net.CronetEngine
import org.chromium.net.CronetException
Expand Down Expand Up @@ -48,17 +49,48 @@ class CronetBridge(
var responseComplete = false
var endQueued = false
val pending = ArrayDeque<Pair<ByteArray, Boolean>>()

// Set once Dart has been told how the call ended. After the bridge fails a call itself, Cronet's own final
// callback still follows, to release the stream.
var reported = false
}

fun cancelAll() {
executor.execute {
execute(null) {
calls.values.forEach { it.stream.cancel() }
}
}

// Handles one method call. [reply] is called on the main thread.
// Runs [task] on the bridge's thread. An exception escaping it would end that thread, and with it the app: Android's
// default handler for uncaught exceptions kills the process. So it is logged, and fails the call it concerns.
private fun execute(callId: Int?, task: () -> Unit) {
executor.execute {
try {
task()
} catch (e: Exception) {
Log.e(TAG, "call $callId failed in the bridge", e)
if (callId != null) {
abort(callId, e)
}
}
}
}

// Handles one method call. [reply] is called on the main thread, and arguments Dart got wrong are refused with an
// error reply rather than thrown on it.
fun handle(method: String, args: Map<String, Any?>, reply: (Reply) -> Unit) {
val result = { r: Reply -> main.post { reply(r) } }
val result: (Reply) -> Unit = { r -> main.post { reply(r) } }
try {
dispatch(method, args, result)
} catch (e: Exception) {
// Not the arguments themselves: an open's include the request headers, credentials among them.
Log.e(TAG, "$method: bad arguments", e)
result(Reply.Error("badArguments", "$method: ${e.message}"))
}
}

@Suppress("UNCHECKED_CAST")
private fun dispatch(method: String, args: Map<String, Any?>, result: (Reply) -> Unit) {
when (method) {
"createEngine" -> {
val quicHints = (args["quicHints"] as List<List<Any>>?).orEmpty()
Expand All @@ -78,14 +110,16 @@ class CronetBridge(
val id = nextEngineId++
engines[id] = Engine(builder.build())
result(Reply.Success(id))
} catch (e: Exception) {
result(Reply.Error("createEngine", e.message))
} catch (e: Throwable) {
// Throwable, not Exception: failing to load Cronet's native library is an UnsatisfiedLinkError.
Log.e(TAG, "createEngine failed", e)
result(Reply.Error("createEngine", e.toString()))
}
}
}
"shutdownEngine" -> {
val engineId = args["engineId"] as Int
executor.execute {
execute(null) {
engines[engineId]?.let {
it.shuttingDown = true
shutdownIfIdle(engineId)
Expand All @@ -98,45 +132,62 @@ class CronetBridge(
val callId = args["callId"] as Int
val url = args["url"] as String
val httpMethod = args["method"] as String
val headers = args["headers"] as List<List<String>>
executor.execute { open(engineId, callId, url, httpMethod, headers) }
val headers = (args["headers"] as List<List<String>>).map { it[0] to it[1] }
execute(callId) { open(engineId, callId, url, httpMethod, headers) }
result(Reply.Success(null))
}
"write" -> {
val callId = args["callId"] as Int
val data = args["data"] as ByteArray
executor.execute { enqueue(callId, data, false) }
execute(callId) { enqueue(callId, data, false) }
result(Reply.Success(null))
}
"end" -> {
val callId = args["callId"] as Int
executor.execute { enqueue(callId, ByteArray(0), true) }
execute(callId) { enqueue(callId, ByteArray(0), true) }
result(Reply.Success(null))
}
"cancel" -> {
val callId = args["callId"] as Int
executor.execute { calls[callId]?.stream?.cancel() }
execute(callId) { calls[callId]?.stream?.cancel() }
result(Reply.Success(null))
}
else -> result(Reply.NotImplemented)
}
}

private fun open(engineId: Int, callId: Int, url: String, method: String, headers: List<List<String>>) {
private fun open(engineId: Int, callId: Int, url: String, method: String, headers: List<Pair<String, String>>) {
val engine = engines[engineId]
if (engine == null || engine.shuttingDown) {
emit(failure(callId, false, "engine $engineId is shut down", null))
return
}
val c = Call(callId, engineId)
val builder = engine.cronet.newBidirectionalStreamBuilder(url, Callback(c), executor).setHttpMethod(method)
for (h in headers) {
builder.addHeader(h[0], h[1])
for ((name, value) in headers) {
builder.addHeader(name, value)
}
c.stream = builder.build()
// Throws on a method or header Cronet rejects, such as a value with a line break. The call is registered only
// once it has started, so abort() then reports it as never sent, with no stream to release.
c.stream.start()
calls[callId] = c
engine.callIds.add(callId)
c.stream.start()
}

// Fails a call the bridge itself could not carry on with, after an exception on its thread.
private fun abort(callId: Int, e: Exception) {
val message = "connect_native_http bridge: $e"
val c = calls[callId]
if (c == null) {
// Not started, so nothing was sent and there is no stream to release. A call that has already finished
// is gone too; Dart ignores events for calls it no longer has.
emit(failure(callId, false, message, null))
return
}
report(c, failure(callId, c.ready, message, null))
// Cronet's onCanceled then releases the call and the stream.
c.stream.cancel()
}

private fun enqueue(callId: Int, data: ByteArray, endOfStream: Boolean) {
Expand All @@ -145,8 +196,9 @@ class CronetBridge(
}

private fun enqueue(c: Call, data: ByteArray, endOfStream: Boolean) {
// Cronet rejects writes after the end of the request, which the bridge may already have sent itself.
if (c.endQueued) {
// Cronet rejects writes after the end of the request, which the bridge may already have sent itself, and an
// empty write before it, which has nothing to send anyway.
if (c.endQueued || c.reported || (data.isEmpty() && !endOfStream)) {
return
}
c.endQueued = endOfStream
Expand All @@ -170,18 +222,31 @@ class CronetBridge(
c.stream.flush()
}

// Cronet's final callback for a call: releases it and, unless the bridge has already failed it, reports [event].
private fun finish(c: Call, event: Map<String, Any?>) {
calls.remove(c.callId)
engines[c.engineId]?.callIds?.remove(c.callId)
emit(event)
report(c, event)
shutdownIfIdle(c.engineId)
}

private fun report(c: Call, event: Map<String, Any?>) {
if (!c.reported) {
c.reported = true
emit(event)
}
}

private fun shutdownIfIdle(engineId: Int) {
val engine = engines[engineId] ?: return
if (engine.shuttingDown && engine.callIds.isEmpty()) {
engines.remove(engineId)
engine.cronet.shutdown()
try {
engine.cronet.shutdown()
} catch (e: Exception) {
// Cronet refuses while it still counts a request as running. The engine is unreachable either way.
Log.w(TAG, "engine $engineId did not shut down", e)
}
}
}

Expand All @@ -195,6 +260,8 @@ class CronetBridge(

private fun headerPairs(headers: List<Map.Entry<String, String>>) = headers.map { listOf(it.key, it.value) }

// Cronet catches exceptions from these methods itself: one from onStreamReady, onResponseHeadersReceived or
// onReadCompleted fails the stream (onFailed, with a CallbackException), and one from a final callback is logged.
private inner class Callback(private val c: Call) : BidirectionalStream.Callback() {
override fun onStreamReady(stream: BidirectionalStream) {
c.ready = true
Expand Down Expand Up @@ -272,6 +339,7 @@ class CronetBridge(
}

private companion object {
const val TAG = "connect_native_http"
const val READ_BUFFER_BYTES = 32 * 1024
}
}
Loading
Loading