Repository navigation
[App] Add cross-platform streaming native HTTP transport (firebase_http_transport) - #1996
AustinBenoit wants to merge 16 commits into
Conversation
…tp_transport) Adds a shared platform-native streaming HTTP transport under app/http/ backed by: - Desktop: libcurl multi-handle (sharing firebase_rest_lib curl/TLS policy) - Apple (iOS/tvOS): ARC NSURLSession with NSStream bound-stream uploads - Android: JNI HttpURLConnection on a bounded worker pool + async cancel dispatcher Includes a flat C/SWIG handle bridge (app/http/http_bridge.h) for Unity consumption and desktop unit + loopback HTTP/SSE gtest coverage.
There was a problem hiding this comment.
Code Review
This pull request introduces a new cross-platform native streaming HTTP transport library (firebase_http_transport) supporting Android (JNI HttpURLConnection), Apple (NSURLSession), and Desktop (libcurl) backends, along with a flat C++/SWIG bridge, common utility helpers, and unit tests. The review feedback highlights a critical busy-wait loop bug in the Android upload path when an operation fails, a resource optimization to terminate response reading early on failure, and a maintainability suggestion to deduplicate the ToLowerAscii helper function across the Android and Apple implementations.
| while (!op->IsCanceled()) { | ||
| bool eof = false; | ||
| size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof); |
There was a problem hiding this comment.
Critical Bug: Potential Infinite Busy-Wait Loop on Upload Failure
In the JNI background upload loop, if the operation fails (e.g., op->failed is set to true by a stream write error or other failure), the op->req_cv.wait predicate:
!op->req_chunks.empty() || op->req_eof || op->failed || op->IsCanceled()will evaluate to true immediately. This causes wait to return without blocking.
Since the loop condition is while (!op->IsCanceled()), and op->IsCanceled() is still false, the loop will continue to the next iteration. It will call PopRequestBytes (which returns 0 bytes), and then immediately hit the else block and call wait again, which again returns immediately. This results in an infinite busy-wait loop that consumes 100% CPU on the worker thread, draining the device's battery and causing severe performance degradation.
To fix this, we should check op->failed under lock at the beginning of the loop and break out of the loop if it is true.
while (!op->IsCanceled()) {
{
std::lock_guard<std::mutex> lock(op->mutex);
if (op->failed) {
break;
}
}
bool eof = false;
size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof);| while (!op->IsCanceled()) { | ||
| jint n = | ||
| env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), 0, | ||
| static_cast<jsize>(kReadSlice)); |
There was a problem hiding this comment.
Improvement: Terminate Response Reading Early on Failure
In the response reading loop, if the operation has already failed (e.g., due to an upload error or stream failure), the thread will continue to block and read the remaining response bytes from the server until EOF, discarding them.
To conserve network bandwidth and CPU resources, we should check op->failed under lock at the beginning of the loop and break early if the operation has already failed.
while (!op->IsCanceled()) {
{
std::lock_guard<std::mutex> lock(op->mutex);
if (op->failed) {
break;
}
}
jint n =
env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), 0,
static_cast<jsize>(kReadSlice));| std::string ToLowerAscii(std::string_view s) { | ||
| std::string out(s.size(), '\0'); | ||
| for (size_t i = 0; i < s.size(); ++i) { | ||
| out[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(s[i]))); | ||
| } | ||
| return out; | ||
| } |
There was a problem hiding this comment.
Maintainability: Code Duplication of ToLowerAscii
The helper function ToLowerAscii is defined identically in both http_transport_android.cc and http_transport_apple.mm. To adhere to the DRY (Don't Repeat Yourself) principle and improve maintainability, we should declare ToLowerAscii in http_transport.h and implement it once in http_transport_common.cc alongside other shared string utilities like AsciiEqualsIgnoreCase.
…d cancel-all (S1-S5, C3, U2)
… classify errors (C1, C2, S4)
… locking, and errors (P1-P5, S3, S4)
… util reuse, and split (A1-A5, S4)
…ng events, and new cases (T1-T4)
… signal a closed request body - Backends no longer follow redirects; a 3xx is delivered as an ordinary response. Remove the URL parser, origin and credential helpers, and the manual redirect re-issue in the curl backend. - HttpTryWriteRequestBodyInternal returns -2 when the transport stopped consuming the body (early response or completed response) instead of -1, so a valid early 4xx is not turned into a failure by the caller. - Error classes: Certificate (peer or host name verification) is separate from Connect (handshake and connection failures); add InvalidRequest for failures detected before any network I/O. Validate the request method. - Pass the proxy URL to libcurl unchanged; refuse userinfo in request URLs. - Tests: early 413 x50, 3xx delivery, invalid requests, proxy pass-through, handshake error classes, and a backpressure test that fails when the receive pause is removed.
…x body-stream restart - Deliver 3xx responses to the caller and remove native redirect handling. - Only certificate NSURLError codes map to Certificate; a failed secure connection maps to Connect. Validation failures use InvalidRequest. - Parse the proxy URL with NSURLComponents. - needNewBodyStream installs a fresh stream only when no body bytes were handed to NSURLSession yet; otherwise the request fails as not replayable. - Report an empty reason phrase; correct the session pool comment. Not yet compiled: no Apple toolchain on the authoring machine.
…de and libcurl backend) - Bridge: WebSocket*Internal functions in http_bridge.h, sharing the handle id space and the event queue with HTTP operations. - Shared code owns bounded send and receive queues and the close state machine; backends move whole messages. - libcurl backend: one worker thread and multi handle for all sockets, frame reassembly, pong replies, keepalive pings, receive backpressure. - Connection options common to HTTP and WebSockets are applied in one place (ApplyCurlConnectionOptions). - A TLS policy setup failure is class Other, not Certificate. Test that a URL with userinfo is refused.
One session per socket with a serial delegate queue. The peer's Close is reported after pending messages are read; a close started locally always ends as a clean close. Not yet compiled: no Apple toolchain on the authoring machine.
…sport Replace the JNI HttpURLConnection backend with the libcurl backend that desktop uses. curl 8.23.0 and a BoringSSL pin used only for this purpose (0.20260929.0, with X25519MLKEM768) are built per ABI and linked statically with hidden visibility. The system CA store is read from /apex/com.android.conscrypt/cacerts or /system/etc/security/cacerts. The Android settings are applied in ApplyCurlConnectionOptions, so HTTP and WebSocket connections both get them. The transport no longer uses JNI.
…TORE libcurl parses a CURLOPT_CAINFO_BLOB again for every new TLS connection. The roots are now parsed once into an X509_STORE that each connection to the server takes with CURLOPT_SSL_CTX_FUNCTION (SSL_CTX_set1_verify_cert_store). The blob stays for HTTPS proxies. A load that finds no certificates is still retried by the next request.
…CURL) Off by default: an Android build of the C++ SDK then neither adds app/http nor downloads and builds libcurl and BoringSSL.
…idden 1005 close code, clear CA defaults on Android
…reConnectionFailed (-1200)
Summary
Adds a cross-platform, full-duplex streaming native HTTP transport (
firebase_http_transport) underapp/http/infirebase-cpp-sdk, together with a thin SWIG-friendly flat C/handle bridge (app/http/http_bridge.h) designed for consumption by both C++ callers andfirebase-unity-sdk.Motivation
Pure-C# Firebase Unity SDK products (Storage, Functions, Firebase AI Logic) need wire-speed transfers and immediate Server-Sent Events (SSE) streaming without depending on
UnityEngine.Networking(main-thread coroutine coupling, brokenUploadHandlerStreamon Unity6000.6IL2CPP) or Mono'sUnityTlsStream(~10–15 MiB/s download ceiling on pre-CoreCLR Unity runtimes). Putting the native HTTP transport infirebase-cpp-sdkkeeps all native C++ / Objective-C++ / JNI code in a single repository rather than duplicating platform transport code insidefirebase-unity-sdk.Legacy desktop-only
app/rest/is intentionally left untouched; Desktophttp_transport_curl.ccreusesfirebase_rest_lib's existingapp/rest/curl/curl_handles.h(ref-countedcurl_global_init) andapp/rest/curl/tls_policy.h(TLS CA bundle resolution).Architecture & Platform Backends
app/http/http_transport.h+app/http/http_transport_common.cc:std::shared_ptr<HttpOperation>registry with atomic single-start and cancellation guards, bounded upload (256 KiBhigh-water /128 KiBlow-water) and download (2 MiB/1 MiB) streaming pipes, and a single global completion event queue (HttpWaitNextEventInternal) that eliminates native-to-managed reverse callbacks.ResolveRedirectUrl), origin normalization (ParseUrlOrigin,IsSameOrigin), proxy URL parser (ParseProxyHostPort), and sensitive credential stripping (Authorization,Proxy-Authorization,X-Firebase-AppCheck,x-goog-api-key) on cross-origin redirects, plushttps→httpdowngrade and non-HTTP(S) scheme blocking across all three backends.app/http/http_bridge.h:12firebase::Http*Internalfunctions using only<stdint.h>and<string>) sofirebase-unity-sdkcan%include "app/http/http_bridge.h"with zeroSWIGTYPE_p_*wrapper leaks.app/http/http_transport_curl.cc):libcurlCURLMmulti-handle loop (CURLMOPT_MAX_TOTAL_CONNECTIONS = 64), per-direction pause bitmask (CURLPAUSE_SEND/CURLPAUSE_RECV) for full-duplex backpressure,CURLOPT_TIMEOUT_MS = 0L(caller-governed timeouts so idle SSE streams stay open), explicit redirect handling (kMaxRedirects = 10), and shared TLS CA policy fromfirebase_rest_lib.app/http/http_transport_apple.mm,-fobjc-arc):NSURLSession(HTTPMaximumConnectionsPerHost = 16, serialNSOperationQueuedelegate withmaxConcurrentOperationCount = 1) withNSStreambound-stream uploads (FIRFirebaseHttpStreamBridge),suspend/resumedownload backpressure,kMaxRedirects = 10enforcement, cross-origin credential stripping, and same-originAuthorizationpreservation fromtask.currentRequest(neveroriginalRequest).app/http/http_transport_android.cc):HttpURLConnectionon a bounded 64-worker pool (AndroidHttpThreadPool) with a dedicated backgroundAndroidCancelDispatcherthread (so cancellation from the UI/Unity main thread never triggersNetworkOnMainThreadExceptionand callsconn.disconnect()before closing streams).JavaVM*via optionalfirebase::http::SetAndroidJavaVM(JavaVM*)(called from Unity'sJNI_OnLoad) with automatic fallback tofirebase::util::GetJNIEnvFromApp().app/CMakeLists.txt,app/http/CMakeLists.txt,build_scripts/desktop/package.sh):firebase_http_transport(-fno-exceptions//EHs-c-), sibling tofirebase_rest_lib(avoiding circular CMake dependencies), packed into Desktoplibfirebase_app.aviadeps_firebase_app.Verification Performed on Linux Desktop
ctest): 3/3 suites (29/29 tests) passed in 0.43s:firebase_app_rest_tls_policy_test: 10/10 PASSfirebase_app_http_common_test: 11/11 PASS (URL/origin/redirect/downgrade/proxy/header parsing, pipe watermarks, earlyMarkResponseComplete()unblocking blocked uploaders, atomic single-start guard)firebase_app_http_curl_test: 8/8 PASS (multi-value headers, JSON POST/400/204, server-barrier immediate SSE trickle delivery, idle SSE cancellation unblocking in ~51 ms, same-origin auth preservation & cross-origin credential stripping, redirect loop & unsafe scheme rejection, 1 MiB chunked upload + 4 MiB slow-consumer backpressure download, concurrent mixed unary + SSE transfers, early 413 response unblocking a 2 MiB upload)aarch64-linux-android24-clang++ -std=c++17 -fno-exceptions -Wall -Wextra -Werrorpassed cleanly;llvm-nmverifiedfirebase::util::GetJNIEnvFromApp()is the only external Firebase symbol dependency.2022.3.76f1Mono,6000.6.2f1Mono, and6000.6.2f1IL2CPP (ManagedStrippingLevel.High) covering Storage (57/57real-GCS tests +136.7–141.6 MiB/s64 MiB downloads), Functions (unary + SSE + mid-stream cancel + concurrent), and Firebase AI Logic (GenerativeModel&TemplateGenerativeModelunary + SSE + cancel).Pending Verification (Draft)
ctest(firebase_app_http_common_test,firebase_app_http_curl_test) + Unity macOS player verificationhttp_transport_apple.mmARCNSURLSession+ bound-stream uploads + SSE)