Skip to content

[App][Storage][Functions][AI] Route pure-C# HTTP stack through C++ native firebase_http_transport - #1579

Draft
AustinBenoit wants to merge 4 commits into
ab-pure-csharp-storagefrom
ab-native-http-unity
Draft

AustinBenoit wants to merge 4 commits into
ab-pure-csharp-storagefrom
ab-native-http-unity

Conversation

@AustinBenoit

Copy link
Copy Markdown
Contributor

Description

Routes all pure-C# HTTP products in firebase-unity-sdk — Storage, Functions, and Firebase AI Logic (GenerativeModel and TemplateGenerativeModel; LiveGenerativeModel remains on ClientWebSocket) — through a shared FirebaseHttpMessageHandler backed by firebase_http_transport in firebase-cpp-sdk (firebase/firebase-cpp-sdk#1996).

Stacked on #1555 (ab-pure-csharp-storage, pure-C# Storage rewrite).

Architecture

  • Zero native HTTP transport code duplicated in firebase-unity-sdk:
    • app/CMakeLists.txt links firebase_http_transport from firebase-cpp-sdk into FirebaseCppApp, CMakeLists.txt includes firebase_http_transport in ios_pack, and app/src/swig/app.i %includes app/http/http_bridge.h directly.
    • app/src/unity_main.cpp forwards JavaVM* from JNI_OnLoad to firebase::http::SetAndroidJavaVM(jvm) on Android (with automatic fallback to firebase::util::GetJNIEnvFromApp()).
    • cmake/unity_tvos.cmake aligns CMAKE_OSX_DEPLOYMENT_TARGET to 15.0 (matching cmake/unity_ios.cmake and firebase-cpp-sdk).
  • Single shared managed entry point (app/src/internal/HttpHelpers.cs + app/src/internal/FirebaseHttpMessageHandler.cs):
    • HttpHelpers.CreateHttpClient(...) is now the single HttpClient construction site across Storage, Functions, and Firebase AI Logic.
    • FirebaseHttpMessageHandler implements HttpMessageHandler over the SWIG handle bridge using a dedicated background event-dispatcher thread (HttpWaitNextEventInternal), bounded request/response streaming pipes (full-duplex upload + SSE streaming without response buffering), GCHandle pinning across native hops, and automatic fallback to HttpClientHandler when AppUtilPINVOKE is unavailable (walking nested TypeInitializationException chains and BadImageFormatException).
    • HttpHelpers.ValidateHttpResponse(...) and HttpHelpers.ReadLineWithCancellationAsync(...) consolidate SSE line reading and cancellation-safe non-2xx error-body reads across Functions and Firebase AI Logic.
  • Product integration:
    • Storage (StorageHttpClient, ResumableUploadTask, ResumableDownloadTask, StorageTaskScheduler): uses HttpHelpers.CreateHttpClient, threads StallWatchdog tokens through error-body reads, and removes the managed-TLS bandwidth bottleneck without introducing UnityEngine.Networking (avoiding Unity 6000.6 IL2CPP UploadHandlerStream corruption).
    • Functions (FirebaseFunctions, HttpsCallableReference): routes unary CallAsync and StreamAsync SSE calls through HttpHelpers.CreateHttpClient, preserves full-body timeout coverage on unary calls, and registers response.Dispose() on cancellation for both SSE and error-body reads.
    • Firebase AI Logic (GenerativeModel, TemplateGenerativeModel): routes unary and GenerateContentStreamAsync SSE calls through HttpHelpers.CreateHttpClient with cancellation-safe error-body and SSE reads. (LiveGenerativeModel uses ClientWebSocket and is unchanged aside from doc/comments.)
  • Documentation (docs/readme.md): Documents why Firebase Unity pure-C# products route HTTP through firebase-cpp-sdk's native firebase_http_transport instead of UnityWebRequest or Mono's UnityTlsStream.

Building Locally Against Paired C++ Branch

python3 scripts/gha/build_zips.py \
  --platform=<linux|darwin|android|ios> \
  --apis=storage,functions,firebaseai,auth,app_check \
  --cmake_extras=-DFIREBASE_CPP_SDK_DIR=/path/to/firebase-cpp-sdk-ab-native-http-transport

