Repository navigation
[App][Storage][Functions][AI] Route pure-C# HTTP stack through C++ native firebase_http_transport - #1579
[App][Storage][Functions][AI] Route pure-C# HTTP stack through C++ native firebase_http_transport#1579AustinBenoit wants to merge 4 commits into
Conversation
…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.
There was a problem hiding this comment.
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.
| 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 { |
There was a problem hiding this comment.
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 {| _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 { |
There was a problem hiding this comment.
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 {|
|
||
| // 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)); | ||
| } |
There was a problem hiding this comment.
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));
}…sed maxConnectionsPerServer, cancel-all on unload (S4, U1, U2)
…or macOS, Android, and iOS (T5)
Description
Routes all pure-C# HTTP products in
firebase-unity-sdk— Storage, Functions, and Firebase AI Logic (GenerativeModelandTemplateGenerativeModel;LiveGenerativeModelremains onClientWebSocket) — through a sharedFirebaseHttpMessageHandlerbacked byfirebase_http_transportinfirebase-cpp-sdk(firebase/firebase-cpp-sdk#1996).Stacked on #1555 (
ab-pure-csharp-storage, pure-C# Storage rewrite).Architecture
firebase-unity-sdk:app/CMakeLists.txtlinksfirebase_http_transportfromfirebase-cpp-sdkintoFirebaseCppApp,CMakeLists.txtincludesfirebase_http_transportinios_pack, andapp/src/swig/app.i%includesapp/http/http_bridge.hdirectly.app/src/unity_main.cppforwardsJavaVM*fromJNI_OnLoadtofirebase::http::SetAndroidJavaVM(jvm)on Android (with automatic fallback tofirebase::util::GetJNIEnvFromApp()).cmake/unity_tvos.cmakealignsCMAKE_OSX_DEPLOYMENT_TARGETto15.0(matchingcmake/unity_ios.cmakeandfirebase-cpp-sdk).app/src/internal/HttpHelpers.cs+app/src/internal/FirebaseHttpMessageHandler.cs):HttpHelpers.CreateHttpClient(...)is now the singleHttpClientconstruction site across Storage, Functions, and Firebase AI Logic.FirebaseHttpMessageHandlerimplementsHttpMessageHandlerover 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),GCHandlepinning across native hops, and automatic fallback toHttpClientHandlerwhenAppUtilPINVOKEis unavailable (walking nestedTypeInitializationExceptionchains andBadImageFormatException).HttpHelpers.ValidateHttpResponse(...)andHttpHelpers.ReadLineWithCancellationAsync(...)consolidate SSE line reading and cancellation-safe non-2xx error-body reads across Functions and Firebase AI Logic.StorageHttpClient,ResumableUploadTask,ResumableDownloadTask,StorageTaskScheduler): usesHttpHelpers.CreateHttpClient, threadsStallWatchdogtokens through error-body reads, and removes the managed-TLS bandwidth bottleneck without introducingUnityEngine.Networking(avoiding Unity6000.6IL2CPPUploadHandlerStreamcorruption).FirebaseFunctions,HttpsCallableReference): routes unaryCallAsyncandStreamAsyncSSE calls throughHttpHelpers.CreateHttpClient, preserves full-body timeout coverage on unary calls, and registersresponse.Dispose()on cancellation for both SSE and error-body reads.GenerativeModel,TemplateGenerativeModel): routes unary andGenerateContentStreamAsyncSSE calls throughHttpHelpers.CreateHttpClientwith cancellation-safe error-body and SSE reads. (LiveGenerativeModelusesClientWebSocketand is unchanged aside from doc/comments.)docs/readme.md): Documents why Firebase Unity pure-C# products route HTTP throughfirebase-cpp-sdk's nativefirebase_http_transportinstead ofUnityWebRequestor Mono'sUnityTlsStream.Building Locally Against Paired C++ Branch
Or in GitHub Actions (
build_starter.yml), dispatch withfirebase_cpp_sdk_version=ab-native-http-transport.Verification Performed on Linux Desktop
All suites built against
firebase/firebase-cpp-sdkab-native-http-transport(e5f05616) and verified green:Unity 6000.6.2f1Mono):27/27PASSHttpClients (Storage, Functions,GenerativeModel,TemplateGenerativeModel) useFirebaseHttpMessageHandler(availability=1).223–809 ms), mid-stream cancel (111 ms), and concurrent SSE + unary calls.152–453 ms), template mid-stream cancel (103 ms), and live HTTPS roundtrip.402 ms), GC-pin mid-await slow body, and all 5 redirect/credential-stripping cases.UIHandlerAutomated.csoffline native HTTP tests (Unity 6000.6.2f1Mono):2/2PASS (InternalTestNativeHttpFallbackClassification,InternalTestNativeHttpLoopbackStreamingAndCancellation: multi-value headers, SSE incremental + cancel, stalled 503 error-body cancel, unary post-header timeout, early 413 >256 KiB upload unblock).57tests):Unity 2022.3.76f1Mono: 57/57 PASS (61.3s)Unity 6000.6.2f1IL2CPP (ManagedStrippingLevel.High): 57/57 PASS (59.4s)FirebaseHttpMessageHandlervs managedUnityTlsStreambaseline):UnityTlsStreamDownloadfirebase_http_transportDownloadgc0_delta2022.3.76f1Mono6000.6.2f1IL2CPP HighPending Verification (Draft)
JNI_OnLoad/GetJNIEnvFromApp+AndroidCancelDispatchermain-thread cancel with zeroNetworkOnMainThreadException)http_transport_apple.mmARCNSURLSession+ bound-stream uploads + SSE +ios_packlinking)Type of Change