1- namespace PuppeteerSharp
1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . IO ;
4+ using System . Threading . Tasks ;
5+ using PuppeteerSharp . Messaging ;
6+
7+ namespace PuppeteerSharp
28{
39 public class Tracing
410 {
5- private Session client ;
11+ private Session _client ;
12+ private bool _recording ;
13+ private string _path ;
14+ private static readonly List < string > _defaultCategories = new List < string > ( )
15+ {
16+ "-*" ,
17+ "devtools.timeline" ,
18+ "v8.execute" ,
19+ "disabled-by-default-devtools.timeline" ,
20+ "disabled-by-default-devtools.timeline.frame" ,
21+ "toplevel" ,
22+ "blink.console" ,
23+ "blink.user_timing" ,
24+ "latencyInfo" ,
25+ "disabled-by-default-devtools.timeline.stack" ,
26+ "disabled-by-default-v8.cpu_profiler"
27+ } ;
628
729 public Tracing ( Session client )
830 {
9- this . client = client ;
31+ _client = client ;
32+ }
33+
34+ /// <summary>
35+ /// Starts tracing.
36+ /// </summary>
37+ /// <returns>Start task</returns>
38+ /// <param name="options">Tracing options</param>
39+ public async Task StartAsync ( TracingOptions options )
40+ {
41+ if ( _recording )
42+ {
43+ throw new InvalidOperationException ( "Cannot start recording trace while already recording trace." ) ;
44+ }
45+
46+ if ( string . IsNullOrEmpty ( options . Path ) )
47+ {
48+ throw new ArgumentException ( "Must specify a path to write trace file to." ) ;
49+ }
50+
51+
52+ var categories = options . Categories ?? _defaultCategories ;
53+
54+ if ( options . Screenshots )
55+ {
56+ categories . Add ( "disabled-by-default-devtools.screenshot" ) ;
57+ }
58+
59+ _path = options . Path ;
60+ _recording = true ;
61+
62+ await _client . SendAsync ( "Tracing.start" , new
63+ {
64+ transferMode = "ReturnAsStream" ,
65+ categories = string . Join ( ", " , categories )
66+ } ) ;
67+ }
68+
69+ /// <summary>
70+ /// Stops tracing
71+ /// </summary>
72+ /// <returns>Stop task</returns>
73+ public async Task StopAsync ( )
74+ {
75+ var taskWrapper = new TaskCompletionSource < bool > ( ) ;
76+
77+ async void EventHandler ( object sender , TracingCompleteEventArgs e )
78+ {
79+ await ReadStream ( e . Stream , _path ) ;
80+ _client . TracingComplete -= EventHandler ;
81+ taskWrapper . SetResult ( true ) ;
82+ } ;
83+
84+ _client . TracingComplete += EventHandler ;
85+
86+ await _client . SendAsync ( "Tracing.end" ) ;
87+
88+ _recording = false ;
89+
90+ await taskWrapper . Task ;
91+ }
92+
93+ private async Task ReadStream ( string stream , string path )
94+ {
95+ using ( var fs = new StreamWriter ( path ) )
96+ {
97+ bool eof = false ;
98+
99+ while ( ! eof )
100+ {
101+ var response = await _client . SendAsync < IOReadResponse > ( "IO.read" , new
102+ {
103+ handle = stream
104+ } ) ;
105+
106+ eof = response . Eof ;
107+
108+ await fs . WriteAsync ( response . Data ) ;
109+ }
110+ }
111+ await _client . SendAsync ( "IO.close" , new
112+ {
113+ handle = stream
114+ } ) ;
10115 }
11116 }
12117}
0 commit comments