m/pkg/event: make type-safe
This is a fairly large change which makes use of Go type parameters
(“generics”) to make the event library (and its memory/etcd
implementations) type safe.
Since we now have the event.Value interface strongly typed, we also move
options which were implementation-specific (like BacklogOnly)
to be part of that interface, instead of the previously type-asserted
specific implementations. Use of options that are not handled by a
particular implementation is a runtime error. Expressing this in the
type system is probably not worth the effort.
We also implement Filter to allow offloading some of the functionality previously implemented in type assertion wrappers into the library itself.
In the end, this ends up removing a bunch of type assertion code, at
the cost of a fairly sweeping change. Unfortunately, some of this is due
to IntelliJ suddenly deciding to reformat comments.
Change-Id: I1ca6d93db1b5c4055a21af3fb9e5e3d425c0d86e
Reviewed-on: https://review.monogon.dev/c/monogon/+/1322
Tested-by: Jenkins CI
Reviewed-by: Leopold Schabel <leo@monogon.tech>
diff --git a/metropolis/pkg/event/memory/example_test.go b/metropolis/pkg/event/memory/example_test.go
index a119666..583650c 100644
--- a/metropolis/pkg/event/memory/example_test.go
+++ b/metropolis/pkg/event/memory/example_test.go
@@ -21,8 +21,6 @@
"fmt"
"net"
"time"
-
- "source.monogon.dev/metropolis/pkg/event"
)
// NetworkStatus is example data that will be stored in a Value.
@@ -31,35 +29,11 @@
DefaultGateway net.IP
}
-// NetworkStatusWatcher is a typesafe wrapper around a Watcher.
-type NetworkStatusWatcher struct {
- watcher event.Watcher
-}
-
-// Get wraps Watcher.Get and performs type assertion.
-func (s *NetworkStatusWatcher) Get(ctx context.Context) (*NetworkStatus, error) {
- val, err := s.watcher.Get(ctx)
- if err != nil {
- return nil, err
- }
- ns := val.(NetworkStatus)
- return &ns, nil
-}
-
// NetworkService is a fake/example network service that is responsible for
// communicating the newest information about a machine's network configuration
// to consumers/watchers.
type NetworkService struct {
- Provider Value
-}
-
-// Watch is a thin wrapper around Value.Watch that returns the typesafe
-// NetworkStatusWatcher wrapper.
-func (s *NetworkService) Watch() NetworkStatusWatcher {
- watcher := s.Provider.Watch()
- return NetworkStatusWatcher{
- watcher: watcher,
- }
+ Provider Value[NetworkStatus]
}
// Run pretends to execute the network service's main logic loop, in which it
@@ -113,7 +87,7 @@
// Run an /etc/hosts updater. It will watch for updates from the NetworkService
// about the current IP address of the node.
go func() {
- w := ns.Watch()
+ w := ns.Provider.Watch()
for {
status, err := w.Get(ctx)
if err != nil {