Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/client-telemetry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
livekit_client: minor
---

Client telemetry: every Room reports its connect, reconnect, publish and subscribe spans, RTC statistics, SDK warnings and device state to its LiveKit Cloud project through the shared Rust core (native platforms only), with LiveKitClient.disableTelemetry() to opt out and Room.emitTelemetryEvent / Room.setTelemetryAttribute for app events and correlation ids
13 changes: 13 additions & 0 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,19 @@ jobs:
- uses: ./.github/actions/setup-flutter
- name: Dart Test Check
run: flutter test
# The telemetry end-to-end test posts OTLP to 127.0.0.1:4319 and reads back what the
# collector wrote (test/telemetry/otelcol.yaml). Only that test gets the endpoint, and a
# collector that did not start fails the job instead of skipping the test.
- name: Telemetry E2E Test
run: |
curl -sSfL -o otelcol.tar.gz "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.162.0/otelcol-contrib_0.162.0_linux_amd64.tar.gz"
echo "fcc063749f730f8c21fe29f2d340ff174f5f1c5885bd3156fb6c985a3036fcc3 otelcol.tar.gz" | sha256sum -c -
tar -xzf otelcol.tar.gz otelcol-contrib
nohup ./otelcol-contrib --config test/telemetry/otelcol.yaml > "$RUNNER_TEMP/otelcol.log" 2>&1 &
timeout 30 bash -c 'until curl -s -o /dev/null http://127.0.0.1:4319; do sleep 1; done' || { cat "$RUNNER_TEMP/otelcol.log"; exit 1; }
flutter test test/telemetry/
env:
LK_TELEMETRY_ENDPOINT: http://127.0.0.1:4319

native-test-check:
name: Native Test
Expand Down
55 changes: 39 additions & 16 deletions lib/src/core/engine.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import '../support/platform.dart' show lkPlatformIsTest, lkPlatformIs, PlatformT
import '../support/region_url_provider.dart';
import '../support/reusable_completer.dart';
import '../support/websocket.dart';
import '../telemetry/telemetry.dart';
import '../track/local/local.dart';
import '../track/local/video.dart';
import '../types/internal.dart';
Expand Down Expand Up @@ -192,6 +193,13 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {

bool _attemptingReconnect = false;

/// The Room's telemetry session, set by the Room.
@internal
RoomTelemetry? telemetry;

/// One reconnect cycle = one `lk.reconnect` span; attempts are its checkpoints.
TraceSpan? _reconnectSpan;

RegionUrlProvider? _regionUrlProvider;

lk_models.ServerInfo? _serverInfo;
Expand Down Expand Up @@ -376,6 +384,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
rethrow;
}
}
telemetry?.step(ConnectStep.signal);

// wait for join response
await events.waitFor<EngineJoinResponseEvent>(
Expand All @@ -399,6 +408,9 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
'Timed out waiting for PeerConnection to connect, please check your network for ice connectivity',
),
);
telemetry
?..step(ConnectStep.engine)
..step(ConnectStep.pcConnected);
connectStopwatch.stop();
logger.info('connection setup took ${connectStopwatch.elapsedMilliseconds} ms');
events.emit(const EngineConnectedEvent());
Expand Down Expand Up @@ -447,6 +459,8 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
_isReconnecting = false;

_clearPendingReconnect();
_reconnectSpan?.cancel();
_reconnectSpan = null;
}

@internal
Expand Down Expand Up @@ -988,6 +1002,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
publisher?.onOffer = (offer, offerId) {
logger.fine('publisher onOffer (offerId: $offerId)');
signalClient.sendOffer(offer, offerId);
telemetry?.step(ConnectStep.offerSent);
};

