mirror of
https://github.com/pezkuwichain/pezkuwi-telemetry.git
synced 2026-06-09 20:21:01 +00:00
Introducing opaque types
This commit is contained in:
+8
-3
@@ -1,21 +1,26 @@
|
||||
import * as EventEmitter from 'events';
|
||||
import Node from './node';
|
||||
import { NodeId } from './nodeId';
|
||||
|
||||
export default class Aggregator extends EventEmitter {
|
||||
private nodes: WeakSet<Node> = new WeakSet;
|
||||
private nodes: Map<NodeId, Node> = new Map;
|
||||
private height: number = 0;
|
||||
|
||||
add(node: Node) {
|
||||
this.nodes.add(node);
|
||||
this.nodes.set(node.id, node);
|
||||
node.once('disconnect', () => {
|
||||
node.removeAllListeners('block');
|
||||
|
||||
this.nodes.delete(node);
|
||||
this.nodes.delete(node.id);
|
||||
});
|
||||
|
||||
node.on('block', () => this.updateBlock(node));
|
||||
}
|
||||
|
||||
get nodeList(): Iterable<Node> {
|
||||
return this.nodes.values();
|
||||
}
|
||||
|
||||
private updateBlock(node: Node) {
|
||||
if (node.height > this.height) {
|
||||
this.height = node.height;
|
||||
|
||||
+3
-4
@@ -1,14 +1,13 @@
|
||||
import * as WebSocket from 'ws';
|
||||
import * as EventEmitter from 'events';
|
||||
import { Maybe } from './maybe';
|
||||
import { NodeId, getId } from './nodeId';
|
||||
import { parseMessage, getBestBlock, Message, BestBlock } from './message';
|
||||
|
||||
const BLOCK_TIME_HISTORY = 10;
|
||||
|
||||
let idDispenser = 0;
|
||||
|
||||
export default class Node extends EventEmitter {
|
||||
public id: number;
|
||||
public id: NodeId;
|
||||
public name: string;
|
||||
public implementation: string;
|
||||
public version: string;
|
||||
@@ -24,7 +23,7 @@ export default class Node extends EventEmitter {
|
||||
constructor(socket: WebSocket, name: string, config: string, implentation: string, version: string) {
|
||||
super();
|
||||
|
||||
this.id = idDispenser++;
|
||||
this.id = getId();
|
||||
this.socket = socket;
|
||||
this.name = name;
|
||||
this.config = config;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Opaque } from './opaque';
|
||||
|
||||
let currentId = 0;
|
||||
|
||||
export type NodeId = Opaque<number, "NodeId">;
|
||||
|
||||
export function getId(): NodeId {
|
||||
return currentId++ as NodeId;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// Hack for Opaque Types
|
||||
export type Opaque<T, Label> = T & {__TYPE__: Label};
|
||||
Reference in New Issue
Block a user