72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
// Command worker is a demo peer: it creates (or joins) a cleartext room and
|
|
// publishes an incrementing counter once per second, to both stdout and the
|
|
// bus. It demonstrates that a process is a first-class bus peer, uniform with
|
|
// the human chat client.
|
|
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/enmanuel/unibus/pkg/client"
|
|
"github.com/enmanuel/unibus/pkg/room"
|
|
)
|
|
|
|
func main() {
|
|
var (
|
|
natsURL = flag.String("nats-url", "nats://127.0.0.1:4222", "NATS url")
|
|
ctrlURL = flag.String("ctrl-url", "http://127.0.0.1:8420", "membershipd control-plane url")
|
|
roomSub = flag.String("room", "proc.test.ticks", "room subject to publish to")
|
|
idFile = flag.String("id-file", "./local_files/worker.id", "identity file path")
|
|
)
|
|
flag.Parse()
|
|
|
|
log.SetFlags(log.LstdFlags | log.Lmsgprefix)
|
|
log.SetPrefix("[worker] ")
|
|
|
|
id, err := client.LoadOrCreateIdentity(*idFile)
|
|
if err != nil {
|
|
log.Fatalf("identity: %v", err)
|
|
}
|
|
c, err := client.New(*natsURL, *ctrlURL, id)
|
|
if err != nil {
|
|
log.Fatalf("connect: %v", err)
|
|
}
|
|
defer c.Close()
|
|
log.Printf("endpoint: %s", c.Endpoint().ID)
|
|
|
|
// Create the room; if it already exists we cannot recreate it under a known
|
|
// id (rooms get fresh ULIDs), so for the demo each worker run owns its room.
|
|
roomID, err := c.CreateRoom(*roomSub, room.ModeNATS)
|
|
if err != nil {
|
|
log.Fatalf("create room: %v", err)
|
|
}
|
|
log.Printf("room %q -> %s (subject %s, cleartext)", *roomSub, roomID, *roomSub)
|
|
|
|
stop := make(chan os.Signal, 1)
|
|
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
ticker := time.NewTicker(1 * time.Second)
|
|
defer ticker.Stop()
|
|
n := 0
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
n++
|
|
payload := fmt.Sprintf("tick %d @ %s", n, time.Now().UTC().Format(time.RFC3339))
|
|
fmt.Println(payload)
|
|
if err := c.Publish(roomID, []byte(payload)); err != nil {
|
|
log.Printf("publish: %v", err)
|
|
}
|
|
case <-stop:
|
|
log.Printf("stopping after %d ticks", n)
|
|
return
|
|
}
|
|
}
|
|
}
|