forked from flutter/devtools
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_analytics_web.dart
More file actions
960 lines (882 loc) · 31.3 KB
/
_analytics_web.dart
File metadata and controls
960 lines (882 loc) · 31.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
// Copyright 2019 The Flutter Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file or at https://developers.google.com/open-source/licenses/bsd.
// ignore_for_file: non_constant_identifier_names
import 'dart:async';
import 'package:devtools_app_shared/ui.dart' as app_ui;
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:stack_trace/stack_trace.dart' as stack_trace;
import 'package:unified_analytics/unified_analytics.dart' as ua;
import 'package:web/web.dart';
import '../globals.dart' as globals;
import '../managers/dtd_manager_extensions.dart';
import '../primitives/query_parameters.dart';
import '../server/server.dart' as server;
import '../utils/utils.dart';
import 'analytics_common.dart';
import 'constants.dart' as gac;
import 'metrics.dart';
/// userApp values.
enum _UserAppType {
flutter,
web,
flutterWeb,
dartCLI;
String get value {
switch (this) {
case _UserAppType.flutter:
return 'flutter';
case _UserAppType.web:
return 'web';
case _UserAppType.flutterWeb:
return 'flutter_web';
case _UserAppType.dartCLI:
return 'dart_cli';
}
}
}
/// userBuild values.
enum _UserBuildType { debug, profile }
// Start with Android_n.n.n
const devToolsPlatformTypeAndroid = 'Android_';
/// devToolsChrome prefix identifiers.
enum _ChromePrefix {
chrome,
crios,
cros;
String get value {
switch (this) {
case _ChromePrefix.chrome:
return 'Chrome/'; // starts with and ends with n.n.n
case _ChromePrefix.crios:
return 'Crios/'; // starts with and ends with n.n.n
case _ChromePrefix.cros:
return 'CrOS'; // Chrome OS
}
}
}
final _log = Logger('_analytics_web');
class DevToolsAnalyticsEvent {
DevToolsAnalyticsEvent._({
required this.screen,
required this.eventCategory,
required this.eventLabel,
required this.value,
required this.nonInteraction,
// IMPORTANT! Only string and int values are supported. All other value
// types will be ignored in GA4.
this.userApp, // [_UserAppType]
this.userBuild, // [_UserBuildType]
this.userPlatform, // (android/ios/fuchsia/linux/mac/windows)
this.devtoolsPlatform, // linux/android/mac/windows
this.devtoolsChrome, // Chrome version #
this.devtoolsVersion, // DevTools version #
this.ideLaunched, // Devtools launched (CLI, VSCode, Android)
this.flutterClientId, // Flutter tool client_id (~/.flutter).
this.isExternalBuild, // External build or google3
this.isEmbedded, // Whether devtools is embedded
this.g3Username, // g3 username (null for external users)
// IDE feature that launched Devtools
// The following is a non-exhaustive list of possible values for this dimension:
// "command" - VS Code command palette
// "sidebarContent" - the content of the sidebar (e.g. the DevTools dropdown for a debug session)
// "sidebarTitle" - the DevTools action in the sidebar title
// "touchbar" - MacOS touchbar button
// "launchConfiguration" - configured explicitly in launch configuration
// "onDebugAutomatic" - configured to always run on debug session start
// "onDebugPrompt" - user responded to prompt when running a debug session
// "languageStatus" - launched from the language status popout
this.ideLaunchedFeature,
this.isWasm, // whether DevTools is running with WASM.
// Performance screen metrics. See [PerformanceScreenMetrics].
this.uiDurationMicros, // metric1
this.rasterDurationMicros, // metric2
this.shaderCompilationDurationMicros, // metric3
// Profiler screen metrics. See [ProfilerScreenMetrics].
this.cpuSampleCount, // metric4
this.cpuStackDepth, // metric5
// Performance screen metric. See [PerformanceScreenMetrics].
this.traceEventCount, // metric6
// Memory screen metric. See [MemoryScreenMetrics].
this.heapDiffObjectsBefore, // metric7
this.heapDiffObjectsAfter, // metric8
this.heapObjectsTotal, // metric9
// Inspector screen metrics. See [InspectorScreenMetrics].
this.rootSetCount, // metric10
this.rowCount, // metric11
this.inspectorTreeControllerId, // metric12
// Deep Link screen metrics. See [DeepLinkScreenMetrics].
this.androidAppId, //metric13
this.iosBundleId, //metric14
// Inspector screen metrics. See [InspectorScreenMetrics].
this.isV2Inspector, // metric15
});
factory DevToolsAnalyticsEvent._create({
required String screen,
required String eventCategory,
required String eventLabel,
bool nonInteraction = false,
int value = 0,
ScreenAnalyticsMetrics? screenMetrics,
}) {
return DevToolsAnalyticsEvent._(
screen: screen,
eventCategory: eventCategory,
eventLabel: eventLabel,
nonInteraction: nonInteraction,
value: value,
userApp: userAppType,
userBuild: userBuildType,
userPlatform: userPlatformType,
devtoolsPlatform: _devtoolsPlatformType,
devtoolsChrome: _devtoolsChrome,
devtoolsVersion: devToolsVersion,
ideLaunched: _ideLaunched,
flutterClientId: _flutterClientId,
isExternalBuild: globals.isExternalBuild.toString(),
isEmbedded: app_ui.isEmbedded().toString(),
g3Username: globals.devToolsEnvironmentParameters.username(),
ideLaunchedFeature: _ideLaunchedFeature,
isWasm: kIsWasm.toString(),
// [PerformanceScreenMetrics]
uiDurationMicros: screenMetrics is PerformanceScreenMetrics
? screenMetrics.uiDuration?.inMicroseconds
: null,
rasterDurationMicros: screenMetrics is PerformanceScreenMetrics
? screenMetrics.rasterDuration?.inMicroseconds
: null,
shaderCompilationDurationMicros: screenMetrics is PerformanceScreenMetrics
? screenMetrics.shaderCompilationDuration?.inMicroseconds
: null,
traceEventCount: screenMetrics is PerformanceScreenMetrics
? screenMetrics.traceEventCount
: null,
// [ProfilerScreenMetrics]
cpuSampleCount: screenMetrics is ProfilerScreenMetrics
? screenMetrics.cpuSampleCount
: null,
cpuStackDepth: screenMetrics is ProfilerScreenMetrics
? screenMetrics.cpuStackDepth
: null,
// [MemoryScreenMetrics]
heapDiffObjectsBefore: screenMetrics is MemoryScreenMetrics
? screenMetrics.heapDiffObjectsBefore
: null,
heapDiffObjectsAfter: screenMetrics is MemoryScreenMetrics
? screenMetrics.heapDiffObjectsAfter
: null,
heapObjectsTotal: screenMetrics is MemoryScreenMetrics
? screenMetrics.heapObjectsTotal
: null,
// [InspectorScreenMetrics]
rootSetCount: screenMetrics is InspectorScreenMetrics
? screenMetrics.rootSetCount
: null,
rowCount: screenMetrics is InspectorScreenMetrics
? screenMetrics.rowCount
: null,
inspectorTreeControllerId: screenMetrics is InspectorScreenMetrics
? screenMetrics.inspectorTreeControllerId
: null,
// [DeepLinkScreenMetrics]
androidAppId: screenMetrics is DeepLinkScreenMetrics
? screenMetrics.androidAppId
: null,
iosBundleId: screenMetrics is DeepLinkScreenMetrics
? screenMetrics.iosBundleId
: null,
// [InspectorScreenMetrics]
// TODO(https://github.com/flutter/devtools/issues/9563): Remove this
// dimension after dashboards have been updated to not include it. The
// legacy inspector will be removed in Flutter 3.47 (Aug 2026), leaving
// the V2 inspector the only inspector.
isV2Inspector: screenMetrics is InspectorScreenMetrics
? true.toString()
: null,
);
}
String? screen;
String? eventCategory;
String? eventLabel;
bool nonInteraction;
int value;
// Custom dimensions:
String? userApp;
String? userBuild;
String? userPlatform;
String? devtoolsPlatform;
String? devtoolsChrome;
String? devtoolsVersion;
String? ideLaunched;
String? flutterClientId;
String? isExternalBuild;
String? isEmbedded;
String? g3Username;
String? ideLaunchedFeature;
String? isWasm;
// Custom metrics:
int? uiDurationMicros;
int? rasterDurationMicros;
int? shaderCompilationDurationMicros;
int? cpuSampleCount;
int? cpuStackDepth;
int? traceEventCount;
int? heapDiffObjectsBefore;
int? heapDiffObjectsAfter;
int? heapObjectsTotal;
int? rootSetCount;
int? rowCount;
int? inspectorTreeControllerId;
String? androidAppId;
String? iosBundleId;
String? isV2Inspector;
}
class DevToolsAnalyticsException {
DevToolsAnalyticsException._({
this.description,
required this.fatal,
// NOTE: Do not reorder any of these. Order here must match the order in the
// Google Analytics console.
// IMPORTANT! Only string and int values are supported. All other value
// types will be ignored in GA4.
this.userApp, // [_UserAppType]
this.userBuild, // [_UserBuildType]
this.userPlatform, // (android/ios/fuchsia/linux/mac/windows)
this.devtoolsPlatform, // linux/android/mac/windows
this.devtoolsChrome, // Chrome version #
this.devtoolsVersion, // DevTools version #
this.ideLaunched, // IDE launched DevTools
this.flutterClientId, // Flutter tool clientId
this.isExternalBuild, // External build or google3
this.isEmbedded, // Whether devtools is embedded
this.g3Username, // g3 username (null for external users)
// IDE feature that launched Devtools
// The following is a non-exhaustive list of possible values for this dimension:
// "command" - VS Code command palette
// "sidebarContent" - the content of the sidebar (e.g. the DevTools dropdown for a debug session)
// "sidebarTitle" - the DevTools action in the sidebar title
// "touchbar" - MacOS touchbar button
// "launchConfiguration" - configured explicitly in launch configuration
// "onDebugAutomatic" - configured to always run on debug session start
// "onDebugPrompt" - user responded to prompt when running a debug session
// "languageStatus" - launched from the language status popout
this.ideLaunchedFeature,
this.isWasm, // whether DevTools is running with WASM.
// Performance screen metrics. See [PerformanceScreenMetrics].
this.uiDurationMicros, // metric1
this.rasterDurationMicros, // metric2
this.shaderCompilationDurationMicros, // metric3
// Profiler screen metrics. See [ProfilerScreenMetrics].
this.cpuSampleCount, // metric4
this.cpuStackDepth, // metric5
// Performance screen metric. See [PerformanceScreenMetrics].
this.traceEventCount, // metric6
// Memory screen metric. See [MemoryScreenMetrics].
this.heapDiffObjectsBefore, // metric7
this.heapDiffObjectsAfter, // metric8
this.heapObjectsTotal, // metric9
// Inspector screen metrics. See [InspectorScreenMetrics].
this.rootSetCount, // metric10
this.rowCount, // metric11
this.inspectorTreeControllerId, // metric12
// Deep Link screen metrics. See [DeepLinkScreenMetrics].
this.androidAppId, //metric13
this.iosBundleId, //metric14
// Inspector screen metrics. See [InspectorScreenMetrics].
this.isV2Inspector, // metric15
});
factory DevToolsAnalyticsException._create(
String errorMessage, {
bool fatal = false,
ScreenAnalyticsMetrics? screenMetrics,
}) {
return DevToolsAnalyticsException._(
description: errorMessage,
fatal: fatal,
userApp: userAppType,
userBuild: userBuildType,
userPlatform: userPlatformType,
devtoolsPlatform: _devtoolsPlatformType,
devtoolsChrome: _devtoolsChrome,
devtoolsVersion: devToolsVersion,
ideLaunched: _ideLaunched,
flutterClientId: _flutterClientId,
isExternalBuild: globals.isExternalBuild.toString(),
isEmbedded: app_ui.isEmbedded().toString(),
g3Username: globals.devToolsEnvironmentParameters.username(),
ideLaunchedFeature: _ideLaunchedFeature,
isWasm: kIsWasm.toString(),
// [PerformanceScreenMetrics]
uiDurationMicros: screenMetrics is PerformanceScreenMetrics
? screenMetrics.uiDuration?.inMicroseconds
: null,
rasterDurationMicros: screenMetrics is PerformanceScreenMetrics
? screenMetrics.rasterDuration?.inMicroseconds
: null,
traceEventCount: screenMetrics is PerformanceScreenMetrics
? screenMetrics.traceEventCount
: null,
shaderCompilationDurationMicros: screenMetrics is PerformanceScreenMetrics
? screenMetrics.shaderCompilationDuration?.inMicroseconds
: null,
// [ProfilerScreenMetrics]
cpuSampleCount: screenMetrics is ProfilerScreenMetrics
? screenMetrics.cpuSampleCount
: null,
cpuStackDepth: screenMetrics is ProfilerScreenMetrics
? screenMetrics.cpuStackDepth
: null,
// [MemoryScreenMetrics]
heapDiffObjectsBefore: screenMetrics is MemoryScreenMetrics
? screenMetrics.heapDiffObjectsBefore
: null,
heapDiffObjectsAfter: screenMetrics is MemoryScreenMetrics
? screenMetrics.heapDiffObjectsAfter
: null,
heapObjectsTotal: screenMetrics is MemoryScreenMetrics
? screenMetrics.heapObjectsTotal
: null,
// [InspectorScreenMetrics]
rootSetCount: screenMetrics is InspectorScreenMetrics
? screenMetrics.rootSetCount
: null,
rowCount: screenMetrics is InspectorScreenMetrics
? screenMetrics.rowCount
: null,
inspectorTreeControllerId: screenMetrics is InspectorScreenMetrics
? screenMetrics.inspectorTreeControllerId
: null,
// [DeepLinkScreenMetrics]
androidAppId: screenMetrics is DeepLinkScreenMetrics
? screenMetrics.androidAppId
: null,
iosBundleId: screenMetrics is DeepLinkScreenMetrics
? screenMetrics.iosBundleId
: null,
// [InspectorScreenMetrics]
isV2Inspector: screenMetrics is InspectorScreenMetrics
? true.toString()
: null,
);
}
String? description;
bool fatal;
// Custom dimensions:
String? userApp;
String? userBuild;
String? userPlatform;
String? devtoolsPlatform;
String? devtoolsChrome;
String? devtoolsVersion;
String? ideLaunched;
String? flutterClientId;
String? isExternalBuild;
String? isEmbedded;
String? g3Username;
String? ideLaunchedFeature;
String? isWasm;
// Custom metrics:
int? uiDurationMicros;
int? rasterDurationMicros;
int? shaderCompilationDurationMicros;
int? cpuSampleCount;
int? cpuStackDepth;
int? traceEventCount;
int? heapDiffObjectsBefore;
int? heapDiffObjectsAfter;
int? heapObjectsTotal;
int? rootSetCount;
int? rowCount;
int? inspectorTreeControllerId;
String? androidAppId;
String? iosBundleId;
String? isV2Inspector;
}
void screen(String screenName, [int value = 0]) {
_log.fine('Event: Screen(screenName:$screenName, value:$value)');
final gtagEvent = DevToolsAnalyticsEvent._create(
screen: screenName,
eventCategory: gac.screenViewEvent,
eventLabel: gac.init,
value: value,
);
_sendEvent(gtagEvent);
}
String _operationKey(String screenName, String timedOperation) {
return '$screenName-$timedOperation';
}
final _timedOperationsInProgress = <String, DateTime>{};
// Use this method coupled with `timeEnd` when an operation cannot be timed in
// a callback, but rather needs to be timed instead at two disjoint start and
// end marks.
void timeStart(String screenName, String timedOperation) {
final startTime = DateTime.now();
final operationKey = _operationKey(screenName, timedOperation);
_timedOperationsInProgress[operationKey] = startTime;
}
// Use this method coupled with `timeStart` when an operation cannot be timed in
// a callback, but rather needs to be timed instead at two disjoint start and
// end marks.
void timeEnd(
String screenName,
String timedOperation, {
ScreenAnalyticsMetrics Function()? screenMetricsProvider,
}) {
final endTime = DateTime.now();
final operationKey = _operationKey(screenName, timedOperation);
final startTime = _timedOperationsInProgress.remove(operationKey);
assert(startTime != null);
if (startTime == null) {
_log.warning(
'Could not time operation "$timedOperation" because a) `timeEnd` was '
'called before `timeStart` or b) the `screenName` and `timedOperation`'
'parameters for the `timeStart` and `timeEnd` calls do not match.',
);
return;
}
final durationMicros =
endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch;
_timing(
screenName,
timedOperation,
durationMicros: durationMicros,
screenMetrics: screenMetricsProvider != null
? screenMetricsProvider()
: null,
);
}
void cancelTimingOperation(String screenName, String timedOperation) {
final operationKey = _operationKey(screenName, timedOperation);
final operation = _timedOperationsInProgress.remove(operationKey);
assert(
operation != null,
'The operation $screenName.$timedOperation cannot be cancelled because it '
'does not exist.',
);
}
// Use this when a synchronous operation can be timed in a callback.
void timeSync(
String screenName,
String timedOperation, {
required void Function() syncOperation,
ScreenAnalyticsMetrics Function()? screenMetricsProvider,
}) {
final startTime = DateTime.now();
try {
syncOperation();
} catch (e, st) {
// Do not send the timing analytic to GA if the operation failed.
_log.warning(
'Could not time sync operation "$timedOperation" '
'because an exception was thrown:\n$e\n$st',
);
rethrow;
}
final endTime = DateTime.now();
final durationMicros =
endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch;
_timing(
screenName,
timedOperation,
durationMicros: durationMicros,
screenMetrics: screenMetricsProvider != null
? screenMetricsProvider()
: null,
);
}
// Use this when an asynchronous operation can be timed in a callback.
Future<void> timeAsync(
String screenName,
String timedOperation, {
required Future<void> Function() asyncOperation,
ScreenAnalyticsMetrics Function()? screenMetricsProvider,
}) async {
final startTime = DateTime.now();
try {
await asyncOperation();
} catch (e, st) {
// Do not send the timing analytic to GA if the operation failed.
_log.warning(
'Could not time async operation "$timedOperation" '
'because an exception was thrown:\n$e\n$st',
);
rethrow;
}
final endTime = DateTime.now();
final durationMicros =
endTime.microsecondsSinceEpoch - startTime.microsecondsSinceEpoch;
_timing(
screenName,
timedOperation,
durationMicros: durationMicros,
screenMetrics: screenMetricsProvider != null
? screenMetricsProvider()
: null,
);
}
void _timing(
String screenName,
String timedOperation, {
required int durationMicros,
ScreenAnalyticsMetrics? screenMetrics,
}) {
_log.fine(
'Event: _timing('
'screenName:$screenName, '
'timedOperation:$timedOperation, '
'durationMicros:$durationMicros)',
);
final gtagEvent = DevToolsAnalyticsEvent._create(
screen: screenName,
eventCategory: gac.timingEvent,
eventLabel: timedOperation,
value: durationMicros,
screenMetrics: screenMetrics,
);
_sendEvent(gtagEvent);
}
/// Sends an analytics event to signal that something in DevTools was selected.
void select(
String screenName,
String selectedItem, {
int value = 0,
bool nonInteraction = false,
ScreenAnalyticsMetrics Function()? screenMetricsProvider,
}) {
_log.fine(
'Event: select('
'screenName:$screenName, '
'selectedItem:$selectedItem, '
'value:$value, '
'nonInteraction:$nonInteraction)',
);
final gtagEvent = DevToolsAnalyticsEvent._create(
screen: screenName,
eventCategory: gac.selectEvent,
eventLabel: selectedItem,
value: value,
nonInteraction: nonInteraction,
screenMetrics: screenMetricsProvider != null
? screenMetricsProvider()
: null,
);
_sendEvent(gtagEvent);
}
/// Sends an analytics event to signal that something in DevTools was viewed.
///
/// Impression events should not signal user interaction like [select].
void impression(
String screenName,
String item, {
ScreenAnalyticsMetrics Function()? screenMetricsProvider,
}) {
_log.fine(
'Event: impression('
'screenName:$screenName, '
'item:$item)',
);
final gtagEvent = DevToolsAnalyticsEvent._create(
screen: screenName,
eventCategory: gac.impressionEvent,
eventLabel: item,
nonInteraction: true,
screenMetrics: screenMetricsProvider != null
? screenMetricsProvider()
: null,
);
_sendEvent(gtagEvent);
}
String? _lastGaError;
/// Reports an error to analytics.
///
/// [errorMessage] is the description of the error.
/// [stackTrace] is the stack trace.
void reportError(
String errorMessage, {
stack_trace.Trace? stackTrace,
bool fatal = false,
}) {
// Don't keep recording same last error.
if (_lastGaError == errorMessage) return;
_lastGaError = errorMessage;
final uaEvent = _uaEventFromDevToolsException(
DevToolsAnalyticsException._create(errorMessage, fatal: fatal),
stackTrace: stackTrace,
);
unawaited(globals.dtdManager.sendAnalyticsEvent(uaEvent));
}
////////////////////////////////////////////////////////////////////////////////
// Utilities to collect all platform and DevTools state for Analytics.
////////////////////////////////////////////////////////////////////////////////
String _userAppType = '';
String _userBuildType = '';
String _userPlatformType = '';
/// MacIntel/Linux/Windows/Android_n
String _devtoolsPlatformType = '';
/// Chrome/n.n.n or Crios/n.n.n
String _devtoolsChrome = '';
/// IDE launched DevTools (VSCode, CLI, ...)
String _ideLaunched = '';
/// The IDE feature that launched DevTools.
///
/// Defaults to [_ideLaunchedCLI] if DevTools was not launched from the IDE.
String _ideLaunchedFeature = '';
/// Flutter tool clientId.
String _flutterClientId = '';
String get userAppType => _userAppType;
set userAppType(String newUserAppType) {
_userAppType = newUserAppType;
}
String get userBuildType => _userBuildType;
set userBuildType(String newUserBuildType) {
_userBuildType = newUserBuildType;
}
String get userPlatformType => _userPlatformType;
set userPlatformType(String newUserPlatformType) {
_userPlatformType = newUserPlatformType;
}
String get ideLaunched => _ideLaunched;
String get ideLaunchedFeature => _ideLaunchedFeature;
set ideLaunchedFeature(String newIdeLaunchedFeature) {
_ideLaunchedFeature = newIdeLaunchedFeature;
}
Completer<void>? _computingDimensionsCompleter;
/// Computes the running application.
void _computeUserApplicationCustomGTagData() {
final connectedApp = globals.serviceConnection.serviceManager.connectedApp!;
assert(connectedApp.isFlutterAppNow != null);
assert(connectedApp.isDartWebAppNow != null);
assert(connectedApp.isProfileBuildNow != null);
const unknownOS = 'unknown';
if (connectedApp.isFlutterAppNow!) {
userPlatformType =
globals.serviceConnection.serviceManager.vm?.operatingSystem ??
unknownOS;
}
if (connectedApp.isFlutterWebAppNow) {
userAppType = _UserAppType.flutterWeb.value;
} else if (connectedApp.isFlutterAppNow!) {
userAppType = _UserAppType.flutter.value;
} else if (connectedApp.isDartWebAppNow!) {
userAppType = _UserAppType.web.value;
} else {
userAppType = _UserAppType.dartCLI.value;
}
userBuildType = connectedApp.isProfileBuildNow!
? _UserBuildType.profile.name
: _UserBuildType.debug.name;
}
/// Computes the DevTools application data.
///
/// Fills in the [_devtoolsPlatformType] and [_devtoolsChrome].
void computeDevToolsCustomData() {
_devtoolsPlatformType = window.navigator.platform.replaceAll(' ', '_');
final appVersion = window.navigator.appVersion;
final splits = appVersion.split(' ');
final len = splits.length;
for (int index = 0; index < len; index++) {
final value = splits[index];
// Chrome or Chrome iOS
if (value.startsWith(_ChromePrefix.chrome.value) ||
value.startsWith(_ChromePrefix.crios.value)) {
_devtoolsChrome = value;
} else if (value.startsWith('Android') && index + 1 < splits.length) {
// appVersion for Android is 'Android n.n.n'
_devtoolsPlatformType =
'$devToolsPlatformTypeAndroid${splits[index + 1]}';
} else if (value == _ChromePrefix.cros.value) {
// Chrome OS will return a platform e.g., CrOS_Linux_x86_64
_devtoolsPlatformType =
'${_ChromePrefix.cros.value}_$_devtoolsPlatformType';
}
}
}
const _ideLaunchedCLI = 'CLI';
/// Look at the query parameters '&ide=' and set values.
void computeDevToolsQueryParams() {
// Default is Command Line launch.
_ideLaunched = _ideLaunchedCLI;
final queryParams = DevToolsQueryParams.load();
final ide = queryParams.ide;
if (ide != null) {
_ideLaunched = ide;
}
final ideFeature = queryParams.ideFeature;
if (ideFeature != null) {
ideLaunchedFeature = ideFeature;
}
}
Future<void> computeFlutterClientId() async {
_flutterClientId = await server.flutterGAClientID();
}
Future<void> setupDimensions() async {
if (_computingDimensionsCompleter != null) {
return _computingDimensionsCompleter!.future;
}
_computingDimensionsCompleter = Completer<void>();
try {
computeDevToolsCustomData();
computeDevToolsQueryParams();
await computeFlutterClientId();
} catch (e, st) {
_log.warning('Failed to compute dimensions', e, st);
} finally {
_computingDimensionsCompleter!.complete();
}
}
void setupUserApplicationDimensions() {
if (globals.serviceConnection.serviceManager.connectedApp == null) {
return;
}
try {
_computeUserApplicationCustomGTagData();
} catch (e, st) {
_log.warning('Failed to compute user application dimensions', e, st);
}
}
Map<String, Object?> generateSurveyQueryParameters() {
const ideKey = 'IDE';
const versionKey = 'Version';
const internalKey = 'Internal';
return {
ideKey: _ideLaunched,
versionKey: devToolsVersion,
internalKey: (!globals.isExternalBuild).toString(),
};
}
void _sendEvent(DevToolsAnalyticsEvent event) {
final uaEvent = _uaEventFromDevToolsEvent(event);
unawaited(globals.dtdManager.sendAnalyticsEvent(uaEvent));
}
ua.Event _uaEventFromDevToolsEvent(DevToolsAnalyticsEvent event) {
// Any dimensions or metrics that have a null value will be removed from
// the event data in the [ua.Event.devtoolsEvent] constructor.
return ua.Event.devtoolsEvent(
screen: event.screen!,
eventCategory: event.eventCategory!,
label: event.eventLabel!,
value: event.value,
userInitiatedInteraction: !event.nonInteraction,
userApp: event.userApp,
userBuild: event.userBuild,
userPlatform: event.userPlatform,
devtoolsPlatform: event.devtoolsPlatform,
devtoolsChrome: event.devtoolsChrome,
devtoolsVersion: event.devtoolsVersion,
ideLaunched: event.ideLaunched,
ideLaunchedFeature: event.ideLaunchedFeature,
isExternalBuild: event.isExternalBuild,
isEmbedded: event.isEmbedded,
isWasm: event.isWasm,
g3Username: event.g3Username,
// Only 25 entries are permitted for GA4 event parameters, but since not
// all of the below metrics will be non-null at the same time, it is okay to
// include all the metrics here. The [ua.Event.devtoolsEvent] constructor
// will remove any entries with a null value from the sent event parameters.
additionalMetrics: _DevToolsEventMetrics(
uiDurationMicros: event.uiDurationMicros,
rasterDurationMicros: event.rasterDurationMicros,
shaderCompilationDurationMicros: event.shaderCompilationDurationMicros,
traceEventCount: event.traceEventCount,
cpuSampleCount: event.cpuSampleCount,
cpuStackDepth: event.cpuStackDepth,
heapDiffObjectsBefore: event.heapDiffObjectsBefore,
heapDiffObjectsAfter: event.heapDiffObjectsAfter,
heapObjectsTotal: event.heapObjectsTotal,
rootSetCount: event.rootSetCount,
rowCount: event.rowCount,
inspectorTreeControllerId: event.inspectorTreeControllerId,
isV2Inspector: event.isV2Inspector,
androidAppId: event.androidAppId,
iosBundleId: event.iosBundleId,
),
);
}
ua.Event _uaEventFromDevToolsException(
DevToolsAnalyticsException exception, {
stack_trace.Trace? stackTrace,
}) {
final stackTraceAsMap = createStackTraceForAnalytics(stackTrace);
// Any data entries that have a null value will be removed from the event data
// in the [ua.Event.exception] constructor.
return ua.Event.exception(
exception: exception.description ?? 'unknown exception',
data: {
'fatal': exception.fatal,
...stackTraceAsMap,
'userApp': exception.userApp,
'userBuild': exception.userBuild,
'userPlatform': exception.userPlatform,
'devtoolsPlatform': exception.devtoolsPlatform,
'devtoolsChrome': exception.devtoolsChrome,
'devtoolsVersion': exception.devtoolsVersion,
'ideLaunched': exception.ideLaunched,
'ideLaunchedFeature': exception.ideLaunchedFeature,
'isExternalBuild': exception.isExternalBuild,
'isEmbedded': exception.isEmbedded,
'isWasm': exception.isWasm,
'g3Username': exception.g3Username,
// Do not include metrics in exceptions because GA4 event parameter are
// limited to 25 entries, and we need to reserve entries for the stack
// trace chunks.
},
);
}
final class _DevToolsEventMetrics extends ua.CustomMetrics {
_DevToolsEventMetrics({
required this.rasterDurationMicros,
required this.shaderCompilationDurationMicros,
required this.traceEventCount,
required this.cpuSampleCount,
required this.cpuStackDepth,
required this.heapDiffObjectsBefore,
required this.heapDiffObjectsAfter,
required this.heapObjectsTotal,
required this.rootSetCount,
required this.rowCount,
required this.inspectorTreeControllerId,
required this.isV2Inspector,
required this.androidAppId,
required this.iosBundleId,
required this.uiDurationMicros,
});
// [PerformanceScreenMetrics]
final int? uiDurationMicros;
final int? rasterDurationMicros;
final int? shaderCompilationDurationMicros;
final int? traceEventCount;
// [ProfilerScreenMetrics]
final int? cpuSampleCount;
final int? cpuStackDepth;
// [MemoryScreenMetrics]
final int? heapDiffObjectsBefore;
final int? heapDiffObjectsAfter;
final int? heapObjectsTotal;
// [InspectorScreenMetrics]
final int? rootSetCount;
final int? rowCount;
final int? inspectorTreeControllerId;
final String? isV2Inspector;
// [DeepLinkScreenMetrics]
final String? androidAppId;
final String? iosBundleId;
@override
Map<String, Object> toMap() => (<String, Object?>{
'uiDurationMicros': uiDurationMicros,
'rasterDurationMicros': rasterDurationMicros,
'shaderCompilationDurationMicros': shaderCompilationDurationMicros,
'traceEventCount': traceEventCount,
'cpuSampleCount': cpuSampleCount,
'cpuStackDepth': cpuStackDepth,
'heapDiffObjectsBefore': heapDiffObjectsBefore,
'heapDiffObjectsAfter': heapDiffObjectsAfter,
'heapObjectsTotal': heapObjectsTotal,
'rootSetCount': rootSetCount,
'rowCount': rowCount,
'inspectorTreeControllerId': inspectorTreeControllerId,
'isV2Inspector': isV2Inspector,
'androidAppId': androidAppId,
'iosBundleId': iosBundleId,
}..removeWhere((key, value) => value == null)).cast<String, Object>();
}