@steve02081504/fount-p2p 0.0.29 → 0.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/discovery/bt/index.mjs +1 -3
- package/discovery/nostr.mjs +3 -3
- package/files/chunk/store.mjs +3 -2
- package/index.mjs +2 -0
- package/infra/priority.mjs +1 -3
- package/infra/service.mjs +2 -6
- package/link/providers/ble_gatt.mjs +2 -6
- package/link/providers/lan_tcp.mjs +3 -9
- package/link/providers/webrtc.mjs +5 -2
- package/link/rtc/ice_local_hostname.mjs +15 -47
- package/link/rtc/polyfill.mjs +3 -15
- package/node/handles.mjs +49 -0
- package/node/instance.mjs +7 -4
- package/node/reputation_sync.mjs +2 -6
- package/package.json +1 -1
- package/transport/group_link_set.mjs +2 -6
- package/transport/link_registry.mjs +1 -3
- package/transport/offer_answer.mjs +1 -3
- package/transport/runtime_bootstrap.mjs +2 -6
- package/utils/async_mutex.mjs +1 -3
- package/utils/ttl_map.mjs +1 -3
- package/link/rtc/w3c_bridge.mjs +0 -152
package/discovery/bt/index.mjs
CHANGED
|
@@ -297,9 +297,7 @@ export function createBluetoothDiscoveryProvider() {
|
|
|
297
297
|
cleanup()
|
|
298
298
|
reject(new Error('p2p: bt signal peripheral timeout'))
|
|
299
299
|
}, 8_000)
|
|
300
|
-
/**
|
|
301
|
-
* @returns {void}
|
|
302
|
-
*/
|
|
300
|
+
/** 清理信号超时计时器并移除 discover 监听器 */
|
|
303
301
|
function cleanup() {
|
|
304
302
|
clearTimeout(deadline)
|
|
305
303
|
noble.removeListener('discover', onDiscover)
|
package/discovery/nostr.mjs
CHANGED
|
@@ -243,6 +243,7 @@ function connectRelay(relayUrl, timeoutMs = NOSTR_CONNECT_TIMEOUT_MS, signal) {
|
|
|
243
243
|
reject(error)
|
|
244
244
|
}
|
|
245
245
|
/**
|
|
246
|
+
* 收到 abort 信号时失败
|
|
246
247
|
* @returns {void}
|
|
247
248
|
*/
|
|
248
249
|
const onAbort = () => fail(new Error('nostr: aborted'))
|
|
@@ -294,6 +295,7 @@ function publishEventOnRelay(ws, relayUrl, event, signal, isCurrent) {
|
|
|
294
295
|
else resolve(ok)
|
|
295
296
|
}
|
|
296
297
|
/**
|
|
298
|
+
* 收到 abort 信号时以失败结束
|
|
297
299
|
* @returns {void}
|
|
298
300
|
*/
|
|
299
301
|
const onAbort = () => finish(false, new Error('nostr: aborted'))
|
|
@@ -492,9 +494,7 @@ function attachSharedRelaySocket(relayUrl, session, ws) {
|
|
|
492
494
|
function scheduleSharedRelayConnect(relayUrl, session, delayMs = 0) {
|
|
493
495
|
if (!isLiveSharedSession(relayUrl, session) || session.connecting || session.ws) return
|
|
494
496
|
clearSharedRelayReconnect(session)
|
|
495
|
-
/**
|
|
496
|
-
* @returns {void}
|
|
497
|
-
*/
|
|
497
|
+
/** 启动/恢复共享会话连接 */
|
|
498
498
|
const start = () => {
|
|
499
499
|
session.reconnectTimer = null
|
|
500
500
|
if (!isLiveSharedSession(relayUrl, session) || session.connecting || session.ws) return
|
package/files/chunk/store.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { dirname, join } from 'node:path'
|
|
|
5
5
|
import { pipeline } from 'node:stream/promises'
|
|
6
6
|
|
|
7
7
|
import { isHex64 } from '../../core/hexIds.mjs'
|
|
8
|
+
import { trackFileStream } from '../../node/handles.mjs'
|
|
8
9
|
import { getNodeDir } from '../../node/instance.mjs'
|
|
9
10
|
|
|
10
11
|
/**
|
|
@@ -50,7 +51,7 @@ export async function getChunk(hash) {
|
|
|
50
51
|
* @returns {import('node:fs').ReadStream} 可读流
|
|
51
52
|
*/
|
|
52
53
|
export function createChunkReadStream(hash) {
|
|
53
|
-
return fs.createReadStream(chunkStorePath(hash))
|
|
54
|
+
return trackFileStream(fs.createReadStream(chunkStorePath(hash)))
|
|
54
55
|
}
|
|
55
56
|
|
|
56
57
|
/**
|
|
@@ -72,5 +73,5 @@ export async function putChunk(hash, data) {
|
|
|
72
73
|
export async function putChunkFromStream(hash, readable) {
|
|
73
74
|
const filePath = chunkStorePath(hash)
|
|
74
75
|
await fsp.mkdir(dirname(filePath), { recursive: true })
|
|
75
|
-
await pipeline(readable, fs.createWriteStream(filePath))
|
|
76
|
+
await pipeline(readable, trackFileStream(fs.createWriteStream(filePath)))
|
|
76
77
|
}
|
package/index.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import { registerLinkProvider } from './link/providers/index.mjs'
|
|
12
12
|
import { ensureNodeDefaults, getNodeHash } from './node/identity.mjs'
|
|
13
13
|
import {
|
|
14
|
+
closeNode,
|
|
14
15
|
getNodeDir,
|
|
15
16
|
initNode,
|
|
16
17
|
isNodeInitialized,
|
|
@@ -58,6 +59,7 @@ import {
|
|
|
58
59
|
export {
|
|
59
60
|
attachReputationSyncWire,
|
|
60
61
|
attachNodeScopeDefaultFeatures,
|
|
62
|
+
closeNode,
|
|
61
63
|
configureLinkRegistry,
|
|
62
64
|
createGroupLinkSet,
|
|
63
65
|
createScopedLinkRoom,
|
package/infra/priority.mjs
CHANGED
|
@@ -28,9 +28,7 @@ export function getInfraPriority() {
|
|
|
28
28
|
return { ...priorityConfig }
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
/**
|
|
32
|
-
* @returns {void}
|
|
33
|
-
*/
|
|
31
|
+
/** 将优先级配置应用到 link registry */
|
|
34
32
|
export function applyPriorityToRegistry() {
|
|
35
33
|
const registry = getLinkRegistry()
|
|
36
34
|
if (!priorityConfig.useLocalReputation) {
|
package/infra/service.mjs
CHANGED
|
@@ -42,9 +42,7 @@ export function consumeOverlayRateToken(buckets, sender, now, limits) {
|
|
|
42
42
|
return true
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
-
/**
|
|
46
|
-
* @returns {void}
|
|
47
|
-
*/
|
|
45
|
+
/** 安装 overlay 速率门 */
|
|
48
46
|
function installOverlayRateLimit() {
|
|
49
47
|
const limits = {
|
|
50
48
|
perMin: Math.max(1, Number(infraTunables.overlayRatePerMin) || 120),
|
|
@@ -56,9 +54,7 @@ function installOverlayRateLimit() {
|
|
|
56
54
|
})
|
|
57
55
|
}
|
|
58
56
|
|
|
59
|
-
/**
|
|
60
|
-
* @returns {void}
|
|
61
|
-
*/
|
|
57
|
+
/** 移除 overlay 速率门并清空桶 */
|
|
62
58
|
function removeOverlayRateLimit() {
|
|
63
59
|
clearOverlayRateGate()
|
|
64
60
|
overlayRateBuckets.clear()
|
|
@@ -80,9 +80,7 @@ async function dialBleGatt(options) {
|
|
|
80
80
|
cleanup()
|
|
81
81
|
reject(new Error('p2p: ble_gatt peripheral scan timeout'))
|
|
82
82
|
}, 8_000)
|
|
83
|
-
/**
|
|
84
|
-
* @returns {void}
|
|
85
|
-
*/
|
|
83
|
+
/** 清理扫描超时计时器与监听器并停止 BLE 扫描 */
|
|
86
84
|
function cleanup() {
|
|
87
85
|
clearTimeout(deadline)
|
|
88
86
|
noble.removeListener('discover', onDiscover)
|
|
@@ -249,9 +247,7 @@ export function createBleGattLinkProvider() {
|
|
|
249
247
|
sessionInbound = handler
|
|
250
248
|
return () => { sessionInbound = null }
|
|
251
249
|
},
|
|
252
|
-
/**
|
|
253
|
-
* @returns {void}
|
|
254
|
-
*/
|
|
250
|
+
/** 关闭入站 transport */
|
|
255
251
|
closeTransport() {
|
|
256
252
|
activeInbound = null
|
|
257
253
|
sessionInbound = null
|
|
@@ -35,9 +35,7 @@ function connectTcp(host, port, timeoutMs = LAN_TCP_CONNECT_TIMEOUT_MS) {
|
|
|
35
35
|
conn.off('connect', onConnect)
|
|
36
36
|
reject(error)
|
|
37
37
|
}
|
|
38
|
-
/**
|
|
39
|
-
* @returns {void}
|
|
40
|
-
*/
|
|
38
|
+
/** TCP 连接成功并返回 socket */
|
|
41
39
|
function onConnect() {
|
|
42
40
|
clearTimeout(timer)
|
|
43
41
|
conn.off('error', onError)
|
|
@@ -111,9 +109,7 @@ function attachLengthPrefix(socket, onPayload) {
|
|
|
111
109
|
header.writeUInt32BE(body.length)
|
|
112
110
|
socket.write(Buffer.concat([header, body]))
|
|
113
111
|
},
|
|
114
|
-
/**
|
|
115
|
-
* @returns {void}
|
|
116
|
-
*/
|
|
112
|
+
/** 仅移除 data 监听器 */
|
|
117
113
|
destroy() {
|
|
118
114
|
socket.off('data', onData)
|
|
119
115
|
},
|
|
@@ -149,9 +145,7 @@ function createTcpPipe(options) {
|
|
|
149
145
|
sendFrame(_action, frame) {
|
|
150
146
|
codec.write(frame)
|
|
151
147
|
},
|
|
152
|
-
/**
|
|
153
|
-
* @returns {void}
|
|
154
|
-
*/
|
|
148
|
+
/** 关闭 transport 与 socket */
|
|
155
149
|
closeTransport() {
|
|
156
150
|
codec.destroy()
|
|
157
151
|
socket.destroy()
|
|
@@ -68,8 +68,7 @@ export async function createWebRtcLink(options) {
|
|
|
68
68
|
const handshakeTimeoutMs = Number(options.handshakeTimeoutMs) || ms('10s')
|
|
69
69
|
const channelOpenTimeoutMs = Math.max(handshakeTimeoutMs, ms('30s'))
|
|
70
70
|
const rtc = options.rtc ?? await loadNodeRtcPolyfill()
|
|
71
|
-
|
|
72
|
-
const trickleIceOff = !rtc.forcesTrickleIce && getSignalingRuntimeConfig().trickleIceOff === true
|
|
71
|
+
const trickleIceOff = getSignalingRuntimeConfig().trickleIceOff === true
|
|
73
72
|
const peerConnection = new rtc.RTCPeerConnection(options.iceServers?.length ? { iceServers: options.iceServers } : undefined)
|
|
74
73
|
const remoteSignalQueue = []
|
|
75
74
|
const seenRemoteSignals = createLruMap(1024)
|
|
@@ -183,6 +182,10 @@ export async function createWebRtcLink(options) {
|
|
|
183
182
|
const deadline = Date.now() + handshakeTimeoutMs
|
|
184
183
|
while (peerConnection.iceGatheringState !== 'complete' && Date.now() < deadline)
|
|
185
184
|
await new Promise(resolve => setTimeout(resolve, 50))
|
|
185
|
+
if (peerConnection.iceGatheringState !== 'complete') {
|
|
186
|
+
await pipe.close('ice-gathering-timeout')
|
|
187
|
+
throw new Error(`p2p: ice gathering incomplete after ${handshakeTimeoutMs}ms`)
|
|
188
|
+
}
|
|
186
189
|
}
|
|
187
190
|
|
|
188
191
|
/**
|
|
@@ -50,18 +50,12 @@ export function filterIceLocalHostnameCandidate(candidate, RTCIceCandidateCtor,
|
|
|
50
50
|
export function wrapRtcPeerConnectionForIceLocalHostname(BaseRTC, RTCIceCandidate, policy = 'drop') {
|
|
51
51
|
if (policy === 'none') return BaseRTC
|
|
52
52
|
|
|
53
|
-
const baseRoutesIce = !!BaseRTC.prototype.prepareIceCandidateEvent
|
|
54
|
-
|
|
55
53
|
return class IceLocalHostnameFilteredRTCPeerConnection extends BaseRTC {
|
|
56
54
|
/** @type {((event: RTCPeerConnectionIceEvent) => void) | null} */
|
|
57
55
|
#userIceHandler = null
|
|
58
|
-
/** @type {Set<(event: unknown) => void>} */
|
|
59
|
-
#iceListeners = new Set()
|
|
60
|
-
/** 去重:同一次 native 派发可能既走 attribute 又走 listener */
|
|
61
|
-
#lastIceEvent = null
|
|
62
56
|
|
|
63
57
|
/**
|
|
64
|
-
* drop:不派发;rewrite
|
|
58
|
+
* drop:不派发;rewrite:构造仅携带替换 candidate 的派生事件。
|
|
65
59
|
* @param {RTCPeerConnectionIceEvent | { candidate?: unknown }} event 原始 ICE 事件
|
|
66
60
|
* @returns {RTCPeerConnectionIceEvent | { candidate?: unknown } | null} 规范化后的事件;drop 时为 null
|
|
67
61
|
*/
|
|
@@ -69,7 +63,10 @@ export function wrapRtcPeerConnectionForIceLocalHostname(BaseRTC, RTCIceCandidat
|
|
|
69
63
|
if (!event?.candidate) return event
|
|
70
64
|
const filtered = filterIceLocalHostnameCandidate(event.candidate, RTCIceCandidate, policy)
|
|
71
65
|
if (!filtered) return null
|
|
72
|
-
|
|
66
|
+
if (filtered === event.candidate) return event
|
|
67
|
+
const rewritten = new event.constructor('icecandidate')
|
|
68
|
+
rewritten.candidate = filtered
|
|
69
|
+
return rewritten
|
|
73
70
|
}
|
|
74
71
|
|
|
75
72
|
/**
|
|
@@ -77,9 +74,6 @@ export function wrapRtcPeerConnectionForIceLocalHostname(BaseRTC, RTCIceCandidat
|
|
|
77
74
|
*/
|
|
78
75
|
constructor(config) {
|
|
79
76
|
super(config)
|
|
80
|
-
if (baseRoutesIce) return
|
|
81
|
-
|
|
82
|
-
// native EventTarget:在派发前规范化,自管 listener,不依赖 stopImmediatePropagation。
|
|
83
77
|
Object.defineProperty(this, 'onicecandidate', {
|
|
84
78
|
configurable: true,
|
|
85
79
|
enumerable: true,
|
|
@@ -93,48 +87,22 @@ export function wrapRtcPeerConnectionForIceLocalHostname(BaseRTC, RTCIceCandidat
|
|
|
93
87
|
*/
|
|
94
88
|
set: handler => { this.#userIceHandler = handler },
|
|
95
89
|
})
|
|
96
|
-
super.addEventListener('icecandidate', event => this.#deliverIce(event))
|
|
97
90
|
}
|
|
98
91
|
|
|
99
92
|
/**
|
|
100
|
-
*
|
|
101
|
-
*
|
|
93
|
+
* 先完成 candidate 转换,再走标准 EventTarget 派发(保留 once/AbortSignal/capture 语义)。
|
|
94
|
+
* addEventListener / removeEventListener 交由基类,故 once / AbortSignal / capture 均保留。
|
|
95
|
+
* drop:不派发;pass-through:派发原事件;rewrite:派发替换 candidate 后的派生事件。
|
|
96
|
+
* @param {Event} event 待派发事件
|
|
97
|
+
* @returns {boolean} 事件是否未被取消
|
|
102
98
|
*/
|
|
103
|
-
|
|
104
|
-
if (
|
|
105
|
-
this.#lastIceEvent = event
|
|
99
|
+
dispatchEvent(event) {
|
|
100
|
+
if (event?.type !== 'icecandidate') return super.dispatchEvent(event)
|
|
106
101
|
const normalized = this.prepareIceCandidateEvent(event)
|
|
107
|
-
if (normalized == null) return
|
|
102
|
+
if (normalized == null) return true
|
|
108
103
|
this.#userIceHandler?.(normalized)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* @param {string} type 事件名
|
|
114
|
-
* @param {(event: unknown) => void} listener 回调
|
|
115
|
-
* @param {boolean | AddEventListenerOptions} [options] 监听选项
|
|
116
|
-
* @returns {void}
|
|
117
|
-
*/
|
|
118
|
-
addEventListener(type, listener, options) {
|
|
119
|
-
if (!baseRoutesIce && type === 'icecandidate') {
|
|
120
|
-
this.#iceListeners.add(listener)
|
|
121
|
-
return
|
|
122
|
-
}
|
|
123
|
-
return super.addEventListener(type, listener, options)
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* @param {string} type 事件名
|
|
128
|
-
* @param {(event: unknown) => void} listener 回调
|
|
129
|
-
* @param {boolean | EventListenerOptions} [options] 监听选项
|
|
130
|
-
* @returns {void}
|
|
131
|
-
*/
|
|
132
|
-
removeEventListener(type, listener, options) {
|
|
133
|
-
if (!baseRoutesIce && type === 'icecandidate') {
|
|
134
|
-
this.#iceListeners.delete(listener)
|
|
135
|
-
return
|
|
136
|
-
}
|
|
137
|
-
return super.removeEventListener(type, listener, options)
|
|
104
|
+
if (normalized === event) return super.dispatchEvent(event)
|
|
105
|
+
return super.dispatchEvent(normalized)
|
|
138
106
|
}
|
|
139
107
|
}
|
|
140
108
|
}
|
package/link/rtc/polyfill.mjs
CHANGED
|
@@ -4,7 +4,6 @@ import { getRtcPolyfillCacheEpoch, getSignalingRuntimeConfig } from '../../node/
|
|
|
4
4
|
import { nodeDebug } from '../../node/log.mjs'
|
|
5
5
|
|
|
6
6
|
import { wrapRtcPeerConnectionForIceLocalHostname } from './ice_local_hostname.mjs'
|
|
7
|
-
import { bridgePeerConnection } from './w3c_bridge.mjs'
|
|
8
7
|
|
|
9
8
|
/** @type {boolean} */
|
|
10
9
|
let exitCleanupHooked = false
|
|
@@ -20,11 +19,9 @@ let cachedDefaultPolyfillEpoch = -1
|
|
|
20
19
|
* RTCPeerConnection: typeof RTCPeerConnection,
|
|
21
20
|
* RTCIceCandidate: typeof RTCIceCandidate,
|
|
22
21
|
* backend: string,
|
|
23
|
-
* forcesTrickleIce: boolean,
|
|
24
22
|
* }} LoadedRtcPolyfill
|
|
25
23
|
* @typedef {{
|
|
26
24
|
* id: string,
|
|
27
|
-
* forcesTrickleIce?: boolean,
|
|
28
25
|
* load: () => Promise<{ RTCPeerConnection: typeof RTCPeerConnection, RTCIceCandidate: typeof RTCIceCandidate }>,
|
|
29
26
|
* }} RtcBackend
|
|
30
27
|
*/
|
|
@@ -57,12 +54,9 @@ async function ensureNodeDatachannelExitCleanup() {
|
|
|
57
54
|
* @returns {Promise<{ RTCPeerConnection: typeof RTCPeerConnection, RTCIceCandidate: typeof RTCIceCandidate }>} node-datachannel 构造器
|
|
58
55
|
*/
|
|
59
56
|
async function loadNodeDatachannelBackend() {
|
|
60
|
-
const
|
|
57
|
+
const module = await import('node-datachannel/polyfill')
|
|
61
58
|
await ensureNodeDatachannelExitCleanup()
|
|
62
|
-
return
|
|
63
|
-
RTCPeerConnection: mod.RTCPeerConnection,
|
|
64
|
-
RTCIceCandidate: mod.RTCIceCandidate,
|
|
65
|
-
}
|
|
59
|
+
return module
|
|
66
60
|
}
|
|
67
61
|
|
|
68
62
|
/**
|
|
@@ -70,17 +64,12 @@ async function loadNodeDatachannelBackend() {
|
|
|
70
64
|
* @returns {Promise<{ RTCPeerConnection: typeof RTCPeerConnection, RTCIceCandidate: typeof RTCIceCandidate }>} node-rtc-connection 构造器
|
|
71
65
|
*/
|
|
72
66
|
async function loadNodeRtcConnectionBackend() {
|
|
73
|
-
|
|
74
|
-
return {
|
|
75
|
-
RTCPeerConnection: /** @type {typeof RTCPeerConnection} */ bridgePeerConnection(module.RTCPeerConnection),
|
|
76
|
-
RTCIceCandidate: module.RTCIceCandidate,
|
|
77
|
-
}
|
|
67
|
+
return import('node-rtc-connection')
|
|
78
68
|
}
|
|
79
69
|
|
|
80
70
|
/** @type {RtcBackend} */
|
|
81
71
|
const PURE_JS_BACKEND = {
|
|
82
72
|
id: 'node-rtc-connection',
|
|
83
|
-
forcesTrickleIce: true,
|
|
84
73
|
load: loadNodeRtcConnectionBackend,
|
|
85
74
|
}
|
|
86
75
|
|
|
@@ -119,7 +108,6 @@ async function loadNodeRtcPolyfillUncached(options) {
|
|
|
119
108
|
),
|
|
120
109
|
RTCIceCandidate: mod.RTCIceCandidate,
|
|
121
110
|
backend: backend.id,
|
|
122
|
-
forcesTrickleIce: backend.forcesTrickleIce === true,
|
|
123
111
|
}
|
|
124
112
|
}
|
|
125
113
|
catch (error) {
|
package/node/handles.mjs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 节点生命周期内打开的文件流注册表。
|
|
3
|
+
*
|
|
4
|
+
* 文件流(chunk 读流 / 写流)在 Windows 上若未 destroy 会占用文件句柄,
|
|
5
|
+
* 导致节点目录删除失败。这里集中跟踪,`closeNode()` 通过
|
|
6
|
+
* `closeAllFileStreams()` 一次性释放全部仍打开的流。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** @type {Set<import('node:stream').Readable | import('node:stream').Writable>} */
|
|
10
|
+
const streams = new Set()
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 跟踪一个文件流:销毁/关闭/出错时自动从注册表移除。
|
|
14
|
+
* @template {import('node:stream').Readable | import('node:stream').Writable} T
|
|
15
|
+
* @param {T} stream 文件流
|
|
16
|
+
* @returns {T} 原流
|
|
17
|
+
*/
|
|
18
|
+
export function trackFileStream(stream) {
|
|
19
|
+
streams.add(stream)
|
|
20
|
+
/** @returns {void} */
|
|
21
|
+
const forget = () => streams.delete(stream)
|
|
22
|
+
stream.once('close', forget)
|
|
23
|
+
stream.once('error', forget)
|
|
24
|
+
return stream
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 关闭并销毁所有仍在打开的文件流(测试 teardown / 节点关闭)。
|
|
29
|
+
* @returns {Promise<number>} 被销毁的流数量
|
|
30
|
+
*/
|
|
31
|
+
export async function closeAllFileStreams() {
|
|
32
|
+
const targeted = [...streams]
|
|
33
|
+
const pending = []
|
|
34
|
+
for (const stream of targeted) {
|
|
35
|
+
if (!stream.closed)
|
|
36
|
+
pending.push(new Promise(resolve => stream.once('close', resolve)))
|
|
37
|
+
stream.destroy()
|
|
38
|
+
}
|
|
39
|
+
await Promise.all(pending)
|
|
40
|
+
for (const stream of targeted) streams.delete(stream)
|
|
41
|
+
return targeted.length
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @returns {boolean} 是否仍有未释放的文件流(测试断言用)
|
|
46
|
+
*/
|
|
47
|
+
export function hasOpenFileStreams() {
|
|
48
|
+
return streams.size > 0
|
|
49
|
+
}
|
package/node/instance.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import path from 'node:path'
|
|
2
2
|
|
|
3
3
|
import { createFsEntityStore } from './entity_store.mjs'
|
|
4
|
+
import { closeAllFileStreams } from './handles.mjs'
|
|
4
5
|
import { defaultSignalingRuntimeConfig, resolveSignalingRuntimeConfig } from './signaling_config.mjs'
|
|
5
6
|
|
|
6
7
|
/** @typedef {{ warn?: (...args: unknown[]) => void, error?: (...args: unknown[]) => void, info?: (...args: unknown[]) => void, log?: (...args: unknown[]) => void }} NodeLogger */
|
|
@@ -37,7 +38,7 @@ export function getRtcPolyfillCacheEpoch() {
|
|
|
37
38
|
* @returns {NodeRuntime} 初始化后的运行时
|
|
38
39
|
*/
|
|
39
40
|
export function initNode(options) {
|
|
40
|
-
if (runtime) throw new Error('p2p: initNode already called — use setNodeLogger / setSignalingRuntimeConfig or
|
|
41
|
+
if (runtime) throw new Error('p2p: initNode already called — use setNodeLogger / setSignalingRuntimeConfig or closeNode')
|
|
41
42
|
if (options?.logger !== undefined || options?.signaling !== undefined)
|
|
42
43
|
throw new Error('p2p: initNode only accepts nodeDir/entityStore — use setNodeLogger / setSignalingRuntimeConfig')
|
|
43
44
|
const nodeDir = path.resolve(options.nodeDir)
|
|
@@ -138,11 +139,13 @@ export function onNodeChange(listener) {
|
|
|
138
139
|
}
|
|
139
140
|
|
|
140
141
|
/**
|
|
141
|
-
*
|
|
142
|
-
*
|
|
142
|
+
* 关闭节点:释放全部文件句柄(chunk 读/写流等)并清空运行时与监听器。
|
|
143
|
+
* 之后可用 initNode 重新引导。
|
|
144
|
+
* @returns {Promise<void>}
|
|
143
145
|
*/
|
|
144
|
-
export function
|
|
146
|
+
export async function closeNode() {
|
|
145
147
|
runtime = null
|
|
146
148
|
changeListeners.clear()
|
|
147
149
|
rtcPolyfillCacheEpoch++
|
|
150
|
+
await closeAllFileStreams()
|
|
148
151
|
}
|
package/node/reputation_sync.mjs
CHANGED
|
@@ -78,9 +78,7 @@ function normalizeHashList(list) {
|
|
|
78
78
|
.filter(id => isHex64(id)))]
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
-
/**
|
|
82
|
-
* @returns {void}
|
|
83
|
-
*/
|
|
81
|
+
/** 将当前 sync 配置写盘 */
|
|
84
82
|
function persistSyncConfig() {
|
|
85
83
|
writeNodeJsonSync(SYNC_DATA_NAME, loadSyncConfig())
|
|
86
84
|
}
|
|
@@ -304,9 +302,7 @@ export async function pullReputationFromNode(nodeHash) {
|
|
|
304
302
|
return await resultPromise
|
|
305
303
|
}
|
|
306
304
|
|
|
307
|
-
/**
|
|
308
|
-
* @returns {void}
|
|
309
|
-
*/
|
|
305
|
+
/** 重置 sync 运行时(测试用) */
|
|
310
306
|
export function resetReputationSyncForTests() {
|
|
311
307
|
syncConfig = null
|
|
312
308
|
detachReputationSyncWire()
|
package/package.json
CHANGED
|
@@ -99,9 +99,7 @@ export function createGroupLinkSet(options) {
|
|
|
99
99
|
scheduleDial()
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
/**
|
|
103
|
-
* @returns {void}
|
|
104
|
-
*/
|
|
102
|
+
/** 按成员选择目标并拨号 */
|
|
105
103
|
function selectAndDial() {
|
|
106
104
|
if (!autoconnectEnabled || !active) return
|
|
107
105
|
const targets = dialAll
|
|
@@ -119,9 +117,7 @@ export function createGroupLinkSet(options) {
|
|
|
119
117
|
void registry.ensureLinkToNode(nodeHash).catch(() => null)
|
|
120
118
|
}
|
|
121
119
|
|
|
122
|
-
/**
|
|
123
|
-
* @returns {void}
|
|
124
|
-
*/
|
|
120
|
+
/** 延迟调度一次拨号 */
|
|
125
121
|
function scheduleDial() {
|
|
126
122
|
if (!autoconnectEnabled || !active || dialTimer) return
|
|
127
123
|
dialTimer = setTimeout(() => { dialTimer = null; selectAndDial() }, 200)
|
|
@@ -719,9 +719,7 @@ export function configureLinkRegistry(options = {}) {
|
|
|
719
719
|
pendingRegistryOptions = { ...pendingRegistryOptions, ...options }
|
|
720
720
|
}
|
|
721
721
|
|
|
722
|
-
/**
|
|
723
|
-
* @returns {void}
|
|
724
|
-
*/
|
|
722
|
+
/** 重置 link registry 运行时(测试用) */
|
|
725
723
|
export function resetLinkRegistryForTests() {
|
|
726
724
|
defaultRegistry = null
|
|
727
725
|
pendingRegistryOptions = null
|
|
@@ -111,9 +111,7 @@ export function createRuntimeBootstrap(deps) {
|
|
|
111
111
|
?? mergeSignalingRelayUrls(getNodeTransportSettings().relayUrls)
|
|
112
112
|
}
|
|
113
113
|
|
|
114
|
-
/**
|
|
115
|
-
* @returns {void}
|
|
116
|
-
*/
|
|
114
|
+
/** 注册默认 discovery provider(lan/nostr) */
|
|
117
115
|
function registerDiscoveryDefaults() {
|
|
118
116
|
const providerIds = new Set(listDiscoveryProviders().map(provider => provider.id))
|
|
119
117
|
if (!providerIds.has('lan'))
|
|
@@ -124,9 +122,7 @@ export function createRuntimeBootstrap(deps) {
|
|
|
124
122
|
registerNostrProvider()
|
|
125
123
|
}
|
|
126
124
|
|
|
127
|
-
/**
|
|
128
|
-
* @returns {void}
|
|
129
|
-
*/
|
|
125
|
+
/** 注册/替换 nostr discovery provider */
|
|
130
126
|
function registerNostrProvider() {
|
|
131
127
|
unregisterDiscoveryProvider('nostr')
|
|
132
128
|
registerDiscoveryProvider(createNostrDiscoveryProvider({
|
package/utils/async_mutex.mjs
CHANGED
|
@@ -42,9 +42,7 @@ export async function withAsyncMutex(key, criticalSection) {
|
|
|
42
42
|
const lockKey = key
|
|
43
43
|
const state = mutexState(lockKey)
|
|
44
44
|
return new Promise((resolve, reject) => {
|
|
45
|
-
/**
|
|
46
|
-
* @returns {void}
|
|
47
|
-
*/
|
|
45
|
+
/** 执行临界区并最终释放锁 */
|
|
48
46
|
const run = () => {
|
|
49
47
|
Promise.resolve()
|
|
50
48
|
.then(criticalSection)
|
package/utils/ttl_map.mjs
CHANGED
package/link/rtc/w3c_bridge.mjs
DELETED
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 把 EventEmitter 风格的 RTC(如 node-rtc-connection)桥成 W3C 属性 handler。
|
|
3
|
-
* 其余链路只认 onicecandidate / onmessage / onbufferedamountlow 等。
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
/** @type {WeakSet<object>} */
|
|
7
|
-
const bridgedChannels = new WeakSet()
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* @param {object} target EventEmitter 目标
|
|
11
|
-
* @param {string} property W3C 属性名(如 onmessage)
|
|
12
|
-
* @param {string} eventName EventEmitter 事件名
|
|
13
|
-
* @param {(payload: unknown) => unknown} [adapt] 事件载荷适配
|
|
14
|
-
* @returns {void}
|
|
15
|
-
*/
|
|
16
|
-
function defineEmitterHandler(target, property, eventName, adapt = payload => payload) {
|
|
17
|
-
let handler = null
|
|
18
|
-
target.on(eventName, payload => handler?.(adapt(payload)))
|
|
19
|
-
Object.defineProperty(target, property, {
|
|
20
|
-
configurable: true,
|
|
21
|
-
enumerable: true,
|
|
22
|
-
/**
|
|
23
|
-
* @returns {((payload: unknown) => void) | null} 当前 handler
|
|
24
|
-
*/
|
|
25
|
-
get: () => handler,
|
|
26
|
-
/**
|
|
27
|
-
* @param {((payload: unknown) => void) | null} value 新 handler
|
|
28
|
-
* @returns {void}
|
|
29
|
-
*/
|
|
30
|
-
set: value => { handler = value },
|
|
31
|
-
})
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* @param {RTCDataChannel} channel 原始 data channel
|
|
36
|
-
* @returns {RTCDataChannel} 已挂 W3C handler 的通道
|
|
37
|
-
*/
|
|
38
|
-
export function bridgeDataChannel(channel) {
|
|
39
|
-
if (bridgedChannels.has(channel) || !channel.on) return channel
|
|
40
|
-
bridgedChannels.add(channel)
|
|
41
|
-
defineEmitterHandler(channel, 'onmessage', 'message')
|
|
42
|
-
defineEmitterHandler(channel, 'onopen', 'open')
|
|
43
|
-
defineEmitterHandler(channel, 'onclose', 'close')
|
|
44
|
-
defineEmitterHandler(channel, 'onbufferedamountlow', 'bufferedamountlow')
|
|
45
|
-
return channel
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* @param {typeof RTCPeerConnection} BaseRTC EventEmitter 风格 RTCPeerConnection
|
|
50
|
-
* @returns {typeof RTCPeerConnection} W3C handler 版
|
|
51
|
-
*/
|
|
52
|
-
export function bridgePeerConnection(BaseRTC) {
|
|
53
|
-
return class W3cRtcPeerConnection extends BaseRTC {
|
|
54
|
-
/** @type {((event: RTCPeerConnectionIceEvent) => void) | null} */
|
|
55
|
-
#iceHandler = null
|
|
56
|
-
/** @type {((event: { channel: RTCDataChannel }) => void) | null} */
|
|
57
|
-
#dataChannelHandler = null
|
|
58
|
-
/** @type {(() => void) | null} */
|
|
59
|
-
#connectionStateHandler = null
|
|
60
|
-
/** @type {Map<string, Set<(event: unknown) => void>>} */
|
|
61
|
-
#listeners = new Map()
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* @param {RTCConfiguration} [config] RTC 配置
|
|
65
|
-
*/
|
|
66
|
-
constructor(config) {
|
|
67
|
-
super(config)
|
|
68
|
-
super.on('icecandidate', event => {
|
|
69
|
-
const normalized = this.prepareIceCandidateEvent(event)
|
|
70
|
-
if (normalized == null) return
|
|
71
|
-
this.#iceHandler?.(normalized)
|
|
72
|
-
this.#emit('icecandidate', normalized)
|
|
73
|
-
})
|
|
74
|
-
super.on('datachannel', event => {
|
|
75
|
-
const adapted = { channel: bridgeDataChannel(event.channel) }
|
|
76
|
-
this.#dataChannelHandler?.(adapted)
|
|
77
|
-
this.#emit('datachannel', adapted)
|
|
78
|
-
})
|
|
79
|
-
super.on('connectionstatechange', () => {
|
|
80
|
-
this.#connectionStateHandler?.()
|
|
81
|
-
this.#emit('connectionstatechange', undefined)
|
|
82
|
-
})
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/**
|
|
86
|
-
* ICE 事件规范化钩子;子类可覆盖(drop 返回 null,rewrite 返回替换后的事件)。
|
|
87
|
-
* @param {RTCPeerConnectionIceEvent | { candidate?: unknown }} event 原始 ICE 事件
|
|
88
|
-
* @returns {RTCPeerConnectionIceEvent | { candidate?: unknown } | null} 规范化后的事件
|
|
89
|
-
*/
|
|
90
|
-
prepareIceCandidateEvent(event) {
|
|
91
|
-
return event
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/**
|
|
95
|
-
* @param {string} type 事件名
|
|
96
|
-
* @param {unknown} event 事件载荷(icecandidate 须已规范化)
|
|
97
|
-
* @returns {void}
|
|
98
|
-
*/
|
|
99
|
-
#emit(type, event) {
|
|
100
|
-
const listeners = this.#listeners.get(type)
|
|
101
|
-
if (!listeners) return
|
|
102
|
-
for (const listener of listeners) listener(event)
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
* @param {string} type 事件名
|
|
107
|
-
* @param {(event: unknown) => void} listener 回调
|
|
108
|
-
* @returns {void}
|
|
109
|
-
*/
|
|
110
|
-
addEventListener(type, listener) {
|
|
111
|
-
let listeners = this.#listeners.get(type)
|
|
112
|
-
if (!listeners) {
|
|
113
|
-
listeners = new Set()
|
|
114
|
-
this.#listeners.set(type, listeners)
|
|
115
|
-
}
|
|
116
|
-
listeners.add(listener)
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* @param {string} type 事件名
|
|
121
|
-
* @param {(event: unknown) => void} listener 回调
|
|
122
|
-
* @returns {void}
|
|
123
|
-
*/
|
|
124
|
-
removeEventListener(type, listener) {
|
|
125
|
-
this.#listeners.get(type)?.delete(listener)
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** @returns {((event: RTCPeerConnectionIceEvent) => void) | null} ICE candidate handler */
|
|
129
|
-
get onicecandidate() { return this.#iceHandler }
|
|
130
|
-
/** @param {((event: RTCPeerConnectionIceEvent) => void) | null} handler ICE candidate handler */
|
|
131
|
-
set onicecandidate(handler) { this.#iceHandler = handler }
|
|
132
|
-
|
|
133
|
-
/** @returns {((event: { channel: RTCDataChannel }) => void) | null} data channel handler */
|
|
134
|
-
get ondatachannel() { return this.#dataChannelHandler }
|
|
135
|
-
/** @param {((event: { channel: RTCDataChannel }) => void) | null} handler data channel handler */
|
|
136
|
-
set ondatachannel(handler) { this.#dataChannelHandler = handler }
|
|
137
|
-
|
|
138
|
-
/** @returns {(() => void) | null} connection state handler */
|
|
139
|
-
get onconnectionstatechange() { return this.#connectionStateHandler }
|
|
140
|
-
/** @param {(() => void) | null} handler connection state handler */
|
|
141
|
-
set onconnectionstatechange(handler) { this.#connectionStateHandler = handler }
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* @param {string} label data channel 标签
|
|
145
|
-
* @param {RTCDataChannelInit} [init] 创建选项
|
|
146
|
-
* @returns {RTCDataChannel} 已桥接 W3C handler 的通道
|
|
147
|
-
*/
|
|
148
|
-
createDataChannel(label, init) {
|
|
149
|
-
return bridgeDataChannel(super.createDataChannel(label, init))
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|