-
Notifications
You must be signed in to change notification settings - Fork 73
/
head-state.ts
72 lines (55 loc) · 1.81 KB
/
head-state.ts
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
import { Block } from './block.js'
import { defaultLogger } from '../logger.js'
type Callback = (block: Block, pairs: [string, string | null][]) => void | Promise<void>
export const randomId = () => Math.random().toString(36).substring(2)
const logger = defaultLogger.child({ name: 'head-state' })
export class HeadState {
#headListeners: Record<string, (block: Block) => void | Promise<void>> = {}
#storageListeners: Record<string, [string[], Callback]> = {}
#oldValues: Record<string, string | null> = {}
#head: Block
constructor(head: Block) {
this.#head = head
}
subscribeHead(cb: (block: Block) => void) {
const id = randomId()
this.#headListeners[id] = cb
return id
}
unsubscribeHead(id: string) {
delete this.#headListeners[id]
}
async subscribeStorage(keys: string[], cb: Callback) {
const id = randomId()
this.#storageListeners[id] = [keys, cb]
for (const key of keys) {
this.#oldValues[key] = await this.#head.get(key).then((val) => val || null)
}
return id
}
unsubscribeStorage(id: string) {
delete this.#storageListeners[id]
}
async setHead(head: Block) {
this.#head = head
for (const cb of Object.values(this.#headListeners)) {
try {
await cb(head)
} catch (error) {
logger.error(error, 'setHead head callback error')
}
}
const diff = await this.#head.storageDiff()
for (const [keys, cb] of Object.values(this.#storageListeners)) {
const changed = keys.filter((key) => diff[key]).map((key) => [key, diff[key]] as [string, string | null])
if (changed.length > 0) {
try {
await cb(head, changed)
} catch (error) {
logger.error(error, 'setHead storage diff callback error')
}
}
}
Object.assign(this.#oldValues, diff)
}
}