Add CORS support and response caching to aggregate endpoints
Publish telemt-api gateway Docker image / test (push) Successful in 25s
Publish telemt-api gateway Docker image / build-and-push (push) Successful in 1m19s

- 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:
Denozordec
2026-03-30 10:02:16 +07:00
parent 2a8390e687
commit 04c257a84e
14 changed files with 1071 additions and 142 deletions
+13 -7
View File
@@ -15,13 +15,14 @@ var aliasRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)
// Config is the gateway YAML configuration.
type Config struct {
Listen string `yaml:"listen"`
AllowAll bool `yaml:"allow_all"`
WhitelistCIDRs []string `yaml:"whitelist_cidrs"`
TrustedProxies []string `yaml:"trusted_proxies"`
Servers []Server `yaml:"servers"`
Aggregate *AggregateConfig `yaml:"aggregate"`
GeoIP *GeoIPConfig `yaml:"geoip"`
Listen string `yaml:"listen"`
AllowAll bool `yaml:"allow_all"`
WhitelistCIDRs []string `yaml:"whitelist_cidrs"`
TrustedProxies []string `yaml:"trusted_proxies"`
CorsAllowedOrigins []string `yaml:"cors_allowed_origins"`
Servers []Server `yaml:"servers"`
Aggregate *AggregateConfig `yaml:"aggregate"`
GeoIP *GeoIPConfig `yaml:"geoip"`
}
// GeoIPConfig enables GeoLite2 lookups for /api/agg/unique-ips (optional).
@@ -38,6 +39,8 @@ type GeoIPConfig struct {
type AggregateConfig struct {
// IncludeAliases limits aggregation to these server aliases; empty means all servers.
IncludeAliases []string `yaml:"include_aliases"`
// CacheTTLMs is in-memory cache TTL for successful GET /api/agg/* responses (milliseconds). 0 disables.
CacheTTLMs uint64 `yaml:"cache_ttl_ms"`
}
// Server maps a URL alias to an upstream base URL.
@@ -123,6 +126,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("aggregate.include_aliases[%d]: unknown server alias %q", i, a)
}
}
if c.Aggregate.CacheTTLMs > 60000 {
return fmt.Errorf("aggregate.cache_ttl_ms must be within [0, 60000]")
}
}
return nil
}
+16
View File
@@ -98,3 +98,19 @@ func TestValidateAggregateIncludeAliases(t *testing.T) {
t.Fatal("expected error for unknown include alias")
}
}
func TestValidateAggregateCacheTTL(t *testing.T) {
c := &Config{
Servers: []Server{
{Alias: "a", BaseURL: "http://x:1"},
},
Aggregate: &AggregateConfig{CacheTTLMs: 60001},
}
if err := c.Validate(); err == nil {
t.Fatal("expected error for cache_ttl_ms > 60000")
}
c.Aggregate.CacheTTLMs = 1000
if err := c.Validate(); err != nil {
t.Fatal(err)
}
}