handlers

package
v0.0.0-...-2dc78fc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AccountTypeDomain = "domain"
	AccountTypeWallet = "wallet"
)

Account types

View Source
const (
	DefaultLimit = 100
	MaxLimit     = 1000
)
View Source
const (
	LatencyWarningPct  = health.LatencyWarningPct
	LatencyCriticalPct = health.LatencyCriticalPct
	LossWarningPct     = health.LossWarningPct
	LossCriticalPct    = health.LossCriticalPct
	UtilWarningPct     = health.UtilWarningPct
	UtilCriticalPct    = health.UtilCriticalPct
)

Thresholds re-exported from the shared health package for local use.

View Source
const ShredGroupPK = "31fdXyG3x8k5Ache7jKNQsuwaMf44oqYQndoBsT1JfVj"

ShredGroupPK is the multicast group PK for edge-solana-shreds (formerly "bebop").

View Source
const ShredsInternalUserPayer = "331ov6bjNUTLTATEUC4m7wxdHfAE5KxWwA6ng1Y1VZh8"

ShredsInternalUserPayer is the primary UserPayer used by the Shreds product when creating access passes on behalf of clients. Passes with this payer are product-managed and should not be grouped as "same payer" matches with each other.

View Source
const ShredsInternalUserPayer2 = "3b2Ze7VYUvhwQBfx5oCMCmsc2xvyZ74s2Lata5vmQeeN"

ShredsInternalUserPayer2 is a second UserPayer used by the Shreds product.

Variables

View Source
var ErrGlobalLimitExceeded = fmt.Errorf("service daily limit reached, please try again tomorrow")

ErrGlobalLimitExceeded is returned when the global daily limit is exceeded

View Source
var ErrKillSwitch = fmt.Errorf("service temporarily unavailable")

ErrKillSwitch is returned when the kill switch is enabled

View Source
var QueryRateLimitMiddleware = RateLimitMiddleware(QueryRateLimiter)

QueryRateLimitMiddleware is middleware that uses the shared query rate limiter.

View Source
var QueryRateLimiter = NewRateLimiter(rate.Every(time.Minute/100), 20)

QueryRateLimiter is the shared rate limiter for database queries. Allows 100 queries per minute per IP with a burst of 20.

ValidEnvs contains all recognized environment values.

Functions

func BuildBurstinessQuery

func BuildBurstinessQuery(timeFilter, sortMetric, sortDir, filterSQL, intfFilterSQL, intfTypeSQL, userKindSQL string, needsUserJoin, needsInterfaceJoin, needsMetroJoin, needsContributorJoin bool, threshold float64, minBps, minPeakBps float64, limit, offset int) string

BuildBurstinessQuery builds the ClickHouse query for the burstiness endpoint. Reads from device_interface_rollup_5m. Each rollup row already represents one 5-minute bucket with max throughput, so we compute P50/P99 across buckets directly.

func BuildDrilldownQuery

func BuildDrilldownQuery(timeFilter, bucketInterval, devicePk, intfFilter string, needsInterfaceJoin bool) string

BuildDrilldownQuery builds the main ClickHouse query for the drilldown endpoint. Reads from device_interface_rollup_5m and re-aggregates into the requested bucket.

func BuildDrilldownQueryRaw

func BuildDrilldownQueryRaw(timeFilter, bucketInterval, devicePk, intfFilter string, needsInterfaceJoin bool) string

BuildDrilldownQueryRaw builds the drilldown query using raw fact_dz_device_interface_counters for sub-5m bucket granularity. Same interface as BuildDrilldownQuery.

func BuildEnvContext

func BuildEnvContext(env DZEnv, mainnetDB string) string

BuildEnvContext returns the agent system prompt context for the given environment. All agent queries run against the mainnet database by default. For other environments, the agent uses fully-qualified table names (e.g., lake_devnet.dim_devices_current).

func BuildHealthQuery

func BuildHealthQuery(timeFilter, sortMetric, sortDir, filterSQL, intfFilterSQL, intfTypeSQL, userKindSQL string, needsUserJoin, needsInterfaceJoin bool, limit int) string

BuildHealthQuery builds the ClickHouse query for the interface health endpoint.

func BuildScopedFieldValuesQuery

func BuildScopedFieldValuesQuery(entity, field string, cfg fieldConfig, r *http.Request) string

BuildScopedFieldValuesQuery builds a scoped query for dashboard-relevant entity+field combos when filter params are present. Returns empty string when no scoping is needed (caller should use the generic query).

func BuildStressQuery

func BuildStressQuery(timeFilter, bucketInterval, metric, groupBy, filterSQL, intfFilterSQL, intfTypeSQL, userKindSQL string, threshold float64,
	needsDeviceJoin, needsLinkJoin, needsMetroJoin, needsContributorJoin, needsUserJoin, needsInterfaceJoin bool) (query string, grouped bool)

BuildStressQuery builds the ClickHouse query for the stress endpoint. Reads from device_interface_rollup_5m and re-aggregates into the requested bucket.

func BuildStressQueryRaw

func BuildStressQueryRaw(timeFilter, bucketInterval, metric, groupBy, filterSQL, intfFilterSQL, intfTypeSQL, userKindSQL string, threshold float64,
	needsDeviceJoin, needsLinkJoin, needsMetroJoin, needsContributorJoin, needsUserJoin, needsInterfaceJoin bool) (query string, grouped bool)

BuildStressQueryRaw builds the stress query using raw fact_dz_device_interface_counters for sub-5m bucket granularity. Same interface as BuildStressQuery.

func BuildTopQuery

func BuildTopQuery(timeFilter, entity, sortMetric, sortDir, filterSQL, intfFilterSQL, intfTypeSQL, userKindSQL string, needsUserJoin, needsInterfaceJoin bool, limit int) string

BuildTopQuery builds the ClickHouse query for the top endpoint. Reads from device_interface_rollup_5m and aggregates across all buckets.

func CheckRateLimit

func CheckRateLimit(limiter *RateLimiter, ip string) string

CheckRateLimit checks the rate limit and returns an error message if exceeded. Returns empty string if allowed, or error message with retry time if not.

func ContextWithEnv

func ContextWithEnv(ctx context.Context, env DZEnv) context.Context

ContextWithEnv returns a new context with the given environment.

func EnvMiddleware

func EnvMiddleware(next http.Handler) http.Handler

EnvMiddleware extracts the X-DZ-Env header and stores the environment in the request context. Defaults to mainnet-beta if not provided or invalid.

func GetDZLedgerRPCURL

func GetDZLedgerRPCURL() string

func GetGlobalDailyLimit

func GetGlobalDailyLimit() int

GetGlobalDailyLimit returns the configured global daily limit (0 = unlimited)

func GetIPFromContext

func GetIPFromContext(ctx context.Context) string

GetIPFromContext returns the IP from context

func GetIPFromRequest

func GetIPFromRequest(r *http.Request) string

GetIPFromRequest extracts the client IP from request

func GetMinSOLThreshold

func GetMinSOLThreshold() int64

GetMinSOLThreshold returns the minimum SOL balance for premium tier (in lamports)

func GetSolanaRPCURL

func GetSolanaRPCURL() string

func GetWalletPremiumLimit

func GetWalletPremiumLimit() int

GetWalletPremiumLimit returns the daily question limit for premium wallet users

func IsKillSwitchEnabled

func IsKillSwitchEnabled() bool

IsKillSwitchEnabled returns true if the kill switch is active (blocks all users)

func IsPremiumWalletUser

func IsPremiumWalletUser(account *Account) bool

IsPremiumWalletUser checks if an account is a wallet user with SOL balance >= threshold

func ParseSIWSMessage

func ParseSIWSMessage(message string) (string, error)

ParseSIWSMessage extracts nonce from a SIWS message

func RateLimitMiddleware

func RateLimitMiddleware(limiter *RateLimiter) func(http.Handler) http.Handler

RateLimitMiddleware creates HTTP middleware that rate limits requests using the given limiter.

func RequireInternalDomain

func RequireInternalDomain(next http.Handler) http.Handler

RequireInternalDomain middleware returns 403 unless the user is authenticated with an email from an allowed domain (AUTH_ALLOWED_DOMAINS).

func SanitizeError

func SanitizeError(err error) string

SanitizeError removes sensitive information from error messages. Use this when you need to include some error context but want to strip credentials and internal details.

func SetAccountInContext

func SetAccountInContext(ctx context.Context, account *Account) context.Context

SetAccountInContext is a test helper that adds an account to the context. This is used for testing handlers without going through the auth middleware.

func SetQuotaHeaders

func SetQuotaHeaders(w http.ResponseWriter, quota *QuotaInfo)

SetQuotaHeaders sets the rate limit headers on response

Types

type API

type API struct {
	// ClickHouse
	DB            driver.Conn
	HealthDB      driver.Conn
	PublicQueryDB driver.Conn
	EnvDBs        map[string]driver.Conn
	EnvDatabases  map[string]string
	Database      string
	ShredderDB    string
	PublisherDB   string
	DZDPDB        string

	// PostgreSQL
	PgPool *pgxpool.Pool

	// Neo4j
	Neo4jClient   neo4j.Client
	Neo4jDatabase string

	// Build info
	BuildVersion string
	BuildCommit  string
	BuildDate    string

	// Workflow manager (manages background workflow execution)
	Manager *WorkflowManager

	// OnSlackInstallationChange is called when a Slack installation changes.
	OnSlackInstallationChange func(teamID string)
}

API holds all dependencies for HTTP handlers. It is constructed once at startup and passed through to every handler and middleware, replacing the former package-level globals in api/config.

func (*API) AutoGenerateStream

func (a *API) AutoGenerateStream(w http.ResponseWriter, r *http.Request)

AutoGenerateStream handles auto-detection of query mode and streams the generation. It first classifies the question as SQL or Cypher, then streams the appropriate query generation.

func (*API) BatchGetSessions

func (a *API) BatchGetSessions(w http.ResponseWriter, r *http.Request)

BatchGetSessions returns multiple sessions by their IDs (filtered by owner)

func (*API) CancelWorkflowRun

func (a *API) CancelWorkflowRun(ctx context.Context, id uuid.UUID) error

CancelWorkflowRun marks a workflow as cancelled.

func (*API) Chat

func (a *API) Chat(w http.ResponseWriter, r *http.Request)

func (*API) ChatStream

func (a *API) ChatStream(w http.ResponseWriter, r *http.Request)

ChatStream handles streaming chat requests with SSE progress updates.

func (*API) CheckQuota

func (a *API) CheckQuota(ctx context.Context, account *Account, ip string) (*int, error)

CheckQuota checks if the user/IP has remaining quota Returns remaining questions (nil = unlimited), and any error

func (*API) ClaimIncompleteWorkflow

func (a *API) ClaimIncompleteWorkflow(ctx context.Context, serverID string, staleTimeout time.Duration) (*WorkflowRun, error)

ClaimIncompleteWorkflow atomically claims a single incomplete workflow for resumption. This uses UPDATE ... RETURNING to ensure only one replica can claim a workflow. A workflow is claimable if: - status = 'running' - not claimed (claimed_at IS NULL), OR - claim is stale (claimed_at < NOW() - staleTimeout AND updated_at < NOW() - staleTimeout)

The stale check uses updated_at to detect if the claiming server is still making progress. Returns nil if no workflow is available to claim.

func (*API) CleanupExpiredNonces

func (a *API) CleanupExpiredNonces(ctx context.Context) error

CleanupExpiredNonces removes expired auth nonces

func (*API) CleanupExpiredSessions

func (a *API) CleanupExpiredSessions(ctx context.Context) error

CleanupExpiredSessions removes expired auth sessions

func (*API) CleanupOldUsageData

func (a *API) CleanupOldUsageData(ctx context.Context) error

CleanupOldUsageData removes usage data older than 90 days

func (*API) Complete

func (a *API) Complete(w http.ResponseWriter, r *http.Request)

Complete handles simple LLM completion requests without the full workflow. This is useful for tasks like generating titles.

func (*API) CompleteWorkflowRun

func (a *API) CompleteWorkflowRun(ctx context.Context, id uuid.UUID, answer string, finalCheckpoint *WorkflowCheckpoint) error

CompleteWorkflowRun marks a workflow as completed with the final answer.

func (*API) ConfirmSlackInstallation

func (a *API) ConfirmSlackInstallation(w http.ResponseWriter, r *http.Request)

ConfirmSlackInstallation confirms a pending takeover installation

func (*API) CreateOAuthState

func (a *API) CreateOAuthState(ctx context.Context, accountID string) (string, error)

CreateOAuthState creates a new OAuth state token tied to an account

func (*API) CreateOpsTicket

func (a *API) CreateOpsTicket(w http.ResponseWriter, r *http.Request)

CreateOpsTicket proxies POST /api/ops-tickets. Requires an internal-domain authenticated user. Sets reporter_name and reporter_email from the authenticated session.

func (*API) CreatePendingInstallation

func (a *API) CreatePendingInstallation(ctx context.Context, accountID string, tokenResp *slackOAuthResponse) (string, error)

CreatePendingInstallation stores token data for a pending takeover confirmation

func (*API) CreateSession

func (a *API) CreateSession(w http.ResponseWriter, r *http.Request)

CreateSession creates a new session owned by the current user

func (*API) CreateWorkflowRun

func (a *API) CreateWorkflowRun(ctx context.Context, sessionID uuid.UUID, question string, env ...string) (*WorkflowRun, error)

CreateWorkflowRun creates a new workflow run in the database.

func (*API) DatabaseForEnvFromContext

func (a *API) DatabaseForEnvFromContext(ctx context.Context) string

databaseForEnvFromContext returns the database name for the environment in the context.

func (*API) DeactivateSlackInstallation

func (a *API) DeactivateSlackInstallation(ctx context.Context, teamID string) error

DeactivateSlackInstallation deactivates a Slack installation by team ID

func (*API) DeleteSession

func (a *API) DeleteSession(w http.ResponseWriter, r *http.Request)

DeleteSession deletes a session by ID (must belong to current user)

func (*API) DeleteSlackInstallation

func (a *API) DeleteSlackInstallation(w http.ResponseWriter, r *http.Request)

DeleteSlackInstallation uninstalls the app from the Slack workspace and deactivates the installation

func (*API) ExecuteCypher

func (a *API) ExecuteCypher(w http.ResponseWriter, r *http.Request)

ExecuteCypher executes a Cypher query against Neo4j and returns formatted results.

func (*API) ExecuteQuery

func (a *API) ExecuteQuery(w http.ResponseWriter, r *http.Request)

func (*API) FailWorkflowRun

func (a *API) FailWorkflowRun(ctx context.Context, id uuid.UUID, errMsg string) error

FailWorkflowRun marks a workflow as failed with an error message.

func (*API) FetchBulkDeviceMetricsData

func (a *API) FetchBulkDeviceMetricsData(ctx context.Context) (*BulkDeviceMetricsResponse, error)

FetchBulkDeviceMetricsData is the exported entry point for the page cache worker.

func (*API) FetchBulkDeviceMetricsIssuesData

func (a *API) FetchBulkDeviceMetricsIssuesData(ctx context.Context) (*BulkDeviceMetricsResponse, error)

FetchBulkDeviceMetricsIssuesData is the page cache variant that only includes devices with issues.

func (*API) FetchBulkLinkMetricsData

func (a *API) FetchBulkLinkMetricsData(ctx context.Context) (*BulkLinkMetricsResponse, error)

FetchBulkLinkMetricsData is the exported entry point for the page cache worker.

func (*API) FetchBulkLinkMetricsIssuesData

func (a *API) FetchBulkLinkMetricsIssuesData(ctx context.Context) (*BulkLinkMetricsResponse, error)

FetchBulkLinkMetricsIssuesData is the page cache variant that only includes links with issues. It reuses FetchBulkLinkMetricsData (which fetches all links in a single pass) and post-filters, since the page cache worker amortizes the cost and both cache entries share the same query work.

func (*API) FetchDefaultDeviceIncidentsData

func (a *API) FetchDefaultDeviceIncidentsData(ctx context.Context) *DeviceIncidentsResponse

FetchDefaultDeviceIncidentsData fetches device incidents data with default parameters for caching.

func (*API) FetchDefaultIncidentsData

func (a *API) FetchDefaultIncidentsData(ctx context.Context) *LinkIncidentsResponse

FetchDefaultIncidentsData fetches incidents data with default parameters for caching.

func (*API) FetchDeviceHistoryData

func (a *API) FetchDeviceHistoryData(ctx context.Context, timeRange string, requestedBuckets int, filters ...statusFilter) (*DeviceHistoryResponse, error)

FetchDeviceHistoryData delegates to the rollup-based implementation.

func (*API) FetchEdgeScoreboardData

func (a *API) FetchEdgeScoreboardData(ctx context.Context, window string, leadersOnly bool, sinceSlot uint64, beforeSlot uint64, slotLimit int) (*EdgeScoreboardResponse, error)

FetchEdgeScoreboardData performs the actual edge scoreboard queries. When leadersOnly is true, results are scoped to slots where the leader published via DZ. sinceSlot > 0 or beforeSlot > 0 enables cursor mode: only recent_slots are returned and heavy query groups (feed stats, metros, etc.) are skipped. sinceSlot returns slots > sinceSlot in ASC order; beforeSlot returns slots < beforeSlot in DESC order. slotLimit controls how many recent slots to return (default 200, max 1000).

func (*API) FetchEdgeScoreboardLatest

func (a *API) FetchEdgeScoreboardLatest(ctx context.Context, leadersOnly bool, slotLimit int) (*EdgeScoreboardResponse, error)

FetchEdgeScoreboardLatest fetches just the latest N slots (recent_slots + slot_leaders). Skips the heavy aggregate queries. Intended for the fast page-cache refresher so live-tail polls can be served from cache rather than hitting ClickHouse every few seconds.

func (*API) FetchGeoConcentrationData

func (a *API) FetchGeoConcentrationData(ctx context.Context) (*GeoConcentrationResponse, error)

func (*API) FetchGeoValidatorsData

func (a *API) FetchGeoValidatorsData(ctx context.Context, metro, dzFilter string) (*GeoValidatorsResponse, error)

func (*API) FetchLatencyComparisonData

func (a *API) FetchLatencyComparisonData(ctx context.Context) (*LatencyComparisonResponse, error)

FetchLatencyComparisonData fetches DZ vs Internet latency comparison data. Used by both the handler and the cache.

func (*API) FetchLinkHistoryData

func (a *API) FetchLinkHistoryData(ctx context.Context, timeRange string, requestedBuckets int, filters ...statusFilter) (*LinkHistoryResponse, error)

FetchLinkHistoryData delegates to the rollup-based implementation.

func (*API) FetchMetroPathLatencyData

func (a *API) FetchMetroPathLatencyData(ctx context.Context, optimize string) (*MetroPathLatencyResponse, error)

FetchMetroPathLatencyData fetches metro path latency data for the given optimization strategy. Used by both the handler and the cache.

func (*API) FetchPublisherCheckData

func (a *API) FetchPublisherCheckData(ctx context.Context, q string, epochsParam, slotsParam int) (*PublisherCheckResponse, error)

FetchPublisherCheckData performs the actual publisher check query.

func (*API) FetchShredSubscribers

func (a *API) FetchShredSubscribers(ctx context.Context, funder string, limit, offset int) ([]ShredSubscriberRow, uint64, error)

FetchShredSubscribers returns a page of shred subscribers (client seats), optionally filtered by funder pubkey (funding_authority_key, exact match). Ordered by active_epoch DESC, pk ASC.

func (*API) FetchStakeOverviewData

func (a *API) FetchStakeOverviewData(ctx context.Context) (*StakeOverview, error)

FetchStakeOverviewData fetches stake overview data from ClickHouse.

func (*API) FetchStatusData

func (a *API) FetchStatusData(ctx context.Context) *StatusResponse

FetchStatusData performs the actual status data fetch from the database. This is called by both the cache refresh and direct requests.

func (*API) FetchTopologyData

func (a *API) FetchTopologyData(ctx context.Context) (TopologyResponse, error)

FetchTopologyData performs the actual topology data fetch from the database. This is called by both the cache refresh and direct requests.

func (*API) FetchValidatorPerfData

func (a *API) FetchValidatorPerfData(ctx context.Context) (*ValidatorPerfResponse, error)

FetchValidatorPerfData fetches aggregated validator performance data.

func (*API) FetchValidatorsMetadata

func (a *API) FetchValidatorsMetadata(ctx context.Context) ([]ValidatorMetadataRow, error)

FetchValidatorsMetadata returns active validator metadata ordered by active_stake DESC.

func (*API) GenerateCypher

func (a *API) GenerateCypher(w http.ResponseWriter, r *http.Request)

GenerateCypher handles synchronous Cypher generation requests.

func (*API) GenerateCypherStream

func (a *API) GenerateCypherStream(w http.ResponseWriter, r *http.Request)

GenerateCypherStream streams the Cypher generation with SSE.

func (*API) GenerateSQL

func (a *API) GenerateSQL(w http.ResponseWriter, r *http.Request)

func (*API) GenerateSQLStream

func (a *API) GenerateSQLStream(w http.ResponseWriter, r *http.Request)

GenerateSQLStream streams the SQL generation with SSE

func (*API) GetAccessPass

func (a *API) GetAccessPass(w http.ResponseWriter, r *http.Request)

func (*API) GetAccessPassConnections

func (a *API) GetAccessPassConnections(w http.ResponseWriter, r *http.Request)

func (*API) GetAccessPasses

func (a *API) GetAccessPasses(w http.ResponseWriter, r *http.Request)

func (*API) GetAccountByToken

func (a *API) GetAccountByToken(ctx context.Context, token string) (*Account, error)

GetAccountByToken retrieves an account by session token

func (*API) GetAuthMe

func (a *API) GetAuthMe(w http.ResponseWriter, r *http.Request)

GetAuthMe handles GET /api/auth/me

func (*API) GetAuthNonce

func (a *API) GetAuthNonce(w http.ResponseWriter, r *http.Request)

GetAuthNonce handles GET /api/auth/nonce - returns a nonce for wallet signing

func (*API) GetBulkDeviceMetrics

func (a *API) GetBulkDeviceMetrics(w http.ResponseWriter, r *http.Request)

GetBulkDeviceMetrics handles GET /api/device-metrics. It returns metrics for all devices in a single response.

func (*API) GetBulkLinkMetrics

func (a *API) GetBulkLinkMetrics(w http.ResponseWriter, r *http.Request)

GetBulkLinkMetrics handles GET /api/link-metrics. It returns metrics for all links in a single response.

func (*API) GetCatalog

func (a *API) GetCatalog(w http.ResponseWriter, r *http.Request)

func (*API) GetConfig

func (a *API) GetConfig(w http.ResponseWriter, r *http.Request)

GetConfig returns public configuration for the frontend

func (*API) GetContributor

func (a *API) GetContributor(w http.ResponseWriter, r *http.Request)

func (*API) GetContributors

func (a *API) GetContributors(w http.ResponseWriter, r *http.Request)
func (a *API) GetCriticalLinks(w http.ResponseWriter, r *http.Request)

GetCriticalLinks returns links that are critical for network connectivity Critical links are identified based on node degrees and connectivity patterns

func (*API) GetDZLedger

func (a *API) GetDZLedger(w http.ResponseWriter, r *http.Request)

GetDZLedger returns ledger telemetry for the DZ chain.

func (*API) GetDevice

func (a *API) GetDevice(w http.ResponseWriter, r *http.Request)

func (*API) GetDeviceHistory

func (a *API) GetDeviceHistory(w http.ResponseWriter, r *http.Request)

func (*API) GetDeviceIncidents

func (a *API) GetDeviceIncidents(w http.ResponseWriter, r *http.Request)

GetDeviceIncidents returns incidents for devices with active and drained views

func (*API) GetDeviceIncidentsCSV

func (a *API) GetDeviceIncidentsCSV(w http.ResponseWriter, r *http.Request)

GetDeviceIncidentsCSV returns device incidents as a CSV download

func (*API) GetDeviceInterfaceHistory

func (a *API) GetDeviceInterfaceHistory(w http.ResponseWriter, r *http.Request)

GetDeviceInterfaceHistory returns interface-level history for a specific device

func (*API) GetDeviceMetrics

func (a *API) GetDeviceMetrics(w http.ResponseWriter, r *http.Request)

GetDeviceMetrics handles GET /api/device-metrics/{pk}. It returns all metrics for a single device in a unified bucket structure.

func (*API) GetDeviceValidatorStats

func (a *API) GetDeviceValidatorStats(w http.ResponseWriter, r *http.Request)

func (*API) GetDevices

func (a *API) GetDevices(w http.ResponseWriter, r *http.Request)

func (*API) GetDiscardsData

func (a *API) GetDiscardsData(w http.ResponseWriter, r *http.Request)

GetDiscardsData returns discard data for all device-interfaces

func (*API) GetEdgeScoreboard

func (a *API) GetEdgeScoreboard(w http.ResponseWriter, r *http.Request)

GetEdgeScoreboard returns aggregated win rate / completeness data for DZ Edge nodes.

func (*API) GetEntityTraffic

func (a *API) GetEntityTraffic(w http.ResponseWriter, r *http.Request)

func (*API) GetFacilities

func (a *API) GetFacilities(w http.ResponseWriter, r *http.Request)

func (*API) GetFacility

func (a *API) GetFacility(w http.ResponseWriter, r *http.Request)

func (*API) GetFailureImpact

func (a *API) GetFailureImpact(w http.ResponseWriter, r *http.Request)

GetFailureImpact returns devices that would become unreachable if a device goes down

func (*API) GetFieldValues

func (a *API) GetFieldValues(w http.ResponseWriter, r *http.Request)

GetFieldValues returns distinct values for a given entity field

func (*API) GetGeoConcentration

func (a *API) GetGeoConcentration(w http.ResponseWriter, r *http.Request)

func (*API) GetGeoValidators

func (a *API) GetGeoValidators(w http.ResponseWriter, r *http.Request)

func (*API) GetGeolocExplorer

func (a *API) GetGeolocExplorer(w http.ResponseWriter, r *http.Request)

func (*API) GetGeolocProbes

func (a *API) GetGeolocProbes(w http.ResponseWriter, r *http.Request)

func (*API) GetGeolocUsers

func (a *API) GetGeolocUsers(w http.ResponseWriter, r *http.Request)

func (*API) GetGlobalUsageToday

func (a *API) GetGlobalUsageToday(ctx context.Context) (int, error)

GetGlobalUsageToday returns the total questions asked today across all users

func (*API) GetGossipNode

func (a *API) GetGossipNode(w http.ResponseWriter, r *http.Request)

func (*API) GetGossipNodes

func (a *API) GetGossipNodes(w http.ResponseWriter, r *http.Request)

func (*API) GetISISPath

func (a *API) GetISISPath(w http.ResponseWriter, r *http.Request)

GetISISPath finds the shortest path between two devices using ISIS metrics

func (*API) GetISISPaths

func (a *API) GetISISPaths(w http.ResponseWriter, r *http.Request)

GetISISPaths finds K-shortest paths between two devices using Yen's algorithm in-memory. Paths are ranked by lowest total ISIS metric (latency proxy), then enriched with measured latency.

func (*API) GetISISTopology

func (a *API) GetISISTopology(w http.ResponseWriter, r *http.Request)

GetISISTopology returns the full ISIS topology graph from ClickHouse

func (*API) GetIncompleteWorkflows

func (a *API) GetIncompleteWorkflows(ctx context.Context) ([]WorkflowRun, error)

GetIncompleteWorkflows returns all workflows with status='running'. Note: For distributed resumption, use ClaimIncompleteWorkflow instead.

func (*API) GetInterfaceIssues

func (a *API) GetInterfaceIssues(w http.ResponseWriter, r *http.Request)

GetInterfaceIssues returns interface issues for a given time range

func (*API) GetLatencyComparison

func (a *API) GetLatencyComparison(w http.ResponseWriter, r *http.Request)

func (*API) GetLatencyHistory

func (a *API) GetLatencyHistory(w http.ResponseWriter, r *http.Request)

GetLatencyHistory returns time-series latency data for a specific metro pair

func (*API) GetLatestWorkflowForSession

func (a *API) GetLatestWorkflowForSession(ctx context.Context, sessionID uuid.UUID) (*WorkflowRun, error)

GetLatestWorkflowForSession returns the most recent workflow for a session, regardless of status.

func (a *API) GetLink(w http.ResponseWriter, r *http.Request)

func (*API) GetLinkHealth

func (a *API) GetLinkHealth(w http.ResponseWriter, r *http.Request)

func (*API) GetLinkHistory

func (a *API) GetLinkHistory(w http.ResponseWriter, r *http.Request)

func (*API) GetLinkIncidents

func (a *API) GetLinkIncidents(w http.ResponseWriter, r *http.Request)

GetLinkIncidents returns incidents for links with active and drained views

func (*API) GetLinkIncidentsCSV

func (a *API) GetLinkIncidentsCSV(w http.ResponseWriter, r *http.Request)

GetLinkIncidentsCSV returns link incidents as a CSV download

func (*API) GetLinkLatencyData

func (a *API) GetLinkLatencyData(w http.ResponseWriter, r *http.Request)

GetLinkLatencyData returns per-link aggregated latency summary data. Supports filtering by device, device_a, device_z, contributor, link_type.

func (*API) GetLinkMetrics

func (a *API) GetLinkMetrics(w http.ResponseWriter, r *http.Request)

GetLinkMetrics handles GET /api/link-metrics/{pk}. It returns all metrics for a single link in a unified bucket structure.

func (a *API) GetLinks(w http.ResponseWriter, r *http.Request)

func (*API) GetMetro

func (a *API) GetMetro(w http.ResponseWriter, r *http.Request)

func (*API) GetMetroConnectivity

func (a *API) GetMetroConnectivity(w http.ResponseWriter, r *http.Request)

GetMetroConnectivity returns the connectivity matrix between all metros

func (*API) GetMetroDevicePaths

func (a *API) GetMetroDevicePaths(w http.ResponseWriter, r *http.Request)

GetMetroDevicePaths returns all paths between devices in two metros Query params: from (metro PK), to (metro PK)

func (*API) GetMetroPathDetail

func (a *API) GetMetroPathDetail(w http.ResponseWriter, r *http.Request)

GetMetroPathDetail returns detailed path breakdown between two metros

func (*API) GetMetroPathLatency

func (a *API) GetMetroPathLatency(w http.ResponseWriter, r *http.Request)

GetMetroPathLatency returns path-based latency between all metro pairs with configurable optimization strategy (hops, latency, or bandwidth)

func (*API) GetMetroPaths

func (a *API) GetMetroPaths(w http.ResponseWriter, r *http.Request)

GetMetroPaths returns distinct paths between two metros

func (*API) GetMetroStats

func (a *API) GetMetroStats(w http.ResponseWriter, r *http.Request)

func (*API) GetMetros

func (a *API) GetMetros(w http.ResponseWriter, r *http.Request)

func (*API) GetMultiLinkLatencyHistory

func (a *API) GetMultiLinkLatencyHistory(w http.ResponseWriter, r *http.Request)

GetMultiLinkLatencyHistory returns time-series latency data for multiple links.

Modes (via "mode" query param):

  • "per_link" (default): returns per-link time series, grouped by link_pk. Requires "pks" param (comma-separated link PKs, max 20).
  • "aggregate": returns a single aggregated time series across all matching links. Uses the same filter params as GetLinkLatencyData (device, contributor, link_type).

func (*API) GetMulticastGroup

func (a *API) GetMulticastGroup(w http.ResponseWriter, r *http.Request)

func (*API) GetMulticastGroupMemberCounts

func (a *API) GetMulticastGroupMemberCounts(w http.ResponseWriter, r *http.Request)

func (*API) GetMulticastGroupMembers

func (a *API) GetMulticastGroupMembers(w http.ResponseWriter, r *http.Request)

func (*API) GetMulticastGroupShredStats

func (a *API) GetMulticastGroupShredStats(w http.ResponseWriter, r *http.Request)

GetMulticastGroupShredStats returns time-bucketed shred stats for publishers in a multicast group. Only meaningful for groups backed by publisher_shred_stats (e.g. edge-solana-shreds).

func (*API) GetMulticastGroupTraffic

func (a *API) GetMulticastGroupTraffic(w http.ResponseWriter, r *http.Request)

func (*API) GetMulticastGroups

func (a *API) GetMulticastGroups(w http.ResponseWriter, r *http.Request)

func (*API) GetMulticastTreePaths

func (a *API) GetMulticastTreePaths(w http.ResponseWriter, r *http.Request)

GetMulticastTreePaths computes paths from all publishers to all subscribers in a multicast group

func (*API) GetMulticastTreeSegments

func (a *API) GetMulticastTreeSegments(w http.ResponseWriter, r *http.Request)

GetMulticastTreeSegments computes aggregated segments from publisher→subscriber paths. Instead of returning full hop-by-hop paths, it returns unique (fromPK, toPK) pairs with the set of publishers that traverse each segment. Uses batched Dijkstra queries (one per publisher) instead of one per (publisher, subscriber) pair.

func (*API) GetOpsAssignees

func (a *API) GetOpsAssignees(w http.ResponseWriter, r *http.Request)

GetOpsAssignees serves GET /api/ops-tickets/assignees. Builds the contributor list directly from ClickHouse dz_contributors_current. The upstream /assignee-options endpoint was removed in API v1.1.0.

func (*API) GetOpsTicketHistory

func (a *API) GetOpsTicketHistory(w http.ResponseWriter, r *http.Request)

GetOpsTicketHistory proxies GET /api/ops-tickets/history Required query param: entity_pk (link or device pubkey). Optional: limit (default 5), type (incident|maintenance). No auth required.

func (*API) GetOpsTickets

func (a *API) GetOpsTickets(w http.ResponseWriter, r *http.Request)

GetOpsTickets proxies GET /api/ops-tickets Query param: status=active (default) or any single status value. The upstream API understands "active" and "not_active" as presets. No auth required.

func (*API) GetPeeringDBFacility

func (a *API) GetPeeringDBFacility(w http.ResponseWriter, r *http.Request)

func (*API) GetPublisherCheck

func (a *API) GetPublisherCheck(w http.ResponseWriter, r *http.Request)

func (*API) GetQuotaForAccount

func (a *API) GetQuotaForAccount(ctx context.Context, account *Account, ip string) (*QuotaInfo, error)

GetQuotaForAccount returns quota info for an account (or anonymous by IP)

func (*API) GetRedundancyReport

func (a *API) GetRedundancyReport(w http.ResponseWriter, r *http.Request)

GetRedundancyReport returns a comprehensive redundancy analysis report

func (*API) GetRunningWorkflowForSession

func (a *API) GetRunningWorkflowForSession(ctx context.Context, sessionID uuid.UUID) (*WorkflowRun, error)

GetRunningWorkflowForSession returns the currently running workflow for a session, if any.

func (*API) GetSession

func (a *API) GetSession(w http.ResponseWriter, r *http.Request)

GetSession returns a single session by ID (must belong to current user)

func (*API) GetSessionEnv

func (a *API) GetSessionEnv(ctx context.Context, sessionID uuid.UUID) (string, error)

GetSessionEnv returns the environment from the most recent workflow run for a session. Returns empty string if no workflow runs exist for the session.

func (*API) GetShredClientSeats

func (a *API) GetShredClientSeats(w http.ResponseWriter, r *http.Request)

func (*API) GetShredDeviceHistories

func (a *API) GetShredDeviceHistories(w http.ResponseWriter, r *http.Request)

func (*API) GetShredDevices

func (a *API) GetShredDevices(w http.ResponseWriter, r *http.Request)

func (*API) GetShredEpochRevenue

func (a *API) GetShredEpochRevenue(w http.ResponseWriter, r *http.Request)

func (*API) GetShredEscrowEvents

func (a *API) GetShredEscrowEvents(w http.ResponseWriter, r *http.Request)

func (*API) GetShredFunders

func (a *API) GetShredFunders(w http.ResponseWriter, r *http.Request)

func (*API) GetShredMetroHistories

func (a *API) GetShredMetroHistories(w http.ResponseWriter, r *http.Request)

func (*API) GetShredSubscriberHistory

func (a *API) GetShredSubscriberHistory(w http.ResponseWriter, r *http.Request)

func (*API) GetShredsOverview

func (a *API) GetShredsOverview(w http.ResponseWriter, r *http.Request)

func (*API) GetSimulateLinkAddition

func (a *API) GetSimulateLinkAddition(w http.ResponseWriter, r *http.Request)

GetSimulateLinkAddition simulates adding a link and shows the benefits

func (*API) GetSimulateLinkRemoval

func (a *API) GetSimulateLinkRemoval(w http.ResponseWriter, r *http.Request)

GetSimulateLinkRemoval simulates removing a link and shows the impact

func (*API) GetSingleDeviceHistory

func (a *API) GetSingleDeviceHistory(w http.ResponseWriter, r *http.Request)

GetSingleDeviceHistory returns the status history for a single device

func (*API) GetSingleLinkHistory

func (a *API) GetSingleLinkHistory(w http.ResponseWriter, r *http.Request)

GetSingleLinkHistory returns the status history for a single link

func (*API) GetSlackInstallationByTeamID

func (a *API) GetSlackInstallationByTeamID(ctx context.Context, teamID string) (*SlackInstallation, error)

GetSlackInstallationByTeamID returns an active installation by team ID

func (*API) GetSlackInstallations

func (a *API) GetSlackInstallations(w http.ResponseWriter, r *http.Request)

GetSlackInstallations returns active Slack installations

func (*API) GetSlackOAuthCallback

func (a *API) GetSlackOAuthCallback(w http.ResponseWriter, r *http.Request)

GetSlackOAuthCallback handles the Slack OAuth callback

func (*API) GetSlackOAuthStart

func (a *API) GetSlackOAuthStart(w http.ResponseWriter, r *http.Request)

GetSlackOAuthStart initiates the Slack OAuth flow

func (*API) GetSolanaLedger

func (a *API) GetSolanaLedger(w http.ResponseWriter, r *http.Request)

GetSolanaLedger returns ledger telemetry for Solana.

func (*API) GetStakeChanges

func (a *API) GetStakeChanges(w http.ResponseWriter, r *http.Request)

func (*API) GetStakeHistory

func (a *API) GetStakeHistory(w http.ResponseWriter, r *http.Request)

func (*API) GetStakeOverview

func (a *API) GetStakeOverview(w http.ResponseWriter, r *http.Request)

func (*API) GetStakeValidators

func (a *API) GetStakeValidators(w http.ResponseWriter, r *http.Request)

func (*API) GetStats

func (a *API) GetStats(w http.ResponseWriter, r *http.Request)

func (*API) GetStatus

func (a *API) GetStatus(w http.ResponseWriter, r *http.Request)

func (*API) GetSwapRate

func (a *API) GetSwapRate(w http.ResponseWriter, r *http.Request)

func (*API) GetTenant

func (a *API) GetTenant(w http.ResponseWriter, r *http.Request)

func (*API) GetTenants

func (a *API) GetTenants(w http.ResponseWriter, r *http.Request)

func (*API) GetTimeline

func (a *API) GetTimeline(w http.ResponseWriter, r *http.Request)

GetTimeline returns timeline events across the network

func (*API) GetTimelineBounds

func (a *API) GetTimelineBounds(w http.ResponseWriter, r *http.Request)

GetTimelineBounds returns the available date range for timeline data

func (*API) GetTopology

func (a *API) GetTopology(w http.ResponseWriter, r *http.Request)

func (*API) GetTopologyCompare

func (a *API) GetTopologyCompare(w http.ResponseWriter, r *http.Request)

GetTopologyCompare compares configured links vs ISIS adjacencies using ClickHouse

func (*API) GetTopologyLinkMetrics

func (a *API) GetTopologyLinkMetrics(w http.ResponseWriter, r *http.Request)

func (*API) GetTopologyValidators

func (a *API) GetTopologyValidators(w http.ResponseWriter, r *http.Request)

func (*API) GetTrafficDashboardBurstiness

func (a *API) GetTrafficDashboardBurstiness(w http.ResponseWriter, r *http.Request)

func (*API) GetTrafficDashboardDrilldown

func (a *API) GetTrafficDashboardDrilldown(w http.ResponseWriter, r *http.Request)

func (*API) GetTrafficDashboardHealth

func (a *API) GetTrafficDashboardHealth(w http.ResponseWriter, r *http.Request)

func (*API) GetTrafficDashboardStress

func (a *API) GetTrafficDashboardStress(w http.ResponseWriter, r *http.Request)

func (*API) GetTrafficDashboardTop

func (a *API) GetTrafficDashboardTop(w http.ResponseWriter, r *http.Request)

func (*API) GetTrafficData

func (a *API) GetTrafficData(w http.ResponseWriter, r *http.Request)

func (*API) GetUsageQuota

func (a *API) GetUsageQuota(w http.ResponseWriter, r *http.Request)

GetUsageQuota handles GET /api/usage/quota

func (*API) GetUsageToday

func (a *API) GetUsageToday(ctx context.Context, account *Account, ip string) (*UsageRecord, error)

GetUsageToday returns today's usage for an account or IP

func (*API) GetUser

func (a *API) GetUser(w http.ResponseWriter, r *http.Request)

func (*API) GetUserMulticastGroups

func (a *API) GetUserMulticastGroups(w http.ResponseWriter, r *http.Request)

func (*API) GetUserTraffic

func (a *API) GetUserTraffic(w http.ResponseWriter, r *http.Request)

func (*API) GetUsers

func (a *API) GetUsers(w http.ResponseWriter, r *http.Request)

func (*API) GetValidator

func (a *API) GetValidator(w http.ResponseWriter, r *http.Request)

func (*API) GetValidatorPerformance

func (a *API) GetValidatorPerformance(w http.ResponseWriter, r *http.Request)

GetValidatorPerformance returns aggregated validator performance comparing DZ vs non-DZ.

func (*API) GetValidators

func (a *API) GetValidators(w http.ResponseWriter, r *http.Request)

func (*API) GetVersion

func (a *API) GetVersion(w http.ResponseWriter, r *http.Request)

GetVersion returns the current build version info.

func (*API) GetWorkflow

func (a *API) GetWorkflow(w http.ResponseWriter, r *http.Request)

GetWorkflow handles GET /api/workflows/{id}

func (*API) GetWorkflowForSession

func (a *API) GetWorkflowForSession(w http.ResponseWriter, r *http.Request)

GetWorkflowForSession handles GET /api/sessions/{id}/workflow Returns the most recent workflow for a session (running, completed, or failed). Use ?status=running to get only running workflows (legacy behavior).

func (*API) GetWorkflowRun

func (a *API) GetWorkflowRun(ctx context.Context, id uuid.UUID) (*WorkflowRun, error)

GetWorkflowRun retrieves a workflow run by ID.

func (*API) IncrementQuestionCount

func (a *API) IncrementQuestionCount(ctx context.Context, account *Account, ip string) error

IncrementQuestionCount is a convenience function to increment just the question count

func (*API) InitMCP

func (a *API) InitMCP() http.Handler

InitMCP initializes the MCP server and returns the HTTP handler. This should be called once during startup.

func (*API) InitUsageMetrics

func (a *API) InitUsageMetrics(ctx context.Context)

InitUsageMetrics initializes usage metrics on startup

func (*API) ListSessions

func (a *API) ListSessions(w http.ResponseWriter, r *http.Request)

ListSessions returns a paginated list of sessions for the current user

func (*API) ListSlackInstallations

func (a *API) ListSlackInstallations(ctx context.Context, accountID string) ([]SlackInstallation, error)

ListSlackInstallations returns active installations for a specific account

func (*API) NewDBQuerier

func (a *API) NewDBQuerier() *DBQuerier

NewDBQuerier creates a new DBQuerier.

func (*API) NewDBSchemaFetcher

func (a *API) NewDBSchemaFetcher() *DBSchemaFetcher

NewDBSchemaFetcher creates a new DBSchemaFetcher.

func (*API) NewNeo4jQuerier

func (a *API) NewNeo4jQuerier() *Neo4jQuerier

NewNeo4jQuerier creates a new Neo4jQuerier.

func (*API) NewNeo4jSchemaFetcher

func (a *API) NewNeo4jSchemaFetcher() *Neo4jSchemaFetcher

NewNeo4jSchemaFetcher creates a new Neo4jSchemaFetcher.

func (*API) OptionalAuth

func (a *API) OptionalAuth(next http.Handler) http.Handler

OptionalAuth middleware attaches user to context if authenticated, allows anonymous

func (*API) PostAuthGoogle

func (a *API) PostAuthGoogle(w http.ResponseWriter, r *http.Request)

PostAuthGoogle handles POST /api/auth/google - verifies Google ID token and creates session

func (*API) PostAuthLogout

func (a *API) PostAuthLogout(w http.ResponseWriter, r *http.Request)

PostAuthLogout handles POST /api/auth/logout

func (*API) PostAuthWallet

func (a *API) PostAuthWallet(w http.ResponseWriter, r *http.Request)

PostAuthWallet handles POST /api/auth/wallet - verifies wallet signature and creates session

func (*API) PostMaintenanceImpact

func (a *API) PostMaintenanceImpact(w http.ResponseWriter, r *http.Request)

PostMaintenanceImpact analyzes the impact of taking multiple devices/links offline

func (*API) PostWhatIfRemoval

func (a *API) PostWhatIfRemoval(w http.ResponseWriter, r *http.Request)

PostWhatIfRemoval analyzes the impact of removing devices and/or links

func (*API) RecommendVisualization

func (a *API) RecommendVisualization(w http.ResponseWriter, r *http.Request)

func (*API) RecordUsage

func (a *API) RecordUsage(ctx context.Context, account *Account, ip string, usage UsageRecord) error

RecordUsage records usage for a question/workflow

func (*API) RequireAuth

func (a *API) RequireAuth(next http.Handler) http.Handler

RequireAuth middleware returns 401 if not authenticated

func (*API) RequireNeo4jMiddleware

func (a *API) RequireNeo4jMiddleware(next http.Handler) http.Handler

RequireNeo4jMiddleware returns 503 for non-mainnet requests on Neo4j-dependent endpoints, since Neo4j only contains mainnet data.

func (*API) RunCleanupTasks

func (a *API) RunCleanupTasks(ctx context.Context)

RunCleanupTasks runs all cleanup tasks (call periodically)

func (*API) Search

func (a *API) Search(w http.ResponseWriter, r *http.Request)

Search handles the full search endpoint

func (*API) SearchAutocomplete

func (a *API) SearchAutocomplete(w http.ResponseWriter, r *http.Request)

SearchAutocomplete handles the autocomplete endpoint

func (*API) StartCleanupWorker

func (a *API) StartCleanupWorker(ctx context.Context)

StartCleanupWorker starts a background worker that periodically cleans up expired data

func (*API) StartDailyResetWorker

func (a *API) StartDailyResetWorker(ctx context.Context)

StartDailyResetWorker starts a worker that resets daily metrics at midnight UTC

func (*API) StreamWorkflow

func (a *API) StreamWorkflow(w http.ResponseWriter, r *http.Request)

StreamWorkflow handles GET /api/workflows/{id}/stream This enables reconnection to running workflows or replaying completed ones.

func (*API) UpdateSession

func (a *API) UpdateSession(w http.ResponseWriter, r *http.Request)

UpdateSession updates an existing session (must belong to current user)

func (*API) UpdateWorkflowCheckpoint

func (a *API) UpdateWorkflowCheckpoint(ctx context.Context, id uuid.UUID, checkpoint *WorkflowCheckpoint) error

UpdateWorkflowCheckpoint updates the checkpoint state of a workflow run.

func (*API) UpsertSlackInstallation

func (a *API) UpsertSlackInstallation(ctx context.Context, teamID, teamName, botToken, botUserID, scope, installedBy string) error

UpsertSlackInstallation creates or updates a Slack installation

func (*API) ValidateOAuthState

func (a *API) ValidateOAuthState(ctx context.Context, state string) (string, error)

ValidateOAuthState validates and consumes an OAuth state token, returning the account ID

func (*API) WritePageCache

func (a *API) WritePageCache(ctx context.Context, key string, value any) error

WritePageCache upserts a cache entry in Postgres.

type AccessPassConnection

type AccessPassConnection struct {
	PK          string `json:"pk"`
	OwnerPubkey string `json:"owner_pubkey"`
	Status      string `json:"status"`
	Kind        string `json:"kind"`
	DzIP        string `json:"dz_ip"`
	ClientIP    string `json:"client_ip"`
	DeviceCode  string `json:"device_code"`
	MetroCode   string `json:"metro_code"`
	TenantCode  string `json:"tenant_code"`
}

type AccessPassDetail

type AccessPassDetail struct {
	PK                  string                `json:"pk"`
	OwnerPubkey         string                `json:"owner_pubkey"`
	TypeTag             string                `json:"type_tag"`
	Status              string                `json:"status"`
	ClientIP            string                `json:"client_ip"`
	UserPayer           string                `json:"user_payer"`
	AssociatedPubkey    string                `json:"associated_pubkey"`
	OthersTypeName      string                `json:"others_type_name"`
	OthersKey           string                `json:"others_key"`
	LastAccessEpoch     uint64                `json:"last_access_epoch"`
	ConnectionCount     uint16                `json:"connection_count"`
	Flags               uint8                 `json:"flags"`
	MGroupPubAllowlist  []MulticastGroupRef   `json:"mgroup_pub_allowlist"`
	MGroupSubAllowlist  []MulticastGroupRef   `json:"mgroup_sub_allowlist"`
	ValidatorVotePubkey string                `json:"validator_vote_pubkey,omitempty"`
	ValidatorNodePubkey string                `json:"validator_node_pubkey,omitempty"`
	ShredsSeat          *AccessPassShredsSeat `json:"shreds_seat,omitempty"`
}

type AccessPassListItem

type AccessPassListItem struct {
	PK               string `json:"pk"`
	OwnerPubkey      string `json:"owner_pubkey"`
	TypeTag          string `json:"type_tag"`
	Status           string `json:"status"`
	ClientIP         string `json:"client_ip"`
	ConnectionCount  uint16 `json:"connection_count"`
	AssociatedPubkey string `json:"associated_pubkey"`
	FirstPubCode     string `json:"first_pub_code"`
	FirstSubCode     string `json:"first_sub_code"`
}

type AccessPassShredsSeat

type AccessPassShredsSeat struct {
	PK                   string `json:"pk"`
	DeviceKey            string `json:"device_key"`
	DeviceCode           string `json:"device_code"`
	MetroPK              string `json:"metro_pk"`
	MetroCode            string `json:"metro_code"`
	TenureEpochs         uint16 `json:"tenure_epochs"`
	FundedEpoch          uint64 `json:"funded_epoch"`
	ActiveEpoch          uint64 `json:"active_epoch"`
	EscrowCount          uint32 `json:"escrow_count"`
	TotalUSDCBalance     uint64 `json:"total_usdc_balance"`
	PricePerEpochDollars int64  `json:"price_per_epoch_dollars"`
	FundingAuthorityKey  string `json:"funding_authority_key"`
}

AccessPassShredsSeat is embedded in AccessPassDetail when the access pass belongs to the Shreds product (user_payer == ShredsInternalUserPayer).

type Account

type Account struct {
	ID                  uuid.UUID  `json:"id"`
	AccountType         string     `json:"account_type"`
	WalletAddress       *string    `json:"wallet_address,omitempty"`
	Email               *string    `json:"email,omitempty"`
	EmailDomain         *string    `json:"email_domain,omitempty"`
	GoogleID            *string    `json:"google_id,omitempty"`
	DisplayName         *string    `json:"display_name,omitempty"`
	SolBalance          *int64     `json:"sol_balance,omitempty"`
	SolBalanceUpdatedAt *time.Time `json:"sol_balance_updated_at,omitempty"`
	IsActive            bool       `json:"is_active"`
	IsInternalUser      bool       `json:"is_internal_user"`
	CreatedAt           time.Time  `json:"created_at"`
	UpdatedAt           time.Time  `json:"updated_at"`
	LastLoginAt         *time.Time `json:"last_login_at,omitempty"`
}

Account represents a user account

func GetAccountFromContext

func GetAccountFromContext(ctx context.Context) *Account

GetAccountFromContext returns the account from context, or nil if not authenticated

type AffectedLink struct {
	SourceDevice string `json:"sourceDevice"` // Device code in source metro
	TargetDevice string `json:"targetDevice"` // Device code in target metro
	Status       string `json:"status"`       // "offline" (device going down) or "rerouted"
}

AffectedLink represents a specific link affected by maintenance

type AffectedMetroPair

type AffectedMetroPair struct {
	SourceMetro   string         `json:"sourceMetro"`
	TargetMetro   string         `json:"targetMetro"`
	AffectedLinks []AffectedLink `json:"affectedLinks"` // Specific links affected
	Status        string         `json:"status"`        // "reduced", "degraded", or "disconnected"
}

AffectedMetroPair represents connectivity impact between two metros

type AffectedPath

type AffectedPath struct {
	FromPK       string `json:"fromPK"`
	FromCode     string `json:"fromCode"`
	ToPK         string `json:"toPK"`
	ToCode       string `json:"toCode"`
	BeforeHops   int    `json:"beforeHops"`
	BeforeMetric uint32 `json:"beforeMetric"`
	AfterHops    int    `json:"afterHops,omitempty"`   // 0 if no alternate path
	AfterMetric  uint32 `json:"afterMetric,omitempty"` // 0 if no alternate path
	HasAlternate bool   `json:"hasAlternate"`
}

AffectedPath represents a path that would be affected by link removal

type AuthSession

type AuthSession struct {
	ID        uuid.UUID `json:"id"`
	AccountID uuid.UUID `json:"account_id"`
	TokenHash string    `json:"-"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
}

AuthSession represents an authentication session

type AutoGenerateRequest

type AutoGenerateRequest struct {
	Prompt       string `json:"prompt"`
	CurrentQuery string `json:"currentQuery,omitempty"`
}

type AutocompleteResponse

type AutocompleteResponse struct {
	Suggestions []SearchSuggestion `json:"suggestions"`
}

AutocompleteResponse is the response for the autocomplete endpoint

type BatchGetSessionsRequest

type BatchGetSessionsRequest struct {
	IDs []uuid.UUID `json:"ids"`
}

BatchGetSessionsRequest is the request body for batch fetching sessions

type BatchGetSessionsRequestWithOwner

type BatchGetSessionsRequestWithOwner struct {
	IDs         []uuid.UUID `json:"ids"`
	AnonymousID *string     `json:"anonymous_id,omitempty"`
}

BatchGetSessionsRequestWithOwner includes anonymous_id

type BatchGetSessionsResponse

type BatchGetSessionsResponse struct {
	Sessions []Session `json:"sessions"`
}

BatchGetSessionsResponse is the response for batch fetching sessions

type BulkDeviceMetricsResponse

type BulkDeviceMetricsResponse struct {
	TimeRange     string                            `json:"time_range"`
	BucketSeconds int                               `json:"bucket_seconds"`
	BucketCount   int                               `json:"bucket_count"`
	Devices       map[string]*DeviceMetricsResponse `json:"devices"`
}

BulkDeviceMetricsResponse wraps metrics for multiple devices.

type BulkLinkMetricsResponse

type BulkLinkMetricsResponse struct {
	TimeRange     string                          `json:"time_range"`
	BucketSeconds int                             `json:"bucket_seconds"`
	BucketCount   int                             `json:"bucket_count"`
	Links         map[string]*LinkMetricsResponse `json:"links"`
}

BulkLinkMetricsResponse wraps metrics for multiple links.

type BurstinessEntity

type BurstinessEntity struct {
	DevicePk        string  `json:"device_pk"`
	DeviceCode      string  `json:"device_code"`
	Intf            string  `json:"intf"`
	MetroCode       string  `json:"metro_code"`
	ContributorCode string  `json:"contributor_code"`
	BandwidthBps    float64 `json:"bandwidth_bps"`
	P50Bps          float64 `json:"p50_bps"`
	P95Bps          float64 `json:"p95_bps"`
	SpikeCount      uint64  `json:"spike_count"`
	TotalBuckets    uint64  `json:"total_buckets"`
	MaxSpikeBps     float64 `json:"max_spike_bps"`
	MaxSpikeRatio   float64 `json:"max_spike_ratio"`
	LastSpikeTime   string  `json:"last_spike_time"`
	PeakDirection   string  `json:"peak_direction"`
}

type BurstinessResponse

type BurstinessResponse struct {
	Entities []BurstinessEntity `json:"entities"`
	Total    uint64             `json:"total"`
}

type CatalogResponse

type CatalogResponse struct {
	Tables []TableInfo `json:"tables"`
}

type ChangeSummary

type ChangeSummary struct {
	JoinedCount      int     `json:"joined_count"`
	JoinedStakeSol   float64 `json:"joined_stake_sol"`
	LeftCount        int     `json:"left_count"`
	LeftStakeSol     float64 `json:"left_stake_sol"`
	StakeIncreaseSol float64 `json:"stake_increase_sol"`
	StakeDecreaseSol float64 `json:"stake_decrease_sol"`
	NetChangeSol     float64 `json:"net_change_sol"`
}

type ChatMessage

type ChatMessage struct {
	Role            string   `json:"role"` // "user" or "assistant"
	Content         string   `json:"content"`
	Env             string   `json:"env,omitempty"`             // Environment this message was sent in
	ExecutedQueries []string `json:"executedQueries,omitempty"` // SQL from previous turns
}

ChatMessage represents a single message in conversation history.

type ChatRequest

type ChatRequest struct {
	Message     string        `json:"message"`
	History     []ChatMessage `json:"history"`
	SessionID   string        `json:"session_id,omitempty"`   // Optional session ID for workflow persistence
	Format      string        `json:"format,omitempty"`       // Output format: "slack" for Slack-specific formatting
	AnonymousID string        `json:"anonymous_id,omitempty"` // For anonymous users to prove session ownership
}

ChatRequest is the incoming request for a chat message.

type ChatResponse

type ChatResponse struct {
	// The final synthesized answer
	Answer string `json:"answer"`

	// Workflow steps (for transparency)
	DataQuestions    []DataQuestionResponse   `json:"dataQuestions,omitempty"`
	GeneratedQueries []GeneratedQueryResponse `json:"generatedQueries,omitempty"`
	ExecutedQueries  []ExecutedQueryResponse  `json:"executedQueries,omitempty"`

	// Thinking steps from the agent (for timeline display)
	ThinkingSteps []string `json:"thinking_steps,omitempty"`

	// Unified steps in execution order (thinking + queries interleaved)
	Steps []WorkflowStep `json:"steps,omitempty"`

	// Suggested follow-up questions
	FollowUpQuestions []string `json:"followUpQuestions,omitempty"`

	// Error if workflow failed
	Error string `json:"error,omitempty"`
}

ChatResponse is the full workflow result returned to the UI.

type ClientProcessingStep

type ClientProcessingStep struct {
	ID   string `json:"id"`   // Unique identifier for this step
	Type string `json:"type"` // "thinking", "sql_query", "cypher_query", "read_docs"

	// For thinking steps
	Content string `json:"content,omitempty"`

	// For sql_query steps
	Question string   `json:"question,omitempty"`
	SQL      string   `json:"sql,omitempty"`
	Status   string   `json:"status,omitempty"`
	Rows     int      `json:"rows,omitempty"` // Row count
	Columns  []string `json:"columns,omitempty"`
	Data     [][]any  `json:"data,omitempty"` // Actual row data
	Error    string   `json:"error,omitempty"`

	// For cypher_query steps
	Cypher string `json:"cypher,omitempty"`
	Nodes  []any  `json:"nodes,omitempty"`
	Edges  []any  `json:"edges,omitempty"`

	// For read_docs steps
	Page string `json:"page,omitempty"`

	// Environment this step was executed in
	Env string `json:"env,omitempty"`
}

ClientProcessingStep matches the web's ProcessingStep format. Type determines which fields are populated:

  • "thinking": Content
  • "sql_query": Question, SQL, Status, Rows (count), Columns, Data, Error
  • "cypher_query": Question, Cypher, Status, Rows (count), Nodes, Edges, Error
  • "read_docs": Page, Status, Content, Error

type CompleteRequest

type CompleteRequest struct {
	Message string `json:"message"`
}

CompleteRequest is the request for a simple LLM completion.

type CompleteResponse

type CompleteResponse struct {
	Response string `json:"response"`
	Error    string `json:"error,omitempty"`
}

CompleteResponse is the response from a simple LLM completion.

type ContributorDetail

type ContributorDetail struct {
	PK                         string  `json:"pk"`
	Code                       string  `json:"code"`
	Name                       string  `json:"name"`
	DeviceCount                uint64  `json:"device_count"`
	SideADevices               uint64  `json:"side_a_devices"`
	SideZDevices               uint64  `json:"side_z_devices"`
	LinkCount                  uint64  `json:"link_count"`
	UserCount                  uint64  `json:"user_count"`
	UnicastUsersCount          uint64  `json:"unicast_users_count"`
	MulticastSubscribersCount  uint64  `json:"multicast_subscribers_count"`
	MulticastPublishersCount   uint64  `json:"multicast_publishers_count"`
	MaxUsers                   int64   `json:"max_users"`
	MaxUnicastUsers            uint64  `json:"max_unicast_users"`
	MaxMulticastSubscribers    uint64  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers     uint64  `json:"max_multicast_publishers"`
	RawMaxUnicastUsers         uint64  `json:"raw_max_unicast_users"`
	RawMaxMulticastSubscribers uint64  `json:"raw_max_multicast_subscribers"`
	RawMaxMulticastPublishers  uint64  `json:"raw_max_multicast_publishers"`
	InBps                      float64 `json:"in_bps"`
	OutBps                     float64 `json:"out_bps"`
}

type ContributorEntity

type ContributorEntity struct {
	PK   string `json:"pk"`
	Code string `json:"code"`
	Name string `json:"name"`
}

ContributorEntity represents a contributor's current state

type ContributorListItem

type ContributorListItem struct {
	PK            string `json:"pk"`
	Code          string `json:"code"`
	Name          string `json:"name"`
	MetroCount    uint64 `json:"metro_count"`
	FacilityCount uint64 `json:"facility_count"`
	DeviceCount   uint64 `json:"device_count"`
	SideADevices  uint64 `json:"side_a_devices"`
	SideZDevices  uint64 `json:"side_z_devices"`
	LinkCount     uint64 `json:"link_count"`
	UserCount     uint64 `json:"user_count"`
	MaxUsers      int64  `json:"max_users"`
}

type CreateOpsTicketRequest

type CreateOpsTicketRequest struct {
	Type                OpsTicketType `json:"type"`
	Title               string        `json:"title"`
	Description         string        `json:"description"`
	Severity            *string       `json:"severity,omitempty"`
	Status              string        `json:"status"`
	AffectedLinkPubkeys []string      `json:"affected_link_pubkey,omitempty"`
	DevicePubkeys       []string      `json:"device_pubkey,omitempty"`
	StartAt             *string       `json:"start_at,omitempty"`
	EndAt               *string       `json:"end_at,omitempty"`
	ContributorPubkey   *string       `json:"contributor_pubkey"`
	ReporterName        string        `json:"reporter_name"`
	ReporterEmail       string        `json:"reporter_email"`
}

CreateOpsTicketRequest is the body for POST /api/ops-tickets.

type CreateSessionRequest

type CreateSessionRequest struct {
	ID      uuid.UUID       `json:"id"`
	Type    string          `json:"type"`
	Name    *string         `json:"name"`
	Content json.RawMessage `json:"content"`
}

CreateSessionRequest is the request body for creating a session

type CreateSessionRequestWithOwner

type CreateSessionRequestWithOwner struct {
	ID          uuid.UUID       `json:"id"`
	Type        string          `json:"type"`
	Name        *string         `json:"name"`
	Content     json.RawMessage `json:"content"`
	AnonymousID *string         `json:"anonymous_id,omitempty"`
}

CreateSessionRequest is the request body for creating a session

type CriticalLink struct {
	SourcePK    string `json:"sourcePK"`
	SourceCode  string `json:"sourceCode"`
	TargetPK    string `json:"targetPK"`
	TargetCode  string `json:"targetCode"`
	Metric      uint32 `json:"metric"`
	Criticality string `json:"criticality"` // "critical", "important", "redundant"
}

CriticalLink represents a link that is critical for network connectivity

type CriticalLinksResponse

type CriticalLinksResponse struct {
	Links []CriticalLink `json:"links"`
	Error string         `json:"error,omitempty"`
}

CriticalLinksResponse is the response for the critical links endpoint

type CypherQueryRequest

type CypherQueryRequest struct {
	Query string `json:"query"`
}

type CypherQueryResponse

type CypherQueryResponse struct {
	Columns   []string         `json:"columns"`
	Rows      []map[string]any `json:"rows"`
	RowCount  int              `json:"row_count"`
	ElapsedMs int64            `json:"elapsed_ms"`
	Error     string           `json:"error,omitempty"`
}

type DBQuerier

type DBQuerier struct {
	// contains filtered or unexported fields
}

DBQuerier implements workflow.Querier using a ClickHouse connection.

func (*DBQuerier) Query

func (q *DBQuerier) Query(ctx context.Context, sql string) (workflow.QueryResult, error)

Query executes a SQL query and returns the result. Agent queries always run against the mainnet database. To query other environments, use fully-qualified table names (e.g., lake_devnet.dim_devices_current).

type DBSchemaFetcher

type DBSchemaFetcher struct {
	// contains filtered or unexported fields
}

DBSchemaFetcher implements workflow.SchemaFetcher using a ClickHouse connection.

func (*DBSchemaFetcher) FetchSchema

func (f *DBSchemaFetcher) FetchSchema(ctx context.Context) (string, error)

FetchSchema retrieves table columns and view definitions from ClickHouse. Schema is always fetched from the mainnet database. Results are cached for 60 seconds to avoid redundant queries under load.

type DZEnv

type DZEnv string

DZEnv represents a DoubleZero network environment.

const (
	EnvMainnet DZEnv = "mainnet-beta"
	EnvDevnet  DZEnv = "devnet"
	EnvTestnet DZEnv = "testnet"
)

func EnvFromContext

func EnvFromContext(ctx context.Context) DZEnv

EnvFromContext returns the environment from the context, defaulting to mainnet.

type DataQuestionResponse

type DataQuestionResponse struct {
	Question  string `json:"question"`
	Rationale string `json:"rationale"`
}

DataQuestionResponse represents a decomposed data question.

type Device

type Device struct {
	PK                        string            `json:"pk"`
	Code                      string            `json:"code"`
	Status                    string            `json:"status"`
	DeviceType                string            `json:"device_type"`
	MetroPK                   string            `json:"metro_pk"`
	ContributorPK             string            `json:"contributor_pk"`
	ContributorCode           string            `json:"contributor_code"`
	UserCount                 uint64            `json:"user_count"`
	UnicastUsersCount         uint16            `json:"unicast_users_count"`
	MulticastSubscribersCount uint16            `json:"multicast_subscribers_count"`
	MulticastPublishersCount  uint16            `json:"multicast_publishers_count"`
	MaxUnicastUsers           uint16            `json:"max_unicast_users"`
	MaxMulticastSubscribers   uint16            `json:"max_multicast_subscribers"`
	MaxMulticastPublishers    uint16            `json:"max_multicast_publishers"`
	ValidatorCount            uint64            `json:"validator_count"`
	StakeSol                  float64           `json:"stake_sol"`
	StakeShare                float64           `json:"stake_share"`
	Interfaces                []DeviceInterface `json:"interfaces"`
}

type DeviceDetail

type DeviceDetail struct {
	PK                        string                  `json:"pk"`
	Code                      string                  `json:"code"`
	Status                    string                  `json:"status"`
	DeviceType                string                  `json:"device_type"`
	ContributorPK             string                  `json:"contributor_pk"`
	ContributorCode           string                  `json:"contributor_code"`
	MetroPK                   string                  `json:"metro_pk"`
	MetroCode                 string                  `json:"metro_code"`
	MetroName                 string                  `json:"metro_name"`
	PublicIP                  string                  `json:"public_ip"`
	MaxUsers                  int32                   `json:"max_users"`
	CurrentUsers              uint64                  `json:"current_users"`
	UnicastUsers              uint64                  `json:"unicast_users"`
	MulticastUsers            uint64                  `json:"multicast_users"`
	MaxUnicastUsers           uint16                  `json:"max_unicast_users"`
	MaxMulticastSubscribers   uint16                  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers    uint16                  `json:"max_multicast_publishers"`
	UnicastUsersCount         uint16                  `json:"unicast_users_count"`
	MulticastSubscribersCount uint16                  `json:"multicast_subscribers_count"`
	ReservedSeats             uint16                  `json:"reserved_seats"`
	MulticastPublishersCount  uint16                  `json:"multicast_publishers_count"`
	InBps                     float64                 `json:"in_bps"`
	OutBps                    float64                 `json:"out_bps"`
	PeakInBps                 float64                 `json:"peak_in_bps"`
	PeakOutBps                float64                 `json:"peak_out_bps"`
	Interfaces                []DeviceDetailInterface `json:"interfaces"`
}

type DeviceDetailInterface

type DeviceDetailInterface struct {
	Name               string `json:"name"`
	IP                 string `json:"ip"`
	Status             string `json:"status"`
	InterfaceType      string `json:"interface_type"`
	CYOAType           string `json:"cyoa_type"`
	DIAType            string `json:"dia_type"`
	LoopbackType       string `json:"loopback_type"`
	RoutingMode        string `json:"routing_mode"`
	Bandwidth          uint64 `json:"bandwidth"`
	Cir                uint64 `json:"cir"`
	Mtu                uint16 `json:"mtu"`
	VlanID             uint16 `json:"vlan_id"`
	NodeSegmentIdx     uint16 `json:"node_segment_idx"`
	UserTunnelEndpoint bool   `json:"user_tunnel_endpoint"`
}

type DeviceEntity

type DeviceEntity struct {
	PK            string `json:"pk"`
	Code          string `json:"code"`
	Status        string `json:"status"`
	DeviceType    string `json:"device_type"`
	PublicIP      string `json:"public_ip"`
	ContributorPK string `json:"contributor_pk"`
	MetroPK       string `json:"metro_pk"`
	MaxUsers      int32  `json:"max_users"`
	// Joined fields
	ContributorCode string `json:"contributor_code,omitempty"`
	MetroCode       string `json:"metro_code,omitempty"`
}

DeviceEntity represents a device's current state

type DeviceHistory

type DeviceHistory struct {
	PK           string             `json:"pk"`
	Code         string             `json:"code"`
	DeviceType   string             `json:"device_type"`
	Contributor  string             `json:"contributor"`
	Metro        string             `json:"metro"`
	MaxUsers     int32              `json:"max_users"`
	Hours        []DeviceHourStatus `json:"hours"`
	IssueReasons []string           `json:"issue_reasons"` // "interface_errors", "discards", "carrier_transitions", "drained", "isis_overload", "isis_unreachable"
}

type DeviceHistoryResponse

type DeviceHistoryResponse struct {
	Devices       []DeviceHistory `json:"devices"`
	TimeRange     string          `json:"time_range"`
	BucketMinutes int             `json:"bucket_minutes"`
	BucketCount   int             `json:"bucket_count"`
}

type DeviceHourStatus

type DeviceHourStatus struct {
	Hour               string  `json:"hour"`
	Status             string  `json:"status"`               // "healthy", "degraded", "unhealthy", "no_data", "disabled"
	Collecting         bool    `json:"collecting,omitempty"` // true for the current incomplete bucket
	CurrentUsers       int32   `json:"current_users"`
	MaxUsers           int32   `json:"max_users"`
	UtilizationPct     float64 `json:"utilization_pct"`
	InErrors           uint64  `json:"in_errors"`
	OutErrors          uint64  `json:"out_errors"`
	InFcsErrors        uint64  `json:"in_fcs_errors"`
	InDiscards         uint64  `json:"in_discards"`
	OutDiscards        uint64  `json:"out_discards"`
	CarrierTransitions uint64  `json:"carrier_transitions"`
	DrainStatus        string  `json:"drain_status,omitempty"` // "", "soft-drained", "hard-drained", "suspended"
	NoProbes           bool    `json:"no_probes,omitempty"`    // true when device has interface data but no latency probes
	// ISIS state
	ISISOverload    bool `json:"isis_overload,omitempty"`    // true when device is in ISIS overload state
	ISISUnreachable bool `json:"isis_unreachable,omitempty"` // true when device is unreachable in ISIS topology
}

Device history types for status timeline

type DeviceIncident

type DeviceIncident struct {
	ID                 string   `json:"id"`
	DevicePK           string   `json:"device_pk"`
	DeviceCode         string   `json:"device_code"`
	DeviceType         string   `json:"device_type"`
	Metro              string   `json:"metro"`
	ContributorCode    string   `json:"contributor_code"`
	IncidentType       string   `json:"incident_type"` // errors, discards, carrier, no_data
	ThresholdCount     *int64   `json:"threshold_count,omitempty"`
	PeakCount          *int64   `json:"peak_count,omitempty"`
	StartedAt          string   `json:"started_at"`
	EndedAt            *string  `json:"ended_at,omitempty"`
	DurationSeconds    *int64   `json:"duration_seconds,omitempty"`
	IsOngoing          bool     `json:"is_ongoing"`
	Confirmed          bool     `json:"confirmed"`
	IsDrained          bool     `json:"is_drained"`
	Severity           string   `json:"severity"` // "degraded" or "incident"
	AffectedInterfaces []string `json:"affected_interfaces,omitempty"`
}

DeviceIncident represents a discrete incident event on a device

type DeviceIncidentsResponse

type DeviceIncidentsResponse struct {
	Active         []DeviceIncident       `json:"active"`
	Drained        []DrainedDeviceInfo    `json:"drained"`
	ActiveSummary  DeviceIncidentsSummary `json:"active_summary"`
	DrainedSummary DrainedSummary         `json:"drained_summary"`
}

DeviceIncidentsResponse is the API response for device incidents

type DeviceIncidentsSummary

type DeviceIncidentsSummary struct {
	Total   int            `json:"total"`
	Ongoing int            `json:"ongoing"`
	ByType  map[string]int `json:"by_type"`
}

DeviceIncidentsSummary contains aggregate counts for active device incidents

type DeviceInterface

type DeviceInterface struct {
	Name   string `json:"name"`
	IP     string `json:"ip"`
	Status string `json:"status"`
}

type DeviceInterfaceHistoryResponse

type DeviceInterfaceHistoryResponse struct {
	Interfaces    []InterfaceHistory `json:"interfaces"`
	TimeRange     string             `json:"time_range"`
	BucketMinutes int                `json:"bucket_minutes"`
	BucketCount   int                `json:"bucket_count"`
}

DeviceInterfaceHistoryResponse is the response for device interface history endpoint

type DeviceInterfaceTraffic

type DeviceInterfaceTraffic struct {
	Intf               string  `json:"intf"`
	LinkPK             string  `json:"link_pk,omitempty"`
	LinkCode           string  `json:"link_code,omitempty"`
	LinkSide           string  `json:"link_side,omitempty"`
	UserPK             string  `json:"user_pk,omitempty"`
	CYOAType           string  `json:"cyoa_type,omitempty"`
	InBps              float64 `json:"in_bps"`
	P50InBps           float64 `json:"p50_in_bps"`
	P90InBps           float64 `json:"p90_in_bps"`
	P95InBps           float64 `json:"p95_in_bps"`
	P99InBps           float64 `json:"p99_in_bps"`
	MaxInBps           float64 `json:"max_in_bps"`
	OutBps             float64 `json:"out_bps"`
	P50OutBps          float64 `json:"p50_out_bps"`
	P90OutBps          float64 `json:"p90_out_bps"`
	P95OutBps          float64 `json:"p95_out_bps"`
	P99OutBps          float64 `json:"p99_out_bps"`
	MaxOutBps          float64 `json:"max_out_bps"`
	InErrors           uint64  `json:"in_errors"`
	OutErrors          uint64  `json:"out_errors"`
	InFcsErrors        uint64  `json:"in_fcs_errors"`
	InDiscards         uint64  `json:"in_discards"`
	OutDiscards        uint64  `json:"out_discards"`
	CarrierTransitions uint64  `json:"carrier_transitions"`
}

DeviceInterfaceTraffic holds per-interface traffic for a single bucket.

type DeviceListItem

type DeviceListItem struct {
	PK                        string  `json:"pk"`
	Code                      string  `json:"code"`
	Status                    string  `json:"status"`
	DeviceType                string  `json:"device_type"`
	ContributorPK             string  `json:"contributor_pk"`
	ContributorCode           string  `json:"contributor_code"`
	MetroPK                   string  `json:"metro_pk"`
	MetroCode                 string  `json:"metro_code"`
	LocationPK                string  `json:"location_pk"`
	LocationCode              string  `json:"location_code"`
	PublicIP                  string  `json:"public_ip"`
	MaxUsers                  int32   `json:"max_users"`
	CurrentUsers              uint64  `json:"current_users"`
	UnicastUsers              uint64  `json:"unicast_users"`
	MulticastUsers            uint64  `json:"multicast_users"`
	MaxUnicastUsers           uint16  `json:"max_unicast_users"`
	MaxMulticastSubscribers   uint16  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers    uint16  `json:"max_multicast_publishers"`
	UnicastUsersCount         uint16  `json:"unicast_users_count"`
	MulticastSubscribersCount uint16  `json:"multicast_subscribers_count"`
	ReservedSeats             uint16  `json:"reserved_seats"`
	MulticastPublishersCount  uint16  `json:"multicast_publishers_count"`
	InBps                     float64 `json:"in_bps"`
	OutBps                    float64 `json:"out_bps"`
	PeakInBps                 float64 `json:"peak_in_bps"`
	PeakOutBps                float64 `json:"peak_out_bps"`
}

type DeviceMetricsBucket

type DeviceMetricsBucket struct {
	TS         string                   `json:"ts"`
	Status     *DeviceMetricsStatus     `json:"status,omitempty"`
	Traffic    *DeviceMetricsTraffic    `json:"traffic,omitempty"`
	Interfaces []DeviceInterfaceTraffic `json:"interfaces,omitempty"`
}

DeviceMetricsBucket holds all metric categories for a single time bucket.

type DeviceMetricsResponse

type DeviceMetricsResponse struct {
	DevicePK        string                `json:"device_pk"`
	DeviceCode      string                `json:"device_code"`
	DeviceType      string                `json:"device_type"`
	ContributorCode string                `json:"contributor_code"`
	ContributorPK   string                `json:"contributor_pk"`
	Metro           string                `json:"metro"`
	MaxUsers        int32                 `json:"max_users"`
	TimeRange       string                `json:"time_range"`
	BucketSeconds   int                   `json:"bucket_seconds"`
	BucketCount     int                   `json:"bucket_count"`
	Buckets         []DeviceMetricsBucket `json:"buckets"`
	StatusChanges   []EntityStatusChange  `json:"status_changes,omitempty"`
}

DeviceMetricsResponse is the top-level response for GET /api/device-metrics/{pk}.

type DeviceMetricsStatus

type DeviceMetricsStatus struct {
	Health          string `json:"health"`
	DrainStatus     string `json:"drain_status"`
	Collecting      bool   `json:"collecting"`
	ISISOverload    bool   `json:"isis_overload"`
	ISISUnreachable bool   `json:"isis_unreachable"`
	NoProbes        bool   `json:"no_probes"`
}

DeviceMetricsStatus represents health/drain/ISIS state for a bucket.

type DeviceMetricsTraffic

type DeviceMetricsTraffic struct {
	InBps              float64 `json:"in_bps"`
	P50InBps           float64 `json:"p50_in_bps"`
	P90InBps           float64 `json:"p90_in_bps"`
	P95InBps           float64 `json:"p95_in_bps"`
	P99InBps           float64 `json:"p99_in_bps"`
	MaxInBps           float64 `json:"max_in_bps"`
	OutBps             float64 `json:"out_bps"`
	P50OutBps          float64 `json:"p50_out_bps"`
	P90OutBps          float64 `json:"p90_out_bps"`
	P95OutBps          float64 `json:"p95_out_bps"`
	P99OutBps          float64 `json:"p99_out_bps"`
	MaxOutBps          float64 `json:"max_out_bps"`
	InPps              float64 `json:"in_pps"`
	P50InPps           float64 `json:"p50_in_pps"`
	P90InPps           float64 `json:"p90_in_pps"`
	P95InPps           float64 `json:"p95_in_pps"`
	P99InPps           float64 `json:"p99_in_pps"`
	MaxInPps           float64 `json:"max_in_pps"`
	OutPps             float64 `json:"out_pps"`
	P50OutPps          float64 `json:"p50_out_pps"`
	P90OutPps          float64 `json:"p90_out_pps"`
	P95OutPps          float64 `json:"p95_out_pps"`
	P99OutPps          float64 `json:"p99_out_pps"`
	MaxOutPps          float64 `json:"max_out_pps"`
	InErrors           uint64  `json:"in_errors"`
	OutErrors          uint64  `json:"out_errors"`
	InFcsErrors        uint64  `json:"in_fcs_errors"`
	InDiscards         uint64  `json:"in_discards"`
	OutDiscards        uint64  `json:"out_discards"`
	CarrierTransitions uint64  `json:"carrier_transitions"`
}

DeviceMetricsTraffic holds aggregated throughput and interface counters.

type DeviceUtilization

type DeviceUtilization struct {
	PK           string  `json:"pk"`
	Code         string  `json:"code"`
	DeviceType   string  `json:"device_type"`
	Contributor  string  `json:"contributor"`
	Metro        string  `json:"metro"`
	CurrentUsers int32   `json:"current_users"`
	MaxUsers     int32   `json:"max_users"`
	Utilization  float64 `json:"utilization"` // percentage
}

type DeviceValidatorStats

type DeviceValidatorStats struct {
	ValidatorCount uint64  `json:"validator_count"`
	StakeSol       float64 `json:"stake_sol"`
	StakeShare     float64 `json:"stake_share"`
}

type DiscardSeriesInfo

type DiscardSeriesInfo struct {
	Key    string `json:"key"`
	Device string `json:"device"`
	Intf   string `json:"intf"`
	Total  int64  `json:"total"`
}

DiscardSeriesInfo describes a discard series for filtering

type DiscardSeriesMean

type DiscardSeriesMean struct {
	Device string
	Intf   string
	Total  int64
}

DiscardSeriesMean is used to accumulate discard totals

type DiscardsDataResponse

type DiscardsDataResponse struct {
	Points []DiscardsPoint     `json:"points"`
	Series []DiscardSeriesInfo `json:"series"`
}

DiscardsDataResponse is the response for the discards endpoint

type DiscardsPoint

type DiscardsPoint struct {
	Time        string `json:"time"`
	DevicePk    string `json:"device_pk"`
	Device      string `json:"device"`
	Intf        string `json:"intf"`
	InDiscards  int64  `json:"in_discards"`
	OutDiscards int64  `json:"out_discards"`
}

DiscardsPoint represents a single data point for discards

type DrainedDeviceInfo

type DrainedDeviceInfo struct {
	DevicePK        string           `json:"device_pk"`
	DeviceCode      string           `json:"device_code"`
	DeviceType      string           `json:"device_type"`
	Metro           string           `json:"metro"`
	ContributorCode string           `json:"contributor_code"`
	DrainStatus     string           `json:"drain_status"`
	DrainedSince    string           `json:"drained_since"`
	ActiveIncidents []DeviceIncident `json:"active_incidents"`
	RecentIncidents []DeviceIncident `json:"recent_incidents"`
	LastIncidentEnd *string          `json:"last_incident_end,omitempty"`
	ClearForSeconds *int64           `json:"clear_for_seconds,omitempty"`
	Readiness       string           `json:"readiness"` // "red", "yellow", "green", "gray"
}

DrainedDeviceInfo represents a drained device with its incident status

type DrainedLinkInfo

type DrainedLinkInfo struct {
	LinkPK          string         `json:"link_pk"`
	LinkCode        string         `json:"link_code"`
	LinkType        string         `json:"link_type"`
	SideAMetro      string         `json:"side_a_metro"`
	SideZMetro      string         `json:"side_z_metro"`
	ContributorCode string         `json:"contributor_code"`
	DrainStatus     string         `json:"drain_status"`
	DrainedSince    string         `json:"drained_since"`
	ActiveIncidents []LinkIncident `json:"active_incidents"`
	RecentIncidents []LinkIncident `json:"recent_incidents"`
	LastIncidentEnd *string        `json:"last_incident_end,omitempty"`
	ClearForSeconds *int64         `json:"clear_for_seconds,omitempty"`
	Readiness       string         `json:"readiness"` // "red", "yellow", "green", "gray"
}

DrainedLinkInfo represents a drained link with its incident status

type DrainedSummary

type DrainedSummary struct {
	Total         int `json:"total"`
	WithIncidents int `json:"with_incidents"`
	Ready         int `json:"ready"`
	NotReady      int `json:"not_ready"`
}

DrainedSummary contains aggregate counts for drained links

type DrilldownPoint

type DrilldownPoint struct {
	Time        string  `json:"time"`
	Intf        string  `json:"intf"`
	InBps       float64 `json:"in_bps"`
	OutBps      float64 `json:"out_bps"`
	InDiscards  int64   `json:"in_discards"`
	OutDiscards int64   `json:"out_discards"`
	InPps       float64 `json:"in_pps"`
	OutPps      float64 `json:"out_pps"`
}

type DrilldownResponse

type DrilldownResponse struct {
	Points    []DrilldownPoint  `json:"points"`
	Series    []DrilldownSeries `json:"series"`
	EffBucket string            `json:"effective_bucket"`
}

type DrilldownSeries

type DrilldownSeries struct {
	Intf         string  `json:"intf"`
	BandwidthBps float64 `json:"bandwidth_bps"`
	LinkType     string  `json:"link_type"`
}

type EdgeScoreboardFeedStats

type EdgeScoreboardFeedStats struct {
	ShredsWon   uint64                   `json:"shreds_won"`
	TotalShreds uint64                   `json:"total_shreds"`
	WinRatePct  float64                  `json:"win_rate_pct"`
	LeadTimes   []EdgeScoreboardLeadTime `json:"lead_times"`
}

EdgeScoreboardFeedStats holds per-feed win rate and pairwise lead time stats for an edge node.

type EdgeScoreboardLeadTime

type EdgeScoreboardLeadTime struct {
	LoserFeed string  `json:"loser_feed"`
	P50Ms     float64 `json:"p50_ms"`
	P95Ms     float64 `json:"p95_ms"`
	SlotCount uint64  `json:"slot_count"`
}

EdgeScoreboardLeadTime holds pairwise lead time stats (winner vs specific loser).

type EdgeScoreboardLeader

type EdgeScoreboardLeader struct {
	Name    string `json:"name,omitempty"`
	Pubkey  string `json:"pubkey"`
	IP      string `json:"ip,omitempty"`
	ASNOrg  string `json:"asn_org,omitempty"`
	City    string `json:"city,omitempty"`
	Country string `json:"country,omitempty"`
}

EdgeScoreboardLeader holds leader validator info for a slot.

type EdgeScoreboardNode

type EdgeScoreboardNode struct {
	Host          string                              `json:"host"`
	Location      string                              `json:"location"`
	MetroName     string                              `json:"metro_name"`
	Latitude      float64                             `json:"latitude"`
	Longitude     float64                             `json:"longitude"`
	Feeds         map[string]*EdgeScoreboardFeedStats `json:"feeds"`
	StakeSol      float64                             `json:"stake_sol"`
	Validators    uint64                              `json:"validators"`
	TotalSlots    uint64                              `json:"total_slots"`
	SlotsObserved uint64                              `json:"slots_observed"`  // view-dependent: DZ-leader slots in leaders_only mode, DZ+retransmit in all-slots mode
	DZLeaderSlots uint64                              `json:"dz_leader_slots"` // slots where the dz feed won shreds and slot was a DZ-leader slot (per-node, informational)
	LastUpdated   time.Time                           `json:"last_updated"`
	Name          string                              `json:"name,omitempty"`
	GossipPubkey  string                              `json:"gossip_pubkey,omitempty"`
	GossipIP      string                              `json:"gossip_ip,omitempty"`
	ASN           int64                               `json:"asn,omitempty"`
	ASNOrg        string                              `json:"asn_org,omitempty"`
	City          string                              `json:"city,omitempty"`
	Country       string                              `json:"country,omitempty"`
}

EdgeScoreboardNode holds aggregated stats for a single edge node.

type EdgeScoreboardResponse

type EdgeScoreboardResponse struct {
	Window             string                           `json:"window"`
	LeadersOnly        bool                             `json:"leaders_only"`
	GeneratedAt        time.Time                        `json:"generated_at"`
	CurrentEpoch       uint64                           `json:"current_epoch"`
	CurrentSlot        uint64                           `json:"current_slot"`
	TotalSlots         uint64                           `json:"total_slots"`
	GlobalTotalSlots   uint64                           `json:"global_total_slots"`
	DZSlots            uint64                           `json:"dz_slots"`
	TotalDZLeaderSlots uint64                           `json:"total_dz_leader_slots"`
	CompletenessPct    float64                          `json:"completeness_pct"`
	PublisherCount     uint64                           `json:"publisher_count"`
	PublishingCount    uint64                           `json:"publishing_count"`
	PublishingStakePct float64                          `json:"publishing_stake_pct"`
	Nodes              []EdgeScoreboardNode             `json:"nodes"`
	RecentSlots        []EdgeScoreboardSlotRace         `json:"recent_slots"`
	SlotBuckets        []EdgeScoreboardSlotBucket       `json:"slot_buckets,omitempty"`
	SlotBucketSize     uint64                           `json:"slot_bucket_size,omitempty"`
	SlotLeaders        map[string]*EdgeScoreboardLeader `json:"slot_leaders,omitempty"`
	// DataLagMs is how far behind wall clock the latest row in slot_feed_race_summary_v2 is
	// (server now − max(event_ts)). The client adds this to its own queue depth to show a
	// pill reflecting actual on-chain time.
	DataLagMs uint64 `json:"data_lag_ms,omitempty"`
}

EdgeScoreboardResponse is the response for the edge scoreboard endpoint.

type EdgeScoreboardSlotBucket

type EdgeScoreboardSlotBucket struct {
	Host        string `json:"host"`
	SlotBucket  uint64 `json:"slot_bucket"` // first slot of the bucket
	Feed        string `json:"feed"`
	FeedWon     uint64 `json:"feed_won"`     // sum(shreds_won) for this feed in bucket
	BucketTotal uint64 `json:"bucket_total"` // sum(shreds_won) across all feeds in bucket
}

EdgeScoreboardSlotBucket holds aggregated win-rate data bucketed by slot range, covering the full selected time window. Raw counts are returned so the frontend can re-aggregate into display buckets of any size.

type EdgeScoreboardSlotRace

type EdgeScoreboardSlotRace struct {
	Host      string  `json:"host"`
	Slot      uint64  `json:"slot"`
	Feed      string  `json:"feed"`
	ShredsWon uint64  `json:"shreds_won"`
	WinPct    float64 `json:"win_pct"`
}

EdgeScoreboardSlotRace holds per-slot per-feed win data for recent slots.

type EntityChangeDetails

type EntityChangeDetails struct {
	ChangeType string        `json:"change_type"` // "created", "updated", "deleted"
	Changes    []FieldChange `json:"changes,omitempty"`
	Entity     any           `json:"entity,omitempty"` // Full entity data
}

EntityChangeDetails contains details for entity change events

type EntityStatusChange

type EntityStatusChange struct {
	PreviousStatus string `json:"previous_status"`
	NewStatus      string `json:"new_status"`
	ChangedTS      string `json:"changed_ts"`
}

EntityStatusChange represents a status transition for a link or device.

type ExecuteCypherInput

type ExecuteCypherInput struct {
	Query       string `json:"query" jsonschema:"The Cypher query to execute against Neo4j"`
	Description string `` /* 127-byte string literal not displayed */
}

ExecuteCypherInput is the input for the execute_cypher tool.

type ExecuteCypherOutput

type ExecuteCypherOutput struct {
	Columns   []string         `json:"columns"`
	Rows      []map[string]any `json:"rows"`
	RowCount  int              `json:"row_count"`
	ElapsedMs int64            `json:"elapsed_ms"`
}

ExecuteCypherOutput is the output from the execute_cypher tool.

type ExecuteSQLInput

type ExecuteSQLInput struct {
	Query       string `json:"query" jsonschema:"The SQL query to execute against ClickHouse"`
	Description string `json:"description,omitempty" jsonschema:"Brief description of what this query does (e.g., 'Count validators by metro')"`
}

ExecuteSQLInput is the input for the execute_sql tool.

type ExecuteSQLOutput

type ExecuteSQLOutput struct {
	Columns   []string `json:"columns"`
	Rows      [][]any  `json:"rows"`
	RowCount  int      `json:"row_count"`
	ElapsedMs int64    `json:"elapsed_ms"`
}

ExecuteSQLOutput is the output from the execute_sql tool.

type ExecutedQueryResponse

type ExecutedQueryResponse struct {
	Question string   `json:"question"`
	SQL      string   `json:"sql,omitempty"`
	Cypher   string   `json:"cypher,omitempty"`
	Columns  []string `json:"columns"`
	Rows     [][]any  `json:"rows"`
	Count    int      `json:"count"`
	Error    string   `json:"error,omitempty"`
}

ExecutedQueryResponse represents an executed query with results.

type FacilityDetail

type FacilityDetail struct {
	PK                        string  `json:"pk"`
	Code                      string  `json:"code"`
	Name                      string  `json:"name"`
	Country                   string  `json:"country"`
	Lat                       float64 `json:"lat"`
	Lng                       float64 `json:"lng"`
	LocId                     uint32  `json:"loc_id"`
	Status                    string  `json:"status"`
	MetroPK                   string  `json:"metro_pk"`
	MetroCode                 string  `json:"metro_code"`
	DeviceCount               uint32  `json:"device_count"`
	UserCount                 uint32  `json:"user_count"`
	MaxUsers                  uint64  `json:"max_users"`
	UnicastUsersCount         uint64  `json:"unicast_users_count"`
	MulticastSubscribersCount uint64  `json:"multicast_subscribers_count"`
	MulticastPublishersCount  uint64  `json:"multicast_publishers_count"`
	MaxUnicastUsers           uint64  `json:"max_unicast_users"`
	MaxMulticastSubscribers   uint64  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers    uint64  `json:"max_multicast_publishers"`
}

type FacilityListItem

type FacilityListItem struct {
	PK                        string  `json:"pk"`
	Code                      string  `json:"code"`
	Name                      string  `json:"name"`
	Country                   string  `json:"country"`
	Lat                       float64 `json:"lat"`
	Lng                       float64 `json:"lng"`
	LocId                     uint32  `json:"loc_id"`
	MetroPK                   string  `json:"metro_pk"`
	MetroCode                 string  `json:"metro_code"`
	DeviceCount               uint32  `json:"device_count"`
	UserCount                 uint32  `json:"user_count"`
	MaxUsers                  uint64  `json:"max_users"`
	UnicastUsersCount         uint64  `json:"unicast_users_count"`
	MulticastSubscribersCount uint64  `json:"multicast_subscribers_count"`
	MulticastPublishersCount  uint64  `json:"multicast_publishers_count"`
	MaxUnicastUsers           uint64  `json:"max_unicast_users"`
	MaxMulticastSubscribers   uint64  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers    uint64  `json:"max_multicast_publishers"`
}

type FailureImpactPath

type FailureImpactPath struct {
	FromPK       string `json:"fromPK"`
	FromCode     string `json:"fromCode"`
	ToPK         string `json:"toPK"`
	ToCode       string `json:"toCode"`
	BeforeHops   int    `json:"beforeHops"`
	BeforeMetric uint32 `json:"beforeMetric"`
	AfterHops    int    `json:"afterHops,omitempty"`   // 0 if no alternate path
	AfterMetric  uint32 `json:"afterMetric,omitempty"` // 0 if no alternate path
	HasAlternate bool   `json:"hasAlternate"`
}

FailureImpactPath represents a path affected by device failure

type FailureImpactResponse

type FailureImpactResponse struct {
	DevicePK           string              `json:"devicePK"`
	DeviceCode         string              `json:"deviceCode"`
	UnreachableDevices []ImpactDevice      `json:"unreachableDevices"`
	UnreachableCount   int                 `json:"unreachableCount"`
	AffectedPaths      []FailureImpactPath `json:"affectedPaths"`
	AffectedPathCount  int                 `json:"affectedPathCount"`
	MetroImpact        []MetroImpact       `json:"metroImpact"`
	Error              string              `json:"error,omitempty"`
}

FailureImpactResponse is the response for the failure impact endpoint

type FieldChange

type FieldChange struct {
	Field    string `json:"field"`
	OldValue any    `json:"old_value,omitempty"`
	NewValue any    `json:"new_value,omitempty"`
}

FieldChange represents a single field that changed

type FieldType

type FieldType int

FieldType indicates how to filter the field

const (
	FieldTypeText FieldType = iota
	FieldTypeNumeric
	FieldTypeBoolean
	FieldTypeBandwidth // numeric with gbps/mbps units
	FieldTypeStake     // numeric with k/m units
)

type FieldValuesResponse

type FieldValuesResponse struct {
	Values []string `json:"values"`
}

FieldValuesResponse is the response for the field values endpoint

type FilterFieldConfig

type FilterFieldConfig struct {
	Column string
	Type   FieldType
}

FilterFieldConfig describes how to filter a field

type FilterParams

type FilterParams struct {
	Field string
	Value string
}

FilterParams holds parsed filter parameters

func ParseFilter

func ParseFilter(r *http.Request) FilterParams

ParseFilter extracts filter parameters from the request (legacy single-filter)

func (FilterParams) BuildFilterClause

func (f FilterParams) BuildFilterClause(fields map[string]FilterFieldConfig) (string, []any)

BuildFilterClause builds a WHERE clause fragment for the given filter Returns the clause (without WHERE keyword) and any query parameters

func (FilterParams) IsEmpty

func (f FilterParams) IsEmpty() bool

IsEmpty returns true if no filter is set

type GenerateRequest

type GenerateRequest struct {
	Prompt       string           `json:"prompt"`
	CurrentQuery string           `json:"currentQuery,omitempty"`
	History      []HistoryMessage `json:"history,omitempty"`
}

type GenerateResponse

type GenerateResponse struct {
	SQL      string `json:"sql"`
	Provider string `json:"provider,omitempty"`
	Attempts int    `json:"attempts,omitempty"`
	Error    string `json:"error,omitempty"`
}

type GeneratedQueryResponse

type GeneratedQueryResponse struct {
	Question    string `json:"question"`
	SQL         string `json:"sql"`
	Explanation string `json:"explanation"`
}

GeneratedQueryResponse represents a generated SQL query.

type GeoConcentrationASN

type GeoConcentrationASN struct {
	ASN        int64   `json:"asn"`
	ASNOrg     string  `json:"asn_org"`
	Validators int     `json:"validators"`
	StakeSol   float64 `json:"stake_sol"`
	StakePct   float64 `json:"stake_pct"`
}

type GeoConcentrationCountry

type GeoConcentrationCountry struct {
	CountryCode string  `json:"country_code"`
	CountryName string  `json:"country_name"`
	Validators  int     `json:"validators"`
	StakeSol    float64 `json:"stake_sol"`
	StakePct    float64 `json:"stake_pct"`
}

type GeoConcentrationHeroStats

type GeoConcentrationHeroStats struct {
	ValidatorsMeasured   int     `json:"validators_measured"`
	StakeTopTwoMetrosPct float64 `json:"stake_top_two_metros_pct"`
	AnchorPoints         int     `json:"anchor_points"`
	StakeMaxASNPct       float64 `json:"stake_max_asn_pct"`
}

type GeoConcentrationMetro

type GeoConcentrationMetro struct {
	MetroCode  string  `json:"metro_code"`
	Validators int     `json:"validators"`
	StakeSol   float64 `json:"stake_sol"`
	StakePct   float64 `json:"stake_pct"`
}

type GeoConcentrationResponse

type GeoConcentrationResponse struct {
	HeroStats GeoConcentrationHeroStats `json:"hero_stats"`
	Metros    []GeoConcentrationMetro   `json:"metros"`
	Countries []GeoConcentrationCountry `json:"countries"`
	ASNs      []GeoConcentrationASN     `json:"asns"`
}

type GeoMetroBreakdown

type GeoMetroBreakdown struct {
	MetroCode  string  `json:"metro_code"`
	Validators int     `json:"validators"`
	StakeSol   float64 `json:"stake_sol"`
	StakePct   float64 `json:"stake_pct"`
}

type GeoTierDistribution

type GeoTierDistribution struct {
	Tier       string  `json:"tier"`
	Validators int     `json:"validators"`
	StakePct   float64 `json:"stake_pct"`
}

type GeoValidatorItem

type GeoValidatorItem struct {
	VotePubkey  string  `json:"vote_pubkey"`
	NodePubkey  string  `json:"node_pubkey"`
	Name        string  `json:"name"`
	StakeSol    float64 `json:"stake_sol"`
	StakePct    float64 `json:"stake_pct"`
	Commission  int64   `json:"commission"`
	MetroCode   string  `json:"metro_code"`
	CountryCode string  `json:"country_code"`
	ASN         int64   `json:"asn"`
	ASNOrg      string  `json:"asn_org"`
	Datacenter  string  `json:"datacenter"`
	IsDZ        bool    `json:"is_dz"`
	Tier        string  `json:"tier"`
	DZDPLat     float64 `json:"dzdp_lat"`
	DZDPLng     float64 `json:"dzdp_lng"`
}

type GeoValidatorsResponse

type GeoValidatorsResponse struct {
	TotalValidators  int                   `json:"total_validators"`
	TotalStakeSol    float64               `json:"total_stake_sol"`
	Validators       []GeoValidatorItem    `json:"validators"`
	TierDistribution []GeoTierDistribution `json:"tier_distribution"`
	MetroBreakdown   []GeoMetroBreakdown   `json:"metro_breakdown"`
}

type GeolocExplorerDevice

type GeolocExplorerDevice struct {
	SenderPubkey        string  `json:"sender_pubkey"`
	ProbeCode           string  `json:"probe_code"`
	Lat                 float64 `json:"lat"`
	Lng                 float64 `json:"lng"`
	MinRefMeasuredRttNs uint64  `json:"min_ref_measured_rtt_ns"`
}

type GeolocExplorerProbe

type GeolocExplorerProbe struct {
	PK   string  `json:"pk"`
	Code string  `json:"code"`
	Lat  float64 `json:"lat"`
	Lng  float64 `json:"lng"`
}

type GeolocExplorerResponse

type GeolocExplorerResponse struct {
	Devices []GeolocExplorerDevice `json:"devices"`
	Probes  []GeolocExplorerProbe  `json:"probes"`
	Targets []GeolocExplorerTarget `json:"targets"`
}

type GeolocExplorerTarget

type GeolocExplorerTarget struct {
	SenderPubkey     string  `json:"sender_pubkey"`
	TargetIP         string  `json:"target_ip"`
	Lat              float64 `json:"lat"`
	Lng              float64 `json:"lng"`
	MinMeasuredRttNs uint64  `json:"min_measured_rtt_ns"`
}

type GeolocProbe

type GeolocProbe struct {
	PK                 string `json:"pk"`
	Owner              string `json:"owner"`
	ExchangePK         string `json:"exchange_pk"`
	PublicIP           string `json:"public_ip"`
	LocationOffsetPort uint16 `json:"location_offset_port"`
	MetricsPublisherPK string `json:"metrics_publisher_pk"`
	ReferenceCount     uint32 `json:"reference_count"`
	Code               string `json:"code"`
	ParentDevices      string `json:"parent_devices"`
	TargetUpdateCount  uint32 `json:"target_update_count"`
}

type GeolocUser

type GeolocUser struct {
	PK                   string `json:"pk"`
	Owner                string `json:"owner"`
	Code                 string `json:"code"`
	TokenAccount         string `json:"token_account"`
	PaymentStatus        string `json:"payment_status"`
	Status               string `json:"status"`
	TargetCount          uint32 `json:"target_count"`
	BillingRate          uint64 `json:"billing_rate"`
	LastDeductionDZEpoch uint64 `json:"last_deduction_dz_epoch"`
}

type GetSchemaInput

type GetSchemaInput struct {
}

GetSchemaInput is the input for the get_schema tool.

type GetSchemaOutput

type GetSchemaOutput struct {
	Schema      string `json:"schema"`
	Environment string `json:"environment"`
}

GetSchemaOutput is the output from the get_schema tool.

type GoogleAuthRequest

type GoogleAuthRequest struct {
	IDToken     string  `json:"id_token"`
	AnonymousID *string `json:"anonymous_id,omitempty"` // For session migration
}

GoogleAuthRequest is the request for Google OAuth

type GoogleAuthResponse

type GoogleAuthResponse struct {
	Token   string   `json:"token"`
	Account *Account `json:"account"`
}

GoogleAuthResponse is the response for Google OAuth

type GoogleIDTokenClaims

type GoogleIDTokenClaims struct {
	Subject string `json:"sub"`
	Email   string `json:"email"`
	Name    string `json:"name"`
	Picture string `json:"picture"`
	Issuer  string `json:"iss"`
	Aud     string `json:"aud"`
	Exp     string `json:"exp"`
	Iat     string `json:"iat"`
}

GoogleIDTokenClaims represents claims from a Google ID token Note: Google's tokeninfo endpoint returns exp/iat as strings, not numbers

type GossipNodeDetail

type GossipNodeDetail struct {
	Pubkey      string  `json:"pubkey"`
	GossipIP    string  `json:"gossip_ip"`
	GossipPort  int32   `json:"gossip_port"`
	Version     string  `json:"version"`
	City        string  `json:"city"`
	Country     string  `json:"country"`
	OnDZ        bool    `json:"on_dz"`
	UserPK      string  `json:"user_pk"`
	OwnerPubkey string  `json:"owner_pubkey"`
	DevicePK    string  `json:"device_pk"`
	DeviceCode  string  `json:"device_code"`
	MetroPK     string  `json:"metro_pk"`
	MetroCode   string  `json:"metro_code"`
	StakeSol    float64 `json:"stake_sol"`
	IsValidator bool    `json:"is_validator"`
	VotePubkey  string  `json:"vote_pubkey"`
}

type GossipNodeListItem

type GossipNodeListItem struct {
	Pubkey      string  `json:"pubkey"`
	GossipIP    string  `json:"gossip_ip"`
	GossipPort  int32   `json:"gossip_port"`
	Version     string  `json:"version"`
	City        string  `json:"city"`
	Country     string  `json:"country"`
	OnDZ        bool    `json:"on_dz"`
	DeviceCode  string  `json:"device_code"`
	MetroCode   string  `json:"metro_code"`
	StakeSol    float64 `json:"stake_sol"`
	IsValidator bool    `json:"is_validator"`
}

type GossipNodeListResponse

type GossipNodeListResponse struct {
	Items          []GossipNodeListItem `json:"items"`
	Total          int                  `json:"total"`
	OnDZCount      int                  `json:"on_dz_count"`
	ValidatorCount int                  `json:"validator_count"`
	Limit          int                  `json:"limit"`
	Offset         int                  `json:"offset"`
}

type HealthEntity

type HealthEntity struct {
	DevicePk                string `json:"device_pk"`
	DeviceCode              string `json:"device_code"`
	Intf                    string `json:"intf"`
	MetroCode               string `json:"metro_code"`
	ContributorCode         string `json:"contributor_code"`
	TotalErrors             int64  `json:"total_errors"`
	TotalDiscards           int64  `json:"total_discards"`
	TotalFcsErrors          int64  `json:"total_fcs_errors"`
	TotalCarrierTransitions int64  `json:"total_carrier_transitions"`
	TotalEvents             int64  `json:"total_events"`
}

type HealthResponse

type HealthResponse struct {
	Entities []HealthEntity `json:"entities"`
}

type HistogramBucket

type HistogramBucket struct {
	Timestamp string `json:"timestamp"`
	Count     int    `json:"count"`
}

HistogramBucket represents a time bucket with event counts

type HistoryMessage

type HistoryMessage struct {
	Role    string `json:"role"` // "user" or "assistant"
	Content string `json:"content"`
}

type ISISDeviceIssue

type ISISDeviceIssue struct {
	Code       string `json:"code"`
	DeviceType string `json:"device_type"`
	Metro      string `json:"metro"`
	Issue      string `json:"issue"` // "overload", "unreachable"
	Since      string `json:"since"` // ISO timestamp
}

type ISISEdge

type ISISEdge struct {
	Data ISISEdgeData `json:"data"`
}

ISISEdge represents an adjacency edge in the ISIS topology graph

type ISISEdgeData

type ISISEdgeData struct {
	ID           string   `json:"id"`
	Source       string   `json:"source"`
	Target       string   `json:"target"`
	Metric       uint32   `json:"metric,omitempty"`
	AdjSIDs      []uint32 `json:"adjSids,omitempty"`
	NeighborAddr string   `json:"neighborAddr,omitempty"`
}

type ISISNode

type ISISNode struct {
	Data ISISNodeData `json:"data"`
}

ISISNode represents a device node in the ISIS topology graph

type ISISNodeData

type ISISNodeData struct {
	ID         string `json:"id"`
	Label      string `json:"label"`
	Status     string `json:"status"`
	DeviceType string `json:"deviceType"`
	MetroPK    string `json:"metroPK,omitempty"`
	SystemID   string `json:"systemId,omitempty"`
	RouterID   string `json:"routerId,omitempty"`
}

type ISISTopologyResponse

type ISISTopologyResponse struct {
	Nodes []ISISNode `json:"nodes"`
	Edges []ISISEdge `json:"edges"`
	Error string     `json:"error,omitempty"`
}

ISISTopologyResponse is the response for the ISIS topology endpoint

type ImpactDevice

type ImpactDevice struct {
	PK         string `json:"pk"`
	Code       string `json:"code"`
	Status     string `json:"status"`
	DeviceType string `json:"deviceType"`
}

ImpactDevice represents a device that would be affected by a failure

type ImprovedPath

type ImprovedPath struct {
	FromPK          string `json:"fromPK"`
	FromCode        string `json:"fromCode"`
	ToPK            string `json:"toPK"`
	ToCode          string `json:"toCode"`
	BeforeHops      int    `json:"beforeHops"`
	BeforeMetric    uint32 `json:"beforeMetric"`
	AfterHops       int    `json:"afterHops"`
	AfterMetric     uint32 `json:"afterMetric"`
	HopReduction    int    `json:"hopReduction"`
	MetricReduction uint32 `json:"metricReduction"`
}

ImprovedPath represents a path that would be improved by adding a link

type IncidentEventDetails

type IncidentEventDetails struct {
	EntityPK        string  `json:"entity_pk"`
	EntityCode      string  `json:"entity_code"`
	EntityType      string  `json:"entity_type"`   // "link" or "device"
	IncidentType    string  `json:"incident_type"` // "packet_loss", "errors", etc.
	PeakValue       float64 `json:"peak_value"`
	DurationSeconds int64   `json:"duration_seconds"`
	IsOngoing       bool    `json:"is_ongoing"`
	LinkType        string  `json:"link_type,omitempty"`
	SideAMetro      string  `json:"side_a_metro,omitempty"`
	SideZMetro      string  `json:"side_z_metro,omitempty"`
	Metro           string  `json:"metro,omitempty"`
	ContributorCode string  `json:"contributor_code,omitempty"`
	Status          string  `json:"status,omitempty"`
}

IncidentEventDetails contains details for incident-based timeline events.

type IncidentFilter

type IncidentFilter struct {
	Type  string // device, link, metro, contributor
	Value string
}

IncidentFilter represents a filter for incidents (e.g., metro:SAO, link:WAN-LAX-01)

type InfrastructureAlerts

type InfrastructureAlerts struct {
	Devices     []NonActivatedDevice `json:"devices"`
	Links       []NonActivatedLink   `json:"links"`
	ISISDevices []ISISDeviceIssue    `json:"isis_devices"`
}

type InterfaceHealth

type InterfaceHealth struct {
	Issues []InterfaceIssue `json:"issues"` // Interfaces with errors/discards/carrier transitions
}

type InterfaceHistory

type InterfaceHistory struct {
	InterfaceName string                `json:"interface_name"`
	LinkPK        string                `json:"link_pk,omitempty"`
	LinkCode      string                `json:"link_code,omitempty"`
	LinkType      string                `json:"link_type,omitempty"`
	LinkSide      string                `json:"link_side,omitempty"`
	Hours         []InterfaceHourStatus `json:"hours"`
}

InterfaceHistory is the history of a single interface

type InterfaceHourStatus

type InterfaceHourStatus struct {
	Hour               string `json:"hour"`
	InErrors           uint64 `json:"in_errors"`
	OutErrors          uint64 `json:"out_errors"`
	InFcsErrors        uint64 `json:"in_fcs_errors"`
	InDiscards         uint64 `json:"in_discards"`
	OutDiscards        uint64 `json:"out_discards"`
	CarrierTransitions uint64 `json:"carrier_transitions"`
}

InterfaceHourStatus is the status of an interface for a single time bucket

type InterfaceIssue

type InterfaceIssue struct {
	DevicePK           string `json:"device_pk"`
	DeviceCode         string `json:"device_code"`
	DeviceType         string `json:"device_type"`
	Contributor        string `json:"contributor"`
	Metro              string `json:"metro"`
	InterfaceName      string `json:"interface_name"`
	InterfaceType      string `json:"interface_type,omitempty"`
	CYOAType           string `json:"cyoa_type,omitempty"`
	LinkPK             string `json:"link_pk,omitempty"`
	LinkCode           string `json:"link_code,omitempty"`
	LinkType           string `json:"link_type,omitempty"`
	LinkSide           string `json:"link_side,omitempty"`
	InErrors           uint64 `json:"in_errors"`
	OutErrors          uint64 `json:"out_errors"`
	InFcsErrors        uint64 `json:"in_fcs_errors"`
	InDiscards         uint64 `json:"in_discards"`
	OutDiscards        uint64 `json:"out_discards"`
	CarrierTransitions uint64 `json:"carrier_transitions"`
	FirstSeen          string `json:"first_seen"`
	LastSeen           string `json:"last_seen"`
}

type InterfaceIssuesResponse

type InterfaceIssuesResponse struct {
	Issues    []InterfaceIssue `json:"issues"`
	TimeRange string           `json:"time_range"`
}

InterfaceIssuesResponse is the response for interface issues endpoint

type InterfaceTrafficDataPoint

type InterfaceTrafficDataPoint struct {
	Time    string  `json:"time"`
	Intf    string  `json:"intf"`
	AvgIn   float64 `json:"avgIn"`
	AvgOut  float64 `json:"avgOut"`
	PeakIn  float64 `json:"peakIn"`
	PeakOut float64 `json:"peakOut"`
}

InterfaceTrafficDataPoint is a per-interface traffic data point

type LatencyComparison

type LatencyComparison struct {
	OriginMetroPK        string   `json:"origin_metro_pk"`
	OriginMetroCode      string   `json:"origin_metro_code"`
	OriginMetroName      string   `json:"origin_metro_name"`
	TargetMetroPK        string   `json:"target_metro_pk"`
	TargetMetroCode      string   `json:"target_metro_code"`
	TargetMetroName      string   `json:"target_metro_name"`
	DzAvgRttMs           float64  `json:"dz_avg_rtt_ms"`
	DzP95RttMs           float64  `json:"dz_p95_rtt_ms"`
	DzAvgJitterMs        *float64 `json:"dz_avg_jitter_ms"`
	DzLossPct            float64  `json:"dz_loss_pct"`
	DzSampleCount        uint64   `json:"dz_sample_count"`
	InternetAvgRttMs     float64  `json:"internet_avg_rtt_ms"`
	InternetP95RttMs     float64  `json:"internet_p95_rtt_ms"`
	InternetAvgJitterMs  *float64 `json:"internet_avg_jitter_ms"`
	InternetSampleCount  uint64   `json:"internet_sample_count"`
	RttImprovementPct    *float64 `json:"rtt_improvement_pct"`
	JitterImprovementPct *float64 `json:"jitter_improvement_pct"`
}

DZ vs Internet latency comparison types

type LatencyComparisonResponse

type LatencyComparisonResponse struct {
	Comparisons []LatencyComparison `json:"comparisons"`
	Summary     struct {
		TotalPairs        int     `json:"total_pairs"`
		AvgImprovementPct float64 `json:"avg_improvement_pct"`
		MaxImprovementPct float64 `json:"max_improvement_pct"`
		PairsWithData     int     `json:"pairs_with_data"`
	} `json:"summary"`
}

type LatencyHistoryPoint

type LatencyHistoryPoint struct {
	Timestamp       time.Time `json:"timestamp"`
	DzAvgRttMs      *float64  `json:"dz_avg_rtt_ms"`
	DzAvgJitterMs   *float64  `json:"dz_avg_jitter_ms"`
	DzSampleCount   uint64    `json:"dz_sample_count"`
	InetAvgRttMs    *float64  `json:"inet_avg_rtt_ms"`
	InetAvgJitterMs *float64  `json:"inet_avg_jitter_ms"`
	InetSampleCount uint64    `json:"inet_sample_count"`
}

Latency history time series point

type LatencyHistoryResponse

type LatencyHistoryResponse struct {
	OriginMetroCode string                `json:"origin_metro_code"`
	TargetMetroCode string                `json:"target_metro_code"`
	Points          []LatencyHistoryPoint `json:"points"`
}

type LedgerResponse

type LedgerResponse struct {
	// Epoch info
	Epoch        uint64  `json:"epoch"`
	SlotIndex    uint64  `json:"slot_index"`
	SlotsInEpoch uint64  `json:"slots_in_epoch"`
	EpochPct     float64 `json:"epoch_pct"`
	EpochETASec  float64 `json:"epoch_eta_sec"`

	// Chain state
	AbsoluteSlot     uint64  `json:"absolute_slot"`
	BlockHeight      uint64  `json:"block_height"`
	TransactionCount uint64  `json:"transaction_count"`
	SkipRate         float64 `json:"skip_rate"`

	// TPS (average over recent samples)
	TPS float64 `json:"tps"`

	// Supply (in SOL)
	TotalSupply       float64 `json:"total_supply"`
	CirculatingSupply float64 `json:"circulating_supply"`

	// Inflation
	InflationTotal      float64 `json:"inflation_total"`
	InflationValidator  float64 `json:"inflation_validator"`
	InflationFoundation float64 `json:"inflation_foundation"`

	// Validator summary
	ActiveValidators     int     `json:"active_validators"`
	DelinquentValidators int     `json:"delinquent_validators"`
	TotalStakeSOL        float64 `json:"total_stake_sol"`

	// Node version (of the RPC node we're talking to)
	NodeVersion string `json:"node_version"`

	Error string `json:"error,omitempty"`
}

LedgerResponse contains ledger/chain telemetry for a Solana-compatible chain.

func FetchLedgerData

func FetchLedgerData(ctx context.Context, rpcURL string) (*LedgerResponse, error)

FetchLedgerData fetches ledger telemetry from the given RPC URL.

type Link struct {
	PK                   string  `json:"pk"`
	Code                 string  `json:"code"`
	Status               string  `json:"status"`
	LinkType             string  `json:"link_type"`
	BandwidthBps         int64   `json:"bandwidth_bps"`
	SideAPK              string  `json:"side_a_pk"`
	SideACode            string  `json:"side_a_code"`
	SideAIfaceName       string  `json:"side_a_iface_name"`
	SideAIP              string  `json:"side_a_ip"`
	SideZPK              string  `json:"side_z_pk"`
	SideZCode            string  `json:"side_z_code"`
	SideZIfaceName       string  `json:"side_z_iface_name"`
	SideZIP              string  `json:"side_z_ip"`
	ContributorPK        string  `json:"contributor_pk"`
	ContributorCode      string  `json:"contributor_code"`
	SideAContributorPK   string  `json:"side_a_contributor_pk"`
	SideAContributorCode string  `json:"side_a_contributor_code"`
	SideZContributorPK   string  `json:"side_z_contributor_pk"`
	SideZContributorCode string  `json:"side_z_contributor_code"`
	LatencyUs            float64 `json:"latency_us"`
	JitterUs             float64 `json:"jitter_us"`
	LatencyAtoZUs        float64 `json:"latency_a_to_z_us"`
	JitterAtoZUs         float64 `json:"jitter_a_to_z_us"`
	LatencyZtoAUs        float64 `json:"latency_z_to_a_us"`
	JitterZtoAUs         float64 `json:"jitter_z_to_a_us"`
	LossPercent          float64 `json:"loss_percent"`
	SampleCount          uint64  `json:"sample_count"`
	InBps                float64 `json:"in_bps"`
	OutBps               float64 `json:"out_bps"`
	CommittedRttNs       int64   `json:"committed_rtt_ns"`
	ISISDelayOverrideNs  int64   `json:"isis_delay_override_ns"`
}

type LinkDetail

type LinkDetail struct {
	PK                   string  `json:"pk"`
	Code                 string  `json:"code"`
	Status               string  `json:"status"`
	LinkType             string  `json:"link_type"`
	BandwidthBps         int64   `json:"bandwidth_bps"`
	SideAPK              string  `json:"side_a_pk"`
	SideACode            string  `json:"side_a_code"`
	SideAMetro           string  `json:"side_a_metro"`
	SideAIfaceName       string  `json:"side_a_iface_name"`
	SideAIP              string  `json:"side_a_ip"`
	SideZPK              string  `json:"side_z_pk"`
	SideZCode            string  `json:"side_z_code"`
	SideZMetro           string  `json:"side_z_metro"`
	SideZIfaceName       string  `json:"side_z_iface_name"`
	SideZIP              string  `json:"side_z_ip"`
	ContributorPK        string  `json:"contributor_pk"`
	ContributorCode      string  `json:"contributor_code"`
	SideAContributorPK   string  `json:"side_a_contributor_pk"`
	SideAContributorCode string  `json:"side_a_contributor_code"`
	SideZContributorPK   string  `json:"side_z_contributor_pk"`
	SideZContributorCode string  `json:"side_z_contributor_code"`
	InBps                float64 `json:"in_bps"`
	OutBps               float64 `json:"out_bps"`
	UtilizationIn        float64 `json:"utilization_in"`
	UtilizationOut       float64 `json:"utilization_out"`
	LatencyUs            float64 `json:"latency_us"`
	JitterUs             float64 `json:"jitter_us"`
	LatencyAtoZUs        float64 `json:"latency_a_to_z_us"`
	JitterAtoZUs         float64 `json:"jitter_a_to_z_us"`
	LatencyZtoAUs        float64 `json:"latency_z_to_a_us"`
	JitterZtoAUs         float64 `json:"jitter_z_to_a_us"`
	LossPercent          float64 `json:"loss_percent"`
	PeakInBps            float64 `json:"peak_in_bps"`
	PeakOutBps           float64 `json:"peak_out_bps"`
	CommittedRttNs       int64   `json:"committed_rtt_ns"`
	ISISDelayOverrideNs  int64   `json:"isis_delay_override_ns"`
}

type LinkEntity

type LinkEntity struct {
	PK                string `json:"pk"`
	Code              string `json:"code"`
	Status            string `json:"status"`
	LinkType          string `json:"link_type"`
	TunnelNet         string `json:"tunnel_net"`
	ContributorPK     string `json:"contributor_pk"`
	SideAPK           string `json:"side_a_pk"`
	SideZPK           string `json:"side_z_pk"`
	SideAIfaceName    string `json:"side_a_iface_name"`
	SideZIfaceName    string `json:"side_z_iface_name"`
	CommittedRttNs    int64  `json:"committed_rtt_ns"`
	CommittedJitterNs int64  `json:"committed_jitter_ns"`
	BandwidthBps      int64  `json:"bandwidth_bps"`
	ISISDelayOverride int64  `json:"isis_delay_override_ns"`
	// Joined fields
	ContributorCode string `json:"contributor_code,omitempty"`
	SideACode       string `json:"side_a_code,omitempty"`
	SideZCode       string `json:"side_z_code,omitempty"`
	SideAMetroCode  string `json:"side_a_metro_code,omitempty"`
	SideZMetroCode  string `json:"side_z_metro_code,omitempty"`
	SideAMetroPK    string `json:"side_a_metro_pk,omitempty"`
	SideZMetroPK    string `json:"side_z_metro_pk,omitempty"`
}

LinkEntity represents a link's current state

type LinkHealth

type LinkHealth struct {
	Total         uint64       `json:"total"`
	Healthy       uint64       `json:"healthy"`
	Degraded      uint64       `json:"degraded"`        // High latency or some loss
	Unhealthy     uint64       `json:"unhealthy"`       // Significant loss
	Down          uint64       `json:"down"`            // 100% packet loss (link is down)
	Issues        []LinkIssue  `json:"issues"`          // Top issues
	HighUtilLinks []LinkMetric `json:"high_util_links"` // Links with high utilization
	TopUtilLinks  []LinkMetric `json:"top_util_links"`  // Top 10 links by max utilization
}

type LinkHistory

type LinkHistory struct {
	PK               string           `json:"pk"`
	Code             string           `json:"code"`
	LinkType         string           `json:"link_type"`
	Contributor      string           `json:"contributor"`
	SideZContributor string           `json:"side_z_contributor"`
	SideAMetro       string           `json:"side_a_metro"`
	SideZMetro       string           `json:"side_z_metro"`
	SideADevice      string           `json:"side_a_device"`
	SideZDevice      string           `json:"side_z_device"`
	BandwidthBps     int64            `json:"bandwidth_bps"`
	CommittedRttUs   float64          `json:"committed_rtt_us"`
	IsDown           bool             `json:"is_down"`
	DrainStatus      string           `json:"drain_status,omitempty"`
	Provisioning     bool             `json:"provisioning,omitempty"`
	Hours            []LinkHourStatus `json:"hours"`
	IssueReasons     []string         `json:"issue_reasons"` // "packet_loss", "high_latency", "no_data", "missing_adjacency", "interface_errors", "discards", "carrier_transitions", "high_utilization"
}

type LinkHistoryResponse

type LinkHistoryResponse struct {
	Links         []LinkHistory `json:"links"`
	TimeRange     string        `json:"time_range"`     // "24h", "3d", "7d"
	BucketMinutes int           `json:"bucket_minutes"` // Size of each bucket in minutes
	BucketCount   int           `json:"bucket_count"`   // Number of buckets
	Error         string        `json:"error,omitempty"`
}

type LinkHourStatus

type LinkHourStatus struct {
	Hour         string  `json:"hour"`
	Status       string  `json:"status"`                 // "healthy", "degraded", "unhealthy", "no_data"
	Collecting   bool    `json:"collecting,omitempty"`   // true for the current incomplete bucket
	DrainStatus  string  `json:"drain_status,omitempty"` // "", "soft-drained", "hard-drained"
	AvgLatencyUs float64 `json:"avg_latency_us"`
	AvgLossPct   float64 `json:"avg_loss_pct"`
	Samples      uint64  `json:"samples"`
	// Per-side latency/loss metrics (direction: A→Z vs Z→A)
	SideALatencyUs float64 `json:"side_a_latency_us,omitempty"`
	SideALossPct   float64 `json:"side_a_loss_pct,omitempty"`
	SideASamples   uint64  `json:"side_a_samples,omitempty"`
	SideZLatencyUs float64 `json:"side_z_latency_us,omitempty"`
	SideZLossPct   float64 `json:"side_z_loss_pct,omitempty"`
	SideZSamples   uint64  `json:"side_z_samples,omitempty"`
	// Per-side interface issues (errors, discards, carrier transitions)
	SideAInErrors           uint64 `json:"side_a_in_errors,omitempty"`
	SideAOutErrors          uint64 `json:"side_a_out_errors,omitempty"`
	SideAInFcsErrors        uint64 `json:"side_a_in_fcs_errors,omitempty"`
	SideAInDiscards         uint64 `json:"side_a_in_discards,omitempty"`
	SideAOutDiscards        uint64 `json:"side_a_out_discards,omitempty"`
	SideACarrierTransitions uint64 `json:"side_a_carrier_transitions,omitempty"`
	SideZInErrors           uint64 `json:"side_z_in_errors,omitempty"`
	SideZOutErrors          uint64 `json:"side_z_out_errors,omitempty"`
	SideZInFcsErrors        uint64 `json:"side_z_in_fcs_errors,omitempty"`
	SideZInDiscards         uint64 `json:"side_z_in_discards,omitempty"`
	SideZOutDiscards        uint64 `json:"side_z_out_discards,omitempty"`
	SideZCarrierTransitions uint64 `json:"side_z_carrier_transitions,omitempty"`
	// Utilization (traffic rate / capacity)
	UtilizationInPct  float64 `json:"utilization_in_pct,omitempty"`
	UtilizationOutPct float64 `json:"utilization_out_pct,omitempty"`
	// ISIS state
	ISISDown bool `json:"isis_down,omitempty"` // true when link has no ISIS adjacency in this bucket
}

Link history types for status timeline

type LinkIncident

type LinkIncident struct {
	ID                 string   `json:"id"`
	LinkPK             string   `json:"link_pk"`
	LinkCode           string   `json:"link_code"`
	LinkType           string   `json:"link_type"`
	SideAMetro         string   `json:"side_a_metro"`
	SideZMetro         string   `json:"side_z_metro"`
	ContributorCode    string   `json:"contributor_code"`
	IncidentType       string   `json:"incident_type"` // packet_loss, errors, discards, carrier, no_data
	ThresholdPct       *float64 `json:"threshold_pct,omitempty"`
	PeakLossPct        *float64 `json:"peak_loss_pct,omitempty"`
	ThresholdCount     *int64   `json:"threshold_count,omitempty"`
	PeakCount          *int64   `json:"peak_count,omitempty"`
	StartedAt          string   `json:"started_at"`
	EndedAt            *string  `json:"ended_at,omitempty"`
	DurationSeconds    *int64   `json:"duration_seconds,omitempty"`
	IsOngoing          bool     `json:"is_ongoing"`
	Confirmed          bool     `json:"confirmed"` // true if ongoing duration >= min_duration
	IsDrained          bool     `json:"is_drained"`
	Severity           string   `json:"severity"` // "degraded" or "incident"
	AffectedInterfaces []string `json:"affected_interfaces,omitempty"`
}

LinkIncident represents a discrete incident event on a link

type LinkIncidentsResponse

type LinkIncidentsResponse struct {
	Active         []LinkIncident       `json:"active"`
	Drained        []DrainedLinkInfo    `json:"drained"`
	ActiveSummary  LinkIncidentsSummary `json:"active_summary"`
	DrainedSummary DrainedSummary       `json:"drained_summary"`
}

LinkIncidentsResponse is the API response for link incidents

type LinkIncidentsSummary

type LinkIncidentsSummary struct {
	Total   int            `json:"total"`
	Ongoing int            `json:"ongoing"`
	ByType  map[string]int `json:"by_type"`
}

LinkIncidentsSummary contains aggregate counts for active incidents

type LinkIssue

type LinkIssue struct {
	Code             string  `json:"code"`
	LinkType         string  `json:"link_type"`
	Contributor      string  `json:"contributor"`
	SideZContributor string  `json:"side_z_contributor"`
	Issue            string  `json:"issue"`     // "packet_loss", "high_latency", "down"
	Value            float64 `json:"value"`     // The problematic value
	Threshold        float64 `json:"threshold"` // The threshold exceeded
	SideAMetro       string  `json:"side_a_metro"`
	SideZMetro       string  `json:"side_z_metro"`
	Since            string  `json:"since"`   // ISO timestamp when issue started
	IsDown           bool    `json:"is_down"` // 100% loss in last 5 minutes
	BandwidthBps     int64   `json:"bandwidth_bps"`
}

type LinkLatencySummary

type LinkLatencySummary struct {
	LinkPk            string  `json:"link_pk"`
	LinkCode          string  `json:"link_code"`
	LinkType          string  `json:"link_type"`
	LinkStatus        string  `json:"link_status"`
	Provisioning      bool    `json:"provisioning"`
	ISISDown          bool    `json:"isis_down"`
	ContributorCode   string  `json:"contributor_code"`
	SideACode         string  `json:"side_a_code"`
	SideZCode         string  `json:"side_z_code"`
	CommittedRttMs    float64 `json:"committed_rtt_ms"`
	CommittedJitterMs float64 `json:"committed_jitter_ms"`
	RttAtoZMs         float64 `json:"rtt_a_to_z_ms"`
	RttZtoAMs         float64 `json:"rtt_z_to_a_ms"`
	JitterAtoZMs      float64 `json:"jitter_a_to_z_ms"`
	JitterZtoAMs      float64 `json:"jitter_z_to_a_ms"`
	LossAPct          float64 `json:"loss_a_pct"`
	LossZPct          float64 `json:"loss_z_pct"`
	Samples           uint64  `json:"samples"`
}

LinkLatencySummary is the per-link aggregated row for the summary table.

type LinkLatencySummaryResponse

type LinkLatencySummaryResponse struct {
	Links []LinkLatencySummary `json:"links"`
}

LinkLatencySummaryResponse is the JSON response for the link latency summary endpoint.

type LinkListItem

type LinkListItem struct {
	PK                   string  `json:"pk"`
	Code                 string  `json:"code"`
	Status               string  `json:"status"`
	LinkType             string  `json:"link_type"`
	BandwidthBps         int64   `json:"bandwidth_bps"`
	SideAPK              string  `json:"side_a_pk"`
	SideACode            string  `json:"side_a_code"`
	SideAMetroPK         string  `json:"side_a_metro_pk"`
	SideAMetro           string  `json:"side_a_metro"`
	SideZPK              string  `json:"side_z_pk"`
	SideZCode            string  `json:"side_z_code"`
	SideZMetroPK         string  `json:"side_z_metro_pk"`
	SideZMetro           string  `json:"side_z_metro"`
	ContributorPK        string  `json:"contributor_pk"`
	ContributorCode      string  `json:"contributor_code"`
	SideAContributorPK   string  `json:"side_a_contributor_pk"`
	SideAContributorCode string  `json:"side_a_contributor_code"`
	SideZContributorPK   string  `json:"side_z_contributor_pk"`
	SideZContributorCode string  `json:"side_z_contributor_code"`
	InBps                float64 `json:"in_bps"`
	OutBps               float64 `json:"out_bps"`
	UtilizationIn        float64 `json:"utilization_in"`
	UtilizationOut       float64 `json:"utilization_out"`
	LatencyUs            float64 `json:"latency_us"`
	JitterUs             float64 `json:"jitter_us"`
	LossPercent          float64 `json:"loss_percent"`
}

type LinkMetric

type LinkMetric struct {
	PK               string  `json:"pk"`
	Code             string  `json:"code"`
	LinkType         string  `json:"link_type"`
	Contributor      string  `json:"contributor"`
	SideZContributor string  `json:"side_z_contributor"`
	BandwidthBps     int64   `json:"bandwidth_bps"`
	InBps            float64 `json:"in_bps"`
	OutBps           float64 `json:"out_bps"`
	UtilizationIn    float64 `json:"utilization_in"`
	UtilizationOut   float64 `json:"utilization_out"`
	SideAMetro       string  `json:"side_a_metro"`
	SideZMetro       string  `json:"side_z_metro"`
}

type LinkMetricsBucket

type LinkMetricsBucket struct {
	TS      string              `json:"ts"`
	Status  *LinkMetricsStatus  `json:"status,omitempty"`
	Latency *LinkMetricsLatency `json:"latency,omitempty"`
	Traffic *LinkMetricsTraffic `json:"traffic,omitempty"`
}

LinkMetricsBucket holds all metric categories for a single time bucket.

type LinkMetricsLatency

type LinkMetricsLatency struct {
	AAvgRttUs float64 `json:"a_avg_rtt_us"`
	AMinRttUs float64 `json:"a_min_rtt_us"`
	AP50RttUs float64 `json:"a_p50_rtt_us"`
	AP90RttUs float64 `json:"a_p90_rtt_us"`
	AP95RttUs float64 `json:"a_p95_rtt_us"`
	AP99RttUs float64 `json:"a_p99_rtt_us"`
	AMaxRttUs float64 `json:"a_max_rtt_us"`
	ALossPct  float64 `json:"a_loss_pct"`
	ASamples  uint64  `json:"a_samples"`
	ZAvgRttUs float64 `json:"z_avg_rtt_us"`
	ZMinRttUs float64 `json:"z_min_rtt_us"`
	ZP50RttUs float64 `json:"z_p50_rtt_us"`
	ZP90RttUs float64 `json:"z_p90_rtt_us"`
	ZP95RttUs float64 `json:"z_p95_rtt_us"`
	ZP99RttUs float64 `json:"z_p99_rtt_us"`
	ZMaxRttUs float64 `json:"z_max_rtt_us"`
	ZLossPct  float64 `json:"z_loss_pct"`
	ZSamples  uint64  `json:"z_samples"`

	AAvgJitterUs float64 `json:"a_avg_jitter_us"`
	AMinJitterUs float64 `json:"a_min_jitter_us"`
	AP50JitterUs float64 `json:"a_p50_jitter_us"`
	AP90JitterUs float64 `json:"a_p90_jitter_us"`
	AP95JitterUs float64 `json:"a_p95_jitter_us"`
	AP99JitterUs float64 `json:"a_p99_jitter_us"`
	AMaxJitterUs float64 `json:"a_max_jitter_us"`
	ZAvgJitterUs float64 `json:"z_avg_jitter_us"`
	ZMinJitterUs float64 `json:"z_min_jitter_us"`
	ZP50JitterUs float64 `json:"z_p50_jitter_us"`
	ZP90JitterUs float64 `json:"z_p90_jitter_us"`
	ZP95JitterUs float64 `json:"z_p95_jitter_us"`
	ZP99JitterUs float64 `json:"z_p99_jitter_us"`
	ZMaxJitterUs float64 `json:"z_max_jitter_us"`
}

LinkMetricsLatency holds per-direction latency and jitter percentiles.

type LinkMetricsResponse

type LinkMetricsResponse struct {
	LinkPK               string               `json:"link_pk"`
	LinkCode             string               `json:"link_code"`
	LinkType             string               `json:"link_type"`
	ContributorCode      string               `json:"contributor_code"`
	ContributorPK        string               `json:"contributor_pk"`
	SideZContributorCode string               `json:"side_z_contributor_code"`
	SideAMetro           string               `json:"side_a_metro"`
	SideZMetro           string               `json:"side_z_metro"`
	SideADevice          string               `json:"side_a_device"`
	SideZDevice          string               `json:"side_z_device"`
	SideAIfaceName       string               `json:"side_a_iface_name"`
	SideZIfaceName       string               `json:"side_z_iface_name"`
	CommittedRttUs       float64              `json:"committed_rtt_us"`
	CommittedJitterUs    float64              `json:"committed_jitter_us"`
	BandwidthBps         int64                `json:"bandwidth_bps"`
	CurrentDrainStatus   string               `json:"current_drain_status"`
	TimeRange            string               `json:"time_range"`
	BucketSeconds        int                  `json:"bucket_seconds"`
	BucketCount          int                  `json:"bucket_count"`
	Buckets              []LinkMetricsBucket  `json:"buckets"`
	StatusChanges        []EntityStatusChange `json:"status_changes,omitempty"`
}

LinkMetricsResponse is the top-level response for GET /api/link-metrics/{pk}.

type LinkMetricsStatus

type LinkMetricsStatus struct {
	Health       string   `json:"health"`
	DrainStatus  string   `json:"drain_status"`
	Provisioning bool     `json:"provisioning"`
	ISISDown     bool     `json:"isis_down"`
	Collecting   bool     `json:"collecting"`
	Reasons      []string `json:"reasons,omitempty"`
}

LinkMetricsStatus represents health/drain/provisioning state for a bucket.

type LinkMetricsTraffic

type LinkMetricsTraffic struct {
	SideAInBps              float64 `json:"side_a_in_bps"`
	SideAP50InBps           float64 `json:"side_a_p50_in_bps"`
	SideAP90InBps           float64 `json:"side_a_p90_in_bps"`
	SideAP95InBps           float64 `json:"side_a_p95_in_bps"`
	SideAP99InBps           float64 `json:"side_a_p99_in_bps"`
	SideAMaxInBps           float64 `json:"side_a_max_in_bps"`
	SideAOutBps             float64 `json:"side_a_out_bps"`
	SideAP50OutBps          float64 `json:"side_a_p50_out_bps"`
	SideAP90OutBps          float64 `json:"side_a_p90_out_bps"`
	SideAP95OutBps          float64 `json:"side_a_p95_out_bps"`
	SideAP99OutBps          float64 `json:"side_a_p99_out_bps"`
	SideAMaxOutBps          float64 `json:"side_a_max_out_bps"`
	SideZInBps              float64 `json:"side_z_in_bps"`
	SideZP50InBps           float64 `json:"side_z_p50_in_bps"`
	SideZP90InBps           float64 `json:"side_z_p90_in_bps"`
	SideZP95InBps           float64 `json:"side_z_p95_in_bps"`
	SideZP99InBps           float64 `json:"side_z_p99_in_bps"`
	SideZMaxInBps           float64 `json:"side_z_max_in_bps"`
	SideZOutBps             float64 `json:"side_z_out_bps"`
	SideZP50OutBps          float64 `json:"side_z_p50_out_bps"`
	SideZP90OutBps          float64 `json:"side_z_p90_out_bps"`
	SideZP95OutBps          float64 `json:"side_z_p95_out_bps"`
	SideZP99OutBps          float64 `json:"side_z_p99_out_bps"`
	SideZMaxOutBps          float64 `json:"side_z_max_out_bps"`
	SideAInPps              float64 `json:"side_a_in_pps"`
	SideAP50InPps           float64 `json:"side_a_p50_in_pps"`
	SideAP90InPps           float64 `json:"side_a_p90_in_pps"`
	SideAP95InPps           float64 `json:"side_a_p95_in_pps"`
	SideAP99InPps           float64 `json:"side_a_p99_in_pps"`
	SideAMaxInPps           float64 `json:"side_a_max_in_pps"`
	SideAOutPps             float64 `json:"side_a_out_pps"`
	SideAP50OutPps          float64 `json:"side_a_p50_out_pps"`
	SideAP90OutPps          float64 `json:"side_a_p90_out_pps"`
	SideAP95OutPps          float64 `json:"side_a_p95_out_pps"`
	SideAP99OutPps          float64 `json:"side_a_p99_out_pps"`
	SideAMaxOutPps          float64 `json:"side_a_max_out_pps"`
	SideZInPps              float64 `json:"side_z_in_pps"`
	SideZP50InPps           float64 `json:"side_z_p50_in_pps"`
	SideZP90InPps           float64 `json:"side_z_p90_in_pps"`
	SideZP95InPps           float64 `json:"side_z_p95_in_pps"`
	SideZP99InPps           float64 `json:"side_z_p99_in_pps"`
	SideZMaxInPps           float64 `json:"side_z_max_in_pps"`
	SideZOutPps             float64 `json:"side_z_out_pps"`
	SideZP50OutPps          float64 `json:"side_z_p50_out_pps"`
	SideZP90OutPps          float64 `json:"side_z_p90_out_pps"`
	SideZP95OutPps          float64 `json:"side_z_p95_out_pps"`
	SideZP99OutPps          float64 `json:"side_z_p99_out_pps"`
	SideZMaxOutPps          float64 `json:"side_z_max_out_pps"`
	SideAInErrors           uint64  `json:"side_a_in_errors"`
	SideAOutErrors          uint64  `json:"side_a_out_errors"`
	SideAInFcsErrors        uint64  `json:"side_a_in_fcs_errors"`
	SideAInDiscards         uint64  `json:"side_a_in_discards"`
	SideAOutDiscards        uint64  `json:"side_a_out_discards"`
	SideACarrierTransitions uint64  `json:"side_a_carrier_transitions"`
	SideZInErrors           uint64  `json:"side_z_in_errors"`
	SideZOutErrors          uint64  `json:"side_z_out_errors"`
	SideZInFcsErrors        uint64  `json:"side_z_in_fcs_errors"`
	SideZInDiscards         uint64  `json:"side_z_in_discards"`
	SideZOutDiscards        uint64  `json:"side_z_out_discards"`
	SideZCarrierTransitions uint64  `json:"side_z_carrier_transitions"`
	UtilizationInPct        float64 `json:"utilization_in_pct"`
	UtilizationOutPct       float64 `json:"utilization_out_pct"`
}

LinkMetricsTraffic holds per-side throughput and interface counters plus utilization.

type MaintenanceAffectedPath

type MaintenanceAffectedPath struct {
	Source       string `json:"source"`       // Source device code
	Target       string `json:"target"`       // Target device code
	SourceMetro  string `json:"sourceMetro"`  // Source metro code
	TargetMetro  string `json:"targetMetro"`  // Target metro code
	HopsBefore   int    `json:"hopsBefore"`   // Hops before maintenance
	HopsAfter    int    `json:"hopsAfter"`    // Hops after maintenance (-1 = disconnected)
	MetricBefore int    `json:"metricBefore"` // Total ISIS metric before
	MetricAfter  int    `json:"metricAfter"`  // Total ISIS metric after (-1 = disconnected)
	Status       string `json:"status"`       // "rerouted", "degraded", or "disconnected"
}

MaintenanceAffectedPath represents a path that would be impacted by maintenance

type MaintenanceImpactRequest

type MaintenanceImpactRequest struct {
	Devices []string `json:"devices"` // Device PKs to take offline
	Links   []string `json:"links"`   // Link PKs to take offline (as "sourcePK:targetPK")
}

MaintenanceImpactRequest is the request body for maintenance impact analysis

type MaintenanceImpactResponse

type MaintenanceImpactResponse struct {
	Items             []MaintenanceItem         `json:"items"`                      // Items with their individual impacts
	TotalImpact       int                       `json:"totalImpact"`                // Total affected paths when all items are down
	TotalDisconnected int                       `json:"totalDisconnected"`          // Total devices that lose connectivity
	RecommendedOrder  []string                  `json:"recommendedOrder"`           // PKs in recommended maintenance order (least impact first)
	AffectedPaths     []MaintenanceAffectedPath `json:"affectedPaths,omitempty"`    // Sample of affected paths
	AffectedMetros    []AffectedMetroPair       `json:"affectedMetros,omitempty"`   // Affected metro pairs
	DisconnectedList  []string                  `json:"disconnectedList,omitempty"` // All devices that would be disconnected
	Error             string                    `json:"error,omitempty"`
}

MaintenanceImpactResponse is the response for maintenance impact analysis

type MaintenanceItem

type MaintenanceItem struct {
	Type                string                    `json:"type"`                          // "device" or "link"
	PK                  string                    `json:"pk"`                            // Device PK or link PK
	Code                string                    `json:"code"`                          // Device code or "sourceCode - targetCode"
	Impact              int                       `json:"impact"`                        // Number of affected paths/devices
	Disconnected        int                       `json:"disconnected"`                  // Devices that would lose connectivity
	CausesPartition     bool                      `json:"causesPartition"`               // Would this cause a network partition?
	DisconnectedDevices []string                  `json:"disconnectedDevices,omitempty"` // Device codes that would be disconnected
	AffectedPaths       []MaintenanceAffectedPath `json:"affectedPaths,omitempty"`       // Paths affected by this item
}

MaintenanceItem represents a device or link being taken offline

type MeResponse

type MeResponse struct {
	Account *Account   `json:"account"`
	Quota   *QuotaInfo `json:"quota"`
}

MeResponse is the response for GET /api/auth/me

type Metro

type Metro struct {
	PK        string  `json:"pk"`
	Code      string  `json:"code"`
	Name      string  `json:"name"`
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
}

type MetroConnectivity

type MetroConnectivity struct {
	FromMetroPK      string  `json:"fromMetroPK"`
	FromMetroCode    string  `json:"fromMetroCode"`
	FromMetroName    string  `json:"fromMetroName"`
	ToMetroPK        string  `json:"toMetroPK"`
	ToMetroCode      string  `json:"toMetroCode"`
	ToMetroName      string  `json:"toMetroName"`
	PathCount        int     `json:"pathCount"`
	MinHops          int     `json:"minHops"`
	MinMetric        int64   `json:"minMetric"`
	BottleneckBwGbps float64 `json:"bottleneckBwGbps,omitempty"` // min bandwidth along best path
}

MetroConnectivity represents connectivity between two metros

type MetroConnectivityResponse

type MetroConnectivityResponse struct {
	Metros       []MetroInfo         `json:"metros"`
	Connectivity []MetroConnectivity `json:"connectivity"`
	Error        string              `json:"error,omitempty"`
}

MetroConnectivityResponse is the response for the metro connectivity endpoint

type MetroDetail

type MetroDetail struct {
	PK                         string  `json:"pk"`
	Code                       string  `json:"code"`
	Name                       string  `json:"name"`
	Country                    string  `json:"country"`
	Latitude                   float64 `json:"latitude"`
	Longitude                  float64 `json:"longitude"`
	DeviceCount                uint64  `json:"device_count"`
	UserCount                  uint64  `json:"user_count"`
	FacilityCount              uint64  `json:"facility_count"`
	UnicastUsersCount          uint64  `json:"unicast_users_count"`
	MulticastSubscribersCount  uint64  `json:"multicast_subscribers_count"`
	MulticastPublishersCount   uint64  `json:"multicast_publishers_count"`
	MaxUsers                   int64   `json:"max_users"`
	MaxUnicastUsers            uint64  `json:"max_unicast_users"`
	MaxMulticastSubscribers    uint64  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers     uint64  `json:"max_multicast_publishers"`
	RawMaxUnicastUsers         uint64  `json:"raw_max_unicast_users"`
	RawMaxMulticastSubscribers uint64  `json:"raw_max_multicast_subscribers"`
	RawMaxMulticastPublishers  uint64  `json:"raw_max_multicast_publishers"`
}

type MetroDevicePairPath

type MetroDevicePairPath struct {
	SourceDevicePK   string     `json:"sourceDevicePK"`
	SourceDeviceCode string     `json:"sourceDeviceCode"`
	TargetDevicePK   string     `json:"targetDevicePK"`
	TargetDeviceCode string     `json:"targetDeviceCode"`
	BestPath         SinglePath `json:"bestPath"`
}

MetroDevicePairPath represents the best path between a device pair across two metros

type MetroDevicePathsResponse

type MetroDevicePathsResponse struct {
	FromMetroPK   string `json:"fromMetroPK"`
	FromMetroCode string `json:"fromMetroCode"`
	ToMetroPK     string `json:"toMetroPK"`
	ToMetroCode   string `json:"toMetroCode"`

	// Aggregate summary
	SourceDeviceCount int     `json:"sourceDeviceCount"`
	TargetDeviceCount int     `json:"targetDeviceCount"`
	TotalPairs        int     `json:"totalPairs"`
	MinHops           int     `json:"minHops"`
	MaxHops           int     `json:"maxHops"`
	MinLatencyMs      float64 `json:"minLatencyMs"`
	MaxLatencyMs      float64 `json:"maxLatencyMs"`
	AvgLatencyMs      float64 `json:"avgLatencyMs"`

	// All device pairs with their best path
	DevicePairs []MetroDevicePairPath `json:"devicePairs"`

	Error string `json:"error,omitempty"`
}

MetroDevicePathsResponse is the response for the metro device paths endpoint

type MetroEntity

type MetroEntity struct {
	PK        string  `json:"pk"`
	Code      string  `json:"code"`
	Name      string  `json:"name"`
	Longitude float64 `json:"longitude"`
	Latitude  float64 `json:"latitude"`
}

MetroEntity represents a metro's current state

type MetroImpact

type MetroImpact struct {
	PK               string `json:"pk"`
	Code             string `json:"code"`
	Name             string `json:"name"`
	TotalDevices     int    `json:"totalDevices"`     // Total ISIS devices in this metro
	RemainingDevices int    `json:"remainingDevices"` // Devices still reachable after failure
	IsolatedDevices  int    `json:"isolatedDevices"`  // Devices that become unreachable
}

MetroImpact represents the impact of a device failure on a metro

type MetroInfo

type MetroInfo struct {
	PK   string `json:"pk"`
	Code string `json:"code"`
	Name string `json:"name"`
}

MetroInfo is a lightweight metro representation for the matrix

type MetroListItem

type MetroListItem struct {
	PK                         string  `json:"pk"`
	Code                       string  `json:"code"`
	Name                       string  `json:"name"`
	Country                    string  `json:"country"`
	Latitude                   float64 `json:"latitude"`
	Longitude                  float64 `json:"longitude"`
	DeviceCount                uint64  `json:"device_count"`
	UserCount                  uint64  `json:"user_count"`
	FacilityCount              uint64  `json:"facility_count"`
	UnicastUsersCount          uint64  `json:"unicast_users_count"`
	MulticastSubscribersCount  uint64  `json:"multicast_subscribers_count"`
	MulticastPublishersCount   uint64  `json:"multicast_publishers_count"`
	MaxUsers                   int64   `json:"max_users"`
	MaxUnicastUsers            uint64  `json:"max_unicast_users"`
	MaxMulticastSubscribers    uint64  `json:"max_multicast_subscribers"`
	MaxMulticastPublishers     uint64  `json:"max_multicast_publishers"`
	RawMaxUnicastUsers         uint64  `json:"raw_max_unicast_users"`
	RawMaxMulticastSubscribers uint64  `json:"raw_max_multicast_subscribers"`
	RawMaxMulticastPublishers  uint64  `json:"raw_max_multicast_publishers"`
}

type MetroPath

type MetroPath struct {
	Hops        []MetroPathsHop `json:"hops"`
	TotalHops   int             `json:"totalHops"`
	TotalMetric int64           `json:"totalMetric"`
	LatencyMs   float64         `json:"latencyMs"`
}

MetroPath represents a single path between metros

type MetroPathDetailHop

type MetroPathDetailHop struct {
	DevicePK    string  `json:"devicePK"`
	DeviceCode  string  `json:"deviceCode"`
	MetroPK     string  `json:"metroPK"`
	MetroCode   string  `json:"metroCode"`
	LinkMetric  int64   `json:"linkMetric"`  // Metric to next hop (0 for last hop)
	LinkBwGbps  float64 `json:"linkBwGbps"`  // Bandwidth to next hop (0 for last hop)
	LinkLatency float64 `json:"linkLatency"` // Latency in ms to next hop
}

MetroPathDetailHop represents a single hop in a path

type MetroPathDetailResponse

type MetroPathDetailResponse struct {
	FromMetroCode     string               `json:"fromMetroCode"`
	ToMetroCode       string               `json:"toMetroCode"`
	Optimize          string               `json:"optimize"`
	TotalLatencyMs    float64              `json:"totalLatencyMs"`
	TotalHops         int                  `json:"totalHops"`
	BottleneckBwGbps  float64              `json:"bottleneckBwGbps"`
	InternetLatencyMs float64              `json:"internetLatencyMs"`
	ImprovementPct    *float64             `json:"improvementPct"`
	Hops              []MetroPathDetailHop `json:"hops"`
	Error             string               `json:"error,omitempty"`
}

MetroPathDetailResponse is the response for the metro path detail endpoint

type MetroPathLatency

type MetroPathLatency struct {
	FromMetroPK       string   `json:"fromMetroPK"`
	FromMetroCode     string   `json:"fromMetroCode"`
	ToMetroPK         string   `json:"toMetroPK"`
	ToMetroCode       string   `json:"toMetroCode"`
	PathLatencyMs     float64  `json:"pathLatencyMs"`     // Sum of link metrics along path (in ms)
	HopCount          int      `json:"hopCount"`          // Number of hops
	BottleneckBwGbps  float64  `json:"bottleneckBwGbps"`  // Min bandwidth along path (Gbps)
	InternetLatencyMs float64  `json:"internetLatencyMs"` // Internet latency for comparison (0 if not available)
	ImprovementPct    *float64 `json:"improvementPct"`    // Improvement vs internet (nil if no internet data)
}

MetroPathLatency represents path-based latency between two metros

type MetroPathLatencyResponse

type MetroPathLatencyResponse struct {
	Optimize string             `json:"optimize"` // "hops", "latency", or "bandwidth"
	Paths    []MetroPathLatency `json:"paths"`
	Summary  struct {
		TotalPairs        int     `json:"totalPairs"`
		PairsWithInternet int     `json:"pairsWithInternet"`
		AvgImprovementPct float64 `json:"avgImprovementPct"`
		MaxImprovementPct float64 `json:"maxImprovementPct"`
	} `json:"summary"`
	Error string `json:"error,omitempty"`
}

MetroPathLatencyResponse is the response for the metro path latency endpoint

type MetroPathsHop

type MetroPathsHop struct {
	DevicePK   string `json:"devicePK"`
	DeviceCode string `json:"deviceCode"`
	MetroPK    string `json:"metroPK"`
	MetroCode  string `json:"metroCode"`
}

MetroPathsHop represents a device in a path

type MetroPathsResponse

type MetroPathsResponse struct {
	FromMetroCode string      `json:"fromMetroCode"`
	ToMetroCode   string      `json:"toMetroCode"`
	Paths         []MetroPath `json:"paths"`
	Error         string      `json:"error,omitempty"`
}

MetroPathsResponse is the response for metro paths endpoint

type MetroStats

type MetroStats struct {
	ValidatorCount uint64  `json:"validator_count"`
	StakeSol       float64 `json:"stake_sol"`
	InBps          float64 `json:"in_bps"`
	OutBps         float64 `json:"out_bps"`
}

type MultiFilterParams

type MultiFilterParams struct {
	Filters []FilterParams
}

MultiFilterParams holds multiple parsed filters

func ParseFilters

func ParseFilters(r *http.Request) MultiFilterParams

ParseFilters extracts multiple filters from repeated "filters" query params. Each value is in "field:value" format; plain values default to field="all". Falls back to legacy filter_field/filter_value if "filters" is absent.

func (MultiFilterParams) BuildFilterClause

func (mf MultiFilterParams) BuildFilterClause(fields map[string]FilterFieldConfig) (string, []any)

BuildFilterClause builds a WHERE clause for multiple filters. Filters with the same field are ORed; different fields are ANDed.

func (MultiFilterParams) IsEmpty

func (mf MultiFilterParams) IsEmpty() bool

IsEmpty returns true if no filters are set

type MultiLinkLatencyPoint

type MultiLinkLatencyPoint struct {
	Time         string  `json:"time"`
	LinkPk       string  `json:"link_pk"`
	LinkCode     string  `json:"link_code"`
	RttAtoZMs    float64 `json:"rtt_a_to_z_ms"`
	RttZtoAMs    float64 `json:"rtt_z_to_a_ms"`
	JitterAtoZMs float64 `json:"jitter_a_to_z_ms"`
	JitterZtoAMs float64 `json:"jitter_z_to_a_ms"`
	LossPct      float64 `json:"loss_pct"`
}

MultiLinkLatencyPoint is a time-series point for one link (or aggregate) in a multi-link query.

type MultiLinkLatencyResponse

type MultiLinkLatencyResponse struct {
	Points []MultiLinkLatencyPoint `json:"points"`
}

MultiLinkLatencyResponse is the JSON response for the multi-link latency history endpoint.

type MultiPathHop

type MultiPathHop struct {
	DevicePK        string  `json:"devicePK"`
	DeviceCode      string  `json:"deviceCode"`
	Status          string  `json:"status"`
	DeviceType      string  `json:"deviceType"`
	MetroPK         string  `json:"metroPK,omitempty"`
	MetroCode       string  `json:"metroCode,omitempty"`
	EdgeMetric      uint32  `json:"edgeMetric,omitempty"`      // ISIS metric to reach this hop from previous
	EdgeMeasuredMs  float64 `json:"edgeMeasuredMs,omitempty"`  // measured RTT in ms to reach this hop
	EdgeJitterMs    float64 `json:"edgeJitterMs,omitempty"`    // measured jitter in ms
	EdgeLossPct     float64 `json:"edgeLossPct,omitempty"`     // packet loss percentage
	EdgeSampleCount int64   `json:"edgeSampleCount,omitempty"` // number of samples for confidence
}

MultiPathHop represents a hop in a path with edge metric information

type MultiPathResponse

type MultiPathResponse struct {
	Paths []SinglePath `json:"paths"`
	From  string       `json:"from"`
	To    string       `json:"to"`
	Error string       `json:"error,omitempty"`
}

MultiPathResponse is the response for the K-shortest paths endpoint

type MulticastAggSegment

type MulticastAggSegment struct {
	FromPK       string   `json:"fromPK"`
	ToPK         string   `json:"toPK"`
	PublisherPKs []string `json:"publisherPKs"`
}

MulticastAggSegment represents a unique link segment used by one or more publishers

type MulticastGroupDetail

type MulticastGroupDetail struct {
	PK              string `json:"pk"`
	Code            string `json:"code"`
	MulticastIP     string `json:"multicast_ip"`
	MaxBandwidth    uint64 `json:"max_bandwidth"`
	Status          string `json:"status"`
	PublisherCount  uint32 `json:"publisher_count"`
	SubscriberCount uint32 `json:"subscriber_count"`
	HasShredStats   bool   `json:"has_shred_stats"`
}

type MulticastGroupListItem

type MulticastGroupListItem struct {
	PK              string `json:"pk"`
	Code            string `json:"code"`
	MulticastIP     string `json:"multicast_ip"`
	MaxBandwidth    uint64 `json:"max_bandwidth"`
	Status          string `json:"status"`
	PublisherCount  uint32 `json:"publisher_count"`
	SubscriberCount uint32 `json:"subscriber_count"`
}

type MulticastGroupRef

type MulticastGroupRef struct {
	PK          string `json:"pk"`
	Code        string `json:"code"`
	MulticastIP string `json:"multicast_ip"`
	Status      string `json:"status"`
}

type MulticastMember

type MulticastMember struct {
	UserPK         string  `json:"user_pk"`
	Mode           string  `json:"mode"` // "P", "S", or "P+S"
	DevicePK       string  `json:"device_pk"`
	DeviceCode     string  `json:"device_code"`
	MetroPK        string  `json:"metro_pk"`
	MetroCode      string  `json:"metro_code"`
	MetroName      string  `json:"metro_name"`
	ClientIP       string  `json:"client_ip"`
	DZIP           string  `json:"dz_ip"`
	Status         string  `json:"status"`
	OwnerPubkey    string  `json:"owner_pubkey"`
	TunnelID       int32   `json:"tunnel_id"`
	TrafficBps     float64 `json:"traffic_bps"`      // traffic rate in bits per second
	TrafficPps     float64 `json:"traffic_pps"`      // traffic rate in packets per second
	IsLeader       bool    `json:"is_leader"`        // true if currently the Solana leader
	NodePubkey     string  `json:"node_pubkey"`      // validator's node identity pubkey
	VotePubkey     string  `json:"vote_pubkey"`      // validator's vote account pubkey
	StakeSol       float64 `json:"stake_sol"`        // activated stake in SOL
	LastLeaderSlot *int64  `json:"last_leader_slot"` // most recent past leader slot
	NextLeaderSlot *int64  `json:"next_leader_slot"` // next upcoming leader slot
	CurrentSlot    int64   `json:"current_slot"`     // current cluster slot
}

type MulticastMemberCountPoint

type MulticastMemberCountPoint struct {
	Time            string `json:"time"`
	PublisherCount  int64  `json:"publisher_count"`
	SubscriberCount int64  `json:"subscriber_count"`
}

type MulticastMembersResponse

type MulticastMembersResponse struct {
	Items           []MulticastMember `json:"items"`
	Total           int               `json:"total"`
	PublisherCount  int               `json:"publisher_count"`
	SubscriberCount int               `json:"subscriber_count"`
	Limit           int               `json:"limit"`
	Offset          int               `json:"offset"`
}

MulticastMembersResponse is the paginated response for multicast group members

type MulticastTrafficPoint

type MulticastTrafficPoint struct {
	Time     string  `json:"time"`
	DevicePK string  `json:"device_pk"`
	TunnelID int64   `json:"tunnel_id"`
	Mode     string  `json:"mode"` // "P" or "S"
	InBps    float64 `json:"in_bps"`
	OutBps   float64 `json:"out_bps"`
	InPps    float64 `json:"in_pps"`
	OutPps   float64 `json:"out_pps"`
}

type MulticastTreeHop

type MulticastTreeHop struct {
	DevicePK   string `json:"devicePK"`
	DeviceCode string `json:"deviceCode"`
	DeviceType string `json:"deviceType"`
	EdgeMetric int    `json:"edgeMetric,omitempty"` // metric to reach this hop from previous
}

MulticastTreeHop represents a single hop in a multicast tree path

type MulticastTreePath

type MulticastTreePath struct {
	PublisherDevicePK    string             `json:"publisherDevicePK"`
	PublisherDeviceCode  string             `json:"publisherDeviceCode"`
	SubscriberDevicePK   string             `json:"subscriberDevicePK"`
	SubscriberDeviceCode string             `json:"subscriberDeviceCode"`
	Path                 []MulticastTreeHop `json:"path"`
	TotalMetric          int                `json:"totalMetric"`
	HopCount             int                `json:"hopCount"`
}

MulticastTreePath represents a path from publisher to subscriber

type MulticastTreeResponse

type MulticastTreeResponse struct {
	GroupCode       string              `json:"groupCode"`
	GroupPK         string              `json:"groupPK"`
	PublisherCount  int                 `json:"publisherCount"`
	SubscriberCount int                 `json:"subscriberCount"`
	Paths           []MulticastTreePath `json:"paths"`
	Error           string              `json:"error,omitempty"`
}

MulticastTreeResponse is the response for multicast tree paths endpoint

type MulticastTreeSegmentsResponse

type MulticastTreeSegmentsResponse struct {
	GroupCode       string                `json:"groupCode"`
	GroupPK         string                `json:"groupPK"`
	PublisherCount  int                   `json:"publisherCount"`
	SubscriberCount int                   `json:"subscriberCount"`
	Segments        []MulticastAggSegment `json:"segments"`
	Error           string                `json:"error,omitempty"`
}

MulticastTreeSegmentsResponse is the response for the aggregated tree segments endpoint

type Neo4jQuerier

type Neo4jQuerier struct {
	// contains filtered or unexported fields
}

Neo4jQuerier implements workflow.Querier for Neo4j graph queries.

func (*Neo4jQuerier) Query

func (q *Neo4jQuerier) Query(ctx context.Context, cypher string) (workflow.QueryResult, error)

Query executes a Cypher query and returns formatted results.

type Neo4jSchemaFetcher

type Neo4jSchemaFetcher struct {
	// contains filtered or unexported fields
}

Neo4jSchemaFetcher implements workflow.SchemaFetcher for Neo4j.

func (*Neo4jSchemaFetcher) FetchSchema

func (f *Neo4jSchemaFetcher) FetchSchema(ctx context.Context) (string, error)

FetchSchema returns a formatted string describing the Neo4j graph schema.

type NetworkSummary

type NetworkSummary struct {
	// Counts
	ValidatorsOnDZ  uint64  `json:"validators_on_dz"`
	TotalStakeSol   float64 `json:"total_stake_sol"`
	StakeSharePct   float64 `json:"stake_share_pct"`
	StakeShareDelta float64 `json:"stake_share_delta"` // Change from 24h ago (percentage points)
	Users           uint64  `json:"users"`
	MaxUsers        uint64  `json:"max_users"`
	Devices         uint64  `json:"devices"`
	Links           uint64  `json:"links"`
	Contributors    uint64  `json:"contributors"`
	Metros          uint64  `json:"metros"`
	Facilities      uint64  `json:"facilities"`
	BandwidthBps    int64   `json:"bandwidth_bps"`
	UserInboundBps  float64 `json:"user_inbound_bps"`

	// Status breakdown
	DevicesByStatus map[string]uint64 `json:"devices_by_status"`
	LinksByStatus   map[string]uint64 `json:"links_by_status"`
}

type NonActivatedDevice

type NonActivatedDevice struct {
	PK         string `json:"pk"`
	Code       string `json:"code"`
	DeviceType string `json:"device_type"`
	Metro      string `json:"metro"`
	Status     string `json:"status"`
	Since      string `json:"since"` // ISO timestamp when entered this status
}
type NonActivatedLink struct {
	PK                  string   `json:"pk"`
	Code                string   `json:"code"`
	LinkType            string   `json:"link_type"`
	SideAMetro          string   `json:"side_a_metro"`
	SideZMetro          string   `json:"side_z_metro"`
	Status              string   `json:"status"`
	Since               string   `json:"since"` // ISO timestamp when entered this status
	ActiveIncidentTypes []string `json:"active_incident_types,omitempty"`
	BandwidthBps        int64    `json:"bandwidth_bps"`
}

type NumericOp

type NumericOp struct {
	Op    string
	Value float64
}

NumericOp represents a numeric comparison operator

func ParseNumericFilter

func ParseNumericFilter(input string, fieldType FieldType) *NumericOp

ParseNumericFilter parses a string like ">100" or ">=10k" into operator and value

type OpsAssignee

type OpsAssignee struct {
	Value  string `json:"value"`
	Label  string `json:"label"`
	Type   string `json:"type,omitempty"`
	Pubkey string `json:"pubkey,omitempty"`
}

OpsAssignee is a single assignee/contributor entry, optionally enriched with a ClickHouse pubkey.

type OpsTicket

type OpsTicket struct {
	ID                  string            `json:"id"`                // UUID
	HumanReadableID     string            `json:"human_readable_id"` // e.g. "I20250413-a7b2"
	Type                OpsTicketType     `json:"type"`
	Title               string            `json:"title"`
	Description         string            `json:"description"`
	Severity            *string           `json:"severity,omitempty"` // "sev1"|"sev2"|"sev3"|nil
	Status              string            `json:"status"`             // "open"|"acknowledged"|"investigating"|...
	AffectedLinkPubkeys []string          `json:"affected_link_pubkey"`
	DevicePubkeys       []string          `json:"device_pubkey"`
	AffectedLinks       []OpsTicketEntity `json:"affected_links,omitempty"`
	AffectedDevices     []OpsTicketEntity `json:"affected_devices,omitempty"`
	ReporterName        string            `json:"reporter_name"`
	ReporterEmail       string            `json:"reporter_email"`
	StartAt             *string           `json:"start_at,omitempty"`
	EndAt               *string           `json:"end_at,omitempty"`
	SlackMessageURL     *string           `json:"slack_message_url,omitempty"`
	CreatedAt           string            `json:"created_at"`
	UpdatedAt           string            `json:"updated_at"`
}

OpsTicket is a ticket from the Ops Management API.

type OpsTicketEntity

type OpsTicketEntity struct {
	Code   string `json:"code"`
	Pubkey string `json:"pubkey"`
}

OpsTicketEntity is an enriched link or device reference returned by the Ops API.

type OpsTicketType

type OpsTicketType string

OpsTicketType is either "incident" or "maintenance".

const (
	OpsTicketTypeIncident    OpsTicketType = "incident"
	OpsTicketTypeMaintenance OpsTicketType = "maintenance"
)

type OpsTicketsListResponse

type OpsTicketsListResponse struct {
	Tickets []OpsTicket `json:"tickets"`
	Total   int         `json:"total"`
}

OpsTicketsListResponse wraps a paginated list of tickets.

type PaginatedResponse

type PaginatedResponse[T any] struct {
	Items  []T `json:"items"`
	Total  int `json:"total"`
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

type PaginationParams

type PaginationParams struct {
	Limit  int
	Offset int
}

func ParsePagination

func ParsePagination(r *http.Request, defaultLimit int) PaginationParams

type PathHop

type PathHop struct {
	DevicePK   string `json:"devicePK"`
	DeviceCode string `json:"deviceCode"`
	Status     string `json:"status"`
	DeviceType string `json:"deviceType"`
}

PathHop represents a hop in a path

type PathResponse

type PathResponse struct {
	Path        []PathHop `json:"path"`
	TotalMetric uint32    `json:"totalMetric"`
	HopCount    int       `json:"hopCount"`
	Error       string    `json:"error,omitempty"`
}

PathResponse is the response for the path endpoint

type PerformanceMetrics

type PerformanceMetrics struct {
	// Latency stats (WAN links, last 3 hours)
	AvgLatencyUs float64 `json:"avg_latency_us"`
	P95LatencyUs float64 `json:"p95_latency_us"`
	MinLatencyUs float64 `json:"min_latency_us"`
	MaxLatencyUs float64 `json:"max_latency_us"`

	// Packet loss (WAN links, last 3 hours)
	AvgLossPercent float64 `json:"avg_loss_percent"`

	// Jitter (WAN links, last 3 hours)
	AvgJitterUs float64 `json:"avg_jitter_us"`

	// Total throughput
	TotalInBps  float64 `json:"total_in_bps"`
	TotalOutBps float64 `json:"total_out_bps"`
}

type PublicConfig

type PublicConfig struct {
	GoogleClientID    string          `json:"googleClientId,omitempty"`
	SentryDSN         string          `json:"sentryDsn,omitempty"`
	SentryEnvironment string          `json:"sentryEnvironment,omitempty"`
	SlackEnabled      bool            `json:"slackEnabled,omitempty"`
	Env               string          `json:"env"`
	AvailableEnvs     []string        `json:"availableEnvs"`
	Features          map[string]bool `json:"features"`
}

PublicConfig holds configuration that is safe to expose to the frontend

type PublisherCheckItem

type PublisherCheckItem struct {
	PublisherIP             string `json:"publisher_ip"`
	ClientIP                string `json:"client_ip"`
	NodePubkey              string `json:"node_pubkey"`
	VotePubkey              string `json:"vote_pubkey"`
	DZUserPubkey            string `json:"dz_user_pubkey"`
	DZDeviceCode            string `json:"dz_device_code"`
	DZMetroCode             string `json:"dz_metro_code"`
	ActivatedStake          uint64 `json:"activated_stake"`
	MulticastConnected      bool   `json:"multicast_connected"`
	PublishingLeaderShreds  bool   `json:"publishing_leader_shreds"`
	PublishingRetransmitted bool   `json:"publishing_retransmitted"`
	LeaderSlots             uint64 `json:"leader_slots"`
	TotalSlots              uint64 `json:"total_slots"`
	TotalUniqueShreds       uint64 `json:"total_unique_shreds"`
	SlotsNeedingRepair      uint64 `json:"slots_needing_repair"`
	ValidatorClient         string `json:"validator_client"`
	ValidatorVersion        string `json:"validator_version"`
	ValidatorName           string `json:"validator_name"`
	ValidatorVersionOk      bool   `json:"validator_version_ok"`
	IsBackup                bool   `json:"is_backup"`
}

PublisherCheckItem represents a single publisher's status.

type PublisherCheckResponse

type PublisherCheckResponse struct {
	Epoch               uint64               `json:"epoch"`
	MaxSlot             uint64               `json:"max_slot"`
	TotalNetworkStake   int64                `json:"total_network_stake"`
	TotalPublishers     uint64               `json:"total_publishers"`
	TotalPublisherStake int64                `json:"total_publisher_stake"`
	Publishers          []PublisherCheckItem `json:"publishers"`
}

PublisherCheckResponse is the response for the publisher check endpoint.

type QueryRequest

type QueryRequest struct {
	Query string `json:"query"`
}

type QueryResponse

type QueryResponse struct {
	Columns   []string `json:"columns"`
	Rows      [][]any  `json:"rows"`
	RowCount  int      `json:"row_count"`
	ElapsedMs int64    `json:"elapsed_ms"`
	Error     string   `json:"error,omitempty"`
}

type QuotaExceededError

type QuotaExceededError struct {
	Error     string `json:"error"`
	Remaining int    `json:"remaining"`
	ResetsAt  string `json:"resets_at"`
}

QuotaExceededError represents a quota exceeded error response

type QuotaInfo

type QuotaInfo struct {
	Remaining *int   `json:"remaining"` // nil = unlimited
	Limit     *int   `json:"limit"`     // nil = unlimited
	ResetsAt  string `json:"resets_at"` // ISO timestamp
}

QuotaInfo represents current quota information

type RateLimitError

type RateLimitError struct {
	Error      string `json:"error"`
	Message    string `json:"message"`
	RetryAfter int    `json:"retry_after"` // seconds
}

RateLimitError is returned when rate limit is exceeded.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides per-IP rate limiting for database queries.

func NewRateLimiter

func NewRateLimiter(r rate.Limit, burst int) *RateLimiter

NewRateLimiter creates a rate limiter with the specified rate (requests per second) and burst size. For example, NewRateLimiter(rate.Every(time.Minute/100), 10) allows 100 requests/minute with burst of 10.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ip string) bool

Allow checks if a request from the given IP is allowed.

func (*RateLimiter) AllowWithRetry

func (rl *RateLimiter) AllowWithRetry(ip string) (allowed bool, retryAfter time.Duration)

AllowWithRetry checks if a request is allowed and returns time until next token if not.

type ReadDocsInput

type ReadDocsInput struct {
	Page string `json:"page" jsonschema:"The documentation page to read"`
}

ReadDocsInput is the input for the read_docs tool.

type ReadDocsOutput

type ReadDocsOutput struct {
	Page    string `json:"page"`
	Content string `json:"content"`
}

ReadDocsOutput is the output from the read_docs tool.

type RedundancyGain

type RedundancyGain struct {
	DevicePK   string `json:"devicePK"`
	DeviceCode string `json:"deviceCode"`
	OldDegree  int    `json:"oldDegree"`
	NewDegree  int    `json:"newDegree"`
	WasLeaf    bool   `json:"wasLeaf"` // Was a single point of failure
}

RedundancyGain represents a device that would gain redundancy

type RedundancyIssue

type RedundancyIssue struct {
	Type        string `json:"type"`        // "leaf_device", "critical_link", "single_exit_metro", "no_backup_device"
	Severity    string `json:"severity"`    // "critical", "warning", "info"
	EntityPK    string `json:"entityPK"`    // PK of affected entity
	EntityCode  string `json:"entityCode"`  // Code/name of affected entity
	EntityType  string `json:"entityType"`  // "device", "link", "metro"
	Description string `json:"description"` // Human-readable description
	Impact      string `json:"impact"`      // Impact description
	// Extra fields for links
	TargetPK   string `json:"targetPK,omitempty"`
	TargetCode string `json:"targetCode,omitempty"`
	// Extra fields for context
	MetroPK   string `json:"metroPK,omitempty"`
	MetroCode string `json:"metroCode,omitempty"`
}

RedundancyIssue represents a single redundancy issue in the network

type RedundancyReportResponse

type RedundancyReportResponse struct {
	Issues  []RedundancyIssue `json:"issues"`
	Summary RedundancySummary `json:"summary"`
	Error   string            `json:"error,omitempty"`
}

RedundancyReportResponse is the response for the redundancy report endpoint

type RedundancySummary

type RedundancySummary struct {
	TotalIssues      int `json:"totalIssues"`
	CriticalCount    int `json:"criticalCount"`
	WarningCount     int `json:"warningCount"`
	InfoCount        int `json:"infoCount"`
	LeafDevices      int `json:"leafDevices"`
	CriticalLinks    int `json:"criticalLinks"`
	SingleExitMetros int `json:"singleExitMetros"`
}

type SearchResponse

type SearchResponse struct {
	Query   string                       `json:"query"`
	Results map[string]SearchResultGroup `json:"results"`
}

SearchResponse is the response for the full search endpoint

type SearchResultGroup

type SearchResultGroup struct {
	Items []SearchSuggestion `json:"items"`
	Total int                `json:"total"`
}

SearchResultGroup represents search results for a single entity type

type SearchSuggestion

type SearchSuggestion struct {
	Type     string `json:"type"`
	ID       string `json:"id"`
	Label    string `json:"label"`
	Sublabel string `json:"sublabel"`
	URL      string `json:"url"`
}

SearchSuggestion represents a single autocomplete suggestion

type SeriesInfo

type SeriesInfo struct {
	Key       string  `json:"key"`
	Device    string  `json:"device"`
	Intf      string  `json:"intf"`
	Direction string  `json:"direction"`
	Mean      float64 `json:"mean"`
	LinkPK    string  `json:"link_pk,omitempty"`
	CYOAType  string  `json:"cyoa_type,omitempty"`
}

type Session

type Session struct {
	ID          uuid.UUID       `json:"id"`
	Type        string          `json:"type"`
	Name        *string         `json:"name"`
	Content     json.RawMessage `json:"content"`
	CreatedAt   time.Time       `json:"created_at"`
	UpdatedAt   time.Time       `json:"updated_at"`
	AccountID   *uuid.UUID      `json:"account_id,omitempty"`
	AnonymousID *string         `json:"anonymous_id,omitempty"`
	Env         *string         `json:"env,omitempty"` // Environment from first workflow run (for chat sessions)
}

Session represents a chat or query session

type SessionChatMessage

type SessionChatMessage struct {
	ID              string               `json:"id"`
	Role            string               `json:"role"` // "user" or "assistant"
	Content         string               `json:"content"`
	Env             string               `json:"env,omitempty"` // Environment this message was sent in
	WorkflowData    *SessionWorkflowData `json:"workflowData,omitempty"`
	ExecutedQueries []string             `json:"executedQueries,omitempty"`
	Status          string               `json:"status,omitempty"` // "streaming", "complete", "error"
	WorkflowID      string               `json:"workflowId,omitempty"`
}

SessionChatMessage represents a message in session content, matching the web's ChatMessage format.

type SessionListItem

type SessionListItem struct {
	ID            uuid.UUID  `json:"id"`
	Type          string     `json:"type"`
	Name          *string    `json:"name"`
	ContentLength int        `json:"content_length"`
	CreatedAt     time.Time  `json:"created_at"`
	UpdatedAt     time.Time  `json:"updated_at"`
	AccountID     *uuid.UUID `json:"account_id,omitempty"`
	AnonymousID   *string    `json:"anonymous_id,omitempty"`
}

SessionListItem represents a session in list responses (without full content)

type SessionListResponse

type SessionListResponse struct {
	Sessions []SessionListItem `json:"sessions"`
	Total    int               `json:"total"`
	HasMore  bool              `json:"has_more"`
}

SessionListResponse is the response for listing sessions

type SessionListWithContentResponse

type SessionListWithContentResponse struct {
	Sessions []Session `json:"sessions"`
	Total    int       `json:"total"`
	HasMore  bool      `json:"has_more"`
}

SessionListWithContentResponse is the response for listing sessions with full content

type SessionWorkflowData

type SessionWorkflowData struct {
	DataQuestions     []DataQuestionResponse   `json:"dataQuestions,omitempty"`
	GeneratedQueries  []GeneratedQueryResponse `json:"generatedQueries,omitempty"`
	ExecutedQueries   []ExecutedQueryResponse  `json:"executedQueries,omitempty"`
	FollowUpQuestions []string                 `json:"followUpQuestions,omitempty"`
	ProcessingSteps   []ClientProcessingStep   `json:"processingSteps,omitempty"`
}

SessionWorkflowData contains workflow execution details for display in the web UI.

type ShredClientSeatItem

type ShredClientSeatItem struct {
	PK                       string `json:"pk"`
	DeviceKey                string `json:"device_key"`
	DeviceCode               string `json:"device_code"`
	MetroPK                  string `json:"metro_pk"`
	MetroCode                string `json:"metro_code"`
	ClientIP                 string `json:"client_ip"`
	TenureEpochs             uint16 `json:"tenure_epochs"`
	FundedEpoch              uint64 `json:"funded_epoch"`
	ActiveEpoch              uint64 `json:"active_epoch"`
	HasPriceOverride         uint8  `json:"has_price_override"`
	OverrideUSDCPriceDollars uint16 `json:"override_usdc_price_dollars"`
	EscrowCount              uint32 `json:"escrow_count"`
	TotalUSDCBalance         uint64 `json:"total_usdc_balance"`
	PricePerEpochDollars     int64  `json:"price_per_epoch_dollars"`
	FundingAuthorityKey      string `json:"funding_authority_key"`
	UserPK                   string `json:"user_pk"`
	UserOwnerPubkey          string `json:"user_owner_pubkey"`
	UserStatus               string `json:"user_status"`
	LastActivity             string `json:"last_activity"`
}

ShredClientSeatItem represents a client seat in list responses.

type ShredDeviceHistoryItem

type ShredDeviceHistoryItem struct {
	PK                             string `json:"pk"`
	DeviceKey                      string `json:"device_key"`
	DeviceCode                     string `json:"device_code"`
	IsEnabled                      uint8  `json:"is_enabled"`
	HasSettledSeats                uint8  `json:"has_settled_seats"`
	MetroExchangeKey               string `json:"metro_exchange_key"`
	MetroCode                      string `json:"metro_code"`
	ActiveGrantedSeats             uint16 `json:"active_granted_seats"`
	ActiveTotalAvailableSeats      uint16 `json:"active_total_available_seats"`
	CurrentEpoch                   uint64 `json:"current_epoch"`
	CurrentRequestedSeatCount      uint16 `json:"current_requested_seat_count"`
	CurrentGrantedSeatCount        uint16 `json:"current_granted_seat_count"`
	CurrentTotalAvailableSeats     uint16 `json:"current_total_available_seats"`
	CurrentUSDCMetroPremiumDollars int16  `json:"current_usdc_metro_premium_dollars"`
}

ShredDeviceHistoryItem represents a device subscription history in list responses.

type ShredDeviceItem

type ShredDeviceItem struct {
	DeviceKey         string `json:"device_key"`
	DeviceCode        string `json:"device_code"`
	MetroExchangeKey  string `json:"metro_exchange_key"`
	MetroCode         string `json:"metro_code"`
	IsEnabled         uint8  `json:"is_enabled"`
	BasePriceDollars  uint16 `json:"base_price_dollars"`
	PremiumDollars    int16  `json:"premium_dollars"`
	TotalPriceDollars int64  `json:"total_price_dollars"`
	GrantedSeats      uint16 `json:"granted_seats"`
	Capacity          uint16 `json:"capacity"`
	AvailableSeats    int64  `json:"available_seats"`
}

ShredDeviceItem represents a device with pricing and seat info for the devices page.

type ShredEpochRevenueItem

type ShredEpochRevenueItem struct {
	Epoch        uint64  `json:"epoch"`
	TotalUSDC    float64 `json:"total_usdc"`
	TotalDollars float64 `json:"total_dollars"`
	PaymentCount uint64  `json:"payment_count"`
}

ShredEpochRevenueItem represents payment revenue aggregated per epoch.

type ShredEscrowEventItem

type ShredEscrowEventItem struct {
	EventTS          string  `json:"event_ts"`
	EscrowPK         string  `json:"escrow_pk"`
	ClientSeatPK     string  `json:"client_seat_pk"`
	TxSignature      string  `json:"tx_signature"`
	Slot             uint64  `json:"slot"`
	EventType        string  `json:"event_type"`
	AmountUSDC       *int64  `json:"amount_usdc"`
	BalanceAfterUSDC *int64  `json:"balance_after_usdc"`
	Epoch            *uint64 `json:"epoch"`
	Status           string  `json:"status"`
	Signer           string  `json:"signer"`
	ClientIP         string  `json:"client_ip"`
	SolscanURL       string  `json:"solscan_url"`
}

ShredEscrowEventItem represents a payment escrow event.

type ShredFunderItem

type ShredFunderItem struct {
	FundingAuthorityKey string `json:"funding_authority_key"`
	TotalSeats          uint64 `json:"total_seats"`
	ActiveSeats         uint64 `json:"active_seats"`
	InactiveSeats       uint64 `json:"inactive_seats"`
	ClosedSeats         uint64 `json:"closed_seats"`
	TotalEscrows        uint64 `json:"total_escrows"`
	UniqueDevices       uint64 `json:"unique_devices"`
}

ShredFunderItem represents a funding authority with aggregated seat stats.

type ShredMetroHistoryItem

type ShredMetroHistoryItem struct {
	PK                      string `json:"pk"`
	ExchangeKey             string `json:"exchange_key"`
	MetroCode               string `json:"metro_code"`
	IsCurrentPriceFinalized uint8  `json:"is_current_price_finalized"`
	TotalInitializedDevices uint16 `json:"total_initialized_devices"`
	CurrentEpoch            uint64 `json:"current_epoch"`
	CurrentUSDCPriceDollars uint16 `json:"current_usdc_price_dollars"`
}

ShredMetroHistoryItem represents a metro pricing history in list responses.

type ShredStatsPoint

type ShredStatsPoint struct {
	Time         string `json:"time"`
	DZUserPubkey string `json:"dz_user_pubkey"`
	UniqueShreds uint64 `json:"unique_shreds"`
	TotalPackets uint64 `json:"total_packets"`
	DataShreds   uint64 `json:"data_shreds"`
	CodingShreds uint64 `json:"coding_shreds"`
	Slots        uint64 `json:"slots"`
	LeaderSlots  uint64 `json:"leader_slots"`
	RepairSlots  uint64 `json:"repair_slots"`
}

ShredStatsPoint represents a time-bucketed shred stats data point for a publisher.

type ShredSubscriberHistoryItem

type ShredSubscriberHistoryItem struct {
	Epoch       uint64 `json:"epoch"`
	ActiveSeats uint64 `json:"active_seats"`
}

ShredSubscriberHistoryItem represents active subscriber count per epoch.

type ShredSubscriberRow

type ShredSubscriberRow struct {
	PK                       string
	DeviceKey                string
	DeviceCode               string
	MetroPK                  string
	MetroCode                string
	ClientIP                 string
	TenureEpochs             uint16
	FundedEpoch              uint64
	ActiveEpoch              uint64
	HasPriceOverride         uint8
	OverrideUSDCPriceDollars uint16
	EscrowCount              uint32
	TotalUSDCBalance         uint64
	PricePerEpochDollars     int64
	FundingAuthorityKey      string
	UserPK                   string
	UserOwnerPubkey          string
	UserStatus               string
	LastActivity             *time.Time
}

ShredSubscriberRow is the raw, internal shape of a shred subscriber (client seat) returned by FetchShredSubscribers. Consumers (including the v1 API) map this to their own public shapes.

type ShredsOverview

type ShredsOverview struct {
	// Execution controller state.
	Phase                    string `json:"phase"`
	CurrentSubscriptionEpoch uint64 `json:"current_subscription_epoch"`
	TotalMetros              uint16 `json:"total_metros"`
	TotalEnabledDevices      uint16 `json:"total_enabled_devices"`
	TotalClientSeats         uint32 `json:"total_client_seats"`
	SettledDevicesCount      uint16 `json:"settled_devices_count"`
	SettledClientSeatsCount  uint16 `json:"settled_client_seats_count"`
	NextSeatFundingIndex     uint64 `json:"next_seat_funding_index"`

	// Current Solana epoch (for determining active/inactive seats).
	CurrentSolanaEpoch uint64 `json:"current_solana_epoch"`

	// Aggregate counts.
	ClientSeatCount            uint64 `json:"client_seat_count"`
	PaymentEscrowCount         uint64 `json:"payment_escrow_count"`
	MetroHistoryCount          uint64 `json:"metro_history_count"`
	DeviceHistoryCount         uint64 `json:"device_history_count"`
	ValidatorClientRewardCount uint64 `json:"validator_client_reward_count"`
}

ShredsOverview is a summary of the shred subscription program state.

type SimulateLinkAdditionResponse

type SimulateLinkAdditionResponse struct {
	SourcePK          string           `json:"sourcePK"`
	SourceCode        string           `json:"sourceCode"`
	TargetPK          string           `json:"targetPK"`
	TargetCode        string           `json:"targetCode"`
	Metric            uint32           `json:"metric"`
	ImprovedPaths     []ImprovedPath   `json:"improvedPaths"`
	ImprovedPathCount int              `json:"improvedPathCount"`
	RedundancyGains   []RedundancyGain `json:"redundancyGains"`
	RedundancyCount   int              `json:"redundancyCount"`
	Error             string           `json:"error,omitempty"`
}

SimulateLinkAdditionResponse is the response for simulating link addition

type SimulateLinkRemovalResponse

type SimulateLinkRemovalResponse struct {
	SourcePK            string         `json:"sourcePK"`
	SourceCode          string         `json:"sourceCode"`
	TargetPK            string         `json:"targetPK"`
	TargetCode          string         `json:"targetCode"`
	DisconnectedDevices []ImpactDevice `json:"disconnectedDevices"`
	DisconnectedCount   int            `json:"disconnectedCount"`
	AffectedPaths       []AffectedPath `json:"affectedPaths"`
	AffectedPathCount   int            `json:"affectedPathCount"`
	CausesPartition     bool           `json:"causesPartition"`
	Error               string         `json:"error,omitempty"`
}

SimulateLinkRemovalResponse is the response for simulating link removal

type SingleDeviceHistoryResponse

type SingleDeviceHistoryResponse struct {
	PK            string             `json:"pk"`
	Code          string             `json:"code"`
	DeviceType    string             `json:"device_type"`
	Contributor   string             `json:"contributor"`
	Metro         string             `json:"metro"`
	MaxUsers      int32              `json:"max_users"`
	Hours         []DeviceHourStatus `json:"hours"`
	IssueReasons  []string           `json:"issue_reasons"`
	TimeRange     string             `json:"time_range"`
	BucketMinutes int                `json:"bucket_minutes"`
	BucketCount   int                `json:"bucket_count"`
}

SingleDeviceHistoryResponse is the response for single device history endpoint

type SingleLinkHistoryResponse

type SingleLinkHistoryResponse struct {
	PK             string           `json:"pk"`
	Code           string           `json:"code"`
	CommittedRttUs float64          `json:"committed_rtt_us"`
	Hours          []LinkHourStatus `json:"hours"`
	TimeRange      string           `json:"time_range"`
	BucketMinutes  int              `json:"bucket_minutes"`
	BucketCount    int              `json:"bucket_count"`
}

SingleLinkHistoryResponse is the response for a single link's status history

type SinglePath

type SinglePath struct {
	Path              []MultiPathHop `json:"path"`
	TotalMetric       uint32         `json:"totalMetric"`
	HopCount          int            `json:"hopCount"`
	MeasuredLatencyMs float64        `json:"measuredLatencyMs,omitempty"` // sum of measured RTT along path
	TotalSamples      int64          `json:"totalSamples,omitempty"`      // min samples across hops
}

SinglePath represents one path in a multi-path response

type SlackInstallation

type SlackInstallation struct {
	ID          string    `json:"id"`
	TeamID      string    `json:"team_id"`
	TeamName    *string   `json:"team_name,omitempty"`
	BotToken    string    `json:"-"`
	BotUserID   string    `json:"bot_user_id"`
	Scope       *string   `json:"scope,omitempty"`
	InstalledBy *string   `json:"installed_by,omitempty"`
	IsActive    bool      `json:"is_active"`
	InstalledAt time.Time `json:"installed_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

SlackInstallation represents a Slack workspace installation

type SortParams

type SortParams struct {
	Field     string
	Direction string
}

func ParseSort

func ParseSort(r *http.Request, defaultField string, allowedFields map[string]string) SortParams

func (SortParams) OrderByClause

func (s SortParams) OrderByClause(fieldMapping map[string]string) string

type StakeChange

type StakeChange struct {
	Category       string  `json:"category"` // "joined", "left", "stake_increase", "stake_decrease"
	VotePubkey     string  `json:"vote_pubkey"`
	NodePubkey     string  `json:"node_pubkey"`
	StakeSol       float64 `json:"stake_sol"`        // Current stake (or stake at time of leaving)
	StakeChangeSol float64 `json:"stake_change_sol"` // Delta
	Timestamp      string  `json:"timestamp"`
	City           string  `json:"city,omitempty"`
	Country        string  `json:"country,omitempty"`
}

StakeChange represents a change in DZ stake (validator joined/left or stake changed)

type StakeChangesResponse

type StakeChangesResponse struct {
	Changes   []StakeChange `json:"changes"`
	Summary   ChangeSummary `json:"summary"`
	Range     string        `json:"range"`
	FetchedAt string        `json:"fetched_at"`
	Error     string        `json:"error,omitempty"`
}

type StakeHistoryPoint

type StakeHistoryPoint struct {
	Timestamp     string  `json:"timestamp"`
	DZStakeSol    float64 `json:"dz_stake_sol"`
	TotalStakeSol float64 `json:"total_stake_sol"`
	StakeSharePct float64 `json:"stake_share_pct"`
}

type StakeHistoryResponse

type StakeHistoryResponse struct {
	Points    []StakeHistoryPoint `json:"points"`
	FetchedAt string              `json:"fetched_at"`
	Error     string              `json:"error,omitempty"`
}

type StakeOverview

type StakeOverview struct {
	// Current values
	DZStakeSol     float64 `json:"dz_stake_sol"`
	TotalStakeSol  float64 `json:"total_stake_sol"`
	StakeSharePct  float64 `json:"stake_share_pct"`
	ValidatorCount uint64  `json:"validator_count"`

	// 24h comparison
	DZStakeSol24hAgo    float64 `json:"dz_stake_sol_24h_ago"`
	StakeSharePct24hAgo float64 `json:"stake_share_pct_24h_ago"`
	DZStakeChange24h    float64 `json:"dz_stake_change_24h"`
	ShareChange24h      float64 `json:"share_change_24h"`

	// 7d comparison
	DZStakeSol7dAgo    float64 `json:"dz_stake_sol_7d_ago"`
	StakeSharePct7dAgo float64 `json:"stake_share_pct_7d_ago"`
	DZStakeChange7d    float64 `json:"dz_stake_change_7d"`
	ShareChange7d      float64 `json:"share_change_7d"`

	FetchedAt string `json:"fetched_at"`
	Error     string `json:"error,omitempty"`
}

type StakeValidator

type StakeValidator struct {
	VotePubkey    string  `json:"vote_pubkey"`
	NodePubkey    string  `json:"node_pubkey"`
	StakeSol      float64 `json:"stake_sol"`
	StakeSharePct float64 `json:"stake_share_pct"`
	Commission    int64   `json:"commission"`
	Version       string  `json:"version"`
	City          string  `json:"city"`
	Country       string  `json:"country"`
	OnDZ          bool    `json:"on_dz"`
	DeviceCode    string  `json:"device_code,omitempty"`
	MetroCode     string  `json:"metro_code,omitempty"`
}

StakeValidator represents a validator with stake info for the stake analytics page

type StakeValidatorsResponse

type StakeValidatorsResponse struct {
	Validators    []StakeValidator `json:"validators"`
	TotalCount    int              `json:"total_count"`
	OnDZCount     int              `json:"on_dz_count"`
	TotalStakeSol float64          `json:"total_stake_sol"`
	DZStakeSol    float64          `json:"dz_stake_sol"`
	FetchedAt     string           `json:"fetched_at"`
	Error         string           `json:"error,omitempty"`
}

type StatsResponse

type StatsResponse struct {
	ValidatorsOnDZ uint64  `json:"validators_on_dz"`
	TotalStakeSol  float64 `json:"total_stake_sol"`
	StakeSharePct  float64 `json:"stake_share_pct"`
	Users          uint64  `json:"users"`
	Devices        uint64  `json:"devices"`
	Links          uint64  `json:"links"`
	Contributors   uint64  `json:"contributors"`
	Metros         uint64  `json:"metros"`
	BandwidthBps   int64   `json:"bandwidth_bps"`
	UserInboundBps float64 `json:"user_inbound_bps"`
	FetchedAt      string  `json:"fetched_at"`
	Error          string  `json:"error,omitempty"`
}

type StatusResponse

type StatusResponse struct {
	// Overall status
	Status    string `json:"status"` // "healthy", "degraded", "unhealthy"
	Timestamp string `json:"timestamp"`

	// System health
	System SystemHealth `json:"system"`

	// Network summary
	Network NetworkSummary `json:"network"`

	// Link health
	Links LinkHealth `json:"links"`

	// Interface issues
	Interfaces InterfaceHealth `json:"interfaces"`

	// Infrastructure alerts (non-activated devices/links)
	Alerts InfrastructureAlerts `json:"alerts"`

	// Performance metrics
	Performance PerformanceMetrics `json:"performance"`

	// Device utilization (top by tunnel usage)
	TopDeviceUtil []DeviceUtilization `json:"top_device_util"`

	Error string `json:"error,omitempty"`
}

StatusResponse contains comprehensive health/status information

type StressGroup

type StressGroup struct {
	Key           string    `json:"key"`
	Label         string    `json:"label"`
	P50In         []float64 `json:"p50_in"`
	P95In         []float64 `json:"p95_in"`
	MaxIn         []float64 `json:"max_in"`
	P50Out        []float64 `json:"p50_out"`
	P95Out        []float64 `json:"p95_out"`
	MaxOut        []float64 `json:"max_out"`
	StressedCount []int64   `json:"stressed_count"`
}

type StressResponse

type StressResponse struct {
	Timestamps    []string      `json:"timestamps"`
	P50In         []float64     `json:"p50_in"`
	P95In         []float64     `json:"p95_in"`
	MaxIn         []float64     `json:"max_in"`
	P50Out        []float64     `json:"p50_out"`
	P95Out        []float64     `json:"p95_out"`
	MaxOut        []float64     `json:"max_out"`
	StressedCount []int64       `json:"stressed_count"`
	TotalCount    []int64       `json:"total_count"`
	EffBucket     string        `json:"effective_bucket"`
	Groups        []StressGroup `json:"groups,omitempty"`
}

type SystemHealth

type SystemHealth struct {
	Database     bool   `json:"database"`
	DatabaseMsg  string `json:"database_msg,omitempty"`
	LastIngested string `json:"last_ingested,omitempty"` // Most recent data timestamp
}

type TableInfo

type TableInfo struct {
	Name     string   `json:"name"`
	Database string   `json:"database"`
	Engine   string   `json:"engine"`
	Type     string   `json:"type"`
	Columns  []string `json:"columns,omitempty"`
}

type TenantListItem

type TenantListItem struct {
	PK            string `json:"pk"`
	OwnerPubkey   string `json:"owner_pubkey"`
	Code          string `json:"code"`
	PaymentStatus string `json:"payment_status"`
	VrfID         uint16 `json:"vrf_id"`
	MetroRouting  bool   `json:"metro_routing"`
	RouteLiveness bool   `json:"route_liveness"`
	BillingRate   uint64 `json:"billing_rate"`
}

type TimeRange

type TimeRange struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

TimeRange represents the time range for the query

type TimelineBoundsResponse

type TimelineBoundsResponse struct {
	EarliestData string `json:"earliest_data"` // ISO 8601 timestamp
	LatestData   string `json:"latest_data"`   // ISO 8601 timestamp
}

TimelineBoundsResponse contains the available date range for timeline data

type TimelineEvent

type TimelineEvent struct {
	ID          string `json:"id"`
	EventType   string `json:"event_type"`
	Timestamp   string `json:"timestamp"`
	Category    string `json:"category"`
	Severity    string `json:"severity"`
	Title       string `json:"title"`
	Description string `json:"description,omitempty"`
	EntityType  string `json:"entity_type"`
	EntityPK    string `json:"entity_pk"`
	EntityCode  string `json:"entity_code"`
	Details     any    `json:"details,omitempty"`
}

TimelineEvent represents a single event in the timeline

type TimelineParams

type TimelineParams struct {
	StartTime       time.Time
	EndTime         time.Time
	Categories      []string // "state_change" or "telemetry"
	EntityTypes     []string // "device", "link", "metro", "contributor", "validator", "gossip_node"
	Severities      []string
	Actions         []string // "added", "removed", "changed", "alerting", "resolved"
	DZFilter        string   // "on_dz", "off_dz", or "" for all
	MinStakePct     float64  // Minimum stake_share_pct to include (0 = no filter)
	Search          []string // Search terms to filter by (entity codes, device codes, etc.)
	Limit           int
	Offset          int
	IncludeInternal bool // Whether to include internal users (default: false)
}

TimelineParams holds parsed query parameters

type TimelineResponse

type TimelineResponse struct {
	Events    []TimelineEvent   `json:"events"`
	Total     int               `json:"total"`
	Limit     int               `json:"limit"`
	Offset    int               `json:"offset"`
	TimeRange TimeRange         `json:"time_range"`
	Histogram []HistogramBucket `json:"histogram,omitempty"`
	Error     string            `json:"error,omitempty"`
}

TimelineResponse is the API response for the timeline endpoint

type TopEntity

type TopEntity struct {
	DevicePk        string  `json:"device_pk"`
	DeviceCode      string  `json:"device_code"`
	Intf            string  `json:"intf,omitempty"`
	MetroCode       string  `json:"metro_code"`
	LinkType        string  `json:"link_type"`
	ContributorCode string  `json:"contributor_code"`
	BandwidthBps    float64 `json:"bandwidth_bps"`
	MaxUtil         float64 `json:"max_util"`
	AvgUtil         float64 `json:"avg_util"`
	P95Util         float64 `json:"p95_util"`
	MaxInBps        float64 `json:"max_in_bps"`
	MaxOutBps       float64 `json:"max_out_bps"`
}

type TopResponse

type TopResponse struct {
	Entities []TopEntity `json:"entities"`
}

type TopologyCompareResponse

type TopologyCompareResponse struct {
	ConfiguredLinks int                   `json:"configuredLinks"`
	ISISAdjacencies int                   `json:"isisAdjacencies"`
	MatchedLinks    int                   `json:"matchedLinks"`
	Discrepancies   []TopologyDiscrepancy `json:"discrepancies"`
	Error           string                `json:"error,omitempty"`
}

TopologyCompareResponse is the response for the topology compare endpoint

type TopologyDiscrepancy

type TopologyDiscrepancy struct {
	Type        string `json:"type"` // "missing_isis", "partial_isis", "extra_isis"
	LinkPK      string `json:"linkPK,omitempty"`
	LinkCode    string `json:"linkCode,omitempty"`
	LinkStatus  string `json:"linkStatus,omitempty"` // "activated", "soft-drained", "provisioning"
	DeviceAPK   string `json:"deviceAPK"`
	DeviceACode string `json:"deviceACode"`
	DeviceBPK   string `json:"deviceBPK"`
	DeviceBCode string `json:"deviceBCode"`
	ISISMetric  uint32 `json:"isisMetric,omitempty"`
	Details     string `json:"details"`
}

TopologyDiscrepancy represents a mismatch between configured and ISIS topology

type TopologyLinkHealth

type TopologyLinkHealth struct {
	LinkPK         string  `json:"link_pk"`
	SideAPK        string  `json:"side_a_pk"`
	SideACode      string  `json:"side_a_code"`
	SideZPK        string  `json:"side_z_pk"`
	SideZCode      string  `json:"side_z_code"`
	AvgRttUs       float64 `json:"avg_rtt_us"`
	P95RttUs       float64 `json:"p95_rtt_us"`
	CommittedRttNs int64   `json:"committed_rtt_ns"`
	LossPct        float64 `json:"loss_pct"`
	ExceedsCommit  bool    `json:"exceeds_commit"`
	HasPacketLoss  bool    `json:"has_packet_loss"`
	IsDark         bool    `json:"is_dark"`
	IsDown         bool    `json:"is_down"`
	SlaStatus      string  `json:"sla_status"` // "healthy", "warning", "critical", "unknown"
	SlaRatio       float64 `json:"sla_ratio"`  // measured / committed (0 if no commitment)
}

TopologyLinkHealth represents the SLO health status of a link for topology overlay

type TopologyLinkHealthResponse

type TopologyLinkHealthResponse struct {
	Links         []TopologyLinkHealth `json:"links"`
	TotalLinks    int                  `json:"total_links"`
	HealthyCount  int                  `json:"healthy_count"`
	WarningCount  int                  `json:"warning_count"`
	CriticalCount int                  `json:"critical_count"`
	UnknownCount  int                  `json:"unknown_count"`
}

type TopologyLinkMetricsEntry

type TopologyLinkMetricsEntry struct {
	LatencyUs     float64 `json:"latency_us"`
	JitterUs      float64 `json:"jitter_us"`
	LatencyAtoZUs float64 `json:"latency_a_to_z_us"`
	JitterAtoZUs  float64 `json:"jitter_a_to_z_us"`
	LatencyZtoAUs float64 `json:"latency_z_to_a_us"`
	JitterZtoAUs  float64 `json:"jitter_z_to_a_us"`
	LossPercent   float64 `json:"loss_percent"`
	SampleCount   uint64  `json:"sample_count"`
	InBps         float64 `json:"in_bps"`
	OutBps        float64 `json:"out_bps"`
}

TopologyLinkMetricsEntry holds latency, jitter, loss, and traffic metrics for a single link.

type TopologyLinkMetricsResponse

type TopologyLinkMetricsResponse struct {
	Metrics map[string]TopologyLinkMetricsEntry `json:"metrics"`
	Error   string                              `json:"error,omitempty"`
}

TopologyLinkMetricsResponse is the response for GET /api/topology/link-metrics.

type TopologyResponse

type TopologyResponse struct {
	Metros     []Metro     `json:"metros"`
	Devices    []Device    `json:"devices"`
	Links      []Link      `json:"links"`
	Validators []Validator `json:"validators"`
	Error      string      `json:"error,omitempty"`
}

type TopologyValidatorsResponse

type TopologyValidatorsResponse struct {
	Validators []Validator `json:"validators"`
	Error      string      `json:"error,omitempty"`
}

TopologyValidatorsResponse is the response for GET /api/topology/validators.

type TrafficDataPoint

type TrafficDataPoint struct {
	Time    string  `json:"time"`
	AvgIn   float64 `json:"avgIn"`
	AvgOut  float64 `json:"avgOut"`
	PeakIn  float64 `json:"peakIn"`
	PeakOut float64 `json:"peakOut"`
}

Traffic data point for charts

type TrafficDataResponse

type TrafficDataResponse struct {
	Points         []TrafficPoint      `json:"points"`
	Series         []SeriesInfo        `json:"series"`
	DiscardsSeries []DiscardSeriesInfo `json:"discards_series"`
	EffBucket      string              `json:"effective_bucket"`
	Truncated      bool                `json:"truncated"`
}

TrafficDataResponse is the JSON response for the traffic data endpoint.

type TrafficPoint

type TrafficPoint struct {
	Time               string  `json:"time"`
	DevicePk           string  `json:"device_pk"`
	Device             string  `json:"device"`
	Intf               string  `json:"intf"`
	InBps              float64 `json:"in_bps"`
	OutBps             float64 `json:"out_bps"`
	InDiscards         int64   `json:"in_discards"`
	OutDiscards        int64   `json:"out_discards"`
	InErrors           int64   `json:"in_errors"`
	OutErrors          int64   `json:"out_errors"`
	InFcsErrors        int64   `json:"in_fcs_errors"`
	CarrierTransitions int64   `json:"carrier_transitions"`
}

type TrafficResponse

type TrafficResponse struct {
	Points     []TrafficDataPoint          `json:"points"`
	Interfaces []InterfaceTrafficDataPoint `json:"interfaces,omitempty"`
	Error      string                      `json:"error,omitempty"`
}

type UpdateSessionRequest

type UpdateSessionRequest struct {
	Name    *string         `json:"name"`
	Content json.RawMessage `json:"content"`
}

UpdateSessionRequest is the request body for updating a session

type UpdateSessionRequestWithOwner

type UpdateSessionRequestWithOwner struct {
	Name        *string         `json:"name"`
	Content     json.RawMessage `json:"content"`
	AnonymousID *string         `json:"anonymous_id,omitempty"`
}

UpdateSessionRequestWithOwner includes anonymous_id for ownership

type UsageRecord

type UsageRecord struct {
	QuestionCount int
	InputTokens   int64
	OutputTokens  int64
}

UsageRecord represents a single usage record for tracking

type UserDetail

type UserDetail struct {
	PK              string  `json:"pk"`
	OwnerPubkey     string  `json:"owner_pubkey"`
	Status          string  `json:"status"`
	Kind            string  `json:"kind"`
	DzIP            string  `json:"dz_ip"`
	ClientIP        string  `json:"client_ip"`
	TunnelID        int32   `json:"tunnel_id"`
	DevicePK        string  `json:"device_pk"`
	DeviceCode      string  `json:"device_code"`
	MetroPK         string  `json:"metro_pk"`
	MetroCode       string  `json:"metro_code"`
	MetroName       string  `json:"metro_name"`
	LocationPK      string  `json:"location_pk"`
	LocationCode    string  `json:"location_code"`
	FacilityLocId   uint32  `json:"facility_loc_id"`
	ContributorPK   string  `json:"contributor_pk"`
	ContributorCode string  `json:"contributor_code"`
	TenantPK        string  `json:"tenant_pk"`
	TenantCode      string  `json:"tenant_code"`
	InBps           float64 `json:"in_bps"`
	OutBps          float64 `json:"out_bps"`
	IsValidator     bool    `json:"is_validator"`
	NodePubkey      string  `json:"node_pubkey"`
	VotePubkey      string  `json:"vote_pubkey"`
	StakeSol        float64 `json:"stake_sol"`
	StakeWeightPct  float64 `json:"stake_weight_pct"`
	IsDeleted       bool    `json:"is_deleted"`
}

type UserEntity

type UserEntity struct {
	PK          string `json:"pk"`
	OwnerPubkey string `json:"owner_pubkey"`
	Status      string `json:"status"`
	Kind        string `json:"kind"`
	ClientIP    string `json:"client_ip"`
	DZIP        string `json:"dz_ip"`
	DevicePK    string `json:"device_pk"`
	TunnelID    int32  `json:"tunnel_id"`
	// Joined fields
	DeviceCode string `json:"device_code,omitempty"`
	MetroCode  string `json:"metro_code,omitempty"`
}

UserEntity represents a user's current state

type UserListItem

type UserListItem struct {
	PK           string  `json:"pk"`
	OwnerPubkey  string  `json:"owner_pubkey"`
	Status       string  `json:"status"`
	Kind         string  `json:"kind"`
	DzIP         string  `json:"dz_ip"`
	ClientIP     string  `json:"client_ip"`
	DevicePK     string  `json:"device_pk"`
	DeviceCode   string  `json:"device_code"`
	MetroPK      string  `json:"metro_pk"`
	MetroCode    string  `json:"metro_code"`
	MetroName    string  `json:"metro_name"`
	LocationPK   string  `json:"location_pk"`
	LocationCode string  `json:"location_code"`
	TenantPK     string  `json:"tenant_pk"`
	TenantCode   string  `json:"tenant_code"`
	InBps        float64 `json:"in_bps"`
	OutBps       float64 `json:"out_bps"`
	IsDeleted    bool    `json:"is_deleted"`
}

type UserMulticastGroup

type UserMulticastGroup struct {
	GroupPK         string `json:"group_pk"`
	GroupCode       string `json:"group_code"`
	MulticastIP     string `json:"multicast_ip"`
	Mode            string `json:"mode"`
	Status          string `json:"status"`
	PublisherCount  uint64 `json:"publisher_count"`
	SubscriberCount uint64 `json:"subscriber_count"`
}

type UserTrafficPoint

type UserTrafficPoint struct {
	Time     string  `json:"time"`
	TunnelID int64   `json:"tunnel_id"`
	InBps    float64 `json:"in_bps"`
	OutBps   float64 `json:"out_bps"`
	InPps    float64 `json:"in_pps"`
	OutPps   float64 `json:"out_pps"`
}

type Validator

type Validator struct {
	VotePubkey  string  `json:"vote_pubkey"`
	NodePubkey  string  `json:"node_pubkey"`
	DevicePK    string  `json:"device_pk"`
	TunnelID    int32   `json:"tunnel_id"`
	Latitude    float64 `json:"latitude"`
	Longitude   float64 `json:"longitude"`
	City        string  `json:"city"`
	Country     string  `json:"country"`
	StakeSol    float64 `json:"stake_sol"`
	StakeShare  float64 `json:"stake_share"`
	Commission  int64   `json:"commission"`
	Version     string  `json:"version"`
	GossipIP    string  `json:"gossip_ip"`
	GossipPort  int32   `json:"gossip_port"`
	TPUQuicIP   string  `json:"tpu_quic_ip"`
	TPUQuicPort int32   `json:"tpu_quic_port"`
	InBps       float64 `json:"in_bps"`
	OutBps      float64 `json:"out_bps"`
}

type ValidatorDetail

type ValidatorDetail struct {
	VotePubkey      string  `json:"vote_pubkey"`
	NodePubkey      string  `json:"node_pubkey"`
	StakeSol        float64 `json:"stake_sol"`
	StakeShare      float64 `json:"stake_share"`
	Commission      int64   `json:"commission"`
	OnDZ            bool    `json:"on_dz"`
	DevicePK        string  `json:"device_pk"`
	DeviceCode      string  `json:"device_code"`
	MetroPK         string  `json:"metro_pk"`
	MetroCode       string  `json:"metro_code"`
	City            string  `json:"city"`
	Country         string  `json:"country"`
	GossipIP        string  `json:"gossip_ip"`
	GossipPort      int32   `json:"gossip_port"`
	InBps           float64 `json:"in_bps"`
	OutBps          float64 `json:"out_bps"`
	SkipRate        float64 `json:"skip_rate"`
	Version         string  `json:"version"`
	SoftwareClient  string  `json:"software_client"`
	SoftwareVersion string  `json:"software_version"`
}

type ValidatorEventDetails

type ValidatorEventDetails struct {
	OwnerPubkey                string  `json:"owner_pubkey"`
	DZIP                       string  `json:"dz_ip,omitempty"`
	VotePubkey                 string  `json:"vote_pubkey,omitempty"`
	NodePubkey                 string  `json:"node_pubkey,omitempty"`
	StakeLamports              int64   `json:"stake_lamports,omitempty"`
	StakeSol                   float64 `json:"stake_sol,omitempty"`
	StakeSharePct              float64 `json:"stake_share_pct,omitempty"`
	StakeShareChangePct        float64 `json:"stake_share_change_pct,omitempty"`
	DZTotalStakeSharePct       float64 `json:"dz_total_stake_share_pct,omitempty"`
	UserPK                     string  `json:"user_pk,omitempty"`
	DevicePK                   string  `json:"device_pk,omitempty"`
	DeviceCode                 string  `json:"device_code,omitempty"`
	MetroCode                  string  `json:"metro_code,omitempty"`
	ContributorCode            string  `json:"contributor_code,omitempty"`
	Kind                       string  `json:"kind"`   // "validator" or "gossip_only"
	Action                     string  `json:"action"` // "joined" or "left"
	ContributionChangeLamports int64   `json:"contribution_change_lamports,omitempty"`
	PrevGossipIP               string  `json:"prev_gossip_ip,omitempty"`
}

ValidatorEventDetails contains details for validator join/leave events

type ValidatorListItem

type ValidatorListItem struct {
	VotePubkey     string  `json:"vote_pubkey"`
	NodePubkey     string  `json:"node_pubkey"`
	StakeSol       float64 `json:"stake_sol"`
	StakeShare     float64 `json:"stake_share"`
	Commission     int64   `json:"commission"`
	OnDZ           bool    `json:"on_dz"`
	DeviceCode     string  `json:"device_code"`
	MetroCode      string  `json:"metro_code"`
	City           string  `json:"city"`
	Country        string  `json:"country"`
	InBps          float64 `json:"in_bps"`
	OutBps         float64 `json:"out_bps"`
	SkipRate       float64 `json:"skip_rate"`
	Version        string  `json:"version"`
	SoftwareClient string  `json:"software_client"`
}

type ValidatorListResponse

type ValidatorListResponse struct {
	Items     []ValidatorListItem `json:"items"`
	Total     int                 `json:"total"`
	OnDZCount int                 `json:"on_dz_count"`
	Limit     int                 `json:"limit"`
	Offset    int                 `json:"offset"`
}

type ValidatorMetadataRow

type ValidatorMetadataRow struct {
	IP              string
	ActiveStake     int64
	VoteAccount     string
	SoftwareClient  string
	SoftwareVersion string
}

type ValidatorPerfGroup

type ValidatorPerfGroup struct {
	ValidatorCount  uint64  `json:"validator_count"`
	AvgVoteLag      float64 `json:"avg_vote_lag"`
	AvgSkipRate     float64 `json:"avg_skip_rate"`
	DelinquentCount uint64  `json:"delinquent_count"`
	TotalStakeSOL   float64 `json:"total_stake_sol"`
}

ValidatorPerfGroup holds aggregated performance metrics for a group of validators.

type ValidatorPerfResponse

type ValidatorPerfResponse struct {
	OnDZ  ValidatorPerfGroup `json:"on_dz"`
	OffDZ ValidatorPerfGroup `json:"off_dz"`
	Error string             `json:"error,omitempty"`
}

ValidatorPerfResponse compares DZ vs non-DZ validator performance.

type VersionResponse

type VersionResponse struct {
	Version string `json:"version"`
	Commit  string `json:"commit"`
	Date    string `json:"date"`
}

VersionResponse contains the API build version info.

type VisualizeRequest

type VisualizeRequest struct {
	Columns    []string `json:"columns"`
	SampleRows [][]any  `json:"sampleRows"`
	RowCount   int      `json:"rowCount"`
	Query      string   `json:"query"`
}

VisualizeRequest is the incoming request for visualization recommendation.

type VisualizeResponse

type VisualizeResponse struct {
	Recommended bool     `json:"recommended"`
	ChartType   string   `json:"chartType,omitempty"`
	XAxis       string   `json:"xAxis,omitempty"`
	YAxis       []string `json:"yAxis,omitempty"`
	Reasoning   string   `json:"reasoning,omitempty"`
	Error       string   `json:"error,omitempty"`
}

VisualizeResponse is the recommendation returned to the UI.

type WalletAuthRequest

type WalletAuthRequest struct {
	PublicKey   string  `json:"public_key"`
	Signature   string  `json:"signature"`
	Message     string  `json:"message"`
	AnonymousID *string `json:"anonymous_id,omitempty"` // For session migration
}

WalletAuthRequest is the request for wallet authentication

type WalletAuthResponse

type WalletAuthResponse struct {
	Token   string   `json:"token"`
	Account *Account `json:"account"`
}

WalletAuthResponse is the response for wallet authentication

type WalletNonceResponse

type WalletNonceResponse struct {
	Nonce string `json:"nonce"`
}

WalletNonceResponse is the response for nonce request

type WhatIfAffectedPath

type WhatIfAffectedPath struct {
	Source       string `json:"source"`
	Target       string `json:"target"`
	SourceMetro  string `json:"sourceMetro,omitempty"`
	TargetMetro  string `json:"targetMetro,omitempty"`
	HopsBefore   int    `json:"hopsBefore"`
	MetricBefore int    `json:"metricBefore"`
	HopsAfter    int    `json:"hopsAfter"`   // -1 if disconnected
	MetricAfter  int    `json:"metricAfter"` // -1 if disconnected
	Status       string `json:"status"`      // "rerouted", "degraded", "disconnected"
}

WhatIfAffectedPath represents a path affected by removal

type WhatIfRemovalItem

type WhatIfRemovalItem struct {
	Type                string               `json:"type"` // "device" or "link"
	PK                  string               `json:"pk"`   // Device PK or Link PK
	Code                string               `json:"code"` // Display name
	AffectedPaths       []WhatIfAffectedPath `json:"affectedPaths"`
	AffectedPathCount   int                  `json:"affectedPathCount"`
	DisconnectedDevices []string             `json:"disconnectedDevices"`
	DisconnectedCount   int                  `json:"disconnectedCount"`
	CausesPartition     bool                 `json:"causesPartition"`
}

WhatIfRemovalItem represents impact of a single device or link removal

type WhatIfRemovalRequest

type WhatIfRemovalRequest struct {
	Devices []string `json:"devices"` // Device PKs
	Links   []string `json:"links"`   // Link PKs
}

WhatIfRemovalRequest is the request body for unified what-if removal analysis

type WhatIfRemovalResponse

type WhatIfRemovalResponse struct {
	Items              []WhatIfRemovalItem  `json:"items"`
	TotalAffectedPaths int                  `json:"totalAffectedPaths"`
	TotalDisconnected  int                  `json:"totalDisconnected"`
	AffectedPaths      []WhatIfAffectedPath `json:"affectedPaths,omitempty"`
	DisconnectedList   []string             `json:"disconnectedList,omitempty"`
	Error              string               `json:"error,omitempty"`
}

WhatIfRemovalResponse is the response for unified what-if removal analysis

type WorkflowCheckpoint

type WorkflowCheckpoint struct {
	Iteration       int                      `json:"iteration"`
	Messages        []workflow.ToolMessage   `json:"messages"`
	ThinkingSteps   []string                 `json:"thinking_steps"`   // Legacy
	ExecutedQueries []workflow.ExecutedQuery `json:"executed_queries"` // Legacy
	Steps           []WorkflowStep           `json:"steps"`            // Unified timeline

	// Metrics
	LLMCalls     int `json:"llm_calls"`
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`
}

WorkflowCheckpoint represents the state to be checkpointed after each iteration.

type WorkflowEvent

type WorkflowEvent struct {
	Type string // "thinking", "query_started", "query_done", "done", "error"
	Data any
}

WorkflowEvent represents a progress event from a running workflow.

type WorkflowManager

type WorkflowManager struct {
	// contains filtered or unexported fields
}

WorkflowManager manages background workflow execution.

func NewWorkflowManager

func NewWorkflowManager(api *API) *WorkflowManager

NewWorkflowManager creates a new WorkflowManager bound to the given API.

func (*WorkflowManager) CancelWorkflow

func (m *WorkflowManager) CancelWorkflow(workflowID uuid.UUID) bool

CancelWorkflow cancels a running workflow.

func (*WorkflowManager) GetRunningWorkflowID

func (m *WorkflowManager) GetRunningWorkflowID(sessionID uuid.UUID) (uuid.UUID, bool)

GetRunningWorkflowID returns the workflow ID for a session, if one is running.

func (*WorkflowManager) IsRunning

func (m *WorkflowManager) IsRunning(workflowID uuid.UUID) bool

IsRunning checks if a workflow is currently running in memory.

func (*WorkflowManager) ResumeIncompleteWorkflows

func (m *WorkflowManager) ResumeIncompleteWorkflows()

ResumeIncompleteWorkflows checks for and resumes any workflows that were interrupted (e.g., by a server restart). Uses distributed locking to ensure only one replica claims each workflow.

func (*WorkflowManager) ResumeWorkflowBackground

func (m *WorkflowManager) ResumeWorkflowBackground(run *WorkflowRun) error

ResumeWorkflowBackground resumes an incomplete workflow in the background. This is called on server startup for workflows left in 'running' state.

func (*WorkflowManager) StartWorkflow

func (m *WorkflowManager) StartWorkflow(
	sessionID uuid.UUID,
	question string,
	history []workflow.ConversationMessage,
	format string,
	env ...DZEnv,
) (uuid.UUID, error)

StartWorkflow starts a new workflow in the background. Returns the workflow ID immediately - the workflow runs asynchronously. The format parameter controls output formatting: "slack" for Slack-specific formatting.

func (*WorkflowManager) Subscribe

func (m *WorkflowManager) Subscribe(workflowID uuid.UUID) *WorkflowSubscriber

Subscribe creates a subscriber to receive events from a workflow. Returns nil if the workflow is not running.

func (*WorkflowManager) Unsubscribe

func (m *WorkflowManager) Unsubscribe(workflowID uuid.UUID, sub *WorkflowSubscriber)

Unsubscribe removes a subscriber from a workflow.

type WorkflowRun

type WorkflowRun struct {
	ID           uuid.UUID `json:"id"`
	SessionID    uuid.UUID `json:"session_id"`
	Status       string    `json:"status"` // running, completed, failed, cancelled
	UserQuestion string    `json:"user_question"`

	// Checkpoint state
	Iteration       int             `json:"iteration"`
	Messages        json.RawMessage `json:"messages"`
	ThinkingSteps   json.RawMessage `json:"thinking_steps"`   // Legacy - kept for backward compatibility
	ExecutedQueries json.RawMessage `json:"executed_queries"` // Legacy - kept for backward compatibility
	Steps           json.RawMessage `json:"steps"`            // Unified timeline of all steps in order
	FinalAnswer     *string         `json:"final_answer,omitempty"`

	// Metrics
	LLMCalls     int `json:"llm_calls"`
	InputTokens  int `json:"input_tokens"`
	OutputTokens int `json:"output_tokens"`

	// Timestamps
	StartedAt   time.Time  `json:"started_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`

	// Distributed claiming (for multi-replica resumption)
	ClaimedBy *string    `json:"claimed_by,omitempty"`
	ClaimedAt *time.Time `json:"claimed_at,omitempty"`

	// Environment
	Env string `json:"env"`

	// Error tracking
	Error *string `json:"error,omitempty"`
}

WorkflowRun represents a persistent workflow execution.

type WorkflowStep

type WorkflowStep struct {
	ID   string `json:"id"`   // Unique identifier for this step
	Type string `json:"type"` // "thinking", "sql_query", "cypher_query", "read_docs"

	// For thinking steps
	Content string `json:"content,omitempty"`

	// For sql_query steps
	Question string   `json:"question,omitempty"`
	SQL      string   `json:"sql,omitempty"`
	Status   string   `json:"status,omitempty"` // "running", "completed", "error"
	Columns  []string `json:"columns,omitempty"`
	Rows     [][]any  `json:"rows,omitempty"`
	Count    int      `json:"count,omitempty"`
	Error    string   `json:"error,omitempty"`

	// For cypher_query steps
	Cypher string `json:"cypher,omitempty"`
	Nodes  []any  `json:"nodes,omitempty"`
	Edges  []any  `json:"edges,omitempty"`

	// For read_docs steps
	Page string `json:"page,omitempty"`

	// Environment this step was executed in
	Env string `json:"env,omitempty"`
}

WorkflowStep represents a single step in the workflow execution timeline. Steps are stored in execution order to preserve the interleaving of thinking and tool calls.

Step types:

  • "thinking": Model reasoning (Content field)
  • "sql_query": SQL query execution (Question, SQL, Status, Columns, Rows, Count, Error)
  • "cypher_query": Cypher query execution (Question, Cypher, Status, Nodes, Edges, Count, Error)
  • "read_docs": Documentation lookup (Page, Status, Content, Error)

type WorkflowStreamResponse

type WorkflowStreamResponse struct {
	// For completed workflows, contains the final response
	Status   string        `json:"status"`
	Response *ChatResponse `json:"response,omitempty"`
	Error    string        `json:"error,omitempty"`

	// For running workflows, contains catch-up events
	ThinkingSteps   []string        `json:"thinking_steps,omitempty"`
	ExecutedQueries json.RawMessage `json:"executed_queries,omitempty"`
}

WorkflowStreamResponse contains the events to emit for a workflow stream reconnection.

type WorkflowSubscriber

type WorkflowSubscriber struct {
	Events chan WorkflowEvent
	Done   chan struct{}
}

WorkflowSubscriber receives events from a running workflow.

Directories

Path Synopsis
Package dberror provides utilities for handling database connectivity errors.
Package dberror provides utilities for handling database connectivity errors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL