Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 501f4f9de6 | |||
| fa926eb10b | |||
| f2d0a9ec1b | |||
| 035173702d | |||
| 07a3365496 | |||
| 1c4f7dbb11 |
20
changelog.md
20
changelog.md
@@ -1,5 +1,25 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-04-13 - 13.15.0 - feat(stats)
|
||||
add typed network stats response fields for bandwidth, domain activity, and protocol distribution
|
||||
|
||||
- extends the network stats request interface with top IP bandwidth, domain activity, and frontend/backend protocol distribution data
|
||||
- updates app state to use a typed getNetworkStats request instead of casting the response to any
|
||||
|
||||
## 2026-04-13 - 13.14.0 - feat(network)
|
||||
add bandwidth-ranked IP and domain activity metrics to network monitoring
|
||||
|
||||
- Expose top IPs by bandwidth and aggregated domain activity from route metrics.
|
||||
- Replace estimated per-connection values with real per-IP throughput data in ops handlers and stats responses.
|
||||
- Update the network UI to show bandwidth-ranked IPs and domain activity while removing the recent request table.
|
||||
|
||||
## 2026-04-13 - 13.13.0 - feat(dns)
|
||||
add domain migration between dcrouter and provider-managed DNS with unified ACME managed-domain handling
|
||||
|
||||
- adds domain migration support in DnsManager, API handlers, request interfaces, app state, and domains UI
|
||||
- routes ACME DNS-01 challenges through managed domains using createRecord/deleteRecord for both dcrouter-hosted and provider-managed zones
|
||||
- enables immediate unregister of deleted dcrouter-hosted DNS records from the embedded DNS server
|
||||
|
||||
## 2026-04-12 - 13.12.0 - feat(email-domains)
|
||||
support creating email domains on optional subdomains
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@serve.zone/dcrouter",
|
||||
"private": false,
|
||||
"version": "13.12.0",
|
||||
"version": "13.15.0",
|
||||
"description": "A multifaceted routing service handling mail and SMS delivery functions.",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/dcrouter',
|
||||
version: '13.12.0',
|
||||
version: '13.15.0',
|
||||
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
|
||||
}
|
||||
|
||||
@@ -930,15 +930,16 @@ export class DcRouter {
|
||||
}
|
||||
|
||||
// Configure DNS-01 challenge if any DnsProviderDoc exists in the DB AND
|
||||
// ACME is enabled. The DnsManager dispatches each challenge to the right
|
||||
// provider client based on the FQDN being certificated.
|
||||
// ACME is enabled. The DnsManager dispatches each challenge through the
|
||||
// unified createRecord()/deleteRecord() path — works for both dcrouter-hosted
|
||||
// zones and provider-managed zones. Only domains under management get certs.
|
||||
let challengeHandlers: any[] = [];
|
||||
if (
|
||||
acmeConfig &&
|
||||
this.dnsManager &&
|
||||
(await this.dnsManager.hasAcmeCapableProvider())
|
||||
(await this.dnsManager.hasAnyManagedDomain())
|
||||
) {
|
||||
logger.log('info', 'Configuring DNS-01 challenge for ACME via DnsManager (DB providers)');
|
||||
logger.log('info', 'Configuring DNS-01 challenge for ACME via DnsManager (managed domains)');
|
||||
const convenientDnsProvider = this.dnsManager.buildAcmeConvenientDnsProvider();
|
||||
const dns01Handler = new plugins.smartacme.handlers.Dns01Handler(convenientDnsProvider);
|
||||
challengeHandlers.push(dns01Handler);
|
||||
|
||||
@@ -296,70 +296,99 @@ export class DnsManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any cloudflare provider exists in the DB. Used by setupSmartProxy()
|
||||
* to decide whether to wire SmartAcme with a DNS-01 handler.
|
||||
* Find the DomainDoc that covers a given FQDN, regardless of source
|
||||
* (dcrouter-hosted or provider-managed). Uses longest-suffix match.
|
||||
*/
|
||||
public async hasAcmeCapableProvider(): Promise<boolean> {
|
||||
const providers = await DnsProviderDoc.findAll();
|
||||
return providers.length > 0;
|
||||
public async findDomainForFqdn(fqdn: string): Promise<DomainDoc | null> {
|
||||
const lower = fqdn.toLowerCase().replace(/^\*\./, '').replace(/\.$/, '');
|
||||
const allDomains = await DomainDoc.findAll();
|
||||
// Sort by name length descending for longest-match-wins
|
||||
allDomains.sort((a, b) => b.name.length - a.name.length);
|
||||
for (const domain of allDomains) {
|
||||
if (lower === domain.name || lower.endsWith(`.${domain.name}`)) {
|
||||
return domain;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an IConvenientDnsProvider that dispatches each ACME challenge to
|
||||
* the right provider client (whichever provider type owns the parent zone),
|
||||
* based on the challenge's hostName. Provider-agnostic — uses the IDnsProviderClient
|
||||
* interface, so any registered provider implementation works.
|
||||
* Returned object plugs directly into smartacme's Dns01Handler.
|
||||
* Delete all DNS records matching a name and type under a domain.
|
||||
* Used for ACME challenge cleanup (may have multiple TXT records at the same name).
|
||||
*/
|
||||
public async deleteRecordsByNameAndType(
|
||||
domainId: string,
|
||||
name: string,
|
||||
type: TDnsRecordType,
|
||||
): Promise<void> {
|
||||
const records = await DnsRecordDoc.findByDomainId(domainId);
|
||||
for (const rec of records) {
|
||||
if (rec.name.toLowerCase() === name.toLowerCase() && rec.type === type) {
|
||||
await this.deleteRecord(rec.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True if any domain is under management (dcrouter-hosted or provider-managed).
|
||||
* Used by setupSmartProxy() to decide whether to wire SmartAcme with a DNS-01 handler.
|
||||
*/
|
||||
public async hasAnyManagedDomain(): Promise<boolean> {
|
||||
const domains = await DomainDoc.findAll();
|
||||
return domains.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an IConvenientDnsProvider that routes ACME DNS-01 challenges through
|
||||
* the DnsManager abstraction. Challenges are dispatched via createRecord() /
|
||||
* deleteRecord(), which transparently handle both dcrouter-hosted zones
|
||||
* (embedded DnsServer) and provider-managed zones (e.g. Cloudflare API).
|
||||
*
|
||||
* Only domains under management (with a DomainDoc in DB) are supported —
|
||||
* this acts as the management gate for certificate issuance.
|
||||
*/
|
||||
public buildAcmeConvenientDnsProvider(): plugins.tsclass.network.IConvenientDnsProvider {
|
||||
const self = this;
|
||||
const adapter = {
|
||||
async acmeSetDnsChallenge(dnsChallenge: { hostName: string; challenge: string }) {
|
||||
const client = await self.getProviderClientForDomain(dnsChallenge.hostName);
|
||||
if (!client) {
|
||||
const domainDoc = await self.findDomainForFqdn(dnsChallenge.hostName);
|
||||
if (!domainDoc) {
|
||||
throw new Error(
|
||||
`DnsManager: no DNS provider configured for ${dnsChallenge.hostName}. ` +
|
||||
'Add one in the Domains > Providers UI before issuing certificates.',
|
||||
`DnsManager: no managed domain found for ${dnsChallenge.hostName}. ` +
|
||||
'Add the domain in Domains before issuing certificates.',
|
||||
);
|
||||
}
|
||||
// Clean any leftover challenge records first to avoid duplicates.
|
||||
// Clean leftover challenge records first to avoid duplicates.
|
||||
try {
|
||||
const existing = await client.listRecords(dnsChallenge.hostName);
|
||||
for (const r of existing) {
|
||||
if (r.type === 'TXT' && r.name === dnsChallenge.hostName) {
|
||||
await client.deleteRecord(dnsChallenge.hostName, r.providerRecordId).catch(() => {});
|
||||
}
|
||||
}
|
||||
await self.deleteRecordsByNameAndType(domainDoc.id, dnsChallenge.hostName, 'TXT');
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `DnsManager: failed to clean existing TXT for ${dnsChallenge.hostName}: ${(err as Error).message}`);
|
||||
}
|
||||
await client.createRecord(dnsChallenge.hostName, {
|
||||
// Create the challenge TXT record via the unified path
|
||||
await self.createRecord({
|
||||
domainId: domainDoc.id,
|
||||
name: dnsChallenge.hostName,
|
||||
type: 'TXT',
|
||||
value: dnsChallenge.challenge,
|
||||
ttl: 120,
|
||||
createdBy: 'acme-dns01',
|
||||
});
|
||||
},
|
||||
async acmeRemoveDnsChallenge(dnsChallenge: { hostName: string; challenge: string }) {
|
||||
const client = await self.getProviderClientForDomain(dnsChallenge.hostName);
|
||||
if (!client) {
|
||||
const domainDoc = await self.findDomainForFqdn(dnsChallenge.hostName);
|
||||
if (!domainDoc) {
|
||||
// The domain may have been removed; nothing to clean up.
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const existing = await client.listRecords(dnsChallenge.hostName);
|
||||
for (const r of existing) {
|
||||
if (r.type === 'TXT' && r.name === dnsChallenge.hostName) {
|
||||
await client.deleteRecord(dnsChallenge.hostName, r.providerRecordId);
|
||||
}
|
||||
}
|
||||
await self.deleteRecordsByNameAndType(domainDoc.id, dnsChallenge.hostName, 'TXT');
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `DnsManager: failed to remove TXT for ${dnsChallenge.hostName}: ${(err as Error).message}`);
|
||||
}
|
||||
},
|
||||
async isDomainSupported(domain: string): Promise<boolean> {
|
||||
const client = await self.getProviderClientForDomain(domain);
|
||||
return !!client;
|
||||
const domainDoc = await self.findDomainForFqdn(domain);
|
||||
return !!domainDoc;
|
||||
},
|
||||
};
|
||||
return { convenience: adapter } as plugins.tsclass.network.IConvenientDnsProvider;
|
||||
@@ -642,6 +671,151 @@ export class DnsManager {
|
||||
return await DnsRecordDoc.findById(id);
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Domain migration
|
||||
// ==========================================================================
|
||||
|
||||
/**
|
||||
* Migrate a domain between dcrouter-hosted and provider-managed.
|
||||
* Transfers all records to the target and updates domain metadata.
|
||||
*/
|
||||
public async migrateDomain(args: {
|
||||
id: string;
|
||||
targetSource: 'dcrouter' | 'provider';
|
||||
targetProviderId?: string;
|
||||
deleteExistingProviderRecords?: boolean;
|
||||
}): Promise<{ success: boolean; recordsMigrated?: number; message?: string }> {
|
||||
const domain = await DomainDoc.findById(args.id);
|
||||
if (!domain) return { success: false, message: 'Domain not found' };
|
||||
|
||||
if (domain.source === args.targetSource && domain.providerId === args.targetProviderId) {
|
||||
return { success: false, message: 'Domain is already in the target configuration' };
|
||||
}
|
||||
|
||||
const records = await DnsRecordDoc.findByDomainId(domain.id);
|
||||
|
||||
if (args.targetSource === 'provider') {
|
||||
return this.migrateToDnsProvider(domain, records, args.targetProviderId!, args.deleteExistingProviderRecords ?? false);
|
||||
} else {
|
||||
return this.migrateToDcrouter(domain, records);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate domain from dcrouter-hosted (or another provider) to an external DNS provider.
|
||||
*/
|
||||
private async migrateToDnsProvider(
|
||||
domain: DomainDoc,
|
||||
records: DnsRecordDoc[],
|
||||
targetProviderId: string,
|
||||
deleteExistingProviderRecords: boolean,
|
||||
): Promise<{ success: boolean; recordsMigrated?: number; message?: string }> {
|
||||
// Validate the target provider exists
|
||||
const client = await this.getProviderClientById(targetProviderId);
|
||||
if (!client) {
|
||||
return { success: false, message: 'Target DNS provider not found' };
|
||||
}
|
||||
|
||||
// Find the zone at the provider
|
||||
const providerDomains = await client.listDomains();
|
||||
const zone = providerDomains.find(
|
||||
(z) => z.name.toLowerCase() === domain.name.toLowerCase(),
|
||||
);
|
||||
if (!zone) {
|
||||
return { success: false, message: `Zone "${domain.name}" not found at the target provider` };
|
||||
}
|
||||
|
||||
// Optionally delete existing records at the provider
|
||||
if (deleteExistingProviderRecords) {
|
||||
try {
|
||||
const existingProviderRecords = await client.listRecords(domain.name);
|
||||
for (const pr of existingProviderRecords) {
|
||||
await client.deleteRecord(domain.name, pr.providerRecordId).catch(() => {});
|
||||
}
|
||||
logger.log('info', `Deleted ${existingProviderRecords.length} existing records at provider for ${domain.name}`);
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `Failed to clean existing provider records for ${domain.name}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Push each local record to the provider
|
||||
let migrated = 0;
|
||||
for (const rec of records) {
|
||||
try {
|
||||
const providerRecord = await client.createRecord(domain.name, {
|
||||
name: rec.name,
|
||||
type: rec.type as any,
|
||||
value: rec.value,
|
||||
ttl: rec.ttl,
|
||||
});
|
||||
// Unregister from embedded DnsServer if it was dcrouter-hosted
|
||||
if (domain.source === 'dcrouter') {
|
||||
this.unregisterRecordFromDnsServer(rec);
|
||||
}
|
||||
// Update the record doc to synced
|
||||
rec.source = 'synced' as TDnsRecordSource;
|
||||
rec.providerRecordId = providerRecord.providerRecordId;
|
||||
await rec.save();
|
||||
migrated++;
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `Failed to migrate record ${rec.name} ${rec.type} to provider: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Update domain metadata
|
||||
domain.source = 'provider';
|
||||
domain.authoritative = false;
|
||||
domain.providerId = targetProviderId;
|
||||
domain.externalZoneId = zone.externalId;
|
||||
domain.nameservers = zone.nameservers;
|
||||
domain.lastSyncedAt = Date.now();
|
||||
domain.updatedAt = Date.now();
|
||||
await domain.save();
|
||||
|
||||
logger.log('info', `Domain ${domain.name} migrated to provider (${migrated} records)`);
|
||||
return { success: true, recordsMigrated: migrated };
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate domain from provider-managed to dcrouter-hosted (authoritative).
|
||||
*/
|
||||
private async migrateToDcrouter(
|
||||
domain: DomainDoc,
|
||||
records: DnsRecordDoc[],
|
||||
): Promise<{ success: boolean; recordsMigrated?: number; message?: string }> {
|
||||
// Register each record with the embedded DnsServer
|
||||
let migrated = 0;
|
||||
for (const rec of records) {
|
||||
try {
|
||||
this.registerRecordWithDnsServer(rec);
|
||||
// Update the record doc to local
|
||||
rec.source = 'local' as TDnsRecordSource;
|
||||
rec.providerRecordId = undefined;
|
||||
await rec.save();
|
||||
migrated++;
|
||||
} catch (err: unknown) {
|
||||
logger.log('warn', `Failed to register record ${rec.name} ${rec.type} with DnsServer: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Update domain metadata
|
||||
domain.source = 'dcrouter';
|
||||
domain.authoritative = true;
|
||||
domain.providerId = undefined;
|
||||
domain.externalZoneId = undefined;
|
||||
domain.nameservers = undefined;
|
||||
domain.lastSyncedAt = undefined;
|
||||
domain.updatedAt = Date.now();
|
||||
await domain.save();
|
||||
|
||||
logger.log('info', `Domain ${domain.name} migrated to dcrouter (${migrated} records)`);
|
||||
return { success: true, recordsMigrated: migrated };
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Record CRUD
|
||||
// ==========================================================================
|
||||
|
||||
public async createRecord(args: {
|
||||
domainId: string;
|
||||
name: string;
|
||||
@@ -759,14 +933,24 @@ export class DnsManager {
|
||||
}
|
||||
}
|
||||
}
|
||||
// For local records: smartdns has no unregister API in the pinned version,
|
||||
// so the record stays served until the next restart. The DB delete still
|
||||
// takes effect — on restart, the record will not be re-registered.
|
||||
// For dcrouter-hosted records: unregister the handler from the embedded DnsServer
|
||||
// so the record stops being served immediately (not just after restart).
|
||||
if (domain.source === 'dcrouter' && this.dnsServer) {
|
||||
this.unregisterRecordFromDnsServer(doc);
|
||||
}
|
||||
|
||||
await doc.delete();
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a record's handler from the embedded DnsServer.
|
||||
*/
|
||||
public unregisterRecordFromDnsServer(rec: DnsRecordDoc): void {
|
||||
if (!this.dnsServer) return;
|
||||
this.dnsServer.unregisterHandler(rec.name, [rec.type]);
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Internal helpers
|
||||
// ==========================================================================
|
||||
|
||||
@@ -553,12 +553,14 @@ export class MetricsManager {
|
||||
connectionsByIP: new Map<string, number>(),
|
||||
throughputRate: { bytesInPerSecond: 0, bytesOutPerSecond: 0 },
|
||||
topIPs: [] as Array<{ ip: string; count: number }>,
|
||||
topIPsByBandwidth: [] as Array<{ ip: string; count: number; bwIn: number; bwOut: number }>,
|
||||
totalDataTransferred: { bytesIn: 0, bytesOut: 0 },
|
||||
throughputHistory: [] as Array<{ timestamp: number; in: number; out: number }>,
|
||||
throughputByIP: new Map<string, { in: number; out: number }>(),
|
||||
requestsPerSecond: 0,
|
||||
requestsTotal: 0,
|
||||
backends: [] as Array<any>,
|
||||
domainActivity: [] as Array<{ domain: string; bytesInPerSecond: number; bytesOutPerSecond: number; activeConnections: number; routeCount: number }>,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -572,7 +574,7 @@ export class MetricsManager {
|
||||
bytesOutPerSecond: instantThroughput.out
|
||||
};
|
||||
|
||||
// Get top IPs
|
||||
// Get top IPs by connection count
|
||||
const topIPs = proxyMetrics.connections.topIPs(10);
|
||||
|
||||
// Get total data transferred
|
||||
@@ -699,10 +701,83 @@ export class MetricsManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Build top 10 IPs by bandwidth (sorted by total throughput desc)
|
||||
const allIPData = new Map<string, { count: number; bwIn: number; bwOut: number }>();
|
||||
for (const [ip, count] of connectionsByIP) {
|
||||
allIPData.set(ip, { count, bwIn: 0, bwOut: 0 });
|
||||
}
|
||||
for (const [ip, tp] of throughputByIP) {
|
||||
const existing = allIPData.get(ip);
|
||||
if (existing) {
|
||||
existing.bwIn = tp.in;
|
||||
existing.bwOut = tp.out;
|
||||
} else {
|
||||
allIPData.set(ip, { count: 0, bwIn: tp.in, bwOut: tp.out });
|
||||
}
|
||||
}
|
||||
const topIPsByBandwidth = Array.from(allIPData.entries())
|
||||
.sort((a, b) => (b[1].bwIn + b[1].bwOut) - (a[1].bwIn + a[1].bwOut))
|
||||
.slice(0, 10)
|
||||
.map(([ip, data]) => ({ ip, count: data.count, bwIn: data.bwIn, bwOut: data.bwOut }));
|
||||
|
||||
// Build domain activity from per-route metrics
|
||||
const connectionsByRoute = proxyMetrics.connections.byRoute();
|
||||
const throughputByRoute = proxyMetrics.throughput.byRoute();
|
||||
|
||||
// Map route name → primary domain using dcrouter's route configs
|
||||
const routeToDomain = new Map<string, string>();
|
||||
if (this.dcRouter.smartProxy) {
|
||||
for (const route of this.dcRouter.smartProxy.routeManager.getRoutes()) {
|
||||
if (!route.name || !route.match.domains) continue;
|
||||
const domains = Array.isArray(route.match.domains)
|
||||
? route.match.domains
|
||||
: [route.match.domains];
|
||||
if (domains.length > 0) {
|
||||
routeToDomain.set(route.name, domains[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Aggregate metrics by domain
|
||||
const domainAgg = new Map<string, {
|
||||
activeConnections: number;
|
||||
bytesInPerSec: number;
|
||||
bytesOutPerSec: number;
|
||||
routeCount: number;
|
||||
}>();
|
||||
for (const [routeName, activeConns] of connectionsByRoute) {
|
||||
const domain = routeToDomain.get(routeName) || routeName;
|
||||
const tp = throughputByRoute.get(routeName) || { in: 0, out: 0 };
|
||||
const existing = domainAgg.get(domain);
|
||||
if (existing) {
|
||||
existing.activeConnections += activeConns;
|
||||
existing.bytesInPerSec += tp.in;
|
||||
existing.bytesOutPerSec += tp.out;
|
||||
existing.routeCount++;
|
||||
} else {
|
||||
domainAgg.set(domain, {
|
||||
activeConnections: activeConns,
|
||||
bytesInPerSec: tp.in,
|
||||
bytesOutPerSec: tp.out,
|
||||
routeCount: 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
const domainActivity = Array.from(domainAgg.entries())
|
||||
.map(([domain, data]) => ({
|
||||
domain,
|
||||
bytesInPerSecond: data.bytesInPerSec,
|
||||
bytesOutPerSecond: data.bytesOutPerSec,
|
||||
activeConnections: data.activeConnections,
|
||||
routeCount: data.routeCount,
|
||||
}))
|
||||
.sort((a, b) => (b.bytesInPerSecond + b.bytesOutPerSecond) - (a.bytesInPerSecond + a.bytesOutPerSecond));
|
||||
|
||||
return {
|
||||
connectionsByIP,
|
||||
throughputRate,
|
||||
topIPs,
|
||||
topIPsByBandwidth,
|
||||
totalDataTransferred,
|
||||
throughputHistory,
|
||||
throughputByIP,
|
||||
@@ -711,6 +786,7 @@ export class MetricsManager {
|
||||
backends,
|
||||
frontendProtocols,
|
||||
backendProtocols,
|
||||
domainActivity,
|
||||
};
|
||||
}, 1000); // 1s cache — matches typical dashboard poll interval
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ export class ConfigHandler {
|
||||
// (replaces the legacy `dnsChallenge.cloudflareApiKey` constructor field).
|
||||
let dnsChallengeEnabled = false;
|
||||
try {
|
||||
dnsChallengeEnabled = (await dcRouter.dnsManager?.hasAcmeCapableProvider()) ?? false;
|
||||
dnsChallengeEnabled = (await dcRouter.dnsManager?.hasAnyManagedDomain()) ?? false;
|
||||
} catch {
|
||||
dnsChallengeEnabled = false;
|
||||
}
|
||||
|
||||
@@ -157,5 +157,23 @@ export class DomainHandler {
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// Migrate domain between dcrouter-hosted and provider-managed
|
||||
this.typedrouter.addTypedHandler(
|
||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_MigrateDomain>(
|
||||
'migrateDomain',
|
||||
async (dataArg) => {
|
||||
await this.requireAuth(dataArg, 'domains:write');
|
||||
const dnsManager = this.opsServerRef.dcRouterRef.dnsManager;
|
||||
if (!dnsManager) return { success: false, message: 'DnsManager not initialized' };
|
||||
return await dnsManager.migrateDomain({
|
||||
id: dataArg.id,
|
||||
targetSource: dataArg.targetSource,
|
||||
targetProviderId: dataArg.targetProviderId,
|
||||
deleteExistingProviderRecords: dataArg.deleteExistingProviderRecords,
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +51,8 @@ export class SecurityHandler {
|
||||
startTime: conn.startTime,
|
||||
protocol: conn.type === 'http' ? 'https' : conn.type as any,
|
||||
state: conn.status as any,
|
||||
bytesReceived: Math.floor(conn.bytesTransferred / 2),
|
||||
bytesSent: Math.floor(conn.bytesTransferred / 2),
|
||||
bytesReceived: (conn as any)._throughputIn || 0,
|
||||
bytesSent: (conn as any)._throughputOut || 0,
|
||||
}));
|
||||
|
||||
const summary = {
|
||||
@@ -96,9 +96,11 @@ export class SecurityHandler {
|
||||
connectionsByIP: Array.from(networkStats.connectionsByIP.entries()).map(([ip, count]) => ({ ip, count })),
|
||||
throughputRate: networkStats.throughputRate,
|
||||
topIPs: networkStats.topIPs,
|
||||
topIPsByBandwidth: networkStats.topIPsByBandwidth,
|
||||
totalDataTransferred: networkStats.totalDataTransferred,
|
||||
throughputHistory: networkStats.throughputHistory || [],
|
||||
throughputByIP,
|
||||
domainActivity: networkStats.domainActivity || [],
|
||||
requestsPerSecond: networkStats.requestsPerSecond || 0,
|
||||
requestsTotal: networkStats.requestsTotal || 0,
|
||||
backends: networkStats.backends || [],
|
||||
@@ -110,9 +112,11 @@ export class SecurityHandler {
|
||||
connectionsByIP: [],
|
||||
throughputRate: { bytesInPerSecond: 0, bytesOutPerSecond: 0 },
|
||||
topIPs: [],
|
||||
topIPsByBandwidth: [],
|
||||
totalDataTransferred: { bytesIn: 0, bytesOut: 0 },
|
||||
throughputHistory: [],
|
||||
throughputByIP: [],
|
||||
domainActivity: [],
|
||||
requestsPerSecond: 0,
|
||||
requestsTotal: 0,
|
||||
backends: [],
|
||||
@@ -251,31 +255,31 @@ export class SecurityHandler {
|
||||
const connectionInfo = await this.opsServerRef.dcRouterRef.metricsManager.getConnectionInfo();
|
||||
const networkStats = await this.opsServerRef.dcRouterRef.metricsManager.getNetworkStats();
|
||||
|
||||
// Use IP-based connection data from the new metrics API
|
||||
// One aggregate row per IP with real throughput data
|
||||
if (networkStats.connectionsByIP && networkStats.connectionsByIP.size > 0) {
|
||||
let connIndex = 0;
|
||||
const publicIp = this.opsServerRef.dcRouterRef.options.publicIp || 'server';
|
||||
|
||||
|
||||
for (const [ip, count] of networkStats.connectionsByIP) {
|
||||
// Create a connection entry for each active IP connection
|
||||
for (let i = 0; i < Math.min(count, 5); i++) { // Limit to 5 connections per IP for UI performance
|
||||
connections.push({
|
||||
id: `conn-${connIndex++}`,
|
||||
type: 'http',
|
||||
source: {
|
||||
ip: ip,
|
||||
port: Math.floor(Math.random() * 50000) + 10000, // High port range
|
||||
},
|
||||
destination: {
|
||||
ip: publicIp,
|
||||
port: 443,
|
||||
service: 'proxy',
|
||||
},
|
||||
startTime: Date.now() - Math.floor(Math.random() * 3600000), // Within last hour
|
||||
bytesTransferred: Math.floor(networkStats.totalDataTransferred.bytesIn / networkStats.connectionsByIP.size),
|
||||
status: 'active',
|
||||
});
|
||||
}
|
||||
const tp = networkStats.throughputByIP?.get(ip);
|
||||
connections.push({
|
||||
id: `ip-${connIndex++}`,
|
||||
type: 'http',
|
||||
source: {
|
||||
ip: ip,
|
||||
port: 0,
|
||||
},
|
||||
destination: {
|
||||
ip: publicIp,
|
||||
port: 443,
|
||||
service: 'proxy',
|
||||
},
|
||||
startTime: 0,
|
||||
bytesTransferred: count, // Store connection count here
|
||||
status: 'active',
|
||||
// Attach real throughput for the handler mapping
|
||||
...(tp ? { _throughputIn: tp.in, _throughputOut: tp.out } : {}),
|
||||
} as any);
|
||||
}
|
||||
} else if (connectionInfo.length > 0) {
|
||||
// Fallback to route-based connection info if no IP data available
|
||||
|
||||
@@ -291,6 +291,20 @@ export class StatsHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Build connectionDetails from real per-IP data
|
||||
const connectionDetails: interfaces.data.IConnectionDetails[] = [];
|
||||
for (const [ip, count] of stats.connectionsByIP) {
|
||||
const tp = stats.throughputByIP?.get(ip);
|
||||
connectionDetails.push({
|
||||
remoteAddress: ip,
|
||||
protocol: 'https',
|
||||
state: 'connected',
|
||||
startTime: 0,
|
||||
bytesIn: tp?.in || 0,
|
||||
bytesOut: tp?.out || 0,
|
||||
});
|
||||
}
|
||||
|
||||
metrics.network = {
|
||||
totalBandwidth: {
|
||||
in: stats.throughputRate.bytesInPerSecond,
|
||||
@@ -301,12 +315,18 @@ export class StatsHandler {
|
||||
out: stats.totalDataTransferred.bytesOut,
|
||||
},
|
||||
activeConnections: serverStats.activeConnections,
|
||||
connectionDetails: [],
|
||||
connectionDetails,
|
||||
topEndpoints: stats.topIPs.map(ip => ({
|
||||
endpoint: ip.ip,
|
||||
requests: ip.count,
|
||||
connections: ip.count,
|
||||
bandwidth: ipBandwidth.get(ip.ip) || { in: 0, out: 0 },
|
||||
})),
|
||||
topEndpointsByBandwidth: stats.topIPsByBandwidth.map(ip => ({
|
||||
endpoint: ip.ip,
|
||||
connections: ip.count,
|
||||
bandwidth: { in: ip.bwIn, out: ip.bwOut },
|
||||
})),
|
||||
domainActivity: stats.domainActivity || [],
|
||||
throughputHistory: stats.throughputHistory || [],
|
||||
requestsPerSecond: stats.requestsPerSecond || 0,
|
||||
requestsTotal: stats.requestsTotal || 0,
|
||||
|
||||
@@ -143,6 +143,14 @@ export interface IHealthStatus {
|
||||
version?: string;
|
||||
}
|
||||
|
||||
export interface IDomainActivity {
|
||||
domain: string;
|
||||
bytesInPerSecond: number;
|
||||
bytesOutPerSecond: number;
|
||||
activeConnections: number;
|
||||
routeCount: number;
|
||||
}
|
||||
|
||||
export interface INetworkMetrics {
|
||||
totalBandwidth: {
|
||||
in: number;
|
||||
@@ -156,12 +164,21 @@ export interface INetworkMetrics {
|
||||
connectionDetails: IConnectionDetails[];
|
||||
topEndpoints: Array<{
|
||||
endpoint: string;
|
||||
requests: number;
|
||||
connections: number;
|
||||
bandwidth: {
|
||||
in: number;
|
||||
out: number;
|
||||
};
|
||||
}>;
|
||||
topEndpointsByBandwidth: Array<{
|
||||
endpoint: string;
|
||||
connections: number;
|
||||
bandwidth: {
|
||||
in: number;
|
||||
out: number;
|
||||
};
|
||||
}>;
|
||||
domainActivity: IDomainActivity[];
|
||||
throughputHistory?: Array<{ timestamp: number; in: number; out: number }>;
|
||||
requestsPerSecond?: number;
|
||||
requestsTotal?: number;
|
||||
|
||||
@@ -148,3 +148,31 @@ export interface IReq_SyncDomain extends plugins.typedrequestInterfaces.implemen
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate a domain between dcrouter-hosted and provider-managed (or between providers).
|
||||
* Records are transferred to the target and the domain source/providerId are updated.
|
||||
*/
|
||||
export interface IReq_MigrateDomain extends plugins.typedrequestInterfaces.implementsTR<
|
||||
plugins.typedrequestInterfaces.ITypedRequest,
|
||||
IReq_MigrateDomain
|
||||
> {
|
||||
method: 'migrateDomain';
|
||||
request: {
|
||||
identity?: authInterfaces.IIdentity;
|
||||
apiToken?: string;
|
||||
id: string;
|
||||
/** Target source type. */
|
||||
targetSource: import('../data/domain.js').TDomainSource;
|
||||
/** Required when targetSource is 'provider'. */
|
||||
targetProviderId?: string;
|
||||
/** When migrating to a provider: delete all existing records at the provider first. */
|
||||
deleteExistingProviderRecords?: boolean;
|
||||
};
|
||||
response: {
|
||||
success: boolean;
|
||||
/** Number of records migrated. */
|
||||
recordsMigrated?: number;
|
||||
message?: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -180,5 +180,9 @@ export interface IReq_GetNetworkStats extends plugins.typedrequestInterfaces.imp
|
||||
requestsPerSecond: number;
|
||||
requestsTotal: number;
|
||||
backends?: statsInterfaces.IBackendInfo[];
|
||||
topIPsByBandwidth: Array<{ ip: string; count: number; bwIn: number; bwOut: number }>;
|
||||
domainActivity: statsInterfaces.IDomainActivity[];
|
||||
frontendProtocols?: statsInterfaces.IProtocolDistribution | null;
|
||||
backendProtocols?: statsInterfaces.IProtocolDistribution | null;
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@serve.zone/dcrouter',
|
||||
version: '13.12.0',
|
||||
version: '13.15.0',
|
||||
description: 'A multifaceted routing service handling mail and SMS delivery functions.'
|
||||
}
|
||||
|
||||
@@ -52,7 +52,9 @@ export interface INetworkState {
|
||||
throughputRate: { bytesInPerSecond: number; bytesOutPerSecond: number };
|
||||
totalBytes: { in: number; out: number };
|
||||
topIPs: Array<{ ip: string; count: number }>;
|
||||
topIPsByBandwidth: Array<{ ip: string; count: number; bwIn: number; bwOut: number }>;
|
||||
throughputByIP: Array<{ ip: string; in: number; out: number }>;
|
||||
domainActivity: interfaces.data.IDomainActivity[];
|
||||
throughputHistory: Array<{ timestamp: number; in: number; out: number }>;
|
||||
requestsPerSecond: number;
|
||||
requestsTotal: number;
|
||||
@@ -160,7 +162,9 @@ export const networkStatePart = await appState.getStatePart<INetworkState>(
|
||||
throughputRate: { bytesInPerSecond: 0, bytesOutPerSecond: 0 },
|
||||
totalBytes: { in: 0, out: 0 },
|
||||
topIPs: [],
|
||||
topIPsByBandwidth: [],
|
||||
throughputByIP: [],
|
||||
domainActivity: [],
|
||||
throughputHistory: [],
|
||||
requestsPerSecond: 0,
|
||||
requestsTotal: 0,
|
||||
@@ -518,14 +522,13 @@ export const fetchNetworkStatsAction = networkStatePart.createAction(async (stat
|
||||
});
|
||||
|
||||
// Get network stats for throughput and IP data
|
||||
const networkStatsRequest = new plugins.domtools.plugins.typedrequest.TypedRequest(
|
||||
'/typedrequest',
|
||||
'getNetworkStats'
|
||||
);
|
||||
|
||||
const networkStatsRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetNetworkStats
|
||||
>('/typedrequest', 'getNetworkStats');
|
||||
|
||||
const networkStatsResponse = await networkStatsRequest.fire({
|
||||
identity: context.identity,
|
||||
}) as any;
|
||||
});
|
||||
|
||||
// Use the connections data for the connection list
|
||||
// and network stats for throughput and IP analytics
|
||||
@@ -552,7 +555,9 @@ export const fetchNetworkStatsAction = networkStatePart.createAction(async (stat
|
||||
? { in: networkStatsResponse.totalDataTransferred.bytesIn, out: networkStatsResponse.totalDataTransferred.bytesOut }
|
||||
: { in: 0, out: 0 },
|
||||
topIPs: networkStatsResponse.topIPs || [],
|
||||
topIPsByBandwidth: networkStatsResponse.topIPsByBandwidth || [],
|
||||
throughputByIP: networkStatsResponse.throughputByIP || [],
|
||||
domainActivity: networkStatsResponse.domainActivity || [],
|
||||
throughputHistory: networkStatsResponse.throughputHistory || [],
|
||||
requestsPerSecond: networkStatsResponse.requestsPerSecond || 0,
|
||||
requestsTotal: networkStatsResponse.requestsTotal || 0,
|
||||
@@ -1887,6 +1892,32 @@ export const syncDomainAction = domainsStatePart.createAction<{ id: string }>(
|
||||
},
|
||||
);
|
||||
|
||||
export const migrateDomainAction = domainsStatePart.createAction<{
|
||||
id: string;
|
||||
targetSource: interfaces.data.TDomainSource;
|
||||
targetProviderId?: string;
|
||||
deleteExistingProviderRecords?: boolean;
|
||||
}>(
|
||||
async (statePartArg, dataArg, actionContext): Promise<IDomainsState> => {
|
||||
const context = getActionContext();
|
||||
try {
|
||||
const request = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_MigrateDomain
|
||||
>('/typedrequest', 'migrateDomain');
|
||||
const response = await request.fire({ identity: context.identity!, ...dataArg });
|
||||
if (!response.success) {
|
||||
return { ...statePartArg.getState()!, error: response.message || 'Migration failed' };
|
||||
}
|
||||
return await actionContext!.dispatch(fetchDomainsAndProvidersAction, null);
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
...statePartArg.getState()!,
|
||||
error: error instanceof Error ? error.message : 'Migration failed',
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const createDnsRecordAction = domainsStatePart.createAction<{
|
||||
domainId: string;
|
||||
name: string;
|
||||
@@ -2623,67 +2654,52 @@ async function dispatchCombinedRefreshActionInner() {
|
||||
if (combinedResponse.metrics.network && currentView === 'network') {
|
||||
const network = combinedResponse.metrics.network;
|
||||
const connectionsByIP: { [ip: string]: number } = {};
|
||||
|
||||
// Convert connection details to IP counts
|
||||
|
||||
// Build connectionsByIP from connectionDetails (now populated with real per-IP data)
|
||||
network.connectionDetails.forEach(conn => {
|
||||
connectionsByIP[conn.remoteAddress] = (connectionsByIP[conn.remoteAddress] || 0) + 1;
|
||||
});
|
||||
|
||||
// Fetch detailed connections for the network view
|
||||
try {
|
||||
const connectionsRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||
interfaces.requests.IReq_GetActiveConnections
|
||||
>('/typedrequest', 'getActiveConnections');
|
||||
|
||||
const connectionsResponse = await connectionsRequest.fire({
|
||||
identity: context.identity,
|
||||
});
|
||||
// Build connections from connectionDetails (real per-IP aggregates)
|
||||
const connections: interfaces.data.IConnectionInfo[] = network.connectionDetails.map((conn, i) => ({
|
||||
id: `ip-${conn.remoteAddress}`,
|
||||
remoteAddress: conn.remoteAddress,
|
||||
localAddress: 'server',
|
||||
startTime: conn.startTime,
|
||||
protocol: conn.protocol as any,
|
||||
state: conn.state as any,
|
||||
bytesReceived: conn.bytesIn,
|
||||
bytesSent: conn.bytesOut,
|
||||
}));
|
||||
|
||||
networkStatePart.setState({
|
||||
...networkStatePart.getState()!,
|
||||
connections: connectionsResponse.connections,
|
||||
connectionsByIP,
|
||||
throughputRate: {
|
||||
bytesInPerSecond: network.totalBandwidth.in,
|
||||
bytesOutPerSecond: network.totalBandwidth.out
|
||||
},
|
||||
totalBytes: network.totalBytes || { in: 0, out: 0 },
|
||||
topIPs: network.topEndpoints.map(e => ({ ip: e.endpoint, count: e.requests })),
|
||||
throughputByIP: network.topEndpoints.map(e => ({ ip: e.endpoint, in: e.bandwidth?.in || 0, out: e.bandwidth?.out || 0 })),
|
||||
throughputHistory: network.throughputHistory || [],
|
||||
requestsPerSecond: network.requestsPerSecond || 0,
|
||||
requestsTotal: network.requestsTotal || 0,
|
||||
backends: network.backends || [],
|
||||
frontendProtocols: network.frontendProtocols || null,
|
||||
backendProtocols: network.backendProtocols || null,
|
||||
lastUpdated: Date.now(),
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
console.error('Failed to fetch connections:', error);
|
||||
networkStatePart.setState({
|
||||
...networkStatePart.getState()!,
|
||||
connections: [],
|
||||
connectionsByIP,
|
||||
throughputRate: {
|
||||
bytesInPerSecond: network.totalBandwidth.in,
|
||||
bytesOutPerSecond: network.totalBandwidth.out
|
||||
},
|
||||
totalBytes: network.totalBytes || { in: 0, out: 0 },
|
||||
topIPs: network.topEndpoints.map(e => ({ ip: e.endpoint, count: e.requests })),
|
||||
throughputByIP: network.topEndpoints.map(e => ({ ip: e.endpoint, in: e.bandwidth?.in || 0, out: e.bandwidth?.out || 0 })),
|
||||
throughputHistory: network.throughputHistory || [],
|
||||
requestsPerSecond: network.requestsPerSecond || 0,
|
||||
requestsTotal: network.requestsTotal || 0,
|
||||
backends: network.backends || [],
|
||||
frontendProtocols: network.frontendProtocols || null,
|
||||
backendProtocols: network.backendProtocols || null,
|
||||
lastUpdated: Date.now(),
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
networkStatePart.setState({
|
||||
...networkStatePart.getState()!,
|
||||
connections,
|
||||
connectionsByIP,
|
||||
throughputRate: {
|
||||
bytesInPerSecond: network.totalBandwidth.in,
|
||||
bytesOutPerSecond: network.totalBandwidth.out,
|
||||
},
|
||||
totalBytes: network.totalBytes || { in: 0, out: 0 },
|
||||
topIPs: network.topEndpoints.map(e => ({ ip: e.endpoint, count: e.connections })),
|
||||
topIPsByBandwidth: (network.topEndpointsByBandwidth || []).map(e => ({
|
||||
ip: e.endpoint,
|
||||
count: e.connections,
|
||||
bwIn: e.bandwidth?.in || 0,
|
||||
bwOut: e.bandwidth?.out || 0,
|
||||
})),
|
||||
throughputByIP: network.topEndpoints.map(e => ({ ip: e.endpoint, in: e.bandwidth?.in || 0, out: e.bandwidth?.out || 0 })),
|
||||
domainActivity: network.domainActivity || [],
|
||||
throughputHistory: network.throughputHistory || [],
|
||||
requestsPerSecond: network.requestsPerSecond || 0,
|
||||
requestsTotal: network.requestsTotal || 0,
|
||||
backends: network.backends || [],
|
||||
frontendProtocols: network.frontendProtocols || null,
|
||||
backendProtocols: network.backendProtocols || null,
|
||||
lastUpdated: Date.now(),
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
}
|
||||
|
||||
// Refresh certificate data if on Domains > Certificates subview
|
||||
|
||||
@@ -149,6 +149,15 @@ export class OpsViewDomains extends DeesElement {
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Migrate',
|
||||
iconName: 'lucide:arrow-right-left',
|
||||
type: ['inRow', 'contextmenu'] as any,
|
||||
actionFunc: async (actionData: any) => {
|
||||
const domain = actionData.item as interfaces.data.IDomain;
|
||||
await this.showMigrateDialog(domain);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Delete',
|
||||
iconName: 'lucide:trash2',
|
||||
@@ -308,6 +317,94 @@ export class OpsViewDomains extends DeesElement {
|
||||
});
|
||||
}
|
||||
|
||||
private async showMigrateDialog(domain: interfaces.data.IDomain) {
|
||||
const { DeesModal, DeesToast } = await import('@design.estate/dees-catalog');
|
||||
const providers = this.domainsState.providers;
|
||||
|
||||
// Build target options based on current source
|
||||
const targetOptions: { option: string; key: string }[] = [];
|
||||
for (const p of providers) {
|
||||
// Skip current source
|
||||
if (p.builtIn && domain.source === 'dcrouter') continue;
|
||||
if (!p.builtIn && domain.source === 'provider' && domain.providerId === p.id) continue;
|
||||
|
||||
const label = p.builtIn ? 'DcRouter (self)' : `${p.name} (${p.type})`;
|
||||
const key = p.builtIn ? 'dcrouter' : `provider:${p.id}`;
|
||||
targetOptions.push({ option: label, key });
|
||||
}
|
||||
|
||||
if (targetOptions.length === 0) {
|
||||
DeesToast.show({
|
||||
message: 'No migration targets available. Add a DNS provider first.',
|
||||
type: 'warning',
|
||||
duration: 3000,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const currentLabel = domain.source === 'dcrouter'
|
||||
? 'DcRouter (self)'
|
||||
: providers.find((p) => p.id === domain.providerId)?.name || 'Provider';
|
||||
|
||||
DeesModal.createAndShow({
|
||||
heading: `Migrate: ${domain.name}`,
|
||||
content: html`
|
||||
<dees-form>
|
||||
<dees-input-text
|
||||
.key=${'currentSource'}
|
||||
.label=${'Current source'}
|
||||
.value=${currentLabel}
|
||||
.disabled=${true}
|
||||
></dees-input-text>
|
||||
<dees-input-dropdown
|
||||
.key=${'target'}
|
||||
.label=${'Migrate to'}
|
||||
.description=${'Select the target DNS management'}
|
||||
.options=${targetOptions}
|
||||
.required=${true}
|
||||
></dees-input-dropdown>
|
||||
<dees-input-checkbox
|
||||
.key=${'deleteExisting'}
|
||||
.label=${'Delete existing records at provider first'}
|
||||
.description=${'Removes all records at the provider before pushing migrated records'}
|
||||
.value=${true}
|
||||
></dees-input-checkbox>
|
||||
</dees-form>
|
||||
`,
|
||||
menuOptions: [
|
||||
{ name: 'Cancel', action: async (m: any) => m.destroy() },
|
||||
{
|
||||
name: 'Migrate',
|
||||
action: async (m: any) => {
|
||||
const form = m.shadowRoot?.querySelector('.content')?.querySelector('dees-form');
|
||||
if (!form) return;
|
||||
const data = await form.collectFormData();
|
||||
const targetKey = typeof data.target === 'object' ? data.target.key : data.target;
|
||||
if (!targetKey) return;
|
||||
|
||||
let targetSource: interfaces.data.TDomainSource;
|
||||
let targetProviderId: string | undefined;
|
||||
if (targetKey === 'dcrouter') {
|
||||
targetSource = 'dcrouter';
|
||||
} else {
|
||||
targetSource = 'provider';
|
||||
targetProviderId = targetKey.replace('provider:', '');
|
||||
}
|
||||
|
||||
await appstate.domainsStatePart.dispatchAction(appstate.migrateDomainAction, {
|
||||
id: domain.id,
|
||||
targetSource,
|
||||
targetProviderId,
|
||||
deleteExistingProviderRecords: targetSource === 'provider' ? Boolean(data.deleteExisting) : false,
|
||||
});
|
||||
DeesToast.show({ message: `Domain ${domain.name} migrated successfully`, type: 'success', duration: 3000 });
|
||||
m.destroy();
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
private async deleteDomain(domain: interfaces.data.IDomain) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
DeesModal.createAndShow({
|
||||
|
||||
@@ -10,22 +10,6 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
interface INetworkRequest {
|
||||
id: string;
|
||||
timestamp: number;
|
||||
method: string;
|
||||
url: string;
|
||||
hostname: string;
|
||||
port: number;
|
||||
protocol: 'http' | 'https' | 'tcp' | 'udp';
|
||||
statusCode?: number;
|
||||
duration: number;
|
||||
bytesIn: number;
|
||||
bytesOut: number;
|
||||
remoteIp: string;
|
||||
route?: string;
|
||||
}
|
||||
|
||||
@customElement('ops-view-network-activity')
|
||||
export class OpsViewNetworkActivity extends DeesElement {
|
||||
/** How far back the traffic chart shows */
|
||||
@@ -42,9 +26,6 @@ export class OpsViewNetworkActivity extends DeesElement {
|
||||
accessor networkState = appstate.networkStatePart.getState()!;
|
||||
|
||||
|
||||
@state()
|
||||
accessor networkRequests: INetworkRequest[] = [];
|
||||
|
||||
@state()
|
||||
accessor trafficDataIn: Array<{ x: string | number; y: number }> = [];
|
||||
|
||||
@@ -314,108 +295,21 @@ export class OpsViewNetworkActivity extends DeesElement {
|
||||
<!-- Protocol Distribution Charts -->
|
||||
${this.renderProtocolCharts()}
|
||||
|
||||
<!-- Top IPs Section -->
|
||||
<!-- Top IPs by Connection Count -->
|
||||
${this.renderTopIPs()}
|
||||
|
||||
<!-- Top IPs by Bandwidth -->
|
||||
${this.renderTopIPsByBandwidth()}
|
||||
|
||||
<!-- Domain Activity -->
|
||||
${this.renderDomainActivity()}
|
||||
|
||||
<!-- Backend Protocols Section -->
|
||||
${this.renderBackendProtocols()}
|
||||
|
||||
<!-- Requests Table -->
|
||||
<dees-table
|
||||
.data=${this.networkRequests}
|
||||
.rowKey=${'id'}
|
||||
.highlightUpdates=${'flash'}
|
||||
.displayFunction=${(req: INetworkRequest) => ({
|
||||
Time: new Date(req.timestamp).toLocaleTimeString(),
|
||||
Protocol: html`<span class="protocolBadge ${req.protocol}">${req.protocol.toUpperCase()}</span>`,
|
||||
Method: req.method,
|
||||
'Host:Port': `${req.hostname}:${req.port}`,
|
||||
Path: this.truncateUrl(req.url),
|
||||
Status: this.renderStatus(req.statusCode),
|
||||
Duration: `${req.duration}ms`,
|
||||
'In/Out': `${this.formatBytes(req.bytesIn)} / ${this.formatBytes(req.bytesOut)}`,
|
||||
'Remote IP': req.remoteIp,
|
||||
})}
|
||||
.dataActions=${[
|
||||
{
|
||||
name: 'View Details',
|
||||
iconName: 'fa:magnifyingGlass',
|
||||
type: ['inRow', 'doubleClick', 'contextmenu'],
|
||||
actionFunc: async (actionData) => {
|
||||
await this.showRequestDetails(actionData.item);
|
||||
}
|
||||
}
|
||||
]}
|
||||
heading1="Recent Network Activity"
|
||||
heading2="Recent network requests"
|
||||
searchable
|
||||
.showColumnFilters=${true}
|
||||
.pagination=${true}
|
||||
.paginationSize=${50}
|
||||
dataName="request"
|
||||
></dees-table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private async showRequestDetails(request: INetworkRequest) {
|
||||
const { DeesModal } = await import('@design.estate/dees-catalog');
|
||||
|
||||
await DeesModal.createAndShow({
|
||||
heading: 'Request Details',
|
||||
content: html`
|
||||
<div style="padding: 20px;">
|
||||
<dees-dataview-codebox
|
||||
.heading=${'Request Information'}
|
||||
progLang="json"
|
||||
.codeToDisplay=${JSON.stringify({
|
||||
id: request.id,
|
||||
timestamp: new Date(request.timestamp).toISOString(),
|
||||
protocol: request.protocol,
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
hostname: request.hostname,
|
||||
port: request.port,
|
||||
statusCode: request.statusCode,
|
||||
duration: `${request.duration}ms`,
|
||||
bytesIn: request.bytesIn,
|
||||
bytesOut: request.bytesOut,
|
||||
remoteIp: request.remoteIp,
|
||||
route: request.route,
|
||||
}, null, 2)}
|
||||
></dees-dataview-codebox>
|
||||
</div>
|
||||
`,
|
||||
menuOptions: [
|
||||
{
|
||||
name: 'Copy Request ID',
|
||||
iconName: 'lucide:Copy',
|
||||
action: async () => {
|
||||
await navigator.clipboard.writeText(request.id);
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private renderStatus(statusCode?: number): TemplateResult {
|
||||
if (!statusCode) {
|
||||
return html`<span class="statusBadge warning">N/A</span>`;
|
||||
}
|
||||
|
||||
const statusClass = statusCode >= 200 && statusCode < 300 ? 'success' :
|
||||
statusCode >= 400 ? 'error' : 'warning';
|
||||
|
||||
return html`<span class="statusBadge ${statusClass}">${statusCode}</span>`;
|
||||
}
|
||||
|
||||
private truncateUrl(url: string, maxLength = 50): string {
|
||||
if (url.length <= maxLength) return url;
|
||||
return url.substring(0, maxLength - 3) + '...';
|
||||
}
|
||||
|
||||
|
||||
private formatNumber(num: number): string {
|
||||
if (num >= 1000000) {
|
||||
return (num / 1000000).toFixed(1) + 'M';
|
||||
@@ -619,6 +513,66 @@ export class OpsViewNetworkActivity extends DeesElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private renderTopIPsByBandwidth(): TemplateResult {
|
||||
if (!this.networkState.topIPsByBandwidth || this.networkState.topIPsByBandwidth.length === 0) {
|
||||
return html``;
|
||||
}
|
||||
|
||||
return html`
|
||||
<dees-table
|
||||
.data=${this.networkState.topIPsByBandwidth}
|
||||
.rowKey=${'ip'}
|
||||
.highlightUpdates=${'flash'}
|
||||
.displayFunction=${(ipData: { ip: string; count: number; bwIn: number; bwOut: number }) => {
|
||||
return {
|
||||
'IP Address': ipData.ip,
|
||||
'Bandwidth In': this.formatBitsPerSecond(ipData.bwIn),
|
||||
'Bandwidth Out': this.formatBitsPerSecond(ipData.bwOut),
|
||||
'Total Bandwidth': this.formatBitsPerSecond(ipData.bwIn + ipData.bwOut),
|
||||
'Connections': ipData.count,
|
||||
};
|
||||
}}
|
||||
heading1="Top IPs by Bandwidth"
|
||||
heading2="IPs with highest throughput"
|
||||
searchable
|
||||
.showColumnFilters=${true}
|
||||
.pagination=${false}
|
||||
dataName="ip"
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderDomainActivity(): TemplateResult {
|
||||
if (!this.networkState.domainActivity || this.networkState.domainActivity.length === 0) {
|
||||
return html``;
|
||||
}
|
||||
|
||||
return html`
|
||||
<dees-table
|
||||
.data=${this.networkState.domainActivity}
|
||||
.rowKey=${'domain'}
|
||||
.highlightUpdates=${'flash'}
|
||||
.displayFunction=${(item: interfaces.data.IDomainActivity) => {
|
||||
const totalBytesPerMin = (item.bytesInPerSecond + item.bytesOutPerSecond) * 60;
|
||||
return {
|
||||
'Domain': item.domain,
|
||||
'Throughput In': this.formatBitsPerSecond(item.bytesInPerSecond),
|
||||
'Throughput Out': this.formatBitsPerSecond(item.bytesOutPerSecond),
|
||||
'Transferred / min': this.formatBytes(totalBytesPerMin),
|
||||
'Connections': item.activeConnections,
|
||||
'Routes': item.routeCount,
|
||||
};
|
||||
}}
|
||||
heading1="Domain Activity"
|
||||
heading2="Per-domain network activity aggregated from route metrics"
|
||||
searchable
|
||||
.showColumnFilters=${true}
|
||||
.pagination=${false}
|
||||
dataName="domain"
|
||||
></dees-table>
|
||||
`;
|
||||
}
|
||||
|
||||
private renderBackendProtocols(): TemplateResult {
|
||||
const backends = this.networkState.backends;
|
||||
if (!backends || backends.length === 0) {
|
||||
@@ -730,25 +684,6 @@ export class OpsViewNetworkActivity extends DeesElement {
|
||||
this.requestsPerSecHistory.shift();
|
||||
}
|
||||
|
||||
// Reassign unconditionally so dees-table's flash diff can compare per-cell
|
||||
// values against the previous snapshot. Row identity is preserved via
|
||||
// rowKey='id', so DOM nodes are reused across ticks.
|
||||
this.networkRequests = this.networkState.connections.map((conn) => ({
|
||||
id: conn.id,
|
||||
timestamp: conn.startTime,
|
||||
method: 'GET', // Default method for proxy connections
|
||||
url: '/',
|
||||
hostname: conn.remoteAddress,
|
||||
port: conn.protocol === 'https' ? 443 : 80,
|
||||
protocol: conn.protocol === 'https' || conn.protocol === 'http' ? conn.protocol : 'tcp',
|
||||
statusCode: conn.state === 'connected' ? 200 : undefined,
|
||||
duration: Date.now() - conn.startTime,
|
||||
bytesIn: conn.bytesReceived,
|
||||
bytesOut: conn.bytesSent,
|
||||
remoteIp: conn.remoteAddress,
|
||||
route: 'proxy',
|
||||
}));
|
||||
|
||||
// Load server-side throughput history into chart (once)
|
||||
if (!this.historyLoaded && this.networkState.throughputHistory && this.networkState.throughputHistory.length > 0) {
|
||||
this.loadThroughputHistory();
|
||||
|
||||
Reference in New Issue
Block a user