Repository navigation
Expand file tree
/
Copy pathsession-state.js
More file actions
69 lines (60 loc) · 1.72 KB
/
Copy pathsession-state.js
File metadata and controls
69 lines (60 loc) · 1.72 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
module.exports = class SessionState {
constructor (corestore) {
this.corestore = corestore
this.hypercores = new Map()
this.resources = new Map()
}
addResource (id, value, dealloc) {
const res = this.resources.get(id)
if (res) {
dealloc()
throw new Error('Resource already exists: ' + id)
}
this.resources.set(id, {
value,
dealloc
})
}
hasResource (id) {
return this.resources.has(id)
}
getResource (id) {
const res = this.resources.get(id)
if (!res) throw new Error('Invalid resource: ' + id)
return res.value
}
deleteResource (id, noDealloc) {
const res = this.resources.get(id)
if (!res) throw new Error('Invalid resource: ' + id)
if (!noDealloc) res.dealloc()
this.resources.delete(id)
}
hasCore (id) {
return this.hypercores.has(id)
}
addCore (id, core, isWeak) {
if (this.hypercores.has(id)) throw new Error('Hypercore already exists in session: ' + id)
if (!isWeak) this.corestore.cache.increment(core.discoveryKey.toString('hex'))
this.hypercores.set(id, { core, isWeak })
}
getCore (id) {
if (!this.hypercores.has(id)) throw new Error('Invalid hypercore: ' + id)
const { core } = this.hypercores.get(id)
return core
}
deleteCore (id) {
if (!this.hypercores.has(id)) throw new Error('Invalid hypercore: ' + id)
const { core, isWeak } = this.hypercores.get(id)
if (!isWeak) this.corestore.cache.decrement(core.discoveryKey.toString('hex'))
this.hypercores.delete(id)
}
deleteAll () {
for (const { dealloc } of this.resources.values()) {
dealloc()
}
for (const id of this.hypercores.keys()) {
this.deleteCore(id)
}
this.resources.clear()
}
}