Files
unibus/cmd/worker/main.go
T
egutierrez 74c8d4f941 feat(client,cmd,mobile): connect securely via client.Connect(caPath)
client.Connect is the single migration seam: a non-empty caPath connects with
TLS pinned to the bus CA plus nkey auth (matching enforce + bus-tls), an empty
caPath keeps the legacy plaintext dev connection; control-plane requests are
signed either way. worker and chat gain a --ca flag; the gomobile NewSession
gains a caPath parameter so the Android app bundles ca.crt and connects
securely. Every peer now flows through one code path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:49:19 +02:00

73 lines
2.1 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:4250", "NATS url")
ctrlURL = flag.String("ctrl-url", "http://127.0.0.1:8470", "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")
caFile = flag.String("ca", "", "path to the bus CA cert (ca.crt); set to connect with TLS + nkey to a secured bus")
)
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.Connect(*natsURL, *ctrlURL, id, *caFile)
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
}
}
}