Skip to content

Commit

Permalink
chore: enable discarded_futures lint
Browse files Browse the repository at this point in the history
  • Loading branch information
nico-famedly committed Nov 2, 2023
1 parent 56386a4 commit 045e5fc
Show file tree
Hide file tree
Showing 26 changed files with 115 additions and 90 deletions.
2 changes: 2 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ linter:
always_use_package_imports: true
avoid_bool_literals_in_conditional_expressions: true
avoid_print: true
cancel_subscriptions: true
discarded_futures: true
non_constant_identifier_names: false # seems to wrongly diagnose static const variables
prefer_final_in_for_each: true
prefer_final_locals: true
Expand Down
14 changes: 4 additions & 10 deletions lib/encryption/encryption.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,12 @@ class Encryption {

void handleDeviceOneTimeKeysCount(
Map<String, int>? countJson, List<String>? unusedFallbackKeyTypes) {
runInRoot(() => olmManager.handleDeviceOneTimeKeysCount(
runInRoot(() async => olmManager.handleDeviceOneTimeKeysCount(
countJson, unusedFallbackKeyTypes));
}

void onSync() {
// ignore: discarded_futures
keyVerificationManager.cleanup();
}

Expand All @@ -118,30 +119,25 @@ class Encryption {
.contains(event.type)) {
// "just" room key request things. We don't need these asap, so we handle
// them in the background
// ignore: unawaited_futures
runInRoot(() => keyManager.handleToDeviceEvent(event));
}
if (event.type == EventTypes.Dummy) {
// the previous device just had to create a new olm session, due to olm session
// corruption. We want to try to send it the last message we just sent it, if possible
// ignore: unawaited_futures
runInRoot(() => olmManager.handleToDeviceEvent(event));
}
if (event.type.startsWith('m.key.verification.')) {
// some key verification event. No need to handle it now, we can easily
// do this in the background

// ignore: unawaited_futures
runInRoot(() => keyVerificationManager.handleToDeviceEvent(event));
}
if (event.type.startsWith('m.secret.')) {
// some ssss thing. We can do this in the background
// ignore: unawaited_futures
runInRoot(() => ssss.handleToDeviceEvent(event));
}
if (event.sender == client.userID) {
// maybe we need to re-try SSSS secrets
// ignore: unawaited_futures
runInRoot(() => ssss.periodicallyRequestMissingCache());
}
}
Expand All @@ -157,14 +153,11 @@ class Encryption {
update.content['content']['msgtype']
.startsWith('m.key.verification.'))) {
// "just" key verification, no need to do this in sync

// ignore: unawaited_futures
runInRoot(() => keyVerificationManager.handleEventUpdate(update));
}
if (update.content['sender'] == client.userID &&
update.content['unsigned']?['transaction_id'] == null) {
// maybe we need to re-try SSSS secrets
// ignore: unawaited_futures
runInRoot(() => ssss.periodicallyRequestMissingCache());
}
}
Expand Down Expand Up @@ -239,6 +232,7 @@ class Encryption {
// the entry should always exist. In the case it doesn't, the following
// line *could* throw an error. As that is a future, though, and we call
// it un-awaited here, nothing happens, which is exactly the result we want
// ignore: discarded_futures
client.database?.updateInboundGroupSessionIndexes(
json.encode(inboundGroupSession.indexes), roomId, sessionId);
}
Expand All @@ -252,7 +246,7 @@ class Encryption {
?.session_id() ??
'') ==
content.sessionId) {
runInRoot(() =>
runInRoot(() async =>
keyManager.clearOrUseOutboundGroupSession(roomId, wipe: true));
}
if (canRequestSession) {
Expand Down
8 changes: 5 additions & 3 deletions lib/encryption/key_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,8 @@ class KeyManager {
!client.isUnknownSession) {
// do e2ee recovery
_requestedSessionIds.add(requestIdent);
runInRoot(() => request(

runInRoot(() async => request(
room,
sessionId,
senderKey,
Expand Down Expand Up @@ -775,8 +776,8 @@ class KeyManager {
Future<void>? _uploadingFuture;

void startAutoUploadKeys() {
_uploadKeysOnSync = encryption.client.onSync.stream
.listen((_) => uploadInboundGroupSessions(skipIfInProgress: true));
_uploadKeysOnSync = encryption.client.onSync.stream.listen(
(_) async => uploadInboundGroupSessions(skipIfInProgress: true));
}

/// This task should be performed after sync processing but should not block
Expand Down Expand Up @@ -1064,6 +1065,7 @@ class KeyManager {
StreamSubscription<SyncUpdate>? _uploadKeysOnSync;

void dispose() {
// ignore: discarded_futures
_uploadKeysOnSync?.cancel();
for (final sess in _outboundGroupSessions.values) {
sess.dispose();
Expand Down
70 changes: 39 additions & 31 deletions lib/encryption/olm_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -396,20 +396,24 @@ class OlmManager {
final device = client.userDeviceKeys[event.sender]?.deviceKeys.values
.firstWhereOrNull((d) => d.curve25519Key == senderKey);
final existingSessions = olmSessions[senderKey];
Future<void> updateSessionUsage([OlmSession? session]) =>
runInRoot(() async {
if (session != null) {
session.lastReceived = DateTime.now();
await storeOlmSession(session);
}
if (device != null) {
device.lastActive = DateTime.now();
await encryption.olmDatabase?.setLastActiveUserDeviceKey(
device.lastActive.millisecondsSinceEpoch,
device.userId,
device.deviceId!);
}
});
Future<void> updateSessionUsage([OlmSession? session]) async {
try {
if (session != null) {
session.lastReceived = DateTime.now();
await storeOlmSession(session);
}
if (device != null) {
device.lastActive = DateTime.now();
await encryption.olmDatabase?.setLastActiveUserDeviceKey(
device.lastActive.millisecondsSinceEpoch,
device.userId,
device.deviceId!);
}
} catch (e, s) {
Logs().e('Error while updating olm session timestamp', e, s);
}
}

if (existingSessions != null) {
for (final session in existingSessions) {
if (session.session == null) {
Expand Down Expand Up @@ -446,14 +450,16 @@ class OlmManager {
newSession.create_inbound_from(_olmAccount!, senderKey, body);
_olmAccount!.remove_one_time_keys(newSession);
await encryption.olmDatabase?.updateClientKeys(pickledOlmAccount!);

plaintext = newSession.decrypt(type, body);
await runInRoot(() => storeOlmSession(OlmSession(
key: client.userID!,
identityKey: senderKey,
sessionId: newSession.session_id(),
session: newSession,
lastReceived: DateTime.now(),
)));

await storeOlmSession(OlmSession(
key: client.userID!,
identityKey: senderKey,
sessionId: newSession.session_id(),
session: newSession,
lastReceived: DateTime.now(),
));
await updateSessionUsage();
} catch (e) {
newSession.free();
Expand Down Expand Up @@ -570,8 +576,6 @@ class OlmManager {
return _decryptToDeviceEvent(event);
} catch (_) {
// okay, the thing errored while decrypting. It is safe to assume that the olm session is corrupt and we should generate a new one

// ignore: unawaited_futures
runInRoot(() => restoreOlmSession(event.senderId, senderKey));

rethrow;
Expand Down Expand Up @@ -658,14 +662,18 @@ class OlmManager {
final encryptResult = sess.first.session!.encrypt(json.encode(fullPayload));
await storeOlmSession(sess.first);
if (encryption.olmDatabase != null) {
await runInRoot(
() async => encryption.olmDatabase?.setLastSentMessageUserDeviceKey(
json.encode({
'type': type,
'content': payload,
}),
device.userId,
device.deviceId!));
try {
await encryption.olmDatabase?.setLastSentMessageUserDeviceKey(
json.encode({
'type': type,
'content': payload,
}),
device.userId,
device.deviceId!);
} catch (e, s) {
// we can ignore this error, since it would just make us use a different olm session possibly
Logs().w('Error while updating olm usage timestamp', e, s);
}
}
final encryptedBody = <String, dynamic>{
'algorithm': AlgorithmTypes.olmV1Curve25519AesSha2,
Expand Down
7 changes: 5 additions & 2 deletions lib/encryption/ssss.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import 'package:matrix/encryption/utils/ssss_cache.dart';
import 'package:matrix/matrix.dart';
import 'package:matrix/src/utils/cached_stream_controller.dart';
import 'package:matrix/src/utils/crypto/crypto.dart' as uc;
import 'package:matrix/src/utils/run_in_root.dart';

const cacheTypes = <String>{
EventTypes.CrossSigningSelfSigning,
Expand Down Expand Up @@ -722,7 +721,11 @@ class OpenSSSS {
throw InvalidPassphraseException('Inalid key');
}
if (postUnlock) {
await runInRoot(() => _postUnlock());
try {
await _postUnlock();
} catch (e, s) {
Logs().e('Error during post unlock', e, s);
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion lib/encryption/utils/base64_unpadded.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'dart:typed_data';

/// decodes base64
///
/// Dart's native [base64.decode] requires a padded base64 input String.
/// Dart's native [base64.decode()] requires a padded base64 input String.
/// This function allows unpadded base64 too.
///
/// See: https://github.com/dart-lang/sdk/issues/39510
Expand Down
4 changes: 2 additions & 2 deletions lib/src/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1635,7 +1635,7 @@ class Client extends MatrixApi {
set backgroundSync(bool enabled) {
_backgroundSync = enabled;
if (_backgroundSync) {
_sync();
runInRoot(() async => _sync());
}
}

Expand Down Expand Up @@ -2228,7 +2228,7 @@ class Client extends MatrixApi {
requestHistoryOnLimitedTimeline) {
Logs().v(
'Limited timeline for ${rooms[roomIndex].id} request history now');
unawaited(runInRoot(rooms[roomIndex].requestHistory));
runInRoot(rooms[roomIndex].requestHistory);
}
}
return room;
Expand Down
2 changes: 2 additions & 0 deletions lib/src/event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ class Event extends MatrixEvent {
final json = toJson();
json['unsigned'] ??= <String, dynamic>{};
json['unsigned'][messageSendingStatusKey] = EventStatus.error.intValue;
// ignore: discarded_futures
room.client.handleSync(
SyncUpdate(
nextBatch: '',
Expand All @@ -154,6 +155,7 @@ class Event extends MatrixEvent {
MessageTypes.File,
}.contains(messageType) &&
!room.sendingFilePlaceholders.containsKey(eventId)) {
// ignore: discarded_futures
remove();
}
}
Expand Down
1 change: 1 addition & 0 deletions lib/src/room.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1626,6 +1626,7 @@ class Room {
return user.asUser;
} else {
if (mxID.isValidMatrixId) {
// ignore: discarded_futures
requestUser(
mxID,
ignoreErrors: true,
Expand Down
3 changes: 3 additions & 0 deletions lib/src/timeline.dart
Original file line number Diff line number Diff line change
Expand Up @@ -300,8 +300,11 @@ class Timeline {

/// Don't forget to call this before you dismiss this object!
void cancelSubscriptions() {
// ignore: discarded_futures
sub?.cancel();
// ignore: discarded_futures
roomSub?.cancel();
// ignore: discarded_futures
sessionIdReceivedSub?.cancel();
}

Expand Down
4 changes: 2 additions & 2 deletions lib/src/utils/device_keys_list.dart
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ class DeviceKeys extends SignableKey {
lastActive = DateTime.fromMillisecondsSinceEpoch(0);
}

KeyVerification startVerification() {
Future<KeyVerification> startVerification() async {
if (!isValid) {
throw Exception('setVerification called on invalid key');
}
Expand All @@ -516,7 +516,7 @@ class DeviceKeys extends SignableKey {
final request = KeyVerification(
encryption: encryption, userId: userId, deviceId: deviceId!);

request.start();
await request.start();
encryption.keyVerificationManager.addRequest(request);
return request;
}
Expand Down
5 changes: 2 additions & 3 deletions lib/src/utils/native_implementations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,9 @@ abstract class NativeImplementations {
bool retryInDummy = false,
});

@override

/// this implementation will catch any non-implemented method
dynamic noSuchMethod(Invocation invocation) {
@override
dynamic noSuchMethod(Invocation invocation) async {
final dynamic argument = invocation.positionalArguments.single;
final memberName = invocation.memberName.toString().split('"')[1];

Expand Down
8 changes: 4 additions & 4 deletions lib/src/utils/run_in_root.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ import 'dart:async';

import 'package:matrix/matrix.dart';

Future<T?> runInRoot<T>(FutureOr<T> Function() fn) async {
return await Zone.root.run(() async {
void runInRoot<T>(FutureOr<T> Function() fn) {
// ignore: discarded_futures
Zone.root.run(() async {
try {
return await fn();
await fn();
} catch (e, s) {
Logs().e('Error thrown in root zone', e, s);
}
return null;
});
}
1 change: 1 addition & 0 deletions lib/src/utils/uia_request.dart
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class UiaRequest<T> {
}

UiaRequest({this.onUpdate, required this.request}) {
// ignore: discarded_futures
_run();
}

Expand Down
12 changes: 5 additions & 7 deletions lib/src/utils/web_worker/native_implementations_web_worker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class NativeImplementationsWebWorker extends NativeImplementations {
return completer.future.timeout(timeout);
}

void _handleIncomingMessage(MessageEvent event) {
Future<void> _handleIncomingMessage(MessageEvent event) async {
final data = event.data;
// don't forget handling errors of our second thread...
if (data['label'] == 'stacktrace') {
Expand All @@ -46,12 +46,10 @@ class NativeImplementationsWebWorker extends NativeImplementations {

final error = event.data['error']!;

Future.value(
onStackTrace.call(event.data['stacktrace'] as String),
).then(
(stackTrace) => completer?.completeError(
WebWorkerError(error: error, stackTrace: stackTrace),
),
final stackTrace =
await onStackTrace.call(event.data['stacktrace'] as String);
completer?.completeError(
WebWorkerError(error: error, stackTrace: stackTrace),
);
} else {
final response = WebWorkerData.fromJson(event.data);
Expand Down
Loading

0 comments on commit 045e5fc

Please sign in to comment.