Merge pull request 'node-tools: the runner creates the _tools twin from the membership's spec (design 47 H2 H-A-472)' (#89) from fix/tools-twin-membership into main
This commit was merged in pull request #89.
This commit is contained in:
@@ -191,9 +191,12 @@ type Conn struct {
|
||||
cred Credential
|
||||
mu sync.Mutex
|
||||
issued map[string]*Membership // module → membership; present with nil = followed, none issued
|
||||
onNew []*func(Membership)
|
||||
subs []*nats.Subscription
|
||||
Logf func(format string, args ...any)
|
||||
// withdrawn are the modules whose membership the grants part deleted: no longer assigned on this node (design 47 H2,
|
||||
// H-A-472 ninth addendum); their twins are removed and not made again, until a membership is issued again.
|
||||
withdrawn map[string]bool
|
||||
onNew []*func(Membership)
|
||||
subs []*nats.Subscription
|
||||
Logf func(format string, args ...any)
|
||||
// answering is every subject this runtime answers on, so a subscription the bus refused can be
|
||||
// asked for again (novox/hq issue 222).
|
||||
answering map[string]*answered
|
||||
@@ -411,6 +414,7 @@ var (
|
||||
func (c *Conn) issue(module string, m Membership) {
|
||||
c.mu.Lock()
|
||||
c.issued[module] = &m
|
||||
delete(c.withdrawn, module)
|
||||
handlers := make([]func(Membership), 0, len(c.onNew))
|
||||
for _, h := range c.onNew {
|
||||
handlers = append(handlers, *h)
|
||||
@@ -494,7 +498,9 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
|
||||
}
|
||||
apply := func(e jetstream.KeyValueEntry) {
|
||||
if e.Operation() != jetstream.KeyValuePut {
|
||||
return // a membership withdrawn is the stream's, or the module's unassignment's, to say
|
||||
// A membership withdrawn: the module is no longer assigned on this node, so its twins go (H-A-472 ninth addendum).
|
||||
c.withdraw(js, module)
|
||||
return
|
||||
}
|
||||
// Read through mesh-sdk's one codec of this state, the grants part's writer's (issue 774): it takes the bare
|
||||
// membership and a wrapper the part wrote before of one published or unchanged, and refuses a held-back one's
|
||||
@@ -541,6 +547,60 @@ func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Durat
|
||||
return true
|
||||
}
|
||||
|
||||
// withdraw removes the runner's twin `<consumer>_tools` from each stream the module's last membership named, as the grants
|
||||
// part withdrew the membership (design 47 H2, H-A-472 ninth addendum): the module left this node. The membership is kept as
|
||||
// it was, and the module marked withdrawn, so no hearing makes a twin again. A module with no membership issued names no
|
||||
// stream, so a delete read at the start removes nothing (the runner removes nothing at its start). Each removal is said; a
|
||||
// twin the bus does not hold is no failure.
|
||||
func (c *Conn) withdraw(js jetstream.JetStream, module string) {
|
||||
c.mu.Lock()
|
||||
m := c.issued[module]
|
||||
if c.withdrawn == nil {
|
||||
c.withdrawn = map[string]bool{}
|
||||
}
|
||||
c.withdrawn[module] = true
|
||||
c.mu.Unlock()
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
for _, h := range m.Hears {
|
||||
if h.Stream == "" || h.Consumer == "" {
|
||||
continue
|
||||
}
|
||||
twin := h.Consumer + ToolsSuffix
|
||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||
err := js.DeleteConsumer(ctx, h.Stream, twin)
|
||||
cancel()
|
||||
switch {
|
||||
case err == nil:
|
||||
c.Logf("[mesh-tools] %s's membership on %s was withdrawn; its consumer %s on %s is removed", module, c.node, twin, h.Stream)
|
||||
case errors.Is(err, jetstream.ErrConsumerNotFound):
|
||||
default:
|
||||
c.Logf("[mesh-tools] %s's membership on %s was withdrawn, and its consumer %s on %s cannot be removed: %v", module, c.node, twin, h.Stream, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Withdrawn says whether the grants part withdrew the module's membership here, and none was issued since.
|
||||
func (c *Conn) Withdrawn(module string) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.withdrawn[module]
|
||||
}
|
||||
|
||||
// heardOn is the entry of the module's membership for a stream, or, where it names none, the entry an older membership
|
||||
// implies: the module's consumer by name, bound and never made.
|
||||
func (c *Conn) heardOn(module, stream string) HeardIssued {
|
||||
if m := c.Membership(module); m != nil {
|
||||
for _, h := range m.Hears {
|
||||
if h.Stream == stream && h.Consumer != "" {
|
||||
return h
|
||||
}
|
||||
}
|
||||
}
|
||||
return HeardIssued{Stream: stream, Consumer: ConsumerOf(c.node, module)}
|
||||
}
|
||||
|
||||
// Membership is what the mesh issued a module here, or nil when nothing has been issued.
|
||||
func (c *Conn) Membership(module string) *Membership {
|
||||
c.mu.Lock()
|
||||
@@ -1205,9 +1265,13 @@ func (c *Conn) ConsumeAsBeatingWhen(module string, deliver func(Envelope) error,
|
||||
missed.Store(false) // an event arrived: the consumer is heard, whatever was said before
|
||||
return deliver(env)
|
||||
})
|
||||
// Bound by name, never created and never matched against a subject: the consumer and its
|
||||
// filters are the mesh's (design 29 §3), exactly as the module's own runtime bound it.
|
||||
events, _, doing, err := h.bind(EventsStream, durable, func(err error) {
|
||||
// Made first from the membership's spec where its EVENTS entry carries one (H-A-472 fifth to eighth addenda), else bound
|
||||
// by name: then the consumer and its filters are the mesh's (design 29 §3), exactly as the module's own runtime bound it.
|
||||
heard := c.heardOn(module, EventsStream)
|
||||
if c.Withdrawn(module) {
|
||||
heard.Filters = nil
|
||||
}
|
||||
events, _, doing, err := h.bind(heard, func(err error) {
|
||||
if errors.Is(err, jetstream.ErrNoHeartbeat) {
|
||||
say("the bus's heartbeat to the consumer " + durable + " stopped arriving")
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package bus
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||
"git.novox.be/novox/mesh-sdk/go/process"
|
||||
)
|
||||
|
||||
@@ -31,11 +33,54 @@ type StreamIssued struct {
|
||||
Subject string `json:"subject"`
|
||||
}
|
||||
|
||||
// HeardIssued is one module stream an assignment hears: the stream and the durable consumer on it the
|
||||
// runtime binds. The consumer is the mesh's to make, to filter and to delete.
|
||||
type HeardIssued struct {
|
||||
Stream string `json:"stream"`
|
||||
Consumer string `json:"consumer"`
|
||||
// HeardIssued is one stream an assignment hears, EVENTS like any other: the stream, the module's durable consumer the
|
||||
// runner's twin on it is named from, and, from a grants part that writes it, the twin's whole spec (mesh-sdk's
|
||||
// membership.HeardIssued; design 47 H2, H-A-472 seventh and eighth addenda). An entry with a spec is created or updated
|
||||
// from it by the runner at a child's first subscribe; one without, an older writer's, is bound by name as before.
|
||||
type HeardIssued = membership.HeardIssued
|
||||
|
||||
// heardKey is one consumer a hearing binds: the stream and the runner's twin on it. The spec rides beside it, never in
|
||||
// it, so a map is keyed by the consumer alone.
|
||||
type heardKey struct{ Stream, Consumer string }
|
||||
|
||||
// twinConfig is the configuration of the runner's twin of a heard entry with a spec: its filters, ack wait, max deliver,
|
||||
// max ack pending and deliver policy as the grants part composed them, under the twin's own name. Every filter goes in
|
||||
// FilterSubjects, one alone too, so the create is on the name alone, the form the reader is granted.
|
||||
func twinConfig(h HeardIssued) (jetstream.ConsumerConfig, error) {
|
||||
cfg := jetstream.ConsumerConfig{
|
||||
Durable: h.Consumer + ToolsSuffix,
|
||||
AckPolicy: jetstream.AckExplicitPolicy,
|
||||
AckWait: time.Duration(h.AckWaitSeconds) * time.Second,
|
||||
MaxDeliver: h.MaxDeliver,
|
||||
MaxAckPending: h.MaxAckPending,
|
||||
FilterSubjects: append([]string(nil), h.Filters...),
|
||||
}
|
||||
switch h.DeliverPolicy {
|
||||
case membership.DeliverFromNow:
|
||||
cfg.DeliverPolicy = jetstream.DeliverNewPolicy
|
||||
case membership.DeliverLastPerSubject:
|
||||
cfg.DeliverPolicy = jetstream.DeliverLastPerSubjectPolicy
|
||||
case membership.DeliverAll, "":
|
||||
cfg.DeliverPolicy = jetstream.DeliverAllPolicy
|
||||
default:
|
||||
return cfg, fmt.Errorf("the membership names the deliver policy %q, which the runner does not know", h.DeliverPolicy)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// makeTwin creates or updates the runner's twin of a heard entry from its spec (H-A-472 fifth to seventh addenda): what
|
||||
// the bus lacks is made as a part's process makes it, and one held is brought to the spec, its delivery position kept.
|
||||
// An entry without a spec makes nothing: its consumer is the grants part's, bound by name.
|
||||
func makeTwin(ctx context.Context, js jetstream.JetStream, h HeardIssued) error {
|
||||
if !h.HasSpec() {
|
||||
return nil
|
||||
}
|
||||
cfg, err := twinConfig(h)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = js.CreateOrUpdateConsumer(ctx, h.Stream, cfg)
|
||||
return err
|
||||
}
|
||||
|
||||
// eventSubject is where a module's event is published: on the subject of the first of its membership's
|
||||
@@ -94,15 +139,15 @@ type hearing struct {
|
||||
|
||||
mu sync.Mutex
|
||||
stopped bool
|
||||
bound map[HeardIssued]jetstream.ConsumeContext
|
||||
bound map[heardKey]jetstream.ConsumeContext
|
||||
// made is when the bus made each bound consumer: a consumer deleted and made again under its name has
|
||||
// another time, and a loop bound to the old one is not reading the new one.
|
||||
made map[HeardIssued]time.Time
|
||||
said map[HeardIssued]bool
|
||||
made map[heardKey]time.Time
|
||||
said map[heardKey]bool
|
||||
// why is the last error the bus gave a consumer's loop, said when the loop ends on it.
|
||||
// Guarded by whyMu, not mu: the bus hands errors from its own goroutines, possibly while mu is held.
|
||||
whyMu sync.Mutex
|
||||
why map[HeardIssued]error
|
||||
why map[heardKey]error
|
||||
kick chan struct{}
|
||||
done chan struct{}
|
||||
unhear func()
|
||||
@@ -115,16 +160,21 @@ type hearing struct {
|
||||
|
||||
func newHearing(c *Conn, js jetstream.JetStream, module string, deliver func(Envelope) error) *hearing {
|
||||
return &hearing{c: c, js: js, module: module, deliver: deliver,
|
||||
bound: map[HeardIssued]jetstream.ConsumeContext{}, made: map[HeardIssued]time.Time{}, said: map[HeardIssued]bool{}, why: map[HeardIssued]error{},
|
||||
bound: map[heardKey]jetstream.ConsumeContext{}, made: map[heardKey]time.Time{}, said: map[heardKey]bool{}, why: map[heardKey]error{},
|
||||
kick: make(chan struct{}, 1), done: make(chan struct{}),
|
||||
rebind: RebindEvery, nakDelay: NakDelay, heartbeat: EventHeartbeat}
|
||||
}
|
||||
|
||||
// bind reads one durable consumer by name, and on failure says what it was doing. Errors the bus gives
|
||||
// the loop afterwards are handed to onErr, when given.
|
||||
func (h *hearing) bind(stream, durable string, onErr func(error)) (jetstream.ConsumeContext, time.Time, string, error) {
|
||||
// bind reads the runner's twin of one heard entry, made first from the entry's spec where it carries one (makeTwin), else
|
||||
// bound by name, and on failure says what it was doing. Errors the bus gives the loop afterwards are handed to onErr, when
|
||||
// given.
|
||||
func (h *hearing) bind(heard HeardIssued, onErr func(error)) (jetstream.ConsumeContext, time.Time, string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
stream, durable := heard.Stream, heard.Consumer+ToolsSuffix
|
||||
if err := makeTwin(ctx, h.js, heard); err != nil {
|
||||
return nil, time.Time{}, "making", err
|
||||
}
|
||||
consumer, err := h.js.Consumer(ctx, stream, durable)
|
||||
if err != nil {
|
||||
return nil, time.Time{}, "binding", err
|
||||
@@ -224,7 +274,7 @@ func (h *hearing) start() {
|
||||
}
|
||||
|
||||
// forget drops the last error a consumer's loop was given.
|
||||
func (h *hearing) forget(heard HeardIssued) {
|
||||
func (h *hearing) forget(heard heardKey) {
|
||||
h.whyMu.Lock()
|
||||
delete(h.why, heard)
|
||||
h.whyMu.Unlock()
|
||||
@@ -260,7 +310,7 @@ func (h *hearing) stop() {
|
||||
|
||||
// replaced says whether the consumer a loop is bound to is gone from the bus or was made again since. A bus
|
||||
// that cannot be asked right now says no: the loop is left as it is.
|
||||
func (h *hearing) replaced(heard HeardIssued) bool {
|
||||
func (h *hearing) replaced(heard heardKey) bool {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
consumer, err := h.js.Consumer(ctx, heard.Stream, heard.Consumer)
|
||||
@@ -276,13 +326,14 @@ func (h *hearing) replaced(heard HeardIssued) bool {
|
||||
|
||||
// reconcile makes what is bound what the module's membership names now.
|
||||
func (h *hearing) reconcile() {
|
||||
want := map[HeardIssued]bool{}
|
||||
if m := h.c.Membership(h.module); m != nil {
|
||||
want := map[heardKey]HeardIssued{}
|
||||
// A module whose membership was withdrawn hears nothing more here, and its twins are not made again (H-A-472 ninth addendum).
|
||||
if m := h.c.Membership(h.module); m != nil && !h.c.Withdrawn(h.module) {
|
||||
for _, heard := range m.Hears {
|
||||
if heard.Stream != "" && heard.Consumer != "" {
|
||||
// EVENTS is its caller's, bound beside the hearing (ConsumeAsBeatingWhen).
|
||||
if heard.Stream != "" && heard.Consumer != "" && heard.Stream != EventsStream {
|
||||
// The runner's own durable beside the program's (A-397).
|
||||
heard.Consumer += ToolsSuffix
|
||||
want[heard] = true
|
||||
want[heardKey{heard.Stream, heard.Consumer + ToolsSuffix}] = heard
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -292,7 +343,7 @@ func (h *hearing) reconcile() {
|
||||
return
|
||||
}
|
||||
for heard, reading := range h.bound {
|
||||
if !want[heard] {
|
||||
if _, still := want[heard]; !still {
|
||||
reading.Stop()
|
||||
delete(h.bound, heard)
|
||||
delete(h.made, heard)
|
||||
@@ -301,7 +352,7 @@ func (h *hearing) reconcile() {
|
||||
}
|
||||
}
|
||||
for heard := range h.said {
|
||||
if !want[heard] {
|
||||
if _, still := want[heard]; !still {
|
||||
delete(h.said, heard)
|
||||
h.forget(heard)
|
||||
}
|
||||
@@ -340,7 +391,7 @@ func (h *hearing) reconcile() {
|
||||
default:
|
||||
}
|
||||
}
|
||||
missing := make([]HeardIssued, 0, len(want))
|
||||
missing := make([]heardKey, 0, len(want))
|
||||
for heard := range want {
|
||||
if h.bound[heard] == nil {
|
||||
missing = append(missing, heard)
|
||||
@@ -350,7 +401,7 @@ func (h *hearing) reconcile() {
|
||||
for _, heard := range missing {
|
||||
heard := heard
|
||||
h.forget(heard)
|
||||
reading, created, doing, err := h.bind(heard.Stream, heard.Consumer, func(err error) {
|
||||
reading, created, doing, err := h.bind(want[heard], func(err error) {
|
||||
h.whyMu.Lock()
|
||||
h.why[heard] = err
|
||||
h.whyMu.Unlock()
|
||||
|
||||
@@ -4,11 +4,15 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||
)
|
||||
@@ -368,3 +372,117 @@ func (l *syncLogs) Has(fragment string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Design 47 H2, H-A-472 fifth to ninth addenda: the runner makes its own twin `<node>_<module>_tools` of every stream its
|
||||
// membership hears, EVENTS among them, from the spec the entry carries, at a child's first subscribe; a twin it holds is
|
||||
// brought to the spec at the next; and when the grants part withdraws the membership, the runner removes the twins from
|
||||
// the streams the entry named and makes none again.
|
||||
func TestTheRunnersTwinIsMadeFromItsMembershipsSpecAndRemovedWhenWithdrawn(t *testing.T) {
|
||||
reader := mt.MembershipOf("reader", "anchor", false, nil)
|
||||
reader.Hears = []bus.HeardIssued{
|
||||
{Stream: bus.EventsStream, Consumer: "anchor_reader", Filters: []string{"mesh.mod.alpha.event.>", "mesh.again.anchor_reader_tools.>"},
|
||||
AckWaitSeconds: 7, MaxDeliver: 3, DeliverPolicy: membership.DeliverFromNow},
|
||||
{Stream: "MAIL", Consumer: "anchor_reader", Filters: []string{"mesh.stream.mail.event.mail.>"}, AckWaitSeconds: 9,
|
||||
MaxDeliver: 4, MaxAckPending: 2, DeliverPolicy: membership.DeliverAll},
|
||||
}
|
||||
mesh, conn := streamMesh(t, reader)
|
||||
nc, err := nats.Connect(mt.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(nc.Close)
|
||||
js, _ := nc.JetStream()
|
||||
// Waiting on MAIL before the twin exists: a twin that delivers all hears it.
|
||||
mesh.Emit(t, "mesh.stream.mail.event.mail.home.message.added", map[string]any{"n": 1})
|
||||
|
||||
var mu sync.Mutex
|
||||
heard := map[string]int{}
|
||||
consume := func() (func(), error) {
|
||||
return conn.ConsumeAs("reader", func(env bus.Envelope) error {
|
||||
mu.Lock()
|
||||
heard[env.Key]++
|
||||
mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
stop, err := consume()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mesh.Emit(t, "mesh.mod.alpha.event.happened", map[string]any{"n": 1})
|
||||
mt.Until(t, func() error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if heard["alpha.happened"] != 1 || heard["mail.mail.home.message.added"] != 1 {
|
||||
return fmt.Errorf("heard %v, want one on EVENTS and one on MAIL", heard)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
for _, row := range []struct {
|
||||
stream string
|
||||
filters []string
|
||||
ackWait time.Duration
|
||||
maxDeliver int
|
||||
maxAckPending int
|
||||
deliver nats.DeliverPolicy
|
||||
}{
|
||||
{bus.EventsStream, []string{"mesh.mod.alpha.event.>", "mesh.again.anchor_reader_tools.>"}, 7 * time.Second, 3, 0, nats.DeliverNewPolicy},
|
||||
{"MAIL", []string{"mesh.stream.mail.event.mail.>"}, 9 * time.Second, 4, 2, nats.DeliverAllPolicy},
|
||||
} {
|
||||
info, err := js.ConsumerInfo(row.stream, "anchor_reader_tools")
|
||||
if err != nil {
|
||||
t.Fatalf("the twin on %s: %v", row.stream, err)
|
||||
}
|
||||
c := info.Config
|
||||
if !slices.Equal(c.FilterSubjects, row.filters) || c.AckWait != row.ackWait || c.MaxDeliver != row.maxDeliver ||
|
||||
(row.maxAckPending != 0 && c.MaxAckPending != row.maxAckPending) || c.DeliverPolicy != row.deliver {
|
||||
t.Errorf("the twin on %s is %+v, want the membership's spec", row.stream, c)
|
||||
}
|
||||
}
|
||||
|
||||
// A twin held is brought to the spec at the next first subscribe.
|
||||
stop()
|
||||
reader.Hears[1].MaxDeliver = 6
|
||||
mesh.Issue(t, reader)
|
||||
mt.Until(t, func() error {
|
||||
if m := conn.Membership("reader"); m == nil || m.Hears[1].MaxDeliver != 6 {
|
||||
return errors.New("the new spec is not issued yet")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if stop, err = consume(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mt.Until(t, func() error {
|
||||
info, err := js.ConsumerInfo("MAIL", "anchor_reader_tools")
|
||||
if err != nil || info.Config.MaxDeliver != 6 {
|
||||
return fmt.Errorf("the twin on MAIL is not brought to the spec: %v", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// Withdrawn: the twins go from both streams, and a subscribe after makes none.
|
||||
kv, err := js.KeyValue(membership.GrantsBucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := kv.Delete(membership.GrantsKey("anchor", "reader")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mt.Until(t, func() error {
|
||||
for _, stream := range []string{bus.EventsStream, "MAIL"} {
|
||||
if _, err := js.ConsumerInfo(stream, "anchor_reader_tools"); !errors.Is(err, nats.ErrConsumerNotFound) {
|
||||
return fmt.Errorf("the twin on %s is still there (%v)", stream, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
stop()
|
||||
if !conn.Withdrawn("reader") {
|
||||
t.Error("the module is not marked withdrawn")
|
||||
}
|
||||
if again, err := consume(); err == nil {
|
||||
again()
|
||||
t.Error("a subscribe after the withdrawal made the twin again")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user