2024-04-04 17:17:23 +01:00
|
|
|
package client
|
|
|
|
|
|
|
|
import "net/netip"
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// runtimeIndex stores information about runtime clients.
|
|
|
|
type runtimeIndex struct {
|
2024-04-04 17:17:23 +01:00
|
|
|
// index maps IP address to runtime client.
|
|
|
|
index map[netip.Addr]*Runtime
|
|
|
|
}
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// newRuntimeIndex returns initialized runtime index.
|
|
|
|
func newRuntimeIndex() (ri *runtimeIndex) {
|
|
|
|
return &runtimeIndex{
|
2024-04-04 17:17:23 +01:00
|
|
|
index: map[netip.Addr]*Runtime{},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// client returns the saved runtime client by ip. If no such client exists,
|
2024-04-04 17:17:23 +01:00
|
|
|
// returns nil.
|
2024-09-30 12:17:42 +01:00
|
|
|
func (ri *runtimeIndex) client(ip netip.Addr) (rc *Runtime) {
|
2024-04-04 17:17:23 +01:00
|
|
|
return ri.index[ip]
|
|
|
|
}
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// add saves the runtime client in the index. IP address of a client must be
|
2024-04-04 17:17:23 +01:00
|
|
|
// unique. See [Runtime.Client]. rc must not be nil.
|
2024-09-30 12:17:42 +01:00
|
|
|
func (ri *runtimeIndex) add(rc *Runtime) {
|
2024-04-04 17:17:23 +01:00
|
|
|
ip := rc.Addr()
|
|
|
|
ri.index[ip] = rc
|
|
|
|
}
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// rangeClients calls f for each runtime client in an undefined order.
|
|
|
|
func (ri *runtimeIndex) rangeClients(f func(rc *Runtime) (cont bool)) {
|
2024-04-04 17:17:23 +01:00
|
|
|
for _, rc := range ri.index {
|
|
|
|
if !f(rc) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// setInfo sets the client information from cs for runtime client stored by ip.
|
|
|
|
// If no such client exists, it creates one.
|
|
|
|
func (ri *runtimeIndex) setInfo(ip netip.Addr, cs Source, hosts []string) (rc *Runtime) {
|
|
|
|
rc = ri.index[ip]
|
|
|
|
if rc == nil {
|
|
|
|
rc = NewRuntime(ip)
|
|
|
|
ri.add(rc)
|
|
|
|
}
|
|
|
|
|
|
|
|
rc.setInfo(cs, hosts)
|
|
|
|
|
|
|
|
return rc
|
2024-04-04 17:17:23 +01:00
|
|
|
}
|
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// clearSource removes information from the specified source from all clients.
|
|
|
|
func (ri *runtimeIndex) clearSource(src Source) {
|
|
|
|
for _, rc := range ri.index {
|
2024-04-04 17:17:23 +01:00
|
|
|
rc.unset(src)
|
2024-09-30 12:17:42 +01:00
|
|
|
}
|
|
|
|
}
|
2024-04-04 17:17:23 +01:00
|
|
|
|
2024-09-30 12:17:42 +01:00
|
|
|
// removeEmpty removes empty runtime clients and returns the number of removed
|
|
|
|
// clients.
|
|
|
|
func (ri *runtimeIndex) removeEmpty() (n int) {
|
|
|
|
for ip, rc := range ri.index {
|
2024-04-04 17:17:23 +01:00
|
|
|
if rc.isEmpty() {
|
|
|
|
delete(ri.index, ip)
|
|
|
|
n++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return n
|
|
|
|
}
|