-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpersist-worker-thread.js
More file actions
48 lines (44 loc) · 1.32 KB
/
persist-worker-thread.js
File metadata and controls
48 lines (44 loc) · 1.32 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
import * as Y from 'yjs'
import * as logging from 'lib0/logging'
import { isMainThread, parentPort } from 'worker_threads'
export class PersistWorkerThread {
/**
* @private
* @readonly
*/
log = logging.createModuleLogger('@y/persist-worker-thread')
/**
* @param {import('./storage.js').AbstractStorage} store
*/
constructor (store) {
if (isMainThread) {
this.log('persist worker cannot run on main thread')
return
}
this.store = store
parentPort?.postMessage({ event: 'ready' })
parentPort?.on('message', ({ event, ...rest }) => {
if (event === 'ping') parentPort?.postMessage({ event: 'pong' })
else this.persist(rest)
})
}
/**
* @param {{ room: string, docstate: SharedArrayBuffer }} props
*/
persist = async ({ room, docstate }) => {
this.log(`persisting ${room} in worker`)
const state = new Uint8Array(docstate)
const doc = new Y.Doc()
Y.applyUpdateV2(doc, state)
await this.store?.persistDoc(room, 'index', doc)
doc.destroy()
parentPort?.postMessage({ event: 'persisted', room })
}
}
/**
* @param {import('./storage.js').AbstractStorage} store
*/
export function createPersistWorkerThread (store) {
if (isMainThread) throw new Error('cannot create persist worker in main thread')
return new PersistWorkerThread(store)
}