fitResponseFrame static method
Shrink a request/response frame the backend is WAITING on so it fits
maxBytes, instead of letting the transport cap drop it:
find_candidates_response sheds its lowest-ranked (trailing) candidates,
info_query_response shortens value. Null for any other type, or when
even the minimal frame cannot fit (the queue then substitutes a failure).
Implementation
@visibleForTesting
static Map<String, dynamic>? fitResponseFrame(
Map<String, dynamic> json, int maxBytes) {
int size(Map<String, dynamic> m) => utf8.encode(jsonEncode(m)).length;
switch (json['type']) {
case FindCandidatesResponseMessage.kType:
final all = json['candidates'];
if (all is! List) return null;
final out = Map<String, dynamic>.of(json);
for (var keep = all.length - 1; keep >= 0; keep--) {
out['candidates'] = all.sublist(0, keep);
if (size(out) <= maxBytes) return out;
}
return null;
case InfoQueryResponseMessage.kType:
final value = json['value'];
if (value is! String || value.isEmpty) return null;
final out = Map<String, dynamic>.of(json);
var keep = value.length;
while (keep > 0) {
keep = keep ~/ 2;
out['value'] = keep == 0 ? '' : '${value.substring(0, keep)}…';
if (size(out) <= maxBytes) return out;
}
return null;
default:
return null;
}
}