Skip to content

Commit

Permalink
(protocol): improve emit method
Browse files Browse the repository at this point in the history
  • Loading branch information
heapwolf committed Feb 7, 2024
1 parent b26ad16 commit 0c235fb
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions api/stream-relay/sugar.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { wrap, Encryption, sha256, NAT, RemotePeer } from './index.js'
import { sodium } from '../crypto.js'
import { Buffer } from '../buffer.js'
import { isBufferLike } from '../util.js'
import { CACHE_TTL } from './packets.js'
import { Packet, CACHE_TTL } from './packets.js'

/**
* Creates and manages a network bus for communication.
Expand Down Expand Up @@ -249,15 +249,32 @@ export default (dgram, events) => {

sub.emit = async (eventName, value, opts = {}) => {
opts.clusterId = opts.clusterId || clusterId
opts.subclusterId = opts.subclusterId || subclusterId
opts.subclusterId = opts.subclusterId || sub.subclusterId

const args = await pack(eventName, value, opts)

for (const p of sub.peers.values()) {
await p._peer.write(sub.sharedKey, args)
}
if (sub.peers.values().length) {
let packets = []

for (const p of sub.peers.values()) {
const r = await p._peer.write(sub.sharedKey, args)
if (packets.length === 0) packets = r
}

for (const packet of packets) {
const p = Packet.from(packet)
_peer.cache.insert(packet.packetId.toString('hex'), p)

return await _peer.publish(sub.sharedKey, args)
_peer.unpublished[packet.packetId.toString('hex')] = Date.now()
if (globalThis.navigator && !globalThis.navigator.onLine) continue

_peer.mcast(packet)
}
return packets
} else {
const packets = await _peer.publish(sub.sharedKey, args)
return packets
}
}

sub.on = async (eventName, cb) => {
Expand Down

0 comments on commit 0c235fb

Please sign in to comment.