-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParticipantWorker.js
235 lines (235 loc) · 7.62 KB
/
ParticipantWorker.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
'use strict'
let _url;
let _interpreter;
let _pendingMessage;
let _localDevelopment;
class Messenger {
static #state = ''; // TODO: Replace with: https://github.com/engine262/engine262/issues/191
static #stepsInit;
static #stepsRemaining = 0;
static #responseTimeout = Error();
static #doCount = true;
static messageInProgress = false;
static tick(){
if(Messenger.#doCount){
if(Messenger.#stepsRemaining-- < 1){
throw Messenger.#responseTimeout;
}
}
}
static countExecutionSteps(value){
if(typeof value === 'boolean'){
Messenger.#doCount = value;
return;
}
try{
Messenger.#doCount = value[0].boolean;
}catch(error){
console.error('FATAL', 'Value not boolean');
throw error;
}
}
static getStepsUsed(){
return Messenger.#stepsInit - Messenger.#stepsRemaining;
}
static async messageInterpreter(input, executionSteps=NaN){
if(Messenger.messageInProgress){
throw Error('Message in progress');
}
if(isNaN(executionSteps)){
throw Error('Input `executionSteps` is not a number');
}
Messenger.countExecutionSteps(true);
Messenger.messageInProgress = true;
Messenger.#stepsInit = Messenger.#stepsRemaining = executionSteps;
if(typeof input !== 'string'){
input = 'onmessage('+JSON.stringify(input)+');';
}
if(!Messenger.#state){
input = '\n'+input;
}
await new Promise(r=>{setTimeout(()=>{r()})}); // Micro sleep
let response;
try{
response = _interpreter.evaluateScript(input);
if(response.Type !== 'throw'){
Messenger.#state += input;
}
}catch(error){
response = error;
}
try{
if(response === Messenger.#responseTimeout){
Messenger.#stepsRemaining = Infinity;
await initNewInterpreter(Messenger.#state);
Messenger.#stepsRemaining = executionSteps;
let timeoutMessage = '\nonmessage({"type": "Timeout-Rollback"});';
try{
response = _interpreter.evaluateScript(timeoutMessage);
}catch(error){}
if(response !== Messenger.#responseTimeout && response.Type !== 'throw'){
Messenger.#state += timeoutMessage;
}else{
Messenger.#stepsRemaining = Infinity;
await initNewInterpreter(Messenger.#state);
if(_localDevelopment){
console.error('Missed timeout message', Messenger.#state+timeoutMessage);
}
}
throw {type: 'Response-Timeout', response: 'Did not finish in time'};
}else if(response.Type === 'throw'){
let message = response.Value.string;
if(!message){
response.Value.properties.map.get('message').Value.string;
}
throw {type: 'Response-Error', response: message};
}
}catch(error){
throw error;
}finally{
Messenger.messageInProgress = false;
}
};
}
let initNewInterpreter = ()=>{};
onmessage = messageEvent => {
_url = messageEvent.data.url;
function onResponse(response){
function logResponseAlreadyReceived(){
if(_localDevelopment){
console.warn('Response to message already received. Skipped.', _url);
}
}
function getValue(response){
if(!response.length){
throw Error('No response');
}
return JSON.parse(response[0].string);
}
if(!_pendingMessage){
logResponseAlreadyReceived();
return;
}
let usedSteps = Messenger.getStepsUsed();
_pendingMessage.then(()=>{
if(_pendingMessage === null){
postMessage({
type: 'Response',
response: {
value: getValue(response),
executionSteps: {
toRespond: usedSteps,
toTerminate: Messenger.getStepsUsed()
}
}
});
}else{
logResponseAlreadyReceived();
}
});
_pendingMessage = null;
}
let dependencies = messageEvent.data.includeScripts.system.map(url => fetch(url).then(response => response.text()));
Promise.allSettled(dependencies).then(results => {
importScripts(...results.map(r => {
let blob;
try{
blob = new Blob([r.value], {type: 'application/javascript'});
}catch(e){
blob = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder)();
blob.append(r.value);
blob = blob.getBlob();
}
let urlObject = URL.createObjectURL(blob);
setTimeout(()=>{URL.revokeObjectURL(urlObject);},10000); // Script does not work if urlObject is removed to early.
return urlObject;
}));
});
_localDevelopment = messageEvent.data.localDevelopment;
let generalSettings = messageEvent.data.workerData.settings.general;
let executionLimit = 0 < generalSettings.executionStepsInit ? generalSettings.executionStepsInit : Infinity;
let interpreterReady;
(()=>{
let promise = new Promise(r => interpreterReady = r);
onmessage = messageEvent => {
promise.then(() => {
_pendingMessage = Messenger.messageInterpreter({type: 'Post', data: messageEvent.data.message}, executionLimit).then(()=>{
if(_pendingMessage){
_pendingMessage = false;
postMessage({type: 'Response-Timeout', response: 'No response'});
}
}).catch(errorMessage => {
_pendingMessage = false;
postMessage(errorMessage);
});
});
};
})();
fetch(_url).then(response => response.text()).then(participantSource => {
let header = (()=>{
try{
return JSON.parse(participantSource.substring(participantSource.indexOf('/**')+3, participantSource.indexOf('**/')));
}catch(error){
return {};
}
})();
if(header.dependencies){
let scope = _url.slice(0, _url.lastIndexOf('/')+1);
header.dependencies.forEach((dependency, index) => {
header.dependencies[index] = scope + dependency;
});
}else{
header.dependencies = [];
}
let participantSources = [];
header.dependencies.forEach(url => {
participantSources.push(fetch(url).then(response => response.text()));
});
participantSources.push(Promise.resolve(participantSource));
Promise.allSettled(dependencies).then(()=>{
const {
Agent,
setSurroundingAgent,
ManagedRealm,
Value,
Get,
CreateDataProperty
} = self['@engine262/engine262'];
setSurroundingAgent(new Agent({
onNodeEvaluation(){
Messenger.tick();
}
}));
initNewInterpreter = async state => {
let random = new Math.seedrandom(messageEvent.data.workerData.settings.general.seed+'@'+messageEvent.data.iframeId);
_interpreter = new ManagedRealm({});
let postMessageName = '_'+Date.now()+'_postMessage';
let countExecutionStepsName = '_'+Date.now()+'_countExecutionSteps';
_interpreter.scope(() => {
CreateDataProperty(_interpreter.GlobalObject, new Value(postMessageName), new Value(onResponse));
CreateDataProperty(_interpreter.GlobalObject, new Value(countExecutionStepsName), new Value(Messenger.countExecutionSteps));
let math = Get(_interpreter.GlobalObject, new Value('Math'));
CreateDataProperty(math.Value, new Value('random'), new Value(()=>{return new Value(random())}));
});
if(state){
_interpreter.evaluateScript(state);
}else{
await Messenger.messageInterpreter('let __url=\''+_url+'\';\nlet onmessage = null; function postMessage(input){'+countExecutionStepsName+'(false); '+postMessageName+'(JSON.stringify(input)); '+countExecutionStepsName+'(true);}', Infinity);
await Messenger.messageInterpreter((await Promise.allSettled(participantSources)).map(r => r.value).join(';\n'), executionLimit).catch(errorMessage => {
postMessage({type: 'Fetal-Error', response: errorMessage.response});
});
await Messenger.messageInterpreter({type: 'Settings', ...messageEvent.data.workerData}, executionLimit).then(()=>{
interpreterReady();
}).catch(errorMessage => {
throw new Error('Participant ('+_url+') initiation failed: '+errorMessage.response);
});
return _interpreter;
}
}
initNewInterpreter().then(()=>{
postMessage(null);
}).catch(error => {postMessage({type: 'Init-Error', response: error})});
});
});
};
postMessage(null);