Skip to content

Commit e47b219

Browse files
author
JJ
committed
Fix - reverting cmd to numbers
1 parent 511740c commit e47b219

2 files changed

Lines changed: 43 additions & 36 deletions

File tree

app/app.js

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ const {
2626

2727
class Drift {
2828
constructor () {
29-
this.spaces = new Map() // id → Space
30-
this._topics = new Map() // topicHex → Space
29+
this.spaces = new Map()
30+
this._topics = new Map()
3131
this.swarm = null
3232
this.rpc = new RPC(BareKit.IPC, (req) => this._onRequest(req))
3333

@@ -42,46 +42,39 @@ class Drift {
4242

4343
this.swarm.on('connection', (conn, info) => {
4444
const noiseKey = info.publicKey.toString('hex')
45-
const topicHexes = (info.topics || []).map(t => t.toString('hex'))
46-
const discHex = info.discoveryKey ? info.discoveryKey.toString('hex') : null
45+
const topics = info.topics || []
46+
const peerTopics = info.peer?.topics || []
4747

48-
console.log('[drift] connection noise:', noiseKey.slice(0, 8),
49-
'topics:', topicHexes.map(t => t.slice(0, 8)),
50-
'disc:', discHex ? discHex.slice(0, 8) : 'none')
48+
// combine all topic sources
49+
const allTopics = [...new Set([
50+
...topics.map(t => t.toString('hex')),
51+
...peerTopics.map(t => t.toString('hex')),
52+
...(info.discoveryKey ? [info.discoveryKey.toString('hex')] : [])
53+
])]
54+
55+
console.log('[drift] connection noise:', noiseKey.slice(0, 8), 'all topics:', allTopics.map(t => t.slice(0, 8)))
5156

5257
conn.on('error', (err) => console.log('[drift] conn error:', err.message))
5358

54-
// initiator side — info.topics is populated
55-
if (topicHexes.length > 0) {
56-
for (const hex of topicHexes) {
57-
const space = this._topics.get(hex)
58-
if (space) {
59-
console.log('[drift] routing to space:', space.name, '(initiator)')
60-
space.addPeer(conn, info, true)
61-
return
62-
}
63-
}
64-
}
59+
const isInitiator = topics.length > 0
6560

66-
// responder side — use discoveryKey which equals the topic
67-
if (discHex) {
68-
const space = this._topics.get(discHex)
61+
// find matching space from any topic source
62+
for (const hex of allTopics) {
63+
const space = this._topics.get(hex)
6964
if (space) {
70-
console.log('[drift] routing to space:', space.name, '(responder)')
71-
space.addPeer(conn, info, false)
65+
console.log('[drift] routing to space:', space.name, isInitiator ? '(initiator)' : '(responder)')
66+
space.addPeer(conn, info, isInitiator)
7267
return
7368
}
7469
}
7570

76-
console.log('[drift] no space found for connection')
71+
console.log('[drift] no space found — known topics:', [...this._topics.keys()].map(k => k.slice(0, 8)))
7772
})
7873

79-
// register all spaces first
8074
const saved = store.loadSpaces()
8175
console.log('[drift] loading', saved.length, 'saved spaces')
8276
for (const opts of saved) this._registerSpace(opts)
8377

84-
// join swarm for all spaces at once
8578
const discoveries = []
8679
for (const space of this.spaces.values()) {
8780
const d = this.swarm.join(space.topic(), { server: true, client: true })

app/space.js

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ const fs = require('bare-fs')
88
const path = require('bare-path')
99
const store = require('./store')
1010

11+
// peer protocol commands
12+
const CMD_MANIFEST = 1
13+
const CMD_GET = 2
14+
const CMD_PUT = 3
15+
const CMD_DEL = 4
16+
1117
class Space {
1218
constructor (opts, emit) {
1319
this.id = opts.id
@@ -54,21 +60,20 @@ class Space {
5460
spaceId: this.id, peerId: id, peers: this._peers.size
5561
})
5662

57-
// only initiator starts the sync to avoid both sides requesting at once
5863
if (isInitiator) this._syncWithPeer(id)
5964
}
6065

6166
async _onRequest (req) {
6267
switch (req.command) {
6368

64-
case 1: { // manifest
69+
case CMD_MANIFEST: {
6570
const manifest = await this._buildManifest()
6671
console.log('[space] sending manifest:', manifest.length, 'files')
6772
req.reply(Buffer.from(JSON.stringify(manifest)))
6873
break
6974
}
7075

71-
case 2: { // get
76+
case CMD_GET: {
7277
const key = req.data.toString()
7378
const abs = path.join(this._folder, key)
7479
console.log('[space] peer GET', key)
@@ -80,7 +85,7 @@ class Space {
8085
break
8186
}
8287

83-
case 3: { // put
88+
case CMD_PUT: {
8489
const { key, data: b64 } = JSON.parse(req.data.toString())
8590
const buf = Buffer.from(b64, 'base64')
8691
const abs = path.join(this._folder, key)
@@ -99,7 +104,7 @@ class Space {
99104
break
100105
}
101106

102-
case 4: { // del
107+
case CMD_DEL: {
103108
const key = req.data.toString()
104109
const abs = path.join(this._folder, key)
105110
console.log('[space] peer DEL', key)
@@ -120,14 +125,23 @@ class Space {
120125
}
121126
}
122127

128+
// wrap bare-rpc request in a promise
129+
_request (rpc, command, data) {
130+
return new Promise((resolve, reject) => {
131+
const req = rpc.request(command)
132+
req.on('response', (res) => resolve(res.data))
133+
req.on('error', reject)
134+
req.send(data)
135+
})
136+
}
137+
123138
async _syncWithPeer (peerId) {
124139
console.log('[space] syncing with', peerId.slice(0, 8))
125140
const rpc = this._peers.get(peerId)
126141
if (!rpc) { console.log('[space] peer gone'); return }
127142

128143
try {
129-
// get their manifest
130-
const raw = await rpc.request(1).send(Buffer.alloc(0))
144+
const raw = await this._request(rpc, CMD_MANIFEST, Buffer.alloc(0))
131145
const theirFiles = JSON.parse(raw.toString())
132146
console.log('[space] peer has', theirFiles.length, 'files')
133147

@@ -138,7 +152,7 @@ class Space {
138152
const mine = myMap.get(their.key)
139153
if (!mine || their.mtime > mine.mtime) {
140154
console.log('[space] pulling', their.key)
141-
const data = await rpc.request(2).send(Buffer.from(their.key))
155+
const data = await this._request(rpc, CMD_GET, Buffer.from(their.key))
142156
if (data && data.length > 0) {
143157
const abs = path.join(this._folder, their.key)
144158
await fs.promises.mkdir(path.dirname(abs), { recursive: true })
@@ -196,7 +210,7 @@ class Space {
196210
const data = await fs.promises.readFile(filename)
197211
for (const [id, rpc] of this._peers) {
198212
try {
199-
await rpc.request(3).send(Buffer.from(
213+
await this._request(rpc, CMD_PUT, Buffer.from(
200214
JSON.stringify({ key, data: data.toString('base64') })
201215
))
202216
console.log('[space] pushed', key, 'to', id.slice(0, 8))
@@ -207,7 +221,7 @@ class Space {
207221
} else if (type === 'delete') {
208222
for (const [id, rpc] of this._peers) {
209223
try {
210-
await rpc.request(4).send(Buffer.from(key))
224+
await this._request(rpc, CMD_DEL, Buffer.from(key))
211225
console.log('[space] del pushed to', id.slice(0, 8))
212226
} catch (err) {
213227
console.log('[space] del failed to', id.slice(0, 8), err.message)

0 commit comments

Comments
 (0)