Commit 583de7b7 authored by nanamicat's avatar nanamicat

rust

parent 126e1439
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
/.idea/
/import/
/target/
\ No newline at end of file
{
"printWidth": 140,
"singleQuote": true
}
{
"udp_bind": "[::]:500",
"http_bind": "[::]:80"
}
\ No newline at end of file
/import/
/target/
/.idea/
\ No newline at end of file
{
"port": 500,
"timeout": 10,
"timeout2": 100,
"interval": 1000,
"throttle": 10
}
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support
# You can see what browsers were selected by your queries by running:
# npx browserslist
last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "pwa-chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}
# RailgunDashboard
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 14.1.3.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"railgun-dashboard": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/railgun-dashboard",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "railgun-dashboard:build:production"
},
"development": {
"browserTarget": "railgun-dashboard:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "railgun-dashboard:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
}
}
}
}
},
"cli": {
"analytics": "290a382f-00ee-4f44-8a2c-21d811baedb5"
}
}
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/railgun-dashboard'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
This diff is collapsed.
{
"name": "railgun-dashboard",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^14.1.0",
"@angular/cdk": "^14.1.2",
"@angular/common": "^14.1.0",
"@angular/compiler": "^14.1.0",
"@angular/core": "^14.1.0",
"@angular/forms": "^14.1.0",
"@angular/material": "^14.1.2",
"@angular/platform-browser": "^14.1.0",
"@angular/platform-browser-dynamic": "^14.1.0",
"@angular/router": "^14.1.0",
"@types/lodash-es": "^4.17.6",
"country-code-emoji": "^2.3.0",
"lodash-es": "^4.17.21",
"rxjs": "~7.5.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^14.1.3",
"@angular/cli": "~14.1.3",
"@angular/compiler-cli": "^14.1.0",
"@types/jasmine": "~4.0.0",
"jasmine-core": "~4.2.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~4.7.2"
}
}
import { PeerQuality } from './api.service';
export class Quality {
static unreachable = new Quality(0, 0, 0, 0);
constructor(public delay = 0, public jitter = 0, public reliability = 1, public cost = 0, public hop = 0) {
}
concat(delay: number, jitter: number, reliability: number, cost: number, hop: number): Quality {
this.delay += delay;
this.jitter += jitter;
this.reliability *= reliability;
this.cost += cost;
this.hop += hop;
return this;
}
concatPeer(quality?: PeerQuality): Quality {
if (!quality) return this.concatQuality(Quality.unreachable);
return this.concat(quality.delay, quality.jitter, quality.reliability, 0, 1);
}
concatQuality(quality: Quality): Quality {
return this.concat(quality.delay, quality.jitter, quality.reliability, quality.cost, quality.hop);
}
// 若 reliability = 0,metric 应为 +∞
// 对于两条路线,同时连接任何一个相同的(reliability > 0的)线路,大小关系不变
metric() {
// assert(this.jitter >= 0);
// assert(0 <= this.reliability && this.reliability <= 1);
// assert(this.cost >= 0);
if (this.reliability === 0) {
return Infinity;
} else {
// 公式
return this.delay + (1 - this.reliability) * 1000 + this.cost * 0.1;
}
}
}
import { TestBed } from '@angular/core/testing';
import { ApiService } from './api.service';
describe('ApiService', () => {
let service: ApiService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ApiService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom, mergeMap, timer } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ApiService {
routers!: any[];
connections!: Record<number, Record<number, Connection>>;
constructor(private http: HttpClient) {
}
async init() {
this.connections = await firstValueFrom(this.http.get<Record<number, Record<number, Connection>>>('http://10.198.0.49:500/api/connections'));
this.routers = await firstValueFrom(this.http.get<RouterStatus[]>('http://10.198.0.49:500/api/routers'));
console.log(
this.routers
.map((item) =>
Object.entries({
Host: item.name,
HostName: item.host,
User: item.user,
Port: item.sshPort === 22 ? undefined : item.sshPort
})
.filter(([key, value]) => value)
.map((line) => line.join(' '))
.join('\n')
)
.join('\n\n')
);
}
state() {
return timer(0, 1000).pipe(
mergeMap(() => this.http.get<RouterStatus[]>('http://10.198.0.49:500/api/state'))
// map((routers) => routers.map(r => ));
);
}
}
export interface RouterStatus {
id: number,
peers: Record<number, PeerQuality>,
via: Record<number, number>
}
export interface PeerQuality {
delay: number;
jitter: number;
reliability: number;
}
export interface Router {
id: number;
name: string;
location: string;
host: string;
port: number;
user: string;
}
export interface Connection {
metric: number;
protocol: string;
}
// const connected: Record<number, Record<number, string>> = {};
// for (const from of data) {
// if (!connected[from.id]) connected[from.id] = {}
// for (const to of data) {
// // @ts-ignore
// if (from[to.name] !== "") {
// const [min, max] = [from.id, to.id].sort();
// // @ts-ignore
// connected[min][max] = from[to.name];
// }
// }
// }
import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {DashboardComponent} from "./dashboard/dashboard.component";
import {RouterComponent} from "./router/router.component";
const routes: Routes = [
{path: '', component: DashboardComponent},
{path: ':id', component: RouterComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
<mat-toolbar color='primary'>Menu</mat-toolbar>
<div id='wrapper' *ngIf='api.routers'>
<mat-nav-list>
<a mat-list-item routerLink=''>总览</a>
<a mat-list-item [routerLink]='router.id.toString()' *ngFor='let router of api.routers'>{{router.name}}</a>
</mat-nav-list>
<router-outlet></router-outlet>
</div>
<!--<router-outlet></router-outlet>-->
:host {
height: 100%;
display: flex;
flex-direction: column;
}
mat-toolbar {
flex-shrink: 0;
}
#wrapper {
display: flex;
overflow: hidden;
> mat-nav-list {
width: 300px;
flex-shrink: 0;
overflow-y: auto;
}
}
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'railgun-dashboard'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('railgun-dashboard');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('railgun-dashboard app is running!');
});
});
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
import * as _ from 'lodash';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(public api: ApiService) {
}
async ngOnInit() {
await this.api.init();
// const protos = [];
// for (const from of this.api.routers) {
// for (const [id1, peer] of Object.entries(from.peers)) {
// const id = parseInt(id1);
// const reverse = this.api.routers.find(r => r.id === id)?.peers?.[from.id];
// if (!reverse) continue;
// const link = this.api.connections[from.id][id];
// if (!link) continue;
// // @ts-ignore
// if (peer.reliability * reverse.reliability <= 0.01) {
// protos.push(link.proto);
// }
// }
// }
// console.log(_.groupBy(protos));
}
}
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatTableModule} from "@angular/material/table";
import {NavComponent} from './nav/nav.component';
import {LayoutModule} from '@angular/cdk/layout';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatButtonModule} from '@angular/material/button';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatIconModule} from '@angular/material/icon';
import {MatListModule} from '@angular/material/list';
import {DashboardComponent} from './dashboard/dashboard.component';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatCardModule} from '@angular/material/card';
import {MatMenuModule} from '@angular/material/menu';
import {RouterComponent} from "./router/router.component";
import {HttpClientModule} from "@angular/common/http";
import { TestComponent } from './test/test.component';
import {MatSlideToggleModule} from "@angular/material/slide-toggle";
import {FormsModule} from "@angular/forms";
@NgModule({
declarations: [
AppComponent,
NavComponent,
DashboardComponent,
RouterComponent,
TestComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatTableModule,
LayoutModule,
MatToolbarModule,
MatButtonModule,
MatSidenavModule,
MatIconModule,
MatListModule,
MatGridListModule,
MatCardModule,
MatMenuModule,
HttpClientModule,
MatSlideToggleModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
<h1 class='mat-h1'>Dashboard</h1>
<mat-card class='mat-elevation-z8'>
<mat-card-header>
<mat-card-title>
<span>直接相邻链路</span>
<mat-slide-toggle [(ngModel)]='routed'>路由后</mat-slide-toggle>
<button mat-icon-button class='more-button' [matMenuTriggerFor]='menu' aria-label='Toggle menu'>
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu='matMenu' xPosition='before'>
<button mat-menu-item>Expand</button>
<button mat-menu-item>Remove</button>
</mat-menu>
</mat-card-title>
</mat-card-header>
<mat-card-content>
<table mat-table [dataSource]='links' *ngIf='api.routers' fixedLayout [trackBy]='trackById'>
<ng-container matColumnDef='name'>
<th mat-header-cell *matHeaderCellDef>name</th>
<td mat-cell *matCellDef='let element'> {{element.name}} </td>
</ng-container>
<ng-container matColumnDef='id'>
<th mat-header-cell *matHeaderCellDef>id</th>
<td mat-cell *matCellDef='let element'> {{element.id}} </td>
</ng-container>
<ng-container *ngFor='let router of api.routers'>
<ng-container [matColumnDef]='router.name'>
<th mat-header-cell *matHeaderCellDef><span class='id'>{{router.id}}</span><span
class='head'>{{router.name}}</span></th>
<td mat-cell *matCellDef='let element'
[style.color]='element.peers[router.id]?.color'
[style.text-decoration]='element.peers[router.id]?.decoration'
> {{element.peers[router.id]?.delay}}<sup>{{element.peers[router.id]?.protocol}}</sup></td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef='displayedColumns'></tr>
<tr mat-row *matRowDef='let row; columns: displayedColumns;'></tr>
</table>
</mat-card-content>
</mat-card>
<!--<h2>直接相邻链路</h2>-->
<!--<mat-card class="mat-elevation-z8">-->
<!-- <table mat-table [dataSource]="links" *ngIf="routers" fixedLayout [trackBy]="trackById">-->
<!-- <ng-container matColumnDef="name">-->
<!-- <th mat-header-cell *matHeaderCellDef></th>-->
<!-- <td mat-cell *matCellDef="let element"> {{element.name}} </td>-->
<!-- </ng-container>-->
<!-- <ng-container *ngFor="let router of routers">-->
<!-- <ng-container [matColumnDef]="router.name">-->
<!-- <th mat-header-cell *matHeaderCellDef><span class="head">{{router.name}}</span></th>-->
<!-- <td mat-cell *matCellDef="let element"-->
<!-- [style.color]="element.peers[router.id]?.color"> {{element.peers[router.id]?.delay}} </td>-->
<!-- </ng-container>-->
<!-- </ng-container>-->
<!-- <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>-->
<!-- <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>-->
<!-- </table>-->
<!--</mat-card>-->
:host {
flex: 1;
overflow: auto;
padding: 20px;
}
mat-card {
width: 100%;
//max-height: 400px;
overflow: auto;
box-sizing: border-box;
background: initial;
.more-button {
position: absolute;
top: 5px;
right: 10px;
}
table {
text-align: right;
border-spacing: 0;
border-collapse: collapse;
background: initial;
overflow: hidden;
z-index: 1;
min-width: 100%;
white-space: nowrap;
::ng-deep thead {
height: 80px;
vertical-align: bottom;
}
tr {
height: 24px;
&:hover {
background: whitesmoke;
}
th, td {
padding: 0 8px;
position: relative;
width: 8px;
}
}
td:hover::after, th:hover::after {
background-color: whitesmoke;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
border-left: 1px solid rgba(0, 0, 0, .12);
border-right: 1px solid rgba(0, 0, 0, .12);
}
}
}
.id {
transform: translateX(10px);
display: inline-block;
}
.head {
display: inline-block;
text-align: left;
transform: rotate(-60deg);
transform-origin: left top;
width: 8px;
padding-left: 4px;
}
.oc {
text-decoration: underline blue;
}
.wg {
text-decoration: underline red;
}
.tun {
text-decoration: underline green;
}
import { LayoutModule } from '@angular/cdk/layout';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { DashboardComponent } from './dashboard.component';
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [DashboardComponent],
imports: [
NoopAnimationsModule,
LayoutModule,
MatButtonModule,
MatCardModule,
MatGridListModule,
MatIconModule,
MatMenuModule,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DashboardComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { ApiService, RouterStatus } from '../api.service';
import * as _ from 'lodash-es';
import { Quality } from '../Quality';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
// changeDetection: ChangeDetectionStrategy.OnPush
})
export class DashboardComponent implements OnInit {
// routers: RouterStatus[] = [];
displayedColumns: string[] = [];
links = this.api.state().pipe(
map(routers => routers.map(router =>
({
id: router.id,
name: this.api.routers.find(r => r.id == router.id)!.name,
peers: _.mapValues(router.peers, (quality, id1) => this.displayQuality(routers, router, parseInt(id1)))
})
))
);
routed = false;
constructor(public api: ApiService) {
}
displayQuality(routers: RouterStatus[], from: RouterStatus, toId: number) {
const to = routers.find(r => r.id === toId);
if (!to) return;
const quality = new Quality();
if (this.routed) {
quality
.concatQuality(this.calculate(routers, from, to))
.concatQuality(this.calculate(routers, to, from));
return {
delay: quality.reliability <= 0.01 ? 'x' : quality.delay,
color: `hsl(${this.mapNumber(quality.reliability, 0.9, 1, 0, 120)}, 100%, 40%)`,
decoration: quality.hop <= 2 ? '' : `underline hsl(${this.mapNumber(quality.hop, 4, 8, 120, 0)}, 100%, 40%)`
};
} else {
const link = this.api.connections[from.id]?.[toId];
if (!link) return;
if (!to.peers[from.id]) return;
quality
.concatPeer(from.peers[toId])
.concatPeer(to.peers[from.id]);
const decorations: Record<string, string> = {
oc: 'underline blue',
wg: 'underline red',
tun: 'underline green'
};
return {
delay: quality.reliability <= 0.01 ? 'x' : quality.delay,
color: `hsl(${this.mapNumber(quality.reliability, 0.9, 1, 0, 120)}, 100%, 40%)`,
// decoration: decorations[link.protocol],
protocol: link.protocol.slice(0, 1)
};
}
}
mapNumber(value: number, minFrom: number, maxFrom: number, minTo: number, maxTo: number) {
return minTo + (maxTo - minTo) * ((_.clamp(value, minFrom, maxFrom) - minFrom) / (maxFrom - minFrom));
}
async ngOnInit() {
this.displayedColumns = ['name', 'id'].concat(this.api.routers.map(r => r.name));
}
trackById(index: number, item: any) {
return index;
}
/** Based on the screen size, switch from standard to one column per row */
private calculate(routers: RouterStatus[], from: RouterStatus, to: RouterStatus): Quality {
const result = new Quality();
let current = from;
while (current !== to) {
const next = routers.find(r => r.id == current.via[to.id])!;
result.concatPeer(next.peers[current.id]);
current = next;
}
return result;
}
}
.sidenav-container {
height: 100%;
}
.sidenav {
width: 200px;
}
.sidenav .mat-toolbar {
background: inherit;
}
.mat-toolbar.mat-primary {
position: sticky;
top: 0;
z-index: 1;
}
import { LayoutModule } from '@angular/cdk/layout';
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatToolbarModule } from '@angular/material/toolbar';
import { NavComponent } from './nav.component';
describe('NavComponent', () => {
let component: NavComponent;
let fixture: ComponentFixture<NavComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [NavComponent],
imports: [
NoopAnimationsModule,
LayoutModule,
MatButtonModule,
MatIconModule,
MatListModule,
MatSidenavModule,
MatToolbarModule,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NavComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
import { Component } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.scss']
})
export class NavComponent {
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches),
shareReplay()
);
constructor(private breakpointObserver: BreakpointObserver) {}
}
<h1 class="mat-h1">Dashboard</h1>
<h2>{{id|async}} 的直接相邻链路</h2>
<mat-card class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" fixedLayout>
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef>#</th>
<td mat-cell *matCellDef="let element"> {{element?.id}} </td>
</ng-container>
<ng-container matColumnDef="delay">
<th mat-header-cell *matHeaderCellDef>延迟 (RTT)</th>
<td mat-cell *matCellDef="let element"> {{element?.delay}} ms</td>
</ng-container>
<ng-container matColumnDef="loss">
<th mat-header-cell *matHeaderCellDef>丢包 (#>{{id|async}})</th>
<td mat-cell *matCellDef="let element"> {{element?.loss | percent:'1.0-2'}} </td>
</ng-container>
<ng-container matColumnDef="loss2">
<th mat-header-cell *matHeaderCellDef>丢包 ({{id|async}}>#)</th>
<td mat-cell *matCellDef="let element"> {{element?.loss2 | percent:'1.0-2'}} </td>
</ng-container>
<ng-container matColumnDef="jitter">
<th mat-header-cell *matHeaderCellDef>抖动</th>
<td mat-cell *matCellDef="let element"> {{element?.jitter}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</mat-card>
:host {
flex: 1;
overflow: auto;
padding: 20px;
}
mat-card {
width: 100%;
//max-height: 400px;
overflow: auto;
box-sizing: border-box;
table {
//text-align: right;
border-spacing: 0;
border-collapse: collapse;
background: initial;
overflow: hidden;
z-index: 1;
min-width: 100%;
tr {
height: 32px;
&:hover {
background: whitesmoke;
}
th, td {
padding: 0 8px;
position: relative;
text-align: right;
}
th:first-child, td:first-child{
width: 24px;
}
}
td:hover::after {
background-color: whitesmoke;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
}
}
import { LayoutModule } from '@angular/cdk/layout';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { RouterComponent } from './router.component';
describe('DashboardComponent', () => {
let component: RouterComponent;
let fixture: ComponentFixture<RouterComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [RouterComponent],
imports: [
NoopAnimationsModule,
LayoutModule,
MatButtonModule,
MatCardModule,
MatGridListModule,
MatIconModule,
MatMenuModule,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(RouterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
import {Component} from '@angular/core';
import {map, switchMap} from 'rxjs/operators';
import {ApiService, PeerQuality} from "../api.service";
import {ActivatedRoute} from "@angular/router";
@Component({
selector: 'app-dashboard',
templateUrl: './router.component.html',
styleUrls: ['./router.component.scss']
})
export class RouterComponent {
id = this.route.params.pipe(map(params => <number>params['id']));
displayedColumns: string[] = ['id', 'delay', 'loss', 'loss2', 'jitter'];
dataSource = this.id.pipe(
switchMap(id => this.api.state().pipe(
map(routers =>
Object.entries(routers.find(r => r.id == id)!.peers).map(([id1, peer]) => {
const peerId = parseInt(id1);
const reverse = routers.find(r => r.id === peerId)?.peers?.[id];
if (!reverse) return undefined;
return this.displayQuality(peerId, peer, reverse)
})
))));
/** Based on the screen size, switch from standard to one column per row */
constructor(private api: ApiService, private route: ActivatedRoute) {
}
displayQuality(id: number, inbound: PeerQuality, outbound: PeerQuality) {
return {
id,
delay: inbound.delay + outbound.delay,
loss: 1 - inbound.reliability,
loss2: 1 - outbound.reliability,
jitter: inbound.jitter + outbound.jitter
};
}
}
<div class="grid-container">
<h1 class="mat-h1">Dashboard</h1>
<mat-grid-list cols="2" rowHeight="350px">
<mat-grid-tile *ngFor="let card of cards | async" [colspan]="card.cols" [rowspan]="card.rows">
<mat-card class="dashboard-card">
<mat-card-header>
<mat-card-title>
{{card.title}}
<button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu" xPosition="before">
<button mat-menu-item>Expand</button>
<button mat-menu-item>Remove</button>
</mat-menu>
</mat-card-title>
</mat-card-header>
<mat-card-content class="dashboard-card-content">
<div>Card Content Here</div>
</mat-card-content>
</mat-card>
</mat-grid-tile>
</mat-grid-list>
</div>
.grid-container {
margin: 20px;
}
.dashboard-card {
position: absolute;
top: 15px;
left: 15px;
right: 15px;
bottom: 15px;
}
.more-button {
position: absolute;
top: 5px;
right: 10px;
}
.dashboard-card-content {
text-align: center;
}
import { LayoutModule } from '@angular/cdk/layout';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { TestComponent } from './test.component';
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [
NoopAnimationsModule,
LayoutModule,
MatButtonModule,
MatCardModule,
MatGridListModule,
MatIconModule,
MatMenuModule,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
import { Component } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent {
/** Based on the screen size, switch from standard to one column per row */
cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
map(({ matches }) => {
if (matches) {
return [
{ title: 'Card 1', cols: 1, rows: 1 },
{ title: 'Card 2', cols: 1, rows: 1 },
{ title: 'Card 3', cols: 1, rows: 1 },
{ title: 'Card 4', cols: 1, rows: 1 }
];
}
return [
{ title: 'Card 1', cols: 2, rows: 1 },
{ title: 'Card 2', cols: 1, rows: 1 },
{ title: 'Card 3', cols: 1, rows: 2 },
{ title: 'Card 4', cols: 1, rows: 1 }
];
})
);
constructor(private breakpointObserver: BreakpointObserver) {}
}
export const environment = {
production: true
};
// This file can be replaced during build by using the `fileReplacements` array.
// `ng build` replaces `environment.ts` with `environment.prod.ts`.
// The list of file replacements can be found in `angular.json`.
export const environment = {
production: false
};
/*
* For easier debugging in development mode, you can import the following file
* to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.
*
* This import should be commented out in production mode because it will have a negative impact
* on performance if an error is thrown.
*/
// import 'zone.js/plugins/zone-error'; // Included with Angular CLI.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>RailgunDashboard</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes recent versions of Safari, Chrome (including
* Opera), Edge on the desktop, and iOS and Chrome on mobile.
*
* Learn more in https://angular.io/guide/browser-support
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/**
* By default, zone.js will patch all possible macroTask and DomEvents
* user can disable parts of macroTask/DomEvents patch by setting following flags
* because those flags need to be set before `zone.js` being loaded, and webpack
* will put import in the top of bundle, so user need to create a separate file
* in this directory (for example: zone-flags.ts), and put the following flags
* into that file, and then add the following code before importing zone.js.
* import './zone-flags';
*
* The flags allowed in zone-flags.ts are listed here.
*
* The following flags will work for all browsers.
*
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
* (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
* (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
*
* in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
* with the following flag, it will bypass `zone.js` patch for IE/Edge
*
* (window as any).__Zone_enable_cross_context_check = true;
*
*/
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/
/* You can add global styles to this file, and also import other style files */
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
<T>(id: string): T;
keys(): string[];
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting(),
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().forEach(context);
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2020",
"module": "es2020",
"lib": [
"es2021",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"files": [
"src/test.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment