Skip to content

[App] Add cross-platform streaming native HTTP transport (firebase_http_transport) - #1996

Draft
AustinBenoit wants to merge 6 commits into
mainfrom
ab-native-http-transport
Draft

AustinBenoit wants to merge 6 commits into
mainfrom
ab-native-http-transport

Conversation

@AustinBenoit

@AustinBenoit AustinBenoit commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a cross-platform, full-duplex streaming native HTTP transport (firebase_http_transport) under app/http/ in firebase-cpp-sdk, together with a thin SWIG-friendly flat C/handle bridge (app/http/http_bridge.h) designed for consumption by both C++ callers and firebase-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, broken UploadHandlerStream on Unity 6000.6 IL2CPP) or Mono's UnityTlsStream (~10–15 MiB/s download ceiling on pre-CoreCLR Unity runtimes). Putting the native HTTP transport in firebase-cpp-sdk keeps all native C++ / Objective-C++ / JNI code in a single repository rather than duplicating platform transport code inside firebase-unity-sdk.

Legacy desktop-only app/rest/ is intentionally left untouched; Desktop http_transport_curl.cc reuses firebase_rest_lib's existing app/rest/curl/curl_handles.h (ref-counted curl_global_init) and app/rest/curl/tls_policy.h (TLS CA bundle resolution).

Architecture & Platform Backends

  • app/http/http_transport.h + app/http/http_transport_common.cc:
    • Handle-keyed std::shared_ptr<HttpOperation> registry with atomic single-start and cancellation guards, bounded upload (256 KiB high-water / 128 KiB low-water) and download (2 MiB / 1 MiB) streaming pipes, and a single global completion event queue (HttpWaitNextEventInternal) that eliminates native-to-managed reverse callbacks.
    • Shared RFC 3986 redirect resolver (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, plus https → http downgrade and non-HTTP(S) scheme blocking across all three backends.
  • app/http/http_bridge.h:
    • Flat C/handle SWIG bridge (12 firebase::Http*Internal functions using only <stdint.h> and <string>) so firebase-unity-sdk can %include "app/http/http_bridge.h" with zero SWIGTYPE_p_* wrapper leaks.
  • Desktop (app/http/http_transport_curl.cc):
    • Dedicated libcurl CURLM multi-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 from firebase_rest_lib.
  • Apple iOS / tvOS (app/http/http_transport_apple.mm, -fobjc-arc):
    • Ephemeral NSURLSession (HTTPMaximumConnectionsPerHost = 16, serial NSOperationQueue delegate with maxConcurrentOperationCount = 1) with NSStream bound-stream uploads (FIRFirebaseHttpStreamBridge), suspend/resume download backpressure, kMaxRedirects = 10 enforcement, cross-origin credential stripping, and same-origin Authorization preservation from task.currentRequest (never originalRequest).
  • Android (app/http/http_transport_android.cc):
    • JNI HttpURLConnection on a bounded 64-worker pool (AndroidHttpThreadPool) with a dedicated background AndroidCancelDispatcher thread (so cancellation from the UI/Unity main thread never triggers NetworkOnMainThreadException and calls conn.disconnect() before closing streams).
    • Resolves JavaVM* via optional firebase::http::SetAndroidJavaVM(JavaVM*) (called from Unity's JNI_OnLoad) with automatic fallback to firebase::util::GetJNIEnvFromApp().
  • Build & Packaging (app/CMakeLists.txt, app/http/CMakeLists.txt, build_scripts/desktop/package.sh):
    • Static library target firebase_http_transport (-fno-exceptions / /EHs-c-), sibling to firebase_rest_lib (avoiding circular CMake dependencies), packed into Desktop libfirebase_app.a via deps_firebase_app.

Verification Performed on Linux Desktop

  • C++ unit & loopback HTTP/SSE gtests (ctest): 3/3 suites (29/29 tests) passed in 0.43s:
    • firebase_app_rest_tls_policy_test: 10/10 PASS
    • firebase_app_http_common_test: 11/11 PASS (URL/origin/redirect/downgrade/proxy/header parsing, pipe watermarks, early MarkResponseComplete() 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)
  • Android NDK r28c cross-compile: aarch64-linux-android24-clang++ -std=c++17 -fno-exceptions -Wall -Wextra -Werror passed cleanly; llvm-nm verified firebase::util::GetJNIEnvFromApp() is the only external Firebase symbol dependency.
  • Paired Unity Desktop end-to-end verification: Built and verified with the stacked Unity draft PR ([App][Storage][Functions][AI] Route pure-C# HTTP stack through C++ native firebase_http_transport firebase-unity-sdk#1579) across Unity 2022.3.76f1 Mono, 6000.6.2f1 Mono, and 6000.6.2f1 IL2CPP (ManagedStrippingLevel.High) covering Storage (57/57 real-GCS tests + 136.7–141.6 MiB/s 64 MiB downloads), Functions (unary + SSE + mid-stream cancel + concurrent), and Firebase AI Logic (GenerativeModel & TemplateGenerativeModel unary + SSE + cancel).

Pending Verification (Draft)

  • macOS Desktop ctest (firebase_app_http_common_test, firebase_app_http_curl_test) + Unity macOS player verification
  • Android physical device end-to-end verification (Storage, Functions, Firebase AI Logic)
  • Physical iPhone (iOS) end-to-end verification (http_transport_apple.mm ARC NSURLSession + bound-stream uploads + SSE)
  • Windows Desktop CI build & gtest verification

…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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread app/http/http_transport_android.cc Outdated
Comment on lines +815 to +817
while (!op->IsCanceled()) {
bool eof = false;
size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

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);

Comment thread app/http/http_transport_android.cc Outdated
Comment on lines +1027 to +1030
while (!op->IsCanceled()) {
jint n =
env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), 0,
static_cast<jsize>(kReadSlice));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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));

Comment on lines +57 to +63
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;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant