Add CORS support and response caching to aggregate endpoints
- Introduced CORS configuration options in config.example.yaml, allowing specification of allowed origins for cross-origin requests. - Enhanced the aggregate handler to support response caching with a configurable TTL, improving performance for repeated requests. - Updated the aggregate API to return a structured response indicating whether any upstream requests failed, enhancing error handling and response clarity. - Modified documentation in AGGREGATE.md and README.md to reflect the new CORS and caching features. - Added tests to validate the new functionality in the aggregate handler.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package aggregate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/telemt/telemt-api/internal/config"
|
||||
)
|
||||
|
||||
// FetchFleetStatus probes GET health and GET system/info for each alias in parallel.
|
||||
func FetchFleetStatus(ctx context.Context, client *http.Client, parsed *config.Parsed, aliases []string) FleetStatusData {
|
||||
if len(aliases) == 0 {
|
||||
return FleetStatusData{}
|
||||
}
|
||||
rows := make([]FleetServerStatus, len(aliases))
|
||||
var wg sync.WaitGroup
|
||||
for i, alias := range aliases {
|
||||
i, alias := i, alias
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
rows[i] = probeFleetServer(ctx, client, parsed, alias)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
sort.Slice(rows, func(i, j int) bool { return rows[i].Alias < rows[j].Alias })
|
||||
allOK, failed := 0, 0
|
||||
for _, r := range rows {
|
||||
if r.OK {
|
||||
allOK++
|
||||
} else {
|
||||
failed++
|
||||
}
|
||||
}
|
||||
return FleetStatusData{
|
||||
Servers: rows,
|
||||
ServersTotal: len(rows),
|
||||
ServersAllOK: allOK,
|
||||
ServersFailed: failed,
|
||||
}
|
||||
}
|
||||
|
||||
func probeFleetServer(ctx context.Context, client *http.Client, parsed *config.Parsed, alias string) FleetServerStatus {
|
||||
h, hm := FetchTelemtGET[HealthData](ctx, client, parsed, alias, "health")
|
||||
s, sm := FetchTelemtGET[SystemInfoData](ctx, client, parsed, alias, "system/info")
|
||||
row := FleetServerStatus{Alias: alias}
|
||||
row.HealthOK = hm.OK
|
||||
row.HealthHTTPStatus = hm.HTTPStatus
|
||||
row.HealthLatencyMs = hm.LatencyMs
|
||||
row.HealthError = hm.Error
|
||||
row.HealthRevision = hm.Revision
|
||||
if hm.OK {
|
||||
row.Health = &h
|
||||
}
|
||||
row.SystemInfoOK = sm.OK
|
||||
row.SystemInfoHTTPStatus = sm.HTTPStatus
|
||||
row.SystemInfoLatencyMs = sm.LatencyMs
|
||||
row.SystemInfoError = sm.Error
|
||||
row.SystemInfoRevision = sm.Revision
|
||||
if sm.OK {
|
||||
row.SystemInfo = &s
|
||||
}
|
||||
row.OK = hm.OK && sm.OK
|
||||
return row
|
||||
}
|
||||
Reference in New Issue
Block a user