Skip to content
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

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

Open
wants to merge 26 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 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
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
2,923 changes: 971 additions & 1,952 deletions .github/workflows/scripts/functions/package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions .github/workflows/scripts/functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^11.5.0",
"firebase-functions": "^4.5.0"
"firebase-admin": "^13.2.0",
"firebase-functions": "^6.3.2"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0",
Expand Down
34 changes: 28 additions & 6 deletions .github/workflows/scripts/functions/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as assert from 'assert';
import * as functions from 'firebase-functions';
import * as functionsv2 from 'firebase-functions/v2';


// For example app.
// noinspection JSUnusedGlobalSymbols
export const listFruit = functions.https.onCall(() => {
Expand All @@ -14,12 +15,17 @@ export const listfruits2ndgen = functionsv2.https.onCall(() => {

// For e2e testing a custom region.
// noinspection JSUnusedGlobalSymbols
export const testFunctionCustomRegion = functions
.region('europe-west1')
.https.onCall(() => 'europe-west1');

export const testFunctionCustomRegion = functions.https.onCall(
{
region: 'europe-west1'
},
() => 'europe-west1'
);

// For e2e testing timeouts.
export const testFunctionTimeout = functions.https.onCall((data) => {
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) {
Expand All @@ -40,7 +46,8 @@ export const testFunctionTimeout = functions.https.onCall((data) => {

// For e2e testing errors & return values.
// noinspection JSUnusedGlobalSymbols
export const testFunctionDefaultRegion = functions.https.onCall((data) => {
export const testFunctionDefaultRegion = functions.https.onCall((req, res) => {
const data = req.data;
console.log(JSON.stringify({ data }));
if (typeof data === 'undefined') {
return 'undefined';
Expand All @@ -66,7 +73,7 @@ export const testFunctionDefaultRegion = functions.https.onCall((data) => {
return 'array';
}

if(data.type === 'rawData') {
if (data.type === 'rawData') {
return data;
}

Expand Down Expand Up @@ -159,3 +166,18 @@ export const testFunctionDefaultRegion = functions.https.onCall((data) => {
export const testMapConvertType = functions.https.onCall((data) => ({
foo: 'bar',
}));

exports.getFruits = functions.https.onCall(async (request, response) => {
const fruits = ['Apple', 'Mango', 'Banana']

const allFruits = fruits.map(async (fruit) => {
// Stream each fruit as it resolves!
if (request.acceptsStreaming) {
response?.sendChunk(fruit);
}
return fruit;
});

// Fallback for non-streaming clients
return Promise.all(allFruits);
});
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ android {
implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrCoreProperty("FirebaseSDKVersion", firebaseCoreProject)}")
implementation 'com.google.firebase:firebase-functions'
implementation 'androidx.annotation:annotation:1.7.0'
implementation 'org.reactivestreams:reactive-streams:1.0.4'
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure why we would need an external library to handle this? We managed to do all the other implementations without it AFAIK/

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes. The other ones provided a way to add listeners directly (eg. addOnConfigUpdatedListener) whereas this one doesn't. It returns a Publisher so this is the only way around it AFAIK.
Reference: https://firebase.google.com/docs/reference/kotlin/com/google/firebase/functions/HttpsCallableReference#summary

}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.plugins.firebase.functions;

import android.net.Uri;
import com.google.firebase.functions.FirebaseFunctions;
import com.google.firebase.functions.HttpsCallableOptions;
import com.google.firebase.functions.HttpsCallableReference;
import com.google.firebase.functions.StreamResponse;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.reactivestreams.Publisher;

public class FirebaseFunctionsStreamHandler implements StreamHandler {

private final FirebaseFunctions firebaseFunctions;

private StreamResponseSubscriber subscriber;

public FirebaseFunctionsStreamHandler(FirebaseFunctions functions) {
this.firebaseFunctions = functions;
}

@Override
public void onListen(Object arguments, EventChannel.EventSink events) {
@SuppressWarnings("unchecked")
Map<String, Object> argumentsMap = (Map<String, Object>) arguments;
httpsStreamCall(argumentsMap, events);
}

@Override
public void onCancel(Object arguments) {
subscriber.cancel();
}

private void httpsStreamCall(Map<String, Object> arguments, EventChannel.EventSink events) {
try {

String functionName = (String) arguments.get("functionName");
String functionUri = (String) arguments.get("functionUri");
String origin = (String) arguments.get("origin");
Integer timeout = (Integer) arguments.get("timeout");
Object parameters = arguments.get("parameters");
boolean limitedUseAppCheckToken =
(boolean) Objects.requireNonNull(arguments.get("limitedUseAppCheckToken"));

if (origin != null) {
Uri originUri = Uri.parse(origin);
firebaseFunctions.useEmulator(originUri.getHost(), originUri.getPort());
}

HttpsCallableReference httpsCallableReference;
HttpsCallableOptions options =
new HttpsCallableOptions.Builder()
.setLimitedUseAppCheckTokens(limitedUseAppCheckToken)
.build();

Publisher<StreamResponse> publisher;
if (functionName != null) {
httpsCallableReference = firebaseFunctions.getHttpsCallable(functionName, options);
publisher = httpsCallableReference.stream(parameters);
} else if (functionUri != null) {
httpsCallableReference =
firebaseFunctions.getHttpsCallableFromUrl(new URL(functionUri), options);
publisher = httpsCallableReference.stream();
} else {
throw new IllegalArgumentException("Either functionName or functionUri must be set");
}

if (timeout != null) {
httpsCallableReference.setTimeout(timeout.longValue(), TimeUnit.MILLISECONDS);
}
subscriber = new StreamResponseSubscriber(events);
publisher.subscribe(subscriber);
} catch (Exception e) {
events.error("firebase_functions", e.getMessage(), null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import com.google.firebase.functions.HttpsCallableReference;
import com.google.firebase.functions.HttpsCallableResult;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
Expand All @@ -35,6 +36,7 @@ public class FlutterFirebaseFunctionsPlugin

private static final String METHOD_CHANNEL_NAME = "plugins.flutter.io/firebase_functions";
private MethodChannel channel;
private FlutterPluginBinding pluginBinding;

/**
* Default Constructor.
Expand All @@ -45,6 +47,7 @@ public FlutterFirebaseFunctionsPlugin() {}

@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
pluginBinding = binding;
channel = new MethodChannel(binding.getBinaryMessenger(), METHOD_CHANNEL_NAME);
channel.setMethodCallHandler(this);
}
Expand All @@ -55,6 +58,16 @@ public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel = null;
}

private void registerEventChannel(Map<String, Object> arguments) {
final String eventId = (String) Objects.requireNonNull(arguments.get("eventChannelId"));
final String eventChannelName = METHOD_CHANNEL_NAME + "/" + eventId;
final EventChannel eventChannel =
new EventChannel(pluginBinding.getBinaryMessenger(), eventChannelName);
FirebaseFunctions functions = getFunctions(arguments);
FirebaseFunctionsStreamHandler streamHandler = new FirebaseFunctionsStreamHandler(functions);
eventChannel.setStreamHandler(streamHandler);
}

private FirebaseFunctions getFunctions(Map<String, Object> arguments) {
String appName = (String) Objects.requireNonNull(arguments.get("appName"));
String region = (String) Objects.requireNonNull(arguments.get("region"));
Expand Down Expand Up @@ -116,24 +129,26 @@ private Task<Object> httpsFunctionCall(Map<String, Object> arguments) {

@Override
public void onMethodCall(MethodCall call, @NonNull final Result result) {
if (!call.method.equals("FirebaseFunctions#call")) {
if (call.method.equals("FirebaseFunctions#registerEventChannel")) {
registerEventChannel(call.arguments());
result.success(null);
} else if (call.method.equals("FirebaseFunctions#call")) {
httpsFunctionCall(call.arguments())
.addOnCompleteListener(
task -> {
if (task.isSuccessful()) {
result.success(task.getResult());
} else {
Exception exception = task.getException();
result.error(
"firebase_functions",
exception != null ? exception.getMessage() : null,
getExceptionDetails(exception));
}
});
} else {
result.notImplemented();
return;
}

httpsFunctionCall(call.arguments())
.addOnCompleteListener(
task -> {
if (task.isSuccessful()) {
result.success(task.getResult());
} else {
Exception exception = task.getException();
result.error(
"firebase_functions",
exception != null ? exception.getMessage() : null,
getExceptionDetails(exception));
}
});
}

private Map<String, Object> getExceptionDetails(@Nullable Exception exception) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.plugins.firebase.functions;

import android.os.Handler;
import android.os.Looper;
import com.google.firebase.functions.StreamResponse;
import io.flutter.plugin.common.EventChannel;
import java.util.HashMap;
import java.util.Map;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

public class StreamResponseSubscriber implements Subscriber<StreamResponse> {
private Subscription subscription;
private final EventChannel.EventSink eventSink;

private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

public StreamResponseSubscriber(EventChannel.EventSink eventSink) {
this.eventSink = eventSink;
}

@Override
public void onSubscribe(Subscription s) {
this.subscription = s;
subscription.request(Long.MAX_VALUE);
}

@Override
public void onNext(StreamResponse streamResponse) {
Map<String, Object> responseMap = new HashMap<>();
if (streamResponse instanceof StreamResponse.Message) {
Object message = ((StreamResponse.Message) streamResponse).getMessage().getData();
responseMap.put("message", message);
mainThreadHandler.post(() -> eventSink.success(responseMap));
} else {
Object result = ((StreamResponse.Result) streamResponse).getResult().getData();
responseMap.put("result", result);
mainThreadHandler.post(() -> eventSink.success(responseMap));
}
}

@Override
public void onError(Throwable t) {
if (eventSink != null) {
eventSink.error("firebase_functions", t.getMessage(), null);
}
}

@Override
public void onComplete() {
if (eventSink != null) {
eventSink.endOfStream();
}
}

public void cancel() {
if (subscription != null) {
subscription.cancel();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<application
android:label="example"
android:name="${applicationName}"
android:usesCleartextTraffic="true"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pluginManagement {

plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "7.3.0" apply false
id "com.android.application" version "8.1.0" apply false
// START: FlutterFire Configuration
id "com.google.gms.google-services" version "4.3.15" apply false
// END: FlutterFire Configuration
Expand Down
Loading
Loading