-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.js
More file actions
245 lines (216 loc) · 8.12 KB
/
demo.js
File metadata and controls
245 lines (216 loc) · 8.12 KB
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
var http = require('http')
var {http_server: braidify} = require('braid-http')
var text = ''
var version = 0
var subs = []
var server = http.createServer(function (req, res) {
braidify(req, res)
if (req.is_multiplexer) return
// Test script — loaded via root-relative URL to test referer-based proxying
if (req.url === '/script.js') {
res.writeHead(200, {'Content-Type': 'application/javascript'})
res.end('document.getElementById("script-status").textContent = "loaded!"')
return
}
// Braid-synced text at /
if (req.method === 'PUT') {
var put_ver = req.version ? Number(req.version[0]) : 0
var body = ''
req.on('data', chunk => body += chunk)
req.on('end', () => {
// Reject stale PUTs that arrived out of order
if (put_ver <= version) {
res.writeHead(432)
res.end()
return
}
text = body
version = put_ver
for (var sub of subs)
sub.sendUpdate({version: ['' + version], body: text})
res.writeHead(200)
res.end()
})
return
}
// GET — serve HTML or braid-synced text
if (!req.subscribe && !req.headers.accept?.includes('application/json')) {
res.writeHead(200, {'Content-Type': 'text/html'})
res.end(page_html)
return
}
res.setHeader('Content-Type', 'application/json')
if (req.subscribe) {
res.startSubscription({
onClose: () => { subs = subs.filter(s => s !== res) }
})
subs.push(res)
}
res.sendUpdate({version: ['' + version], body: text})
if (!req.subscribe) res.end()
})
// Websocket echo server — for testing cookie-based ws proxying
server.on('upgrade', function (req, socket, head) {
if (req.url !== '/ws-echo') {
socket.destroy()
return
}
// Minimal websocket handshake
var crypto = require('crypto')
var key = req.headers['sec-websocket-key']
var accept = crypto.createHash('sha1')
.update(key + '258EAFA5-E914-47DA-95CA-5ABB663B0174')
.digest('base64')
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
'Sec-WebSocket-Accept: ' + accept + '\r\n' +
'\r\n'
)
// Echo back any frame we receive
socket.on('data', function (buf) {
// Parse client frame (masked)
if (buf.length < 6) return
var len = buf[1] & 0x7f
var mask = buf.slice(2, 6)
var payload = buf.slice(6, 6 + len)
for (var i = 0; i < payload.length; i++)
payload[i] ^= mask[i % 4]
// Send unmasked frame back
var frame = Buffer.alloc(2 + payload.length)
frame[0] = 0x81 // text, fin
frame[1] = payload.length
payload.copy(frame, 2)
socket.write(frame)
})
})
server.listen(3000, () => console.log('demo on http://localhost:3000'))
var page_html = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Braid Text — Bad Braid Demo</title>
<style>
body {
font-family: monospace;
max-width: 700px; margin: 60px auto; padding: 0 20px;
background: #1a1a2e; color: #ccc
}
h1 { font-weight: normal; color: #eee }
h2 { font-weight: normal; color: #999; font-size: 14px; margin-top: 40px }
textarea {
width: 100%; height: 120px; font-family: monospace; font-size: 16px;
background: #16213e; color: #eee; border: 2px solid #444; padding: 12px;
border-radius: 4px; resize: vertical
}
textarea:focus { outline: none; border-color: #ffe066 }
.server-view {
background: #0f3460; border: 2px solid #444; padding: 12px;
min-height: 120px; white-space: pre-wrap; font-size: 16px;
border-radius: 4px; color: #8888ff; word-wrap: break-word
}
.status { font-size: 12px; color: #666; margin: 4px 0 }
.info {
margin-top: 40px; line-height: 1.8; color: #888;
border-top: 1px solid #333; padding-top: 20px
}
a { color: #ffe066 }
.lag-indicator {
display: inline-block; width: 8px; height: 8px; border-radius: 50%;
background: #333; margin-left: 8px; vertical-align: middle
}
.lag-indicator.sending { background: #ffe066 }
.lag-indicator.synced { background: #66ff88 }
</style>
</head>
<body>
<h1>Braid Text</h1>
<p>Type below. The server's view appears underneath — separated by the network.</p>
<h2>You type here <span class="lag-indicator" id="send-lag"></span></h2>
<textarea id="input" placeholder="start typing..."></textarea>
<div class="status" id="send-status"></div>
<h2>Server sees this <span class="lag-indicator" id="recv-lag"></span></h2>
<div class="server-view" id="server-view"></div>
<div class="status" id="recv-status"></div>
<p>/script.js (root-relative): <span id="script-status" style="color:#ff6666">not loaded</span></p>
<p>/ws-echo (websocket): <span id="ws-status" style="color:#ff6666">not connected</span></p>
<script src="/script.js"></script>
<div class="info">
<p>Access this page through Bad Braid to add latency:</p>
<p><code style="background:#333;padding:4px 8px">http://localhost:4000/latency/http://localhost:3000/</code></p>
<p>Then configure latency at <code style="background:#333;padding:4px 8px">http://localhost:4000/latency</code></p>
</div>
<script src="https://unpkg.com/braid-http/braid-http-client.js"></script>
<script>
var input = document.getElementById('input')
var server_view = document.getElementById('server-view')
var send_lag = document.getElementById('send-lag')
var recv_lag = document.getElementById('recv-lag')
var send_status = document.getElementById('send-status')
var recv_status = document.getElementById('recv-status')
var inflight = 0
// Subscribe to server's view of the text
async function subscribe() {
var res = await braid_fetch(location.href, {
subscribe: true,
retry: true,
headers: {Accept: 'application/json'}
})
res.subscribe(function (update) {
server_view.textContent = update.body_text || ''
recv_lag.className = 'lag-indicator synced'
recv_status.textContent = 'updated at ' + new Date().toLocaleTimeString()
setTimeout(() => recv_lag.className = 'lag-indicator', 300)
})
}
// Send text on each keystroke — versioned so server ignores stale PUTs
var put_version = 0
var inflight = 0
input.addEventListener('input', function () {
send()
})
async function send() {
inflight++
put_version++
send_lag.className = 'lag-indicator sending'
var start = performance.now()
var res = await braid_fetch(location.href, {
method: 'PUT',
version: ['' + put_version],
headers: {'Content-Type': 'text/plain'},
body: input.value
})
inflight--
var rtt = Math.round(performance.now() - start)
send_status.textContent = 'PUT round-trip: ' + rtt + ' ms'
// Server rejected as stale — resend with fresh version and current value
if (res.status === 432) return send()
if (inflight === 0) {
send_lag.className = 'lag-indicator synced'
setTimeout(() => {
if (inflight === 0) send_lag.className = 'lag-indicator'
}, 300)
}
}
subscribe()
// Test websocket via root-relative URL (uses cookie-based proxy hack)
var ws_status = document.getElementById('ws-status')
var proto = location.protocol === 'https:' ? 'wss:' : 'ws:'
var ws = new WebSocket(proto + '//' + location.host + '/ws-echo')
ws.onopen = function () {
ws_status.textContent = 'connected'
ws_status.style.color = '#66ff88'
ws.send('ping')
}
ws.onmessage = function (e) {
ws_status.textContent = 'echo: ' + e.data
ws_status.style.color = '#66ff88'
}
ws.onerror = function () {
ws_status.textContent = 'error'
ws_status.style.color = '#ff6666'
}
</script>
</body>
</html>`