Files
cloud-ip-validator/internal/db/subnet_matcher.go
T
ayurishchevandClaude Sonnet 5.5 1536723196 Registry: trend chart, always-pass indicator, subnet columns in the address list dialog
- Registry: "Динамика по запускам" chart (Chart.js 4.5.1, vendored) over finalized
  runs per target or site, % or count, subnet and calendar period filters;
  GET /admin/registry/trend
- Registry: clickable "Всегда проходили" indicator with the address list and CSV;
  GET /admin/registry/always-pass and /always-pass/list
- Address list dialog: "Подсеть" and "Метка подсети" columns from the
  administrator's subnet list (shared db.SubnetMatcher), per-subnet summary chips
  with a client-side filter; "прочие" renamed to "вне списка подсетей"
- Rebuild control-api and admin-dashboard binaries; plans and summaries in
  docs/changes, README, API and USAGE updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-08 13:15:02 +03:00

58 lines
1.4 KiB
Go

package db
import (
"net/netip"
"sort"
)
// SubnetOutside is the group name of an address that matches no configured
// subnet (or is not an IP address at all).
const SubnetOutside = "вне списка подсетей"
// SubnetMatcher maps an address to the most specific configured subnet.
type SubnetMatcher struct {
list []subnetEntry
}
type subnetEntry struct {
p netip.Prefix
label string
}
// NewSubnetMatcher builds a matcher from the administrator's subnet list.
// Entries that are not valid CIDR are skipped.
func NewSubnetMatcher(subnets []Subnet) *SubnetMatcher {
m := &SubnetMatcher{}
for _, s := range subnets {
if p, err := netip.ParsePrefix(s.CIDR); err == nil {
m.list = append(m.list, subnetEntry{p.Masked(), s.Label})
}
}
sort.SliceStable(m.list, func(i, j int) bool { return m.list[i].p.Bits() > m.list[j].p.Bits() })
return m
}
// Lookup returns the CIDR and the label of the most specific subnet that
// contains ip. With an empty list the address is grouped by /24 (/64 for
// IPv6) without a label. An address outside the list gets SubnetOutside.
func (m *SubnetMatcher) Lookup(ip string) (cidr, label string) {
a, err := netip.ParseAddr(ip)
if err != nil {
return SubnetOutside, ""
}
if len(m.list) == 0 {
bits := 24
if a.Is6() {
bits = 64
}
p, _ := a.Prefix(bits)
return p.String(), ""
}
for _, e := range m.list {
if e.p.Contains(a) {
return e.p.String(), e.label
}
}
return SubnetOutside, ""
}