-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport.ts
55 lines (44 loc) · 1.32 KB
/
transport.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
import { Digest, Diff } from './node.ts'
import { Address } from './common.ts'
export type { Address }
type NodeDiff = [Digest, Diff[], Address?]
export enum MessageType { NUL, SYN, ACK }
export type Message = [MessageType, Digest[], NodeDiff[]]
type AddressedMessage = [Address, Message]
export interface Transport {
local(): Address
roots(): Address[]
send(to: Address, data: Message): void
recv(): AsyncGenerator<AddressedMessage>
stop(): void
}
export type TransportConfig = {
local: Address,
roots: Address[],
}
export abstract class ConfiguredTransport implements Transport {
constructor(private config: TransportConfig) {}
local() { return this.config.local }
roots() { return this.config.roots }
// Implemented by subclasses
send(_to: Address, _data: Message) {}
async *recv(): AsyncGenerator<AddressedMessage> {}
stop() {}
}
import Queue from './queue.ts'
const NULL = '\x00h' as Address
export abstract class QueuedTransport extends ConfiguredTransport {
private messages = new Queue<AddressedMessage>
push(entry: AddressedMessage) {
this.messages.push(entry)
}
async *recv(): AsyncGenerator<AddressedMessage> {
for await (const entry of this.messages) {
if (entry[0] === NULL) break
yield entry
}
}
stop() {
this.push([NULL, [MessageType.NUL, [], []]])
}
}