@livestore/adapter-web 0.4.0-dev.9 → 0.5.0-dev.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 +5 -5
- package/dist/.tsbuildinfo +1 -1
- package/dist/in-memory/in-memory-adapter.d.ts +50 -8
- package/dist/in-memory/in-memory-adapter.d.ts.map +1 -1
- package/dist/in-memory/in-memory-adapter.js +100 -39
- package/dist/in-memory/in-memory-adapter.js.map +1 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -1
- package/dist/index.js.map +1 -1
- package/dist/single-tab/mod.d.ts +15 -0
- package/dist/single-tab/mod.d.ts.map +1 -0
- package/dist/single-tab/mod.js +15 -0
- package/dist/single-tab/mod.js.map +1 -0
- package/dist/single-tab/single-tab-adapter.d.ts +108 -0
- package/dist/single-tab/single-tab-adapter.d.ts.map +1 -0
- package/dist/single-tab/single-tab-adapter.js +252 -0
- package/dist/single-tab/single-tab-adapter.js.map +1 -0
- package/dist/web-worker/client-session/client-session-devtools.d.ts +4 -5
- package/dist/web-worker/client-session/client-session-devtools.d.ts.map +1 -1
- package/dist/web-worker/client-session/client-session-devtools.js +27 -14
- package/dist/web-worker/client-session/client-session-devtools.js.map +1 -1
- package/dist/web-worker/client-session/devtools-web-channel.d.ts +20 -0
- package/dist/web-worker/client-session/devtools-web-channel.d.ts.map +1 -0
- package/dist/web-worker/client-session/devtools-web-channel.js +34 -0
- package/dist/web-worker/client-session/devtools-web-channel.js.map +1 -0
- package/dist/web-worker/client-session/persisted-adapter.d.ts +18 -0
- package/dist/web-worker/client-session/persisted-adapter.d.ts.map +1 -1
- package/dist/web-worker/client-session/persisted-adapter.js +170 -103
- package/dist/web-worker/client-session/persisted-adapter.js.map +1 -1
- package/dist/web-worker/client-session/sqlite-loader.d.ts +2 -0
- package/dist/web-worker/client-session/sqlite-loader.d.ts.map +1 -0
- package/dist/web-worker/client-session/sqlite-loader.js +16 -0
- package/dist/web-worker/client-session/sqlite-loader.js.map +1 -0
- package/dist/web-worker/common/persisted-sqlite.d.ts +15 -35
- package/dist/web-worker/common/persisted-sqlite.d.ts.map +1 -1
- package/dist/web-worker/common/persisted-sqlite.js +91 -201
- package/dist/web-worker/common/persisted-sqlite.js.map +1 -1
- package/dist/web-worker/common/rpc-worker.d.ts +14 -0
- package/dist/web-worker/common/rpc-worker.d.ts.map +1 -0
- package/dist/web-worker/common/rpc-worker.js +8 -0
- package/dist/web-worker/common/rpc-worker.js.map +1 -0
- package/dist/web-worker/common/shutdown-channel.d.ts +3 -2
- package/dist/web-worker/common/shutdown-channel.d.ts.map +1 -1
- package/dist/web-worker/common/shutdown-channel.js +2 -2
- package/dist/web-worker/common/shutdown-channel.js.map +1 -1
- package/dist/web-worker/common/webmesh-node-names.d.ts +4 -0
- package/dist/web-worker/common/webmesh-node-names.d.ts.map +1 -0
- package/dist/web-worker/common/webmesh-node-names.js +2 -0
- package/dist/web-worker/common/webmesh-node-names.js.map +1 -0
- package/dist/web-worker/common/worker-disconnect-channel.d.ts +3 -10
- package/dist/web-worker/common/worker-disconnect-channel.d.ts.map +1 -1
- package/dist/web-worker/common/worker-disconnect-channel.js +4 -4
- package/dist/web-worker/common/worker-disconnect-channel.js.map +1 -1
- package/dist/web-worker/common/worker-schema.d.ts +295 -146
- package/dist/web-worker/common/worker-schema.d.ts.map +1 -1
- package/dist/web-worker/common/worker-schema.js +89 -54
- package/dist/web-worker/common/worker-schema.js.map +1 -1
- package/dist/web-worker/leader-worker/make-leader-worker.d.ts +6 -6
- package/dist/web-worker/leader-worker/make-leader-worker.d.ts.map +1 -1
- package/dist/web-worker/leader-worker/make-leader-worker.js +191 -80
- package/dist/web-worker/leader-worker/make-leader-worker.js.map +1 -1
- package/dist/web-worker/shared-worker/make-shared-worker.d.ts +2 -1
- package/dist/web-worker/shared-worker/make-shared-worker.d.ts.map +1 -1
- package/dist/web-worker/shared-worker/make-shared-worker.js +91 -94
- package/dist/web-worker/shared-worker/make-shared-worker.js.map +1 -1
- package/dist/web-worker/vite-dev-polyfill.js +1 -2
- package/dist/web-worker/vite-dev-polyfill.js.map +1 -1
- package/package.json +47 -19
- package/src/in-memory/in-memory-adapter.ts +147 -73
- package/src/index.ts +15 -1
- package/src/single-tab/mod.ts +15 -0
- package/src/single-tab/single-tab-adapter.ts +499 -0
- package/src/web-worker/ambient.d.ts +7 -24
- package/src/web-worker/client-session/client-session-devtools.ts +47 -25
- package/src/web-worker/client-session/devtools-web-channel.ts +57 -0
- package/src/web-worker/client-session/persisted-adapter.ts +259 -163
- package/src/web-worker/client-session/sqlite-loader.ts +19 -0
- package/src/web-worker/common/persisted-sqlite.ts +204 -309
- package/src/web-worker/common/rpc-worker.ts +39 -0
- package/src/web-worker/common/shutdown-channel.ts +10 -3
- package/src/web-worker/common/webmesh-node-names.ts +1 -0
- package/src/web-worker/common/worker-disconnect-channel.ts +11 -4
- package/src/web-worker/common/worker-schema.ts +138 -131
- package/src/web-worker/leader-worker/make-leader-worker.ts +396 -194
- package/src/web-worker/shared-worker/make-shared-worker.ts +143 -146
- package/src/web-worker/vite-dev-polyfill.ts +1 -2
- package/dist/opfs-utils.d.ts +0 -7
- package/dist/opfs-utils.d.ts.map +0 -1
- package/dist/opfs-utils.js +0 -43
- package/dist/opfs-utils.js.map +0 -1
- package/src/opfs-utils.ts +0 -61
|
@@ -1,53 +1,66 @@
|
|
|
1
|
-
import type { Adapter, ClientSession, LockStatus } from '@livestore/common'
|
|
1
|
+
import type { Adapter, BootWarningReason, ClientSession, LockStatus } from '@livestore/common'
|
|
2
2
|
import {
|
|
3
3
|
IntentionalShutdownCause,
|
|
4
4
|
liveStoreVersion,
|
|
5
5
|
makeClientSession,
|
|
6
|
+
StateHead,
|
|
6
7
|
StoreInterrupted,
|
|
7
|
-
|
|
8
|
-
UnexpectedError,
|
|
8
|
+
UnknownError,
|
|
9
9
|
} from '@livestore/common'
|
|
10
10
|
// TODO bring back - this currently doesn't work due to https://github.com/vitejs/vite/issues/8427
|
|
11
11
|
// NOTE We're using a non-relative import here for Vite to properly resolve the import during app builds
|
|
12
12
|
// import LiveStoreSharedWorker from '@livestore/adapter-web/internal-shared-worker?sharedworker'
|
|
13
|
-
import { EventSequenceNumber } from '@livestore/common/schema'
|
|
14
13
|
import { sqliteDbFactory } from '@livestore/sqlite-wasm/browser'
|
|
15
|
-
import {
|
|
16
|
-
import { isDevEnv, shouldNeverHappen, tryAsFunctionAndNew } from '@livestore/utils'
|
|
14
|
+
import { isDevEnv, omitUndefineds, shouldNeverHappen, tryAsFunctionAndNew } from '@livestore/utils'
|
|
17
15
|
import {
|
|
18
|
-
BrowserWorker,
|
|
19
16
|
Cause,
|
|
20
17
|
Deferred,
|
|
21
18
|
Effect,
|
|
22
19
|
Exit,
|
|
23
20
|
Fiber,
|
|
24
21
|
Layer,
|
|
25
|
-
ParseResult,
|
|
26
22
|
Queue,
|
|
23
|
+
RpcClient,
|
|
24
|
+
RpcWorker,
|
|
27
25
|
Schema,
|
|
28
26
|
Stream,
|
|
27
|
+
Subscribable,
|
|
29
28
|
SubscriptionRef,
|
|
30
|
-
WebLock,
|
|
31
|
-
Worker,
|
|
32
|
-
WorkerError,
|
|
33
29
|
} from '@livestore/utils/effect'
|
|
30
|
+
import { BrowserWorker, Opfs, WebError, WebLock } from '@livestore/utils/effect/browser'
|
|
34
31
|
import { nanoid } from '@livestore/utils/nanoid'
|
|
35
32
|
|
|
36
|
-
import
|
|
37
|
-
import {
|
|
33
|
+
import { makeSingleTabAdapter } from '../../single-tab/single-tab-adapter.ts'
|
|
34
|
+
import {
|
|
35
|
+
readPersistedStateDbFromClientSession,
|
|
36
|
+
resetPersistedDataFromClientSession,
|
|
37
|
+
} from '../common/persisted-sqlite.ts'
|
|
38
|
+
import {
|
|
39
|
+
type WithoutRpcClientError,
|
|
40
|
+
dieOnRpcClientError,
|
|
41
|
+
dieOnRpcClientErrorStream,
|
|
42
|
+
makeWebmeshWorkerProxy,
|
|
43
|
+
} from '../common/rpc-worker.ts'
|
|
38
44
|
import { makeShutdownChannel } from '../common/shutdown-channel.ts'
|
|
39
45
|
import { DedicatedWorkerDisconnectBroadcast, makeWorkerDisconnectChannel } from '../common/worker-disconnect-channel.ts'
|
|
40
46
|
import * as WorkerSchema from '../common/worker-schema.ts'
|
|
41
47
|
import { connectWebmeshNodeClientSession } from './client-session-devtools.ts'
|
|
48
|
+
import { loadSqlite3 } from './sqlite-loader.ts'
|
|
42
49
|
|
|
43
|
-
|
|
44
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Checks if SharedWorker API is available in the current browser context.
|
|
52
|
+
*
|
|
53
|
+
* Returns false on Android Chrome and other browsers without SharedWorker support.
|
|
54
|
+
*
|
|
55
|
+
* @see https://github.com/livestorejs/livestore/issues/321
|
|
56
|
+
* @see https://issues.chromium.org/issues/40290702
|
|
57
|
+
*/
|
|
58
|
+
export const canUseSharedWorker = (): boolean => typeof SharedWorker !== 'undefined'
|
|
45
59
|
|
|
46
|
-
if (isDevEnv()) {
|
|
60
|
+
if (isDevEnv() === true) {
|
|
47
61
|
globalThis.__debugLiveStoreUtils = {
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
runFork: (effect: Effect.Effect<any, any, never>) => Effect.runFork(effect),
|
|
62
|
+
...globalThis.__debugLiveStoreUtils,
|
|
63
|
+
opfs: Opfs.debugUtils,
|
|
51
64
|
}
|
|
52
65
|
}
|
|
53
66
|
|
|
@@ -69,9 +82,7 @@ export type WebAdapterOptions = {
|
|
|
69
82
|
*/
|
|
70
83
|
sharedWorker:
|
|
71
84
|
| ((options: { name: string }) => globalThis.SharedWorker)
|
|
72
|
-
| (new (options: {
|
|
73
|
-
name: string
|
|
74
|
-
}) => globalThis.SharedWorker)
|
|
85
|
+
| (new (options: { name: string }) => globalThis.SharedWorker)
|
|
75
86
|
/**
|
|
76
87
|
* Specifies where to persist data for this adapter
|
|
77
88
|
*/
|
|
@@ -123,6 +134,15 @@ export type WebAdapterOptions = {
|
|
|
123
134
|
* Creates a web adapter with persistent storage (currently only supports OPFS).
|
|
124
135
|
* Requires both a web worker and a shared worker.
|
|
125
136
|
*
|
|
137
|
+
* On browsers without SharedWorker support (e.g. Android Chrome), this adapter
|
|
138
|
+
* automatically falls back to single-tab mode. In single-tab mode:
|
|
139
|
+
* - Each tab runs independently with its own leader worker
|
|
140
|
+
* - Multi-tab synchronization is not available
|
|
141
|
+
* - Devtools are not supported
|
|
142
|
+
*
|
|
143
|
+
* @see https://github.com/livestorejs/livestore/issues/321 - SharedWorker tracking issue
|
|
144
|
+
* @see https://issues.chromium.org/issues/40290702 - Chromium SharedWorker bug
|
|
145
|
+
*
|
|
126
146
|
* @example
|
|
127
147
|
* ```ts
|
|
128
148
|
* import { makePersistedAdapter } from '@livestore/adapter-web'
|
|
@@ -140,25 +160,72 @@ export const makePersistedAdapter =
|
|
|
140
160
|
(options: WebAdapterOptions): Adapter =>
|
|
141
161
|
(adapterArgs) =>
|
|
142
162
|
Effect.gen(function* () {
|
|
143
|
-
|
|
163
|
+
// Check SharedWorker availability first and fall back to single-tab mode if unavailable
|
|
164
|
+
if (canUseSharedWorker() === false) {
|
|
165
|
+
yield* Effect.logWarning(
|
|
166
|
+
'[@livestore/adapter-web] SharedWorker unavailable (e.g. Android Chrome). ' +
|
|
167
|
+
'Falling back to single-tab mode. Multi-tab synchronization and devtools are disabled. ' +
|
|
168
|
+
'See: https://github.com/livestorejs/livestore/issues/321',
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
return yield* makeSingleTabAdapter({
|
|
172
|
+
worker: options.worker,
|
|
173
|
+
storage: options.storage,
|
|
174
|
+
...omitUndefineds({
|
|
175
|
+
resetPersistence: options.resetPersistence,
|
|
176
|
+
clientId: options.clientId,
|
|
177
|
+
sessionId: options.sessionId,
|
|
178
|
+
experimental: options.experimental,
|
|
179
|
+
}),
|
|
180
|
+
})(adapterArgs)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const {
|
|
184
|
+
schema,
|
|
185
|
+
storeId,
|
|
186
|
+
devtoolsEnabled,
|
|
187
|
+
debugInstanceId,
|
|
188
|
+
bootStatusQueue,
|
|
189
|
+
shutdown,
|
|
190
|
+
syncPayloadSchema: _syncPayloadSchema,
|
|
191
|
+
syncPayloadEncoded,
|
|
192
|
+
} = adapterArgs
|
|
193
|
+
|
|
194
|
+
// NOTE: The schema travels with the worker bundle (developers call
|
|
195
|
+
// `makeWorker({ schema, syncPayloadSchema })`). We only keep the
|
|
196
|
+
// destructured value here to document availability on the client session
|
|
197
|
+
// side—structured cloning the Effect schema into the worker is not
|
|
198
|
+
// possible, so we intentionally do not forward it.
|
|
199
|
+
void _syncPayloadSchema
|
|
144
200
|
|
|
145
201
|
yield* ensureBrowserRequirements
|
|
146
202
|
|
|
147
203
|
yield* Queue.offer(bootStatusQueue, { stage: 'loading' })
|
|
148
204
|
|
|
149
|
-
const sqlite3 = yield* Effect.promise(() =>
|
|
205
|
+
const sqlite3 = yield* Effect.promise(() => loadSqlite3())
|
|
150
206
|
|
|
151
207
|
const LIVESTORE_TAB_LOCK = `livestore-tab-lock-${storeId}`
|
|
152
208
|
const LIVESTORE_SHARED_WORKER_TERMINATION_LOCK = `livestore-shared-worker-termination-lock-${storeId}`
|
|
153
209
|
|
|
154
|
-
const storageOptions = yield* Schema.
|
|
210
|
+
const storageOptions = yield* Schema.decodeEffect(WorkerSchema.StorageType)(options.storage)
|
|
155
211
|
|
|
156
212
|
const shutdownChannel = yield* makeShutdownChannel(storeId)
|
|
157
213
|
|
|
158
|
-
if (
|
|
214
|
+
// Check OPFS availability early and notify user if storage is unavailable (e.g. private browsing)
|
|
215
|
+
const opfsWarning = yield* checkOpfsAvailability
|
|
216
|
+
if (opfsWarning !== undefined) {
|
|
217
|
+
yield* Effect.logWarning('[@livestore/adapter-web:client-session] OPFS unavailable', opfsWarning)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (options.resetPersistence === true && opfsWarning === undefined) {
|
|
159
221
|
yield* shutdownChannel.send(IntentionalShutdownCause.make({ reason: 'adapter-reset' }))
|
|
160
222
|
|
|
161
223
|
yield* resetPersistedDataFromClientSession({ storageOptions, storeId })
|
|
224
|
+
} else if (options.resetPersistence === true) {
|
|
225
|
+
yield* Effect.logWarning(
|
|
226
|
+
'[@livestore/adapter-web:client-session] Skipping persistence reset because storage is unavailable',
|
|
227
|
+
opfsWarning,
|
|
228
|
+
)
|
|
162
229
|
}
|
|
163
230
|
|
|
164
231
|
// Note on fast-path booting:
|
|
@@ -168,9 +235,17 @@ export const makePersistedAdapter =
|
|
|
168
235
|
// We need to be extra careful though to not run into any race conditions or inconsistencies.
|
|
169
236
|
// TODO also verify persisted data
|
|
170
237
|
const dataFromFile =
|
|
171
|
-
options.experimental?.disableFastPath === true
|
|
238
|
+
options.experimental?.disableFastPath === true || opfsWarning !== undefined
|
|
172
239
|
? undefined
|
|
173
|
-
: yield*
|
|
240
|
+
: yield* readPersistedStateDbFromClientSession({ storageOptions, storeId, schema }).pipe(
|
|
241
|
+
Effect.tapError((error) =>
|
|
242
|
+
Effect.logDebug('[@livestore/adapter-web:client-session] Could not read persisted state db', error, {
|
|
243
|
+
storeId,
|
|
244
|
+
}),
|
|
245
|
+
),
|
|
246
|
+
// If we get any error here, we return `undefined` to fall back to the slow path
|
|
247
|
+
Effect.orElseSucceed(() => undefined),
|
|
248
|
+
)
|
|
174
249
|
|
|
175
250
|
// The same across all client sessions (i.e. tabs, windows)
|
|
176
251
|
const clientId = options.clientId ?? getPersistedId(`clientId:${storeId}`, 'local')
|
|
@@ -180,9 +255,9 @@ export const makePersistedAdapter =
|
|
|
180
255
|
const workerDisconnectChannel = yield* makeWorkerDisconnectChannel(storeId)
|
|
181
256
|
|
|
182
257
|
yield* shutdownChannel.listen.pipe(
|
|
183
|
-
Stream.
|
|
258
|
+
Stream.mapEffect(Effect.fromResult),
|
|
184
259
|
Stream.tap((cause) =>
|
|
185
|
-
shutdown(cause._tag === '
|
|
260
|
+
shutdown(cause._tag === 'IntentionalShutdownCause' ? Exit.succeed(cause) : Exit.fail(cause)),
|
|
186
261
|
),
|
|
187
262
|
Stream.runDrain,
|
|
188
263
|
Effect.interruptible,
|
|
@@ -192,38 +267,23 @@ export const makePersistedAdapter =
|
|
|
192
267
|
|
|
193
268
|
const sharedWebWorker = tryAsFunctionAndNew(options.sharedWorker, { name: `livestore-shared-worker-${storeId}` })
|
|
194
269
|
|
|
195
|
-
if (options.experimental?.awaitSharedWorkerTermination) {
|
|
270
|
+
if (options.experimental?.awaitSharedWorkerTermination === true) {
|
|
196
271
|
// Relying on the lock being available is currently the only mechanism we're aware of
|
|
197
272
|
// to know whether the shared worker has terminated.
|
|
198
273
|
yield* Effect.addFinalizer(() => WebLock.waitForLock(LIVESTORE_SHARED_WORKER_TERMINATION_LOCK))
|
|
199
274
|
}
|
|
200
275
|
|
|
201
|
-
const sharedWorkerContext = yield* Layer.build(
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
liveStoreVersion,
|
|
208
|
-
payload: {
|
|
209
|
-
_tag: 'FromClientSession',
|
|
210
|
-
initialMessage: new WorkerSchema.LeaderWorkerInnerInitialMessage({
|
|
211
|
-
storageOptions,
|
|
212
|
-
storeId,
|
|
213
|
-
clientId,
|
|
214
|
-
devtoolsEnabled,
|
|
215
|
-
debugInstanceId,
|
|
216
|
-
syncPayload,
|
|
217
|
-
}),
|
|
218
|
-
},
|
|
219
|
-
}),
|
|
220
|
-
}).pipe(
|
|
276
|
+
const sharedWorkerContext = yield* Layer.build(
|
|
277
|
+
RpcClient.layerProtocolWorker({ size: 1, concurrency: 100 }).pipe(
|
|
278
|
+
Layer.provide(BrowserWorker.layer(() => sharedWebWorker)),
|
|
279
|
+
),
|
|
280
|
+
)
|
|
281
|
+
const sharedWorker = yield* RpcClient.make(WorkerSchema.SharedWorkerRpcs).pipe(
|
|
221
282
|
Effect.provide(sharedWorkerContext),
|
|
222
283
|
Effect.tapCauseLogPretty,
|
|
223
|
-
|
|
224
|
-
Effect.
|
|
284
|
+
UnknownError.mapToUnknownError,
|
|
285
|
+
Effect.tapCause((cause) => shutdown(Exit.failCause(cause))),
|
|
225
286
|
Effect.withSpan('@livestore/adapter-web:client-session:setupSharedWorker'),
|
|
226
|
-
Effect.forkScoped,
|
|
227
287
|
)
|
|
228
288
|
|
|
229
289
|
const lockDeferred = yield* Deferred.make<void>()
|
|
@@ -232,7 +292,7 @@ export const makePersistedAdapter =
|
|
|
232
292
|
//
|
|
233
293
|
// Sorry for this pun ...
|
|
234
294
|
let gotLocky = yield* WebLock.tryGetDeferredLock(lockDeferred, LIVESTORE_TAB_LOCK)
|
|
235
|
-
const lockStatus = yield* SubscriptionRef.make<LockStatus>(gotLocky ? 'has-lock' : 'no-lock')
|
|
295
|
+
const lockStatus = yield* SubscriptionRef.make<LockStatus>(gotLocky === true ? 'has-lock' : 'no-lock')
|
|
236
296
|
|
|
237
297
|
// Ideally we can come up with a simpler implementation that doesn't require this
|
|
238
298
|
const waitForSharedWorkerInitialized = yield* Deferred.make<void>()
|
|
@@ -258,24 +318,44 @@ export const makePersistedAdapter =
|
|
|
258
318
|
// and adding the `sessionId` to make it easier to debug which session a worker belongs to in logs
|
|
259
319
|
const worker = tryAsFunctionAndNew(options.worker, { name: `livestore-worker-${storeId}-${sessionId}` })
|
|
260
320
|
|
|
261
|
-
yield*
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
321
|
+
const outerWorkerContext = yield* Layer.build(
|
|
322
|
+
RpcClient.layerProtocolWorker({ size: 1 }).pipe(
|
|
323
|
+
Layer.provide(BrowserWorker.layer(() => worker)),
|
|
324
|
+
Layer.provide(
|
|
325
|
+
RpcWorker.layerInitialMessage(
|
|
326
|
+
WorkerSchema.LeaderWorkerOuterInitialMessage.payloadSchema,
|
|
327
|
+
Effect.succeed({ port: mc.port1, storeId, clientId }),
|
|
328
|
+
),
|
|
329
|
+
),
|
|
330
|
+
),
|
|
331
|
+
)
|
|
332
|
+
yield* RpcClient.make(WorkerSchema.LeaderWorkerOuterRpcs).pipe(
|
|
333
|
+
Effect.provide(outerWorkerContext),
|
|
334
|
+
UnknownError.mapToUnknownError,
|
|
335
|
+
Effect.tapCause((cause) => shutdown(Exit.failCause(cause))),
|
|
267
336
|
Effect.withSpan('@livestore/adapter-web:client-session:setupDedicatedWorker'),
|
|
268
337
|
Effect.tapCauseLogPretty,
|
|
269
|
-
Effect.forkScoped,
|
|
270
338
|
)
|
|
271
339
|
|
|
272
340
|
yield* workerDisconnectChannel.send(DedicatedWorkerDisconnectBroadcast.make({}))
|
|
273
341
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
342
|
+
yield* sharedWorker
|
|
343
|
+
.UpdateMessagePort({
|
|
344
|
+
port: mc.port2,
|
|
345
|
+
liveStoreVersion,
|
|
346
|
+
initial: {
|
|
347
|
+
storageOptions,
|
|
348
|
+
storeId,
|
|
349
|
+
clientId,
|
|
350
|
+
devtoolsEnabled,
|
|
351
|
+
debugInstanceId,
|
|
352
|
+
syncPayloadEncoded,
|
|
353
|
+
},
|
|
354
|
+
})
|
|
355
|
+
.pipe(
|
|
356
|
+
UnknownError.mapToUnknownError,
|
|
357
|
+
Effect.tapCause((cause) => shutdown(Exit.failCause(cause))),
|
|
358
|
+
)
|
|
279
359
|
|
|
280
360
|
yield* Deferred.succeed(waitForSharedWorkerInitialized, undefined)
|
|
281
361
|
|
|
@@ -302,65 +382,50 @@ export const makePersistedAdapter =
|
|
|
302
382
|
yield* runLocked.pipe(Effect.interruptible, Effect.tapCauseLogPretty, Effect.forkScoped)
|
|
303
383
|
}
|
|
304
384
|
|
|
305
|
-
const runInWorker = <
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
Fiber.join(sharedWorkerFiber).pipe(
|
|
385
|
+
const runInWorker = <A, E, R>(
|
|
386
|
+
tag: string,
|
|
387
|
+
effect: Effect.Effect<A, E, R>,
|
|
388
|
+
): Effect.Effect<A, WithoutRpcClientError<E>, R> =>
|
|
389
|
+
Deferred.await(waitForSharedWorkerInitialized).pipe(
|
|
311
390
|
// NOTE we need to wait for the shared worker to be initialized before we can send requests to it
|
|
312
|
-
Effect.
|
|
313
|
-
|
|
391
|
+
Effect.andThen(effect),
|
|
392
|
+
dieOnRpcClientError,
|
|
314
393
|
// NOTE we want to treat worker requests as atomic and therefore not allow them to be interrupted
|
|
315
394
|
// Interruption usually only happens during leader re-election or store shutdown
|
|
316
395
|
// Effect.uninterruptible,
|
|
317
396
|
Effect.logWarnIfTakesLongerThan({
|
|
318
|
-
label: `@livestore/adapter-web:client-session:runInWorker:${
|
|
397
|
+
label: `@livestore/adapter-web:client-session:runInWorker:${tag}`,
|
|
319
398
|
duration: 2000,
|
|
320
399
|
}),
|
|
321
|
-
Effect.withSpan(`@livestore/adapter-web:client-session:runInWorker:${
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
),
|
|
329
|
-
Effect.catchAllDefect((cause) => new UnexpectedError({ cause })),
|
|
330
|
-
) as any
|
|
331
|
-
|
|
332
|
-
const runInWorkerStream = <TReq extends typeof WorkerSchema.SharedWorkerRequest.Type>(
|
|
333
|
-
req: TReq,
|
|
334
|
-
): TReq extends Schema.WithResult<infer A, infer _I, infer _E, infer _EI, infer R>
|
|
335
|
-
? Stream.Stream<A, UnexpectedError, R>
|
|
336
|
-
: never =>
|
|
400
|
+
Effect.withSpan(`@livestore/adapter-web:client-session:runInWorker:${tag}`),
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
const runInWorkerStream = <A, E, R>(
|
|
404
|
+
tag: string,
|
|
405
|
+
stream: Stream.Stream<A, E, R>,
|
|
406
|
+
): Stream.Stream<A, WithoutRpcClientError<E>, R> =>
|
|
337
407
|
Effect.gen(function* () {
|
|
338
|
-
|
|
339
|
-
return
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
? cause
|
|
343
|
-
: ParseResult.isParseError(cause) || Schema.is(WorkerError.WorkerError)(cause)
|
|
344
|
-
? new UnexpectedError({ cause })
|
|
345
|
-
: cause,
|
|
346
|
-
),
|
|
347
|
-
Stream.withSpan(`@livestore/adapter-web:client-session:runInWorkerStream:${req._tag}`),
|
|
408
|
+
yield* Deferred.await(waitForSharedWorkerInitialized)
|
|
409
|
+
return stream.pipe(
|
|
410
|
+
dieOnRpcClientErrorStream,
|
|
411
|
+
Stream.withSpan(`@livestore/adapter-web:client-session:runInWorkerStream:${tag}`),
|
|
348
412
|
)
|
|
349
|
-
}).pipe(Stream.unwrap)
|
|
413
|
+
}).pipe(Stream.unwrap)
|
|
350
414
|
|
|
351
|
-
const bootStatusFiber = yield* runInWorkerStream(
|
|
415
|
+
const bootStatusFiber = yield* runInWorkerStream('BootStatusStream', sharedWorker.BootStatusStream({})).pipe(
|
|
352
416
|
Stream.tap((_) => Queue.offer(bootStatusQueue, _)),
|
|
353
417
|
Stream.runDrain,
|
|
354
|
-
Effect.
|
|
355
|
-
Cause.
|
|
418
|
+
Effect.tapCause((cause) =>
|
|
419
|
+
Cause.hasInterruptsOnly(cause) === true ? Effect.void : shutdown(Exit.failCause(cause)),
|
|
356
420
|
),
|
|
357
421
|
Effect.interruptible,
|
|
358
422
|
Effect.tapCauseLogPretty,
|
|
359
423
|
Effect.forkScoped,
|
|
360
424
|
)
|
|
361
425
|
|
|
362
|
-
yield* Queue.
|
|
426
|
+
yield* Queue.await(bootStatusQueue).pipe(
|
|
363
427
|
Effect.andThen(Fiber.interrupt(bootStatusFiber)),
|
|
428
|
+
Effect.interruptible,
|
|
364
429
|
Effect.tapCauseLogPretty,
|
|
365
430
|
Effect.forkScoped,
|
|
366
431
|
)
|
|
@@ -369,7 +434,7 @@ export const makePersistedAdapter =
|
|
|
369
434
|
// re-exporting the db
|
|
370
435
|
const initialResult =
|
|
371
436
|
dataFromFile === undefined
|
|
372
|
-
? yield* runInWorker(
|
|
437
|
+
? yield* runInWorker('GetRecreateSnapshot', sharedWorker.GetRecreateSnapshot({})).pipe(
|
|
373
438
|
Effect.map(({ snapshot, migrationsReport }) => ({
|
|
374
439
|
_tag: 'from-leader-worker' as const,
|
|
375
440
|
snapshot,
|
|
@@ -389,105 +454,110 @@ export const makePersistedAdapter =
|
|
|
389
454
|
const numberOfTables =
|
|
390
455
|
sqliteDb.select<{ count: number }>(`select count(*) as count from sqlite_master`)[0]?.count ?? 0
|
|
391
456
|
if (numberOfTables === 0) {
|
|
392
|
-
return yield*
|
|
457
|
+
return yield* UnknownError.make({
|
|
393
458
|
cause: `Encountered empty or corrupted database`,
|
|
394
459
|
payload: { snapshotByteLength: initialResult.snapshot.byteLength, storageOptions: options.storage },
|
|
395
460
|
})
|
|
396
461
|
}
|
|
397
462
|
|
|
398
|
-
//
|
|
399
|
-
//
|
|
400
|
-
const
|
|
401
|
-
sessionChangesetMetaTable
|
|
402
|
-
.select('seqNumClient', 'seqNumGlobal', 'seqNumRebaseGeneration')
|
|
403
|
-
.orderBy([
|
|
404
|
-
{ col: 'seqNumGlobal', direction: 'desc' },
|
|
405
|
-
{ col: 'seqNumClient', direction: 'desc' },
|
|
406
|
-
])
|
|
407
|
-
.first(),
|
|
408
|
-
)
|
|
409
|
-
|
|
410
|
-
const initialLeaderHead = initialLeaderHeadRes
|
|
411
|
-
? EventSequenceNumber.make({
|
|
412
|
-
global: initialLeaderHeadRes.seqNumGlobal,
|
|
413
|
-
client: initialLeaderHeadRes.seqNumClient,
|
|
414
|
-
rebaseGeneration: initialLeaderHeadRes.seqNumRebaseGeneration,
|
|
415
|
-
})
|
|
416
|
-
: EventSequenceNumber.ROOT
|
|
463
|
+
// The state snapshot carries its own cursor, so the fast path does not
|
|
464
|
+
// need to export or transfer the eventlog database.
|
|
465
|
+
const initialLeaderHead = yield* StateHead.make({ dbState: sqliteDb }).get
|
|
417
466
|
|
|
418
467
|
// console.debug('[@livestore/adapter-web:client-session] initialLeaderHead', initialLeaderHead)
|
|
419
468
|
|
|
420
|
-
yield* Effect.addFinalizer((ex) =>
|
|
469
|
+
yield* Effect.addFinalizer((ex: Exit.Exit<unknown, unknown>) =>
|
|
421
470
|
Effect.gen(function* () {
|
|
422
|
-
if (
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
471
|
+
if (Exit.isFailure(ex) === true) {
|
|
472
|
+
const cause = ex.cause
|
|
473
|
+
const shouldLogAsError =
|
|
474
|
+
Exit.hasInterrupts(ex) === false &&
|
|
475
|
+
Schema.is(IntentionalShutdownCause)(Cause.squash(cause)) === false &&
|
|
476
|
+
Schema.is(StoreInterrupted)(Cause.squash(cause)) === false
|
|
477
|
+
|
|
478
|
+
if (shouldLogAsError === true) {
|
|
479
|
+
yield* Effect.logError('[@livestore/adapter-web:client-session] client-session shutdown', cause)
|
|
480
|
+
} else {
|
|
481
|
+
yield* Effect.logDebug('[@livestore/adapter-web:client-session] client-session shutdown', gotLocky, ex)
|
|
482
|
+
}
|
|
429
483
|
} else {
|
|
430
484
|
yield* Effect.logDebug('[@livestore/adapter-web:client-session] client-session shutdown', gotLocky, ex)
|
|
431
485
|
}
|
|
432
486
|
|
|
433
|
-
if (gotLocky) {
|
|
487
|
+
if (gotLocky === true) {
|
|
434
488
|
yield* Deferred.succeed(lockDeferred, undefined)
|
|
435
489
|
}
|
|
436
490
|
}).pipe(Effect.tapCauseLogPretty, Effect.orDie),
|
|
437
491
|
)
|
|
438
492
|
|
|
439
493
|
const leaderThread: ClientSession['leaderThread'] = {
|
|
440
|
-
export: runInWorker(
|
|
441
|
-
Effect.
|
|
442
|
-
UnexpectedError.mapToUnexpectedError,
|
|
494
|
+
export: runInWorker('Export', sharedWorker.Export({})).pipe(
|
|
495
|
+
Effect.timeoutOrDie(10_000),
|
|
443
496
|
Effect.withSpan('@livestore/adapter-web:client-session:export'),
|
|
444
497
|
),
|
|
445
498
|
|
|
446
499
|
events: {
|
|
447
|
-
pull: ({ cursor }) =>
|
|
448
|
-
runInWorkerStream(new WorkerSchema.LeaderWorkerInnerPullStream({ cursor })).pipe(Stream.orDie),
|
|
500
|
+
pull: ({ cursor }) => runInWorkerStream('PullStream', sharedWorker.PullStream({ cursor })).pipe(Stream.orDie),
|
|
449
501
|
push: (batch) =>
|
|
450
|
-
runInWorker(
|
|
502
|
+
runInWorker('PushToLeader', sharedWorker.PushToLeader({ batch })).pipe(
|
|
451
503
|
Effect.withSpan('@livestore/adapter-web:client-session:pushToLeader', {
|
|
452
504
|
attributes: { batchSize: batch.length },
|
|
453
505
|
}),
|
|
454
506
|
),
|
|
507
|
+
stream: (options) =>
|
|
508
|
+
runInWorkerStream('StreamEvents', sharedWorker.StreamEvents(options)).pipe(
|
|
509
|
+
Stream.withSpan('@livestore/adapter-web:client-session:streamEvents'),
|
|
510
|
+
Stream.orDie,
|
|
511
|
+
),
|
|
455
512
|
},
|
|
456
513
|
|
|
457
|
-
initialState: {
|
|
514
|
+
initialState: {
|
|
515
|
+
leaderHead: initialLeaderHead,
|
|
516
|
+
migrationsReport,
|
|
517
|
+
storageMode: opfsWarning === undefined ? 'persisted' : 'in-memory',
|
|
518
|
+
},
|
|
458
519
|
|
|
459
|
-
getEventlogData: runInWorker(
|
|
460
|
-
Effect.
|
|
461
|
-
UnexpectedError.mapToUnexpectedError,
|
|
520
|
+
getEventlogData: runInWorker('ExportEventlog', sharedWorker.ExportEventlog({})).pipe(
|
|
521
|
+
Effect.timeoutOrDie(10_000),
|
|
462
522
|
Effect.withSpan('@livestore/adapter-web:client-session:getEventlogData'),
|
|
463
523
|
),
|
|
464
524
|
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
525
|
+
syncState: Subscribable.make({
|
|
526
|
+
get: runInWorker('GetLeaderSyncState', sharedWorker.GetLeaderSyncState({})).pipe(
|
|
527
|
+
Effect.withSpan('@livestore/adapter-web:client-session:getLeaderSyncState'),
|
|
528
|
+
),
|
|
529
|
+
changes: runInWorkerStream('SyncStateStream', sharedWorker.SyncStateStream({})).pipe(Stream.orDie),
|
|
530
|
+
}),
|
|
469
531
|
|
|
470
532
|
sendDevtoolsMessage: (message) =>
|
|
471
|
-
runInWorker(
|
|
472
|
-
UnexpectedError.mapToUnexpectedError,
|
|
533
|
+
runInWorker('ExtraDevtoolsMessage', sharedWorker.ExtraDevtoolsMessage({ message })).pipe(
|
|
473
534
|
Effect.withSpan('@livestore/adapter-web:client-session:devtoolsMessageForLeader'),
|
|
474
535
|
),
|
|
536
|
+
networkStatus: Subscribable.make({
|
|
537
|
+
get: runInWorker('GetNetworkStatus', sharedWorker.GetNetworkStatus({})),
|
|
538
|
+
changes: runInWorkerStream('NetworkStatusStream', sharedWorker.NetworkStatusStream({})),
|
|
539
|
+
}),
|
|
475
540
|
}
|
|
476
541
|
|
|
477
|
-
const sharedWorker = yield* Fiber.join(sharedWorkerFiber)
|
|
478
|
-
|
|
479
542
|
const clientSession = yield* makeClientSession({
|
|
480
543
|
...adapterArgs,
|
|
481
544
|
sqliteDb,
|
|
482
545
|
lockStatus,
|
|
483
546
|
clientId,
|
|
484
547
|
sessionId,
|
|
485
|
-
|
|
486
|
-
isLeader: true,
|
|
548
|
+
isLeader: gotLocky,
|
|
487
549
|
leaderThread,
|
|
488
550
|
webmeshMode: 'direct',
|
|
551
|
+
// Can be undefined in Node.js
|
|
552
|
+
origin: globalThis.location?.origin,
|
|
489
553
|
connectWebmeshNode: ({ sessionInfo, webmeshNode }) =>
|
|
490
|
-
connectWebmeshNodeClientSession({
|
|
554
|
+
connectWebmeshNodeClientSession({
|
|
555
|
+
webmeshNode,
|
|
556
|
+
sessionInfo,
|
|
557
|
+
sharedWorker: makeWebmeshWorkerProxy(sharedWorker),
|
|
558
|
+
devtoolsEnabled,
|
|
559
|
+
schema,
|
|
560
|
+
}),
|
|
491
561
|
registerBeforeUnload: (onBeforeUnload) => {
|
|
492
562
|
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
|
|
493
563
|
window.addEventListener('beforeunload', onBeforeUnload)
|
|
@@ -499,7 +569,7 @@ export const makePersistedAdapter =
|
|
|
499
569
|
})
|
|
500
570
|
|
|
501
571
|
return clientSession
|
|
502
|
-
}).pipe(
|
|
572
|
+
}).pipe(Effect.provide(Opfs.layer), UnknownError.mapToUnknownError)
|
|
503
573
|
|
|
504
574
|
// NOTE for `local` storage we could also use the eventlog db to store the data
|
|
505
575
|
const getPersistedId = (key: string, storageType: 'session' | 'local') => {
|
|
@@ -512,7 +582,7 @@ const getPersistedId = (key: string, storageType: 'session' | 'local') => {
|
|
|
512
582
|
? sessionStorage
|
|
513
583
|
: storageType === 'local'
|
|
514
584
|
? localStorage
|
|
515
|
-
: shouldNeverHappen(`[@livestore/adapter-web] Invalid storage type: ${storageType}`)
|
|
585
|
+
: shouldNeverHappen(`[@livestore/adapter-web] Invalid storage type: ${String(storageType)}`)
|
|
516
586
|
|
|
517
587
|
// in case of a worker, we need the id of the parent window, to keep the id consistent
|
|
518
588
|
// we also need to handle the case where there are multiple workers being spawned by the same window
|
|
@@ -523,7 +593,7 @@ const getPersistedId = (key: string, storageType: 'session' | 'local') => {
|
|
|
523
593
|
const fullKey = `livestore:${key}`
|
|
524
594
|
const storedKey = storage.getItem(fullKey)
|
|
525
595
|
|
|
526
|
-
if (storedKey) return storedKey
|
|
596
|
+
if (storedKey !== null) return storedKey
|
|
527
597
|
|
|
528
598
|
const newKey = makeId()
|
|
529
599
|
storage.setItem(fullKey, newKey)
|
|
@@ -534,8 +604,8 @@ const getPersistedId = (key: string, storageType: 'session' | 'local') => {
|
|
|
534
604
|
const ensureBrowserRequirements = Effect.gen(function* () {
|
|
535
605
|
const validate = (condition: boolean, label: string) =>
|
|
536
606
|
Effect.gen(function* () {
|
|
537
|
-
if (condition) {
|
|
538
|
-
return yield*
|
|
607
|
+
if (condition === true) {
|
|
608
|
+
return yield* UnknownError.make({
|
|
539
609
|
cause: `[@livestore/adapter-web] Browser not supported. The LiveStore web adapter needs '${label}' to work properly`,
|
|
540
610
|
})
|
|
541
611
|
}
|
|
@@ -550,3 +620,29 @@ const ensureBrowserRequirements = Effect.gen(function* () {
|
|
|
550
620
|
validate(typeof sessionStorage === 'undefined', 'sessionStorage'),
|
|
551
621
|
])
|
|
552
622
|
})
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Attempts to access OPFS and returns a warning if unavailable.
|
|
626
|
+
*
|
|
627
|
+
* Common failure scenarios:
|
|
628
|
+
* - Safari/Firefox private browsing: SecurityError or NotAllowedError
|
|
629
|
+
* - Permission denied: NotAllowedError
|
|
630
|
+
* - Quota exceeded: QuotaExceededError
|
|
631
|
+
*/
|
|
632
|
+
const checkOpfsAvailability = Effect.gen(function* () {
|
|
633
|
+
const opfs = yield* Opfs.Opfs
|
|
634
|
+
return yield* opfs.getRootDirectoryHandle.pipe(
|
|
635
|
+
Effect.as(undefined),
|
|
636
|
+
Effect.catch((error) => {
|
|
637
|
+
const reason: BootWarningReason =
|
|
638
|
+
Schema.is(WebError.SecurityError)(error) === true || Schema.is(WebError.NotAllowedError)(error) === true
|
|
639
|
+
? 'private-browsing'
|
|
640
|
+
: 'storage-unavailable'
|
|
641
|
+
const message =
|
|
642
|
+
reason === 'private-browsing'
|
|
643
|
+
? 'Storage unavailable in private browsing mode. LiveStore will continue without persistence.'
|
|
644
|
+
: 'Storage access denied. LiveStore will continue without persistence.'
|
|
645
|
+
return Effect.succeed({ reason, message } as const)
|
|
646
|
+
}),
|
|
647
|
+
)
|
|
648
|
+
})
|