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

[firebase_core] Add platform interface #1324

Merged
merged 12 commits into from
Nov 14, 2019
Merged
Show file tree
Hide file tree
Changes from 5 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
@@ -1,3 +1,7 @@
## 0.4.1+2
ditman marked this conversation as resolved.
Show resolved Hide resolved

* Update the homepage now that the package structure has changed.

## 0.4.1+1

* Include lifecycle dependency as a compileOnly one on Android to resolve
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ name: firebase_core
description: Flutter plugin for Firebase Core, enabling connecting to multiple
Firebase apps.
author: Flutter Team <flutter-dev@googlegroups.com>
homepage: https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_core
version: 0.4.1+1
homepage: https://github.com/FirebaseExtended/flutterfire/tree/master/packages/firebase_core/firebase_core
version: 0.4.1+2

flutter:
plugin:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 1.0.0

- Initial open-source release.
27 changes: 27 additions & 0 deletions packages/firebase_core/firebase_core_platform_interface/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 changes: 26 additions & 0 deletions packages/firebase_core/firebase_core_platform_interface/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# firebase_core_platform_interface

A common platform interface for the [`firebase_core`][1] plugin.

This interface allows platform-specific implementations of the `firebase_core`
plugin, as well as the plugin itself, to ensure they are supporting the
same interface.

# Usage

To implement a new platform-specific implementation of `firebase_core`, extend
[`FirebaseCorePlatform`][2] with an implementation that performs the
platform-specific behavior, and when you register your plugin, set the default
`FirebaseCorePlatform` by calling
`FirebaseCorePlatform.instance = MyFirebaseCore()`.

# Note on breaking changes

Strongly prefer non-breaking changes (such as adding a method to the interface)
over breaking changes for this package.

See https://flutter.dev/go/platform-interface-breaking-changes for a discussion
on why a less-clean interface is preferable to a breaking change.

[1]: ../firebase_core
[2]: lib/firebase_core_platform_interface.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright 2019 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.

import 'dart:async';

import 'package:meta/meta.dart' show visibleForTesting;

import 'src/firebase_app_data.dart';
import 'src/firebase_options.dart';
import 'src/method_channel_firebase_core.dart';

export 'src/firebase_app_data.dart';
export 'src/firebase_options.dart';
export 'src/method_channel_firebase_core.dart';