Or in GitHub Actions (build_starter.yml), dispatch with firebase_cpp_sdk_version=ab-native-http-transport.

Verification Performed on Linux Desktop

All suites built against firebase/firebase-cpp-sdk ab-native-http-transport (e5f05616) and verified green:

  • Unified Storage + Functions + Firebase AI Logic smoke (Unity 6000.6.2f1 Mono): 27/27 PASS
    • Verified all 4 HttpClients (Storage, Functions, GenerativeModel, TemplateGenerativeModel) use FirebaseHttpMessageHandler (availability=1).
    • Verified Functions unary calls, header propagation, 429 error mapping, incremental SSE delivery (223–809 ms), mid-stream cancel (111 ms), and concurrent SSE + unary calls.
    • Verified Firebase AI Logic incremental SSE delivery (152–453 ms), template mid-stream cancel (103 ms), and live HTTPS roundtrip.
    • Verified Storage real-GCS roundtrip, timeout enforcement (402 ms), GC-pin mid-await slow body, and all 5 redirect/credential-stripping cases.
  • Firebase AI Logic UIHandlerAutomated.cs offline native HTTP tests (Unity 6000.6.2f1 Mono): 2/2 PASS (InternalTestNativeHttpFallbackClassification, InternalTestNativeHttpLoopbackStreamingAndCancellation: multi-value headers, SSE incremental + cancel, stalled 503 error-body cancel, unary post-header timeout, early 413 >256 KiB upload unblock).
  • Storage real-GCS automated suite (57 tests):
    • Unity 2022.3.76f1 Mono: 57/57 PASS (61.3s)
    • Unity 6000.6.2f1 IL2CPP (ManagedStrippingLevel.High): 57/57 PASS (59.4s)
  • Storage 64 MiB real-GCS throughput (FirebaseHttpMessageHandler vs managed UnityTlsStream baseline):
Runtime Managed UnityTlsStream Download Native firebase_http_transport Download Speedup Native Upload gc0_delta Off-Main-Thread Callbacks
Unity 2022.3.76f1 Mono 15.4 MiB/s 141.6 MiB/s 9.2× 39.4 MiB/s 5 0
Unity 6000.6.2f1 IL2CPP High 10.7 MiB/s 136.7 MiB/s 12.8× 41.5 MiB/s 5 0

Pending Verification (Draft)

  • macOS Desktop Unity Mono & IL2CPP end-to-end verification (Storage, Functions, Firebase AI Logic)
  • Physical Android device end-to-end verification (Storage, Functions, Firebase AI Logic; JNI JNI_OnLoad / GetJNIEnvFromApp + AndroidCancelDispatcher main-thread cancel with zero NetworkOnMainThreadException)
  • Physical iPhone (iOS) end-to-end verification (http_transport_apple.mm ARC NSURLSession + bound-stream uploads + SSE + ios_pack linking)
  • Windows Desktop CI build & Playmode/Standalone verification

Type of Change

  • Bug fix
  • New feature
  • Other

…ative firebase_http_transport

Replaces per-product default HttpClientHandler usage across Storage, Functions, and
Firebase AI Logic with a shared internal FirebaseHttpMessageHandler backed by
firebase-cpp-sdk's firebase_http_transport (libcurl on Desktop, ARC NSURLSession on
iOS/tvOS, JNI HttpURLConnection on Android), bridged via SWIG in app.i.

- Zero C++/ObjC++/JNI HTTP transport sources live in firebase-unity-sdk; CMake links
  firebase_http_transport from firebase-cpp-sdk (including ios_pack and JNI_OnLoad
  SetAndroidJavaVM wiring) and aligns iOS/tvOS CMake deployment targets to 15.0.
- Hardens SSE mid-stream and non-2xx error-body cancellation across Functions,
  Firebase AI (GenerativeModel & TemplateGenerativeModel), and Storage StallWatchdog,
  and switches unary Functions CallAsync to ResponseContentRead so HttpClient's 70s
  timeout covers full response body reads.
- Adds SSE cancellation and offline loopback FirebaseHttpMessageHandler/HttpHelpers
  automated tests in FirebaseAI UIHandlerAutomated.cs.

