lang: interfaces, funcs: Port Func API to new Stream signature

This removes the `Close() error` and replaces it with a more modern
Stream API that takes a context. This removes boilerplate and makes
integration with concurrent code easier. The only downside is that there
isn't an explicit cleanup step, but only one function was even using
that and it was possible to switch it to a defer in Stream.

This also renames the functions from polyfunc to just func which we
determine by API not naming.
This commit is contained in:
James Shubin
2023-05-28 16:20:42 -04:00
parent 6a06f7b2ea
commit b134c4b778
41 changed files with 276 additions and 540 deletions

View File

@@ -18,6 +18,7 @@
package structs
import (
"context"
"fmt"
"github.com/purpleidea/mgmt/lang/interfaces"
@@ -33,8 +34,7 @@ const (
type ConstFunc struct {
Value types.Value
init *interfaces.Init
closeChan chan struct{}
init *interfaces.Init
}
// String returns a simple name for this function. This is needed so this struct
@@ -70,24 +70,17 @@ func (obj *ConstFunc) Info() *interfaces.Info {
// Init runs some startup code for this const.
func (obj *ConstFunc) Init(init *interfaces.Init) error {
obj.init = init
obj.closeChan = make(chan struct{})
return nil
}
// Stream returns the single value that this const has, and then closes.
func (obj *ConstFunc) Stream() error {
func (obj *ConstFunc) Stream(ctx context.Context) error {
select {
case obj.init.Output <- obj.Value:
// pass
case <-obj.closeChan:
case <-ctx.Done():
return nil
}
close(obj.init.Output) // signal that we're done sending
return nil
}
// Close runs some shutdown code for this const and turns off the stream.
func (obj *ConstFunc) Close() error {
close(obj.closeChan)
return nil
}