Skip to content

Instantly share code, notes, and snippets.

@cmars
Last active August 29, 2015 14:26
Show Gist options
  • Save cmars/261d26348e0d7e63c924 to your computer and use it in GitHub Desktop.
Save cmars/261d26348e0d7e63c924 to your computer and use it in GitHub Desktop.
dependency engine example
package main
import (
"fmt"
"os"
"time"
"github.com/juju/juju/worker"
"github.com/juju/juju/worker/dependency"
)
func neverFatal(err error) bool {
return false
}
type fooWorker struct {
worker.Worker
ch chan string
}
func newFooWorker(_ dependency.GetResourceFunc) (worker.Worker, error) {
w := &fooWorker{
ch: make(chan string),
}
w.Worker = worker.NewSimpleWorker(w.makeFoo)
return w, nil
}
func (w *fooWorker) makeFoo(stopCh <-chan struct{}) error {
fmt.Println("foo started")
for i := 0; i < 10; i++ {
timer := time.NewTimer(time.Second)
select {
case <-stopCh:
return nil
case <-timer.C:
w.ch <- "foo"
timer.Reset(time.Second)
}
}
fmt.Println("foo is tired")
return fmt.Errorf("foo is tired")
}
func wantsFoo(worker worker.Worker, target interface{}) error {
fooChan, ok := target.(*chan string)
if !ok {
return fmt.Errorf("%T isn't *chan string", target)
}
fooWorker, ok := worker.(*fooWorker)
if !ok {
return fmt.Errorf("%T isn't *fooWorker", worker)
}
*fooChan = fooWorker.ch
fmt.Println("success")
return nil
}
type barWorker struct {
worker.Worker
ch chan string
}
func newBarWorker(getResource dependency.GetResourceFunc) (worker.Worker, error) {
w := &barWorker{}
err := getResource("foo", &w.ch)
if err != nil {
return nil, err
}
w.Worker = worker.NewSimpleWorker(w.showFoo)
return w, nil
}
func (w *barWorker) showFoo(stopCh <-chan struct{}) error {
for {
select {
case <-stopCh:
return nil
case s := <-w.ch:
fmt.Println(s)
}
}
}
func main() {
e := dependency.NewEngine(neverFatal, time.Second, time.Second)
manifolds := dependency.Manifolds{
"foo": dependency.Manifold{
Start: newFooWorker,
Output: wantsFoo,
},
"bar": dependency.Manifold{
Inputs: []string{"foo"},
Start: newBarWorker,
},
}
dependency.Install(e, manifolds)
err := e.Wait()
if err != nil {
println(err)
os.Exit(1)
}
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment