Line data Source code
1 : // Copyright The OpenTelemetry Authors
2 : // SPDX-License-Identifier: Apache-2.0
3 :
4 : // Native (`dart:io`) implementation of the HTTP client factory used by
5 : // the OTLP/HTTP exporters. Builds an `IOClient` wrapping an `HttpClient`
6 : // configured with custom certificates via [CertificateUtils] when the
7 : // caller has provided any.
8 :
9 : import 'dart:io';
10 :
11 : import 'package:dartastic_opentelemetry_api/dartastic_opentelemetry_api.dart'
12 : show OTelLog;
13 : import 'package:http/http.dart' as http;
14 : import 'package:http/io_client.dart';
15 :
16 : import '../certificate_utils_io.dart';
17 :
18 : /// Builds an [http.Client] for the OTLP/HTTP exporters.
19 : ///
20 : /// If any of [certificate] / [clientKey] / [clientCertificate] are
21 : /// non-null, builds an `HttpClient` with a custom `SecurityContext`
22 : /// loaded from those files and wraps it in an `IOClient`. Otherwise
23 : /// returns the default `http.Client()`.
24 : ///
25 : /// On any error constructing the secure client, falls back to the
26 : /// default client so the exporter still runs (logs an error).
27 128 : http.Client createOtlpHttpClient({
28 : required String exporterName,
29 : String? certificate,
30 : String? clientKey,
31 : String? clientCertificate,
32 : }) {
33 : if (certificate == null && clientKey == null && clientCertificate == null) {
34 128 : return http.Client();
35 : }
36 :
37 : try {
38 5 : final context = CertificateUtils.createSecurityContext(
39 : certificate: certificate,
40 : clientKey: clientKey,
41 : clientCertificate: clientCertificate,
42 : );
43 : if (context == null) {
44 0 : return http.Client();
45 : }
46 10 : return IOClient(HttpClient(context: context));
47 : } catch (e) {
48 0 : if (OTelLog.isError()) {
49 0 : OTelLog.error(
50 0 : '$exporterName: Failed to create HTTP client with certificates: $e',
51 : );
52 : }
53 0 : return http.Client();
54 : }
55 : }
|