-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncClientStore.ts
More file actions
169 lines (165 loc) · 5.41 KB
/
asyncClientStore.ts
File metadata and controls
169 lines (165 loc) · 5.41 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
import { createTransport } from 'data-transport';
import type { Patches } from 'mutative';
import type {
ClientTransportOptions,
CreateState,
ClientTransport,
MiddlewareStore
} from './interface';
import type { Internal } from './internal';
import { wrapStore } from './wrapStore';
export const createAsyncClientStore = <T extends CreateState>(
createStore: (options: { share?: 'client' }) => {
store: MiddlewareStore<T>;
internal: Internal<T>;
},
asyncStoreClientOption: ClientTransportOptions
) => {
const { store: asyncClientStore, internal } = createStore({
share: 'client'
});
// the transport is in the worker or shared worker, and the client is in the main thread.
// This store can't be directly executed by any of the store's methods
// its methods are proxied to the worker or share worker for execution.
// and the executed patch is sent to the store to be applied to synchronize the state.
const transport: ClientTransport = asyncStoreClientOption.worker
? createTransport(
asyncStoreClientOption.worker instanceof SharedWorker
? 'SharedWorkerClient'
: 'WebWorkerClient',
{
worker: asyncStoreClientOption.worker as SharedWorker,
prefix: asyncClientStore.name
}
)
: asyncStoreClientOption.clientTransport;
if (!transport) {
throw new Error('transport is required');
}
asyncClientStore.transport = transport;
let syncingPromise: Promise<void> | null = null;
let awaitingReconnectSync = false;
let reconnectSequenceBaseline: number | null = null;
const fullSync = async (allowLowerSequence = false) => {
if (!syncingPromise) {
syncingPromise = (async () => {
const latest = await transport.emit('fullSync');
if (
typeof latest.sequence !== 'number' ||
typeof latest.state !== 'string'
) {
throw new Error('Invalid fullSync payload');
}
const canApplyLowerSequence =
allowLowerSequence &&
awaitingReconnectSync &&
reconnectSequenceBaseline !== null &&
reconnectSequenceBaseline === internal.sequence;
if (latest.sequence < internal.sequence && !canApplyLowerSequence) {
return;
}
asyncClientStore.apply(JSON.parse(latest.state));
internal.sequence = latest.sequence;
awaitingReconnectSync = false;
reconnectSequenceBaseline = null;
})().finally(() => {
syncingPromise = null;
});
}
return syncingPromise;
};
if (typeof transport.onConnect !== 'function') {
throw new Error('transport.onConnect is required');
}
transport.onConnect?.(() => {
awaitingReconnectSync = true;
reconnectSequenceBaseline = internal.sequence;
void fullSync(true).catch((error) => {
if (process.env.NODE_ENV === 'development') {
console.error(error);
}
});
});
transport.listen('update', async (options) => {
let shouldFullSync = false;
let allowLowerSequence = false;
try {
if (typeof options.sequence !== 'number') {
shouldFullSync = true;
} else if (options.sequence <= internal.sequence) {
if (awaitingReconnectSync) {
shouldFullSync = true;
allowLowerSequence = true;
} else if (options.sequence === 0 && internal.sequence > 0) {
awaitingReconnectSync = true;
reconnectSequenceBaseline = internal.sequence;
shouldFullSync = true;
allowLowerSequence = true;
} else {
return;
}
} else if (options.sequence === internal.sequence + 1) {
asyncClientStore.apply(undefined, options.patches);
internal.sequence = options.sequence;
awaitingReconnectSync = false;
reconnectSequenceBaseline = null;
return;
} else {
shouldFullSync = true;
allowLowerSequence = awaitingReconnectSync;
}
if (shouldFullSync) {
await fullSync(allowLowerSequence);
}
} catch (error) {
if (!shouldFullSync) {
try {
await fullSync(awaitingReconnectSync);
} catch (syncError) {
if (process.env.NODE_ENV === 'development') {
console.error(syncError);
}
}
}
if (process.env.NODE_ENV === 'development') {
console.error(error);
}
}
});
return wrapStore(asyncClientStore, () => asyncClientStore.getState());
};
export const emit = <T extends CreateState>(
store: MiddlewareStore<T>,
internal: Internal<T>,
patches?: Patches
) => {
if (store.transport && patches?.length) {
internal.sequence += 1;
// it is not necessary to respond to the update event
store.transport.emit(
{
name: 'update',
respond: false
},
{
patches: patches,
sequence: internal.sequence
}
);
}
};
export const handleDraft = <T extends CreateState>(
store: MiddlewareStore<T>,
internal: Internal<T>
) => {
internal.rootState = internal.backupState;
const [, patches, inversePatches] = internal.finalizeDraft();
const finalPatches = store.patch
? store.patch({ patches, inversePatches })
: { patches, inversePatches };
if (finalPatches.patches.length) {
store.apply(internal.rootState as T, finalPatches.patches);
// 3rd party model will send update notifications on its own after `store.apply` in mutableInstance mode
emit(store, internal, finalPatches.patches);
}
};