publisher?.onNegotiationError = _onPublisherNegotiationError;
Expand Down Expand Up @@ -1318,11 +1333,14 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {

if (_reconnectAttempts == 0) {
_reconnectStart = DateTime.timestamp();
_reconnectSpan ??= telemetry?.reconnect(reason, reconnectReason);
}

if (_reconnectAttempts >= _reconnectCount) {
logger.fine('reconnectAttempts exceeded, disconnecting...');
markClosed();
_reconnectSpan?.fail('reconnectAttemptsExceeded');
_reconnectSpan = null;
markClosed(reason: DisconnectReason.reconnectAttemptsExceeded);
await cleanUp();

events.emit(
Expand Down Expand Up @@ -1385,6 +1403,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
final fullReconnect = fullReconnectOnNext;
fullReconnectOnNext = false;
_attemptIsFullReconnect = fullReconnect;
_reconnectSpan?.attempt(_reconnectAttempts + 1, full: fullReconnect);

var succeeded = false;
try {
Expand All @@ -1402,18 +1421,15 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
);
}

if (fullReconnect) {
await restartConnection();
} else {
await resumeConnection(
reason,
reconnectReason: reconnectReason,
);
}
await _reconnectSpan.run(
() => fullReconnect ? restartConnection() : resumeConnection(reason, reconnectReason: reconnectReason),
);
_clearPendingReconnect();
_attemptingReconnect = false;
_isReconnecting = false;
succeeded = true;
_reconnectSpan?.end();
_reconnectSpan = null;
} catch (e) {
_reconnectAttempts = _reconnectAttempts + 1;
logger.fine('attemptReconnect: ${fullReconnect ? 'full reconnect' : 'resume'} failed: $e');
Expand All @@ -1434,16 +1450,19 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
unawaited(handleReconnect(ClientDisconnectReason.reconnectRetry));
} else {
logger.fine('attemptReconnect: disconnecting...');
markClosed();
_reconnectSpan?.fail(e);
_reconnectSpan = null;
final reason = e is CertificatePinningException
? DisconnectReason.signalingConnectionFailure
: DisconnectReason.disconnected;
markClosed(reason: reason);
// clean up before emitting, room's EngineDisconnectedEvent handler
// drops the event while fullReconnectOnNext is still true and
// cleanUp() is what resets it
await cleanUp();
events.emit(
EngineDisconnectedEvent(
reason: e is CertificatePinningException
? DisconnectReason.signalingConnectionFailure
: DisconnectReason.disconnected,
reason: reason,
),
);
}
Expand Down Expand Up @@ -1671,6 +1690,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {

void _setUpSignalListeners() => _signalListener
..on<SignalJoinResponseEvent>((event) async {
telemetry?.step(ConnectStep.joinRecv);
// create peer connections
_subscriberPrimary = event.response.subscriberPrimary;
// Derive single PC mode from the actual signal path, not just the option.
Expand Down Expand Up @@ -1699,6 +1719,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {

if (publisher == null && subscriber == null) {
await _createPeerConnections(rtcConfiguration);
telemetry?.step(ConnectStep.pcCreated);
}

if (_singlePCMode || !_subscriberPrimary || event.response.fastPublish) {
Expand Down Expand Up @@ -1751,6 +1772,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
})
..on<SignalConnectedEvent>((event) async {
logger.fine('Signal connected');
telemetry?.step(ConnectStep.wsOpen);
// The attempt counter is not reset here. A resume opens its socket before
// the peer connections are restored, so a reset on socket connect would
// let an attempt that fails afterwards start again from zero and never
Expand Down Expand Up @@ -1810,6 +1832,7 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
logger.fine('Created answer');
logger.finer('sdp: ${answer.sdp}');
signalClient.sendAnswer(answer, event.offerId);
telemetry?.step(ConnectStep.answerSent);
} catch (_) {
logger.severe('[$objectId] Failed to createAnswer()');
}
Expand Down Expand Up @@ -1946,17 +1969,17 @@ class Engine extends Disposable with EventsEmittable<EngineEvent> {
// Announce terminal closure before tearing down transports or event listeners.
// A full reconnect also disposes transports, but must keep the engine open.
@internal
void markClosed() {
void markClosed({DisconnectReason reason = DisconnectReason.clientInitiated}) {
if (_isClosed) return;
_isClosed = true;
_sendStateChanged.complete();
events.emit(EngineClosingEvent());
events.emit(EngineClosingEvent(reason: reason));
}

Future<void> disconnect({
DisconnectReason reason = DisconnectReason.clientInitiated,
}) async {
markClosed();
markClosed(reason: reason);
if (connectionState == ConnectionState.connected) {
// Tell the server, then tear down locally without waiting for its Leave
// echo, the same as the other SDKs. The echo is not guaranteed: media
Expand Down
61 changes: 55 additions & 6 deletions lib/src/core/room.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import '../support/disposable.dart';
import '../support/http_client.dart';
import '../support/platform.dart';
import '../support/region_url_provider.dart';
import '../telemetry/telemetry.dart';
import '../track/audio_management.dart';
import '../track/local/audio.dart';
import '../track/local/video.dart';
Expand Down Expand Up @@ -127,6 +128,33 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {

@internal
final Engine engine;

/// This Room's telemetry session, one trace for the Room's lifetime; null on web and after
/// `LiveKitClient.disableTelemetry`.
@internal
late final RoomTelemetry? telemetry = RoomTelemetry.create(this);

/// Records an app event in this Room's telemetry, exported as `custom.<name>` next to the SDK's
/// own records, with this Room's correlation attributes. A no-op on web.
///
/// ```dart
/// room.emitTelemetryEvent('checkout.started', attributes: {'cart.items': '3'});
/// ```
///
/// Names and keys up to 128 bytes, values up to 1024 bytes, at most 64 attributes and no `lk.`
/// keys; anything else is dropped, never truncated.
void emitTelemetryEvent(String name, {Map<String, String> attributes = const {}}) =>
telemetry?.emitCustom(name, attributes);

/// Sets a correlation attribute on every telemetry record this Room captures from now on, to
/// match them with your own data (an order id, a tenant); `null` removes it. Same limits as
/// [emitTelemetryEvent], at most 64 per Room. A no-op on web.
///
/// ```dart
/// room.setTelemetryAttribute('app.order_id', orderId);
/// ```
void setTelemetryAttribute(String key, String? value) => telemetry?.setAttribute(key, value);

// suppport for multiple event listeners
late final EventsListener<EngineEvent> _engineListener;

Expand Down Expand Up @@ -199,14 +227,18 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
connectOptions: connectOptions,
roomOptions: roomOptions,
) {
//
dataStreams = createDataStreams(this);
this.engine.telemetry = telemetry;
// The Room's handlers run in its telemetry zone: a warning one of them logs lands in this
// Room's session even with no span open.
telemetry.run(() {
dataStreams = createDataStreams(this);

_engineListener = this.engine.createListener();
_setUpEngineListeners();
_engineListener = this.engine.createListener();
_setUpEngineListeners();

_signalListener = this.engine.signalClient.createListener();
_setUpSignalListeners();
_signalListener = this.engine.signalClient.createListener();
_setUpSignalListeners();
});

_rpcClientManager = RpcClientManager(this);
_rpcServerManager = RpcServerManager(this);
Expand Down Expand Up @@ -303,6 +335,23 @@ class Room extends DisposableChangeNotifier with EventsEmittable<RoomEvent> {
ConnectOptions? connectOptions,
@Deprecated('deprecated, please use roomOptions in Room constructor') RoomOptions? roomOptions,
FastConnectOptions? fastConnectOptions,
}) {
Future<void> connect() => _connect(
url,
token,
connectOptions: connectOptions,
roomOptions: roomOptions,
fastConnectOptions: fastConnectOptions,
);
return telemetry?.connect(url, token, connect) ?? connect();
}

Future<void> _connect(
String url,
String token, {
ConnectOptions? connectOptions,
RoomOptions? roomOptions,
FastConnectOptions? fastConnectOptions,
}) async {
var effectiveRoomOptions = roomOptions ?? this.roomOptions;
if (lkPlatformIs(PlatformType.web) &&
Expand Down
56 changes: 56 additions & 0 deletions lib/src/ffi/ffi_io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,62 @@

import 'package:livekit_ffi/livekit_ffi.dart' as ffi;

// The telemetry types and calls lib/src/telemetry/telemetry_io.dart uses, re-exported so it
// reaches the core through this file only.
export 'package:livekit_ffi/livekit_telemetry.dart'
show
AnswerSentSpanStep,
AppState,
AttemptSpanStep,
AttributeValue,
AudioOutput,
AudioRouteChangedDeviceEvent,
AudioRouteReason,
BoolAttributeValue,
CaptureDevice,
CaptureFailedDeviceEvent,
CaptureFailure,
ConnectSpanName,
DeviceState,
DisconnectReason,
DoubleAttributeValue,
EngineSpanStep,
ExportRequest,
ExportResponse,
IntAttributeValue,
JoinRecvSpanStep,
LogRecord,
LogSource,
MemoryPressure,
NetworkType,
OfferSentSpanStep,
PcConnectedSpanStep,
PcCreatedSpanStep,
PublishSpanName,
TelemetryReconnectReason,
ReconnectSpanName,
RejectedExportException,
RetryableExportException,
RoomConnectedSpanStep,
RoomIdentity,
RtcStat,
Sdk,
Severity,
SignalSpanStep,
SpanName,
SpanOutcome,
SpanStep,
SpanTrack,
StrAttributeValue,
TelemetryConfig,
TelemetryInstrument,
TelemetryResource,
ThermalState,
TrackKind,
TrackSource,
WsOpenSpanStep;
export 'package:livekit_ffi/livekit_ffi.dart';

/// Native implementation of [LiveKitFFI]. See `ffi.dart`.
///
/// This is the only file in the SDK that may import the generated bindings:
Expand Down
6 changes: 4 additions & 2 deletions lib/src/internal/events.dart
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,12 @@ class EngineDisconnectedEvent with InternalEvent, EngineEvent {

@internal
class EngineClosingEvent with InternalEvent, EngineEvent {
const EngineClosingEvent();
/// Why the engine closes: [DisconnectReason.clientInitiated] for the app's own `disconnect()`.
final DisconnectReason reason;
const EngineClosingEvent({this.reason = DisconnectReason.clientInitiated});

@override
String toString() => '${runtimeType}()';
String toString() => '${runtimeType}(reason: $reason)';
}

@internal
Expand Down
9 changes: 9 additions & 0 deletions lib/src/livekit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,21 @@ import 'audio/audio_session.dart';
import 'support/native.dart';
import 'support/platform.dart' show PlatformType, lkPlatformIs, lkPlatformIsMobile, lkPlatformIsDesktop;
import 'support/webrtc_initialize_options.dart';
import 'telemetry/telemetry.dart';

/// Main entry point to connect to a room.
/// {@category Room}
class LiveKitClient {
static const version = '2.14.0';

/// Opts this process out of client telemetry, in effect as soon as it is called: collection
/// stops and Rooms created afterwards collect nothing. Everything not yet sent — queued, open or
/// cached on disk — is deleted in the background. Call it at every launch, before creating a
/// Room, to collect nothing at all. A no-op on web.
///
/// TODO: final shape pending the token/consent discussion.
static Future<void> disableTelemetry() => RoomTelemetry.disable();

/// Initialize the WebRTC plugin.
///
/// Optional: call once at startup to enable [bypassVoiceProcessing] before
Expand Down
Loading
Loading