atp-sdk
Version:
Official TypeScript SDK for Agent Trust Protocolâ„¢ - Build secure, verifiable, and trustworthy applications with decentralized identity, verifiable credentials, and robust access control
214 lines • 6.18 kB
JavaScript
import { BaseClient } from './base.js';
import WebSocket from 'ws';
import { EventEmitter } from 'eventemitter3';
export class GatewayClient extends BaseClient {
constructor(config) {
super(config, 'gateway');
this.eventEmitter = new EventEmitter();
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 10;
}
/**
* Get gateway status and health information
*/
async getStatus() {
return this.get('/status');
}
/**
* Get detailed health check for all services
*/
async getHealth() {
return this.get('/health');
}
/**
* Get available routes
*/
async getRoutes() {
return this.get('/routes');
}
/**
* Get connection statistics
*/
async getConnectionStats() {
return this.get('/stats/connections');
}
/**
* Get security events
*/
async getSecurityEvents(params) {
return this.get('/security/events', { params });
}
/**
* Acknowledge security event
*/
async acknowledgeSecurityEvent(eventId) {
return this.post(`/security/events/${encodeURIComponent(eventId)}/acknowledge`);
}
// Rate Limiting Management
/**
* Get rate limit status for authenticated user
*/
async getRateLimit() {
return this.get('/rate-limit');
}
/**
* Get rate limiting rules
*/
async getRateLimitRules() {
return this.get('/rate-limit/rules');
}
// TLS Certificate Management
/**
* Get certificate information
*/
async getCertificateInfo() {
return this.get('/tls/certificates');
}
/**
* Verify certificate chain
*/
async verifyCertificateChain(certificatePem) {
return this.post('/tls/verify', { certificate: certificatePem });
}
// WebSocket Real-time Features
/**
* Connect to real-time event stream
*/
async connectEventStream(options) {
const wsUrl = this.config.services.gateway?.replace('http', 'ws') ||
this.config.baseUrl.replace('http', 'ws') + ':3000';
const url = `${wsUrl}/ws/events`;
const queryParams = new URLSearchParams();
if (options?.filters) {
queryParams.append('filters', JSON.stringify(options.filters));
}
this.ws = new WebSocket(`${url}?${queryParams}`, {
headers: this.isAuthenticated() ? {
'Authorization': `Bearer ${this.config.auth.token}`
} : undefined
});
this.ws.on('open', () => {
this.reconnectAttempts = 0;
this.eventEmitter.emit('connected');
});
this.ws.on('message', (data) => {
try {
const event = JSON.parse(data.toString());
this.eventEmitter.emit('event', event);
this.eventEmitter.emit(event.type, event);
}
catch (error) {
this.eventEmitter.emit('error', new Error(`Failed to parse event: ${error}`));
}
});
this.ws.on('error', (error) => {
this.eventEmitter.emit('error', error);
});
this.ws.on('close', () => {
this.eventEmitter.emit('disconnected');
if (options?.autoReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
this.scheduleReconnect(options);
}
});
}
/**
* Disconnect from event stream
*/
disconnectEventStream() {
if (this.reconnectInterval) {
clearTimeout(this.reconnectInterval);
this.reconnectInterval = undefined;
}
if (this.ws) {
this.ws.close();
this.ws = undefined;
}
}
on(event, handler) {
this.eventEmitter.on(event, handler);
}
/**
* Unsubscribe from events
*/
off(event, handler) {
if (handler) {
this.eventEmitter.off(event, handler);
}
else {
this.eventEmitter.removeAllListeners(event);
}
}
/**
* Send command through WebSocket
*/
async sendCommand(command) {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new Error('WebSocket is not connected');
}
this.ws.send(JSON.stringify({
...command,
id: command.id || Date.now().toString(),
timestamp: new Date().toISOString()
}));
}
// Service Proxy Methods
/**
* Proxy request to any ATP service through gateway
*/
async proxyRequest(service, method, path, data) {
return this.request(method, `/proxy/${service}${path}`, data);
}
// Load Balancing and Failover
/**
* Get service discovery information
*/
async getServiceDiscovery() {
return this.get('/discovery/services');
}
/**
* Force service discovery refresh
*/
async refreshServiceDiscovery() {
return this.post('/discovery/refresh');
}
// Configuration Management
/**
* Get gateway configuration
*/
async getConfiguration() {
return this.get('/config');
}
/**
* Update gateway configuration (admin only)
*/
async updateConfiguration(config) {
return this.put('/config', config);
}
scheduleReconnect(options) {
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
this.reconnectAttempts++;
this.reconnectInterval = setTimeout(() => {
this.connectEventStream(options);
}, delay);
}
/**
* Get WebSocket connection status
*/
get connectionStatus() {
if (!this.ws)
return 'disconnected';
switch (this.ws.readyState) {
case WebSocket.OPEN: return 'connected';
case WebSocket.CONNECTING: return 'connecting';
default: return 'disconnected';
}
}
/**
* Cleanup resources
*/
cleanup() {
this.disconnectEventStream();
this.eventEmitter.removeAllListeners();
}
}
//# sourceMappingURL=gateway.js.map