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(remote-config): custom signals support #17053

Merged
merged 16 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.google.firebase.remoteconfig.ConfigUpdate;
import com.google.firebase.remoteconfig.ConfigUpdateListener;
import com.google.firebase.remoteconfig.ConfigUpdateListenerRegistration;
import com.google.firebase.remoteconfig.CustomSignals;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigClientException;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigException;
Expand Down Expand Up @@ -137,6 +138,36 @@ private FirebaseRemoteConfig getRemoteConfig(Map<String, Object> arguments) {
return FirebaseRemoteConfig.getInstance(app);
}

private Task<Void> setCustomSignals(
FirebaseRemoteConfig remoteConfig, Map<String, Object> customSignalsArguments) {
TaskCompletionSource<Void> taskCompletionSource = new TaskCompletionSource<>();
cachedThreadPool.execute(
() -> {
try {
CustomSignals.Builder customSignals = new CustomSignals.Builder();
for (Map.Entry<String, Object> entry : customSignalsArguments.entrySet()) {
Object value = entry.getValue();
if (value instanceof String) {
customSignals.put(entry.getKey(), (String) value);
} else if (value instanceof Long) {
customSignals.put(entry.getKey(), (Long) value);
} else if (value instanceof Integer) {
customSignals.put(entry.getKey(), ((Integer) value).longValue());
} else if (value instanceof Double) {
customSignals.put(entry.getKey(), (Double) value);
} else if (value == null) {
customSignals.put(entry.getKey(), null);
}
}
Tasks.await(remoteConfig.setCustomSignals(customSignals.build()));
taskCompletionSource.setResult(null);
} catch (Exception e) {
taskCompletionSource.setException(e);
}
});
return taskCompletionSource.getTask();
}

@Override
public void onMethodCall(MethodCall call, @NonNull final MethodChannel.Result result) {
Task<?> methodCallTask;
Expand Down Expand Up @@ -192,6 +223,13 @@ public void onMethodCall(MethodCall call, @NonNull final MethodChannel.Result re
methodCallTask = Tasks.forResult(configProperties);
break;
}
case "RemoteConfig#setCustomSignals":
{
Map<String, Object> customSignals =
Objects.requireNonNull(call.argument("customSignals"));
methodCallTask = setCustomSignals(remoteConfig, customSignals);
break;
}
default:
{
result.notImplemented();
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
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,28 @@ - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)flutter
[self setDefaults:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"RemoteConfig#getProperties" isEqualToString:call.method]) {
[self getProperties:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"RemoteConfig#setCustomSignals" isEqualToString:call.method]) {
[self setCustomSignals:call.arguments withMethodCallResult:methodCallResult];
} else {
methodCallResult.success(FlutterMethodNotImplemented);
}
}

#pragma mark - Remote Config API
- (void)setCustomSignals:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRRemoteConfig *remoteConfig = [self getFIRRemoteConfigFromArguments:arguments];
NSDictionary *customSignals = arguments[@"customSignals"];

[remoteConfig setCustomSignals:customSignals
withCompletion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}

