Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(43)

Side by Side Diff: lib/isolate/frog/isolateimpl.dart

Issue 9422019: isolates refactor: this change introduces 'dart:isolate' as a library. This is a (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: '' Created 8 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 #library("isolateimpl");
6
7 #import("dart:isolate");
8 #import("messages.dart", prefix: 'messages');
9 #import("ports.dart", prefix: 'ports');
10 #native("natives.js");
11
12 /** Implementation of [Isolate2]. */
13 class Isolate2Impl implements Isolate2 {
14 SendPort sendPort;
15
16 Isolate2Impl(this.sendPort);
17 }
18
5 /** 19 /**
6 * A native object that is shared across isolates. This object is visible to all 20 * A native object that is shared across isolates. This object is visible to all
7 * isolates running on the same worker (either UI or background web worker). 21 * isolates running on the same worker (either UI or background web worker).
8 * 22 *
9 * This is code that is intended to 'escape' the isolate boundaries in order to 23 * This is code that is intended to 'escape' the isolate boundaries in order to
10 * implement the semantics of friendly isolates in JavaScript. Without this we 24 * implement the semantics of isolates in JavaScript. Without this we would have
11 * would have been forced to implement more code (including the top-level event 25 * been forced to implement more code (including the top-level event loop) in
12 * loop) in JavaScript itself. 26 * JavaScript itself.
13 */ 27 */
14 GlobalState get _globalState() native "return \$globalState;"; 28 GlobalState get globalState() native "return \$globalState;";
15 set _globalState(GlobalState val) native "\$globalState = val;"; 29 set globalState(GlobalState val) native "\$globalState = val;";
16 30
17 /** 31 void fillStatics(context) native @"""
18 * Wrapper that takes the dart entry point and runs it within an isolate. The
19 * frog compiler will inject a call of the form [: startRootIsolate(main); :]
20 * when it determines that this wrapping is needed. For single-isolate
21 * applications (e.g. hello world), this call is not emitted.
22 */
23 void startRootIsolate(entry) {
24 _globalState = new GlobalState();
25
26 // Don't start the main loop again, if we are in a worker.
27 if (_globalState.isWorker) return;
28 final rootContext = new IsolateContext();
29 _globalState.rootContext = rootContext;
30 _fillStatics(rootContext);
31
32 // BUG(5151491): Setting currentContext should not be necessary, but
33 // because closures passed to the DOM as event handlers do not bind their
34 // isolate automatically we try to give them a reasonable context to live in
35 // by having a "default" isolate (the first one created).
36 _globalState.currentContext = rootContext;
37
38 rootContext.eval(entry);
39 _globalState.topEventLoop.run();
40 }
41
42 void _fillStatics(context) native @"""
43 $globals = context.isolateStatics; 32 $globals = context.isolateStatics;
44 $static_init(); 33 $static_init();
45 """; 34 """;
46 35
47 /** Global state associated with the current worker. See [_globalState]. */ 36 /** Global state associated with the current worker. See [globalState]. */
48 // TODO(sigmund): split in multiple classes: global, thread, main-worker states? 37 // TODO(sigmund): split in multiple classes: global, thread, main-worker states?
49 class GlobalState { 38 class GlobalState {
50 39
51 /** Next available isolate id. */ 40 /** Next available isolate id. */
52 int nextIsolateId = 0; 41 int nextIsolateId = 0;
53 42
54 /** Worker id associated with this worker. */ 43 /** Worker id associated with this worker. */
55 int currentWorkerId = 0; 44 int currentWorkerId = 0;
56 45
57 /** 46 /**
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
95 * Registry of isolates. Isolates must be registered if, and only if, receive 84 * Registry of isolates. Isolates must be registered if, and only if, receive
96 * ports are alive. Normally no open receive-ports means that the isolate is 85 * ports are alive. Normally no open receive-ports means that the isolate is
97 * dead, but DOM callbacks could resurrect it. 86 * dead, but DOM callbacks could resurrect it.
98 */ 87 */
99 Map<int, IsolateContext> isolates; 88 Map<int, IsolateContext> isolates;
100 89
101 /** Reference to the main worker. */ 90 /** Reference to the main worker. */
102 MainWorker mainWorker; 91 MainWorker mainWorker;
103 92
104 /** Registry of active workers. Only used in the main worker. */ 93 /** Registry of active workers. Only used in the main worker. */
105 Map<int, var> workers; 94 Map<int, Dynamic> workers;
106 95
107 GlobalState() { 96 GlobalState() {
108 topEventLoop = new EventLoop(); 97 topEventLoop = new EventLoop();
109 isolates = {}; 98 isolates = {};
110 workers = {}; 99 workers = {};
111 mainWorker = new MainWorker(); 100 mainWorker = new MainWorker();
112 _nativeInit(); 101 _nativeInit();
113 } 102 }
114 103
115 void _nativeInit() native @""" 104 void _nativeInit() native @"""
(...skipping 14 matching lines...) Expand all
130 } 119 }
131 120
132 /** 121 /**
133 * Close the worker running this code, called when there is nothing else to 122 * Close the worker running this code, called when there is nothing else to
134 * run. 123 * run.
135 */ 124 */
136 void closeWorker() { 125 void closeWorker() {
137 if (isWorker) { 126 if (isWorker) {
138 if (!isolates.isEmpty()) return; 127 if (!isolates.isEmpty()) return;
139 mainWorker.postMessage( 128 mainWorker.postMessage(
140 _serializeMessage({'command': 'close'})); 129 messages.serialize({'command': 'close'}));
141 } else if (isolates.containsKey(rootContext.id) && workers.isEmpty() && 130 } else if (isolates.containsKey(rootContext.id) && workers.isEmpty() &&
142 !supportsWorkers && !inWindow) { 131 !supportsWorkers && !inWindow) {
143 // This should only trigger when running on the command-line. 132 // This should only trigger when running on the command-line.
144 // We don't want this check to execute in the browser where the isolate 133 // We don't want this check to execute in the browser where the isolate
145 // might still be alive due to DOM callbacks. 134 // might still be alive due to DOM callbacks.
146 throw new Exception("Program exited with open ReceivePorts."); 135 throw new Exception("Program exited with open ReceivePorts.");
147 } 136 }
148 } 137 }
149 } 138 }
150 139
151 _serializeMessage(message) {
152 if (_globalState.needSerialization) {
153 return new Serializer().traverse(message);
154 } else {
155 return new Copier().traverse(message);
156 }
157 }
158
159 _deserializeMessage(message) {
160 if (_globalState.needSerialization) {
161 return new Deserializer().deserialize(message);
162 } else {
163 // Nothing more to do.
164 return message;
165 }
166 }
167
168 /** Wait until all ports in a message are resolved. */
169 _waitForPendingPorts(var message, void callback()) {
170 final finder = new PendingSendPortFinder();
171 finder.traverse(message);
172 Futures.wait(finder.ports).then((_) => callback());
173 }
174
175 /** Default worker. */
176 class MainWorker {
177 int id = 0;
178 void postMessage(msg) native "return \$globalThis.postMessage(msg);";
179 void set onmessage(f) native "\$globalThis.onmessage = f;";
180 void terminate() {}
181 }
182
183 /**
184 * A web worker. This type is also defined in 'dart:dom', but we define it here
185 * to avoid introducing a dependency from corelib to dom. This definition uses a
186 * 'hidden' type (* prefix on the native name) to enforce that the type is
187 * defined dynamically only when web workers are actually available.
188 */
189 class _Worker native "*Worker" {
190 get id() native "return this.id;";
191 void set id(i) native "this.id = i;";
192 void set onmessage(f) native "this.onmessage = f;";
193 void postMessage(msg) native "return this.postMessage(msg);";
194 }
195
196 /** Context information tracked for each isolate. */ 140 /** Context information tracked for each isolate. */
197 class IsolateContext { 141 class IsolateContext {
198 /** Current isolate id. */ 142 /** Current isolate id. */
199 int id; 143 int id;
200 144
201 /** Registry of receive ports currently active on this isolate. */ 145 /** Registry of receive ports currently active on this isolate. */
202 Map<int, ReceivePort> ports; 146 Map<int, ReceivePort> ports;
203 147
204 /** Holds isolate globals (statics and top-level properties). */ 148 /** Holds isolate globals (statics and top-level properties). */
205 var isolateStatics; // native object containing all globals of an isolate. 149 var isolateStatics; // native object containing all globals of an isolate.
206 150
207 IsolateContext() { 151 IsolateContext() {
208 id = _globalState.nextIsolateId++; 152 id = globalState.nextIsolateId++;
209 ports = {}; 153 ports = {};
210 initGlobals(); 154 initGlobals();
211 } 155 }
212 156
213 // these are filled lazily the first time the isolate starts running. 157 // these are filled lazily the first time the isolate starts running.
214 void initGlobals() native 'this.isolateStatics = {};'; 158 void initGlobals() native 'this.isolateStatics = {};';
215 159
216 /** 160 /**
217 * Run [code] in the context of the isolate represented by [this]. Note this 161 * Run [code] in the context of the isolate represented by [this]. Note this
218 * is called from JavaScript (see $wrap_call in corejs.dart). 162 * is called from JavaScript (see $wrap_call in corejs.dart).
219 */ 163 */
220 void eval(Function code) { 164 void eval(Function code) {
221 var old = _globalState.currentContext; 165 var old = globalState.currentContext;
222 _globalState.currentContext = this; 166 globalState.currentContext = this;
223 this._setGlobals(); 167 this._setGlobals();
224 var result = null; 168 var result = null;
225 try { 169 try {
226 result = code(); 170 result = code();
227 } finally { 171 } finally {
228 _globalState.currentContext = old; 172 globalState.currentContext = old;
229 if (old != null) old._setGlobals(); 173 if (old != null) old._setGlobals();
230 } 174 }
231 return result; 175 return result;
232 } 176 }
233 177
234 void _setGlobals() native @'$globals = this.isolateStatics;'; 178 void _setGlobals() native @'$globals = this.isolateStatics;';
235 179
236 /** Lookup a port registered for this isolate. */ 180 /** Lookup a port registered for this isolate. */
237 ReceivePort lookup(int id) => ports[id]; 181 ReceivePort lookup(int id) => ports[id];
238 182
239 /** Register a port on this isolate. */ 183 /** Register a port on this isolate. */
240 void register(int portId, ReceivePort port) { 184 void register(int portId, ReceivePort port) {
241 if (ports.containsKey(portId)) { 185 if (ports.containsKey(portId)) {
242 throw new Exception("Registry: ports must be registered only once."); 186 throw new Exception("Registry: ports must be registered only once.");
243 } 187 }
244 ports[portId] = port; 188 ports[portId] = port;
245 _globalState.isolates[id] = this; // indicate this isolate is active 189 globalState.isolates[id] = this; // indicate this isolate is active
246 } 190 }
247 191
248 /** Unregister a port on this isolate. */ 192 /** Unregister a port on this isolate. */
249 void unregister(int portId) { 193 void unregister(int portId) {
250 ports.remove(portId); 194 ports.remove(portId);
251 if (ports.isEmpty()) { 195 if (ports.isEmpty()) {
252 _globalState.isolates.remove(id); // indicate this isolate is not active 196 globalState.isolates.remove(id); // indicate this isolate is not active
253 } 197 }
254 } 198 }
255 } 199 }
256 200
201
257 /** Represent the event loop on a javascript thread (DOM or worker). */ 202 /** Represent the event loop on a javascript thread (DOM or worker). */
258 class EventLoop { 203 class EventLoop {
259 Queue<IsolateEvent> events; 204 Queue<IsolateEvent> events;
260 205
261 EventLoop() : events = new Queue<IsolateEvent>(); 206 EventLoop() : events = new Queue<IsolateEvent>();
262 207
263 void enqueue(isolate, fn, msg) { 208 void enqueue(isolate, fn, msg) {
264 events.addLast(new IsolateEvent(isolate, fn, msg)); 209 events.addLast(new IsolateEvent(isolate, fn, msg));
265 } 210 }
266 211
267 IsolateEvent dequeue() { 212 IsolateEvent dequeue() {
268 if (events.isEmpty()) return null; 213 if (events.isEmpty()) return null;
269 return events.removeFirst(); 214 return events.removeFirst();
270 } 215 }
271 216
272 /** Process a single event, if any. */ 217 /** Process a single event, if any. */
273 bool runIteration() { 218 bool runIteration() {
274 final event = dequeue(); 219 final event = dequeue();
275 if (event == null) { 220 if (event == null) {
276 _globalState.closeWorker(); 221 globalState.closeWorker();
277 return false; 222 return false;
278 } 223 }
279 event.process(); 224 event.process();
280 return true; 225 return true;
281 } 226 }
282 227
283 /** Function equivalent to [:window.setTimeout:] when available, or null. */ 228 /** Function equivalent to [:window.setTimeout:] when available, or null. */
284 static Function _wrapSetTimeout() native """ 229 static Function _wrapSetTimeout() native """
285 return typeof window != 'undefined' ? 230 return typeof window != 'undefined' ?
286 function(a, b) { window.setTimeout(a, b); } : undefined; 231 function(a, b) { window.setTimeout(a, b); } : undefined;
(...skipping 16 matching lines...) Expand all
303 // Run synchronously until no more iterations are available. 248 // Run synchronously until no more iterations are available.
304 while (runIteration()) {} 249 while (runIteration()) {}
305 } 250 }
306 } 251 }
307 252
308 /** 253 /**
309 * Call [_runHelper] but ensure that worker exceptions are propragated. Note 254 * Call [_runHelper] but ensure that worker exceptions are propragated. Note
310 * this is called from JavaScript (see $wrap_call in corejs.dart). 255 * this is called from JavaScript (see $wrap_call in corejs.dart).
311 */ 256 */
312 void run() { 257 void run() {
313 if (!_globalState.isWorker) { 258 if (!globalState.isWorker) {
314 _runHelper(); 259 _runHelper();
315 } else { 260 } else {
316 try { 261 try {
317 _runHelper(); 262 _runHelper();
318 } catch(var e, var trace) { 263 } catch(var e, var trace) {
319 _globalState.mainWorker.postMessage(_serializeMessage( 264 globalState.mainWorker.postMessage(messages.serialize(
320 {'command': 'error', 'msg': '$e\n$trace' })); 265 {'command': 'error', 'msg': '$e\n$trace' }));
321 } 266 }
322 } 267 }
323 } 268 }
324 } 269 }
325 270
326 /** An event in the top-level event queue. */ 271 /** An event in the top-level event queue. */
327 class IsolateEvent { 272 class IsolateEvent {
328 IsolateContext isolate; 273 IsolateContext isolate;
329 Function fn; 274 Function fn;
330 String message; 275 String message;
331 276
332 IsolateEvent(this.isolate, this.fn, this.message); 277 IsolateEvent(this.isolate, this.fn, this.message);
333 278
334 void process() { 279 void process() {
335 isolate.eval(fn); 280 isolate.eval(fn);
336 } 281 }
337 } 282 }
338 283
339 /** Common functionality to all send ports. */
340 class BaseSendPort implements SendPort {
341 /** Id for the destination isolate. */
342 final int _isolateId;
343 284
344 BaseSendPort(this._isolateId); 285 /** Default worker. */
345 286 class MainWorker {
346 ReceivePortSingleShotImpl call(var message) { 287 int id = 0;
347 final result = new ReceivePortSingleShotImpl(); 288 void postMessage(msg) native "return \$globalThis.postMessage(msg);";
348 this.send(message, result.toSendPort()); 289 void set onmessage(f) native "\$globalThis.onmessage = f;";
349 return result; 290 void terminate() {}
350 }
351
352 static void checkReplyTo(SendPort replyTo) {
353 if (replyTo !== null
354 && replyTo is! NativeJsSendPort
355 && replyTo is! WorkerSendPort
356 && replyTo is! BufferingSendPort) {
357 throw new Exception("SendPort.send: Illegal replyTo port type");
358 }
359 }
360
361 // TODO(sigmund): replace the current SendPort.call with the following:
362 //Future call(var message) {
363 //  final completer = new Completer();
364 //  final port = new ReceivePort.singleShot();
365 //  send(message, port.toSendPort());
366 //  port.receive((value, ignoreReplyTo) {
367 //    if (value is Exception) {
368 //  completer.completeException(value);
369 // } else {
370 // completer.complete(value);
371 // }
372 // });
373 //  return completer.future;
374 //}
375
376 abstract void send(var message, [SendPort replyTo]);
377 abstract bool operator ==(var other);
378 abstract int hashCode();
379 } 291 }
380 292
381 /** A send port that delivers messages in-memory via native JavaScript calls. */ 293 /**
382 class NativeJsSendPort extends BaseSendPort implements SendPort { 294 * A web worker. This type is also defined in 'dart:dom', but we define it here
383 final ReceivePortImpl _receivePort; 295 * to avoid introducing a dependency from corelib to dom. This definition uses a
384 296 * 'hidden' type (* prefix on the native name) to enforce that the type is
385 const NativeJsSendPort(this._receivePort, int isolateId) : super(isolateId); 297 * defined dynamically only when web workers are actually available.
386 298 */
387 void send(var message, [SendPort replyTo = null]) { 299 class _Worker native "*Worker" {
388 _waitForPendingPorts([message, replyTo], () { 300 get id() native "return this.id;";
389 checkReplyTo(replyTo); 301 void set id(i) native "this.id = i;";
390 // Check that the isolate still runs and the port is still open 302 void set onmessage(f) native "this.onmessage = f;";
391 final isolate = _globalState.isolates[_isolateId]; 303 void postMessage(msg) native "return this.postMessage(msg);";
392 if (isolate == null) return;
393 if (_receivePort._callback == null) return;
394
395 // We force serialization/deserialization as a simple way to ensure
396 // isolate communication restrictions are respected between isolates that
397 // live in the same worker. NativeJsSendPort delivers both messages from
398 // the same worker and messages from other workers. In particular,
399 // messages sent from a worker via a WorkerSendPort are received at
400 // [_processWorkerMessage] and forwarded to a native port. In such cases,
401 // here we'll see [_globalState.currentContext == null].
402 final shouldSerialize = _globalState.currentContext != null
403 && _globalState.currentContext.id != _isolateId;
404 var msg = message;
405 var reply = replyTo;
406 if (shouldSerialize) {
407 msg = _serializeMessage(msg);
408 reply = _serializeMessage(reply);
409 }
410 _globalState.topEventLoop.enqueue(isolate, () {
411 if (_receivePort._callback != null) {
412 if (shouldSerialize) {
413 msg = _deserializeMessage(msg);
414 reply = _deserializeMessage(reply);
415 }
416 _receivePort._callback(msg, reply);
417 }
418 }, 'receive ' + message);
419 });
420 }
421
422 bool operator ==(var other) => (other is NativeJsSendPort) &&
423 (_receivePort == other._receivePort);
424
425 int hashCode() => _receivePort._id;
426 }
427
428 /** A send port that delivers messages via worker.postMessage. */
429 class WorkerSendPort extends BaseSendPort implements SendPort {
430 final int _workerId;
431 final int _receivePortId;
432
433 const WorkerSendPort(this._workerId, int isolateId, this._receivePortId)
434 : super(isolateId);
435
436 void send(var message, [SendPort replyTo = null]) {
437 _waitForPendingPorts([message, replyTo], () {
438 checkReplyTo(replyTo);
439 final workerMessage = _serializeMessage({
440 'command': 'message',
441 'port': this,
442 'msg': message,
443 'replyTo': replyTo});
444
445 if (_globalState.isWorker) {
446 // communication from one worker to another go through the main worker:
447 _globalState.mainWorker.postMessage(workerMessage);
448 } else {
449 _globalState.workers[_workerId].postMessage(workerMessage);
450 }
451 });
452 }
453
454 bool operator ==(var other) {
455 return (other is WorkerSendPort) &&
456 (_workerId == other._workerId) &&
457 (_isolateId == other._isolateId) &&
458 (_receivePortId == other._receivePortId);
459 }
460
461 int hashCode() {
462 // TODO(sigmund): use a standard hash when we get one available in corelib.
463 return (_workerId << 16) ^ (_isolateId << 8) ^ _receivePortId;
464 }
465 }
466
467 /** A port that buffers messages until an underlying port gets resolved. */
468 class BufferingSendPort extends BaseSendPort implements SendPort {
469 /** Internal counter to assign unique ids to each port. */
470 static int _idCount = 0;
471
472 /** For implementing equals and hashcode. */
473 final int _id;
474
475 /** Underlying port, when resolved. */
476 SendPort _port;
477
478 /**
479 * Future of the underlying port, so that we can detect when this port can be
480 * sent on messages.
481 */
482 Future<SendPort> _futurePort;
483
484 /** Pending messages (and reply ports). */
485 List pending;
486
487 BufferingSendPort(isolateId, this._futurePort)
488 : super(isolateId), _id = _idCount, pending = [] {
489 _idCount++;
490 _futurePort.then((p) {
491 _port = p;
492 for (final item in pending) {
493 p.send(item['message'], item['replyTo']);
494 }
495 pending = null;
496 });
497 }
498
499 BufferingSendPort.fromPort(isolateId, this._port)
500 : super(isolateId), _id = _idCount {
501 _idCount++;
502 }
503
504 void send(var message, [SendPort replyTo]) {
505 if (_port != null) {
506 _port.send(message, replyTo);
507 } else {
508 pending.add({'message': message, 'replyTo': replyTo});
509 }
510 }
511
512 bool operator ==(var other) => other is BufferingSendPort && _id == other._id;
513 int hashCode() => _id;
514 }
515
516 /** Default factory for receive ports. */
517 class ReceivePortFactory {
518
519 factory ReceivePort() {
520 return new ReceivePortImpl();
521 }
522
523 factory ReceivePort.singleShot() {
524 return new ReceivePortSingleShotImpl();
525 }
526 }
527
528 /** Implementation of a multi-use [ReceivePort] on top of JavaScript. */
529 class ReceivePortImpl implements ReceivePort {
530 int _id;
531 Function _callback;
532 static int _nextFreeId = 1;
533
534 ReceivePortImpl()
535 : _id = _nextFreeId++ {
536 _globalState.currentContext.register(_id, this);
537 }
538
539 void receive(void onMessage(var message, SendPort replyTo)) {
540 _callback = onMessage;
541 }
542
543 void close() {
544 _callback = null;
545 _globalState.currentContext.unregister(_id);
546 }
547
548 SendPort toSendPort() {
549 return new NativeJsSendPort(this, _globalState.currentContext.id);
550 }
551 }
552
553 /** Implementation of a single-shot [ReceivePort]. */
554 class ReceivePortSingleShotImpl implements ReceivePort {
555
556 ReceivePortSingleShotImpl() : _port = new ReceivePortImpl() { }
557
558 void receive(void callback(var message, SendPort replyTo)) {
559 _port.receive((var message, SendPort replyTo) {
560 _port.close();
561 callback(message, replyTo);
562 });
563 }
564
565 void close() {
566 _port.close();
567 }
568
569 SendPort toSendPort() => _port.toSendPort();
570
571 final ReceivePortImpl _port;
572 } 304 }
573 305
574 final String _SPAWNED_SIGNAL = "spawned"; 306 final String _SPAWNED_SIGNAL = "spawned";
575 307
576 class IsolateNatives { 308 class IsolateNatives {
577 309
578 /** JavaScript-specific implementation to spawn an isolate. */ 310 /** JavaScript-specific implementation to spawn an isolate. */
579 static Future<SendPort> spawn(Isolate isolate, bool isLight) { 311 static Future<SendPort> spawn(Isolate isolate, bool isLight) {
580 Completer<SendPort> completer = new Completer<SendPort>(); 312 Completer<SendPort> completer = new Completer<SendPort>();
581 ReceivePort port = new ReceivePort.singleShot(); 313 ReceivePort port = new ReceivePort.singleShot();
582 port.receive((msg, SendPort replyPort) { 314 port.receive((msg, SendPort replyPort) {
583 assert(msg == _SPAWNED_SIGNAL); 315 assert(msg == _SPAWNED_SIGNAL);
584 completer.complete(replyPort); 316 completer.complete(replyPort);
585 }); 317 });
586 318
587 // TODO(floitsch): throw exception if isolate's class doesn't have a 319 // TODO(floitsch): throw exception if isolate's class doesn't have a
588 // default constructor. 320 // default constructor.
589 if (_globalState.useWorkers && !isLight) { 321 if (globalState.useWorkers && !isLight) {
590 _startWorker(isolate, port.toSendPort()); 322 _startWorker(isolate, port.toSendPort());
591 } else { 323 } else {
592 _startNonWorker(isolate, port.toSendPort()); 324 _startNonWorker(isolate, port.toSendPort());
593 } 325 }
594 326
595 return completer.future; 327 return completer.future;
596 } 328 }
597 329
598 static SendPort _startWorker(Isolate runnable, SendPort replyPort) { 330 static SendPort _startWorker(Isolate runnable, SendPort replyPort) {
599 var factoryName = _getJSConstructorName(runnable); 331 var factoryName = _getJSConstructorName(runnable);
600 if (_globalState.isWorker) { 332 if (globalState.isWorker) {
601 _globalState.mainWorker.postMessage(_serializeMessage({ 333 globalState.mainWorker.postMessage(messages.serialize({
602 'command': 'spawn-worker', 334 'command': 'spawn-worker',
603 'factoryName': factoryName, 335 'factoryName': factoryName,
604 'replyPort': _serializeMessage(replyPort)})); 336 'replyPort': messages.serialize(replyPort)}));
605 } else { 337 } else {
606 _spawnWorker(factoryName, _serializeMessage(replyPort)); 338 _spawnWorker(factoryName, messages.serialize(replyPort));
607 } 339 }
608 } 340 }
609 341
610 /** 342 /**
611 * The src url for the script tag that loaded this code. Used to create 343 * The src url for the script tag that loaded this code. Used to create
612 * JavaScript workers. 344 * JavaScript workers.
613 */ 345 */
614 static String get _thisScript() => 346 static String get _thisScript() =>
615 _thisScriptCache != null ? _thisScriptCache : _computeThisScript(); 347 _thisScriptCache != null ? _thisScriptCache : _computeThisScript();
616 348
(...skipping 23 matching lines...) Expand all
640 /** Starts a new worker with the given URL. */ 372 /** Starts a new worker with the given URL. */
641 static _Worker _newWorker(url) native "return new Worker(url);"; 373 static _Worker _newWorker(url) native "return new Worker(url);";
642 374
643 /** 375 /**
644 * Spawns an isolate in a worker. [factoryName] is the Javascript constructor 376 * Spawns an isolate in a worker. [factoryName] is the Javascript constructor
645 * name for the isolate entry point class. 377 * name for the isolate entry point class.
646 */ 378 */
647 static void _spawnWorker(factoryName, serializedReplyPort) { 379 static void _spawnWorker(factoryName, serializedReplyPort) {
648 final worker = _newWorker(_thisScript); 380 final worker = _newWorker(_thisScript);
649 worker.onmessage = (e) { _processWorkerMessage(worker, e); }; 381 worker.onmessage = (e) { _processWorkerMessage(worker, e); };
650 var workerId = _globalState.nextWorkerId++; 382 var workerId = globalState.nextWorkerId++;
651 // We also store the id on the worker itself so that we can unregister it. 383 // We also store the id on the worker itself so that we can unregister it.
652 worker.id = workerId; 384 worker.id = workerId;
653 _globalState.workers[workerId] = worker; 385 globalState.workers[workerId] = worker;
654 worker.postMessage(_serializeMessage({ 386 worker.postMessage(messages.serialize({
655 'command': 'start', 387 'command': 'start',
656 'id': workerId, 388 'id': workerId,
657 'replyTo': serializedReplyPort, 389 'replyTo': serializedReplyPort,
658 'factoryName': factoryName })); 390 'factoryName': factoryName }));
659 } 391 }
660 392
661 /** 393 /**
662 * Assume that [e] is a browser message event and extract its message data. 394 * Assume that [e] is a browser message event and extract its message data.
663 * We don't import the dom explicitly so, when workers are disabled, this 395 * We don't import the dom explicitly so, when workers are disabled, this
664 * library can also run on top of nodejs. 396 * library can also run on top of nodejs.
665 */ 397 */
666 static _getEventData(e) native "return e.data"; 398 static _getEventData(e) native "return e.data";
667 399
668 /** 400 /**
669 * Process messages on a worker, either to control the worker instance or to 401 * Process messages on a worker, either to control the worker instance or to
670 * pass messages along to the isolate running in the worker. 402 * pass messages along to the isolate running in the worker.
671 */ 403 */
672 static void _processWorkerMessage(sender, e) { 404 static void _processWorkerMessage(sender, e) {
673 var msg = _deserializeMessage(_getEventData(e)); 405 var msg = messages.deserialize(_getEventData(e));
674 switch (msg['command']) { 406 switch (msg['command']) {
675 // TODO(sigmund): delete after we migrate to Isolate2 407 // TODO(sigmund): delete after we migrate to Isolate2
676 case 'start': 408 case 'start':
677 _globalState.currentWorkerId = msg['id']; 409 globalState.currentWorkerId = msg['id'];
678 var runnerObject = 410 var runnerObject =
679 _allocate(_getJSConstructorFromName(msg['factoryName'])); 411 _allocate(_getJSConstructorFromName(msg['factoryName']));
680 var serializedReplyTo = msg['replyTo']; 412 var serializedReplyTo = msg['replyTo'];
681 _globalState.topEventLoop.enqueue(new IsolateContext(), function() { 413 globalState.topEventLoop.enqueue(new IsolateContext(), function() {
682 var replyTo = _deserializeMessage(serializedReplyTo); 414 var replyTo = messages.deserialize(serializedReplyTo);
683 _startIsolate(runnerObject, replyTo); 415 _startIsolate(runnerObject, replyTo);
684 }, 'worker-start'); 416 }, 'worker-start');
685 _globalState.topEventLoop.run(); 417 globalState.topEventLoop.run();
686 break; 418 break;
687 case 'start2': 419 case 'start2':
688 _globalState.currentWorkerId = msg['id']; 420 globalState.currentWorkerId = msg['id'];
689 Function entryPoint = _getJSFunctionFromName(msg['functionName']); 421 Function entryPoint = _getJSFunctionFromName(msg['functionName']);
690 var replyTo = _deserializeMessage(msg['replyTo']); 422 var replyTo = messages.deserialize(msg['replyTo']);
691 _globalState.topEventLoop.enqueue(new IsolateContext(), function() { 423 globalState.topEventLoop.enqueue(new IsolateContext(), function() {
692 _startIsolate2(entryPoint, replyTo); 424 _startIsolate2(entryPoint, replyTo);
693 }, 'worker-start'); 425 }, 'worker-start');
694 _globalState.topEventLoop.run(); 426 globalState.topEventLoop.run();
695 break; 427 break;
696 // TODO(sigmund): delete after we migrate to Isolate2 428 // TODO(sigmund): delete after we migrate to Isolate2
697 case 'spawn-worker': 429 case 'spawn-worker':
698 _spawnWorker(msg['factoryName'], msg['replyPort']); 430 _spawnWorker(msg['factoryName'], msg['replyPort']);
699 break; 431 break;
700 case 'spawn-worker2': 432 case 'spawn-worker2':
701 _spawnWorker2(msg['functionName'], msg['uri'], msg['replyPort']); 433 _spawnWorker2(msg['functionName'], msg['uri'], msg['replyPort']);
702 break; 434 break;
703 case 'message': 435 case 'message':
704 msg['port'].send(msg['msg'], msg['replyTo']); 436 msg['port'].send(msg['msg'], msg['replyTo']);
705 _globalState.topEventLoop.run(); 437 globalState.topEventLoop.run();
706 break; 438 break;
707 case 'close': 439 case 'close':
708 _log("Closing Worker"); 440 _log("Closing Worker");
709 _globalState.workers.remove(sender.id); 441 globalState.workers.remove(sender.id);
710 sender.terminate(); 442 sender.terminate();
711 _globalState.topEventLoop.run(); 443 globalState.topEventLoop.run();
712 break; 444 break;
713 case 'log': 445 case 'log':
714 _log(msg['msg']); 446 _log(msg['msg']);
715 break; 447 break;
716 case 'print': 448 case 'print':
717 if (_globalState.isWorker) { 449 if (globalState.isWorker) {
718 _globalState.mainWorker.postMessage( 450 globalState.mainWorker.postMessage(
719 _serializeMessage({'command': 'print', 'msg': msg})); 451 messages.serialize({'command': 'print', 'msg': msg}));
720 } else { 452 } else {
721 print(msg['msg']); 453 print(msg['msg']);
722 } 454 }
723 break; 455 break;
724 case 'error': 456 case 'error':
725 throw msg['msg']; 457 throw msg['msg'];
726 } 458 }
727 } 459 }
728 460
729 /** Log a message, forwarding to the main worker if appropriate. */ 461 /** Log a message, forwarding to the main worker if appropriate. */
730 static _log(msg) { 462 static _log(msg) {
731 if (_globalState.isWorker) { 463 if (globalState.isWorker) {
732 _globalState.mainWorker.postMessage( 464 globalState.mainWorker.postMessage(
733 _serializeMessage({'command': 'log', 'msg': msg })); 465 messages.serialize({'command': 'log', 'msg': msg }));
734 } else { 466 } else {
735 try { 467 try {
736 _consoleLog(msg); 468 _consoleLog(msg);
737 } catch(e, trace) { 469 } catch(e, trace) {
738 throw new Exception(trace); 470 throw new Exception(trace);
739 } 471 }
740 } 472 }
741 } 473 }
742 474
743 static void _consoleLog(msg) native "\$globalThis.console.log(msg);"; 475 static void _consoleLog(msg) native "\$globalThis.console.log(msg);";
(...skipping 30 matching lines...) Expand all
774 /** Starts a non-worker isolate. */ 506 /** Starts a non-worker isolate. */
775 static SendPort _startNonWorker(Isolate runnable, SendPort replyTo) { 507 static SendPort _startNonWorker(Isolate runnable, SendPort replyTo) {
776 // Spawn a new isolate and create the receive port in it. 508 // Spawn a new isolate and create the receive port in it.
777 final spawned = new IsolateContext(); 509 final spawned = new IsolateContext();
778 510
779 // Instead of just running the provided runnable, we create a 511 // Instead of just running the provided runnable, we create a
780 // new cloned instance of it with a fresh state in the spawned 512 // new cloned instance of it with a fresh state in the spawned
781 // isolate. This way, we do not get cross-isolate references 513 // isolate. This way, we do not get cross-isolate references
782 // through the runnable. 514 // through the runnable.
783 final ctor = _getJSConstructor(runnable); 515 final ctor = _getJSConstructor(runnable);
784 _globalState.topEventLoop.enqueue(spawned, function() { 516 globalState.topEventLoop.enqueue(spawned, function() {
785 _startIsolate(_allocate(ctor), replyTo); 517 _startIsolate(_allocate(ctor), replyTo);
786 }, 'nonworker start'); 518 }, 'nonworker start');
787 } 519 }
788 520
789 /** Given a ready-to-start runnable, start running it. */ 521 /** Given a ready-to-start runnable, start running it. */
790 static void _startIsolate(Isolate isolate, SendPort replyTo) { 522 static void _startIsolate(Isolate isolate, SendPort replyTo) {
791 _fillStatics(_globalState.currentContext); 523 fillStatics(globalState.currentContext);
792 ReceivePort port = new ReceivePort(); 524 ReceivePort port = new ReceivePort();
793 replyTo.send(_SPAWNED_SIGNAL, port.toSendPort()); 525 replyTo.send(_SPAWNED_SIGNAL, port.toSendPort());
794 isolate._run(port); 526 isolate._run(port);
795 } 527 }
796 528
797 // TODO(sigmund): clean up above, after we make the new API the default: 529 // TODO(sigmund): clean up above, after we make the new API the default:
798 530
799 static _spawn2(String functionName, String uri, bool isLight) { 531 static _spawn2(String functionName, String uri, bool isLight) {
800 Completer<SendPort> completer = new Completer<SendPort>(); 532 Completer<SendPort> completer = new Completer<SendPort>();
801 ReceivePort port = new ReceivePort.singleShot(); 533 ReceivePort port = new ReceivePort.singleShot();
802 port.receive((msg, SendPort replyPort) { 534 port.receive((msg, SendPort replyPort) {
803 assert(msg == _SPAWNED_SIGNAL); 535 assert(msg == _SPAWNED_SIGNAL);
804 completer.complete(replyPort); 536 completer.complete(replyPort);
805 }); 537 });
806 538
807 SendPort signalReply = port.toSendPort(); 539 SendPort signalReply = port.toSendPort();
808 540
809 if (_globalState.useWorkers && !isLight) { 541 if (globalState.useWorkers && !isLight) {
810 _startWorker2(functionName, uri, signalReply); 542 _startWorker2(functionName, uri, signalReply);
811 } else { 543 } else {
812 _startNonWorker2(functionName, uri, signalReply); 544 _startNonWorker2(functionName, uri, signalReply);
813 } 545 }
814 return new BufferingSendPort( 546 return new ports.BufferingSendPort(
815 _globalState.currentContext.id, completer.future); 547 globalState.currentContext.id, completer.future);
816 } 548 }
817 549
818 static SendPort _startWorker2( 550 static SendPort _startWorker2(
819 String functionName, String uri, SendPort replyPort) { 551 String functionName, String uri, SendPort replyPort) {
820 if (_globalState.isWorker) { 552 if (globalState.isWorker) {
821 _globalState.mainWorker.postMessage(_serializeMessage({ 553 globalState.mainWorker.postMessage(messages.serialize({
822 'command': 'spawn-worker2', 554 'command': 'spawn-worker2',
823 'functionName': functionName, 555 'functionName': functionName,
824 'uri': uri, 556 'uri': uri,
825 'replyPort': replyPort})); 557 'replyPort': replyPort}));
826 } else { 558 } else {
827 _spawnWorker2(functionName, uri, replyPort); 559 _spawnWorker2(functionName, uri, replyPort);
828 } 560 }
829 } 561 }
830 562
831 static SendPort _startNonWorker2( 563 static SendPort _startNonWorker2(
832 String functionName, String uri, SendPort replyPort) { 564 String functionName, String uri, SendPort replyPort) {
833 // TODO(eub): support IE9 using an iframe -- Dart issue 1702. 565 // TODO(eub): support IE9 using an iframe -- Dart issue 1702.
834 if (uri != null) throw new UnsupportedOperationException( 566 if (uri != null) throw new UnsupportedOperationException(
835 "Currently Isolate2.fromUri is not supported without web workers."); 567 "Currently Isolate2.fromUri is not supported without web workers.");
836 _globalState.topEventLoop.enqueue(new IsolateContext(), function() { 568 globalState.topEventLoop.enqueue(new IsolateContext(), function() {
837 final func = _getJSFunctionFromName(functionName); 569 final func = _getJSFunctionFromName(functionName);
838 _startIsolate2(func, replyPort); 570 _startIsolate2(func, replyPort);
839 }, 'nonworker start'); 571 }, 'nonworker start');
840 } 572 }
841 573
842 static void _startIsolate2(Function topLevel, SendPort replyTo) { 574 static void _startIsolate2(Function topLevel, SendPort replyTo) {
843 _fillStatics(_globalState.currentContext); 575 fillStatics(globalState.currentContext);
844 final port = new ReceivePort(); 576 final port = new ReceivePort();
845 replyTo.send(_SPAWNED_SIGNAL, port.toSendPort()); 577 replyTo.send(_SPAWNED_SIGNAL, port.toSendPort());
846 topLevel(port); 578 topLevel(port);
847 } 579 }
848 580
849 /** 581 /**
850 * Spawns an isolate in a worker. [factoryName] is the Javascript constructor 582 * Spawns an isolate in a worker. [factoryName] is the Javascript constructor
851 * name for the isolate entry point class. 583 * name for the isolate entry point class.
852 */ 584 */
853 static void _spawnWorker2(functionName, uri, replyPort) { 585 static void _spawnWorker2(functionName, uri, replyPort) {
854 // TODO(eub): convert to 'main' once we switch back to port at top-level. 586 // TODO(eub): convert to 'main' once we switch back to port at top-level.
855 if (functionName == null) functionName = 'isolateMain'; 587 if (functionName == null) functionName = 'isolateMain';
856 if (uri == null) uri = _thisScript; 588 if (uri == null) uri = _thisScript;
857 final worker = _newWorker(uri); 589 final worker = _newWorker(uri);
858 worker.onmessage = (e) { _processWorkerMessage(worker, e); }; 590 worker.onmessage = (e) { _processWorkerMessage(worker, e); };
859 var workerId = _globalState.nextWorkerId++; 591 var workerId = globalState.nextWorkerId++;
860 // We also store the id on the worker itself so that we can unregister it. 592 // We also store the id on the worker itself so that we can unregister it.
861 worker.id = workerId; 593 worker.id = workerId;
862 _globalState.workers[workerId] = worker; 594 globalState.workers[workerId] = worker;
863 worker.postMessage(_serializeMessage({ 595 worker.postMessage(messages.serialize({
864 'command': 'start2', 596 'command': 'start2',
865 'id': workerId, 597 'id': workerId,
866 // Note: we serialize replyPort twice because the child worker needs to 598 // Note: we serialize replyPort twice because the child worker needs to
867 // first deserialize the worker id, before it can correctly deserialize 599 // first deserialize the worker id, before it can correctly deserialize
868 // the port (port deserialization is sensitive to what is the current 600 // the port (port deserialization is sensitive to what is the current
869 // workerId). 601 // workerId).
870 'replyTo': _serializeMessage(replyPort), 602 'replyTo': messages.serialize(replyPort),
871 'functionName': functionName })); 603 'functionName': functionName }));
872 } 604 }
873 } 605 }
874
875 class Isolate2Impl implements Isolate2 {
876 SendPort sendPort;
877
878 Isolate2Impl(this.sendPort);
879
880 void stop() {}
881 }
882
883 class IsolateFactory implements Isolate2 {
884
885 factory Isolate2.fromCode(Function topLevelFunction) {
886 final name = IsolateNatives._getJSFunctionName(topLevelFunction);
887 if (name == null) {
888 throw new UnsupportedOperationException(
889 "only top-level functions can be spawned.");
890 }
891 return new Isolate2Impl(IsolateNatives._spawn2(name, null, false));
892 }
893
894 factory Isolate2.fromUri(String uri) {
895 return new Isolate2Impl(IsolateNatives._spawn2(null, uri, false));
896 }
897 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698