Skip to content

Commit 6316080

Browse files
Cleanup part 1
1 parent 3d0f2d7 commit 6316080

File tree

8 files changed

+36
-120
lines changed

8 files changed

+36
-120
lines changed

packages/firebase_data_connect/firebase_data_connect/lib/src/cache/cache_manager.dart

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class Cache {
5151
Stream<Set<String>> get impactedQueries => _impactedQueryController.stream;
5252

5353
String _contructCacheIdentifier() {
54-
return '${_settings.storage}-${dataConnect.app.options.projectId}-${dataConnect.app.name}-${dataConnect.connectorConfig.serviceId}-${dataConnect.connectorConfig.connector}-${dataConnect.connectorConfig.location}-${FirebaseAuth.instanceFor(app: dataConnect.app).currentUser?.uid}-${dataConnect.transport.transportOptions.host}';
54+
return '${_settings.storage}-${dataConnect.app.options.projectId}-${dataConnect.app.name}-${dataConnect.connectorConfig.serviceId}-${dataConnect.connectorConfig.connector}-${dataConnect.connectorConfig.location}-${dataConnect.auth?.currentUser?.uid ?? 'anon'}-${dataConnect.transport.transportOptions.host}';
5555
}
5656

5757
void _initializeProvider() {
@@ -77,7 +77,12 @@ class Cache {
7777
}
7878

7979
void _listenForAuthChanges() {
80-
FirebaseAuth.instanceFor(app: dataConnect.app)
80+
if (dataConnect.auth == null) {
81+
developer.log('Not listening for auth changes since no auth instance in data connect');
82+
return;
83+
}
84+
85+
dataConnect.auth!
8186
.authStateChanges()
8287
.listen((User? user) {
8388
_initializeProvider();
@@ -86,9 +91,8 @@ class Cache {
8691

8792
/// Caches a server response.
8893
Future<void> update(String queryId, ServerResponse serverResponse) async {
89-
print("updateCache data for $queryId");
90-
9194
if (_cacheProvider == null) {
95+
developer.log('cache update: no provider available');
9296
return;
9397
}
9498

@@ -105,7 +109,6 @@ class Cache {
105109
EntityNode rootNode = dehydrationResult.dehydratedTree;
106110
String dehydratedJson =
107111
jsonEncode(rootNode.toJson(mode: EncodingMode.dehydrated));
108-
print("cacheUpdate: dehydrateResult ${dehydratedJson}");
109112

110113
Duration ttl = serverResponse.ttl != null
111114
? serverResponse.ttl!
@@ -118,18 +121,13 @@ class Cache {
118121
cachedAt: DateTime.now(),
119122
lastAccessed: DateTime.now());
120123

121-
print("updateCache - got resultTree $resultTree");
122-
123124
_cacheProvider!.saveResultTree(queryId, resultTree);
124-
print("updateCache - savedResultTree $queryId - $resultTree");
125125

126126
_impactedQueryController.add(dehydrationResult.impactedQueryIds);
127127
}
128128

129129
/// Fetches a cached result.
130130
Future<Map<String, dynamic>?> get(String queryId, bool allowStale) async {
131-
print("getCache for $queryId");
132-
133131
if (_cacheProvider == null) {
134132
return null;
135133
}
@@ -142,18 +140,16 @@ class Cache {
142140
}
143141

144142
final resultTree = _cacheProvider!.getResultTree(queryId);
145-
print("getCache resultTree $resultTree");
146143

147144
if (resultTree != null) {
148145
// Simple TTL check
149146
if (resultTree.isStale() && !allowStale) {
150-
print("getCache result is stale and allowStale is false");
147+
developer.log('getCache result is stale and allowStale is false');
151148
return null;
152149
}
153150

154151
resultTree.lastAccessed = DateTime.now();
155152
_cacheProvider!.saveResultTree(queryId, resultTree);
156-
print("getCache updated lastAccessed ${resultTree.data}");
157153

158154
EntityNode rootNode =
159155
EntityNode.fromJson(resultTree.data, _cacheProvider!);

packages/firebase_data_connect/firebase_data_connect/lib/src/cache/in_memory_cache_provider.dart

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,10 @@ class InMemoryCacheProvider implements CacheProvider {
3838
@override
3939
void saveResultTree(String queryId, ResultTree resultTree) {
4040
_resultTrees[queryId] = resultTree;
41-
print("Saved resultTree for $queryId $resultTree");
42-
print("save InMemoryCacheProvider ${_resultTrees.keys}");
4341
}
4442

4543
@override
4644
ResultTree? getResultTree(String queryId) {
47-
print("Getting resultTree for $queryId");
48-
print("InMemoryCacheProvider ${_resultTrees.keys}");
4945
return _resultTrees[queryId];
5046
}
5147

packages/firebase_data_connect/firebase_data_connect/lib/src/cache/result_tree_processor.dart

Lines changed: 1 addition & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,13 @@ class ResultTreeProcessor {
3333
Map<String, dynamic> serverResponse, CacheProvider cacheProvider) async {
3434
final impactedQueryIds = <String>{};
3535

36-
print("dehydrate: ${jsonEncode(serverResponse)}");
37-
3836
Map<String, dynamic> jsonData = serverResponse;
3937
if (serverResponse.containsKey('data')) {
4038
jsonData = serverResponse['data'];
4139
}
4240
final rootNode =
4341
_dehydrateNode(queryId, jsonData, cacheProvider, impactedQueryIds);
4442

45-
//debug only
46-
47-
print(
48-
"dehydrated rootNode ${jsonEncode(rootNode.toJson(mode: EncodingMode.dehydrated))}");
49-
5043
return DehydrationResult(rootNode, impactedQueryIds);
5144
}
5245

@@ -55,7 +48,6 @@ class ResultTreeProcessor {
5548
if (data is Map<String, dynamic>) {
5649
if (data.containsKey(GlobalIDKey)) {
5750
final guid = data[GlobalIDKey] as String;
58-
print("dehydrate - obj with globalId ${guid}");
5951

6052
final serverValues = <String, dynamic>{};
6153
final nestedObjects = <String, EntityNode>{};
@@ -69,12 +61,6 @@ class ResultTreeProcessor {
6961
EntityNode en =
7062
_dehydrateNode(queryId, value, cacheProvider, impactedQueryIds);
7163
nestedObjects[key] = en;
72-
if (en != null) {
73-
print(
74-
'dehydrate - got nestedObject EN for key ${key} ${en!.scalarValues?.length} ${en!.nestedObjectLists?.length} ${en!.nestedObjects?.length}');
75-
} else {
76-
print("dehydrate - EntityNode is null");
77-
}
7864
} else if (value is List) {
7965
final nodeList = <EntityNode>[];
8066
for (final item in value) {
@@ -93,15 +79,12 @@ class ResultTreeProcessor {
9379
existingEdo.setServerValues(serverValues);
9480
cacheProvider.saveEntityDataObject(existingEdo);
9581

96-
print(
97-
"dehydrate - returning EN ${existingEdo.guid} with EDO ${existingEdo}");
9882
return EntityNode(
9983
entity: existingEdo,
10084
nestedObjects: nestedObjects,
10185
nestedObjectLists: nestedObjectLists);
10286
} else {
10387
// GlobalID check
104-
print("dehydrate - no globalID ${data}");
10588
final scalarValues = <String, dynamic>{};
10689
final nestedObjects = <String, EntityNode>{};
10790
final nestedObjectLists = <String, List<EntityNode>>{};
@@ -114,22 +97,17 @@ class ResultTreeProcessor {
11497
nestedObjects[key] =
11598
_dehydrateNode(queryId, value, cacheProvider, impactedQueryIds);
11699
} else if (value is List) {
117-
print("dehydrate - listValue for key ${key} count ${value.length}");
118100
final nodeList = <EntityNode>[];
119101
for (final item in value) {
120102
nodeList.add(_dehydrateNode(
121103
queryId, item, cacheProvider, impactedQueryIds));
122104
}
123105
nestedObjectLists[key] = nodeList;
124-
print(
125-
"dehydrate - added to lists ${key} ${nodeList.length} ${jsonEncode(nodeList)}");
126106
} else {
127107
scalarValues[key] = value;
128108
}
129109
}
130-
print(
131-
"dehydrate - returning an EN with scalaraValues ${scalarValues.length} nestedObjectLists ${nestedObjectLists.length} nestedObjects ${nestedObjects.length}");
132-
110+
133111
return EntityNode(
134112
scalarValues: scalarValues,
135113
nestedObjects: nestedObjects,

packages/firebase_data_connect/firebase_data_connect/lib/src/core/ref.dart

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ abstract class OperationRef<Data, Variables> {
7878

7979
// Converts a hydrated Json tree to Typed Data
8080
Data _convertBodyJsonToData(Map<String, dynamic> bodyJson) {
81-
print("convertBodyBodyToData ${bodyJson}");
8281
List errors = bodyJson['errors'] ?? [];
8382
final data = bodyJson['data'] ?? bodyJson;
8483
List<DataConnectOperationFailureResponseErrorInfo> suberrors = errors
@@ -218,17 +217,14 @@ class QueryRef<Data, Variables> extends OperationRef<Data, Variables> {
218217

219218
Future<QueryResult<Data, Variables>> execute(
220219
{QueryFetchPolicy fetchPolicy = QueryFetchPolicy.preferCache}) async {
221-
print("execute called with policy $fetchPolicy");
222220
if (dataConnect.cacheManager != null) {
223221
switch (fetchPolicy) {
224222
case QueryFetchPolicy.cacheOnly:
225223
return _executeFromCache(fetchPolicy);
226224
case QueryFetchPolicy.preferCache:
227225
try {
228-
print("preferCache policy - checking cache");
229226
return await _executeFromCache(fetchPolicy);
230227
} catch (e) {
231-
print("error executing from cache. trying server");
232228
return _executeFromServer();
233229
}
234230
case QueryFetchPolicy.serverOnly:
@@ -243,35 +239,32 @@ class QueryRef<Data, Variables> extends OperationRef<Data, Variables> {
243239

244240
Future<QueryResult<Data, Variables>> _executeFromCache(
245241
QueryFetchPolicy fetchPolicy) async {
246-
print("_executeFromCache called with policy $fetchPolicy");
242+
if (dataConnect.cacheManager == null) {
243+
throw DataConnectError(DataConnectErrorCode.cacheMiss, 'Cache miss. No configured cache');
244+
}
247245
final cacheManager = dataConnect.cacheManager!;
248246
bool allowStale = fetchPolicy ==
249247
QueryFetchPolicy.cacheOnly; //if its cache only, we always allow stale
250248
final cachedData = await cacheManager.get(_queryId, allowStale);
251249

252250
if (cachedData != null) {
253-
print("cached data is not null. Returning result");
254-
String jsonStr = jsonEncode(cachedData);
255-
print("cached data $jsonStr");
256251
final result = QueryResult(
257252
dataConnect,
258253
deserializer(jsonEncode(cachedData['data'] ?? cachedData)),
259254
DataSource.cache,
260255
this);
261256
return result;
262257
} else {
263-
print("_executeFromCache cachedData is null");
264258
if (fetchPolicy == QueryFetchPolicy.cacheOnly) {
265259
throw DataConnectError(DataConnectErrorCode.cacheMiss, 'Cache miss');
266260
} else {
267261
throw DataConnectError(
268-
DataConnectErrorCode.cacheMiss, 'Stale cache miss');
262+
DataConnectErrorCode.cacheMiss, 'Possible stale cache miss');
269263
}
270264
}
271265
}
272266

273267
Future<QueryResult<Data, Variables>> _executeFromServer() async {
274-
print("_executeFromServer called ");
275268
bool shouldRetry = await _shouldRetry();
276269
try {
277270
ServerResponse serverResponse =
@@ -284,7 +277,6 @@ class QueryRef<Data, Variables> extends OperationRef<Data, Variables> {
284277
);
285278

286279
if (dataConnect.cacheManager != null) {
287-
print("Updating cache");
288280
await dataConnect.cacheManager!.update(_queryId, serverResponse);
289281
}
290282
Data typedData = _convertBodyJsonToData(serverResponse.data);

packages/firebase_data_connect/firebase_data_connect/lib/src/firebase_data_connect.dart

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,8 @@ class FirebaseDataConnect extends FirebasePluginPlatform {
3636
required this.connectorConfig,
3737
this.auth,
3838
this.appCheck,
39-
this.cacheSettings,
4039
CallerSDKType? sdkType,
40+
this.cacheSettings
4141
}) : options = DataConnectOptions(
4242
app.options.projectId,
4343
connectorConfig.location,
@@ -157,6 +157,7 @@ class FirebaseDataConnect extends FirebasePluginPlatform {
157157
transportOptions = TransportOptions(mappedHost, port, isSecure);
158158

159159
if (cacheManager != null) {
160+
// dispose and clean this up. it will get reinitialized for newer QueryRefs that target the emulator.
160161
cacheManager?.dispose();
161162
cacheManager = null;
162163
}
@@ -175,27 +176,26 @@ class FirebaseDataConnect extends FirebasePluginPlatform {
175176
FirebaseApp? app,
176177
FirebaseAuth? auth,
177178
FirebaseAppCheck? appCheck,
178-
CacheSettings? cacheSettings,
179179
CallerSDKType? sdkType,
180180
required ConnectorConfig connectorConfig,
181+
CacheSettings? cacheSettings = const CacheSettings()
181182
}) {
182183
app ??= Firebase.app();
183184
auth ??= FirebaseAuth.instanceFor(app: app);
184185
appCheck ??= FirebaseAppCheck.instanceFor(app: app);
185186

186187
if (cachedInstances[app.name] != null &&
187188
cachedInstances[app.name]![connectorConfig.toJson()] != null) {
188-
print("Returning cached instance for FirebaseDataConnect");
189189
return cachedInstances[app.name]![connectorConfig.toJson()]!;
190190
}
191191

192192
FirebaseDataConnect newInstance = FirebaseDataConnect(
193193
app: app,
194194
auth: auth,
195195
appCheck: appCheck,
196-
cacheSettings: cacheSettings,
197196
connectorConfig: connectorConfig,
198197
sdkType: sdkType,
198+
cacheSettings: cacheSettings,
199199
);
200200
if (cachedInstances[app.name] == null) {
201201
cachedInstances[app.name] = <String, FirebaseDataConnect>{};

packages/firebase_data_connect/firebase_data_connect/lib/src/network/grpc_transport.dart

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,10 @@ class GRPCTransport implements DataConnectTransport {
171171

172172
ServerResponse handleResponse<Data>(CommonResponse<Data> commonResponse) {
173173
log('handleResponse type ${commonResponse.data.runtimeType}');
174+
Map<String, dynamic>? jsond = commonResponse.data as Map<String, dynamic>?;
175+
log('handleResponse got json data $jsond');
174176
String jsonEncoded = jsonEncode(commonResponse.data);
175-
log('handleResponse jsonEncoded ${jsonEncoded.length} $jsonEncoded');
176-
Map<String, dynamic> decodedData = jsonDecode(jsonEncoded);
177-
log('handleResponse decodedData $decodedData');
177+
178178
if (commonResponse.errors.isNotEmpty) {
179179
Map<String, dynamic>? data =
180180
jsonDecode(jsonEncoded) as Map<String, dynamic>?;
@@ -201,9 +201,13 @@ ServerResponse handleResponse<Data>(CommonResponse<Data> commonResponse) {
201201
throw DataConnectOperationError(DataConnectErrorCode.other,
202202
'failed to invoke operation: ${response.errors}', response);
203203
}
204-
ServerResponse response = ServerResponse(decodedData);
205-
print("Converted to server response");
206-
return response;
204+
205+
// no errors - return a standard response
206+
if (jsond != null) {
207+
return ServerResponse(jsond!);
208+
} else {
209+
return ServerResponse({});
210+
}
207211
}
208212

209213
/// Initializes GRPC transport for Data Connect.

packages/firebase_data_connect/firebase_data_connect/lib/src/network/rest_transport.dart

Lines changed: 0 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -128,59 +128,6 @@ class RestTransport implements DataConnectTransport {
128128
);
129129
}
130130
return ServerResponse(bodyJson);
131-
/*
132-
List errors = bodyJson['errors'] ?? [];
133-
final data = bodyJson['data'];
134-
List<DataConnectOperationFailureResponseErrorInfo> suberrors = errors
135-
.map((e) => switch (e) {
136-
{'path': List? path, 'message': String? message} =>
137-
DataConnectOperationFailureResponseErrorInfo(
138-
(path ?? [])
139-
.map((val) => switch (val) {
140-
String() => DataConnectFieldPathSegment(val),
141-
int() => DataConnectListIndexPathSegment(val),
142-
_ => throw DataConnectError(
143-
DataConnectErrorCode.other,
144-
'Incorrect type for $val')
145-
})
146-
.toList(),
147-
message ??
148-
(throw DataConnectError(
149-
DataConnectErrorCode.other, 'Missing message'))),
150-
_ => throw DataConnectError(
151-
DataConnectErrorCode.other, 'Unable to parse JSON: $e')
152-
})
153-
.toList();
154-
Data? decodedData;
155-
Object? decodeError;
156-
try {
157-
/// The response we get is in the data field of the response
158-
/// Once we get the data back, it's not quite json-encoded,
159-
/// so we have to encode it and then send it to the user's deserializer.
160-
decodedData = deserializer(jsonEncode(bodyJson['data']));
161-
} catch (e) {
162-
decodeError = e;
163-
}
164-
if (suberrors.isNotEmpty) {
165-
final response =
166-
DataConnectOperationFailureResponse(suberrors, data, decodedData);
167-
168-
throw DataConnectOperationError(DataConnectErrorCode.other,
169-
'Failed to invoke operation: ', response);
170-
} else {
171-
if (decodeError != null) {
172-
throw DataConnectError(DataConnectErrorCode.other,
173-
'Unable to decode data: $decodeError');
174-
}
175-
if (decodedData is! Data) {
176-
throw DataConnectError(
177-
DataConnectErrorCode.other,
178-
"Decoded data wasn't parsed properly. Expected $Data, got $decodedData",
179-
);
180-
}
181-
return decodedData;
182-
}
183-
*/
184131
} on Exception catch (e) {
185132
if (e is DataConnectError) {
186133
rethrow;

0 commit comments

Comments
 (0)