- (void)ensureInitialized:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRRemoteConfig *remoteConfig = [self getFIRRemoteConfigFromArguments:arguments];
[remoteConfig ensureInitializedWithCompletionHandler:^(NSError *initializationError) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,20 @@ class FirebaseRemoteConfig extends FirebasePluginPlatform {
Stream<RemoteConfigUpdate> get onConfigUpdated {
return _delegate.onConfigUpdated;
}

/// Changes the custom signals for this FirebaseRemoteConfig instance
/// Custom signals are subject to limits on the size of key/value pairs and the total number of signals.
/// Any calls that exceed these limits will be discarded.
/// If a key already exists, the value is overwritten. Setting the value of a custom signal to null un-sets the signal.
/// The signals will be persisted locally on the client.
Future<void> setCustomSignals(Map<String, Object?> customSignals) {
customSignals.forEach((key, value) {
// Apple will not trigger exception for boolean because it is represented as a number in objective-c so we assert early for all platforms
assert(
value is String || value is num || value == null,
'Invalid value type "${value.runtimeType}" for key "$key". Only strings, numbers, or null are supported.',
);
});
return _delegate.setCustomSignals(customSignals);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -306,4 +306,19 @@ class MethodChannelFirebaseRemoteConfig extends FirebaseRemoteConfigPlatform {
});
return _onConfigUpdatedStream!;
}

@override
Future<void> setCustomSignals(Map<String, Object?> customSignals) {
try {
return channel.invokeMethod<void>(
'RemoteConfig#setCustomSignals',
<String, dynamic>{
'appName': app.name,
'customSignals': customSignals,
},
);
} catch (exception, stackTrace) {
convertPlatformException(exception, stackTrace);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,13 @@ abstract class FirebaseRemoteConfigPlatform extends PlatformInterface {
Stream<RemoteConfigUpdate> get onConfigUpdated {
throw UnimplementedError('onConfigUpdated getter not implemented');
}

/// Changes the custom signals for this FirebaseRemoteConfig instance
/// Custom signals are subject to limits on the size of key/value pairs and the total number of signals.
/// Any calls that exceed these limits will be discarded.
/// If a key already exists, the value is overwritten. Setting the value of a custom signal to null un-sets the signal.
/// The signals will be persisted locally on the client.
Future<void> setCustomSignals(Map<String, Object?> customSignals) {
throw UnimplementedError('setCustomSignals() is not implemented');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_web/firebase_core_web.dart';
import 'package:firebase_core_web/firebase_core_web_interop.dart'
as core_interop;
import 'package:firebase_remote_config_web/src/internals.dart';
import 'package:firebase_remote_config_platform_interface/firebase_remote_config_platform_interface.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';

Expand Down Expand Up @@ -185,4 +186,11 @@ class FirebaseRemoteConfigWeb extends FirebaseRemoteConfigPlatform {
Stream<RemoteConfigUpdate> get onConfigUpdated {
throw UnsupportedError('onConfigUpdated is not supported for web');
}

@override
Future<void> setCustomSignals(Map<String, Object?> customSignals) {
return convertWebExceptions(
() => _delegate.setCustomSignals(customSignals),
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2021, the Chromium project authors. Please see the AUTHORS file
// 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 'package:firebase_core/firebase_core.dart';
import 'package:_flutterfire_internals/_flutterfire_internals.dart'
as internals;

/// Will return a [FirebaseException] from a thrown web error.
/// Any other errors will be propagated as normal.
R convertWebExceptions<R>(R Function() cb) {
return internals.guardWebExceptions(
cb,
plugin: 'firebase_remote_config',
codeParser: (code) => code.replaceFirst('remote_config/', ''),
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@ class RemoteConfig
.toJS,
);
}

Future<void> setCustomSignals(Map<String, Object?> customSignals) {
return remote_config_interop
.setCustomSignals(jsObject, customSignals.jsify()! as JSObject)
.toDart;
}
}

ValueSource getSource(String source) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,17 @@ external JSString getString(RemoteConfigJsImpl remoteConfig, JSString key);
@staticInterop
external ValueJsImpl getValue(RemoteConfigJsImpl remoteConfig, JSString key);

// TODO - api to be implemented
@JS()
@staticInterop
external JSPromise isSupported();

@JS()
@staticInterop
external JSPromise setCustomSignals(
RemoteConfigJsImpl remoteConfig,
JSObject customSignals,
);

@JS()
@staticInterop
external void setLogLevel(RemoteConfigJsImpl remoteConfig, JSString logLevel);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ environment:
flutter: '>=3.22.0'

dependencies:
_flutterfire_internals: ^1.3.50
firebase_core: ^3.10.1
firebase_core_web: ^2.18.2
firebase_remote_config_platform_interface: ^1.4.49
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,57 @@ void main() {
expect(FirebaseRemoteConfig.instance.getInt('does-not-exist'), 0);
expect(FirebaseRemoteConfig.instance.getDouble('does-not-exist'), 0.0);
});

group('setCustomSignals()', () {
test('valid signal values; `string`, `number` & `null`', () async {
const signals = <String, Object?>{
'signal1': 'string',
'signal2': 204953,
'signal3': 3.24,
'signal4': null,
};

await FirebaseRemoteConfig.instance.setCustomSignals(signals);
});

test('invalid signal values throws assertion', () async {
const signals = <String, Object?>{
'signal1': true,
};

await expectLater(
() => FirebaseRemoteConfig.instance.setCustomSignals(signals),
throwsA(isA<AssertionError>()),
);

const signals2 = <String, Object?>{
'signal1': [1, 2, 3],
};

await expectLater(
() => FirebaseRemoteConfig.instance.setCustomSignals(signals2),
throwsA(isA<AssertionError>()),
);

const signals3 = <String, Object?>{
'signal1': {'key': 'value'},
};

await expectLater(
() => FirebaseRemoteConfig.instance.setCustomSignals(signals3),
throwsA(isA<AssertionError>()),
);

const signals4 = <String, Object?>{
'signal1': false,
};

await expectLater(
() => FirebaseRemoteConfig.instance.setCustomSignals(signals4),
throwsA(isA<AssertionError>()),
);
});
});
},
);
}
Loading