@dasl/tile-loader 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +841 -26
- package/dist/at.d.ts +126 -12
- package/dist/at.d.ts.map +1 -1
- package/dist/at.js +574 -90
- package/dist/at.js.map +1 -1
- package/dist/car.d.ts +21 -2
- package/dist/car.d.ts.map +1 -1
- package/dist/car.js +78 -15
- package/dist/car.js.map +1 -1
- package/dist/content-scheme.d.ts +17 -3
- package/dist/content-scheme.d.ts.map +1 -1
- package/dist/content-scheme.js +32 -6
- package/dist/content-scheme.js.map +1 -1
- package/dist/guard.d.ts +242 -0
- package/dist/guard.d.ts.map +1 -0
- package/dist/guard.js +956 -0
- package/dist/guard.js.map +1 -0
- package/dist/index.d.ts +297 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +917 -78
- package/dist/index.js.map +1 -1
- package/dist/lib/cid.d.ts +25 -0
- package/dist/lib/cid.d.ts.map +1 -0
- package/dist/lib/cid.js +65 -0
- package/dist/lib/cid.js.map +1 -0
- package/dist/lib/defaults.d.ts +8 -0
- package/dist/lib/defaults.d.ts.map +1 -0
- package/dist/lib/defaults.js +14 -0
- package/dist/lib/defaults.js.map +1 -0
- package/dist/lib/destinations.d.ts +25 -0
- package/dist/lib/destinations.d.ts.map +1 -0
- package/dist/lib/destinations.js +94 -0
- package/dist/lib/destinations.js.map +1 -0
- package/dist/lib/drisl.d.ts +10 -0
- package/dist/lib/drisl.d.ts.map +1 -0
- package/dist/lib/drisl.js +169 -0
- package/dist/lib/drisl.js.map +1 -0
- package/dist/lib/errors.d.ts +80 -0
- package/dist/lib/errors.d.ts.map +1 -0
- package/dist/lib/errors.js +44 -0
- package/dist/lib/errors.js.map +1 -0
- package/dist/lib/fetching.d.ts +24 -0
- package/dist/lib/fetching.d.ts.map +1 -0
- package/dist/lib/fetching.js +135 -0
- package/dist/lib/fetching.js.map +1 -0
- package/dist/lib/limits.d.ts +34 -0
- package/dist/lib/limits.d.ts.map +1 -0
- package/dist/lib/limits.js +33 -0
- package/dist/lib/limits.js.map +1 -0
- package/dist/lib/pointer.d.ts +83 -0
- package/dist/lib/pointer.d.ts.map +1 -0
- package/dist/lib/pointer.js +244 -0
- package/dist/lib/pointer.js.map +1 -0
- package/dist/link.d.ts +110 -13
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +336 -43
- package/dist/link.js.map +1 -1
- package/dist/memory.d.ts +1 -0
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +5 -0
- package/dist/memory.js.map +1 -1
- package/dist/mount.d.ts +54 -0
- package/dist/mount.d.ts.map +1 -0
- package/dist/mount.js +286 -0
- package/dist/mount.js.map +1 -0
- package/dist/size.d.ts +43 -2
- package/dist/size.d.ts.map +1 -1
- package/dist/size.js +296 -15
- package/dist/size.js.map +1 -1
- package/package.json +13 -3
- package/src/at.ts +582 -84
- package/src/car.ts +75 -16
- package/src/content-scheme.ts +38 -7
- package/src/guard.ts +1013 -0
- package/src/index.ts +1011 -80
- package/src/lib/cid.ts +65 -0
- package/src/lib/defaults.ts +12 -0
- package/src/lib/destinations.ts +79 -0
- package/src/lib/drisl.ts +160 -0
- package/src/lib/errors.ts +111 -0
- package/src/lib/fetching.ts +138 -0
- package/src/lib/limits.ts +61 -0
- package/src/lib/pointer.ts +290 -0
- package/src/link.ts +365 -48
- package/src/memory.ts +5 -0
- package/src/mount.ts +356 -0
- package/src/size.ts +304 -16
package/src/index.ts
CHANGED
|
@@ -36,6 +36,7 @@ The tile-loading architecture has four levels that all communicate together:
|
|
|
36
36
|
*/
|
|
37
37
|
|
|
38
38
|
import { el } from "./lib/el.js";
|
|
39
|
+
import { TileLoadError } from "./lib/errors.js";
|
|
39
40
|
import { tileResponseHeaders, dockPath } from "@dasl/tile-lexicon";
|
|
40
41
|
import type { AnyMasl, MaslHeaders, MaslResponse } from "@dasl/tile-lexicon";
|
|
41
42
|
|
|
@@ -43,12 +44,18 @@ export interface MothershipConfig {
|
|
|
43
44
|
/** Host of the loading server (`load.webtil.es`), with a scheme and port when not https://. */
|
|
44
45
|
loadDomain?: string;
|
|
45
46
|
/**
|
|
46
|
-
*
|
|
47
|
-
* the port if there is one),
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
47
|
+
* A named origin to run tiles on, instead of a fresh random one for every
|
|
48
|
+
* load: its host (`notes.tiles.example`, with the port if there is one), or
|
|
49
|
+
* the origin in full (`https://notes.tiles.example`). For a deployment that
|
|
50
|
+
* means tiles to share an origin or to find their storage again; the
|
|
51
|
+
* loading server has to know the name as one of its tile origins.
|
|
52
|
+
*
|
|
53
|
+
* Almost no one wants this. Left out, every tile gets an origin of its
|
|
54
|
+
* own, made for that one load and wiped when the tile is closed; a named
|
|
55
|
+
* origin is never wiped.
|
|
51
56
|
*/
|
|
57
|
+
namedOrigin?: string;
|
|
58
|
+
/** @deprecated The old name of `namedOrigin`. It goes in the next major version. */
|
|
52
59
|
tileHost?: string;
|
|
53
60
|
/**
|
|
54
61
|
* Whether the shuttle spends the renderer's WebRTC budget before the tile
|
|
@@ -56,14 +63,77 @@ export interface MothershipConfig {
|
|
|
56
63
|
* the policy switches set, say) passes 'none' and skips the cost.
|
|
57
64
|
*/
|
|
58
65
|
webrtcGuard?: 'exhaust' | 'none';
|
|
66
|
+
/**
|
|
67
|
+
* How long a tile gets to start, in milliseconds: counted from when its
|
|
68
|
+
* frame is attached, and again from when that frame loads; time that the
|
|
69
|
+
* frame spends out of the document is not counted. A tile whose root
|
|
70
|
+
* document has not been handed to its runtime by then fires an `error`
|
|
71
|
+
* event with the reason `timeout`. The deadline only reports: nothing is
|
|
72
|
+
* stopped, and a tile that was merely slow goes on to load. 15 seconds
|
|
73
|
+
* when left out; `0` for no deadline.
|
|
74
|
+
*/
|
|
75
|
+
startDeadline?: number;
|
|
76
|
+
/** What one tile may ask of this page (see TileBudget). */
|
|
77
|
+
budget?: TileBudget;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* What one tile may ask of the page that runs it. A tile's messages, and the
|
|
82
|
+
* resolving of its resources, are handled on the host page's main thread,
|
|
83
|
+
* which the page and every tile on it share: these keep one tile from taking
|
|
84
|
+
* it all. Each is for one tile, for as long as it is in one frame: rendered
|
|
85
|
+
* again, a tile starts afresh. `Infinity` lifts a limit.
|
|
86
|
+
*/
|
|
87
|
+
export interface TileBudget {
|
|
88
|
+
/**
|
|
89
|
+
* How many messages a tile may send in a second, over time. Its requests
|
|
90
|
+
* for its own resources are not counted here. What is over is dropped.
|
|
91
|
+
* 200 when left out.
|
|
92
|
+
*/
|
|
93
|
+
messagesPerSecond?: number;
|
|
94
|
+
/** How many it may send at once, before that rate holds it. 400. */
|
|
95
|
+
messageBurst?: number;
|
|
96
|
+
/** How many of a tile's resources are resolved at one time; further requests wait their turn. 16. */
|
|
97
|
+
requestsInFlight?: number;
|
|
98
|
+
/** How many requests may be waiting; a tile that asks for more is refused them. 2000. */
|
|
99
|
+
requestsQueued?: number;
|
|
100
|
+
/** How many lines a tile may have logged to the console. 10. */
|
|
101
|
+
logLines?: number;
|
|
59
102
|
}
|
|
60
103
|
|
|
104
|
+
/**
|
|
105
|
+
* What a host can ask of a load: the tile it expects, by CID. A page that
|
|
106
|
+
* embeds a tile someone posted holds what was posted, and the tile's address
|
|
107
|
+
* only says where it is now. With a CID, a tile that is not the one expected
|
|
108
|
+
* is not loaded: the load fails with a TileLoadError, `record-changed`.
|
|
109
|
+
*/
|
|
110
|
+
export interface TileLoadOptions {
|
|
111
|
+
/** The CID of the tile's record, as a strong reference to it carries. It changes whenever the record is written again, as it stands or not. */
|
|
112
|
+
cid?: string;
|
|
113
|
+
/** The CID of the tile's manifest alone: the content, whatever record carries it. With both, either will do. */
|
|
114
|
+
manifestCid?: string;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Which tile this is, as its loader worked it out from the bytes it was
|
|
118
|
+
* given, and never from what a server said they were.
|
|
119
|
+
*/
|
|
120
|
+
export interface TileIdentity {
|
|
121
|
+
/** The CID of the record or file the tile was made from. */
|
|
122
|
+
cid?: string;
|
|
123
|
+
/** The CID of its manifest alone. */
|
|
124
|
+
manifestCid?: string;
|
|
125
|
+
/** Whether it was checked against a CID its host expected. */
|
|
126
|
+
pinned?: boolean;
|
|
127
|
+
}
|
|
61
128
|
export interface TileLoader {
|
|
62
|
-
load (url: string, mothership: TileMothership): Promise<Tile | false | undefined>;
|
|
129
|
+
load (url: string, mothership: TileMothership, options?: TileLoadOptions): Promise<Tile | false | undefined>;
|
|
63
130
|
}
|
|
64
131
|
export interface TilePathLoader {
|
|
65
132
|
resolvePath (path: string): Promise<MaslResponse>;
|
|
66
133
|
}
|
|
134
|
+
// What a loader says went wrong, for a host to tell one failure from another.
|
|
135
|
+
export { TileLoadError } from "./lib/errors.js";
|
|
136
|
+
export type { TileLoadErrorCode, TileLoadErrorDetails, TileLoadErrorEvent, TileLoadFailure } from "./lib/errors.js";
|
|
67
137
|
|
|
68
138
|
const TILES_PFX = 'tiles-';
|
|
69
139
|
const SHUTTLE_PFX = 'tiles-shuttle-';
|
|
@@ -71,6 +141,24 @@ const SND_SHUTTLE_LOAD = `${SHUTTLE_PFX}load`; // tell worker to roll
|
|
|
71
141
|
const RCV_SHUTTLE_READY = `${SHUTTLE_PFX}ready`; // worker ready
|
|
72
142
|
const SND_SET_TITLE = `${SHUTTLE_PFX}set-title`; // set the title
|
|
73
143
|
const SND_SET_ICON = `${SHUTTLE_PFX}set-icon`; // set the icon
|
|
144
|
+
const SND_SHUTTLE_CLOSE = `${SHUTTLE_PFX}close`; // we are done with this tile: clean up
|
|
145
|
+
const RCV_SHUTTLE_CLOSED = `${SHUTTLE_PFX}closed`; // it has
|
|
146
|
+
// How long a runtime gets to clean up after itself before its frame goes anyway.
|
|
147
|
+
const CLOSE_MS = 2500;
|
|
148
|
+
// How long the wiping of an origin gets when it is asked for from a frame of
|
|
149
|
+
// our own (TileMothership.wipeOrigin), before it is given up on and counted
|
|
150
|
+
// as not done. A guess, and a generous one: nothing waits on it but the
|
|
151
|
+
// promise close() returns, and it has to cover a slow network and a tile
|
|
152
|
+
// that holds its own pages up on their way out.
|
|
153
|
+
const WIPE_MS = 10000;
|
|
154
|
+
// How long after an origin was wiped it is wiped once more (Tile.close()).
|
|
155
|
+
// The first wipe comes after everything the tile's pages did, but a worker
|
|
156
|
+
// of the tile's has a thread of its own, and a browser can take a moment to
|
|
157
|
+
// stop one after its page is gone (up to two seconds, in Chromium): what it
|
|
158
|
+
// writes in that moment lands on an origin that was just wiped. A guess,
|
|
159
|
+
// with a margin over that. A wipe that did not go through the first time
|
|
160
|
+
// gets its second chance then too.
|
|
161
|
+
const WIPE_AGAIN_MS = 3000;
|
|
74
162
|
const WORKER_PFX = 'tiles-worker-';
|
|
75
163
|
const SND_WORKER_LOAD = `${WORKER_PFX}load`; // tell worker to roll
|
|
76
164
|
const RCV_WORKER_READY = `${WORKER_PFX}ready`; // worker ready
|
|
@@ -79,13 +167,39 @@ const SND_WORKER_RESPONSE = `${WORKER_PFX}response`; // respond to a worker
|
|
|
79
167
|
const TILES_WARNING = `${TILES_PFX}warn`; // worker warnings
|
|
80
168
|
const TILES_ERROR = `${SHUTTLE_PFX}error`; // shuttle errors
|
|
81
169
|
const RCV_DOCK_STOPPED = 'tiles-dock-stopped'; // the dock stopped the tile
|
|
170
|
+
const RCV_DOCK_READY = 'tiles-dock-ready'; // the dock is there, and of which generation
|
|
171
|
+
// The generations of the runtime this loader speaks: what a dock names when
|
|
172
|
+
// it says it is ready (see GENERATION in @dasl/tile-server's dock.js). A dock
|
|
173
|
+
// from before that message names none, and is taken as it comes.
|
|
174
|
+
const GENERATIONS: readonly unknown[] = [3];
|
|
82
175
|
// Tiles protocols (https://dasl.ing/tp-data.html and friends): the shuttle
|
|
83
176
|
// relays `tiles-protocol-up-<protocol>-<kind>` from the tile to us, and
|
|
84
177
|
// `tiles-protocol-down-<protocol>-<kind>` from us to the tile.
|
|
85
178
|
const PROTOCOL_UP = 'tiles-protocol-up-';
|
|
86
179
|
const PROTOCOL_DOWN = 'tiles-protocol-down-';
|
|
87
|
-
// Warnings and errors come as a list
|
|
88
|
-
|
|
180
|
+
// Warnings and errors come as a list of things to log; anything else is
|
|
181
|
+
// logged as it is. The runtime's own lists are two or three texts, but the
|
|
182
|
+
// tile can have its runtime say anything, and a console writes out what it
|
|
183
|
+
// is handed: every entry, and some things in full each time they are there,
|
|
184
|
+
// however little it took to say them. So the first few entries are logged,
|
|
185
|
+
// however many the list says it has, and of those what is a text, a number
|
|
186
|
+
// or a boolean; anything else is named by its kind ("[object Array]").
|
|
187
|
+
const LOG_MAX = 8;
|
|
188
|
+
const loggable = (v: unknown): unknown => (
|
|
189
|
+
v === undefined || v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
|
|
190
|
+
? v
|
|
191
|
+
: Object.prototype.toString.call(v)
|
|
192
|
+
);
|
|
193
|
+
const asList = (msg: unknown): unknown[] => (Array.isArray(msg) ? msg.slice(0, LOG_MAX) : [msg]).map(loggable);
|
|
194
|
+
// How long a tile gets to start before its host is told that it has not
|
|
195
|
+
// (MothershipConfig.startDeadline). A guess: on a busy machine a tile with
|
|
196
|
+
// nothing wrong with it has been seen to take eight seconds.
|
|
197
|
+
const START_DEADLINE_MS = 15000;
|
|
198
|
+
// A timer is set for no longer than this: a longer wait comes round to none.
|
|
199
|
+
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
200
|
+
// A frame that is out of the document when its deadline passes is looked at
|
|
201
|
+
// again later, and no sooner than this, however short the deadline.
|
|
202
|
+
const OUT_MS = 1000;
|
|
89
203
|
|
|
90
204
|
/**
|
|
91
205
|
* The dock stopped a tile, because its runtime tried to leave the frame it
|
|
@@ -97,23 +211,187 @@ export interface StoppedEvent extends Event {
|
|
|
97
211
|
reason: 'blocked' | 'navigated';
|
|
98
212
|
}
|
|
99
213
|
|
|
214
|
+
/**
|
|
215
|
+
* A tile is not starting. `reason` says what is known of why:
|
|
216
|
+
*
|
|
217
|
+
* - `timeout`: the deadline (`startDeadline`) passed before the tile's root
|
|
218
|
+
* document was handed to its runtime. `stage` says what the tile was
|
|
219
|
+
* waiting for: `dock` (nothing was heard from its frame at all: the loading
|
|
220
|
+
* server is down, or out of reach, or not answering), `shuttle` (the dock
|
|
221
|
+
* was there: the tile's origin refuses the connection or cannot be found,
|
|
222
|
+
* or the runtime on it never ran), `worker` (the runtime was there, its
|
|
223
|
+
* service worker had not said it was ready), `content` (the tile had
|
|
224
|
+
* loaded, in the sense of the `load` event, and its root document had not
|
|
225
|
+
* arrived). Two cases give no way to tell the first two apart, and are
|
|
226
|
+
* `dock`: a loading server from before its dock said it was ready, and a
|
|
227
|
+
* tile origin that takes the connection and never answers, as nothing is
|
|
228
|
+
* heard from a frame before it has loaded. Nothing is stopped: the tile
|
|
229
|
+
* may yet load, and fire `load` after its `error`.
|
|
230
|
+
* - `version`: the dock named a generation of the runtime that this loader
|
|
231
|
+
* does not speak (`generation`): the loader in the page and the loading
|
|
232
|
+
* server are too far apart. Nothing is stopped here either, but little
|
|
233
|
+
* can be expected of the tile.
|
|
234
|
+
* - `worker`: the runtime could not start the tile's service worker. Some
|
|
235
|
+
* browsers refuse one to a frame of another site once the user blocks
|
|
236
|
+
* cross-site storage.
|
|
237
|
+
* - `unsupported`: the browser lacks what the runtime needs.
|
|
238
|
+
* - `content`: the tile's root document is not to be had: resolving it
|
|
239
|
+
* failed, or the tile's worker gave up waiting for it (after a minute: a
|
|
240
|
+
* deadline shorter than that has reported it first, as `timeout`).
|
|
241
|
+
*
|
|
242
|
+
* A start (a frame the tile is attached to, each time it loads) fires one at
|
|
243
|
+
* most. `worker` and `unsupported` are the runtime's own account, which
|
|
244
|
+
* passes through the tile's origin on its way here, and a dock passes on what
|
|
245
|
+
* its frame says under any name: what runs on that origin can have the start
|
|
246
|
+
* reported as failed, for any of these reasons. On an origin made for the
|
|
247
|
+
* one load nothing of the tile's runs before it has started, and no other
|
|
248
|
+
* tile is there; tiles that share a named origin can do it to one another.
|
|
249
|
+
*/
|
|
250
|
+
export interface TileErrorEvent extends Event {
|
|
251
|
+
reason: 'timeout' | 'version' | 'worker' | 'unsupported' | 'content';
|
|
252
|
+
/** With `timeout`: what the tile was still waiting for. */
|
|
253
|
+
stage?: 'dock' | 'shuttle' | 'worker' | 'content';
|
|
254
|
+
/** With `version`: the generation the dock named, when it named a number. */
|
|
255
|
+
generation?: number;
|
|
256
|
+
}
|
|
257
|
+
// What a tile's runtime comes up through, in order: what a start is waiting
|
|
258
|
+
// for, until it waits for nothing.
|
|
259
|
+
const STAGES: readonly TileErrorEvent['stage'][] = ['dock', 'shuttle', 'worker', 'content'];
|
|
260
|
+
|
|
261
|
+
// What a tile may ask of the page it runs in, when the host does not say
|
|
262
|
+
// (MothershipConfig.budget). Guesses, every one, at what an ordinary tile
|
|
263
|
+
// never comes near and a page can bear from each tile it shows.
|
|
264
|
+
const BUDGET: Required<TileBudget> = {
|
|
265
|
+
// A tile that tells its host of every frame it draws, or of the pointer as
|
|
266
|
+
// it moves, sends 60 to 120 messages a second.
|
|
267
|
+
messagesPerSecond: 200,
|
|
268
|
+
messageBurst: 400,
|
|
269
|
+
// More than a browser asks of one server at once over HTTP/1.1 (six), so
|
|
270
|
+
// that a loader which fetches is not slowed much; few enough that what a
|
|
271
|
+
// loader is at work on for one tile stays small. (An answer counts until
|
|
272
|
+
// it is posted, not until the tile has it: what is on its way down, copied
|
|
273
|
+
// at every hop, is as much as the tile asked for faster than it reads.)
|
|
274
|
+
requestsInFlight: 16,
|
|
275
|
+
requestsQueued: 2000,
|
|
276
|
+
logLines: 10,
|
|
277
|
+
};
|
|
278
|
+
// A resource that has been resolving for this long no longer counts as in
|
|
279
|
+
// flight: a server that stalls on some of a tile's resources does not get to
|
|
280
|
+
// keep the others waiting behind them for good.
|
|
281
|
+
const HOLD_MS = 10000;
|
|
282
|
+
// No resource of a tile's has a path longer than this. A request for one is
|
|
283
|
+
// answered without being kept: what waits its turn has to stay small.
|
|
284
|
+
const MAX_PATH = 8192;
|
|
285
|
+
// Requests that waited their turn are started this many at a time, and the
|
|
286
|
+
// page's thread is given back before the next lot. A loader that answers
|
|
287
|
+
// some resources at once would otherwise have each one start the next as it
|
|
288
|
+
// ended, and all that waited would be resolved in one go.
|
|
289
|
+
const RUN = 16;
|
|
290
|
+
// What a tile's runtime says for itself (that it is ready, that the tile was
|
|
291
|
+
// closed, or stopped) is counted apart from what the tile says, and each
|
|
292
|
+
// kind apart from the others. A tile can spend its own budget, and it can
|
|
293
|
+
// have its runtime say any of these as often as it likes: neither may keep
|
|
294
|
+
// its host from hearing that it was stopped. (What is left to a tile is to
|
|
295
|
+
// have its runtime say that very thing, and then the host has heard it.)
|
|
296
|
+
// There are a few of each in a tile's life, and a few are all that is heard.
|
|
297
|
+
const OWN = new Set([RCV_DOCK_READY, RCV_DOCK_STOPPED, RCV_SHUTTLE_READY, RCV_SHUTTLE_CLOSED, RCV_WORKER_READY]);
|
|
298
|
+
const OWN_BURST = 20;
|
|
299
|
+
const OWN_PER_SECOND = 2;
|
|
300
|
+
|
|
301
|
+
// The budget a host gave, with ours wherever it gave none we can use.
|
|
302
|
+
function budgetFrom (given?: TileBudget | null): Required<TileBudget> {
|
|
303
|
+
const budget = { ...BUDGET };
|
|
304
|
+
for (const name of Object.keys(BUDGET) as (keyof TileBudget)[]) {
|
|
305
|
+
const n = given?.[name];
|
|
306
|
+
// (Nothing is ever resolved with no request in flight.)
|
|
307
|
+
if (typeof n === 'number' && n >= (name === 'requestsInFlight' ? 1 : 0)) budget[name] = n;
|
|
308
|
+
}
|
|
309
|
+
return budget;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// So many at once, and so many a second from then on.
|
|
313
|
+
class Allowance {
|
|
314
|
+
#burst: number;
|
|
315
|
+
#perSecond: number;
|
|
316
|
+
#left: number;
|
|
317
|
+
#at = performance.now();
|
|
318
|
+
constructor (burst: number, perSecond: number) {
|
|
319
|
+
this.#burst = this.#left = burst;
|
|
320
|
+
this.#perSecond = perSecond;
|
|
321
|
+
}
|
|
322
|
+
// Takes one, if there is one to take.
|
|
323
|
+
spend (): boolean {
|
|
324
|
+
const now = performance.now();
|
|
325
|
+
if (now > this.#at) this.#left = Math.min(this.#burst, this.#left + (now - this.#at) * this.#perSecond / 1000);
|
|
326
|
+
this.#at = now;
|
|
327
|
+
if (this.#left < 1) return false;
|
|
328
|
+
this.#left--;
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// What a tile has used of its budget, in the frame it is in.
|
|
334
|
+
interface Usage {
|
|
335
|
+
id: string | undefined; // the frame, by the id the tile's runtime has in it
|
|
336
|
+
said: Allowance; // messages: the tile's
|
|
337
|
+
own: Map<string, Allowance>; // and its runtime's own, each kind for itself
|
|
338
|
+
over: boolean; // it has been said that the tile is over its budget
|
|
339
|
+
inFlight: number; // resources being resolved
|
|
340
|
+
waiting: { path: string, requestId: number }[]; // requests that wait their turn
|
|
341
|
+
run: number; // how many of those were started since the page's thread was last given back
|
|
342
|
+
paused: boolean; // it is being given back now
|
|
343
|
+
logged: number; // lines in the console
|
|
344
|
+
}
|
|
345
|
+
|
|
100
346
|
/** A tiles-protocol message from a tile: `protocol` ("data"), `kind` ("payload", "ready"), and its `payload`. The mothership attaches no meaning to any of them. */
|
|
101
347
|
export interface ProtocolEvent extends Event {
|
|
102
348
|
protocol: string;
|
|
103
349
|
kind: string;
|
|
104
350
|
payload: unknown;
|
|
351
|
+
/** What the tile's dock said as it passed the message on; left out when it said nothing. */
|
|
352
|
+
dock?: DockStamp;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* What a tile's dock says of the user and that tile: `activated` when the
|
|
357
|
+
* user has just pressed or typed inside the tile itself, not elsewhere on the
|
|
358
|
+
* page and not in another tile. The dock is the loading server's page, which
|
|
359
|
+
* the tile cannot script, so this is not the tile's to say.
|
|
360
|
+
*
|
|
361
|
+
* Read it to refuse, never to grant: a loading server from before its dock
|
|
362
|
+
* said this passes on whatever came from below under that name.
|
|
363
|
+
*/
|
|
364
|
+
export interface DockStamp {
|
|
365
|
+
activated: boolean;
|
|
105
366
|
}
|
|
106
367
|
|
|
107
368
|
export class TileMothership {
|
|
108
369
|
#loaders: TileLoader[] = [];
|
|
109
370
|
#conf: MothershipConfig;
|
|
110
|
-
|
|
111
|
-
|
|
371
|
+
// Which tile a window speaks for: its dock's window. Weakly, so that the
|
|
372
|
+
// mothership never keeps a tile alive. A frame in the document keeps its
|
|
373
|
+
// window, and so its tile, reachable; once the frame is gone and let go of,
|
|
374
|
+
// so is the entry, and the tile with everything it holds (its manifest, its
|
|
375
|
+
// loader, for some loaders the tile's whole content) is the host's alone to
|
|
376
|
+
// keep or drop. Nothing has to be called for that.
|
|
377
|
+
#tiles = new WeakMap<object, Tile>();
|
|
378
|
+
// What each tile has used of its budget: weakly too.
|
|
379
|
+
#budget: Required<TileBudget>;
|
|
380
|
+
#usage = new WeakMap<Tile, Usage>();
|
|
112
381
|
constructor (conf: MothershipConfig = {}) {
|
|
113
382
|
this.#conf = conf;
|
|
383
|
+
this.#budget = budgetFrom(conf.budget);
|
|
114
384
|
}
|
|
385
|
+
// What init() has listening, kept so that destroy() can take it away.
|
|
386
|
+
#listener: ((ev: MessageEvent) => void) | undefined;
|
|
387
|
+
/**
|
|
388
|
+
* Starts listening to the tiles' docks. Once is enough, and once is all it
|
|
389
|
+
* does: called again it changes nothing, where a second listener would
|
|
390
|
+
* answer every request twice.
|
|
391
|
+
*/
|
|
115
392
|
init () {
|
|
116
|
-
|
|
393
|
+
if (this.#listener) return;
|
|
394
|
+
this.#listener = async (ev: MessageEvent) => {
|
|
117
395
|
const { action } = ev.data || {};
|
|
118
396
|
if (typeof action !== 'string') return;
|
|
119
397
|
// Any frame can post a message, and say anything in it: the window
|
|
@@ -121,46 +399,63 @@ export class TileMothership {
|
|
|
121
399
|
// dock, on the loading server's origin, and it stays there; a message
|
|
122
400
|
// from one of our frames that is somewhere else is not from a dock.
|
|
123
401
|
// Messages still carry an id; we don't read it.
|
|
124
|
-
const
|
|
125
|
-
if (!
|
|
126
|
-
const
|
|
402
|
+
const tile = this.tileForWindow(ev.source);
|
|
403
|
+
if (!tile || ev.origin !== this.getLoadOrigin()) return;
|
|
404
|
+
const id = tile.runtimeId;
|
|
405
|
+
// A tile says as much as it likes, and can have its runtime say the
|
|
406
|
+
// same: what is listened to is bounded. Requests for its resources
|
|
407
|
+
// have a bound of their own, below.
|
|
408
|
+
const used = this.#used(tile);
|
|
409
|
+
if (action !== RCV_WORKER_REQUEST && !this.#admit(used, action)) return;
|
|
127
410
|
if (action === TILES_WARNING) {
|
|
128
|
-
|
|
411
|
+
this.#log(used, 'warn', `[W:${id}]`, ...asList(ev.data.msg));
|
|
412
|
+
// The worker gave up on a request of its tile's that we never
|
|
413
|
+
// answered. Before the tile is up, that is its root document.
|
|
414
|
+
if (ev.data.code === 'unanswered') tile.failed('content');
|
|
129
415
|
}
|
|
130
416
|
else if (action === TILES_ERROR) {
|
|
131
|
-
|
|
417
|
+
this.#log(used, 'error', `[S:${id}]`, ...asList(ev.data.msg));
|
|
418
|
+
// With a code, it is what kept the runtime from starting the tile.
|
|
419
|
+
const { code } = ev.data;
|
|
420
|
+
if (code === 'worker' || code === 'unsupported') tile.failed(code);
|
|
132
421
|
}
|
|
133
422
|
else if (action === RCV_DOCK_STOPPED) {
|
|
134
423
|
const reason = ev.data.payload?.reason === 'blocked' ? 'blocked' : 'navigated';
|
|
135
|
-
|
|
424
|
+
this.#log(used, 'error', `[D:${id}] The tile's runtime tried to navigate (${reason}); the tile was stopped.`);
|
|
136
425
|
tile.dispatchEvent(Object.assign(new Event('stopped'), { reason }));
|
|
426
|
+
// The host has been told what became of it: it is waited for no longer.
|
|
427
|
+
tile.awaits();
|
|
428
|
+
}
|
|
429
|
+
else if (action === RCV_SHUTTLE_CLOSED) {
|
|
430
|
+
tile.runtimeClosed();
|
|
431
|
+
}
|
|
432
|
+
else if (action === RCV_DOCK_READY) {
|
|
433
|
+
// The loading server is there. Whether we can talk to what it runs
|
|
434
|
+
// is in the generation it names; a number we do not know is said to
|
|
435
|
+
// the host, and the rest is left to happen or not.
|
|
436
|
+
const generation = ev.data.payload?.generation;
|
|
437
|
+
if (GENERATIONS.includes(generation)) tile.awaits('shuttle');
|
|
438
|
+
else tile.failed('version', typeof generation === 'number' ? { generation } : {});
|
|
137
439
|
}
|
|
138
440
|
else if (action === RCV_SHUTTLE_READY) {
|
|
139
|
-
|
|
441
|
+
tile.awaits('worker');
|
|
442
|
+
tile.post(SND_WORKER_LOAD, { id });
|
|
140
443
|
}
|
|
141
444
|
else if (action === RCV_WORKER_READY) {
|
|
142
445
|
tile.dispatchEvent(new Event('load'));
|
|
446
|
+
tile.awaits('content');
|
|
143
447
|
}
|
|
144
448
|
else if (action === RCV_WORKER_REQUEST) {
|
|
145
449
|
const { type, payload } = ev.data;
|
|
146
450
|
if (type === 'resolve-path') {
|
|
451
|
+
// The worker always sends one; without it there is no request to answer.
|
|
452
|
+
if (!payload || typeof payload !== 'object') return;
|
|
147
453
|
const { path, requestId } = payload;
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
// Answer all the same, or the worker waits for ever.
|
|
154
|
-
console.error(`Could not resolve ${path}:`, err);
|
|
155
|
-
res = { ok: false, status: 502, statusText: 'Bad Gateway' };
|
|
156
|
-
}
|
|
157
|
-
// Every document the worker serves, 404s included, carries the
|
|
158
|
-
// policy: the tile can script anything on its origin, so nothing
|
|
159
|
-
// on it may be unconfined.
|
|
160
|
-
const response = res.ok
|
|
161
|
-
? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
|
|
162
|
-
: { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
|
|
163
|
-
this.sendToShuttle(id, SND_WORKER_RESPONSE, { requestId, response });
|
|
454
|
+
// Nor is there one without a path, which is a string, and a number
|
|
455
|
+
// to answer it by: nothing else is the worker's, and nothing else is
|
|
456
|
+
// ours to resolve or spell out.
|
|
457
|
+
if (typeof path !== 'string' || typeof requestId !== 'number') return;
|
|
458
|
+
this.#request(tile, used, path, requestId);
|
|
164
459
|
}
|
|
165
460
|
}
|
|
166
461
|
else if (action.startsWith(PROTOCOL_UP)) {
|
|
@@ -170,9 +465,169 @@ export class TileMothership {
|
|
|
170
465
|
const protocol = rest.slice(0, dash);
|
|
171
466
|
const kind = rest.slice(dash + 1);
|
|
172
467
|
const { payload } = ev.data;
|
|
173
|
-
|
|
468
|
+
// What the dock said of the user as it passed this on, when it said.
|
|
469
|
+
const activated = ev.data.dock?.activated;
|
|
470
|
+
const dock = typeof activated === 'boolean' ? { dock: { activated } } : {};
|
|
471
|
+
tile.dispatchEvent(Object.assign(new Event('protocol'), { protocol, kind, payload, ...dock }));
|
|
174
472
|
}
|
|
175
|
-
}
|
|
473
|
+
};
|
|
474
|
+
window.addEventListener('message', this.#listener);
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Stops listening: what init() did, undone. The page's listener is what
|
|
478
|
+
* keeps a mothership, with its loaders and all they hold, for as long as
|
|
479
|
+
* the page lives; without it they are the host's to keep or drop. Tiles
|
|
480
|
+
* that are still running get no more answers, so close them first.
|
|
481
|
+
* init() starts it again.
|
|
482
|
+
*/
|
|
483
|
+
destroy () {
|
|
484
|
+
if (!this.#listener) return;
|
|
485
|
+
window.removeEventListener('message', this.#listener);
|
|
486
|
+
this.#listener = undefined;
|
|
487
|
+
}
|
|
488
|
+
// What a tile has used of its budget. A tile that is rendered again starts
|
|
489
|
+
// again, and its budget with it.
|
|
490
|
+
#used (tile: Tile): Usage {
|
|
491
|
+
let used = this.#usage.get(tile);
|
|
492
|
+
if (!used || used.id !== tile.runtimeId) {
|
|
493
|
+
const { messageBurst, messagesPerSecond } = this.#budget;
|
|
494
|
+
used = {
|
|
495
|
+
id: tile.runtimeId,
|
|
496
|
+
said: new Allowance(messageBurst, messagesPerSecond),
|
|
497
|
+
own: new Map(),
|
|
498
|
+
over: false,
|
|
499
|
+
inFlight: 0,
|
|
500
|
+
waiting: [],
|
|
501
|
+
run: 0,
|
|
502
|
+
paused: false,
|
|
503
|
+
logged: 0,
|
|
504
|
+
};
|
|
505
|
+
this.#usage.set(tile, used);
|
|
506
|
+
}
|
|
507
|
+
return used;
|
|
508
|
+
}
|
|
509
|
+
// Whether a message is within what its tile may send. One that is not is
|
|
510
|
+
// dropped, and the first time that is said.
|
|
511
|
+
#admit (used: Usage, action: string): boolean {
|
|
512
|
+
let allowance = used.said;
|
|
513
|
+
if (OWN.has(action)) {
|
|
514
|
+
allowance = used.own.get(action) ?? new Allowance(OWN_BURST, OWN_PER_SECOND);
|
|
515
|
+
used.own.set(action, allowance);
|
|
516
|
+
}
|
|
517
|
+
if (allowance.spend()) return true;
|
|
518
|
+
this.#over(used, 'sends more messages');
|
|
519
|
+
return false;
|
|
520
|
+
}
|
|
521
|
+
#over (used: Usage, how: string) {
|
|
522
|
+
if (used.over) return;
|
|
523
|
+
used.over = true;
|
|
524
|
+
this.#log(used, 'warn', `[M:${used.id}] This tile ${how} than its budget allows: what is over is dropped.`);
|
|
525
|
+
}
|
|
526
|
+
// What a tile has logged is logged a few times and then no more. A tile's
|
|
527
|
+
// runtime can be made to say anything, as often as the tile likes, and so
|
|
528
|
+
// can its requests be made to fail.
|
|
529
|
+
#log (used: Usage, level: 'warn' | 'error', ...args: unknown[]) {
|
|
530
|
+
const { logLines } = this.#budget;
|
|
531
|
+
if (used.logged >= logLines) return;
|
|
532
|
+
used.logged++;
|
|
533
|
+
console[level](...args);
|
|
534
|
+
if (used.logged >= logLines) console.warn(`[M:${used.id}] Nothing more of this tile is logged.`);
|
|
535
|
+
}
|
|
536
|
+
// A tile's requests for its resources are resolved a few at a time, in the
|
|
537
|
+
// order they came, and the rest wait: resolving is the loader's work (a
|
|
538
|
+
// fetch, for some), and every answer is copied at each hop on its way to
|
|
539
|
+
// the tile. So that what is in flight is what the page chose, not what the
|
|
540
|
+
// tile asked for.
|
|
541
|
+
#request (tile: Tile, used: Usage, path: string, requestId: number) {
|
|
542
|
+
const { requestsInFlight, requestsQueued } = this.#budget;
|
|
543
|
+
if (path.length > MAX_PATH) return this.#turnDown(tile, used, requestId, 404);
|
|
544
|
+
if (used.inFlight < requestsInFlight) return void this.#resolve(tile, used, path, requestId);
|
|
545
|
+
if (used.waiting.length < requestsQueued) return void used.waiting.push({ path, requestId });
|
|
546
|
+
// More at once than a tile has any use for.
|
|
547
|
+
this.#over(used, 'asks for more of its resources at once');
|
|
548
|
+
this.#turnDown(tile, used, requestId, 503);
|
|
549
|
+
}
|
|
550
|
+
// A request that is not resolved is answered all the same, so that a worker
|
|
551
|
+
// does not wait for nothing: for as long as its tile has messages to
|
|
552
|
+
// spend, as each answer is one more that the tile has us send.
|
|
553
|
+
#turnDown (tile: Tile, used: Usage, requestId: number, status: number) {
|
|
554
|
+
if (!used.said.spend()) return;
|
|
555
|
+
tile.post(SND_WORKER_RESPONSE, { requestId, response: { status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined } });
|
|
556
|
+
}
|
|
557
|
+
// The next of the requests that wait, while there is room for them: a few
|
|
558
|
+
// (RUN), and then the page's thread is given back before any more. Those
|
|
559
|
+
// of a frame the tile has left are for a worker that is gone.
|
|
560
|
+
#next (tile: Tile, used: Usage) {
|
|
561
|
+
if (tile.runtimeId !== used.id) used.waiting.length = 0;
|
|
562
|
+
while (used.waiting.length && used.inFlight < this.#budget.requestsInFlight) {
|
|
563
|
+
if (used.run >= RUN) return this.#pause(tile, used);
|
|
564
|
+
used.run++;
|
|
565
|
+
const { path, requestId } = used.waiting.shift()!;
|
|
566
|
+
void this.#resolve(tile, used, path, requestId);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
// Lets the page get on with whatever else it has to do, then goes on with
|
|
570
|
+
// the requests that wait: in a task of its own, by a message to ourselves.
|
|
571
|
+
// (Not by a timer: a browser holds those back in a page that is not in
|
|
572
|
+
// view, and a tile that loads there would get its resources a few a second.)
|
|
573
|
+
#pause (tile: Tile, used: Usage) {
|
|
574
|
+
if (used.paused) return;
|
|
575
|
+
used.paused = true;
|
|
576
|
+
const { port1, port2 } = new MessageChannel();
|
|
577
|
+
port1.onmessage = () => {
|
|
578
|
+
port1.close();
|
|
579
|
+
used.paused = false;
|
|
580
|
+
used.run = 0;
|
|
581
|
+
this.#next(tile, used);
|
|
582
|
+
};
|
|
583
|
+
port2.postMessage(null);
|
|
584
|
+
}
|
|
585
|
+
async #resolve (tile: Tile, used: Usage, path: string, requestId: number) {
|
|
586
|
+
// In flight until it is answered, or has been long enough at it.
|
|
587
|
+
used.inFlight++;
|
|
588
|
+
let held = true;
|
|
589
|
+
const release = () => {
|
|
590
|
+
if (!held) return;
|
|
591
|
+
held = false;
|
|
592
|
+
used.inFlight--;
|
|
593
|
+
this.#next(tile, used);
|
|
594
|
+
};
|
|
595
|
+
const hold = setTimeout(release, HOLD_MS);
|
|
596
|
+
// (Under Node, where the tests run, a timer would keep the process up.)
|
|
597
|
+
(hold as { unref?: () => void }).unref?.();
|
|
598
|
+
try {
|
|
599
|
+
let response;
|
|
600
|
+
let served = false;
|
|
601
|
+
try {
|
|
602
|
+
const res = await tile.resolvePath(path);
|
|
603
|
+
// Every document the worker serves, 404s included, carries the
|
|
604
|
+
// policy: the tile can script anything on its origin, so nothing
|
|
605
|
+
// on it may be unconfined.
|
|
606
|
+
response = res.ok
|
|
607
|
+
? { status: res.status, headers: this.hardenResponse(res.headers), body: res.body }
|
|
608
|
+
: { status: res.status, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
|
|
609
|
+
served = res.ok;
|
|
610
|
+
}
|
|
611
|
+
catch (err) {
|
|
612
|
+
// Answer all the same, or the worker waits for ever. Resolving the
|
|
613
|
+
// path can throw, and so can hardening what it resolved to: a
|
|
614
|
+
// resource's headers are the tile's to write.
|
|
615
|
+
this.#log(used, 'error', `Could not resolve ${path}:`, err);
|
|
616
|
+
response = { status: 502, headers: this.hardenResponse({ 'content-type': 'text/plain' }), body: undefined };
|
|
617
|
+
}
|
|
618
|
+
tile.post(SND_WORKER_RESPONSE, { requestId, response });
|
|
619
|
+
// The root document is what a tile starts with: once it is on its
|
|
620
|
+
// way the tile is up, and when it is not to be had the host hears.
|
|
621
|
+
// (Unless the tile has left that frame while we were resolving.)
|
|
622
|
+
if (path === '/' && tile.runtimeId === used.id) {
|
|
623
|
+
if (served) tile.awaits();
|
|
624
|
+
else tile.failed('content');
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
finally {
|
|
628
|
+
clearTimeout(hold);
|
|
629
|
+
release();
|
|
630
|
+
}
|
|
176
631
|
}
|
|
177
632
|
/**
|
|
178
633
|
* The headers a tile document ships with: the resource's own, plus the
|
|
@@ -182,35 +637,126 @@ export class TileMothership {
|
|
|
182
637
|
hardenResponse (headers?: MaslHeaders): MaslHeaders {
|
|
183
638
|
return tileResponseHeaders(headers);
|
|
184
639
|
}
|
|
640
|
+
/** The tile whose dock `source` is the window of, if it is one of ours. */
|
|
185
641
|
tileForWindow (source: MessageEventSource | null): Tile | undefined {
|
|
186
|
-
|
|
187
|
-
if (id) return this.#id2tile.get(id);
|
|
642
|
+
return source ? this.#tiles.get(source as object) : undefined;
|
|
188
643
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
644
|
+
/** @internal A tile's frame has this window: messages from it are that tile's. */
|
|
645
|
+
dock (win: object, tile: Tile) {
|
|
646
|
+
this.#tiles.set(win, tile);
|
|
647
|
+
}
|
|
648
|
+
/** @internal The window no longer speaks for a tile. */
|
|
649
|
+
undock (win: object) {
|
|
650
|
+
this.#tiles.delete(win);
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* @internal What a tile's runtime is told to start with. The manifest's
|
|
654
|
+
* `sizing` goes along: the shuttle measures the content of a tile that
|
|
655
|
+
* declares `fit` (see @dasl/tile-loader/size). So does whether its origin
|
|
656
|
+
* is its own, made for this load: one that is can be thrown away with it.
|
|
657
|
+
*/
|
|
658
|
+
loadPayload (tile: Tile): Record<string, unknown> {
|
|
659
|
+
const sizing = tile.manifest?.sizing;
|
|
660
|
+
return {
|
|
661
|
+
id: tile.runtimeId,
|
|
662
|
+
webrtcGuard: this.#conf.webrtcGuard ?? 'exhaust',
|
|
663
|
+
ephemeral: this.ephemeral,
|
|
664
|
+
...(sizing ? { sizing } : {}),
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
/** @internal How long a tile gets to start, in milliseconds; 0 for no deadline. */
|
|
668
|
+
get startDeadline (): number {
|
|
669
|
+
const ms = this.#conf.startDeadline;
|
|
670
|
+
if (typeof ms !== 'number' || Number.isNaN(ms) || ms < 0) return START_DEADLINE_MS;
|
|
671
|
+
return Number.isFinite(ms) ? Math.min(ms, MAX_TIMER_MS) : 0;
|
|
672
|
+
}
|
|
673
|
+
/** Whether tiles get an origin of their own for every load (no `namedOrigin`). */
|
|
674
|
+
get ephemeral (): boolean {
|
|
675
|
+
return !this.#namedHost();
|
|
676
|
+
}
|
|
677
|
+
// The named origin's host, if the configuration names one.
|
|
678
|
+
#namedHost (): string | undefined {
|
|
679
|
+
const named = this.#conf.namedOrigin ?? this.#conf.tileHost;
|
|
680
|
+
if (!named) return undefined;
|
|
681
|
+
return /^https?:\/\//.test(named) ? new URL(named).host : named;
|
|
682
|
+
}
|
|
683
|
+
// The host of a tile origin for one load, as the loading server makes them:
|
|
684
|
+
// twenty random letters under its base host, which is its own host without
|
|
685
|
+
// the `load.` it starts with (and with its port). A loading server that is
|
|
686
|
+
// somewhere else does not say where its tile origins are: it is then left
|
|
687
|
+
// to pick the origin itself, in a redirect, as it always could.
|
|
688
|
+
#freshHost (): string | undefined {
|
|
689
|
+
const { host } = new URL(this.getLoadOrigin());
|
|
690
|
+
return host.startsWith(LOAD_LABEL) ? `${randomLabel()}.${host.slice(LOAD_LABEL.length)}` : undefined;
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* @internal The tile origin a frame's address names, when the address is
|
|
694
|
+
* the dock's on our loading server and names one (getLoadSource() does).
|
|
695
|
+
*/
|
|
696
|
+
originNamedIn (src: unknown): string | undefined {
|
|
697
|
+
if (typeof src !== 'string' || !src) return undefined;
|
|
698
|
+
let url: URL;
|
|
699
|
+
try { url = new URL(src); }
|
|
700
|
+
catch { return undefined; }
|
|
701
|
+
if (url.origin !== this.getLoadOrigin() || url.pathname !== dockPath) return undefined;
|
|
702
|
+
const [host, ...more] = url.searchParams.getAll('tile');
|
|
703
|
+
if (!host || more.length || !/^[a-z0-9.-]+(?::\d+)?$/.test(host)) return undefined;
|
|
704
|
+
return `${url.protocol}//${host}`;
|
|
194
705
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
706
|
+
/**
|
|
707
|
+
* @internal Has a tile origin wiped, from a frame of our own making: what
|
|
708
|
+
* closing a tile comes down to once its frame is out of the document.
|
|
709
|
+
*
|
|
710
|
+
* The wipe answers a page of the origin it empties and no one else, and
|
|
711
|
+
* this page is not one. So a frame is made, out of sight, that loads the
|
|
712
|
+
* dock for that origin again; the dock frames the runtime there, a shuttle
|
|
713
|
+
* that never had a tile in it, and is told to close and wipe, in the words
|
|
714
|
+
* a tile's own frame is told. That shuttle lets the worker go and has the
|
|
715
|
+
* loading server wipe the origin, and the answer comes back up. Nothing in
|
|
716
|
+
* that frame was ever within the tile's reach, so its answer is not the
|
|
717
|
+
* tile's to give; and the shuttle only gets to run once the tile's own
|
|
718
|
+
* pages, which share its origin, are done with whatever they do on their
|
|
719
|
+
* way out, so it does not come too soon.
|
|
720
|
+
*
|
|
721
|
+
* `credentialless` is for a tile that ran in a credentialless frame: the
|
|
722
|
+
* browser keeps what such a frame stores apart, and only another one
|
|
723
|
+
* reaches it.
|
|
724
|
+
*
|
|
725
|
+
* Resolves to whether the origin was wiped: true when the runtime says so,
|
|
726
|
+
* false when it says not, or says nothing for WIPE_MS.
|
|
727
|
+
*/
|
|
728
|
+
wipeOrigin (origin: string, credentialless = false): Promise<boolean> {
|
|
729
|
+
const loadOrigin = this.getLoadOrigin();
|
|
730
|
+
const url = new URL(dockPath, loadOrigin);
|
|
731
|
+
url.searchParams.set('tile', new URL(origin).host);
|
|
732
|
+
return new Promise<boolean>((resolve) => {
|
|
733
|
+
const ifr = el('iframe', {
|
|
734
|
+
src: url.href,
|
|
735
|
+
// The dock and the runtime need no more than this to wipe.
|
|
736
|
+
sandbox: 'allow-scripts allow-same-origin',
|
|
737
|
+
// The attribute is there or it is not; it has no value.
|
|
738
|
+
credentialless: credentialless ? '' : undefined,
|
|
739
|
+
hidden: '',
|
|
740
|
+
style: { display: 'none' },
|
|
741
|
+
}) as HTMLIFrameElement;
|
|
742
|
+
const done = (wiped: boolean) => {
|
|
743
|
+
clearTimeout(timer);
|
|
744
|
+
window.removeEventListener('message', onMessage);
|
|
745
|
+
ifr.remove();
|
|
746
|
+
resolve(wiped);
|
|
747
|
+
};
|
|
748
|
+
// Only that frame's window, on the loading server, speaks for it.
|
|
749
|
+
const onMessage = (ev: MessageEvent) => {
|
|
750
|
+
if (!ev.source || ev.source !== ifr.contentWindow || ev.origin !== loadOrigin) return;
|
|
751
|
+
if (ev.data?.action === RCV_SHUTTLE_CLOSED) done(ev.data.payload?.wiped !== false);
|
|
752
|
+
};
|
|
753
|
+
const timer = setTimeout(() => done(false), WIPE_MS);
|
|
754
|
+
window.addEventListener('message', onMessage);
|
|
755
|
+
ifr.addEventListener('load', () => {
|
|
756
|
+
ifr.contentWindow?.postMessage({ action: SND_SHUTTLE_CLOSE, payload: { wipe: true } }, loadOrigin);
|
|
757
|
+
}, { once: true });
|
|
758
|
+
(document.body ?? document.documentElement).append(ifr);
|
|
759
|
+
});
|
|
214
760
|
}
|
|
215
761
|
// Adds a loader that will handle matching requests to load a tile.
|
|
216
762
|
// - `loader` is an object that knows how to load a tile for a specific scheme
|
|
@@ -228,47 +774,124 @@ export class TileMothership {
|
|
|
228
774
|
return new URL(/^https?:\/\//.test(domain) ? domain : `https://${domain}`).origin;
|
|
229
775
|
}
|
|
230
776
|
/**
|
|
231
|
-
* What a tile's frame loads: the dock, on the loading server
|
|
232
|
-
*
|
|
777
|
+
* What a tile's frame loads: the dock, on the loading server, for a tile
|
|
778
|
+
* origin that the address names. Unless the configuration names one
|
|
779
|
+
* (`namedOrigin`), that is a fresh origin at every call, made here as the
|
|
780
|
+
* loading server would make it, so an address is for one frame. Named
|
|
781
|
+
* here, the origin is one the page knows, which is what lets it be wiped
|
|
782
|
+
* once the frame its tile ran in is gone (see Tile.close()); and it saves
|
|
783
|
+
* the redirect in which the loading server would have picked it.
|
|
233
784
|
*/
|
|
234
785
|
getLoadSource (): string {
|
|
235
786
|
const url = new URL(dockPath, this.getLoadOrigin());
|
|
236
|
-
|
|
787
|
+
const named = this.#namedHost() ?? this.#freshHost();
|
|
788
|
+
if (named) url.searchParams.set('tile', named);
|
|
237
789
|
return url.href;
|
|
238
790
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
791
|
+
/**
|
|
792
|
+
* Loads a tile: the first loader that has one for `url` gives it, and it
|
|
793
|
+
* is `false` when none does.
|
|
794
|
+
*
|
|
795
|
+
* `options` say which tile is expected (see TileLoadOptions), and a tile
|
|
796
|
+
* that is not that one is not returned. With options, even none of them
|
|
797
|
+
* (`{}`), a tile that could not be loaded is a rejection, with the
|
|
798
|
+
* TileLoadError that says why. With the URL alone, which is all there was
|
|
799
|
+
* to call this with before, it is `false` as it is for a URL no loader
|
|
800
|
+
* knows, and the error is logged: a host that only looks for a tile keeps
|
|
801
|
+
* working.
|
|
802
|
+
*/
|
|
803
|
+
async loadTile (url: string, options?: TileLoadOptions): Promise<Tile | false> {
|
|
804
|
+
try {
|
|
805
|
+
for (const ldr of this.#loaders) {
|
|
806
|
+
const tile = await ldr.load(url, this, options);
|
|
807
|
+
if (!tile) continue;
|
|
808
|
+
// A loader that knows nothing of expected CIDs must not pass for one
|
|
809
|
+
// that checked: whatever made the tile, it has to be one asked for.
|
|
810
|
+
const { cid, manifestCid } = options ?? {};
|
|
811
|
+
const expected = cid !== undefined || manifestCid !== undefined;
|
|
812
|
+
if (expected && !(cid !== undefined && tile.cid === cid) && !(manifestCid !== undefined && tile.manifestCid === manifestCid)) {
|
|
813
|
+
throw new TileLoadError('record-changed', `The tile at ${url} is not the one expected, or has no CID to tell by.`, {
|
|
814
|
+
expected: cid ?? manifestCid,
|
|
815
|
+
actual: cid !== undefined ? tile.cid : tile.manifestCid,
|
|
816
|
+
manifestCid: tile.manifestCid,
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
return tile;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
catch (err) {
|
|
823
|
+
if (options || !(err instanceof TileLoadError)) throw err;
|
|
824
|
+
console.error(`Could not load ${url}:`, err);
|
|
244
825
|
}
|
|
245
826
|
return false;
|
|
246
827
|
}
|
|
247
828
|
}
|
|
248
829
|
|
|
830
|
+
// The loading server is at `load.<base>`, and a tile origin at `<label>.<base>`.
|
|
831
|
+
const LOAD_LABEL = 'load.';
|
|
832
|
+
const LETTERS = 'abcdefghijklmnopqrstuvwxyz';
|
|
833
|
+
// Twenty random letters: the name of a tile origin that no one can guess, and
|
|
834
|
+
// that is not made twice.
|
|
835
|
+
function randomLabel (): string {
|
|
836
|
+
let label = '';
|
|
837
|
+
while (label.length < 20) {
|
|
838
|
+
for (const byte of crypto.getRandomValues(new Uint8Array(32))) {
|
|
839
|
+
// 234 is nine times 26: the bytes from there up would favour the first letters.
|
|
840
|
+
if (byte < 234 && label.length < 20) label += LETTERS[byte % 26];
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
return label;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// Loads a picture once so that it is decoded and cached, then revokes its
|
|
847
|
+
// object URL. For pictures set where no load event says when they are in.
|
|
848
|
+
function releaseWhenLoaded (url: string) {
|
|
849
|
+
if (typeof Image !== 'function') return;
|
|
850
|
+
const img = new Image();
|
|
851
|
+
const release = () => URL.revokeObjectURL(url);
|
|
852
|
+
img.addEventListener('load', release, { once: true });
|
|
853
|
+
img.addEventListener('error', release, { once: true });
|
|
854
|
+
img.src = url;
|
|
855
|
+
}
|
|
856
|
+
|
|
249
857
|
export class Tile extends EventTarget {
|
|
250
858
|
#mothership: TileMothership;
|
|
251
859
|
#url: string;
|
|
252
860
|
#manifest: AnyMasl;
|
|
253
861
|
#pathLoader: TilePathLoader;
|
|
254
|
-
|
|
255
|
-
|
|
862
|
+
// The address a frame of the host's own making loads for this run (getLoadSource()).
|
|
863
|
+
#source: string | undefined;
|
|
864
|
+
// What the close under way will resolve to, and the frame it is closing.
|
|
865
|
+
#closed: Promise<boolean> | undefined;
|
|
866
|
+
#closingFrame: HTMLIFrameElement | undefined;
|
|
867
|
+
// The frame the tile runs in, and the id its runtime knows it by. The frame
|
|
868
|
+
// is held weakly: it is the host's, in the host's document.
|
|
869
|
+
#runtimeId: string | undefined;
|
|
870
|
+
#frame: WeakRef<HTMLIFrameElement> | undefined;
|
|
871
|
+
#window: object | undefined;
|
|
872
|
+
#onFrameLoad: (() => void) | undefined;
|
|
873
|
+
#started = false;
|
|
874
|
+
#closing: Promise<void> | undefined;
|
|
875
|
+
#runtimeDone: (() => void) | undefined;
|
|
876
|
+
#identity: TileIdentity;
|
|
877
|
+
constructor (mothership: TileMothership, url: string, manifest: AnyMasl, pathLoader: TilePathLoader, identity: TileIdentity = {}) {
|
|
256
878
|
super();
|
|
257
879
|
this.#mothership = mothership;
|
|
258
880
|
this.#url = url;
|
|
259
881
|
this.#manifest = manifest;
|
|
260
882
|
this.#pathLoader = pathLoader;
|
|
883
|
+
this.#identity = identity;
|
|
261
884
|
this.addEventListener('load', () => {
|
|
262
885
|
if (this.#manifest?.name) {
|
|
263
886
|
const title = this.#manifest?.name;
|
|
264
|
-
this
|
|
887
|
+
this.post(SND_SET_TITLE, { title });
|
|
265
888
|
const ev = new Event('title-change') as Event & { title?: string };
|
|
266
889
|
ev.title = title;
|
|
267
890
|
this.dispatchEvent(ev);
|
|
268
891
|
}
|
|
269
892
|
const icon = this.#manifest?.icons?.[0]?.src;
|
|
270
893
|
if (icon) {
|
|
271
|
-
this
|
|
894
|
+
this.post(SND_SET_ICON, { path: icon });
|
|
272
895
|
}
|
|
273
896
|
});
|
|
274
897
|
}
|
|
@@ -278,6 +901,22 @@ export class Tile extends EventTarget {
|
|
|
278
901
|
get manifest (): AnyMasl {
|
|
279
902
|
return this.#manifest;
|
|
280
903
|
}
|
|
904
|
+
/**
|
|
905
|
+
* The CID of the record or file this tile was made from, computed by its
|
|
906
|
+
* loader from the bytes it was given: what a host keeps to know the tile
|
|
907
|
+
* again (see TileLoadOptions). Undefined where a loader has none to give.
|
|
908
|
+
*/
|
|
909
|
+
get cid (): string | undefined {
|
|
910
|
+
return this.#identity.cid;
|
|
911
|
+
}
|
|
912
|
+
/** The CID of the tile's manifest alone: its content, whatever record carries it. */
|
|
913
|
+
get manifestCid (): string | undefined {
|
|
914
|
+
return this.#identity.manifestCid;
|
|
915
|
+
}
|
|
916
|
+
/** Whether the tile was checked against a CID its host expected. */
|
|
917
|
+
get pinned (): boolean {
|
|
918
|
+
return this.#identity.pinned === true;
|
|
919
|
+
}
|
|
281
920
|
async resolvePath (path: string): Promise<MaslResponse> {
|
|
282
921
|
const u = new URL(`fake:${path}`);
|
|
283
922
|
return this.#pathLoader.resolvePath(u.pathname);
|
|
@@ -308,6 +947,9 @@ export class Tile extends EventTarget {
|
|
|
308
947
|
'background-position': '50%',
|
|
309
948
|
'aspect-ratio': '16/9',
|
|
310
949
|
}}, [], card);
|
|
950
|
+
// A background has no load event to hang this on: load the picture
|
|
951
|
+
// once ourselves, and the URL (which holds the bytes) can go.
|
|
952
|
+
releaseWhenLoaded(url);
|
|
311
953
|
}
|
|
312
954
|
}
|
|
313
955
|
const title = el('div', { style: {
|
|
@@ -321,7 +963,11 @@ export class Tile extends EventTarget {
|
|
|
321
963
|
if (res.ok) {
|
|
322
964
|
const blob = new Blob([res.body as BlobPart], { type: res.headers?.['content-type'] });
|
|
323
965
|
const url = URL.createObjectURL(blob);
|
|
324
|
-
el('img', { src: url, width: '48', height: '48', alt: 'icon', style: { 'padding-right': '0.5rem' } }, [], title);
|
|
966
|
+
const img = el('img', { src: url, width: '48', height: '48', alt: 'icon', style: { 'padding-right': '0.5rem' } }, [], title);
|
|
967
|
+
// Once decoded the picture stays; the URL, which holds the bytes, need not.
|
|
968
|
+
const release = () => URL.revokeObjectURL(url);
|
|
969
|
+
img.addEventListener('load', release, { once: true });
|
|
970
|
+
img.addEventListener('error', release, { once: true });
|
|
325
971
|
}
|
|
326
972
|
}
|
|
327
973
|
el('span', { style: { 'font-weight': 'bold' } }, [this.#manifest.name || 'Untitled Tile'], title);
|
|
@@ -330,8 +976,17 @@ export class Tile extends EventTarget {
|
|
|
330
976
|
}
|
|
331
977
|
return card;
|
|
332
978
|
}
|
|
979
|
+
/**
|
|
980
|
+
* What a frame of the host's own making loads to run this tile (the frame
|
|
981
|
+
* is then handed to `attachIframe()`): the dock, for an origin made for
|
|
982
|
+
* this one run of the tile. It is the same address every time it is asked
|
|
983
|
+
* for, so that it can sit in a template that is rendered again and again,
|
|
984
|
+
* until the tile is closed: after that it is another run, on another
|
|
985
|
+
* origin.
|
|
986
|
+
*/
|
|
333
987
|
getLoadSource (): string {
|
|
334
|
-
|
|
988
|
+
this.#source ??= this.#mothership.getLoadSource();
|
|
989
|
+
return this.#source;
|
|
335
990
|
}
|
|
336
991
|
/**
|
|
337
992
|
* Sends a tiles-protocol message down to the rendered tile. Messages the
|
|
@@ -339,12 +994,288 @@ export class Tile extends EventTarget {
|
|
|
339
994
|
* means is up to the caller (see `@dasl/tile-loader/data` for tp-data).
|
|
340
995
|
*/
|
|
341
996
|
sendProtocol (protocol: string, kind: string, payload?: unknown) {
|
|
342
|
-
if (!this.#
|
|
343
|
-
this
|
|
997
|
+
if (!this.#runtimeId) throw new Error('The tile is not rendered yet.');
|
|
998
|
+
this.post(`${PROTOCOL_DOWN}${protocol}-${kind}`, payload);
|
|
999
|
+
}
|
|
1000
|
+
/** The id this tile's runtime knows it by, once it is rendered. */
|
|
1001
|
+
get runtimeId (): string | undefined {
|
|
1002
|
+
return this.#runtimeId;
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* @internal Posts to the tile's runtime, by way of its dock: to the dock
|
|
1006
|
+
* and no one else. Should the frame ever be anywhere but on the loading
|
|
1007
|
+
* server, what we say (the tile's documents, the host's data) does not go
|
|
1008
|
+
* with it. A tile whose frame is gone says nothing.
|
|
1009
|
+
*/
|
|
1010
|
+
post (action: string, payload?: unknown) {
|
|
1011
|
+
const win = this.#frame?.deref()?.contentWindow;
|
|
1012
|
+
win?.postMessage({ id: this.#runtimeId, action, payload }, this.#mothership.getLoadOrigin());
|
|
1013
|
+
}
|
|
1014
|
+
// --- Starting
|
|
1015
|
+
// What the host hears of a tile that does not start. A start is a frame
|
|
1016
|
+
// the tile is attached to, and each time that frame loads (which is when
|
|
1017
|
+
// the runtime in it is told to load the tile: see start()). The runtime in
|
|
1018
|
+
// it comes up in steps the mothership hears of, and `#waiting` is the one
|
|
1019
|
+
// that has not happened yet (see TileErrorEvent); it is nothing before
|
|
1020
|
+
// there is a frame, and nothing again once the root document is on its
|
|
1021
|
+
// way. A start that fails is reported once: by the runtime, when it knows
|
|
1022
|
+
// what stopped it; when the root document is not to be had; or by the
|
|
1023
|
+
// deadline, which reports and does nothing else.
|
|
1024
|
+
#waiting: TileErrorEvent['stage'];
|
|
1025
|
+
#reported = false;
|
|
1026
|
+
#rootFailed = false;
|
|
1027
|
+
#deadline: ReturnType<typeof setTimeout> | undefined;
|
|
1028
|
+
// A start, and the time it is given.
|
|
1029
|
+
#watch () {
|
|
1030
|
+
this.#waiting = STAGES[0];
|
|
1031
|
+
this.#reported = this.#rootFailed = false;
|
|
1032
|
+
this.#clock();
|
|
1033
|
+
}
|
|
1034
|
+
// Sets the deadline, for the frame the tile is in now. `out`: that frame
|
|
1035
|
+
// was not in the document when it was last looked at (see #late).
|
|
1036
|
+
#clock (out = false) {
|
|
1037
|
+
clearTimeout(this.#deadline);
|
|
1038
|
+
const ms = this.#mothership.startDeadline;
|
|
1039
|
+
if (!ms) return;
|
|
1040
|
+
// By a weak reference, the way the mothership knows a tile: a deadline
|
|
1041
|
+
// keeps none alive.
|
|
1042
|
+
const weak = new WeakRef(this);
|
|
1043
|
+
const id = this.#runtimeId;
|
|
1044
|
+
this.#deadline = setTimeout(() => {
|
|
1045
|
+
const tile = weak.deref();
|
|
1046
|
+
if (tile) tile.#late(id, out);
|
|
1047
|
+
}, out ? Math.max(ms, OUT_MS) : ms);
|
|
1048
|
+
// (Under Node, where the tests run, a timer would keep the process up.)
|
|
1049
|
+
(this.#deadline as { unref?: () => void }).unref?.();
|
|
1050
|
+
}
|
|
1051
|
+
// The deadline has passed: for the frame the tile was in when it was set,
|
|
1052
|
+
// which it may have left since. A frame that is not in the document loads
|
|
1053
|
+
// nothing, and a host may make one well before it shows it. That time is
|
|
1054
|
+
// not held against the tile, and it must not use the deadline up either,
|
|
1055
|
+
// or a frame put in the page late would never be watched. So a frame that
|
|
1056
|
+
// is out is looked at again later, and one that is found back in is given
|
|
1057
|
+
// its time from there: what is reported is a whole deadline spent in the
|
|
1058
|
+
// document.
|
|
1059
|
+
#late (id: string | undefined, wasOut: boolean) {
|
|
1060
|
+
const ifr = this.#frame?.deref();
|
|
1061
|
+
if (id !== this.#runtimeId || !ifr) return;
|
|
1062
|
+
const out = !ifr.isConnected;
|
|
1063
|
+
if (out || wasOut) return this.#clock(out);
|
|
1064
|
+
this.failed('timeout', { stage: this.#waiting });
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* @internal What this start is waiting for now: a later step than before,
|
|
1068
|
+
* or nothing more, because the tile is up or because it was stopped.
|
|
1069
|
+
*/
|
|
1070
|
+
awaits (stage?: TileErrorEvent['stage']) {
|
|
1071
|
+
if (!this.#waiting) return;
|
|
1072
|
+
if (stage && STAGES.indexOf(stage) <= STAGES.indexOf(this.#waiting)) return;
|
|
1073
|
+
this.#waiting = stage;
|
|
1074
|
+
if (!stage) clearTimeout(this.#deadline);
|
|
1075
|
+
else if (stage === 'content' && this.#rootFailed) this.failed('content');
|
|
1076
|
+
}
|
|
1077
|
+
/**
|
|
1078
|
+
* @internal A start, and the time it is given, from now: for a tile that
|
|
1079
|
+
* had more to do before its runtime could be told to load (one from AT
|
|
1080
|
+
* fetches all of itself first), and was waiting for nothing meanwhile
|
|
1081
|
+
* (`awaits()`). What that took is not the runtime being late.
|
|
1082
|
+
*/
|
|
1083
|
+
watch () {
|
|
1084
|
+
this.#watch();
|
|
1085
|
+
}
|
|
1086
|
+
/**
|
|
1087
|
+
* @internal This start of the tile has failed, or is late: the host is
|
|
1088
|
+
* told, once, with what there is to say of it (`stage`, `generation`). Not
|
|
1089
|
+
* of a frame it has taken out of the document: nothing is expected of that
|
|
1090
|
+
* one.
|
|
1091
|
+
*/
|
|
1092
|
+
failed (reason: TileErrorEvent['reason'], detail: Pick<TileErrorEvent, 'stage' | 'generation'> = {}) {
|
|
1093
|
+
if (!this.#waiting || this.#reported || !this.#frame?.deref()?.isConnected) return;
|
|
1094
|
+
// A worker asks for the root document as soon as it knows its tile,
|
|
1095
|
+
// which can be before it has said that it is ready. A root document that
|
|
1096
|
+
// fails that early is kept until then: `load` first, as when it is late.
|
|
1097
|
+
if (reason === 'content' && this.#waiting !== 'content') {
|
|
1098
|
+
this.#rootFailed = true;
|
|
1099
|
+
return;
|
|
1100
|
+
}
|
|
1101
|
+
this.#reported = true;
|
|
1102
|
+
clearTimeout(this.#deadline);
|
|
1103
|
+
this.dispatchEvent(Object.assign(new Event('error'), { reason, ...detail }));
|
|
1104
|
+
}
|
|
1105
|
+
/** @internal Tells the runtime in the frame to load the tile. */
|
|
1106
|
+
start () {
|
|
1107
|
+
this.#started = true;
|
|
1108
|
+
// A start, and its time, from here: what a tile does before it has its
|
|
1109
|
+
// runtime load it (one that fetches its content first, say) is not the
|
|
1110
|
+
// runtime being late.
|
|
1111
|
+
this.#watch();
|
|
1112
|
+
this.post(SND_SHUTTLE_LOAD, this.#mothership.loadPayload(this));
|
|
344
1113
|
}
|
|
1114
|
+
/** @internal The runtime says it has cleaned up. */
|
|
1115
|
+
runtimeClosed () {
|
|
1116
|
+
this.#runtimeDone?.();
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Runs the tile in `ifr`, a frame of the host's making that loads
|
|
1120
|
+
* `getLoadSource()`. A tile runs in one frame: one it was in before is let
|
|
1121
|
+
* go of (though not removed: that frame is the host's).
|
|
1122
|
+
*/
|
|
345
1123
|
attachIframe (ifr: HTMLIFrameElement) {
|
|
346
|
-
this.#
|
|
347
|
-
|
|
1124
|
+
this.#letGo();
|
|
1125
|
+
this.#runtimeId = crypto.randomUUID(); // we might want to make that pluggable
|
|
1126
|
+
this.#frame = new WeakRef(ifr);
|
|
1127
|
+
// The frame's window is how the tile's messages are known for its own.
|
|
1128
|
+
// It is there once the frame is in a document, and it is a new one if
|
|
1129
|
+
// the frame is taken out and put back, so it is taken down at each load.
|
|
1130
|
+
const track = () => {
|
|
1131
|
+
const win = ifr.contentWindow as object | null;
|
|
1132
|
+
if (!win || win === this.#window) return;
|
|
1133
|
+
if (this.#window) this.#mothership.undock(this.#window);
|
|
1134
|
+
this.#window = win;
|
|
1135
|
+
this.#mothership.dock(win, this);
|
|
1136
|
+
};
|
|
1137
|
+
track();
|
|
1138
|
+
this.#onFrameLoad = () => {
|
|
1139
|
+
track();
|
|
1140
|
+
// The frame has loaded: the time a start is given runs from when the
|
|
1141
|
+
// runtime in it is told to load the tile (see start()).
|
|
1142
|
+
clearTimeout(this.#deadline);
|
|
1143
|
+
this.start();
|
|
1144
|
+
};
|
|
1145
|
+
ifr.addEventListener('load', this.#onFrameLoad);
|
|
1146
|
+
// The frame may never load (a loading server that does not answer), so
|
|
1147
|
+
// the time a start is given runs from here: if the frame is in the
|
|
1148
|
+
// document by the time the host's code that made it has run (it places
|
|
1149
|
+
// what renderContent() hands it), and from when it is put there if not.
|
|
1150
|
+
this.#watch();
|
|
1151
|
+
queueMicrotask(() => {
|
|
1152
|
+
if (this.#frame?.deref() === ifr && this.#waiting && !ifr.isConnected) this.#clock(true);
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
// Forgets the frame the tile was in, without touching the frame.
|
|
1156
|
+
#letGo () {
|
|
1157
|
+
const ifr = this.#frame?.deref();
|
|
1158
|
+
if (ifr && this.#onFrameLoad) ifr.removeEventListener?.('load', this.#onFrameLoad);
|
|
1159
|
+
if (this.#window) this.#mothership.undock(this.#window);
|
|
1160
|
+
this.#frame = this.#window = this.#onFrameLoad = this.#runtimeId = undefined;
|
|
1161
|
+
this.#started = false;
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Closes the tile: its frame is removed from the document, the tile
|
|
1165
|
+
* forgets it, and the origin it ran on is wiped. Resolves when that is
|
|
1166
|
+
* done, to whether the origin was wiped. The tile can be rendered again
|
|
1167
|
+
* afterwards.
|
|
1168
|
+
*
|
|
1169
|
+
* Removing the frame yourself and dropping the tile is enough for the
|
|
1170
|
+
* page's memory: the mothership keeps nothing alive. What that cannot
|
|
1171
|
+
* reach is what the tile left in the browser. Every tile runs on an origin
|
|
1172
|
+
* made for that one load, and its worker's registration, and anything the
|
|
1173
|
+
* tile stored, would stay there for good. `close()` has that origin wiped
|
|
1174
|
+
* (not a named origin, `namedOrigin`, which is kept on purpose).
|
|
1175
|
+
*
|
|
1176
|
+
* It does not matter what became of the frame first, nor what the tile
|
|
1177
|
+
* did. The frame's address names the origin (getLoadSource() does, and so
|
|
1178
|
+
* every frame renderContent() makes), and that is all it takes: the frame
|
|
1179
|
+
* is removed, if the host has not removed it already, and the origin is
|
|
1180
|
+
* wiped from a frame of the loader's own (TileMothership.wipeOrigin). So
|
|
1181
|
+
* `close()` can be called before the frame is taken out of the document,
|
|
1182
|
+
* or after. A few seconds later the origin is wiped a second time, the
|
|
1183
|
+
* same way, without anyone waiting for it: a worker of the tile's can
|
|
1184
|
+
* outlive its pages for a moment, and write.
|
|
1185
|
+
*
|
|
1186
|
+
* Only a frame whose address does not name the origin, which a host that
|
|
1187
|
+
* builds the address itself can make, has to be asked while it is there:
|
|
1188
|
+
* the runtime in it is told to close, as it always was, and given
|
|
1189
|
+
* CLOSE_MS to answer. Out of the document, there is no one to ask.
|
|
1190
|
+
*
|
|
1191
|
+
* What it resolves to: true when the origin was wiped, and when the tile
|
|
1192
|
+
* never started (there was nothing to wipe); false for a named origin, and
|
|
1193
|
+
* when the wipe could not be done or was not confirmed, which is also
|
|
1194
|
+
* logged as a warning.
|
|
1195
|
+
*/
|
|
1196
|
+
close (): Promise<boolean> {
|
|
1197
|
+
const ifr = this.#frame?.deref();
|
|
1198
|
+
// Kept until it settles, so that closing twice is closing once. Unless
|
|
1199
|
+
// the tile was rendered again meanwhile: it is in another frame then,
|
|
1200
|
+
// and closing that one is another close.
|
|
1201
|
+
if (this.#closed && (!ifr || ifr === this.#closingFrame)) return this.#closed;
|
|
1202
|
+
const outcome = { wiped: false };
|
|
1203
|
+
const closing = this.#close(outcome).finally(() => {
|
|
1204
|
+
if (this.#closing === closing) this.#closing = this.#closed = this.#closingFrame = undefined;
|
|
1205
|
+
});
|
|
1206
|
+
this.#closing = closing;
|
|
1207
|
+
this.#closingFrame = ifr;
|
|
1208
|
+
this.#closed = closing.then(() => outcome.wiped);
|
|
1209
|
+
return this.#closed;
|
|
1210
|
+
}
|
|
1211
|
+
async #close (outcome: { wiped: boolean }): Promise<void> {
|
|
1212
|
+
// The host is done with this start, however far it got: nothing more is
|
|
1213
|
+
// expected of it, and a deadline that runs out while its runtime is
|
|
1214
|
+
// asked to close is not the tile failing to start.
|
|
1215
|
+
this.awaits();
|
|
1216
|
+
const ifr = this.#frame?.deref();
|
|
1217
|
+
// There is something to wipe once a runtime was started on an origin
|
|
1218
|
+
// made for this load: nothing was put there before that.
|
|
1219
|
+
const started = this.#started;
|
|
1220
|
+
const wipe = this.#mothership.ephemeral && started;
|
|
1221
|
+
// Which origin, the frame's address says, when it is one of ours.
|
|
1222
|
+
const origin = wipe ? this.#mothership.originNamedIn(ifr?.src) : undefined;
|
|
1223
|
+
const credentialless = (ifr as { credentialless?: boolean } | undefined)?.credentialless === true;
|
|
1224
|
+
{
|
|
1225
|
+
// The runtime in the frame is only asked when we cannot do without it:
|
|
1226
|
+
// for an origin we were not told of, and for a named origin, where
|
|
1227
|
+
// there is nothing to wipe and it just closes.
|
|
1228
|
+
if (ifr?.isConnected && ifr.contentWindow && started && !origin) {
|
|
1229
|
+
const win = ifr.contentWindow;
|
|
1230
|
+
const loadOrigin = this.#mothership.getLoadOrigin();
|
|
1231
|
+
let answered = false;
|
|
1232
|
+
// What the runtime's answer says of the wipe. A runtime whose dock
|
|
1233
|
+
// carries a close out itself says whether the origin was wiped; one
|
|
1234
|
+
// from before that says only that it has closed, and is taken at its
|
|
1235
|
+
// word.
|
|
1236
|
+
let wipedThere = true;
|
|
1237
|
+
const onAnswer = (ev: MessageEvent) => {
|
|
1238
|
+
if (ev.source === win && ev.origin === loadOrigin && ev.data?.action === RCV_SHUTTLE_CLOSED) wipedThere = ev.data.payload?.wiped !== false;
|
|
1239
|
+
};
|
|
1240
|
+
window.addEventListener('message', onAnswer);
|
|
1241
|
+
await new Promise<void>((resolve) => {
|
|
1242
|
+
this.#runtimeDone = () => {
|
|
1243
|
+
answered = true;
|
|
1244
|
+
// In a moment: the listener above is handed the same message,
|
|
1245
|
+
// and may be handed it after the one that calls us.
|
|
1246
|
+
setTimeout(resolve);
|
|
1247
|
+
};
|
|
1248
|
+
setTimeout(resolve, CLOSE_MS);
|
|
1249
|
+
this.post(SND_SHUTTLE_CLOSE, { wipe: this.#mothership.ephemeral });
|
|
1250
|
+
});
|
|
1251
|
+
window.removeEventListener('message', onAnswer);
|
|
1252
|
+
this.#runtimeDone = undefined;
|
|
1253
|
+
outcome.wiped = wipe && answered && wipedThere;
|
|
1254
|
+
}
|
|
1255
|
+
// Only if it is still the frame we had: the host may have rendered the
|
|
1256
|
+
// tile again while the old runtime was tidying up.
|
|
1257
|
+
if (this.#frame?.deref() === ifr) {
|
|
1258
|
+
this.#letGo();
|
|
1259
|
+
// That run is over: the next has an address, and an origin, of its own.
|
|
1260
|
+
this.#source = undefined;
|
|
1261
|
+
}
|
|
1262
|
+
ifr?.remove?.();
|
|
1263
|
+
if (origin) {
|
|
1264
|
+
outcome.wiped = await this.#mothership.wipeOrigin(origin, credentialless);
|
|
1265
|
+
// And once more in a moment, for what a worker of the tile's may
|
|
1266
|
+
// have written since (see WIPE_AGAIN_MS), and for a wipe that did
|
|
1267
|
+
// not go through the first time. No one waits for that one, and
|
|
1268
|
+
// nothing is said of how it went.
|
|
1269
|
+
setTimeout(() => { void this.#mothership.wipeOrigin(origin, credentialless); }, WIPE_AGAIN_MS);
|
|
1270
|
+
}
|
|
1271
|
+
else if (!started) outcome.wiped = this.#mothership.ephemeral;
|
|
1272
|
+
if (wipe && !outcome.wiped) {
|
|
1273
|
+
console.warn(origin
|
|
1274
|
+
? `[tiles] A closed tile's origin was not wiped, as far as can be told: its loading server said so, or did not answer in time (${origin}).`
|
|
1275
|
+
: '[tiles] A closed tile\'s origin was not wiped: its frame was out of the document, or did not answer, or said that it could not, and its address does not name the origin. Load tile.getLoadSource() in a frame of your own, or close the tile before removing the frame.');
|
|
1276
|
+
}
|
|
1277
|
+
this.dispatchEvent(new Event('close'));
|
|
1278
|
+
}
|
|
348
1279
|
}
|
|
349
1280
|
renderContent (height = 300): HTMLIFrameElement {
|
|
350
1281
|
const ifr = el('iframe', {
|