buildScreenPerformanceJson function

Map<String, dynamic> buildScreenPerformanceJson({
  1. required String screenName,
  2. required List<AppFrameTimingEntry> frames,
  3. required List<PerformanceMarker> markers,
  4. List<APICallRecord> apiCalls = const [],
  5. List<StorageStepDiff> storageChanges = const [],
  6. List<StorageStepDiff> secureStorageChanges = const [],
  7. List<StorageStepDiff> keychainChanges = const [],
  8. bool storageDiagnosticsEnabled = false,
})

Implementation

Map<String, dynamic> buildScreenPerformanceJson({
  required String screenName,
  required List<AppFrameTimingEntry> frames,
  required List<PerformanceMarker> markers,
  List<APICallRecord> apiCalls = const [],
  List<StorageStepDiff> storageChanges = const [],
  List<StorageStepDiff> secureStorageChanges = const [],
  List<StorageStepDiff> keychainChanges = const [],
  bool storageDiagnosticsEnabled = false,
}) {
  return RunnerBenchmark.sync('diagnostic', 'buildScreenPerformanceJson', () {
    final screenMarkers = markers.where((m) => m.screen == screenName).toList();
    final screenFrames = frames.where((f) {
      final marker = _markerForFrame(f, markers);
      return marker?.screen == screenName;
    }).toList();

    final jankyFrames = screenFrames.where((frame) => frame.isJanky).length;
    final attributedCalls = apiCalls
        .where((call) => screenMarkers.any((marker) {
              final stepMatches = marker.stepIndex != null &&
                  call.stepIndex != null &&
                  marker.stepIndex == call.stepIndex! + 1;
              return stepMatches || marker.overlaps(call.timestamp);
            }))
        .toList(growable: false);
    final durations = attributedCalls
        .map((call) => call.providerDurationMs)
        .whereType<int>()
        .map((duration) => duration.toDouble())
        .toList(growable: false);
    final sortedDurations = durations.toList()..sort();
    List<StorageStepDiff> changesForScreen(
            List<StorageStepDiff> changes) =>
        changes
            .where((diff) => screenMarkers.any((marker) =>
                marker.stepIndex != null &&
                diff.stepIndex + 1 == marker.stepIndex))
            .toList(growable: false);
    final publicChanges = changesForScreen(storageChanges);
    final privateChanges = changesForScreen(secureStorageChanges);
    final keychainDiffs = changesForScreen(keychainChanges);
    final screenSteps = <int, PerformanceMarker>{};
    for (final marker in screenMarkers) {
      final stepIndex = marker.stepIndex;
      if (stepIndex == null) continue;
      screenSteps.putIfAbsent(stepIndex, () => marker);
    }
    final stepTimeline = screenSteps.entries.map((entry) {
      final marker = entry.value;
      final stepFrames = screenFrames
          .where((frame) => marker.containsFrame(frame.frameNumber))
          .toList(growable: false);
      final prefix =
          marker.testId + ' step ' + marker.stepIndex.toString() + ' ';
      return {
        'stepIndex': entry.key,
        'label': marker.label.startsWith(prefix)
            ? marker.label.substring(prefix.length)
            : marker.label,
        'phase': marker.phase,
        'durationMs':
            marker.endTime.difference(marker.startTime).inMilliseconds,
        'startFrame': marker.startFrame,
        'endFrame': marker.endFrame,
        'framesObserved': stepFrames.length,
        'slowFrames': stepFrames.where((frame) => frame.isJanky).length,
      };
    }).toList()
      ..sort(
          (a, b) => (a['startFrame'] as int).compareTo(b['startFrame'] as int));
    final frameTimeline = screenFrames.map((frame) {
      final marker = _markerForFrame(frame, markers);
      return {
        ...frame.toJson(),
        if (marker?.stepIndex != null) 'stepIndex': marker!.stepIndex,
      };
    }).toList(growable: false);
    return {
      'screen': screenName,
      'steps': stepTimeline,
      'timeline': {
        'frames': frameTimeline,
      },
      'frameBudgetMs': AppFrameTimingEntry.frameBudgetMs,
      'totalFrames': screenFrames.length,
      'jankyFrames': jankyFrames,
      'jankyFrameRate': _ratio(jankyFrames, screenFrames.length),
      'averageBuildMs': _average(screenFrames.map((frame) => frame.buildMs)),
      'maxBuildMs': _max(screenFrames.map((frame) => frame.buildMs)),
      'averageRasterMs': _average(screenFrames.map((frame) => frame.rasterMs)),
      'averageTotalSpanMs':
          _average(screenFrames.map((frame) => frame.totalSpanMs)),
      'framePercentilesMs': {
        'p50': _percentile(screenFrames.map((frame) => frame.totalSpanMs), .50),
        'p95': _percentile(screenFrames.map((frame) => frame.totalSpanMs), .95),
      },
      'rasterTimingAvailable': screenFrames.any((frame) => frame.rasterMs > 0),
      'network': {
        'requests': attributedCalls.length,
        'completed': attributedCalls.where((call) => call.isCompleted).length,
        'failed': attributedCalls
            .where((call) =>
                call.error != null ||
                (call.statusCode != null && call.statusCode! >= 400))
            .length,
        'pendingAtStepEnd':
            attributedCalls.where((call) => call.wasPendingAtStepEnd).length,
        'timedRequests': durations.length,
        'p95ProviderMs': _percentile(sortedDurations, .95),
        'maxProviderMs': _max(durations),
        'peakConcurrentRequests': _peakConcurrentRequests(
          attributedCalls,
          screenMarkers,
        ),
      },
      'storage': {
        'captured': storageDiagnosticsEnabled,
        'publicMutations': publicChanges.fold<int>(
            0, (sum, diff) => sum + diff.changes.length),
        'secureMutations': privateChanges.fold<int>(
            0, (sum, diff) => sum + diff.changes.length),
        'keychainMutations': keychainDiffs.fold<int>(
            0, (sum, diff) => sum + diff.changes.length),
      },
    };
  });
}