/// The interface that implementations of `firebase_core` must extend.
///
/// Platform implementations should extend this class rather than implement it
/// as `firebase_core` does not consider newly added methods to be breaking
/// changes. Extending this class (using `extends`) ensures that the subclass
/// will get the default implementation, while platform implementations that
/// `implements` this interface will be broken by newly added
/// [FirebaseCorePlatform] methods.
abstract class FirebaseCorePlatform {
/// Only mock implementations should set this to `true`.
///
/// Mockito mocks implement this class with `implements` which is forbidden
/// (see class docs). This property provides a backdoor for mocks to skip the
/// verification that the class isn't implemented with `implements`.
@visibleForTesting
bool get isMock => false;

/// The default instance of [FirebaseCorePlatform] to use.
///
/// Platform-specific plugins should override this with their own class
/// that extends [FirebaseCorePlatform] when they register themselves.
///
/// Defaults to [MethodChannelFirebaseCore].
static FirebaseCorePlatform get instance => _instance;

static FirebaseCorePlatform _instance = MethodChannelFirebaseCore();

// TODO(amirh): Extract common platform interface logic.
// https://github.com/flutter/flutter/issues/43368
static set instance(FirebaseCorePlatform instance) {
if (!instance.isMock) {
harryterkelsen marked this conversation as resolved.
Show resolved Hide resolved
try {
instance._verifyProvidesDefaultImplementations();
} on NoSuchMethodError catch (_) {
throw AssertionError(
'Platform interfaces must not be implemented with `implements`');
}
}
_instance = instance;
}

/// This method ensures that [FirebaseCorePlatform] isn't implemented with `implements`.
///
/// See class docs for more details on why using `implements` to implement
/// [FirebaseCorePlatform] is forbidden.
///
/// This private method is called by the [instance] setter, which should fail
/// if the provided instance is a class implemented with `implements`.
void _verifyProvidesDefaultImplementations() {}

/// Returns the data for the Firebase app with the given [name].
///
/// If there is no such app, returns null.
Future<FirebaseAppData> appNamed(String name) {
throw UnimplementedError('appNamed() has not been implemented.');
}

/// Configures the app named [name] with the given [options].
Future<void> configure(String name, FirebaseOptions options) {
throw UnimplementedError('configure() has not been implemented.');
}

/// Returns a list of all extant Firebase app instances.
///
/// If there are no live Firebase apps, returns `null`.
Future<List<FirebaseAppData>> allApps() {
throw UnimplementedError('allApps() has not been implemented.');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2019 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.

import 'package:quiver_hashcode/hashcode.dart';

import 'firebase_options.dart';

/// A data class storing the name and options of a Firebase app.
class FirebaseAppData {
Copy link
Contributor

@collinjackson collinjackson Nov 11, 2019

Choose a reason for hiding this comment

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

This relates to #1392 which @kroikie just landed.

Generally in Flutterfire we try to match the native Firebase APIs as closely as we can while remaining idiomatic to the target platform. There's no equivalent to the FirebaseAppData class in the native Firebase API. There's just FirebaseApp and our Dart version of it exposes a Future<FirebaseOptions> options getter.

The reason why we put an asynchronous options on firebase_core's FirebaseApp is that we wanted the developer to be able to say FirebaseApp.instance and start using that app immediately without calling await.

It seems odd, although not necessarily wrong to have a class FirebaseOptions that matches the naming in the app-facing API exactly and is designed to be exported, but then have another class FirebaseAppData that serves a similar function to FirebaseApp but has a slightly different class behavior and can't be exported. It seems that the main difference is that FirebaseOptions is a pure data class whereas FirebaseApp has some behavior.

It seems like for every class we have the following options. All of them avoid exposing nonstandard classes (FirebaseAppData) to the end developer.

  1. We could write the platform interface class in a way that can be exported and reused (so firebase_core and firebase_core_platform_interface share both the same class). This approach would match what's going on with FirebaseOptions but makes it harder to make breaking changes in firebase_core because they might also break firebase_core_platform_interface.
  2. Use Dart namespaces to disambiguate app-facing classes and platform interface classes, e.g. having a class called FirebaseApp but don't require it to match firebase_core's FirebaseApp. The same could apply to FirebaseOptions. It could be confusing to have two identically named classes that are subtly different, but it makes it clear that both classes refer to the same native SDK concept on different layers. One of them could extend the other without polluting public API with classes that don't have a native SDK equivalent.
  3. We can have the platform interface class names be visually distinguishable from the class name in the the app-facing package (e.g. FirebaseAppData or PlatformFirebaseApp). This might make make the code more readable within the app-facing package because it's obvious that the class is a more primitive representation of an app-facing class. However, it isn't possible to extend the platform class without exposing a platform implementation base class to the end developer.

Right now you're doing Option 1 for FirebaseOptions and Option 3 for FirebaseApp. Starting off with Option 1 and then moving to Option 2 or 3 later is possible, although here it would force the platform interface to use the same asynchronous API for options.

Here's a sketch of what it might look like to do option 3 with FirebaseApp (i.e. PlatformFirebaseApp instead of FirebaseAppData).

export 'firebase_core_platform_implementation.dart' show FirebaseOptions; 

class FirebaseApp {
  static Map<String, FirebaseApp> _apps = <String, FirebaseApp>{};

  /// Retrieves a [FirebaseApp] that was previously configured using [configure].
  ///
  /// If no name is provided, the default is used.
  factory FirebaseApp.instanceFor({ String name }) {
    if (name == null) {
      return FirebaseApp.instance;
    }
    String app = _apps[name];
    assert(app != null);
    return app;
  }

  /// Returns the default (first initialized) instance of the FirebaseApp.
  static final FirebaseApp instance = FirebaseApp(name: defaultAppName);

  @visibleForTesting
  FirebaseApp({ @required String this.name });

  /// The name of this Firebase app.
  final String name;

  /// The options that this app was configured with.
  Future<FirebaseOptions> get options {
    PlatformFirebaseApp platformApp = await FirebaseCorePlatform.instance.appNamed(name);
    return platformApp.options;
  }

  /// Configures the app named [name] with the given [options].
  ///
  /// Returns a previously configured app if there is one.
  /// Reconfiguring an app is not supported.
  static Future<FirebaseApp> configure({
    @required String name,
    @required FirebaseOptions options,
  }) async {
    if (options != null) {
      await FirebaseCorePlatform.instance.configure(name, options);
    }
    PlatformFirebaseApp platformApp = await FirebaseCorePlatform.instance.appNamed(name);
    FirebaseApp app = FirebaseApp._(platformApp);
    _apps[name] = app;
    return app;
  }
}

In the platform interface:

class PlatformFirebaseApp {
  PlatformFirebaseApp(this.name, this.options);

  /// The name of this Firebase app.
  final String name;

  /// The options that this app was configured with.
  final FirebaseOptions options;

  @override
  bool operator ==(dynamic other) {
    if (identical(this, other)) return true;
    if (other is! FirebaseAppData) return false;
    return other.name == name && other.options == options;
  }

  @override
  int get hashCode => hash2(name, options);

  @override
  String toString() => '$FirebaseApp($name)';
}

abstract class FirebaseCorePlatform {
  /// Returns the data for the Firebase app with the given [name].
  ///
  /// If there is no such app, returns null.
  Future<FirebaseApp> appNamed(String name);

  /// Configures the app named [name] with the given [options].
  Future<FirebaseApp> configure(String name, FirebaseOptions options);
}

FirebaseAppData(this.name, this.options);

/// The name of this Firebase app.
final String name;

/// The options that this app was configured with.
final FirebaseOptions options;

@override
bool operator ==(dynamic other) {
if (identical(this, other)) return true;
if (other is! FirebaseAppData) return false;
return other.name == name && other.options == options;
}

@override
int get hashCode => hash2(name, options);
ditman marked this conversation as resolved.
Show resolved Hide resolved

@override
String toString() => '$FirebaseAppData($name)';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright 2019 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.

import 'package:meta/meta.dart' show required;
import 'package:quiver_hashcode/hashcode.dart';

/// The options used to configure a Firebase app.
class FirebaseOptions {
const FirebaseOptions({
this.apiKey,
this.bundleID,
this.clientID,
this.trackingID,
this.gcmSenderID,
this.projectID,
this.androidClientID,
@required this.googleAppID,
this.databaseURL,
this.deepLinkURLScheme,
this.storageBucket,
}) : assert(googleAppID != null);

FirebaseOptions.from(Map<dynamic, dynamic> map)
: apiKey = map['APIKey'],
bundleID = map['bundleID'],
clientID = map['clientID'],
trackingID = map['trackingID'],
gcmSenderID = map['GCMSenderID'],
projectID = map['projectID'],
androidClientID = map['androidClientID'],
googleAppID = map['googleAppID'],
databaseURL = map['databaseURL'],
deepLinkURLScheme = map['deepLinkURLScheme'],
storageBucket = map['storageBucket'] {
assert(googleAppID != null);
}

/// An API key used for authenticating requests from your app, e.g.
/// "AIzaSyDdVgKwhZl0sTTTLZ7iTmt1r3N2cJLnaDk", used to identify your app to
/// Google servers.
///
/// This property is required on Android.
final String apiKey;

/// The iOS bundle ID for the application. Defaults to
/// `[[NSBundle mainBundle] bundleID]` when not set manually or in a plist.
///
/// This property is used on iOS only.
final String bundleID;

/// The OAuth2 client ID for iOS application used to authenticate Google
/// users, for example "12345.apps.googleusercontent.com", used for signing in
/// with Google.
///
/// This property is used on iOS only.
final String clientID;

/// The tracking ID for Google Analytics, e.g. "UA-12345678-1", used to
/// configure Google Analytics.
///
/// This property is used on iOS only.
final String trackingID;

/// The Project Number from the Google Developer’s console, for example
/// "012345678901", used to configure Google Cloud Messaging.
///
/// This property is required on iOS.
final String gcmSenderID;

/// The Project ID from the Firebase console, for example "abc-xyz-123."
final String projectID;

/// The Android client ID, for example "12345.apps.googleusercontent.com."
///
/// This property is used on iOS only.
final String androidClientID;

/// The Google App ID that is used to uniquely identify an instance of an app.
///
/// This property cannot be `null`.
final String googleAppID;

/// The database root URL, e.g. "http://abc-xyz-123.firebaseio.com."
///
/// This property should be set for apps that use Firebase Database.
final String databaseURL;

/// The URL scheme used to set up Durable Deep Link service.
///
/// This property is used on iOS only.
final String deepLinkURLScheme;

/// The Google Cloud Storage bucket name, e.g.
/// "abc-xyz-123.storage.firebase.com."
final String storageBucket;

Map<String, String> get asMap {
return <String, String>{
'APIKey': apiKey,
'bundleID': bundleID,
'clientID': clientID,
'trackingID': trackingID,
'GCMSenderID': gcmSenderID,
'projectID': projectID,
'androidClientID': androidClientID,
'googleAppID': googleAppID,
'databaseURL': databaseURL,
'deepLinkURLScheme': deepLinkURLScheme,
'storageBucket': storageBucket,
};
}

@override
bool operator ==(dynamic other) {
harryterkelsen marked this conversation as resolved.
Show resolved Hide resolved
if (identical(this, other)) return true;
if (other is! FirebaseOptions) return false;
return other.apiKey == apiKey &&
other.bundleID == bundleID &&
other.clientID == clientID &&
other.trackingID == trackingID &&
other.gcmSenderID == gcmSenderID &&
other.projectID == projectID &&
other.androidClientID == androidClientID &&
other.googleAppID == googleAppID &&
other.databaseURL == databaseURL &&
other.deepLinkURLScheme == deepLinkURLScheme &&
other.storageBucket == storageBucket;
}

@override
int get hashCode {
return hashObjects(
<String>[
apiKey,
bundleID,
clientID,
trackingID,
gcmSenderID,
projectID,
androidClientID,
googleAppID,
databaseURL,
deepLinkURLScheme,
storageBucket,
],
);
}

@override
String toString() => asMap.toString();
}
Loading