writeApiCallsLogFile function

Future<String> writeApiCallsLogFile({
  1. required TestLogger logger,
  2. required String filePrefix,
  3. required List<APICallRecord> calls,
})

Implementation

Future<String> writeApiCallsLogFile({
  required TestLogger logger,
  required String filePrefix,
  required List<APICallRecord> calls,
}) {
  return RunnerBenchmark.future('diagnostic', 'writeApiCallsLogFile', () {
    final callsByName = <String, List<DateTime>>{};
    for (final call in calls) {
      callsByName
          .putIfAbsent(call.name, () => <DateTime>[])
          .add(call.timestamp);
    }
    Map<String, dynamic> eventFor(
      APICallRecord call,
      int index, {
      int? stepIndex,
      DateTime? timestamp,
      bool? completed,
      bool includeResponse = true,
      bool includeOutcome = true,
      String? phase,
      bool overrideStepIndex = false,
    }) {
      return {
        'index': index,
        'callId': index,
        'name': call.name,
        'timestamp': (timestamp ?? call.timestamp).toIso8601String(),
        if ((overrideStepIndex ? stepIndex : stepIndex ?? call.stepIndex) !=
            null)
          'stepIndex':
              overrideStepIndex ? stepIndex : stepIndex ?? call.stepIndex,
        if (call.mocked != null) 'mocked': call.mocked,
        if (includeOutcome && call.statusCode != null)
          'statusCode': call.statusCode,
        if (includeOutcome && call.error != null) 'error': call.error,
        'completed': completed ?? call.isCompleted,
        if (includeOutcome && call.providerDurationMs != null)
          'providerDurationMs': call.providerDurationMs,
        if (phase != null) 'phase': phase,
        if (includeResponse && (call.isCompleted || call.responseBody != null))
          'responseBody': _loggableResponseBody(call.responseBody),
        if (call.type != null) 'type': call.type,
        'request': {
          'url': (call.resolvedUrl?.isNotEmpty == true)
              ? call.resolvedUrl!
              : (call.type == 'firestore'
                  ? ((call.apiDefinition['path'] ??
                              call.apiDefinition['firestore']?['path'])
                          ?.toString() ??
                      '')
                  : (call.type == 'functions'
                      ? ((call.apiDefinition['name'] ??
                                  call.apiDefinition['function']?['name'])
                              ?.toString() ??
                          '')
                      : (call.apiDefinition['url'] ?? call.apiDefinition['uri'])
                              ?.toString() ??
                          '')),
          'method': call.type == 'firestore'
              ? ((call.apiDefinition['operation'] ??
                          call.apiDefinition['firestore']?['operation'])
                      ?.toString()
                      .toUpperCase() ??
                  'GET')
              : (call.type == 'functions'
                  ? 'CALL'
                  : (call.apiDefinition['method']?.toString() ?? 'GET')),
          if (call.resolvedHeaders != null ||
              call.apiDefinition['headers'] != null ||
              call.apiDefinition['firestore']?['headers'] != null ||
              call.apiDefinition['function']?['headers'] != null)
            'headers': call.resolvedHeaders ??
                call.apiDefinition['headers'] ??
                call.apiDefinition['firestore']?['headers'] ??
                call.apiDefinition['function']?['headers'],
          if (call.resolvedBody != null ||
              call.apiDefinition['body'] != null ||
              call.apiDefinition['data'] != null ||
              call.apiDefinition['firestore']?['body'] != null ||
              call.apiDefinition['firestore']?['data'] != null ||
              call.apiDefinition['function']?['body'] != null ||
              call.apiDefinition['function']?['data'] != null)
            'body': call.resolvedBody ??
                call.apiDefinition['body'] ??
                call.apiDefinition['data'] ??
                call.apiDefinition['firestore']?['body'] ??
                call.apiDefinition['firestore']?['data'] ??
                call.apiDefinition['function']?['body'] ??
                call.apiDefinition['function']?['data'],
          if (call.resolvedParameters != null ||
              call.apiDefinition['parameters'] != null ||
              call.apiDefinition['query'] != null ||
              call.apiDefinition['firestore']?['parameters'] != null ||
              call.apiDefinition['firestore']?['query'] != null ||
              call.apiDefinition['function']?['parameters'] != null ||
              call.apiDefinition['function']?['query'] != null)
            'parameters': call.resolvedParameters ??
                call.apiDefinition['parameters'] ??
                call.apiDefinition['query'] ??
                call.apiDefinition['firestore']?['parameters'] ??
                call.apiDefinition['firestore']?['query'] ??
                call.apiDefinition['function']?['parameters'] ??
                call.apiDefinition['function']?['query'],
        },
      };
    }

    final events = <Map<String, dynamic>>[];
    for (var i = 0; i < calls.length; i++) {
      final call = calls[i];
      final wasPendingAtStepEnd = call.wasPendingAtStepEnd;
      if (!wasPendingAtStepEnd) {
        events.add(eventFor(call, i + 1));
        continue;
      }
      if (call.isCompleted && call.completionStepIndex == call.stepIndex) {
        // The request and response both occurred inside this step. It is one
        // completed call in that step, not a cross-step pending/response pair.
        events.add(eventFor(call, i + 1));
        continue;
      }
      // Preserve the end-of-step observation even if the response eventually
      // arrived (or the test ended) before the report was written.
      events.add(eventFor(
        call,
        i + 1,
        stepIndex: call.stepIndex,
        completed: false,
        includeResponse: false,
        includeOutcome: false,
        phase: 'pending',
      ));
      if (!call.isCompleted) continue;

      // The later response is a separate event on the step where the provider
      // actually completed. A null step means it completed between steps.
      events.add(eventFor(
        call,
        i + 1,
        stepIndex: call.completionStepIndex,
        timestamp: call.completedAt,
        phase: 'completed',
        overrideStepIndex: true,
      ));
    }
    final content = const JsonEncoder.withIndent('  ').convert(
      _toSerializable({
        'total': calls.length,
        'calls': callsByName.entries
            .map(
              (entry) => {
                'name': entry.key,
                'count': entry.value.length,
                'timestamps': [
                  for (final timestamp in entry.value)
                    timestamp.toIso8601String(),
                ],
              },
            )
            .toList(),
        'events': events,
      }),
    );

    return logger.writeLogFile(
      testId: filePrefix,
      name: 'api_calls',
      content: content,
      extension: 'json',
    );
  });
}