Skip to content
This repository was archived by the owner on Mar 11, 2025. It is now read-only.

Commit 9902cdd

Browse files
Fix: "Ops, it should perform configure connection first"
1 parent 8e93b52 commit 9902cdd

File tree

5 files changed

+80
-73
lines changed

5 files changed

+80
-73
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ pubspec.yaml:
8484
sdk: flutter
8585
8686
# Add this line:
87-
askless: ^3.0.0
87+
askless: ^3.0.1
8888

8989
**5 -** Import the package
9090

lib/constants.dart

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ const REQUEST_PREFIX = 'REQ-';
1414
const LISTEN_PREFIX = 'LIS-';
1515

1616
// TODO onupdate:
17-
const CLIENT_LIBRARY_VERSION_NAME = '3.0.0';
18-
const CLIENT_LIBRARY_VERSION_CODE = 4;
17+
const CLIENT_LIBRARY_VERSION_NAME = '3.0.1';
18+
const CLIENT_LIBRARY_VERSION_CODE = 5;
1919

20-
// TODO onupdate: CHECK README (# Add this line: askless: ^3.0.0)
20+
// TODO onupdate: CHECK README (# Add this line: askless: ^3.0.1)
2121

2222
// TODO onupdate: add changelog

lib/domain/services/connection_service.dart

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ class ConnectionService {
113113
getIt.get<SendPingTask>().changeInterval(connectionConfiguration.intervalInMsClientPing);
114114
getIt.get<ReconnectWhenDidNotReceivePongFromServerTask>().changeInterval(connectionConfiguration.reconnectClientAfterMillisecondsWithoutServerPong);
115115

116-
print ("------------------- _configureConnection ------------------");
116+
logger ("configureConnection ok");
117117
notifyConnectionChanged(ConnectionStatus.connected);
118118

119119
Future.delayed(const Duration(seconds: 1), (){
@@ -172,7 +172,7 @@ class ConnectionService {
172172
}
173173

174174
Stream<ConnectionDetails> streamConnectionChanges({bool immediately = false}) {
175-
if (immediately) {
175+
if (immediately) {
176176
Future.delayed(const Duration(milliseconds: 50), () {
177177
_connectionWithServerChangesStreamController.add(
178178
ConnectionDetails(_connectionStatus, disconnectionReason));
@@ -183,6 +183,9 @@ class ConnectionService {
183183

184184
//Não pode ser acessado de fora do package:
185185
void notifyConnectionChanged(ConnectionStatus conn, {DisconnectionReason ? disconnectionReason}) async {
186+
logger("notifyConnectionChanged: ${conn.toString()}");
187+
188+
assert(conn != ConnectionStatus.connected || connectionConfiguration.isFromServer, "\"connect\" status is only when connectionConfiguration is received from server");
186189
if (conn == _connectionStatus) {
187190
return;
188191
}
@@ -218,4 +221,4 @@ class ConnectionService {
218221
_onConnectionWithServerChangeListenersBeforeOthersListeners.remove(listener);
219222
}
220223

221-
}
224+
}

lib/domain/services/requests_service.dart

Lines changed: 69 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class RequestsService {
3434
List.from(_pendingRequestsList.where((req) => whereRequestType?.toString().isNotEmpty != true || req.data.requestType == whereRequestType))
3535
.forEach((req) {
3636
// _lockPendingRequestsList.synchronized(() async {
37-
_pendingRequestsList.remove(req);
37+
_pendingRequestsList.remove(req);
3838
// });
3939
});
4040
}
@@ -46,22 +46,22 @@ class RequestsService {
4646

4747
void notifyThatHasBeenReceivedServerResponse(InternalAsklessResponseEntity response) {
4848
// _lockPendingRequestsList.synchronized(() async {
49-
final req = _pendingRequestsList.firstWhereOrNull((p) => p.data.clientRequestId == response.clientRequestId,);
50-
if (req != null) {
51-
logger("${req.data.getRoute() ?? ''}: response received!: ${response.success} ${response.error?.code}");
52-
req.onResponse(response);
53-
_pendingRequestsList.remove(req);
54-
} else {
55-
logger(response.clientRequestId.toString());
56-
logger("Response received, but did nothing, probably because the request timed out before. clientRequestId: ${response.clientRequestId}", level: Level.debug);
57-
}
49+
final req = _pendingRequestsList.firstWhereOrNull((p) => p.data.clientRequestId == response.clientRequestId,);
50+
if (req != null) {
51+
logger("${req.data.getRoute() ?? ''}: response received!: ${response.success} ${response.error?.code}");
52+
req.onResponse(response);
53+
_pendingRequestsList.remove(req);
54+
} else {
55+
logger(response.clientRequestId.toString());
56+
logger("Response received, but did nothing, probably because the request timed out before. clientRequestId: ${response.clientRequestId}", level: Level.debug);
57+
}
5858
// });
5959
}
6060

6161
void setAsReceivedPendingMessageThatServerShouldReceive(String clientRequestId) {
6262
// _lockPendingRequestsList.synchronized(() async {
63-
final pending = _pendingRequestsList.firstWhereOrNull((p) => p.data.clientRequestId == clientRequestId,);
64-
pending?.serverReceived = true;
63+
final pending = _pendingRequestsList.firstWhereOrNull((p) => p.data.clientRequestId == clientRequestId,);
64+
pending?.serverReceived = true;
6565
// });
6666
}
6767

@@ -85,62 +85,63 @@ class RequestsService {
8585
data.clientRequestId ??= '${REQUEST_PREFIX}_${randomAlphaNumeric(28)}';
8686

8787
// ignore: prefer_function_declarations_over_variables
88-
final sendAgainWhenConnected = (ConnectionDetails connection) async {
88+
final sendWhenConnected = (ConnectionDetails connection) async {
8989
if (connection.status == ConnectionStatus.connected) {
9090
if (isAfterAuthentication) {
9191
await getIt.get<AuthenticateService>().waitForAuthentication(neverTimeout: false, isPersevere: () => false);
9292
}
93-
logger("sending AGAIN because is connected");
93+
logger('Sending data to server...', level: Level.debug,);
9494
ws.sinkAdd(map: data);
9595
}
9696
};
9797

9898
final _Request request = _Request(data, (response) {
99+
getIt.get<ConnectionService>().removeOnConnectionChange(sendWhenConnected);
99100
if (!completer.isCompleted){
100-
getIt.get<ConnectionService>().removeOnConnectionChange(sendAgainWhenConnected);
101101
completer.complete(response);
102102
}
103103
});
104104

105-
getIt.get<ConnectionService>().addOnConnectionChangeListener(sendAgainWhenConnected, immediately: false);
105+
getIt.get<ConnectionService>().addOnConnectionChangeListener(sendWhenConnected, immediately: request.data.requestType != RequestType.CONFIGURE_CONNECTION, beforeOthersListeners: data.requestType == RequestType.CONFIGURE_CONNECTION || data.requestType == RequestType.AUTHENTICATE);
106106

107107
if (neverTimeout == false && connectionConfiguration.requestTimeoutInMs > 0) {
108108
Future.delayed(Duration(milliseconds: connectionConfiguration.requestTimeoutInMs), () {
109109
// _lockPendingRequestsList.synchronized(() async {
110-
final remove = _pendingRequestsList.firstWhereOrNull((p) => p.data.clientRequestId == request.data.clientRequestId,);
111-
if (remove != null) {
112-
_pendingRequestsList.remove(remove);
113-
request.onResponse(InternalAsklessResponseEntity(
114-
clientRequestId: data.clientRequestId!,
115-
error: AsklessError(code: AsklessErrorCode.noConnection, description: 'Request timed out')
116-
));
117-
logger('Your request (${data.requestType}) \"${data.getRoute() ?? ''}\" timed out, check if: \n\t1) Your server configuration is serving on ${serverUrl}\n\t2) Your device has connection with internet\n\t3) Your API route implementation calls context.success or context.error methods', level: Level.error);
118-
}
119-
});
110+
final remove = _pendingRequestsList.firstWhereOrNull((p) => p.data.clientRequestId == request.data.clientRequestId,);
111+
if (remove != null) {
112+
_pendingRequestsList.remove(remove);
113+
request.onResponse(InternalAsklessResponseEntity(
114+
clientRequestId: data.clientRequestId!,
115+
error: AsklessError(code: AsklessErrorCode.noConnection, description: 'Request timed out')
116+
));
117+
logger('Your request (${data.requestType}) \"${data.getRoute() ?? ''}\" timed out, check if: \n\t1) Your server configuration is serving on ${serverUrl}\n\t2) Your device has connection with internet\n\t3) Your API route implementation calls context.success or context.error methods', level: Level.error);
118+
}
119+
});
120120
// });
121121
}
122122

123123

124124
// await _lockPendingRequestsList.synchronized(() async {
125-
if (ws.isReady == true){
125+
if (ws.isReady == true){
126+
await _addAsPending(request);
127+
} else {
128+
if (data.waitUntilGetServerConnection) {
126129
await _addAsPending(request);
130+
logger('Waiting connection to send message', level: Level.debug);
127131
} else {
128-
if (data.waitUntilGetServerConnection) {
129-
await _addAsPending(request);
130-
logger('Waiting connection to send message', level: Level.debug);
131-
} else {
132-
logger('You can\'t send this message while not connected', level: Level.debug);
133-
request.onResponse(InternalAsklessResponseEntity(
134-
clientRequestId: data.clientRequestId!,
135-
error: AsklessError(description: 'Maybe de device has no internet or the server is offline', code: 'AsklessErrorCode.noConnection')
136-
)
137-
);
138-
}
132+
logger('You can\'t send this message while not connected', level: Level.debug);
133+
request.onResponse(InternalAsklessResponseEntity(
134+
clientRequestId: data.clientRequestId!,
135+
error: AsklessError(description: 'Maybe de device has no internet or the server is offline', code: 'AsklessErrorCode.noConnection')
136+
)
137+
);
139138
}
140-
// });
141-
//In the end:
142-
logger('Sending data to server...', level: Level.debug,);
143-
ws.sinkAdd(map: data);
139+
}
140+
141+
if (request.data.requestType == RequestType.CONFIGURE_CONNECTION) {
142+
logger('Sending data to server...', level: Level.debug,);
143+
ws.sinkAdd(map: data);
144+
}
144145

145146
final response = await completer.future;
146147
if (ifRequiresAuthenticationWaitForIt && response.error?.code == AsklessErrorCode.pendingAuthentication) {
@@ -172,28 +173,31 @@ class RequestsService {
172173
return response;
173174
}
174175

175-
//A RESPOSTA ESTÁ VINDO ANTES DO addAsPending
176-
177176
Future<void> _addAsPending (_Request request) async {
178-
//Se for um listening, deve ficar no final, do contrário
179-
//corre o risco de receber 2 dados iguais por conta do método onClientListen na Server
180-
// await _lockPendingRequestsList.synchronized(() {
181-
_pendingRequestsList.add(request);
182-
_pendingRequestsList.sort((a,b) {
183-
if (a.data.requestType == RequestType.CONFIGURE_CONNECTION) {
184-
return -2;
185-
}
186-
if (b.data.requestType == RequestType.CONFIGURE_CONNECTION) {
187-
return 2;
188-
}
189-
if (a.data.requestType == RequestType.AUTHENTICATE) {
190-
return -1;
191-
}
192-
if (b.data.requestType == RequestType.AUTHENTICATE) {
193-
return 1;
194-
}
195-
return 0;
196-
});
197-
// });
177+
_pendingRequestsList.add(request);
178+
_pendingRequestsList.sort((a,b) {
179+
// Listen should always be in the END!
180+
if (a.data.requestType == RequestType.LISTEN) {
181+
return 3;
182+
}
183+
if (b.data.requestType == RequestType.LISTEN) {
184+
return -3;
185+
}
186+
187+
if (a.data.requestType == RequestType.CONFIGURE_CONNECTION) {
188+
return -2;
189+
}
190+
if (b.data.requestType == RequestType.CONFIGURE_CONNECTION) {
191+
return 2;
192+
}
193+
if (a.data.requestType == RequestType.AUTHENTICATE) {
194+
return -1;
195+
}
196+
if (b.data.requestType == RequestType.AUTHENTICATE) {
197+
return 1;
198+
}
199+
200+
return 0;
201+
});
198202
}
199-
}
203+
}

pubspec.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name: askless
22
description: Build Flutter Apps with PostgreSQL, MySQL, or any database, stream data changes through websockets effortlessly, handle websocket authentication like a pro and elevate your Flutter Chat App with video and audio calls!
33

4-
version: 3.0.0 # TODO onupdate:
4+
version: 3.0.1 # TODO onupdate:
55

66
environment:
77
sdk: '>=3.1.1 <4.0.0'

0 commit comments

Comments
 (0)