@libp2p/memory 0.0.0-665769021

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/src/memory.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { ConnectionFailedError, serviceCapabilities, transportSymbol } from '@libp2p/interface'
2
+ import { Memory } from '@multiformats/multiaddr-matcher'
3
+ import { connections } from './connections.js'
4
+ import { MemoryTransportListener } from './listener.js'
5
+ import type { MemoryTransportComponents, MemoryTransportInit } from './index.js'
6
+ import type { Connection, Transport, Listener, CreateListenerOptions, DialTransportOptions } from '@libp2p/interface'
7
+ import type { Multiaddr } from '@multiformats/multiaddr'
8
+
9
+ export class MemoryTransport implements Transport {
10
+ private readonly components: MemoryTransportComponents
11
+ private readonly init: MemoryTransportInit
12
+
13
+ constructor (components: MemoryTransportComponents, init: MemoryTransportInit = {}) {
14
+ this.components = components
15
+ this.init = init
16
+ }
17
+
18
+ readonly [transportSymbol] = true
19
+
20
+ readonly [Symbol.toStringTag] = '@libp2p/memory'
21
+
22
+ readonly [serviceCapabilities]: string[] = [
23
+ '@libp2p/transport'
24
+ ]
25
+
26
+ async dial (ma: Multiaddr, options: DialTransportOptions): Promise<Connection> {
27
+ options.signal?.throwIfAborted()
28
+
29
+ const memoryConnection = connections.get(`${ma.getPeerId() == null ? ma : ma.decapsulate('/p2p')}`)
30
+
31
+ if (memoryConnection == null) {
32
+ throw new ConnectionFailedError(`No memory listener found at ${ma}`)
33
+ }
34
+
35
+ const maConn = await memoryConnection.dial(this.components.peerId)
36
+
37
+ try {
38
+ options.signal?.throwIfAborted()
39
+
40
+ return await options.upgrader.upgradeOutbound(maConn, {
41
+ ...options,
42
+ ...this.init.upgraderOptions
43
+ })
44
+ } catch (err: any) {
45
+ maConn.abort(err)
46
+ throw err
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Creates a TCP listener. The provided `handler` function will be called
52
+ * anytime a new incoming Connection has been successfully upgraded via
53
+ * `upgrader.upgradeInbound`.
54
+ */
55
+ createListener (options: CreateListenerOptions): Listener {
56
+ return new MemoryTransportListener(this.components, {
57
+ ...options,
58
+ ...this.init
59
+ })
60
+ }
61
+
62
+ listenFilter (multiaddrs: Multiaddr[]): Multiaddr[] {
63
+ return multiaddrs.filter(ma => Memory.exactMatch(ma))
64
+ }
65
+
66
+ dialFilter (multiaddrs: Multiaddr[]): Multiaddr[] {
67
+ return this.listenFilter(multiaddrs)
68
+ }
69
+ }