-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
3063 lines (2769 loc) · 88.7 KB
/
main.js
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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ft=javascript ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const { Ci, Cu, components } = require("devtools/sham/chrome");
const Services = require("devtools/sham/services");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
// WARNING I swapped the sync one for the async one here
//const promise = require("resource://devtools/shared/deprecated-sync-thenables.js", {}).Promise;
const promise = require("devtools/sham/promise");
const events = require("sdk/event/core");
const { WebConsoleClient } = require("devtools/shared/webconsole/client");
/*const { DebuggerSocket } = require("devtools/shared/security/socket");*/
/*const Authentication = require("devtools/shared/security/auth");*/
const noop = () => {};
/**
* TODO: Get rid of this API in favor of EventTarget (bug 1042642)
*
* Add simple event notification to a prototype object. Any object that has
* some use for event notifications or the observer pattern in general can be
* augmented with the necessary facilities by passing its prototype to this
* function.
*
* @param aProto object
* The prototype object that will be modified.
*/
function eventSource(aProto) {
/**
* Add a listener to the event source for a given event.
*
* @param aName string
* The event to listen for.
* @param aListener function
* Called when the event is fired. If the same listener
* is added more than once, it will be called once per
* addListener call.
*/
aProto.addListener = function (aName, aListener) {
if (typeof aListener != "function") {
throw TypeError("Listeners must be functions.");
}
if (!this._listeners) {
this._listeners = {};
}
this._getListeners(aName).push(aListener);
};
/**
* Add a listener to the event source for a given event. The
* listener will be removed after it is called for the first time.
*
* @param aName string
* The event to listen for.
* @param aListener function
* Called when the event is fired.
*/
aProto.addOneTimeListener = function (aName, aListener) {
let l = (...args) => {
this.removeListener(aName, l);
aListener.apply(null, args);
};
this.addListener(aName, l);
};
/**
* Remove a listener from the event source previously added with
* addListener().
*
* @param aName string
* The event name used during addListener to add the listener.
* @param aListener function
* The callback to remove. If addListener was called multiple
* times, all instances will be removed.
*/
aProto.removeListener = function (aName, aListener) {
if (!this._listeners || (aListener && !this._listeners[aName])) {
return;
}
if (!aListener) {
this._listeners[aName] = [];
}
else {
this._listeners[aName] =
this._listeners[aName].filter(function (l) { return l != aListener });
}
};
/**
* Returns the listeners for the specified event name. If none are defined it
* initializes an empty list and returns that.
*
* @param aName string
* The event name.
*/
aProto._getListeners = function (aName) {
if (aName in this._listeners) {
return this._listeners[aName];
}
this._listeners[aName] = [];
return this._listeners[aName];
};
/**
* Notify listeners of an event.
*
* @param aName string
* The event to fire.
* @param arguments
* All arguments will be passed along to the listeners,
* including the name argument.
*/
aProto.emit = function () {
if (!this._listeners) {
return;
}
let name = arguments[0];
let listeners = this._getListeners(name).slice(0);
for (let listener of listeners) {
try {
listener.apply(null, arguments);
} catch (e) {
// Prevent a bad listener from interfering with the others.
DevToolsUtils.reportException("notify event '" + name + "'", e);
}
}
}
}
/**
* Set of protocol messages that affect thread state, and the
* state the actor is in after each message.
*/
const ThreadStateTypes = {
"paused": "paused",
"resumed": "attached",
"detached": "detached"
};
/**
* Set of protocol messages that are sent by the server without a prior request
* by the client.
*/
const UnsolicitedNotifications = {
"consoleAPICall": "consoleAPICall",
"eventNotification": "eventNotification",
"fileActivity": "fileActivity",
"lastPrivateContextExited": "lastPrivateContextExited",
"logMessage": "logMessage",
"networkEvent": "networkEvent",
"networkEventUpdate": "networkEventUpdate",
"newGlobal": "newGlobal",
"newScript": "newScript",
"tabDetached": "tabDetached",
"tabListChanged": "tabListChanged",
"reflowActivity": "reflowActivity",
"addonListChanged": "addonListChanged",
"workerListChanged": "workerListChanged",
"tabNavigated": "tabNavigated",
"frameUpdate": "frameUpdate",
"pageError": "pageError",
"documentLoad": "documentLoad",
"enteredFrame": "enteredFrame",
"exitedFrame": "exitedFrame",
"appOpen": "appOpen",
"appClose": "appClose",
"appInstall": "appInstall",
"appUninstall": "appUninstall",
"evaluationResult": "evaluationResult",
};
/**
* Set of pause types that are sent by the server and not as an immediate
* response to a client request.
*/
const UnsolicitedPauses = {
"resumeLimit": "resumeLimit",
"debuggerStatement": "debuggerStatement",
"breakpoint": "breakpoint",
"DOMEvent": "DOMEvent",
"watchpoint": "watchpoint",
"exception": "exception"
};
/**
* Creates a client for the remote debugging protocol server. This client
* provides the means to communicate with the server and exchange the messages
* required by the protocol in a traditional JavaScript API.
*/
const DebuggerClient = exports.DebuggerClient = function (aTransport)
{
this._transport = aTransport;
this._transport.hooks = this;
// Map actor ID to client instance for each actor type.
this._clients = new Map();
this._pendingRequests = new Map();
this._activeRequests = new Map();
this._eventsEnabled = true;
this.traits = {};
this.request = this.request.bind(this);
this.localTransport = this._transport.onOutputStreamReady === undefined;
/*
* As the first thing on the connection, expect a greeting packet from
* the connection's root actor.
*/
this.mainRoot = null;
this.expectReply("root", (aPacket) => {
this.mainRoot = new RootClient(this, aPacket);
this.emit("connected", aPacket.applicationType, aPacket.traits);
});
}
/**
* A declarative helper for defining methods that send requests to the server.
*
* @param aPacketSkeleton
* The form of the packet to send. Can specify fields to be filled from
* the parameters by using the |args| function.
* @param telemetry
* The unique suffix of the telemetry histogram id.
* @param before
* The function to call before sending the packet. Is passed the packet,
* and the return value is used as the new packet. The |this| context is
* the instance of the client object we are defining a method for.
* @param after
* The function to call after the response is received. It is passed the
* response, and the return value is considered the new response that
* will be passed to the callback. The |this| context is the instance of
* the client object we are defining a method for.
*/
DebuggerClient.requester = function (aPacketSkeleton,
{ telemetry, before, after }) {
return DevToolsUtils.makeInfallible(function (...args) {
let histogram, startTime;
if (telemetry) {
let transportType = this._transport.onOutputStreamReady === undefined
? "LOCAL_"
: "REMOTE_";
let histogramId = "DEVTOOLS_DEBUGGER_RDP_"
+ transportType + telemetry + "_MS";
// histogram = Services.telemetry.getHistogramById(histogramId);
startTime = +new Date;
}
let outgoingPacket = {
to: aPacketSkeleton.to || this.actor
};
let maxPosition = -1;
for (let k of Object.keys(aPacketSkeleton)) {
if (aPacketSkeleton[k] instanceof DebuggerClient.Argument) {
let { position } = aPacketSkeleton[k];
outgoingPacket[k] = aPacketSkeleton[k].getArgument(args);
maxPosition = Math.max(position, maxPosition);
} else {
outgoingPacket[k] = aPacketSkeleton[k];
}
}
if (before) {
outgoingPacket = before.call(this, outgoingPacket);
}
return this.request(outgoingPacket, DevToolsUtils.makeInfallible((aResponse) => {
if (after) {
let { from } = aResponse;
aResponse = after.call(this, aResponse);
if (!aResponse.from) {
aResponse.from = from;
}
}
// The callback is always the last parameter.
let thisCallback = args[maxPosition + 1];
if (thisCallback) {
thisCallback(aResponse);
}
if (histogram) {
histogram.add(+new Date - startTime);
}
}, "DebuggerClient.requester request callback"));
}, "DebuggerClient.requester");
};
function args(aPos) {
return new DebuggerClient.Argument(aPos);
}
DebuggerClient.Argument = function (aPosition) {
this.position = aPosition;
};
DebuggerClient.Argument.prototype.getArgument = function (aParams) {
if (!(this.position in aParams)) {
throw new Error("Bad index into params: " + this.position);
}
return aParams[this.position];
};
// Expose these to save callers the trouble of importing DebuggerSocket
DebuggerClient.socketConnect = function(options) {
// Defined here instead of just copying the function to allow lazy-load
return DebuggerSocket.connect(options);
};
DevToolsUtils.defineLazyGetter(DebuggerClient, "Authenticators", () => {
return Authentication.Authenticators;
});
DevToolsUtils.defineLazyGetter(DebuggerClient, "AuthenticationResult", () => {
return Authentication.AuthenticationResult;
});
DebuggerClient.prototype = {
/**
* Connect to the server and start exchanging protocol messages.
*
* @param aOnConnected function
* If specified, will be called when the greeting packet is
* received from the debugging server.
*/
connect: function (aOnConnected) {
let deferred = promise.defer();
this.emit("connect");
// Also emit the event on the |DebuggerServer| object (not on
// the instance), so it's possible to track all instances.
events.emit(DebuggerClient, "connect", this);
this.addOneTimeListener("connected", (aName, aApplicationType, aTraits) => {
this.traits = aTraits;
if (aOnConnected) {
aOnConnected(aApplicationType, aTraits);
}
deferred.resolve();
});
this._transport.ready();
return deferred.promise;
},
/**
* Shut down communication with the debugging server.
*
* @param aOnClosed function
* If specified, will be called when the debugging connection
* has been closed.
*/
close: function (aOnClosed) {
// Disable detach event notifications, because event handlers will be in a
// cleared scope by the time they run.
this._eventsEnabled = false;
let cleanup = () => {
this._transport.close();
this._transport = null;
};
// If the connection is already closed,
// there is no need to detach client
// as we won't be able to send any message.
if (this._closed) {
cleanup();
if (aOnClosed) {
aOnClosed();
}
return;
}
if (aOnClosed) {
this.addOneTimeListener('closed', function (aEvent) {
aOnClosed();
});
}
// Call each client's `detach` method by calling
// lastly registered ones first to give a chance
// to detach child clients first.
let clients = [...this._clients.values()];
this._clients.clear();
const detachClients = () => {
let client = clients.pop();
if (!client) {
// All clients detached.
cleanup();
return;
}
if (client.detach) {
client.detach(detachClients);
return;
}
detachClients();
};
detachClients();
},
/*
* This function exists only to preserve DebuggerClient's interface;
* new code should say 'client.mainRoot.listTabs()'.
*/
listTabs: function (aOnResponse) { return this.mainRoot.listTabs(aOnResponse); },
/*
* This function exists only to preserve DebuggerClient's interface;
* new code should say 'client.mainRoot.listAddons()'.
*/
listAddons: function (aOnResponse) { return this.mainRoot.listAddons(aOnResponse); },
getTab: function (aFilter) { return this.mainRoot.getTab(aFilter); },
/**
* Attach to a tab actor.
*
* @param string aTabActor
* The actor ID for the tab to attach.
* @param function aOnResponse
* Called with the response packet and a TabClient
* (which will be undefined on error).
*/
attachTab: function (aTabActor, aOnResponse = noop) {
if (this._clients.has(aTabActor)) {
let cachedTab = this._clients.get(aTabActor);
let cachedResponse = {
cacheDisabled: cachedTab.cacheDisabled,
javascriptEnabled: cachedTab.javascriptEnabled,
traits: cachedTab.traits,
};
DevToolsUtils.executeSoon(() => aOnResponse(cachedResponse, cachedTab));
return;
}
let packet = {
to: aTabActor,
type: "attach"
};
this.request(packet, (aResponse) => {
let tabClient;
if (!aResponse.error) {
tabClient = new TabClient(this, aResponse);
this.registerClient(tabClient);
}
aOnResponse(aResponse, tabClient);
});
},
attachWorker: function DC_attachWorker(aWorkerActor, aOnResponse = noop) {
let workerClient = this._clients.get(aWorkerActor);
if (workerClient !== undefined) {
DevToolsUtils.executeSoon(() => aOnResponse({
from: workerClient.actor,
type: "attached",
url: workerClient.url
}, workerClient));
return;
}
this.request({ to: aWorkerActor, type: "attach" }, (aResponse) => {
if (aResponse.error) {
aOnResponse(aResponse, null);
return;
}
let workerClient = new WorkerClient(this, aResponse);
this.registerClient(workerClient);
aOnResponse(aResponse, workerClient);
});
},
/**
* Attach to an addon actor.
*
* @param string aAddonActor
* The actor ID for the addon to attach.
* @param function aOnResponse
* Called with the response packet and a AddonClient
* (which will be undefined on error).
*/
attachAddon: function DC_attachAddon(aAddonActor, aOnResponse = noop) {
let packet = {
to: aAddonActor,
type: "attach"
};
this.request(packet, aResponse => {
let addonClient;
if (!aResponse.error) {
addonClient = new AddonClient(this, aAddonActor);
this.registerClient(addonClient);
this.activeAddon = addonClient;
}
aOnResponse(aResponse, addonClient);
});
},
/**
* Attach to a Web Console actor.
*
* @param string aConsoleActor
* The ID for the console actor to attach to.
* @param array aListeners
* The console listeners you want to start.
* @param function aOnResponse
* Called with the response packet and a WebConsoleClient
* instance (which will be undefined on error).
*/
attachConsole:
function (aConsoleActor, aListeners, aOnResponse = noop) {
let packet = {
to: aConsoleActor,
type: "startListeners",
listeners: aListeners,
};
this.request(packet, (aResponse) => {
let consoleClient;
if (!aResponse.error) {
if (this._clients.has(aConsoleActor)) {
consoleClient = this._clients.get(aConsoleActor);
} else {
consoleClient = new WebConsoleClient(this, aResponse);
this.registerClient(consoleClient);
}
}
aOnResponse(aResponse, consoleClient);
});
},
/**
* Attach to a global-scoped thread actor for chrome debugging.
*
* @param string aThreadActor
* The actor ID for the thread to attach.
* @param function aOnResponse
* Called with the response packet and a ThreadClient
* (which will be undefined on error).
* @param object aOptions
* Configuration options.
* - useSourceMaps: whether to use source maps or not.
*/
attachThread: function (aThreadActor, aOnResponse = noop, aOptions={}) {
if (this._clients.has(aThreadActor)) {
DevToolsUtils.executeSoon(() => aOnResponse({}, this._clients.get(aThreadActor)));
return;
}
let packet = {
to: aThreadActor,
type: "attach",
options: aOptions
};
this.request(packet, (aResponse) => {
if (!aResponse.error) {
var threadClient = new ThreadClient(this, aThreadActor);
this.registerClient(threadClient);
}
aOnResponse(aResponse, threadClient);
});
},
/**
* Attach to a trace actor.
*
* @param string aTraceActor
* The actor ID for the tracer to attach.
* @param function aOnResponse
* Called with the response packet and a TraceClient
* (which will be undefined on error).
*/
attachTracer: function (aTraceActor, aOnResponse = noop) {
if (this._clients.has(aTraceActor)) {
DevToolsUtils.executeSoon(() => aOnResponse({}, this._clients.get(aTraceActor)));
return;
}
let packet = {
to: aTraceActor,
type: "attach"
};
this.request(packet, (aResponse) => {
if (!aResponse.error) {
var traceClient = new TraceClient(this, aTraceActor);
this.registerClient(traceClient);
}
aOnResponse(aResponse, traceClient);
});
},
/**
* Fetch the ChromeActor for the main process or ChildProcessActor for a
* a given child process ID.
*
* @param number aId
* The ID for the process to attach (returned by `listProcesses`).
* Connected to the main process if omitted, or is 0.
*/
getProcess: function (aId) {
let packet = {
to: "root",
type: "getProcess"
}
if (typeof(aId) == "number") {
packet.id = aId;
}
return this.request(packet);
},
/**
* Release an object actor.
*
* @param string aActor
* The actor ID to send the request to.
* @param aOnResponse function
* If specified, will be called with the response packet when
* debugging server responds.
*/
release: DebuggerClient.requester({
to: args(0),
type: "release"
}, {
telemetry: "RELEASE"
}),
/**
* Send a request to the debugging server.
*
* @param aRequest object
* A JSON packet to send to the debugging server.
* @param aOnResponse function
* If specified, will be called with the JSON response packet when
* debugging server responds.
* @return Request
* This object emits a number of events to allow you to respond to
* different parts of the request lifecycle.
* It is also a Promise object, with a `then` method, that is resolved
* whenever a JSON or a Bulk response is received; and is rejected
* if the response is an error.
* Note: This return value can be ignored if you are using JSON alone,
* because the callback provided in |aOnResponse| will be bound to the
* "json-reply" event automatically.
*
* Events emitted:
* * json-reply: The server replied with a JSON packet, which is
* passed as event data.
* * bulk-reply: The server replied with bulk data, which you can read
* using the event data object containing:
* * actor: Name of actor that received the packet
* * type: Name of actor's method that was called on receipt
* * length: Size of the data to be read
* * stream: This input stream should only be used directly if you
* can ensure that you will read exactly |length| bytes
* and will not close the stream when reading is complete
* * done: If you use the stream directly (instead of |copyTo|
* below), you must signal completion by resolving /
* rejecting this deferred. If it's rejected, the
* transport will be closed. If an Error is supplied as a
* rejection value, it will be logged via |dumpn|. If you
* do use |copyTo|, resolving is taken care of for you
* when copying completes.
* * copyTo: A helper function for getting your data out of the
* stream that meets the stream handling requirements
* above, and has the following signature:
* @param output nsIAsyncOutputStream
* The stream to copy to.
* @return Promise
* The promise is resolved when copying completes or
* rejected if any (unexpected) errors occur.
* This object also emits "progress" events for each chunk
* that is copied. See stream-utils.js.
*/
request: function (aRequest, aOnResponse) {
if (!this.mainRoot) {
throw Error("Have not yet received a hello packet from the server.");
}
let type = aRequest.type || "";
if (!aRequest.to) {
throw Error("'" + type + "' request packet has no destination.");
}
if (this._closed) {
let msg = "'" + type + "' request packet to " +
"'" + aRequest.to + "' " +
"can't be sent as the connection is closed.";
let resp = { error: "connectionClosed", message: msg };
if (aOnResponse) {
aOnResponse(resp);
}
return promise.reject(resp);
}
let request = new Request(aRequest);
request.format = "json";
request.stack = components.stack;
if (aOnResponse) {
request.on("json-reply", aOnResponse);
}
this._sendOrQueueRequest(request);
// Implement a Promise like API on the returned object
// that resolves/rejects on request response
let deferred = promise.defer();
function listenerJson(resp) {
request.off("json-reply", listenerJson);
request.off("bulk-reply", listenerBulk);
if (resp.error) {
deferred.reject(resp);
} else {
deferred.resolve(resp);
}
}
function listenerBulk(resp) {
request.off("json-reply", listenerJson);
request.off("bulk-reply", listenerBulk);
deferred.resolve(resp);
}
request.on("json-reply", listenerJson);
request.on("bulk-reply", listenerBulk);
request.then = deferred.promise.then.bind(deferred.promise);
return request;
},
/**
* Transmit streaming data via a bulk request.
*
* This method initiates the bulk send process by queuing up the header data.
* The caller receives eventual access to a stream for writing.
*
* Since this opens up more options for how the server might respond (it could
* send back either JSON or bulk data), and the returned Request object emits
* events for different stages of the request process that you may want to
* react to.
*
* @param request Object
* This is modeled after the format of JSON packets above, but does not
* actually contain the data, but is instead just a routing header:
* * actor: Name of actor that will receive the packet
* * type: Name of actor's method that should be called on receipt
* * length: Size of the data to be sent
* @return Request
* This object emits a number of events to allow you to respond to
* different parts of the request lifecycle.
*
* Events emitted:
* * bulk-send-ready: Ready to send bulk data to the server, using the
* event data object containing:
* * stream: This output stream should only be used directly if
* you can ensure that you will write exactly |length|
* bytes and will not close the stream when writing is
* complete
* * done: If you use the stream directly (instead of |copyFrom|
* below), you must signal completion by resolving /
* rejecting this deferred. If it's rejected, the
* transport will be closed. If an Error is supplied as
* a rejection value, it will be logged via |dumpn|. If
* you do use |copyFrom|, resolving is taken care of for
* you when copying completes.
* * copyFrom: A helper function for getting your data onto the
* stream that meets the stream handling requirements
* above, and has the following signature:
* @param input nsIAsyncInputStream
* The stream to copy from.
* @return Promise
* The promise is resolved when copying completes or
* rejected if any (unexpected) errors occur.
* This object also emits "progress" events for each chunk
* that is copied. See stream-utils.js.
* * json-reply: The server replied with a JSON packet, which is
* passed as event data.
* * bulk-reply: The server replied with bulk data, which you can read
* using the event data object containing:
* * actor: Name of actor that received the packet
* * type: Name of actor's method that was called on receipt
* * length: Size of the data to be read
* * stream: This input stream should only be used directly if you
* can ensure that you will read exactly |length| bytes
* and will not close the stream when reading is complete
* * done: If you use the stream directly (instead of |copyTo|
* below), you must signal completion by resolving /
* rejecting this deferred. If it's rejected, the
* transport will be closed. If an Error is supplied as a
* rejection value, it will be logged via |dumpn|. If you
* do use |copyTo|, resolving is taken care of for you
* when copying completes.
* * copyTo: A helper function for getting your data out of the
* stream that meets the stream handling requirements
* above, and has the following signature:
* @param output nsIAsyncOutputStream
* The stream to copy to.
* @return Promise
* The promise is resolved when copying completes or
* rejected if any (unexpected) errors occur.
* This object also emits "progress" events for each chunk
* that is copied. See stream-utils.js.
*/
startBulkRequest: function(request) {
if (!this.traits.bulk) {
throw Error("Server doesn't support bulk transfers");
}
if (!this.mainRoot) {
throw Error("Have not yet received a hello packet from the server.");
}
if (!request.type) {
throw Error("Bulk packet is missing the required 'type' field.");
}
if (!request.actor) {
throw Error("'" + request.type + "' bulk packet has no destination.");
}
if (!request.length) {
throw Error("'" + request.type + "' bulk packet has no length.");
}
request = new Request(request);
request.format = "bulk";
this._sendOrQueueRequest(request);
return request;
},
/**
* If a new request can be sent immediately, do so. Otherwise, queue it.
*/
_sendOrQueueRequest(request) {
let actor = request.actor;
if (!this._activeRequests.has(actor)) {
this._sendRequest(request);
} else {
this._queueRequest(request);
}
},
/**
* Send a request.
* @throws Error if there is already an active request in flight for the same
* actor.
*/
_sendRequest(request) {
let actor = request.actor;
this.expectReply(actor, request);
if (request.format === "json") {
this._transport.send(request.request);
return false;
}
this._transport.startBulkSend(request.request).then((...args) => {
request.emit("bulk-send-ready", ...args);
});
},
/**
* Queue a request to be sent later. Queues are only drained when an in
* flight request to a given actor completes.
*/
_queueRequest(request) {
let actor = request.actor;
let queue = this._pendingRequests.get(actor) || [];
queue.push(request);
this._pendingRequests.set(actor, queue);
},
/**
* Attempt the next request to a given actor (if any).
*/
_attemptNextRequest(actor) {
if (this._activeRequests.has(actor)) {
return;
}
let queue = this._pendingRequests.get(actor);
if (!queue) {
return;
}
let request = queue.shift();
if (queue.length === 0) {
this._pendingRequests.delete(actor);
}
this._sendRequest(request);
},
/**
* Arrange to hand the next reply from |aActor| to the handler bound to
* |aRequest|.
*
* DebuggerClient.prototype.request / startBulkRequest usually takes care of
* establishing the handler for a given request, but in rare cases (well,
* greetings from new root actors, is the only case at the moment) we must be
* prepared for a "reply" that doesn't correspond to any request we sent.
*/
expectReply: function (aActor, aRequest) {
if (this._activeRequests.has(aActor)) {
throw Error("clashing handlers for next reply from " + uneval(aActor));
}
// If a handler is passed directly (as it is with the handler for the root
// actor greeting), create a dummy request to bind this to.
if (typeof aRequest === "function") {
let handler = aRequest;
aRequest = new Request();
aRequest.on("json-reply", handler);
}
this._activeRequests.set(aActor, aRequest);
},
// Transport hooks.
/**
* Called by DebuggerTransport to dispatch incoming packets as appropriate.
*
* @param aPacket object
* The incoming packet.
*/
onPacket: function (aPacket) {
if (!aPacket.from) {
DevToolsUtils.reportException(
"onPacket",
new Error("Server did not specify an actor, dropping packet: " +
JSON.stringify(aPacket)));
return;
}
// If we have a registered Front for this actor, let it handle the packet
// and skip all the rest of this unpleasantness.
let front = this.getActor(aPacket.from);
if (front) {
front.onPacket(aPacket);
return;
}
if (this._clients.has(aPacket.from) && aPacket.type) {
let client = this._clients.get(aPacket.from);
let type = aPacket.type;
if (client.events.indexOf(type) != -1) {
client.emit(type, aPacket);
// we ignore the rest, as the client is expected to handle this packet.
return;
}
}
let activeRequest;
// See if we have a handler function waiting for a reply from this
// actor. (Don't count unsolicited notifications or pauses as
// replies.)
if (this._activeRequests.has(aPacket.from) &&
!(aPacket.type in UnsolicitedNotifications) &&
!(aPacket.type == ThreadStateTypes.paused &&
aPacket.why.type in UnsolicitedPauses)) {
activeRequest = this._activeRequests.get(aPacket.from);
this._activeRequests.delete(aPacket.from);
}
// If there is a subsequent request for the same actor, hand it off to the
// transport. Delivery of packets on the other end is always async, even
// in the local transport case.
this._attemptNextRequest(aPacket.from);
// Packets that indicate thread state changes get special treatment.
if (aPacket.type in ThreadStateTypes &&
this._clients.has(aPacket.from) &&
typeof this._clients.get(aPacket.from)._onThreadState == "function") {
this._clients.get(aPacket.from)._onThreadState(aPacket);
}
// TODO: Bug 1151156 - Remove once Gecko 40 is on b2g-stable.
if (!this.traits.noNeedToFakeResumptionOnNavigation) {
// On navigation the server resumes, so the client must resume as well.
// We achieve that by generating a fake resumption packet that triggers
// the client's thread state change listeners.
if (aPacket.type == UnsolicitedNotifications.tabNavigated &&
this._clients.has(aPacket.from) &&
this._clients.get(aPacket.from).thread) {
let thread = this._clients.get(aPacket.from).thread;
let resumption = { from: thread._actor, type: "resumed" };
thread._onThreadState(resumption);
}
}
// Only try to notify listeners on events, not responses to requests
// that lack a packet type.
if (aPacket.type) {
this.emit(aPacket.type, aPacket);
}
if (activeRequest) {