Skip to content

feat(cloud_functions): add support for cloud functions stream #17214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 39 commits into from
Apr 28, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
5bbf13d
chore: add platform interface and method channel implementation for C…
SelaseKay Mar 18, 2025
24acdda
chore: add `httpsCallableStreamFromUrl` and `httpsStreamCallableWithUri`
SelaseKay Mar 18, 2025
fa00dd9
chore: resolve comments
SelaseKay Mar 21, 2025
fa750ed
chore: add Android implementation for Cloud Functions stream
SelaseKay Mar 21, 2025
3e8ac29
chore: resolve formatting issues
SelaseKay Mar 21, 2025
c248cd6
chore: correct variable name
SelaseKay Mar 21, 2025
1ac4533
chore: add support for Cloud Functions Stream(Android)
SelaseKay Mar 23, 2025
d8e0fce
Merge branch 'main' into feat/cloud_functions_stream_support
SelaseKay Mar 24, 2025
95236c8
chore: create dedicated StreamHandler class
SelaseKay Mar 24, 2025
785e019
Merge branch 'main' into feat/cloud_functions_stream_support
SelaseKay Mar 24, 2025
6161988
chore: add streamhandler implementation for ios
SelaseKay Mar 25, 2025
debdc46
Merge branch 'main' into feat/cloud_functions_stream_support
SelaseKay Mar 26, 2025
4d0c10e
chore: add iOS implementation for Cloud Functions stream
SelaseKay Mar 28, 2025
1190fde
chore: add license header to stream handler files
SelaseKay Mar 28, 2025
6bbde2f
chore: web Cloud Functions stream wip
SelaseKay Apr 1, 2025
66be89b
chore: push all
SelaseKay Apr 1, 2025
4804ab9
chore: update functions based on API Doc modification
SelaseKay Apr 2, 2025
4f83c36
chore: clean up code
SelaseKay Apr 3, 2025
213e283
chore: add web package
SelaseKay Apr 3, 2025
de10bcc
Merge branch 'main' into feat/cloud_functions_stream_support
SelaseKay Apr 3, 2025
794d441
chore: add streaming example
SelaseKay Apr 3, 2025
560e3eb
Merge branch 'feat/cloud_functions_stream_support' of github.com:fire…
SelaseKay Apr 3, 2025
6ad0820
chore: fix ci issues
SelaseKay Apr 3, 2025
a9819db
chore: fix ci
SelaseKay Apr 3, 2025
295c6c6
chore: fix cloud function test
SelaseKay Apr 3, 2025
7a5ad4e
chore: add missing doc
SelaseKay Apr 4, 2025
45fea6f
chore: fixes and clean up
SelaseKay Apr 9, 2025
047354a
chore: add e2e for Cloud Functions Stream
SelaseKay Apr 10, 2025
045150d
chore: fix formatting issue
SelaseKay Apr 10, 2025
69ef58f
chore: add more tests and fix timeout for Android
SelaseKay Apr 11, 2025
693aa89
chore: add test for map and list
SelaseKay Apr 11, 2025
aa77160
chore: fix test
SelaseKay Apr 11, 2025
06c1c9c
chore: update year to 2025 in files
SelaseKay Apr 16, 2025
1404359
chore(web): add support for abort signal
SelaseKay Apr 17, 2025
43c223c
chore: resolve comments and add test for Abort
SelaseKay Apr 17, 2025
df743ee
chore: fix test
SelaseKay Apr 17, 2025
c5136d6
chore: fix test
SelaseKay Apr 17, 2025
3964f3b
chore: update copyright year
SelaseKay Apr 18, 2025
f3af9e8
chore: print error to console
SelaseKay Apr 25, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions .github/workflows/scripts/functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,30 @@ export const testFunctionCustomRegion = functions.https.onCall(
export const testFunctionTimeout = functions.https.onCall((req, res) => {
const data = req.data
console.log(JSON.stringify({ data }));
return new Promise((resolve, reject) => {
if (data && data.testTimeout) {
setTimeout(
() => resolve({ timeLimit: 'exceeded' }),
parseInt(data.testTimeout, 10)
);
} else {
reject(
new functions.https.HttpsError(
'invalid-argument',
'testTimeout must be provided.'
)
);
}

const timeoutMs = parseInt(data?.testTimeout, 10);

if (isNaN(timeoutMs)) {
throw new functions.https.HttpsError(
'invalid-argument',
'testTimeout must be provided.'
);
}

if (req.acceptsStreaming) {
setTimeout(() => {
res?.sendChunk({ timeLimit: 'exceeded' });
}, timeoutMs);

return new Promise((resolve) => {
setTimeout(resolve, timeoutMs + 100);
});
}

return new Promise((resolve) => {
setTimeout(() => resolve({ timeLimit: 'exceeded' }), timeoutMs);
});

});

// For e2e testing errors & return values.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ import 'package:firebase_core_platform_interface/firebase_core_platform_interfac
import 'package:flutter/foundation.dart';

export 'package:cloud_functions_platform_interface/cloud_functions_platform_interface.dart'
show HttpsCallableOptions, FirebaseFunctionsException;
show
HttpsCallableOptions,
FirebaseFunctionsException,
AbortSignal,
TimeLimit,
Abort,
Any;

part 'src/firebase_functions.dart';
part 'src/https_callable.dart';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,72 @@ class HttpsCallableOptions {
/// Defaults [limitedUseAppCheckToken] to `false`
HttpsCallableOptions(
{this.timeout = const Duration(seconds: 60),
this.limitedUseAppCheckToken = false});
this.limitedUseAppCheckToken = false,
this.webAbortSignal});

/// Returns the timeout for this instance
Duration timeout;

/// Sets whether or not to use limited-use App Check tokens when invoking the associated function.
bool limitedUseAppCheckToken;

/// An AbortSignal that can be used to cancel the streaming response.
/// When the signal is aborted, the underlying HTTP connection will be terminated.
AbortSignal? webAbortSignal;
}

/// Represents a base class for encapsulating abort signals.
sealed class AbortSignal {}

/// Creates an [AbortSignal] that will automatically abort after a specified [time].
///
/// This is equivalent to calling `AbortSignal.timeout(ms)` in the Web SDK.
///
/// Typically used to cancel long-running operations after a timeout duration.
///
/// Example:
/// ```dart
/// final signal = HttpsCallableOptions(webAbortSignal: TimeLimit(Duration(seconds: 10)));
/// ```
class TimeLimit extends AbortSignal {
final Duration time;
TimeLimit(this.time);
}

/// Creates an [AbortSignal] that is immediately aborted with an optional [reason].
///
/// This is equivalent to calling `AbortSignal.abort(reason)` in the Web SDK.
///
/// Useful when you want to explicitly cancel a callable before it begins, or to provide
/// a specific reason for cancellation.
///
/// Example:
/// ```dart
/// final signal = HttpsCallableOptions(webAbortSignal: Abort('User exited'));
/// ```

class Abort extends AbortSignal {
final Object? reason;
Abort([this.reason]);
}

/// Creates an [AbortSignal] that is aborted when **any** of the provided [signals] is aborted.
///
/// This is equivalent to calling `AbortSignal.any([...])` in the Web SDK.
///
/// Useful for combining multiple abort conditions.
///
/// Example:
/// ```dart
/// final signal = HttpsCallableOptions(
/// webAbortSignal: Any([
/// TimeLimit(Duration(seconds: 10)),
/// Abort('User cancelled'),
/// ]),
/// );
/// ```

class Any extends AbortSignal {
final List<AbortSignal> signals;
Any(this.signals);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import 'package:cloud_functions_web/interop/functions_interop.dart' as interop;

import 'interop/functions.dart' as functions_interop;
import 'utils.dart';
import 'package:web/web.dart' as web;

/// A web specific implementation of [HttpsCallable].
class HttpsCallableWeb extends HttpsCallablePlatform {
Expand Down Expand Up @@ -77,9 +78,14 @@ class HttpsCallableWeb extends HttpsCallablePlatform {
}

final JSAny? parametersJS = parameters?.jsify();
web.AbortSignal? signal;
if (options.webAbortSignal != null) {
signal = _createJsAbortSignal(options.webAbortSignal!);
}
interop.HttpsCallableStreamOptions callableStreamOptions =
interop.HttpsCallableStreamOptions(
limitedUseAppCheckTokens: options.limitedUseAppCheckToken.toJS);
limitedUseAppCheckTokens: options.limitedUseAppCheckToken.toJS,
signal: signal);
try {
await for (final value
in callable.stream(parametersJS, callableStreamOptions)) {
Expand All @@ -89,4 +95,20 @@ class HttpsCallableWeb extends HttpsCallablePlatform {
throw convertFirebaseFunctionsException(e as JSObject, s);
}
}

web.AbortSignal _createJsAbortSignal(AbortSignal signal) {
try {
switch (signal) {
case TimeLimit(:final time):
return web.AbortSignal.timeout(time.inMilliseconds);
case Abort(:final reason):
return web.AbortSignal.abort(reason.jsify());
case Any(:final signals):
final jsSignals = signals.map(_createJsAbortSignal).toList().toJS;
return web.AbortSignal.any(jsSignals);
}
} catch (e, s) {
throw convertFirebaseFunctionsException(e as JSObject, s);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,14 @@ extension HttpsCallableStreamResultJsImplExtension
@anonymous
abstract class HttpsCallableStreamOptions {
external factory HttpsCallableStreamOptions(
{JSBoolean? limitedUseAppCheckTokens});
{JSBoolean? limitedUseAppCheckTokens, web.AbortSignal? signal});
}

extension HttpsCallableStreamOptionsExtension on HttpsCallableStreamOptions {
external JSBoolean? get limitedUseAppCheckTokens;
external set limitedUseAppCheckTokens(JSBoolean? t);
external web.AbortSignal? signal;
external set siganl(web.AbortSignal? s);
}

extension type JsAsyncIterator<T extends JSAny>._(JSObject _)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:cloud_functions/cloud_functions.dart';
Expand Down Expand Up @@ -354,7 +355,8 @@ void main() {
});

test('accepts a [List]', () async {
final stream = callable.stream(data.list).where((event) => event is Chunk);
final stream =
callable.stream(data.list).where((event) => event is Chunk);
await expectLater(
stream,
emits(
Expand All @@ -366,17 +368,54 @@ void main() {

test('accepts a deeply nested [Map]', () async {
final stream = callable.stream({
'type': 'deepMap',
'inputData': data.deepMap,
}).where((event) => event is Chunk);
'type': 'deepMap',
'inputData': data.deepMap,
}).where((event) => event is Chunk);
await expectLater(
stream,
emits(
isA<Chunk>()
.having((e) => e.partialData, 'partialData', equals(data.deepMap)),
isA<Chunk>().having(
(e) => e.partialData,
'partialData',
equals(data.deepMap),
),
),
);
});

test(
'times out when aborted with TimeLimit signal',
() async {
final instance = FirebaseFunctions.instance;
instance.useFunctionsEmulator('localhost', 5001);

final completer = Completer<void>();

final timeoutCallable = FirebaseFunctions.instance.httpsCallable(
kTestFunctionTimeout,
options: HttpsCallableOptions(
webAbortSignal: TimeLimit(const Duration(seconds: 3)),
),
);

timeoutCallable.stream().listen(
(data) {
completer.completeError('Should have thrown');
},
onError: (error) {
if (error is FirebaseFunctionsException) {
expect(error.code, equals('deadline-exceeded'));
completer.complete();
} else {
completer.completeError('Unexpected error type: $error');
}
},
);

await completer.future;
},
skip: !kIsWeb,
);
});
});
}
Loading