@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 shared platform-native FirebaseHttpMessageHandler backed by firebase-cpp-sdk's native HTTP transport to route networking for Storage, Functions, and Firebase AI on Unity, bypassing UnityEngine.Networking to achieve native wire-speed transfers. The review feedback focuses on critical performance optimizations within FirebaseHttpMessageHandler to reduce garbage collection pressure. Specifically, the reviewer recommends moving CancellationTokenRegistration and TaskCompletionSource allocations outside of the read and write loops, and optimizing the synchronous fast path in ReadAsync by attempting to read from the native buffer before preparing the async wait.

Comment on lines +1036 to +1083
try {
Task waitTask = initialWaitTask;
while (true) {
if (cancellationToken.CanBeCanceled) {
CancellationTokenRegistration reg = default;
bool registered = false;
try {
reg = cancellationToken.Register(
state => ((NativeOperationState)state).AbortAndRelease(), _op);
registered = true;
} catch (ObjectDisposedException) {
// If the caller's CTS was already disposed without cancelling (e.g. HttpClient's
// send-phase CTS after ResponseHeadersRead), await waitTask without registration.
}
try {
await waitTask.ConfigureAwait(false);
} finally {
if (registered) {
reg.Dispose();
}
}
} else {
await waitTask.ConfigureAwait(false);
}

if (Volatile.Read(ref _disposed) != 0) {
throw new ObjectDisposedException(nameof(NativeResponseStream));
}
if (cancellationToken.IsCancellationRequested) {
_op.AbortAndRelease();
throw new OperationCanceledException(cancellationToken);
}

waitTask = _op.ReadSignal.PrepareWait();
int rc = _op.TryReadResponseBody(buffer, offset, count);
if (rc > 0) {
return rc;
}
if (rc == 0) {
_eof = true;
_op.AbortAndRelease();
return 0;
}
if (rc == ReadErrorOrCanceled) {
throw CreateReadFailureException(cancellationToken);
}
}
} finally {

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

Registering and disposing CancellationTokenRegistration on every single iteration of the while (true) loop in ReadSlowPathAsync is highly inefficient and creates significant garbage collection pressure. Since the cancellationToken does not change during the lifetime of ReadSlowPathAsync, we can register the cancellation callback once outside the loop.

        try {
          CancellationTokenRegistration reg = default;
          bool registered = false;
          if (cancellationToken.CanBeCanceled) {
            try {
              reg = cancellationToken.Register(
                  state => ((NativeOperationState)state).AbortAndRelease(), _op);
              registered = true;
            } catch (ObjectDisposedException) {
              // If the caller's CTS was already disposed without cancelling (e.g. HttpClient's
              // send-phase CTS after ResponseHeadersRead), await waitTask without registration.
            }
          }
          try {
            Task waitTask = initialWaitTask;
            while (true) {
              await waitTask.ConfigureAwait(false);

              if (Volatile.Read(ref _disposed) != 0) {
                throw new ObjectDisposedException(nameof(NativeResponseStream));
              }
              if (cancellationToken.IsCancellationRequested) {
                _op.AbortAndRelease();
                throw new OperationCanceledException(cancellationToken);
              }

              waitTask = _op.ReadSignal.PrepareWait();
              int rc = _op.TryReadResponseBody(buffer, offset, count);
              if (rc > 0) {
                return rc;
              }
              if (rc == 0) {
                _eof = true;
                _op.AbortAndRelease();
                return 0;
              }
              if (rc == ReadErrorOrCanceled) {
                throw CreateReadFailureException(cancellationToken);
              }
            }
          } finally {
            if (registered) {
              reg.Dispose();
            }
          }
        } finally {

Comment on lines +853 to +884
_op.PinWaiter();
try {
int writtenTotal = 0;
while (writtenTotal < count) {
effectiveToken.ThrowIfCancellationRequested();
_token.ThrowIfCancellationRequested();

Task waitTask = _op.WriteSignal.PrepareWait();
int accepted = _op.TryWriteRequestBody(
buffer, offset + writtenTotal, count - writtenTotal);
if (accepted < 0) {
effectiveToken.ThrowIfCancellationRequested();
_token.ThrowIfCancellationRequested();
string err = _op.GetErrorMessage();
throw new IOException(
string.IsNullOrEmpty(err) ? "Native HTTP upload stream closed." : err);
}
writtenTotal += accepted;
if (writtenTotal < count) {
if (effectiveToken.CanBeCanceled) {
var cancelTcs = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
using (effectiveToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs)) {
await Task.WhenAny(waitTask, cancelTcs.Task).ConfigureAwait(false);
}
} else {
await waitTask.ConfigureAwait(false);
}
}
}
} finally {

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

Allocating a new TaskCompletionSource<bool> and registering a cancellation callback on every single iteration of the write loop when the stream blocks is highly inefficient. We can register the cancellation callback once outside the loop to call CancelNativeOnly(), which will signal WriteSignal and complete the waitTask immediately, completely avoiding these allocations.

        _op.PinWaiter();
        try {
          CancellationTokenRegistration reg = default;
          if (effectiveToken.CanBeCanceled) {
            reg = effectiveToken.Register(state => ((NativeOperationState)state).CancelNativeOnly(), _op);
          }
          try {
            int writtenTotal = 0;
            while (writtenTotal < count) {
              effectiveToken.ThrowIfCancellationRequested();
              _token.ThrowIfCancellationRequested();

              Task waitTask = _op.WriteSignal.PrepareWait();
              int accepted = _op.TryWriteRequestBody(
                  buffer, offset + writtenTotal, count - writtenTotal);
              if (accepted < 0) {
                effectiveToken.ThrowIfCancellationRequested();
                _token.ThrowIfCancellationRequested();
                string err = _op.GetErrorMessage();
                throw new IOException(
                    string.IsNullOrEmpty(err) ? "Native HTTP upload stream closed." : err);
              }
              writtenTotal += accepted;
              if (writtenTotal < count) {
                await waitTask.ConfigureAwait(false);
              }
            }
          } finally {
            reg.Dispose();
          }
        } finally {

Comment on lines +1004 to +1021

// Synchronous fast path: while the native engine is streaming ahead into its 2 MiB buffer,
// most reads copy straight out of native memory with zero Task or TCS allocation.
Task waitTask = _op.ReadSignal.PrepareWait();
int rc = _op.TryReadResponseBody(buffer, offset, count);
if (rc > 0) {
return Task.FromResult(rc);
}
if (rc == 0) {
_eof = true;
// Eagerly release the native operation handle at EOF so callers that omit `using` on
// HttpResponseMessage do not retain native memory until GC finalization.
_op.AbortAndRelease();
return Task.FromResult(0);
}
if (rc == ReadErrorOrCanceled) {
return Task.FromException<int>(CreateReadFailureException(cancellationToken));
}

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

Calling PrepareWait() before TryReadResponseBody always allocates a TaskCompletionSource<bool> even on the fast path when data is already available in the native buffer. We can optimize this by attempting to read first without preparing the wait. If it would block, we then prepare the wait and try reading once more to safely handle any race signals before entering the slow path.

        // Synchronous fast path: try reading first without preparing the wait.
        // This completely avoids TaskCompletionSource allocation when data is already available.
        int rc = _op.TryReadResponseBody(buffer, offset, count);
        if (rc > 0) {
          return Task.FromResult(rc);
        }
        if (rc == 0) {
          _eof = true;
          // Eagerly release the native operation handle at EOF so callers that omit `using` on
          // HttpResponseMessage do not retain native memory until GC finalization.
          _op.AbortAndRelease();
          return Task.FromResult(0);
        }
        if (rc == ReadErrorOrCanceled) {
          return Task.FromException<int>(CreateReadFailureException(cancellationToken));
        }

        // Slow path: prepare the wait and try reading one more time to avoid missing a race signal.
        Task waitTask = _op.ReadSignal.PrepareWait();
        rc = _op.TryReadResponseBody(buffer, offset, count);
        if (rc > 0) {
          return Task.FromResult(rc);
        }
        if (rc == 0) {
          _eof = true;
          _op.AbortAndRelease();
          return Task.FromResult(0);
        }
        if (rc == ReadErrorOrCanceled) {
          return Task.FromException<int>(CreateReadFailureException(cancellationToken));
        }

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