This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathstore.ts
187 lines (151 loc) · 5.37 KB
/
store.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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import { CodeError } from '@libp2p/interfaces/errors'
import { PeerMap } from '@libp2p/peer-collections'
import { peerIdFromBytes } from '@libp2p/peer-id'
import mortice, { type Mortice } from 'mortice'
import { base32 } from 'multiformats/bases/base32'
import { equals as uint8ArrayEquals } from 'uint8arrays/equals'
import { codes } from './errors.js'
import { Peer as PeerPB } from './pb/peer.js'
import { bytesToPeer } from './utils/bytes-to-peer.js'
import { NAMESPACE_COMMON, peerIdToDatastoreKey } from './utils/peer-id-to-datastore-key.js'
import { toPeerPB } from './utils/to-peer-pb.js'
import type { AddressFilter, PersistentPeerStoreComponents, PersistentPeerStoreInit } from './index.js'
import type { PeerUpdate as PeerUpdateExternal } from '@libp2p/interface-libp2p'
import type { PeerId } from '@libp2p/interface-peer-id'
import type { Peer, PeerData, PeerQuery } from '@libp2p/interface-peer-store'
import type { Datastore, Key, Query } from 'interface-datastore'
/**
* Event detail emitted when peer data changes
*/
export interface PeerUpdate extends PeerUpdateExternal {
updated: boolean
}
function decodePeer (key: Key, value: Uint8Array, cache: PeerMap<Peer>): Peer {
// /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}
const base32Str = key.toString().split('/')[2]
const buf = base32.decode(base32Str)
const peerId = peerIdFromBytes(buf)
const cached = cache.get(peerId)
if (cached != null) {
return cached
}
const peer = bytesToPeer(peerId, value)
cache.set(peerId, peer)
return peer
}
function mapQuery (query: PeerQuery, cache: PeerMap<Peer>): Query {
if (query == null) {
return {}
}
return {
prefix: NAMESPACE_COMMON,
filters: (query.filters ?? []).map(fn => ({ key, value }) => {
return fn(decodePeer(key, value, cache))
}),
orders: (query.orders ?? []).map(fn => (a, b) => {
return fn(decodePeer(a.key, a.value, cache), decodePeer(b.key, b.value, cache))
})
}
}
export class PersistentStore {
private readonly peerId: PeerId
private readonly datastore: Datastore
public readonly lock: Mortice
private readonly addressFilter?: AddressFilter
constructor (components: PersistentPeerStoreComponents, init: PersistentPeerStoreInit = {}) {
this.peerId = components.peerId
this.datastore = components.datastore
this.addressFilter = init.addressFilter
this.lock = mortice({
name: 'peer-store',
singleProcess: true
})
}
async has (peerId: PeerId): Promise<boolean> {
return this.datastore.has(peerIdToDatastoreKey(peerId))
}
async delete (peerId: PeerId): Promise<void> {
if (this.peerId.equals(peerId)) {
throw new CodeError('Cannot delete self peer', codes.ERR_INVALID_PARAMETERS)
}
await this.datastore.delete(peerIdToDatastoreKey(peerId))
}
async load (peerId: PeerId): Promise<Peer> {
const buf = await this.datastore.get(peerIdToDatastoreKey(peerId))
return bytesToPeer(peerId, buf)
}
async save (peerId: PeerId, data: PeerData): Promise<PeerUpdate> {
const {
existingBuf,
existingPeer
} = await this.#findExistingPeer(peerId)
const peerPb: PeerPB = await toPeerPB(peerId, data, 'patch', {
addressFilter: this.addressFilter
})
return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer)
}
async patch (peerId: PeerId, data: Partial<PeerData>): Promise<PeerUpdate> {
const {
existingBuf,
existingPeer
} = await this.#findExistingPeer(peerId)
const peerPb: PeerPB = await toPeerPB(peerId, data, 'patch', {
addressFilter: this.addressFilter,
existingPeer
})
return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer)
}
async merge (peerId: PeerId, data: PeerData): Promise<PeerUpdate> {
const {
existingBuf,
existingPeer
} = await this.#findExistingPeer(peerId)
const peerPb: PeerPB = await toPeerPB(peerId, data, 'merge', {
addressFilter: this.addressFilter,
existingPeer
})
return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer)
}
async * all (query?: PeerQuery): AsyncGenerator<Peer, void, unknown> {
const peerCache = new PeerMap<Peer>()
for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, peerCache))) {
const peer = decodePeer(key, value, peerCache)
if (peer.id.equals(this.peerId)) {
// Skip self peer if present
continue
}
yield peer
}
}
async #findExistingPeer (peerId: PeerId): Promise<{ existingBuf?: Uint8Array, existingPeer?: Peer }> {
try {
const existingBuf = await this.datastore.get(peerIdToDatastoreKey(peerId))
const existingPeer = bytesToPeer(peerId, existingBuf)
return {
existingBuf,
existingPeer
}
} catch (err: any) {
if (err.code !== 'ERR_NOT_FOUND') {
throw err
}
}
return {}
}
async #saveIfDifferent (peerId: PeerId, peer: PeerPB, existingBuf?: Uint8Array, existingPeer?: Peer): Promise<PeerUpdate> {
const buf = PeerPB.encode(peer)
if (existingBuf != null && uint8ArrayEquals(buf, existingBuf)) {
return {
peer: bytesToPeer(peerId, buf),
previous: existingPeer,
updated: false
}
}
await this.datastore.put(peerIdToDatastoreKey(peerId), buf)
return {
peer: bytesToPeer(peerId, buf),
previous: existingPeer,
updated: true
}
}
}