Repository navigation
[App] Add cross-platform streaming native HTTP transport (firebase_http_transport) - #1996
AustinBenoit wants to merge 6 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)
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)