Skip to content

Commit e75e124

Browse files
committed
fix(plugins): web start-up events and workspace switch (TM-431)
1 parent 3407f60 commit e75e124

4 files changed

Lines changed: 111 additions & 69 deletions

File tree

‎src/pluginSystem/__tests__/leader.test.ts‎

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,55 +6,65 @@ class FakeLocks implements LockManagerLike {
66

77
request(
88
name: string,
9-
options: { signal?: AbortSignal },
10-
callback: () => Promise<void>,
9+
options: { signal?: AbortSignal; ifAvailable?: boolean },
10+
callback: (lock: unknown) => Promise<void>,
1111
) {
1212
return new Promise<void>((resolve, reject) => {
13+
const finish = () => {
14+
this.held.delete(name);
15+
const next = this.queue.findIndex((q) => q.name === name);
16+
if (next >= 0) this.queue.splice(next, 1)[0].run();
17+
resolve();
18+
};
1319
const run = () => {
1420
this.held.add(name);
15-
void callback().then(() => {
16-
this.held.delete(name);
17-
const next = this.queue.findIndex((q) => q.name === name);
18-
if (next >= 0) this.queue.splice(next, 1)[0].run();
19-
resolve();
20-
});
21+
void callback({ name }).then(finish);
2122
};
23+
if (!this.held.has(name)) return run();
24+
if (options.ifAvailable) {
25+
void callback(null).then(() => resolve());
26+
return;
27+
}
28+
this.queue.push({ name, run });
2229
options.signal?.addEventListener('abort', () => {
2330
const index = this.queue.findIndex((q) => q.run === run);
2431
if (index >= 0) {
2532
this.queue.splice(index, 1);
2633
reject(new Error('aborted'));
2734
}
2835
});
29-
if (this.held.has(name)) this.queue.push({ name, run });
30-
else run();
3136
});
3237
}
3338
}
3439

40+
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
41+
3542
it('leads at once without a lock manager', async () => {
36-
expect(await createLeader(null).lead('a')).toBe(true);
43+
expect(await createLeader(null).lead('a', () => undefined)).toBe(true);
3744
});
3845

