-
Notifications
You must be signed in to change notification settings - Fork 20
/
workerFactory.js
136 lines (106 loc) · 3.21 KB
/
workerFactory.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
/**
* Ternific Copyright (c) 2015 Miguel Castillo.
*
* Licensed under MIT
*/
define(function (require /*, exports, module*/) {
"use strict";
var logger = require("Logger").factory("LocalServer");
var Promise = require("node_modules/spromise/dist/spromise.min");
function createWorker(server, workerScript) {
var worker = new Worker(workerScript);
var current = null;
var pending = null;
worker.onmessage = function(evt) {
var data = evt.data;
// If tern requests a file, then we will load it and then send it back to
// tern as an addFile action.
if (data.type === "getFile") {
getFile(server, data);
}
else if (data.type === "debug") {
logger.log(data.message);
}
else if (current) {
if (data.err) {
current.deferred.reject(data.err);
}
else {
current.deferred.resolve(data.body);
}
}
};
worker.onerror = function(e) {
logger.error(e);
if (current) {
current.deferred.reject(e);
}
};
function send(data) {
logger.log(data.type, data);
worker.postMessage(data);
}
function deferredSend(data) {
logger.log(data.type, data);
var request = {
data: data,
deferred: Promise.defer()
};
if (!current) {
current = sendRequest(request);
}
else {
if (pending) {
pending.deferred.resolve(null);
}
pending = request;
}
return request.deferred;
}
function sendRequest(request) {
worker.postMessage(request.data);
request.deferred
.done(function(response) {
logger.log(response);
sendPending();
})
.fail(function(error) {
logger.error(error);
sendPending();
});
return request;
}
function sendPending() {
current = null;
if (pending) {
current = sendRequest(pending);
pending = null;
}
}
return {
send: send,
deferredSend: deferredSend
};
}
function getFile(server, data) {
logger.log(data.type, data.name, data);
server.documenProvider.getDocument(data.name)
.then(function(docMeta) {
server.worker.send({
type: "addFile",
text: docMeta.doc.getValue(),
id: data.id
});
}, function(error) {
logger.error(error);
server.worker.send({
type: "addFile",
err: String(error),
id: data.id
});
});
}
return {
create: createWorker
};
});