/
service.js
231 lines (212 loc) · 5.74 KB
/
service.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
// @flow strict
const baseURI = new URL("https://lunet.link/")
// Companion service is used p2p sites / applications. Site uses embedded
// `iframe` with `companion/bridge.html` to connect this SW with an
// "access point" SW allowing site / app to load all of the data from the p2p
// network.
self.addEventListener("install", function(event) {
console.log(`Companion service worker is installed for ${self.origin}`)
// We cache all the companion assets because occasionally we will need to
// reconnect to the "access point" SW and if we won't be able to do so
// while offline (as access point doesn't serve across origins).
event.waitUntil(initCache())
})
self.addEventListener("activate", function(event) {
console.log(`Companion service worker is activated for ${self.origin}`)
event.waitUntil(self.clients.claim())
})
self.addEventListener("fetch", function(event) {
console.log(`Companion at ${self.origin} got fetch request`, event)
const { request } = event
event.respondWith(matchRoute(request))
})
self.addEventListener("message", function({ data, ports, source }) {
const [port] = ports
connection = Connection.new(port, source)
console.log(
`Companion at ${self.origin} was connected an access point`,
connection
)
})
let connection = null
/*::
type EncodedResponse = {
type:"response";
id:number;
buffer:ArrayBuffer;
url:string;
status:number;
statusText:string;
destination:string;
headers:{[key: string]: string};
integrity: string;
method: string;
mode: string;
redirect: boolean;
referrer: string;
referrerPolicy: string;
}
type Alive = {
type:"alive"
}
type Message =
| Alive
| EncodedResponse
*/
class Connection {
/*::
id:number
time:number
port:MessagePort
pendingRequests: {[number]:(EncodedResponse) => void}
*/
static new(port /*:MessagePort*/, source /*:WindowProxy*/) {
const self = new this(port)
source.postMessage("ready")
return self
}
isAlive() {
return Date.now() - this.time < 200
}
constructor(port /*:MessagePort*/) {
this.time = Date.now()
this.id = 0
this.port = port
port.start()
this.port.onmessage = (message /*:Object*/) => this.receive(message.data)
this.pendingRequests = {}
}
receive(message /*:Message*/) {
switch (message.type) {
case "alive": {
return this.alive()
}
case "response": {
return this.respond(message)
}
}
}
alive() {
this.time = Date.now()
}
respond(encodedResponse /*:EncodedResponse*/) {
const pendingRequest = this.pendingRequests[encodedResponse.id]
if (pendingRequest) {
pendingRequest(encodedResponse)
} else {
console.warn(
`Unable to find request for id ${encodedResponse.id}`,
encodedResponse
)
}
}
wait(id /*:number*/) /*:Promise<EncodedResponse>*/ {
return new Promise((resolve /*:EncodedResponse => void*/) => {
this.pendingRequests[id] = resolve
})
}
async request(request) {
const id = ++this.id
const buffer = await request.arrayBuffer()
this.port.postMessage(
{
id,
buffer,
url: request.url,
cache: request.cache,
destination: request.destination,
headers: [...request.headers.entries()],
integrity: request.integrity,
method: request.method,
mode: request.mode,
redirect: request.redirect,
referrer: request.referrer,
referrerPolicy: request.referrerPolicy
},
[buffer]
)
const response = await this.wait(id)
return new Response(response.buffer, {
status: response.status,
statusText: response.statusText,
headers: new Headers(response.headers)
})
}
}
const matchRoute = async request => {
const url = new URL(request.url)
// If matches companion route serve it from cache
if (url.origin === baseURI.origin) {
return companionRoute(request)
}
// If connected to access point use it to fetch underlying content.
else if (connection && connection.isAlive()) {
return await connection.request(request)
}
// If not connected to access point then load a page that would
// establish connection.
// TODO: We should probably use redirects here instead.
else if (url.origin === self.origin) {
return await connectRoute(request)
}
// Otherwise it is fetch to some other foreign origin in which case we
// just serve it through fetch.
else {
return foreignFetch(request.url)
}
}
const foreignFetch = url => fetch(url, { mode: "no-cors" })
const companionRoute = async request => {
const cache = await caches.open("companion")
const response = await cache.match(request)
if (response) {
return response
} else {
return notFound(request)
}
}
const connectRoute = async request => {
return new Response(
`<html>
<head>
<meta charset="utf-8" />
<title>P2P Site</title>
<script
type="module"
async
defer
src="https://lunet.link/companion/embed.js"
></script>
</head>
<body></body>
</html>
`,
{
status: 200,
headers: {
"Content-Type": "text/html"
}
}
)
}
// Non existing documents under `companion` route.
const notFound = async request => {
return new Response("<h1>Page Not Found</h1>", {
status: 404,
headers: {
"content-type": "text/html"
}
})
}
const initCache = async () => {
console.log(`Init companion cache for ${self.origin}`)
const cache = await caches.open("companion")
const urls = [
new URL("./companion/bridge.html", baseURI),
new URL("./companion/bridge.js", baseURI),
new URL("./companion/embed.js", baseURI),
new URL("./companion/service.js", baseURI)
]
console.log(`Companion "${self.origin}" is caching`, urls)
return cache.addAll(urls)
}