39-
it('lets one tab lead and the next take over when it leaves', async () => {
46+
it('lets the first tab lead and promotes the next when it leaves', async () => {
4047
const locks = new FakeLocks();
4148
const first = createLeader(locks);
4249
const second = createLeader(locks);
43-
expect(await first.lead('a')).toBe(true);
44-
let secondLeads = false;
45-
const waiting = second.lead('a').then((ok) => (secondLeads = ok));
46-
await Promise.resolve();
47-
expect(secondLeads).toBe(false);
50+
expect(await first.lead('a', () => undefined)).toBe(true);
51+
const promoted = jest.fn();
52+
expect(await second.lead('a', promoted)).toBe(false);
53+
expect(promoted).not.toHaveBeenCalled();
4854
first.leave();
49-
expect(await waiting).toBe(true);
55+
await flush();
56+
expect(promoted).toHaveBeenCalledTimes(1);
5057
});
5158

52-
it('stops waiting when the tab moves to another name', async () => {
59+
it('does not promote a tab that moved to another name', async () => {
5360
const locks = new FakeLocks();
5461
const first = createLeader(locks);
5562
const second = createLeader(locks);
56-
await first.lead('a');
57-
const waiting = second.lead('a');
58-
expect(await second.lead('b')).toBe(true);
59-
expect(await waiting).toBe(false);
63+
await first.lead('a', () => undefined);
64+
const promoted = jest.fn();
65+
await second.lead('a', promoted);
66+
expect(await second.lead('b', () => undefined)).toBe(true);
67+
first.leave();
68+
await flush();
69+
expect(promoted).not.toHaveBeenCalled();
6070
});

‎src/pluginSystem/leader.ts‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
export interface LockManagerLike {
22
request(
33
name: string,
4-
options: { signal?: AbortSignal },
5-
callback: () => Promise<void>,
4+
options: { signal?: AbortSignal; ifAvailable?: boolean },
5+
callback: (lock: unknown) => Promise<void>,
66
): Promise<unknown>;
77
}
88

9-
/** One tab per name runs the plugins; the others queue and take over when it closes or switches away. */
9+
/** One tab per name leads; the others queue and are promoted when it closes or switches away. */
1010
export const createLeader = (
1111
locks: LockManagerLike | undefined | null = typeof navigator === 'undefined'
1212
? null
@@ -22,26 +22,42 @@ export const createLeader = (
2222
release = null;
2323
};
2424

25-
/** Resolves true once this tab leads `name`; false when it was superseded by another `lead` or `leave` call. */
26-
const lead = async (name: string): Promise<boolean> => {
25+
const hold = () =>
26+
new Promise<void>((done) => {
27+
release = done;
28+
});
29+
30+
/** Resolves true when this tab leads `name` right now; otherwise false, and `onPromoted` runs if it later takes over. */
31+
const lead = async (
32+
name: string,
33+
onPromoted: () => void,
34+
): Promise<boolean> => {
2735
leave();
2836
if (!locks) return true;
2937
const mine = new AbortController();
3038
abort = mine;
31-
return new Promise<boolean>((resolve) => {
39+
const now = await new Promise<boolean>((resolve) => {
3240
locks
33-
.request(name, { signal: mine.signal }, () => {
34-
if (mine.signal.aborted) {
41+
.request(name, { ifAvailable: true }, (lock) => {
42+
if (!lock || mine.signal.aborted) {
3543
resolve(false);
3644
return Promise.resolve();
3745
}
3846
resolve(true);
39-
return new Promise<void>((done) => {
40-
release = done;
41-
});
47+
return hold();
4248
})
4349
.catch(() => resolve(false));
4450
});
51+
if (now) return true;
52+
if (mine.signal.aborted) return false;
53+
locks
54+
.request(name, { signal: mine.signal }, () => {
55+
if (mine.signal.aborted) return Promise.resolve();
56+
onPromoted();
57+
return hold();
58+
})
59+
.catch(() => undefined);
60+
return false;
4561
};
4662

4763
return { lead, leave };

‎src/pluginSystem/web.ts‎

Lines changed: 50 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,11 @@ export const installWebPlugins = (store: Store<any>) => {
9090
});
9191
const leader = createLeader();
9292
let host: ReturnType<typeof createPluginHost> | null = null;
93-
let pinned: WorkspacePluginRecord[] = [];
93+
let pinned: { workspaceId: number; records: WorkspacePluginRecord[] } = {
94+
workspaceId: 0,
95+
records: [],
96+
};
97+
let requested = '';
9498
let sequence = 0;
9599
let session: string | null = null;
96100
let leading = false;
@@ -136,8 +140,9 @@ export const installWebPlugins = (store: Store<any>) => {
136140
const packages = async (): Promise<PluginPackage[]> => {
137141
const found: PluginPackage[] = [];
138142
const errors: Record<string, string> = {};
139-
const workspaceId = pluginState.workspace?.id ?? currentId();
140-
for (const record of pinned) {
143+
const { workspaceId, records } = pinned;
144+
const loadedFor = sequence;
145+
for (const record of records) {
141146
try {
142147
if (record.repo === BUILTIN_REPO) {
143148
const builtin = builtinPackages().find(
@@ -159,10 +164,12 @@ export const installWebPlugins = (store: Store<any>) => {
159164
}`;
160165
}
161166
}
162-
Object.keys(installedPluginErrors).forEach(
163-
(key) => delete installedPluginErrors[key],
164-
);
165-
Object.assign(installedPluginErrors, errors);
167+
if (loadedFor === sequence) {
168+
Object.keys(installedPluginErrors).forEach(
169+
(key) => delete installedPluginErrors[key],
170+
);
171+
Object.assign(installedPluginErrors, errors);
172+
}
166173
return found;
167174
};
168175

@@ -226,45 +233,54 @@ export const installWebPlugins = (store: Store<any>) => {
226233
store.getters.currentWorkspace?.code ?? ''
227234
}|${store.state.token ? (store.state.user?.id ?? '') : ''}`,
228235
async () => {
229-
const current = ++sequence;
230236
const user = store.state.token ? String(store.state.user?.id ?? '') : '';
231-
const sessionChanged = user !== session;
232237
const workspace = user
233238
? workspaceOf(store.getters.currentWorkspace)
234239
: null;
235-
if (
236-
!sessionChanged &&
237-
pluginState.workspace?.id === workspace?.id &&
238-
pluginState.workspace?.code === workspace?.code
239-
)
240-
return;
240+
const target = `${user}|${workspace?.id ?? ''}|${workspace?.code ?? ''}`;
241+
if (target === requested) return;
242+
requested = target;
243+
const current = ++sequence;
241244
stepDown();
242-
if (sessionChanged) {
245+
if (user !== session) {
243246
session = user;
244247
cloudClients.clear();
245248
Object.keys(workspacePlugins).forEach(
246249
(id) => delete workspacePlugins[Number(id)],
247250
);
248251
}
249-
if (!workspace) {
250-
await host?.activate(null);
251-
return;
252-
}
253-
await loadWorkspacePlugins(workspace.id).catch(() => undefined);
254-
if (current !== sequence) return;
255-
pinned = workspacePlugins[workspace.id] ?? [];
256-
if (!pinned.length) {
257-
await host?.activate(null);
258-
return;
252+
try {
253+
if (!workspace) {
254+
await host?.activate(null);
255+
return;
256+
}
257+
await loadWorkspacePlugins(workspace.id).catch(() => undefined);
258+
if (current !== sequence) return;
259+
pinned = {
260+
workspaceId: workspace.id,
261+
records: workspacePlugins[workspace.id] ?? [],
262+
};
263+
if (!pinned.records.length) {
264+
await host?.activate(null);
265+
return;
266+
}
267+
await ensureHost().load();
268+
if (current !== sequence) return;
269+
const promoted = () => {
270+
if (current !== sequence) return;
271+
leading = true;
272+
startPageEvents(workspace.id);
273+
};
274+
const now = await leader.lead(
275+
`tmgr-plugins:${user}:${workspace.id}`,
276+
promoted,
277+
);
278+
if (current !== sequence) return;
279+
if (now) promoted();
280+
await host!.activate(workspace);
281+
} catch (error) {
282+
console.error('[plugins] could not start on the web', error);
259283
}
260-
await ensureHost().load();
261-
if (current !== sequence) return;
262-
await host!.activate(workspace);
263-
void leader.lead(`tmgr-plugins:${user}:${workspace.id}`).then((ok) => {
264-
if (!ok || current !== sequence) return;
265-
leading = true;
266-
startPageEvents(workspace.id);
267-
});
268284
},
269285
{ immediate: true },
270286
);

‎src/pluginSystem/webSupport.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ export const sha256Hex = async (bytes: ArrayBuffer): Promise<string> =>
2727
.map((byte) => byte.toString(16).padStart(2, '0'))
2828
.join('');
2929

30-
/** The bundle must be byte-for-byte what the creator pinned; the proxy that delivered it is not trusted. */
3130
export const withoutHtmlPages = <T extends PluginPackage>(pkg: T): T => ({
3231
...pkg,
3332
pages: {},
3433
});
3534

35+
/** The bundle must be byte-for-byte what the creator pinned; the proxy that delivered it is not trusted. */
3636
export const packageFromPin = async (
3737
record: WorkspacePluginRecord,
3838
download: () => Promise<ArrayBuffer>,

0 commit comments

Comments
 (0)