-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclouddata-ping.js
109 lines (97 loc) · 2.39 KB
/
clouddata-ping.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
(function (Scratch) {
"use strict";
/**
* @typedef CacheEntry
* @property {number} expires
* @property {boolean} value
*/
/** @type {Map<string, Promise<CacheEntry>>} */
const computing = new Map();
/** @type {Map<string, CacheEntry>} */
const computed = new Map();
/**
* @param {string} uri
* @returns {Promise<CacheEntry>}
*/
const pingWebSocket = async (uri) => {
/** @type {WebSocket} */
let ws;
try {
ws = new WebSocket(uri);
} catch (e) {
return {
expires: 0,
value: false
};
}
let timeoutId;
const isUp = await new Promise((resolve) => {
ws.onopen = () => {
setTimeout(() => {
resolve(true);
}, 2000);
};
ws.onclose = () => {
resolve(false);
};
ws.onerror = () => {
resolve(false);
};
timeoutId = setTimeout(() => {
ws.close();
}, 5000);
});
ws.close();
clearTimeout(timeoutId);
return {
expires: Date.now() + 60000,
value: isUp
};
};
/**
* @param {string} uri
* @returns {boolean|Promise<boolean>}
*/
const cachedPingWebSocket = (uri) => {
const computingEntry = computing.get(uri);
if (computingEntry) {
return computingEntry.then((entry) => entry.value);
}
const computedEntry = computed.get(uri);
if (computedEntry && Date.now() < computedEntry.expires) {
return computedEntry.value;
}
const promise = pingWebSocket(uri);
computing.set(uri, promise);
return promise.then((entry) => {
computing.delete(uri);
computed.set(uri, entry);
return entry.value;
});
};
class PingUtil {
getInfo() {
return {
id: "clouddataping",
name: "Ping Cloud Data",
blocks: [
{
opcode: "ping",
blockType: Scratch.BlockType.BOOLEAN,
text: "is cloud data server [SERVER] up?",
arguments: {
SERVER: {
type: Scratch.ArgumentType.STRING,
defaultValue: "wss://clouddata.turbowarp.org",
},
},
},
],
};
}
ping({ SERVER }) {
return cachedPingWebSocket(SERVER);
}
}
Scratch.extensions.register(new PingUtil());
})(Scratch);