forked from mozilla/libdweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
929 lines (836 loc) · 23.1 KB
/
router.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
// @flow
/*::
import { Components } from "gecko"
import type {
nsresult,
nsWebProgressState,
nsIIDRef,
nsIFactory,
nsIStreamListener,
nsIInterfaceRequestor,
nsILoadGroup,
nsLoadFlags,
nsILoadInfo,
nsIURL,
nsIURI,
nsIProtocolHandler,
nsIRequest,
nsIChannel,
nsISupports,
nsITransportSecurityInfo,
nsIChannelEventSink,
nsIMessageListener,
nsIMessageSender,
nsIMessageBroadcaster,
nsIMessageListenerManager,
nsIProgressEventSink
} from "gecko"
*/
const EXPORTED_SYMBOLS = ["Supervisor", "Agent"]
const debug = true
const {
classes: Cc,
interfaces: Ci,
utils: Cu,
results: Cr,
manager: Cm
} = Components
const { ppmm, cpmm, mm, appinfo } = Cu.import(
"resource://gre/modules/Services.jsm",
{}
).Services
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm", {})
const { setTimeout } = Cu.import("resource://gre/modules/Timer.jsm", {})
const { console } = Cu.import("resource://gre/modules/Console.jsm", {})
const PR_UINT32_MAX = 0xffffffff
const { generateUUID } = Cc["@mozilla.org/uuid-generator;1"].getService(
Ci.nsIUUIDGenerator
)
const contentSecManager = Cc[
"@mozilla.org/contentsecuritymanager;1"
].getService(Ci.nsIContentSecurityManager)
const isParent = appinfo.processType === appinfo.PROCESS_TYPE_DEFAULT
const { ID } = Components
const componentRegistrar = Cm.QueryInterface(Ci.nsIComponentRegistrar)
const pid = `@${appinfo.processType}#${appinfo.processID}`
const getFactoryByCID = cid => Cm.getClassObject(cid, Ci.nsIFactory)
const getCIDByContractID = contractID =>
componentRegistrar.contractIDToCID(contractID)
const getContractIDByScheme = scheme =>
`@mozilla.org/network/protocol;1?name=${scheme}`
const getCIDByScheme = scheme =>
getCIDByContractID(getContractIDByScheme(scheme)) || null
const getFactoryByProtocolScheme = scheme => {
const cid = getCIDByScheme(scheme)
return cid == null ? null : getFactoryByCID(cid)
}
const unregisterProtocol = scheme => {
const cid = getCIDByScheme(scheme)
const factory = cid && getFactoryByCID(cid)
if (cid && factory) {
componentRegistrar.unregisterFactory(cid, factory)
}
}
const isContractIDRegistered = contractID =>
componentRegistrar.isContractIDRegistered(contractID)
const isRegisteredProtocol = scheme =>
isContractIDRegistered(getContractIDByScheme(scheme))
const registerProtocol = ({ scheme, uuid }, handler) => {
const contractID = getContractIDByScheme(scheme)
if (isContractIDRegistered(contractID)) {
unregisterProtocol(scheme)
}
const cid = new ID(uuid)
const description = `${scheme} protocol handler`
const factory = new Factory(new ProtocolHandler(scheme, handler))
componentRegistrar.registerFactory(cid, description, contractID, factory)
debug &&
console.log(
`registerFactory${pid}`,
cid.toString(),
contractID,
factory.instance.scheme,
isContractIDRegistered(contractID)
)
}
const Channel$QueryInterface = XPCOMUtils.generateQI([
Ci.nsIChannel,
Ci.nsIRequest
])
const LOAD_NORMAL = 0
const IDLE = 0
const ACTIVE = 1
const PAUSED = 2
const CANCELED = 3
const CLOSED = 4
const FAILED = 5
const abort = {}
const wait = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms))
const createDict = /*::<a>*/ () /*: { [string]: a } */ => {
const dict /*: Object */ = Object.create(null)
return dict
}
/*::
type ReadyState =
| typeof IDLE
| typeof ACTIVE
| typeof PAUSED
| typeof CANCELED
| typeof CLOSED
| typeof FAILED
export type RequestStatus =
| typeof Cr.NS_OK
| typeof Cr.NS_BASE_STREAM_WOULD_BLOCK
| typeof Cr.NS_BINDING_ABORTED
*/
class TransportSecurityInfo /*::implements nsITransportSecurityInfo*/ {
/*::
securityState:nsWebProgressState
shortSecurityDescription:string
errorCode:nsresult
errorMessage:string
QueryInterface:*
SSLStatus:*
state:string
*/
constructor() {
this.state = "secure"
this.securityState = Ci.nsIWebProgressListener.STATE_IS_SECURE
this.errorCode = Cr.NS_OK
this.shortSecurityDescription = "Content Addressed"
this.QueryInterface = XPCOMUtils.generateQI([
Ci.nsITransportSecurityInfo,
Ci.nsISSLStatusProvider
])
this.SSLStatus = {
cipherSuite: "TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",
// TLS_VERSION_1_2
protocolVersion: 3,
isDomainMismatch: false,
isNotValidAtThisTime: true,
serverCert: {
subjectName: "Content Addressing",
displayName: "Content Addressing",
certType: Ci.nsIX509Cert.CA_CERT,
isSelfSigned: true,
validity: {}
}
}
}
}
const MAX_UNKNOWN = 0xffffffffffffffff
class Channel /*::implements nsIChannel, nsIRequest*/ {
/*::
URI: nsIURI
scheme: string
url: string
originalURI: nsIURI
loadInfo: null | nsILoadInfo
contentCharset: ?string
contentLength: number
contentType: ?string
byteOffset: number
requestID: string
owner: nsISupports<*> | null
securityInfo: nsITransportSecurityInfo | null
loadFlags: nsLoadFlags
loadGroup: nsILoadGroup
name: string
status: nsresult
readyState: ReadyState
QueryInterface: typeof Channel$QueryInterface
contentDisposition: number
contentDispositionFilename: string
contentDispositionHeader: string
notificationCallbacks: nsIInterfaceRequestor<nsIProgressEventSink> | null;
listener: ?nsIStreamListener
context: ?nsISupports<mixed>
handler: RequestHandler
*/
constructor(
uri /*: nsIURI */,
loadInfo /*: null | nsILoadInfo */,
requestID /*: string */,
handler /*: RequestHandler */
) {
this.URI = uri
this.url = uri.spec
this.scheme = uri.scheme
this.originalURI = uri
this.loadInfo = loadInfo
this.originalURI = uri
this.contentCharset = "utf-8"
this.contentLength = -1
this.contentType = "application/x-unknown-content-type"
this.contentDispositionFilename = ""
this.contentDispositionHeader = ""
this.byteOffset = 0
this.requestID = requestID
this.owner = null
this.securityInfo = new TransportSecurityInfo()
this.notificationCallbacks = null
this.loadFlags = Ci.nsIRequest.LOAD_NORMAL
this.name = uri.spec
this.status = Cr.NS_ERROR_NOT_INITIALIZED
this.readyState = IDLE
this.QueryInterface = Channel$QueryInterface
this.handler = handler
}
toJSON() {
return {
scheme: this.URI.scheme,
url: this.URI.spec,
readyState: this.readyState,
status: this.status,
contentType: this.contentType,
byteOffset: this.byteOffset,
contentLength: this.contentLength
}
}
open2() {
// throws an error if security checks fail
contentSecManager.performSecurityCheck(this, null)
return this.open()
}
open() {
throw Cr.NS_BASE_STREAM_WOULD_BLOCK
}
asyncOpen2(listener) {
// throws an error if security checks fail
var outListener = contentSecManager.performSecurityCheck(this, listener)
return this.asyncOpen(outListener, null)
}
asyncOpen(listener, context) {
// TODO: Make sure that we report status updates
// https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIProgressEventSink
debug && console.log(`asyncOpen${pid} ${JSON.stringify(this)}`)
switch (this.readyState) {
case IDLE: {
this.listener = listener
this.context = context
this.status = Cr.NS_OK
this.loadGroup.addRequest(this, context)
return this.handler.request(this)
}
default: {
throw this.status
}
}
}
isPending() {
switch (this.readyState) {
case ACTIVE:
case PAUSED: {
return true
}
default: {
return false
}
}
}
cancel(status = Cr.NS_BINDING_ABORTED) {
debug && console.log(`cancel(${status})${pid} ${JSON.stringify(this)}`)
const { handler, readyState } = this
if (handler) {
switch (readyState) {
case ACTIVE:
case PAUSED: {
this.setStatus(status)
return handler.updateRequest(this, Cr.NS_BINDING_ABORTED)
}
default: {
throw this.status
}
}
}
}
suspend() {
debug && console.log(`suspend${pid} ${JSON.stringify(this)}`)
switch (this.readyState) {
case ACTIVE: {
this.readyState = PAUSED
return this.handler.updateRequest(this, Cr.NS_BASE_STREAM_WOULD_BLOCK)
}
case PAUSED: {
return void this
}
default: {
throw this.status
}
}
}
resume() {
debug && console.log(`resume${pid} ${JSON.stringify(this)}`)
switch (this.readyState) {
case ACTIVE: {
return void this
}
case PAUSED: {
this.readyState = ACTIVE
return this.handler.updateRequest(this, Cr.NS_OK)
}
default: {
throw this.status
}
}
}
setStatus(status) {
switch (status) {
case Cr.NS_OK:
case Cr.NS_BINDING_ABORTED: {
this.readyState = CANCELED
this.status = Cr.NS_BINDING_ABORTED
return this
}
default: {
this.readyState = FAILED
this.status = status
return this
}
}
}
head({ contentType, contentLength, contentCharset }) {
debug &&
console.log(
`head${pid} ${JSON.stringify({
contentType,
contentLength,
contentCharset
})}`
)
if (contentType) {
this.contentType = contentType
}
if (contentLength) {
this.contentLength = contentLength
}
if (contentCharset) {
this.contentCharset = contentCharset
}
this.status = Cr.NS_OK
this.readyState = ACTIVE
const { listener, context } = this
this.byteOffset = 0
try {
listener && listener.onStartRequest(this, context)
} catch (_) {
console.error(_)
}
}
body({ content }) {
const stream = Cc[
"@mozilla.org/io/arraybuffer-input-stream;1"
].createInstance(Ci.nsIArrayBufferInputStream)
const { byteLength } = content
stream.setData(content, 0, byteLength)
debug &&
console.log(
`body${pid} ${JSON.stringify(
this
)} ${stream.available()} ${byteLength} ${content.toString()} `
)
const { listener, context } = this
listener && listener.onDataAvailable(this, context, stream, 0, byteLength)
this.byteOffset += byteLength
}
end(_) {
this.readyState = CLOSED
this.contentLength = this.byteOffset
debug && console.log(`end${pid} ${JSON.stringify(this)}`)
this.close()
}
abort() {
debug && console.log(`abort${pid} ${JSON.stringify(this)}`)
this.readyState = CANCELED
this.status = Cr.NS_BINDING_ABORTED
this.close()
}
close() {
const { listener, context, status } = this
debug && console.log(`close${pid} ${JSON.stringify(this)}`)
delete this.listener
delete this.context
delete this.handler
try {
listener && listener.onStopRequest(this, context, status)
this.loadGroup.removeRequest(this, context, status)
} catch (_) {
debug && console.error(`Failed onStopRequest${pid} ${_}`)
}
}
}
class ProtocolHandler /*::implements nsIProtocolHandler*/ {
/*::
scheme: string
defaultPort: number
handler: RequestHandler
protocolFlags: number
*/
constructor(scheme, handler) {
this.scheme = scheme
this.defaultPort = -1
this.handler = handler
this.protocolFlags =
Ci.nsIProtocolHandler.URI_STD |
Ci.nsIProtocolHandler.URI_LOADABLE_BY_ANYONE |
Ci.nsIProtocolHandler.URI_IS_POTENTIALLY_TRUSTWORTHY
}
toJSON() {
return {
scheme: this.scheme,
defaultPort: this.defaultPort,
protocolFlags: this.protocolFlags
}
}
allowPort(port, scheme) {
return false
}
newURI(spec, charset, baseURI) {
debug &&
console.log(`newURI${pid} ${spec} ${String(baseURI && baseURI.spec)}`)
try {
const url = Cc["@mozilla.org/network/standard-url-mutator;1"]
.createInstance(Ci.nsIStandardURLMutator)
.init(
Ci.nsIStandardURL.URLTYPE_AUTHORITY,
this.defaultPort,
spec,
charset,
baseURI
)
.finalize()
return url
} catch (_) {
const resolvedSpec = baseURI == null ? spec : baseURI.resolve(spec)
return Cc["@mozilla.org/network/simple-uri-mutator;1"]
.createInstance(Ci.nsIURIMutator)
.setSpec(resolvedSpec)
.finalize()
}
}
newChannel(uri /*: nsIURI */) {
debug &&
console.log(`newChannel(${uri.spec})${pid} ${JSON.stringify(this)}`)
return this.newChannel2(uri, null)
}
newChannel2(uri /*: nsIURI */, loadInfo /*: nsILoadInfo | null */) {
debug &&
console.log(`newChannel2(${uri.spec})${pid} ${JSON.stringify(this)}`)
return this.handler.channel(uri, loadInfo)
}
QueryInterface(iid) {
if (iid.equals(Ci.nsIProtocolHandler) || iid.equals(Ci.nsISupports)) {
return this
}
throw Cr.NS_ERROR_NO_INTERFACE
}
}
class Factory /*::implements nsIFactory<nsIProtocolHandler>*/ {
/*::
instance: nsIProtocolHandler
*/
constructor(instance /*: nsIProtocolHandler */) {
this.instance = instance
}
createInstance(
outer /*: null | nsISupports<nsIProtocolHandler> */,
iid /*: nsIIDRef<nsIProtocolHandler> */
) /*: nsIProtocolHandler */ {
if (outer != null) {
throw Cr.NS_ERROR_NO_AGGREGATION
}
return this.instance
}
lockFactory(lock /*: boolean */) /*: void */ {
throw Cr.NS_ERROR_NOT_IMPLEMENTED
}
QueryInterface(
iid /*: nsIIDRef<nsIFactory<nsIProtocolHandler>> */
) /*: nsIFactory<nsIProtocolHandler> */ {
if (iid.equals(Ci.nsISupports) || iid.equals(Ci.nsIFactory)) {
return this
}
console.log(`!!! Factory.QueryInterface ${iid.name} ${iid.number}\n`)
throw Cr.NS_ERROR_NO_INTERFACE
}
}
const PROTOCOLS = `libdweb:protocol:protocols`
const REGISTER = `libdweb:protocol:register`
const INSTALL = `libdweb:protocol:install`
const REQUEST = `libdweb:protocol:request`
const REQUEST_UPDATE = `libdweb:protocol:request:update`
const RESPONSE_HEAD = `libdweb:protocol:response:head`
const RESPONSE_BODY = `libdweb:protocol:response:body`
const RESPONSE_END = `libdweb:protocol:response:end`
const AGENT_INBOX = `libdweb:protocol:agent:inbox`
const AGENT_OUTBOX = `libdweb:protocol:agent:outbox`
const HANDLER_INBOX = `libdweb:protocol:handler:inbox`
const HANDLER_OUTBOX = `libdweb:protocol:handler:outbox`
class RequestHandler {
/*::
requestID: number
+requests: { [string]: Channel }
+pid: string
QueryInterface: *
*/
constructor() {
this.requestID = 0
this.requests = createDict()
this.pid = `Handler${pid}`
this.QueryInterface = XPCOMUtils.generateQI([Ci.nsIMessageListener])
}
channel(
url /*: nsIURI */,
loadInfo /*: null | nsILoadInfo */
) /*: Channel */ {
const { scheme } = url
const requestID = `${scheme}:${++this.requestID}:${this.pid}`
const request = new Channel(url, loadInfo, requestID, this)
this.requests[requestID] = request
return request
}
request(channel /*: Channel */) {}
updateRequest(channel /*: Channel */, status /*: RequestStatus */) {}
}
/*::
export type Register = {
type: "register",
scheme: string,
uuid: string
}
export type Unregister = {
type: "unregister",
scheme: string,
uuid: string
}
export type Terminate = {
type: "terminate"
}
export type Install = {
type: "install",
scheme: string
}
export type Head = {
type: "head",
requestID: string,
contentType?: string,
contentLength?: number,
contentCharset?: string,
contentDispositionFilename?: string,
contentDispositionHeader?:string
}
export type Body = {
type: "body",
requestID: string,
content: ArrayBuffer
}
export type End = {
type: "end",
requestID: string
}
export type Response = Head | Body | End
export type HandlerOutbox = {
name: "libdweb:protocol:handler:outbox",
data: Install | Response,
target: { messageManager: Out<HandlerInbox> }
}
export type HandlerInbox = {
name: "libdweb:protocol:handler:inbox",
data: Request | RequestUpdate,
target: Out<HandlerOutbox>
}
export type ProtocolSpec = { scheme: string, uuid: string }
type Request = {
type: "request",
requestID: string,
url: string,
scheme: string,
status?: void
}
type RequestUpdate = {
type: "requestUpdate",
requestID: string,
scheme: string,
status: RequestStatus
}
export type AgentInbox = {
name: "libdweb:protocol:agent:inbox",
data: Register | Unregister | Terminate | Response
}
export type AgentOutbox = {
name: "libdweb:protocol:agent:outbox",
data: Request | RequestUpdate,
target: nsIMessageSender<AgentInbox>
}
export type Inn<a> = nsIMessageListenerManager<a>
export type Out<a> = nsIMessageSender<a>
*/
class Supervisor extends RequestHandler {
/*::
+protocols: { [string]: ProtocolSpec }
+handlers: { [string]: Out<HandlerInbox> }
+agents: { [string]: Out<AgentInbox> }
+agentsPort: nsIMessageBroadcaster<*, AgentInbox>
*/
constructor() {
super()
this.protocols = createDict()
this.handlers = createDict()
this.agents = createDict()
this.pid = `Supervisor${pid}`
this.agentsPort = ppmm
}
receiveMessage(message /*: AgentOutbox | HandlerOutbox */) {
debug &&
console.log(
`Receive message:${message.name} at ${this.pid} ${JSON.stringify(
message.data
)}`,
message.target
)
switch (message.name) {
case AGENT_OUTBOX:
return this.receiveAgentMessage(message)
case HANDLER_OUTBOX:
return this.receiveHandlerMessage(message)
}
}
receiveAgentMessage({ data, target } /*:AgentOutbox*/) {
const { handlers, agents, pid } = this
const { scheme, requestID } = data
const handler = handlers[scheme]
if (handler) {
debug &&
console.log(
`-> request${this.pid} ${JSON.stringify(data)}`,
target,
handler
)
agents[requestID] = target
handler.sendAsyncMessage(HANDLER_INBOX, data)
}
}
receiveHandlerMessage({ data, target } /*:HandlerOutbox*/) {
switch (data.type) {
case "install":
return this.register(data.scheme, target.messageManager)
default:
return this.forwardResponse(data)
}
}
forwardResponse(response /*:Response*/) {
debug && console.log(`-> response${this.pid} ${JSON.stringify(response)}`)
const { agents } = this
const { requestID } = response
const agent = agents[requestID]
if (agent) {
if (response.type === "end") {
delete agents[requestID]
}
agent.sendAsyncMessage(AGENT_INBOX, response)
}
}
register(scheme /*: string */, handler /*: Out<HandlerInbox> */) {
const { protocols, handlers } = this
if (handlers[scheme]) {
handlers[scheme] = handler
} else {
const uuid = generateUUID().toString()
const protocol = { type: "register", scheme, uuid }
protocols[scheme] = protocol
handlers[scheme] = handler
registerProtocol(protocol, this)
this.agentsPort.broadcastAsyncMessage(AGENT_INBOX, protocol)
}
}
unregister({ scheme, uuid } /*: ProtocolSpec*/) {
const { protocols, handlers } = this
if (protocols[scheme] != null) {
delete protocols[scheme]
delete handlers[scheme]
const unregister = { type: "unregister", scheme, uuid }
unregisterProtocol(scheme)
this.agentsPort.broadcastAsyncMessage(AGENT_INBOX, unregister)
}
}
terminate() {
debug && console.log(`Terminate ${this.pid}`)
const { protocols, requests } = this
this.agentsPort.broadcastAsyncMessage(AGENT_INBOX, { type: "terminate" })
ppmm.removeDelayedProcessScript(Components.stack.filename)
mm.removeMessageListener(HANDLER_OUTBOX, this)
ppmm.removeMessageListener(AGENT_INBOX, this)
delete this.request
delete this.protocols
delete this.agents
delete this.handlers
for (const scheme in protocols) {
unregisterProtocol(scheme)
}
}
static new() {
const self = new this()
debug && console.log(`new ${self.pid}`)
ppmm.initialProcessData[PROTOCOLS] = self.protocols
debug &&
console.log(`initialProcessData`, ppmm.initialProcessData[PROTOCOLS])
ppmm.loadProcessScript(Components.stack.filename, true)
mm.addMessageListener(HANDLER_OUTBOX, self)
ppmm.addMessageListener(AGENT_OUTBOX, self)
return self
}
}
class Agent extends RequestHandler {
/*::
outbox: Out<AgentOutbox>
inbox: Inn<AgentInbox>
protocols: {[string]:ProtocolSpec}
*/
constructor() {
super()
this.pid = `Agent${pid}`
this.requestID = 0
this.outbox = cpmm
this.inbox = cpmm
this.protocols = createDict()
}
register(protocol /*: ProtocolSpec */) {
const { protocols } = this
if (protocols[protocol.scheme] == null) {
protocols[protocol.scheme] = protocol
registerProtocol(protocol, this)
}
}
unregister(protocol /*: ProtocolSpec*/) {
const { protocols } = this
if (protocols[protocol.scheme] != null) {
delete protocols[protocol.scheme]
unregisterProtocol(protocol.scheme)
}
}
request(channel /*: Channel */) {
const { url, scheme, requestID } = channel
debug && console.log(`request${this.pid} ${JSON.stringify(channel)}`)
this.outbox.sendAsyncMessage(AGENT_OUTBOX, {
type: "request",
requestID,
url,
scheme
})
}
updateRequest(channel /*: Channel */, status /*: RequestStatus */) {
const { url, scheme, requestID } = channel
debug && console.log(`request${this.pid} ${JSON.stringify(channel)}`)
this.outbox.sendAsyncMessage(AGENT_OUTBOX, {
type: "requestUpdate",
requestID,
status,
url,
scheme
})
}
head(head /*:Head*/) {
this.requests[head.requestID].head(head)
}
body(body /*:Body*/) {
this.requests[body.requestID].body(body)
}
end(end /*:End*/) {
this.requests[end.requestID].end(end)
}
receiveMessage({ data } /*: AgentInbox */) {
debug &&
console.log(`Receive message at ${this.pid} ${JSON.stringify(data)}`)
switch (data.type) {
case "terminate":
return this.terminate()
case "unregister":
return this.unregister(data)
case "register":
return this.register(data)
case "head":
return this.head(data)
case "body":
return this.body(data)
case "end":
return this.end(data)
}
}
terminate() {
debug && console.log(`Terminate ${this.pid}`)
const { protocols, requests } = this
this.inbox.removeMessageListener(AGENT_INBOX, this)
delete this.protocols
delete this.outbox
delete this.inbox
for (const requestID in requests) {
const request = requests[requestID]
request.abort()
}
for (const scheme in protocols) {
unregisterProtocol(scheme)
}
}
static new() {
const self = new Agent()
debug && console.log(`new ${self.pid}`)
self.inbox.addMessageListener(AGENT_INBOX, self)
const protocols /*: { [string]: ProtocolSpec } */ =
cpmm.initialProcessData[PROTOCOLS]
console.log(`Initial protocols ${JSON.stringify(protocols)}`)
if (protocols) {
for (let scheme in protocols) {
self.register(protocols[scheme])
}
}
}
}
if (!isParent) {
Agent.new()
}
const self /*:window*/ = this
self.Supervisor = Supervisor
self.Agent = Agent
/*::
export {Supervisor, Agent}
*/