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

fix(notifications): configure call hangs on Flutter app hot restart #3013

Merged
merged 2 commits into from
May 8, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -23,8 +23,4 @@ class AmplifyLifecycleObserver : DefaultLifecycleObserver {
isAppLaunch = false
super.onResume(owner)
}
override fun onCreate(owner: LifecycleOwner) {
refreshToken()
super.onCreate(owner)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ class AmplifyPushNotificationsPlugin(
return
}

override fun requestInitialToken() {
refreshToken()
}

override fun getPermissionStatus(result: PushNotificationsHostApiBindings.Result<PushNotificationsHostApiBindings.GetPermissionStatusResult>) {
val resultBuilder = PushNotificationsHostApiBindings.GetPermissionStatusResult.Builder()
val permission = PushNotificationPermission(applicationContext)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Autogenerated from Pigeon (v9.2.4), do not edit directly.
// Autogenerated from Pigeon (v9.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon

package com.amazonaws.amplify.amplify_push_notifications;
Expand Down Expand Up @@ -326,6 +326,8 @@ protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) {
/** Generated interface from Pigeon that represents a handler of messages from Flutter. */
public interface PushNotificationsHostApi {

void requestInitialToken();

void getPermissionStatus(@NonNull Result<GetPermissionStatusResult> result);

void requestPermissions(@NonNull PermissionsOptions withPermissionOptions, @NonNull Result<Boolean> result);
Expand All @@ -346,6 +348,28 @@ public interface PushNotificationsHostApi {
}
/**Sets up an instance of `PushNotificationsHostApi` to handle messages through the `binaryMessenger`. */
static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable PushNotificationsHostApi api) {
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
binaryMessenger, "dev.flutter.pigeon.PushNotificationsHostApi.requestInitialToken", getCodec());
if (api != null) {
channel.setMessageHandler(
(message, reply) -> {
ArrayList<Object> wrapped = new ArrayList<Object>();
try {
api.requestInitialToken();
wrapped.add(0, null);
}
catch (Throwable exception) {
ArrayList<Object> wrappedError = wrapError(exception);
wrapped = wrappedError;
}
reply.reply(wrapped);
});
} else {
channel.setMessageHandler(null);
}
}
{
BasicMessageChannel<Object> channel =
new BasicMessageChannel<>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ public class AmplifyPushNotificationsPlugin: NSObject, FlutterPlugin, PushNotifi
registrar.addApplicationDelegate(pluginInstance)
}

public func requestInitialTokenWithError(_ error: AutoreleasingUnsafeMutablePointer<FlutterError?>) {
UIApplication.shared.registerForRemoteNotifications()
}

public func getPermissionStatus(completion: @escaping (GetPermissionStatusResult?, FlutterError?) -> Void) {
Task {
switch await AUNotificationPermissions.status {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Autogenerated from Pigeon (v9.2.4), do not edit directly.
// Autogenerated from Pigeon (v9.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon

#import <Foundation/Foundation.h>
Expand Down Expand Up @@ -54,6 +54,7 @@ NSObject<FlutterMessageCodec> *PushNotificationsFlutterApiGetCodec(void);
NSObject<FlutterMessageCodec> *PushNotificationsHostApiGetCodec(void);

@protocol PushNotificationsHostApi
- (void)requestInitialTokenWithError:(FlutterError *_Nullable *_Nonnull)error;
- (void)getPermissionStatusWithCompletion:(void (^)(GetPermissionStatusResult *_Nullable, FlutterError *_Nullable))completion;
- (void)requestPermissionsWithPermissionOptions:(PermissionsOptions *)withPermissionOptions completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion;
- (nullable NSDictionary<id, id> *)getLaunchNotificationWithError:(FlutterError *_Nullable *_Nonnull)error;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Autogenerated from Pigeon (v9.2.4), do not edit directly.
// Autogenerated from Pigeon (v9.2.5), do not edit directly.
// See also: https://pub.dev/packages/pigeon

#import "PushNotificationsNativePlugin.h"
Expand Down Expand Up @@ -229,6 +229,23 @@ - (FlutterStandardReader *)readerWithData:(NSData *)data {
}

void PushNotificationsHostApiSetup(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PushNotificationsHostApi> *api) {
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
initWithName:@"dev.flutter.pigeon.PushNotificationsHostApi.requestInitialToken"
binaryMessenger:binaryMessenger
codec:PushNotificationsHostApiGetCodec()];
if (api) {
NSCAssert([api respondsToSelector:@selector(requestInitialTokenWithError:)], @"PushNotificationsHostApi api (%@) doesn't respond to @selector(requestInitialTokenWithError:)", api);
[channel setMessageHandler:^(id _Nullable message, FlutterReply callback) {
FlutterError *error;
[api requestInitialTokenWithError:&error];
callback(wrapResult(nil, error));
}];
} else {
[channel setMessageHandler:nil];
}
}
{
FlutterBasicMessageChannel *channel =
[[FlutterBasicMessageChannel alloc]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,14 +335,26 @@ abstract class AmplifyPushNotifications

Future<void> _registerDeviceWhenConfigure() async {
late String deviceToken;

try {
deviceToken = await _bufferedTokenStream.peek;
await _hostApi.requestInitialToken();
deviceToken =
await _bufferedTokenStream.peek.timeout(const Duration(seconds: 2));
Copy link
Contributor

Choose a reason for hiding this comment

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

Is 2 seconds long enough? Can we make it 5 or 10 to be safe?

Copy link
Member Author

Choose a reason for hiding this comment

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

On iOS and Android token generation is client behavior, and doesn't require network round trip... it should be quick. But can increase the timeout surely to avoid surprises, as this timeout is for catching potential error without increasing latency for normal use cases. Will update to 5.

Copy link
Contributor

Choose a reason for hiding this comment

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

Makes sense. Thanks!

} on PlatformException catch (error) {
// the error mostly like is the App doesn't have corresponding
// capability to request a push notification device token
throw PushNotificationException(
'Error occurred awaiting for device token',
recoverySuggestion: 'Please review the underlying exception',
'Error occurred awaiting for device token.',
recoverySuggestion: 'Review the underlying exception.',
underlyingException: error,
);
} on TimeoutException catch (error) {
throw PushNotificationException(
'Timed out awaiting for device token.',
recoverySuggestion:
'This may happen when the native apps have not been correctly configured'
' for push notifications, review push notification configurations'
' of the native iOS and Android apps of your Flutter project.',
underlyingException: error,
);
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ abstract class PushNotificationsFlutterApi {

@HostApi()
abstract class PushNotificationsHostApi {
void requestInitialToken();

@async
GetPermissionStatusResult getPermissionStatus();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import 'dart:async';
import 'dart:convert';

import 'package:amplify_core/amplify_core.dart';
Expand Down Expand Up @@ -99,6 +100,7 @@ void main() {
config: config,
);

verify(mockPushNotificationsHostApi.requestInitialToken()).called(1);
verify(
mockServiceProviderClient.recordNotificationEvent(
eventType: PinpointEventType.notificationOpened,
Expand All @@ -118,6 +120,8 @@ void main() {
authProviderRepo: authProviderRepo,
config: config,
);

verify(mockPushNotificationsHostApi.requestInitialToken()).called(1);
verify(mockServiceProviderClient.registerDevice('123')).called(1);

void tokenHandler(String token) {
Expand Down Expand Up @@ -264,6 +268,23 @@ void main() {
},
);
});

test('configure should fail if timed out awaiting for device token',
() async {
expect(
plugin.configure(
authProviderRepo: authProviderRepo,
config: config,
),
throwsA(
isA<PushNotificationException>().having(
(o) => o.underlyingException,
'underlyingException',
isA<TimeoutException>(),
),
),
);
});
});
test('should fail configure when registering device is unsuccessful',
() async {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ class MockPushNotificationsHostApi extends _i1.Mock
_i1.throwOnMissingStub(this);
}

@override
_i5.Future<void> requestInitialToken() => (super.noSuchMethod(
Invocation.method(
#requestInitialToken,
[],
),
returnValue: _i5.Future<void>.value(),
returnValueForMissingStub: _i5.Future<void>.value(),
) as _i5.Future<void>);
@override
_i5.Future<_i2.GetPermissionStatusResult> getPermissionStatus() =>
(super.noSuchMethod(
Expand Down