Compare commits
109
Commits
1e1a1602e1
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
393449e840 | ||
|
|
56d20314ba | ||
|
|
6a1b4817f8 | ||
|
|
309069dec1 | ||
|
|
5d87f7d375 | ||
|
|
662b05ca5a | ||
|
|
e8f58540ee | ||
|
|
089d98b406 | ||
|
|
f26ca923c9 | ||
|
|
ba82044cc0 | ||
|
|
51a24ea801 | ||
|
|
c90ff7d9c0 | ||
|
|
cab76319b8 | ||
|
|
026fb780d6 | ||
|
|
e8579359b6 | ||
|
|
a6a16c897b | ||
|
|
917195a302 | ||
|
|
bebf2538db | ||
|
|
b8a30b2bc7 | ||
|
|
d602f731ee | ||
|
|
4f265fe884 | ||
|
|
ec3fe34afc | ||
|
|
a1c12af8b2 | ||
|
|
0e03495757 | ||
|
|
0c7000fa93 | ||
|
|
5cca1fceba | ||
|
|
858beb2b63 | ||
|
|
537e44eff6 | ||
|
|
a75d86236b | ||
|
|
07ebeae74d | ||
|
|
2365e41811 | ||
|
|
f7269d9812 | ||
|
|
02675a43ea | ||
|
|
e70de721dc | ||
|
|
d064bb75cd | ||
|
|
ee143c9f91 | ||
|
|
05d8f6b762 | ||
|
|
fe707779e3 | ||
|
|
3eef0254df | ||
|
|
39c2604926 | ||
|
|
07f5aa11c3 | ||
|
|
876adfbf05 | ||
|
|
c952386737 | ||
|
|
d76d9e0b1a | ||
|
|
8ee4fdfb8e | ||
|
|
05deea5952 | ||
|
|
3850eb8eac | ||
|
|
eb174d853f | ||
|
|
b1d10dd67e | ||
|
|
fb4fe282c7 | ||
|
|
13ff8041b8 | ||
|
|
f92ec7d24f | ||
|
|
8a534ba436 | ||
|
|
d9fe2568de | ||
|
|
81663a4d9e | ||
|
|
a118559515 | ||
|
|
f2a05fb440 | ||
|
|
5d88eecea9 | ||
|
|
618d8953ed | ||
|
|
5314231c0d | ||
|
|
76df3cb420 | ||
|
|
d1dc482b05 | ||
|
|
2f9690fe80 | ||
|
|
30b2a72f9b | ||
|
|
470e57124e | ||
|
|
e554402e47 | ||
|
|
ef0a61d348 | ||
|
|
42a752f052 | ||
|
|
4043dd1176 | ||
|
|
b232e39c96 | ||
|
|
20b6b02341 | ||
|
|
72b0d4ca4e | ||
|
|
4333d5b944 | ||
|
|
9e8bf6dc0c | ||
|
|
45fbc813df | ||
|
|
3d6daad925 | ||
|
|
903ac4ce93 | ||
|
|
9fa29ad801 | ||
|
|
30027347e9 | ||
|
|
7a6174bb3e | ||
|
|
faa1064214 | ||
|
|
27a45d414d | ||
|
|
a96df478d4 | ||
|
|
6be5679a0d | ||
|
|
af83854956 | ||
|
|
df2162e381 | ||
|
|
a775b42e4d | ||
|
|
481a83e11c | ||
|
|
28bece26b0 | ||
|
|
816df217cd | ||
|
|
c35c27f664 | ||
|
|
d350c98823 | ||
|
|
29757dabc3 | ||
|
|
95a265e730 | ||
|
|
d6c267d2f0 | ||
|
|
e03d8d3c7b | ||
|
|
a91386b3b5 | ||
|
|
8b980a9480 | ||
|
|
9fcb14e741 | ||
|
|
14f464e8bc | ||
|
|
2d95c0eb59 | ||
|
|
b5c7bf13ea | ||
|
|
99f8c8c050 | ||
|
|
24f257e929 | ||
|
|
e63d707eac | ||
|
|
5e373af70d | ||
|
|
64015b5952 | ||
|
|
e873cb3b86 | ||
|
|
e88e0c825c |
@@ -12,7 +12,7 @@ import (
|
|||||||
|
|
||||||
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||||
seat "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
seat "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
"git.novox.be/novox/mesh-sdk/go/approval"
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
// node-tools — the node's tool runtime, in Go (novox/hq ADR 0175, ADR 0193; to-be 38 WP4d).
|
// node-tools — the node's tool runtime, in Go (novox/hq ADR 0175, ADR 0193; to-be 38 WP4d).
|
||||||
|
// (Its pipeline is asked again by this line, 2026-11-16 23:45: main.981 passed all but composition, whose revision 433 was removed; the assigner now waits 3 minutes for composing nodes.)
|
||||||
|
// Design 47 H1, proof 2: the tool runner delivered by its pipeline at the current mesh-sdk release.
|
||||||
//
|
//
|
||||||
// One process per machine: it connects to the bus on the node's credential, launches every assigned
|
// One process per machine: it connects to the bus on the node's credential, launches every assigned
|
||||||
// module's tools bundle and serves its tools and its seats' verbs; as the node-tools module — or
|
// module's tools bundle and serves its tools and its seats' verbs; as the node-tools module — or
|
||||||
@@ -27,7 +29,9 @@ import (
|
|||||||
|
|
||||||
handacts "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts"
|
handacts "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts"
|
||||||
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||||
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"git.novox.be/novox/mesh-sdk/go/approval"
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/busretry"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/alive"
|
"github.com/novox/mesh-tools/node-tools/internal/alive"
|
||||||
runnerapproval "github.com/novox/mesh-tools/node-tools/internal/approval"
|
runnerapproval "github.com/novox/mesh-tools/node-tools/internal/approval"
|
||||||
@@ -52,6 +56,26 @@ func main() {
|
|||||||
fmt.Fprintf(os.Stderr, "node-tools: %q is not a mode; this runtime serves (novox/hq ADR 0193)\n", os.Args[1])
|
fmt.Fprintf(os.Stderr, "node-tools: %q is not a mode; this runtime serves (novox/hq ADR 0193)\n", os.Args[1])
|
||||||
os.Exit(2)
|
os.Exit(2)
|
||||||
}
|
}
|
||||||
|
// Stopped by the service manager's signal; the runtime itself is serve, which a whole test starts by its entry (design 47 H §774).
|
||||||
|
ctx, stopSignals := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||||
|
defer stopSignals()
|
||||||
|
if err := serve(ctx); err != nil {
|
||||||
|
log.Fatalf("node-tools: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// serve is the tool runner: it reads its credential and serves until ctx ends, then shuts down in order. It is the entry a whole test
|
||||||
|
// starts, beside the process's own (design 47 H §774, H-A-61).
|
||||||
|
func serve(ctx context.Context) error {
|
||||||
|
// The drain bound, read first so a setting that is no duration stops the runner before it serves (design 47 H2 §813 (12)).
|
||||||
|
drainBound, err := drainBoundSetting()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// And the pace of its kept calls, its settings kept-call-pace-first and kept-call-pace-max (design 47 H2 §775).
|
||||||
|
if err := busretry.ReadPace(stdio.SettingDuration); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
until := time.Now().Add(startWait)
|
until := time.Now().Add(startWait)
|
||||||
cred := credential(until)
|
cred := credential(until)
|
||||||
conn := connectPatiently(cred, until)
|
conn := connectPatiently(cred, until)
|
||||||
@@ -60,11 +84,11 @@ func main() {
|
|||||||
|
|
||||||
served, err := runtime.ServedModulesFrom(os.Getenv(runtime.ToolModules), cred.Module)
|
served, err := runtime.ServedModulesFrom(os.Getenv(runtime.ToolModules), cred.Module)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("node-tools: %v", err)
|
return err
|
||||||
}
|
}
|
||||||
envs, err := runtime.TakeToolEnvs()
|
envs, err := runtime.TakeToolEnvs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("node-tools: %v", err)
|
return err
|
||||||
}
|
}
|
||||||
// Its own secret ledgers: each module's ledger connection, the only one its history is published on (novox/hq ADR
|
// Its own secret ledgers: each module's ledger connection, the only one its history is published on (novox/hq ADR
|
||||||
// 0597 §9). Followed, so a credential minted or retired is taken with no restart.
|
// 0597 §9). Followed, so a credential minted or retired is taken with no restart.
|
||||||
@@ -77,7 +101,10 @@ func main() {
|
|||||||
// The indexer's and the assigner's states the console indexes the mesh by, and the gate reads its marks from, come to it as
|
// The indexer's and the assigner's states the console indexes the mesh by, and the gate reads its marks from, come to it as
|
||||||
// first views, asked of the owners' own tools and followed on their views families, never read from their state (novox/hq
|
// first views, asked of the owners' own tools and followed on their views families, never read from their state (novox/hq
|
||||||
// ADR 0615 §1; design 46 7-approval-mark §5).
|
// ADR 0615 §1; design 46 7-approval-mark §5).
|
||||||
source, stopViews := firstview.Start(context.Background(), conn, log.Printf)
|
// In a module's own runtime the follower hears on the module's one consumer, bound by the runtime for its bundle (design 47
|
||||||
|
// H §752, H-A-132).
|
||||||
|
source, stopViews, hearing := startViews(context.Background(), firstview.DepsOf(conn, log.Printf), served, cred.Module, log.Printf)
|
||||||
|
opts = append(opts, hearing...)
|
||||||
defer stopViews()
|
defer stopViews()
|
||||||
approvals := approvalsState{conn: conn, module: cred.Module}
|
approvals := approvalsState{conn: conn, module: cred.Module}
|
||||||
gate := approval.New(approval.Deps{Node: conn.Node(), Runner: cred.Module, Catalog: source.ApprovalCatalog(definitionsOf(seatList)), Wait: source.WaitCatalog,
|
gate := approval.New(approval.Deps{Node: conn.Node(), Runner: cred.Module, Catalog: source.ApprovalCatalog(definitionsOf(seatList)), Wait: source.WaitCatalog,
|
||||||
@@ -89,7 +116,8 @@ func main() {
|
|||||||
Build: os.Getenv(runtime.FingerprintWord), Hear: hearOne(conn)})
|
Build: os.Getenv(runtime.FingerprintWord), Hear: hearOne(conn)})
|
||||||
// A failed read or write of the state approvals is made again at the next membership change the runner hears (A-157).
|
// A failed read or write of the state approvals is made again at the next membership change the runner hears (A-157).
|
||||||
conn.OnMembership(func(bus.Membership) { go gate.StateAgain() })
|
conn.OnMembership(func(bus.Membership) { go gate.StateAgain() })
|
||||||
opts = append(opts, runtime.WithGate(gate), runtime.WithSeatDefinitions(definitionsOf(seatList)))
|
opts = append(opts, runtime.WithGate(gate), runtime.WithSeatDefinitions(definitionsOf(seatList)),
|
||||||
|
runtime.WithSeatDefinitionsAgain(rereadOf(seatList)))
|
||||||
// A run still unrecorded is asked again at each start and when the hand-act seat's holder is heard again (lead answer A-157).
|
// A run still unrecorded is asked again at each start and when the hand-act seat's holder is heard again (lead answer A-157).
|
||||||
if stopBounds, err := gate.WatchBounds(); err != nil {
|
if stopBounds, err := gate.WatchBounds(); err != nil {
|
||||||
log.Printf("[mesh-tools] the gate's bound keys are not watched (%v): an unanswered hand-act is said in the log only", err)
|
log.Printf("[mesh-tools] the gate's bound keys are not watched (%v): an unanswered hand-act is said in the log only", err)
|
||||||
@@ -100,7 +128,7 @@ func main() {
|
|||||||
go gate.Recover()
|
go gate.Recover()
|
||||||
stop, err := runtime.Run(conn, served, envs, log.Printf, opts...)
|
stop, err := runtime.Run(conn, served, envs, log.Printf, opts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("node-tools: %v", err)
|
return err
|
||||||
}
|
}
|
||||||
// And says it is there (novox/hq to-be 45 S11): the machine's runtime, on its machine's name. A
|
// And says it is there (novox/hq to-be 45 S11): the machine's runtime, on its machine's name. A
|
||||||
// runtime on another credential — a module's own, in a test — is not the machine's.
|
// runtime on another credential — a module's own, in a test — is not the machine's.
|
||||||
@@ -125,20 +153,25 @@ func main() {
|
|||||||
}
|
}
|
||||||
who := node + "." + cred.Module
|
who := node + "." + cred.Module
|
||||||
surface := console.NewSurface(conn, source, who)
|
surface := console.NewSurface(conn, source, who)
|
||||||
|
surface.Definitions = definitionsOf(seatList)
|
||||||
surface.Approvals = gateTools{Gate: gate, state: approvalsState{conn: conn, module: cred.Module}}
|
surface.Approvals = gateTools{Gate: gate, state: approvalsState{conn: conn, module: cred.Module}}
|
||||||
up, err = console.Serve(surface, listen)
|
up, err = console.Serve(surface, listen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("node-tools: %v", err)
|
return err
|
||||||
}
|
}
|
||||||
log.Printf("mesh console listening on http://%s/mcp as %s", up.Address, who)
|
log.Printf("mesh console listening on http://%s/mcp as %s", up.Address, who)
|
||||||
}
|
}
|
||||||
|
|
||||||
signals := make(chan os.Signal, 1)
|
<-ctx.Done()
|
||||||
signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
|
|
||||||
<-signals
|
|
||||||
// First of all: the service manager signalled every bundle with this process, and none is started again
|
// First of all: the service manager signalled every bundle with this process, and none is started again
|
||||||
// (issue 1126).
|
// (issue 1126).
|
||||||
launch.ShutDown()
|
launch.ShutDown()
|
||||||
|
// Then it unsubscribes from every subject it answers calls on, so a call made from now on meets no responders wherever no
|
||||||
|
// other tool runner serves it, until the new runner subscribes (design 47 H2 H-A-570 (1)).
|
||||||
|
conn.StopAnswering()
|
||||||
|
// Then it drains (design 47 H2 §813 (12), H-A-353): no new call is taken, the calls in flight finish within the drain bound
|
||||||
|
// or are cut and said, and only then are the bundles stopped, by the runner itself.
|
||||||
|
launch.Drain(drainBound, log.Printf)
|
||||||
stopSaying()
|
stopSaying()
|
||||||
stopProviding()
|
stopProviding()
|
||||||
stop()
|
stop()
|
||||||
@@ -146,6 +179,14 @@ func main() {
|
|||||||
_ = up.Close()
|
_ = up.Close()
|
||||||
}
|
}
|
||||||
conn.Close()
|
conn.Close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// drainBoundSetting is how long the runner, told to stop, waits for the calls in flight to finish: the module's setting
|
||||||
|
// drain-bound, a duration text the node-engine composes as MESH_CONFIG_DRAIN_BOUND, read through the one settings reader, 30 s
|
||||||
|
// when none is composed (design 47 H2 §813 (12), H-A-369, H-A-370, H-A-377).
|
||||||
|
func drainBoundSetting() (time.Duration, error) {
|
||||||
|
return stdio.SettingDuration(launch.DrainBoundSetting, launch.DefaultDrainBound)
|
||||||
}
|
}
|
||||||
|
|
||||||
// startWait is how long a runtime waits, from its start, for its broker credential to be on the machine and for the bus
|
// startWait is how long a runtime waits, from its start, for its broker credential to be on the machine and for the bus
|
||||||
|
|||||||
@@ -13,11 +13,43 @@ import (
|
|||||||
"github.com/novox/mesh-tools/node-tools/internal/runtime"
|
"github.com/novox/mesh-tools/node-tools/internal/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The runner's start waits for its credential and its bus within the start's bound (issue 1496): one test, two cases, so
|
// The runner's start waits for its credential and its bus within the start's bound (issue 1496), and reads its settings
|
||||||
// design 46 7-approval-mark §22's whole test of the gate adds no test to the module (design 47 G §419, §626).
|
// before it serves: one test, three cases, so design 46 7-approval-mark §22's whole test of the gate adds no test to the
|
||||||
|
// module (design 47 G §419, §626).
|
||||||
func TestTheRunnersStartWaitsForItsCredentialAndItsBus(t *testing.T) {
|
func TestTheRunnersStartWaitsForItsCredentialAndItsBus(t *testing.T) {
|
||||||
t.Run("the credential", awaitsCredential)
|
t.Run("the credential", awaitsCredential)
|
||||||
t.Run("the bus", connectsWithin)
|
t.Run("the bus", connectsWithin)
|
||||||
|
// **The runner's settings are read through the one settings reader** (design 47 H2 §813 (12), §775, H-A-369, H-A-370,
|
||||||
|
// H-A-377): drain-bound, a duration text the node-engine composes as MESH_CONFIG_DRAIN_BOUND, 30 s when none is composed; a
|
||||||
|
// value that is no duration, of it or of the kept call's pace, stops the runner before it serves, naming the setting.
|
||||||
|
t.Run("its settings", func(t *testing.T) {
|
||||||
|
for _, row := range []struct {
|
||||||
|
word, composed, refused string
|
||||||
|
want time.Duration
|
||||||
|
}{
|
||||||
|
{"MESH_CONFIG_DRAIN_BOUND", "", "", 30 * time.Second},
|
||||||
|
{"MESH_CONFIG_DRAIN_BOUND", "5s", "", 5 * time.Second},
|
||||||
|
{"MESH_CONFIG_DRAIN_BOUND", "30", "drain-bound", 0},
|
||||||
|
{"MESH_CONFIG_KEPT_CALL_PACE_FIRST", "1", "kept-call-pace-first", 30 * time.Second},
|
||||||
|
{"MESH_CONFIG_KEPT_CALL_PACE_MAX", "100ms", "kept-call-pace-max", 30 * time.Second},
|
||||||
|
} {
|
||||||
|
t.Run(row.word+"="+row.composed, func(t *testing.T) {
|
||||||
|
t.Setenv(row.word, row.composed)
|
||||||
|
if row.refused != "" {
|
||||||
|
if err := serve(t.Context()); err == nil || !strings.Contains(err.Error(), row.refused) {
|
||||||
|
t.Errorf("the runner with %s=%q served (%v); want it stopped before it serves, naming %s", row.word,
|
||||||
|
row.composed, err, row.refused)
|
||||||
|
}
|
||||||
|
if row.want == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, err := drainBoundSetting(); err != nil || got != row.want {
|
||||||
|
t.Errorf("drain-bound read %s, %v; want %s", got, err, row.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// A runtime started before its credential is on the machine waits for it, woken by the watch of its directory, and gives
|
// A runtime started before its credential is on the machine waits for it, woken by the watch of its directory, and gives
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/firstview"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ownHearer is the branch follower's hearing in a module's own runtime: the runtime binds the module's consumer once, for
|
||||||
|
// its bundle, and hands each event to it after the bundle took it (runtime.WithHearer), so no second pull loop reads the
|
||||||
|
// same durable and each event reaches both (design 47 H §752, H-A-113, H-A-132).
|
||||||
|
type ownHearer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
deliver func(bus.Envelope) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// consume is the follower's Consume: it binds nothing, and holds deliver until the stop is called.
|
||||||
|
func (h *ownHearer) consume(deliver func(bus.Envelope) error) (func(), error) {
|
||||||
|
h.mu.Lock()
|
||||||
|
h.deliver = deliver
|
||||||
|
h.mu.Unlock()
|
||||||
|
return func() {
|
||||||
|
h.mu.Lock()
|
||||||
|
h.deliver = nil
|
||||||
|
h.mu.Unlock()
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// hear hands one event of the module's consumer to the follower, while it hears.
|
||||||
|
func (h *ownHearer) hear(env bus.Envelope) error {
|
||||||
|
h.mu.Lock()
|
||||||
|
deliver := h.deliver
|
||||||
|
h.mu.Unlock()
|
||||||
|
if deliver == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return deliver(env)
|
||||||
|
}
|
||||||
|
|
||||||
|
// followerOnOwnConsumer is the first views' reach in a runtime that serves its own account's module: the follower hears on
|
||||||
|
// the consumer the runtime binds for the module's bundle, through the hearer answered, which the runtime is given
|
||||||
|
// (runtime.WithHearer). A runtime that serves another module's account (the machine's runtime) keeps the follower's own
|
||||||
|
// binding, and answers no hearer.
|
||||||
|
func followerOnOwnConsumer(d firstview.Deps, served []runtime.Served, own string) (firstview.Deps, *ownHearer) {
|
||||||
|
for _, s := range served {
|
||||||
|
if s.Module == own {
|
||||||
|
h := &ownHearer{}
|
||||||
|
d.Consume = h.consume
|
||||||
|
return d, h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// startViews is serve's first views: it starts the follower over d and answers the options runtime.Run is given, so that on a
|
||||||
|
// module's own account the follower binds nothing and hears on the module's one consumer (runtime.WithHearer), and on the
|
||||||
|
// machine's account the follower binds its own (design 47 H §752, H-A-132, H-A-133).
|
||||||
|
func startViews(ctx context.Context, d firstview.Deps, served []runtime.Served, own string, logf func(string, ...any)) (*firstview.Views, func(), []runtime.Option) {
|
||||||
|
followed, hearer := followerOnOwnConsumer(d, served, own)
|
||||||
|
source, stop := firstview.StartWith(ctx, followed, logf)
|
||||||
|
if hearer == nil {
|
||||||
|
return source, stop, nil
|
||||||
|
}
|
||||||
|
return source, stop, []runtime.Option{runtime.WithHearer(own, hearer.hear)}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/firstview"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
// In a module's own runtime the branch follower binds no consumer of its own and hears each event the runtime hands it from the
|
||||||
|
// module's one consumer; a runtime that is not the module's own keeps the follower's own binding (design 47 H §752, H-A-132).
|
||||||
|
func TestTheFollowerHearsOnTheOwnModulesOneConsumer(t *testing.T) {
|
||||||
|
for _, row := range []struct {
|
||||||
|
name string
|
||||||
|
served []runtime.Served
|
||||||
|
own string
|
||||||
|
binds bool
|
||||||
|
}{
|
||||||
|
{"a module's own runtime", []runtime.Served{{Module: "mesh-delivery-indexer"}}, "mesh-delivery-indexer", false},
|
||||||
|
{"the machine's runtime", []runtime.Served{{Module: "mesh-delivery-indexer"}}, runtime.NodeRuntimeModule, true},
|
||||||
|
} {
|
||||||
|
t.Run(row.name, func(t *testing.T) {
|
||||||
|
bound := 0
|
||||||
|
d := firstview.Deps{Consume: func(func(bus.Envelope) error) (func(), error) { bound++; return func() {}, nil }}
|
||||||
|
got, hearer := followerOnOwnConsumer(d, row.served, row.own)
|
||||||
|
var heard []string
|
||||||
|
stop, err := got.Consume(func(env bus.Envelope) error { heard = append(heard, env.Key); return nil })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if (bound == 1) != row.binds || (hearer == nil) != row.binds {
|
||||||
|
t.Fatalf("bound its own consumer %d time(s), hearer given to the runtime %v; want its own binding %v", bound, hearer != nil, row.binds)
|
||||||
|
}
|
||||||
|
if row.binds {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
env := bus.Envelope{Key: "mesh-catalog.catalog-revision.main", Body: json.RawMessage(`{}`)}
|
||||||
|
if err := hearer.hear(env); err != nil || len(heard) != 1 || heard[0] != env.Key {
|
||||||
|
t.Fatalf("the event handed by the runtime: err %v, the follower heard %q", err, heard)
|
||||||
|
}
|
||||||
|
stop()
|
||||||
|
if err := hearer.hear(env); err != nil || len(heard) != 1 {
|
||||||
|
t.Fatalf("after the follower stopped: err %v, heard %q", err, heard)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// serve's first views: on a module's own account the follower binds nothing and the runtime is given the hearer; on the
|
||||||
|
// machine's account the follower binds its own consumer and the runtime is given nothing (design 47 H §752, H-A-132).
|
||||||
|
func TestServesFollowerBindsOnlyOnTheMachinesAccount(t *testing.T) {
|
||||||
|
served := []runtime.Served{{Module: "mesh-delivery-indexer"}}
|
||||||
|
for _, row := range []struct {
|
||||||
|
own string
|
||||||
|
binds bool
|
||||||
|
}{{"mesh-delivery-indexer", false}, {runtime.NodeRuntimeModule, true}} {
|
||||||
|
t.Run(row.own, func(t *testing.T) {
|
||||||
|
bound := 0
|
||||||
|
d := firstview.Deps{Module: row.own,
|
||||||
|
Ask: func(string, any) (json.RawMessage, error) { return nil, errors.New("no owner here") },
|
||||||
|
Consume: func(func(bus.Envelope) error) (func(), error) { bound++; return func() {}, nil }}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
_, stop, opts := startViews(ctx, d, served, row.own, t.Logf)
|
||||||
|
cancel()
|
||||||
|
stop()
|
||||||
|
if (bound == 1) != row.binds || (len(opts) == 1) == row.binds {
|
||||||
|
t.Fatalf("the follower bound %d consumer(s), the runtime is given %d option(s); want the follower's own binding %v",
|
||||||
|
bound, len(opts), row.binds)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -63,11 +63,25 @@ func startSeatListOn(b seatlist.Bus, bound <-chan time.Time, logf func(string, .
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
catalogue.UseSeats(reader.Seats())
|
catalogue.UseSeats(reader.Seats())
|
||||||
|
// a first read that ended without an answer is no failure of the reader, which holds the bootstrap and waits for the seat's next
|
||||||
|
// event: so it is said here, where nothing else would say it, whether it ends before the bound or after it (a read the bus does
|
||||||
|
// not answer is asked again for about 30 s, so it ends after the bound); the runner then reads again where a bundle asks a verb of
|
||||||
|
// a seat the list defines that its definition does not name (design 47 G A-490m)
|
||||||
|
sayUnanswered := func() {
|
||||||
|
if st := reader.Status(); !st.Heard {
|
||||||
|
logf("node-tools: the first read of the seat list ended without an answer (%s); the runner serves with the bootstrapped seats and reads again when a bundle asks a verb of a seat the list defines that its definition does not name", st.LastError)
|
||||||
|
}
|
||||||
|
}
|
||||||
select {
|
select {
|
||||||
case <-reader.Ready():
|
case <-reader.Ready():
|
||||||
catalogue.UseSeats(reader.Seats())
|
catalogue.UseSeats(reader.Seats())
|
||||||
|
sayUnanswered()
|
||||||
case <-bound:
|
case <-bound:
|
||||||
logf("node-tools: the seat list is not read yet; the runner serves with the bootstrapped seats and reads on")
|
logf("node-tools: the seat list is not read yet; the runner serves with the bootstrapped seats and reads on")
|
||||||
|
go func() {
|
||||||
|
<-reader.Ready()
|
||||||
|
sayUnanswered()
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
return reader
|
return reader
|
||||||
}
|
}
|
||||||
@@ -82,3 +96,14 @@ func definitionsOf(reader *seatlist.Reader) func() map[string]seatdef.Definition
|
|||||||
return reader.Definitions()
|
return reader.Definitions()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// rereadOf is how the runner reads the seat list again where a verb is not named by the definitions it holds; it reads nothing
|
||||||
|
// while the reader did not start.
|
||||||
|
func rereadOf(reader *seatlist.Reader) func() error {
|
||||||
|
return func() error {
|
||||||
|
if reader == nil {
|
||||||
|
return fmt.Errorf("the seat list reader did not start")
|
||||||
|
}
|
||||||
|
return reader.Reload()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -32,19 +33,23 @@ func TestTheRunnerWaitsForTheFirstReadOfTheSeatListOnlyToItsBound(t *testing.T)
|
|||||||
wantSaid string
|
wantSaid string
|
||||||
wantReady bool
|
wantReady bool
|
||||||
}{
|
}{
|
||||||
{"the first read ends before the bound", true, "", true},
|
{"the first read ends before the bound, unanswered", true, "the first read of the seat list ended without an answer", true},
|
||||||
{"the bound passes with the seat silent", false, "the seat list is not read yet", false},
|
{"the bound passes with the seat silent", false, "the seat list is not read yet", false},
|
||||||
|
{"the bound passes, then the read ends unanswered", false, "the first read of the seat list ended without an answer", false},
|
||||||
} {
|
} {
|
||||||
t.Run(row.name, func(t *testing.T) {
|
t.Run(row.name, func(t *testing.T) {
|
||||||
b := &busOfAStandIn{release: make(chan struct{})}
|
b := &busOfAStandIn{release: make(chan struct{})}
|
||||||
bound := make(chan time.Time, 1)
|
bound := make(chan time.Time, 1)
|
||||||
|
var mu sync.Mutex
|
||||||
var said []string
|
var said []string
|
||||||
|
saidAgain := make(chan struct{}, 4)
|
||||||
|
say := func(f string, a ...any) { mu.Lock(); said = append(said, f); mu.Unlock(); saidAgain <- struct{}{} }
|
||||||
if row.release {
|
if row.release {
|
||||||
close(b.release)
|
close(b.release)
|
||||||
} else {
|
} else {
|
||||||
bound <- time.Time{}
|
bound <- time.Time{}
|
||||||
}
|
}
|
||||||
r := startSeatListOn(b, bound, func(f string, a ...any) { said = append(said, f) })
|
r := startSeatListOn(b, bound, say)
|
||||||
if r == nil {
|
if r == nil {
|
||||||
t.Fatal("no reader")
|
t.Fatal("no reader")
|
||||||
}
|
}
|
||||||
@@ -57,12 +62,25 @@ func TestTheRunnerWaitsForTheFirstReadOfTheSeatListOnlyToItsBound(t *testing.T)
|
|||||||
if ended != row.wantReady {
|
if ended != row.wantReady {
|
||||||
t.Errorf("first read ended = %v, want %v", ended, row.wantReady)
|
t.Errorf("first read ended = %v, want %v", ended, row.wantReady)
|
||||||
}
|
}
|
||||||
if got := strings.Join(said, ";"); !strings.Contains(got, row.wantSaid) || (row.wantSaid == "" && got != "") {
|
|
||||||
t.Errorf("said %q, want %q", got, row.wantSaid)
|
|
||||||
}
|
|
||||||
if !row.release {
|
if !row.release {
|
||||||
close(b.release)
|
close(b.release)
|
||||||
<-r.Ready()
|
<-r.Ready()
|
||||||
|
// the read that ends after the bound is said by a goroutine of its own: wait for it, to a deadline that only a fault reaches
|
||||||
|
if strings.Contains(row.wantSaid, "first read") {
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
select {
|
||||||
|
case <-saidAgain:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("the unanswered end of the first read was never said")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
got := strings.Join(said, ";")
|
||||||
|
mu.Unlock()
|
||||||
|
if !strings.Contains(got, row.wantSaid) {
|
||||||
|
t.Errorf("said %q, want %q", got, row.wantSaid)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/seatlist"
|
||||||
|
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// catalogStandIn is the seat mesh-catalog's verb `seat-definitions`, as the seat list's reader asks it: the seat node-desk whose
|
||||||
|
// first listing names the verbs who and slow (slow with a timeout of one second) and, from the second listing on, also the verb
|
||||||
|
// fresh, which sends its answer in chunks.
|
||||||
|
type catalogStandIn struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
listings int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *catalogStandIn) definition(withFresh bool) json.RawMessage {
|
||||||
|
one := 1
|
||||||
|
verbs := []seatdef.Verb{{Name: "who"}, {Name: "slow", Timeout: &one}}
|
||||||
|
if withFresh {
|
||||||
|
verbs = append(verbs, seatdef.Verb{Name: "fresh", Chunks: true})
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(seatdef.Definition{Format: seatdef.Format, Seat: "node-desk", Scope: seatdef.ScopeNode, Grain: seatdef.SeatList,
|
||||||
|
Decision: "ADR 0001", Domain: seatdef.Domains[0], Verbs: verbs})
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *catalogStandIn) handle(body json.RawMessage) (any, error) {
|
||||||
|
var asked struct {
|
||||||
|
Seat string `json:"seat"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(body, &asked)
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if asked.Seat == "" {
|
||||||
|
c.listings++
|
||||||
|
return seatlist.Listing{Revision: uint64(c.listings), Seats: []seatlist.Entry{{Seat: "node-desk", Source: seatlist.SourceTrunk,
|
||||||
|
Digest: map[bool]string{false: "d1", true: "d2"}[c.listings > 1]}}}, nil
|
||||||
|
}
|
||||||
|
withFresh := c.listings > 1
|
||||||
|
return seatlist.Answer{Seat: asked.Seat, Found: true, Revision: uint64(c.listings), Entry: &seatlist.Entry{Seat: asked.Seat,
|
||||||
|
Source: seatlist.SourceTrunk, Digest: map[bool]string{false: "d1", true: "d2"}[withFresh], Definition: c.definition(withFresh)}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// **The tool runner, started whole by its entry** (design 47 H §774, H-A-16, H-A-61): the process's own `serve`, on an embedded bus with
|
||||||
|
// JetStream, with a credential file and the environment the node-engine writes, serving one bundle's tool and seat verbs, over the
|
||||||
|
// seat list read from a stand-in of the seat mesh-catalog.
|
||||||
|
// - the bundle's tool and its seat verb are answered on the bus (§734's way of serving a verb from a bundle);
|
||||||
|
// - a verb whose definition names a timeout of one second is waited one second by the serving runner, not the runner's own
|
||||||
|
// thirty (design 47 H §760, H-A-43);
|
||||||
|
// - a bundle's ask of a seat verb its first seat list does not name is asked after one reread of the list, with its call token
|
||||||
|
// for a verb that sends chunks (design 47 G A-490m).
|
||||||
|
func TestTheToolRunnerStartedByItsEntryServesABundleOverTheSeatListItReads(t *testing.T) {
|
||||||
|
mesh := mt.New(t)
|
||||||
|
ledger := mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who", "slow"}})
|
||||||
|
ledger.State = []bus.StateIssued{{Name: "pages", Bucket: "ledger_pages", Writes: true}}
|
||||||
|
mesh.Issue(t, ledger)
|
||||||
|
// a state of 10,000 keys of 300 bytes each, about four pages of 768 KB (design 47 H2 §779)
|
||||||
|
pages := mesh.Bucket(t, "ledger_pages")
|
||||||
|
value := []byte(`"` + strings.Repeat("v", 298) + `"`)
|
||||||
|
for i := range 10000 {
|
||||||
|
if _, err := pages.Put(fmt.Sprintf("k%05d", i), value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
credential, _ := json.Marshal(bus.Credential{URL: mt.URL(t), Module: runtimeModule, Node: "anchor"})
|
||||||
|
file := filepath.Join(dir, "broker")
|
||||||
|
if err := os.WriteFile(file, credential, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("MESH_BROKER_FILE", file)
|
||||||
|
t.Setenv("MESH_TOOL_MODULES", "ledger="+mt.Fixture("whole-bundle.py"))
|
||||||
|
t.Setenv("MESH_CONSOLE_LISTEN", "127.0.0.1:0")
|
||||||
|
heldFile := filepath.Join(dir, "held")
|
||||||
|
t.Setenv("HELD_FILE", heldFile)
|
||||||
|
|
||||||
|
open := func(module, node string) *bus.Conn {
|
||||||
|
c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: module, Node: node, User: node + "." + module, Password: "unused"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.Logf = func(string, ...any) {}
|
||||||
|
t.Cleanup(c.Close)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
catalog := &catalogStandIn{}
|
||||||
|
holder := open("mesh-catalog", "anchor")
|
||||||
|
if _, err := holder.HandleSubject("mesh.seat.mesh-catalog.tool.seat-definitions", func(body json.RawMessage) (any, error) { return catalog.handle(body) }); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var mu sync.Mutex
|
||||||
|
var fresh []map[string]any
|
||||||
|
if _, err := holder.HandleSubject("mesh.seat.node-desk.tool.fresh", func(body json.RawMessage) (any, error) {
|
||||||
|
var got map[string]any
|
||||||
|
_ = json.Unmarshal(body, &got)
|
||||||
|
mu.Lock()
|
||||||
|
fresh = append(fresh, got)
|
||||||
|
mu.Unlock()
|
||||||
|
return map[string]any{"ok": true}, nil
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
holder.Flush()
|
||||||
|
|
||||||
|
// The journal, read for the drain's line at the stop (design 47 H2 §813 (12)).
|
||||||
|
journal := &said{}
|
||||||
|
log.SetOutput(journal)
|
||||||
|
t.Cleanup(func() { log.SetOutput(os.Stderr) })
|
||||||
|
// the setting drain-bound as the node-engine composes it (H-A-370, H-A-377)
|
||||||
|
t.Setenv("MESH_CONFIG_DRAIN_BOUND", "2s")
|
||||||
|
|
||||||
|
ctx, stop := context.WithCancel(context.Background())
|
||||||
|
ended := make(chan error, 1)
|
||||||
|
go func() { ended <- serve(ctx) }()
|
||||||
|
var stopped sync.Once
|
||||||
|
stopServe := func() {
|
||||||
|
stopped.Do(func() {
|
||||||
|
stop()
|
||||||
|
select {
|
||||||
|
case err := <-ended:
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("serve ended with %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(mt.Bound(t)):
|
||||||
|
t.Errorf("the tool runner did not stop within %s", mt.Bound(t))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
t.Cleanup(stopServe)
|
||||||
|
// a module's account, which the approval gate runs unmarked while the catalog half is unread (the stand-in serves no catalog half)
|
||||||
|
asker := open("shop", "workstation")
|
||||||
|
ask := func(key string) (string, error) {
|
||||||
|
answered, err := asker.Ask(key, map[string]any{}, "")
|
||||||
|
return string(answered.Result), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// the bundle's tool and its seat verb are served
|
||||||
|
for _, key := range []string{"ledger.who", "seat:node-desk.who@anchor"} {
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
got, err := ask(key)
|
||||||
|
if err == nil && !strings.Contains(got, `"tool":`) {
|
||||||
|
t.Errorf("%s answered %s, want the bundle's", key, got)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// a verb whose definition names a timeout of one second is waited one second
|
||||||
|
began := time.Now()
|
||||||
|
if _, err := ask("seat:node-desk.slow@anchor"); err == nil {
|
||||||
|
t.Error("the verb that answers after three seconds was answered within its timeout of one second")
|
||||||
|
}
|
||||||
|
if took := time.Since(began); took < time.Second || took > bus.RequestTimeout/2 { // 1754/AC4
|
||||||
|
t.Errorf("the verb of a timeout of one second was waited %s, want about one second, not the runner's own %s", took, bus.RequestTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// the bundle's ask of a verb its first list does not name is asked after one reread, with its call token
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
got, err := ask("ledger.reach")
|
||||||
|
if err == nil && strings.Contains(got, "error") {
|
||||||
|
t.Errorf("the bundle's ask of node-desk.fresh failed: %s", got)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
catalog.mu.Lock()
|
||||||
|
listings := catalog.listings
|
||||||
|
catalog.mu.Unlock()
|
||||||
|
mu.Lock()
|
||||||
|
if listings != 2 || len(fresh) != 1 || fresh[0]["call"] == nil || fresh[0]["call"] == "" {
|
||||||
|
t.Errorf("the list was read %d times (want 2) and the holder of node-desk.fresh was asked %v (want once, with a call token)", listings, fresh)
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
|
||||||
|
// a state read in pages by the bundle, each after the cursor the page before answered, delivers each kept message once
|
||||||
|
// across the pages, and a key written again mid-read comes again in a later page marked seen-again (design 47 H2 §779,
|
||||||
|
// H-A-382)
|
||||||
|
type paged struct {
|
||||||
|
Keys []string `json:"keys"`
|
||||||
|
Again []string `json:"again"`
|
||||||
|
Next string `json:"next"`
|
||||||
|
Error any `json:"error"`
|
||||||
|
}
|
||||||
|
readPage := func(cursor string) paged {
|
||||||
|
t.Helper()
|
||||||
|
answered, err := asker.AskWithin("ledger.page", map[string]any{"cursor": cursor}, "", mt.Bound(t))
|
||||||
|
var p paged
|
||||||
|
if err != nil || json.Unmarshal(answered.Result, &p) != nil || p.Error != nil {
|
||||||
|
t.Fatalf("the page after %q was answered %.300s, %v", cursor, answered.Result, err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
handed, again, count := map[string]int{}, []string{}, 0
|
||||||
|
for p, n := readPage(""), 1; ; p, n = readPage(p.Next), n+1 {
|
||||||
|
count++
|
||||||
|
for _, k := range p.Keys {
|
||||||
|
handed[k]++
|
||||||
|
}
|
||||||
|
again = append(again, p.Again...)
|
||||||
|
if n == 1 {
|
||||||
|
if len(p.Keys) == 0 || p.Keys[0] != "k00000" || p.Next == "" {
|
||||||
|
t.Fatalf("the first page holds %d keys from %v and next %q; want k00000 first and more to follow", len(p.Keys), p.Keys[:min(1, len(p.Keys))], p.Next)
|
||||||
|
}
|
||||||
|
if _, err := pages.Put("k00000", []byte(`"again"`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.Next == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if count > 20 {
|
||||||
|
t.Fatal("the read did not end within 20 pages")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if count < 3 || len(handed) != 10000 || len(again) != 1 || again[0] != "k00000" {
|
||||||
|
t.Errorf("the read took %d pages, handed %d keys and marked %v seen-again; want at least 3 pages, 10,000 keys and k00000", count, len(handed), again)
|
||||||
|
}
|
||||||
|
for k, n := range handed {
|
||||||
|
if n != 1 {
|
||||||
|
t.Errorf("%s was handed %d times outside of seen-again, want once", k, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// at its stop the runner drains (design 47 H2 §813 (12), H-A-353; the bound 2 s here for the setting's 30 s): a call of 1 s in
|
||||||
|
// flight is answered, one of 6 s is cut at the bound, said, and its caller answered nothing; a call after the stop meets no
|
||||||
|
// responders, since the runner took its subscriptions down first (H-A-570 (1))
|
||||||
|
type answer struct {
|
||||||
|
got string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
hold := func(seconds int, within time.Duration) chan answer {
|
||||||
|
out := make(chan answer, 1)
|
||||||
|
go func() {
|
||||||
|
answered, err := asker.AskWithin("ledger.hold", map[string]any{"seconds": seconds}, "", within)
|
||||||
|
out <- answer{string(answered.Result), err}
|
||||||
|
}()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
short, long := hold(1, 10*time.Second), hold(6, 5*time.Second)
|
||||||
|
// both calls are in flight once the bundle noted them
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
if noted, _ := os.ReadFile(heldFile); strings.Count(string(noted), "hold") != 2 {
|
||||||
|
return fmt.Errorf("the bundle noted %q, want both calls", noted)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
stop()
|
||||||
|
// a call after the stop began, of a tool and of a seat verb, meets no responders within a second, a transport fault its
|
||||||
|
// caller's kept call waits out until the new runner subscribes, never an answer of the old runner's (H-A-570 (1)): until
|
||||||
|
// the runner took its subscriptions down it is still answered. The runner takes them down before it drains, so its callers
|
||||||
|
// meet no responders while the call of 6 s is still in flight, before the drain bound cuts it.
|
||||||
|
for _, key := range []string{"ledger.who", "seat:node-desk.who@anchor"} {
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
at := time.Now()
|
||||||
|
answered, err := asker.AskWithin(key, map[string]any{}, "", 300*time.Millisecond)
|
||||||
|
if took := time.Since(at); !errors.Is(err, bus.ErrNoResponders) || took > time.Second {
|
||||||
|
return fmt.Errorf("a call of %s after the stop was answered %s, %v in %s; want no responders within a second", key,
|
||||||
|
answered.Result, err, took)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if journal.has("cut ledger's call hold") {
|
||||||
|
t.Errorf("a call of %s met no responders only once the drain had ended, want it from the stop on", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := <-short; got.err != nil || !strings.Contains(got.got, `"held":1`) {
|
||||||
|
t.Errorf("the call of 1 s in flight at the stop was answered %s, %v; want it finished", got.got, got.err)
|
||||||
|
}
|
||||||
|
if got := <-long; got.err == nil || strings.Contains(got.err.Error(), "cut") {
|
||||||
|
t.Errorf("the call of 6 s was answered %s, %v; want no answer, a transport fault for its caller", got.got, got.err)
|
||||||
|
}
|
||||||
|
stopServe()
|
||||||
|
if !journal.has("cut ledger's call hold") {
|
||||||
|
t.Errorf("the journal does not say the cut call: %s", journal.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// said is the runner's journal in a test, safe to read while it writes.
|
||||||
|
type said struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
b strings.Builder
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *said) Write(p []byte) (int, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.b.Write(p) }
|
||||||
|
func (s *said) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
|
||||||
|
func (s *said) has(words string) bool { return strings.Contains(s.String(), words) }
|
||||||
+6
-3
@@ -5,14 +5,13 @@ go 1.26.0
|
|||||||
require (
|
require (
|
||||||
git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshconditionsclient v0.0.0-00010101000000-000000000000
|
|
||||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-contracts/provisioning/go/clients/meshprovisionerclient v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient v0.0.0-00010101000000-000000000000
|
||||||
git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000
|
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000
|
||||||
github.com/nats-io/nats.go v1.54.0
|
github.com/nats-io/nats.go v1.54.0
|
||||||
golang.org/x/sys v0.48.0
|
golang.org/x/sys v0.48.0
|
||||||
)
|
)
|
||||||
@@ -30,3 +29,7 @@ require (
|
|||||||
golang.org/x/crypto v0.57.0 // indirect
|
golang.org/x/crypto v0.57.0 // indirect
|
||||||
golang.org/x/time v0.16.0 // indirect
|
golang.org/x/time v0.16.0 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
|
require git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery v0.0.0-00010101000000-000000000000 // indirect
|
||||||
|
|
||||||
|
require git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk v0.0.0-00010101000000-000000000000 // indirect
|
||||||
|
|||||||
@@ -49,13 +49,20 @@ func Version() string {
|
|||||||
// Keep says the runtime is there now and every interval until the returned function is called. A
|
// Keep says the runtime is there now and every interval until the returned function is called. A
|
||||||
// heartbeat that cannot be said is logged when that starts and when it stops — not every minute.
|
// heartbeat that cannot be said is logged when that starts and when it stops — not every minute.
|
||||||
func Keep(bus Sayer, node string, every time.Duration, logf func(string, ...any)) func() {
|
func Keep(bus Sayer, node string, every time.Duration, logf func(string, ...any)) func() {
|
||||||
|
tick := time.NewTicker(every)
|
||||||
|
stop := keep(bus, node, every, tick.C, logf)
|
||||||
|
return func() { stop(); tick.Stop() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// keep is Keep saying it again on every tick: the interval is told in the beat, the ticks are the caller's.
|
||||||
|
// Its stop returns once nothing more is said.
|
||||||
|
func keep(bus Sayer, node string, every time.Duration, ticks <-chan time.Time, logf func(string, ...any)) func() {
|
||||||
body, _ := json.Marshal(Beat{Node: node, IntervalSeconds: int(every / time.Second), Version: Version()})
|
body, _ := json.Marshal(Beat{Node: node, IntervalSeconds: int(every / time.Second), Version: Version()})
|
||||||
done := make(chan struct{})
|
done, ended := make(chan struct{}), make(chan struct{})
|
||||||
var once sync.Once
|
var once sync.Once
|
||||||
go func() {
|
go func() {
|
||||||
|
defer close(ended)
|
||||||
failing := ""
|
failing := ""
|
||||||
tick := time.NewTicker(every)
|
|
||||||
defer tick.Stop()
|
|
||||||
for {
|
for {
|
||||||
why := ""
|
why := ""
|
||||||
if err := bus.Say(Subject(node), body); err != nil {
|
if err := bus.Say(Subject(node), body); err != nil {
|
||||||
@@ -72,9 +79,12 @@ func Keep(bus Sayer, node string, every time.Duration, logf func(string, ...any)
|
|||||||
select {
|
select {
|
||||||
case <-done:
|
case <-done:
|
||||||
return
|
return
|
||||||
case <-tick.C:
|
case <-ticks:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
return func() { once.Do(func() { close(done) }) }
|
return func() {
|
||||||
|
once.Do(func() { close(done) })
|
||||||
|
<-ended
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package alive
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"runtime"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -13,11 +15,29 @@ type said struct {
|
|||||||
subs []string
|
subs []string
|
||||||
body [][]byte
|
body [][]byte
|
||||||
fail error
|
fail error
|
||||||
|
// tried is told every Say, said or not, so a test waits on the heartbeat itself and never on the clock.
|
||||||
|
tried chan struct{}
|
||||||
|
// held, when set, keeps each Say from returning until it is closed; inSay says one is held there now.
|
||||||
|
held chan struct{}
|
||||||
|
inSay atomic.Bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newSaid(fail error) *said { return &said{fail: fail, tried: make(chan struct{}, 16)} }
|
||||||
|
|
||||||
func (s *said) Say(subject string, body []byte) error {
|
func (s *said) Say(subject string, body []byte) error {
|
||||||
|
if s.held != nil {
|
||||||
|
s.inSay.Store(true)
|
||||||
|
s.tried <- struct{}{}
|
||||||
|
<-s.held
|
||||||
|
defer s.inSay.Store(false)
|
||||||
|
}
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer func() {
|
||||||
|
s.mu.Unlock()
|
||||||
|
if s.held == nil {
|
||||||
|
s.tried <- struct{}{}
|
||||||
|
}
|
||||||
|
}()
|
||||||
if s.fail != nil {
|
if s.fail != nil {
|
||||||
return s.fail
|
return s.fail
|
||||||
}
|
}
|
||||||
@@ -32,39 +52,85 @@ func (s *said) count() int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// **The runtime says it is there at once and every interval, as its machine, with the interval**: the
|
// **The runtime says it is there at once and every interval, as its machine, with the interval**: the
|
||||||
// controller's bound is three of them (to-be 45 S11).
|
// controller's bound is three of them (to-be 45 S11). The ticks are the test's own, so a loaded machine
|
||||||
|
// cannot make it miss one (principle 11; design 47 H §774); stopped, it says nothing more.
|
||||||
func TestTheRuntimeSaysItIsThereEveryInterval(t *testing.T) {
|
func TestTheRuntimeSaysItIsThereEveryInterval(t *testing.T) {
|
||||||
s := &said{}
|
s := newSaid(nil)
|
||||||
stop := Keep(s, "anchor", 20*time.Millisecond, t.Logf)
|
ticks := make(chan time.Time)
|
||||||
time.Sleep(70 * time.Millisecond)
|
stop := keep(s, "anchor", 20*time.Millisecond, ticks, t.Logf)
|
||||||
|
<-s.tried
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
ticks <- time.Time{}
|
||||||
|
<-s.tried
|
||||||
|
}
|
||||||
stop()
|
stop()
|
||||||
stop()
|
stop()
|
||||||
if n := s.count(); n < 3 {
|
if n := s.count(); n != 3 {
|
||||||
t.Fatalf("said %d times in three intervals", n)
|
t.Fatalf("said %d times at once and on two ticks", n)
|
||||||
}
|
}
|
||||||
var beat Beat
|
var beat Beat
|
||||||
if err := json.Unmarshal(s.body[0], &beat); err != nil || beat.Node != "anchor" || beat.IntervalSeconds != 0 ||
|
if err := json.Unmarshal(s.body[0], &beat); err != nil || beat.Node != "anchor" || beat.IntervalSeconds != 0 ||
|
||||||
s.subs[0] != "mesh.control.anchor.tools-alive" {
|
s.subs[0] != "mesh.control.anchor.tools-alive" {
|
||||||
t.Fatalf("%s on %s: %v", s.body[0], s.subs[0], err)
|
t.Fatalf("%s on %s: %v", s.body[0], s.subs[0], err)
|
||||||
}
|
}
|
||||||
n := s.count()
|
select {
|
||||||
time.Sleep(50 * time.Millisecond)
|
case ticks <- time.Time{}:
|
||||||
if s.count() != n {
|
t.Fatal("a tick was taken after it was stopped")
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
if s.count() != 3 {
|
||||||
t.Fatal("said after it was stopped")
|
t.Fatal("said after it was stopped")
|
||||||
}
|
}
|
||||||
|
// Stopped while a beat is being said, stop returns only once that Say has returned: nothing is said after it.
|
||||||
|
slow := newSaid(nil)
|
||||||
|
slow.held = make(chan struct{})
|
||||||
|
stopSlow := keep(slow, "anchor", 20*time.Millisecond, make(chan time.Time), t.Logf)
|
||||||
|
<-slow.tried
|
||||||
|
returned := make(chan bool)
|
||||||
|
go func() {
|
||||||
|
stopSlow()
|
||||||
|
returned <- slow.inSay.Load()
|
||||||
|
}()
|
||||||
|
// The stop is given its turn before the Say is let go (no clock: a returned stop is seen at once).
|
||||||
|
for i := 0; i < 1000; i++ {
|
||||||
|
select {
|
||||||
|
case stillSaying := <-returned:
|
||||||
|
close(slow.held)
|
||||||
|
t.Fatalf("stop returned while a beat was still being said (held: %v)", stillSaying)
|
||||||
|
default:
|
||||||
|
runtime.Gosched()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
close(slow.held)
|
||||||
|
if stillSaying := <-returned; stillSaying {
|
||||||
|
t.Fatal("stop returned while a beat was still being said")
|
||||||
|
}
|
||||||
|
// Keep itself keeps the interval on a ticker of its own.
|
||||||
|
kept := newSaid(nil)
|
||||||
|
stopKept := Keep(kept, "anchor", time.Hour, t.Logf)
|
||||||
|
<-kept.tried
|
||||||
|
stopKept()
|
||||||
|
if kept.count() != 1 {
|
||||||
|
t.Fatalf("Keep said %d times before its first interval", kept.count())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// **A heartbeat the bus will not take is said once, and again when it is taken**: not a line a minute.
|
// **A heartbeat the bus will not take is said once, and again when it is taken**: not a line a minute.
|
||||||
func TestAHeartbeatThatCannotBeSaidIsLoggedOnce(t *testing.T) {
|
func TestAHeartbeatThatCannotBeSaidIsLoggedOnce(t *testing.T) {
|
||||||
s := &said{fail: errors.New("permissions violation")}
|
s := newSaid(errors.New("permissions violation"))
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
var lines []string
|
var lines []string
|
||||||
stop := Keep(s, "anchor", 10*time.Millisecond, func(f string, a ...any) {
|
ticks := make(chan time.Time)
|
||||||
|
stop := keep(s, "anchor", 10*time.Millisecond, ticks, func(f string, a ...any) {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
lines = append(lines, f)
|
lines = append(lines, f)
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
})
|
})
|
||||||
time.Sleep(60 * time.Millisecond)
|
<-s.tried
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
ticks <- time.Time{}
|
||||||
|
<-s.tried
|
||||||
|
}
|
||||||
stop()
|
stop()
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
|
|||||||
@@ -48,6 +48,11 @@ const Digest = "digest"
|
|||||||
// module needing one is placed only where the runtime states it.
|
// module needing one is placed only where the runtime states it.
|
||||||
const Capabilities = "capabilities"
|
const Capabilities = "capabilities"
|
||||||
|
|
||||||
|
// Fingerprint is the service metadata key the tool runner states its own fingerprint under, beside Capabilities: the build
|
||||||
|
// its composed environment names (MESH_FINGERPRINT, design 47 G §424), so the node-engine ties the capabilities it takes
|
||||||
|
// into the node's record to the runner that stated them (design 46 approval mark §6, lead answer A-203).
|
||||||
|
const Fingerprint = "fingerprint"
|
||||||
|
|
||||||
// Shortened is the service metadata key a runtime sets when its announcement was cut to fit the bus.
|
// Shortened is the service metadata key a runtime sets when its announcement was cut to fit the bus.
|
||||||
const Shortened = "shortened"
|
const Shortened = "shortened"
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package approval
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -10,7 +11,7 @@ import (
|
|||||||
|
|
||||||
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||||
seat "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
seat "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
gate "git.novox.be/novox/mesh-sdk/go/approval"
|
gate "git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||||
@@ -217,16 +218,6 @@ func TestTheRefusalsAndAnswers(t *testing.T) {
|
|||||||
t.Fatalf("asked %d, %v, runs %d", len(w.asked), err, w.runs)
|
t.Fatalf("asked %d, %v, runs %d", len(w.asked), err, w.runs)
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
{"§17: an ask the router holds back as the fourth open one still waits", func(t *testing.T, w *world) {
|
|
||||||
_, _ = w.do(call("wipe", `{}`))
|
|
||||||
a := w.asked[0]
|
|
||||||
rec := w.records["shell."+a.ID]
|
|
||||||
rec.State, rec.HeldSince = "held-back", operatorchannelclient.FormatTime(w.now)
|
|
||||||
w.records["shell."+a.ID] = rec
|
|
||||||
if _, err := w.do(call("wipe", `{}`)); err == nil || !strings.Contains(err.Error(), "still waiting") || len(w.asked) != 1 {
|
|
||||||
t.Fatalf("%v, asked %d", err, len(w.asked))
|
|
||||||
}
|
|
||||||
}},
|
|
||||||
{"§14, §15: approved, the same call runs once; made again it is already run and asks anew", func(t *testing.T, w *world) {
|
{"§14, §15: approved, the same call runs once; made again it is already run and asks anew", func(t *testing.T, w *world) {
|
||||||
_, _ = w.do(call("wipe", `{"dir":"scratch"}`))
|
_, _ = w.do(call("wipe", `{"dir":"scratch"}`))
|
||||||
w.decide(gate.OptionApprove, w.now.Add(time.Minute))
|
w.decide(gate.OptionApprove, w.now.Add(time.Minute))
|
||||||
@@ -320,9 +311,9 @@ func TestTheRefusalsAndAnswers(t *testing.T) {
|
|||||||
_, _ = w.do(call("wipe", `{}`))
|
_, _ = w.do(call("wipe", `{}`))
|
||||||
a := w.asked[0]
|
a := w.asked[0]
|
||||||
rec := w.records["shell."+a.ID]
|
rec := w.records["shell."+a.ID]
|
||||||
rec.State, rec.Answer = "refused", "the asker has too many open asks"
|
rec.State, rec.Answer = "refused", "the asker is not known to the router"
|
||||||
w.records["shell."+a.ID] = rec
|
w.records["shell."+a.ID] = rec
|
||||||
if _, err := w.do(call("wipe", `{}`)); err == nil || !strings.Contains(err.Error(), "the asker has too many open asks") {
|
if _, err := w.do(call("wipe", `{}`)); err == nil || !strings.Contains(err.Error(), "the asker is not known to the router") {
|
||||||
t.Fatalf("%v", err)
|
t.Fatalf("%v", err)
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
@@ -506,4 +497,86 @@ func TestTheRefusalsAndAnswers(t *testing.T) {
|
|||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) { tc.run(t, newWorld()) })
|
t.Run(tc.name, func(t *testing.T) { tc.run(t, newWorld()) })
|
||||||
}
|
}
|
||||||
|
// Design 46 7-approval-mark §5, §3, §4 and design 34 every-event §33: the marks a module's calls are gated by, derived from
|
||||||
|
// fixture catalog halves and served entries.
|
||||||
|
t.Run("TheMarks", func(t *testing.T) {
|
||||||
|
login := map[string]seatdef.Definition{"node-login-shell": {Seat: "node-login-shell",
|
||||||
|
Verbs: []seatdef.Verb{{Name: "execute", NeedsApproval: true}, {Name: "sessions"}}}}
|
||||||
|
v1 := entry("src2:1", []string{"node-login-shell.execute", "node-login-shell.sessions"},
|
||||||
|
map[string]any{"needs-approval": []any{"wipe"}})
|
||||||
|
v2 := entry("src2:2", []string{"node-login-shell.execute", "node-login-shell.sessions"},
|
||||||
|
map[string]any{"needs-approval": []any{"erase", "node-login-shell.sessions"}})
|
||||||
|
mail := catalogseat.CatalogEntry{Module: "mail", Fp: "src2:m", Manifest: map[string]any{
|
||||||
|
"needs-approval": []any{"mail.received"}, "emits": []any{"mail.received"},
|
||||||
|
"streams": []any{map[string]any{"name": "MAIL", "events": []any{"mail.**"}, "grant": map[string]any{"config": "readers", "events": "mail.{key}.**"}}}}}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
cat *fakeCatalog
|
||||||
|
module string
|
||||||
|
fp string
|
||||||
|
tools []string
|
||||||
|
verbs map[string]string
|
||||||
|
subjects []string
|
||||||
|
unread bool
|
||||||
|
}{
|
||||||
|
{name: "a seat's mark stands for every holder, and the holder's own adds up", cat: &fakeCatalog{revision: "7",
|
||||||
|
byFp: map[string]catalogseat.CatalogEntry{"src2:1": v1}, newest: map[string]catalogseat.CatalogEntry{"shell": v1}, defs: login},
|
||||||
|
module: "shell", fp: "src2:1", tools: []string{"wipe"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell"}},
|
||||||
|
{name: "a holder's needs-approval cannot unmark its seat's verb, and marks another", cat: &fakeCatalog{revision: "8",
|
||||||
|
byFp: map[string]catalogseat.CatalogEntry{"src2:2": v2}, newest: map[string]catalogseat.CatalogEntry{"shell": v2}, defs: login},
|
||||||
|
module: "shell", fp: "src2:2", tools: []string{"erase"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell",
|
||||||
|
"node-login-shell.sessions": "entry shell src2:2"}},
|
||||||
|
{name: "across a version change the union stands: a dropped mark is asked while the old bundle runs", cat: &fakeCatalog{revision: "9",
|
||||||
|
byFp: map[string]catalogseat.CatalogEntry{"src2:1": v1, "src2:2": v2}, newest: map[string]catalogseat.CatalogEntry{"shell": v2}, defs: login},
|
||||||
|
module: "shell", fp: "src2:1", tools: []string{"erase", "wipe"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell",
|
||||||
|
"node-login-shell.sessions": "entry shell src2:2"}},
|
||||||
|
{name: "a served entry that cannot be read leaves the newest marks, every marked call refused", cat: &fakeCatalog{revision: "9",
|
||||||
|
newest: map[string]catalogseat.CatalogEntry{"shell": v2}, defs: login},
|
||||||
|
module: "shell", fp: "src2:1", tools: []string{"erase"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell",
|
||||||
|
"node-login-shell.sessions": "entry shell src2:2"}, unread: true},
|
||||||
|
{name: "a bundle with no fingerprint has no served entry", cat: &fakeCatalog{revision: "9", defs: login},
|
||||||
|
module: "shell", unread: true},
|
||||||
|
{name: "a marked event and a stream with a grant give their subjects and each .>", cat: &fakeCatalog{revision: "3",
|
||||||
|
byFp: map[string]catalogseat.CatalogEntry{"src2:m": mail}, newest: map[string]catalogseat.CatalogEntry{"mail": mail}},
|
||||||
|
module: "mail", fp: "src2:m", subjects: []string{"mesh.mod.mail.event.mail.received", "mesh.mod.mail.event.mail.received.>",
|
||||||
|
"mesh.stream.mail.event.mail.>", "mesh.stream.mail.event.mail.received", "mesh.stream.mail.event.mail.received.>"}},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
m := gate.Derive(tc.cat, tc.module, tc.fp)
|
||||||
|
if got := keysOf(m.Tools); !reflect.DeepEqual(got, tc.tools) {
|
||||||
|
t.Errorf("tools %v, want %v", got, tc.tools)
|
||||||
|
}
|
||||||
|
if tc.verbs == nil {
|
||||||
|
tc.verbs = map[string]string{}
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(m.Verbs, tc.verbs) {
|
||||||
|
t.Errorf("verbs %v, want %v", m.Verbs, tc.verbs)
|
||||||
|
}
|
||||||
|
if got := keysOf(m.Subjects); !reflect.DeepEqual(got, tc.subjects) {
|
||||||
|
t.Errorf("subjects %v, want %v", got, tc.subjects)
|
||||||
|
}
|
||||||
|
if (m.Unread != "") != tc.unread || m.Revision != tc.cat.revision {
|
||||||
|
t.Errorf("unread %q, revision %q", m.Unread, m.Revision)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// §4: a bundle whose marks name a tool it does not register is not loaded, its finding mark-unserved raised; a bundle that
|
||||||
|
// serves it clears it, and a catalog without the mark too.
|
||||||
|
t.Run("mark-unserved raised and cleared", func(t *testing.T) {
|
||||||
|
cat := &fakeCatalog{revision: "7", byFp: map[string]catalogseat.CatalogEntry{"src2:1": v1}, newest: map[string]catalogseat.CatalogEntry{"shell": v1}, defs: login}
|
||||||
|
w := &findings{}
|
||||||
|
g := gate.New(gate.Deps{Node: "n1", Runner: "node-tools", Catalog: cat, Findings: Findings(w, "n1", "node-tools", nil)})
|
||||||
|
if got := g.Unserved("shell", "src2:1", []string{"other"}); !reflect.DeepEqual(got, []string{"wipe"}) || w.raised[keys.EscapeName("n1.shell")] != gate.KindMarkUnserved {
|
||||||
|
t.Fatalf("unserved %v, findings %v", got, w.raised)
|
||||||
|
}
|
||||||
|
if got := g.Unserved("shell", "src2:1", []string{"wipe"}); got != nil || w.raised[keys.EscapeName("n1.shell")] != "" {
|
||||||
|
t.Fatalf("a bundle serving the mark: unserved %v, findings %v", got, w.raised)
|
||||||
|
}
|
||||||
|
_ = g.Unserved("shell", "src2:1", nil)
|
||||||
|
cat.byFp["src2:1"], cat.newest["shell"] = entry("src2:1", nil, nil), entry("src2:1", nil, nil)
|
||||||
|
if got := g.Unserved("shell", "src2:1", nil); got != nil || w.raised[keys.EscapeName("n1.shell")] != "" {
|
||||||
|
t.Fatalf("a catalog without the mark: unserved %v, findings %v", got, w.raised)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
|
|
||||||
assignerseat "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
assignerseat "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||||
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
gate "git.novox.be/novox/mesh-sdk/go/approval"
|
gate "git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -2,15 +2,12 @@ package approval
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"reflect"
|
|
||||||
"sort"
|
"sort"
|
||||||
"testing"
|
|
||||||
|
|
||||||
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
|
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
gate "git.novox.be/novox/mesh-sdk/go/approval"
|
gate "git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
)
|
)
|
||||||
@@ -47,89 +44,6 @@ func entry(fp string, serves []string, manifest map[string]any) catalogseat.Cata
|
|||||||
return catalogseat.CatalogEntry{Module: "shell", Fp: fp, Serves: serves, Manifest: manifest}
|
return catalogseat.CatalogEntry{Module: "shell", Fp: fp, Serves: serves, Manifest: manifest}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Design 46 7-approval-mark §5, §3, §4 and design 34 every-event §33: the marks a module's calls are gated by, derived from
|
|
||||||
// fixture catalog halves and served entries.
|
|
||||||
func TestTheMarks(t *testing.T) {
|
|
||||||
login := map[string]seatdef.Definition{"node-login-shell": {Seat: "node-login-shell",
|
|
||||||
Verbs: []seatdef.Verb{{Name: "execute", NeedsApproval: true}, {Name: "sessions"}}}}
|
|
||||||
v1 := entry("src2:1", []string{"node-login-shell.execute", "node-login-shell.sessions"},
|
|
||||||
map[string]any{"needs-approval": []any{"wipe"}})
|
|
||||||
v2 := entry("src2:2", []string{"node-login-shell.execute", "node-login-shell.sessions"},
|
|
||||||
map[string]any{"needs-approval": []any{"erase", "node-login-shell.sessions"}})
|
|
||||||
mail := catalogseat.CatalogEntry{Module: "mail", Fp: "src2:m", Manifest: map[string]any{
|
|
||||||
"needs-approval": []any{"mail.received"}, "emits": []any{"mail.received"},
|
|
||||||
"streams": []any{map[string]any{"name": "MAIL", "events": []any{"mail.**"}, "grant": map[string]any{"config": "readers", "events": "mail.{key}.**"}}}}}
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
cat *fakeCatalog
|
|
||||||
module string
|
|
||||||
fp string
|
|
||||||
tools []string
|
|
||||||
verbs map[string]string
|
|
||||||
subjects []string
|
|
||||||
unread bool
|
|
||||||
}{
|
|
||||||
{name: "a seat's mark stands for every holder, and the holder's own adds up", cat: &fakeCatalog{revision: "7",
|
|
||||||
byFp: map[string]catalogseat.CatalogEntry{"src2:1": v1}, newest: map[string]catalogseat.CatalogEntry{"shell": v1}, defs: login},
|
|
||||||
module: "shell", fp: "src2:1", tools: []string{"wipe"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell"}},
|
|
||||||
{name: "a holder's needs-approval cannot unmark its seat's verb, and marks another", cat: &fakeCatalog{revision: "8",
|
|
||||||
byFp: map[string]catalogseat.CatalogEntry{"src2:2": v2}, newest: map[string]catalogseat.CatalogEntry{"shell": v2}, defs: login},
|
|
||||||
module: "shell", fp: "src2:2", tools: []string{"erase"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell",
|
|
||||||
"node-login-shell.sessions": "entry shell src2:2"}},
|
|
||||||
{name: "across a version change the union stands: a dropped mark is asked while the old bundle runs", cat: &fakeCatalog{revision: "9",
|
|
||||||
byFp: map[string]catalogseat.CatalogEntry{"src2:1": v1, "src2:2": v2}, newest: map[string]catalogseat.CatalogEntry{"shell": v2}, defs: login},
|
|
||||||
module: "shell", fp: "src2:1", tools: []string{"erase", "wipe"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell",
|
|
||||||
"node-login-shell.sessions": "entry shell src2:2"}},
|
|
||||||
{name: "a served entry that cannot be read leaves the newest marks, every marked call refused", cat: &fakeCatalog{revision: "9",
|
|
||||||
newest: map[string]catalogseat.CatalogEntry{"shell": v2}, defs: login},
|
|
||||||
module: "shell", fp: "src2:1", tools: []string{"erase"}, verbs: map[string]string{"node-login-shell.execute": "seat node-login-shell",
|
|
||||||
"node-login-shell.sessions": "entry shell src2:2"}, unread: true},
|
|
||||||
{name: "a bundle with no fingerprint has no served entry", cat: &fakeCatalog{revision: "9", defs: login},
|
|
||||||
module: "shell", unread: true},
|
|
||||||
{name: "a marked event and a stream with a grant give their subjects and each .>", cat: &fakeCatalog{revision: "3",
|
|
||||||
byFp: map[string]catalogseat.CatalogEntry{"src2:m": mail}, newest: map[string]catalogseat.CatalogEntry{"mail": mail}},
|
|
||||||
module: "mail", fp: "src2:m", subjects: []string{"mesh.mod.mail.event.mail.received", "mesh.mod.mail.event.mail.received.>",
|
|
||||||
"mesh.stream.mail.event.mail.>", "mesh.stream.mail.event.mail.received", "mesh.stream.mail.event.mail.received.>"}},
|
|
||||||
} {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
m := gate.Derive(tc.cat, tc.module, tc.fp)
|
|
||||||
if got := keysOf(m.Tools); !reflect.DeepEqual(got, tc.tools) {
|
|
||||||
t.Errorf("tools %v, want %v", got, tc.tools)
|
|
||||||
}
|
|
||||||
if tc.verbs == nil {
|
|
||||||
tc.verbs = map[string]string{}
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(m.Verbs, tc.verbs) {
|
|
||||||
t.Errorf("verbs %v, want %v", m.Verbs, tc.verbs)
|
|
||||||
}
|
|
||||||
if got := keysOf(m.Subjects); !reflect.DeepEqual(got, tc.subjects) {
|
|
||||||
t.Errorf("subjects %v, want %v", got, tc.subjects)
|
|
||||||
}
|
|
||||||
if (m.Unread != "") != tc.unread || m.Revision != tc.cat.revision {
|
|
||||||
t.Errorf("unread %q, revision %q", m.Unread, m.Revision)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// §4: a bundle whose marks name a tool it does not register is not loaded, its finding mark-unserved raised; a bundle that
|
|
||||||
// serves it clears it, and a catalog without the mark too.
|
|
||||||
t.Run("mark-unserved raised and cleared", func(t *testing.T) {
|
|
||||||
cat := &fakeCatalog{revision: "7", byFp: map[string]catalogseat.CatalogEntry{"src2:1": v1}, newest: map[string]catalogseat.CatalogEntry{"shell": v1}, defs: login}
|
|
||||||
w := &findings{}
|
|
||||||
g := gate.New(gate.Deps{Node: "n1", Runner: "node-tools", Catalog: cat, Findings: Findings(w, "n1", "node-tools", nil)})
|
|
||||||
if got := g.Unserved("shell", "src2:1", []string{"other"}); !reflect.DeepEqual(got, []string{"wipe"}) || w.raised[keys.EscapeName("n1.shell")] != gate.KindMarkUnserved {
|
|
||||||
t.Fatalf("unserved %v, findings %v", got, w.raised)
|
|
||||||
}
|
|
||||||
if got := g.Unserved("shell", "src2:1", []string{"wipe"}); got != nil || w.raised[keys.EscapeName("n1.shell")] != "" {
|
|
||||||
t.Fatalf("a bundle serving the mark: unserved %v, findings %v", got, w.raised)
|
|
||||||
}
|
|
||||||
_ = g.Unserved("shell", "src2:1", nil)
|
|
||||||
cat.byFp["src2:1"], cat.newest["shell"] = entry("src2:1", nil, nil), entry("src2:1", nil, nil)
|
|
||||||
if got := g.Unserved("shell", "src2:1", nil); got != nil || w.raised[keys.EscapeName("n1.shell")] != "" {
|
|
||||||
t.Fatalf("a catalog without the mark: unserved %v, findings %v", got, w.raised)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// findings is the runner's held writer as a fixture: each finding raised now, by id.
|
// findings is the runner's held writer as a fixture: each finding raised now, by id.
|
||||||
type findings struct {
|
type findings struct {
|
||||||
raised map[string]string
|
raised map[string]string
|
||||||
|
|||||||
@@ -62,8 +62,28 @@ func (c *Conn) Bindings(module string) []membership.BusBinding {
|
|||||||
// A-16, A-27).
|
// A-16, A-27).
|
||||||
func (c *Conn) JetStream() (jetstream.JetStream, error) { return jetstream.New(c.nc) }
|
func (c *Conn) JetStream() (jetstream.JetStream, error) { return jetstream.New(c.nc) }
|
||||||
|
|
||||||
func (c *Conn) objectStore(ctx context.Context, module, local string) (jetstream.ObjectStore, membership.BusBinding, error) {
|
// objectBucketOf is the bus name of the module's object store of a local name: its binding's when it has one, else, for a
|
||||||
|
// name no binding of any type holds, the store grants creates for a module's old `objects` entry, `<module>_<name>`
|
||||||
|
// (catalogue.ObjectsBucket; design 47 G lead answers A-380): the bus's rights decide whether it is reached. A name bound
|
||||||
|
// with another storage type is refused as the binding refuses it.
|
||||||
|
func (c *Conn) objectBucketOf(module, local string) (membership.BusBinding, error) {
|
||||||
b, err := c.Binding(module, local, catalogue.StorageObjectStore)
|
b, err := c.Binding(module, local, catalogue.StorageObjectStore)
|
||||||
|
if err == nil {
|
||||||
|
return b, nil
|
||||||
|
}
|
||||||
|
if m := c.Membership(module); m != nil {
|
||||||
|
for _, held := range m.Bindings {
|
||||||
|
if held.Local == local {
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return membership.BusBinding{Local: local, Storage: catalogue.StorageObjectStore, ObjectStore: catalogue.ObjectsBucket(module, local)}, nil
|
||||||
|
}
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) objectStore(ctx context.Context, module, local string) (jetstream.ObjectStore, membership.BusBinding, error) {
|
||||||
|
b, err := c.objectBucketOf(module, local)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, b, err
|
return nil, b, err
|
||||||
}
|
}
|
||||||
@@ -73,6 +93,10 @@ func (c *Conn) objectStore(ctx context.Context, module, local string) (jetstream
|
|||||||
}
|
}
|
||||||
obs, err := js.ObjectStore(ctx, b.ObjectStore)
|
obs, err := js.ObjectStore(ctx, b.ObjectStore)
|
||||||
if errors.Is(err, jetstream.ErrBucketNotFound) || errors.Is(err, jetstream.ErrStreamNotFound) {
|
if errors.Is(err, jetstream.ErrBucketNotFound) || errors.Is(err, jetstream.ErrStreamNotFound) {
|
||||||
|
if b.Template == "" {
|
||||||
|
return nil, b, fmt.Errorf("%s was bound no object-store called %q, and the store %s grants creates for an old `objects` entry of that name is not on the bus",
|
||||||
|
module, local, b.ObjectStore)
|
||||||
|
}
|
||||||
return nil, b, fmt.Errorf("%s's objects %q are bound and their store %s is not on the bus", module, local, b.ObjectStore)
|
return nil, b, fmt.Errorf("%s's objects %q are bound and their store %s is not on the bus", module, local, b.ObjectStore)
|
||||||
}
|
}
|
||||||
return obs, b, err
|
return obs, b, err
|
||||||
@@ -172,19 +196,28 @@ func (c *Conn) ObjectsList(module string, r buscalls.ObjectsRequest) (buscalls.O
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ObjectsInfo is how full the module's object store is: its objects, its bytes and its cap.
|
// ObjectsInfo is how full the module's object store is, from the figures the bus keeps for its stream: its bytes, its
|
||||||
|
// messages' live subjects as the count, and its cap. It never lists the store: a store's descriptions, the leftovers
|
||||||
|
// of deleted objects among them, may be many thousands, and a fill read per chunk of a transfer read them all each
|
||||||
|
// time (design 47 H lead answers H-A-227).
|
||||||
func (c *Conn) ObjectsInfo(module string, r buscalls.ObjectsRequest) (buscalls.Fill, error) {
|
func (c *Conn) ObjectsInfo(module string, r buscalls.ObjectsRequest) (buscalls.Fill, error) {
|
||||||
listed, err := c.ObjectsList(module, r)
|
b, err := c.objectBucketOf(module, r.Objects)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return buscalls.Fill{}, err
|
return buscalls.Fill{}, err
|
||||||
}
|
}
|
||||||
b, _ := c.Binding(module, r.Objects, catalogue.StorageObjectStore)
|
info, err := c.streamInfo("OBJ_" + b.ObjectStore)
|
||||||
fill, err := c.streamFill("OBJ_" + b.ObjectStore)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return buscalls.Fill{}, err
|
return buscalls.Fill{}, err
|
||||||
}
|
}
|
||||||
fill.Count = uint64(len(listed.Objects))
|
return objectsFillOf(info), nil
|
||||||
return fill.Fill, nil
|
}
|
||||||
|
|
||||||
|
// objectsFillOf is an object store's fill from its stream's info alone: the bytes the stream keeps, its live subjects
|
||||||
|
// as the count (H-A-227: the stream's live subjects, or none) and its cap.
|
||||||
|
func objectsFillOf(info *jetstream.StreamInfo) buscalls.Fill {
|
||||||
|
fill := streamFillOf(info).Fill
|
||||||
|
fill.Count = uint64(info.State.NumSubjects)
|
||||||
|
return fill
|
||||||
}
|
}
|
||||||
|
|
||||||
// ObjectsWatch hands deliver every object of the module's object store as it is, then each stored or deleted.
|
// ObjectsWatch hands deliver every object of the module's object store as it is, then each stored or deleted.
|
||||||
@@ -237,29 +270,39 @@ func (c *Conn) ObjectsWatch(module string, r buscalls.ObjectsWatchRequest, deliv
|
|||||||
|
|
||||||
// streamFill is a stream's fill and its first and last sequence, by its name on the bus.
|
// streamFill is a stream's fill and its first and last sequence, by its name on the bus.
|
||||||
func (c *Conn) streamFill(name string) (buscalls.StreamFilled, error) {
|
func (c *Conn) streamFill(name string) (buscalls.StreamFilled, error) {
|
||||||
|
info, err := c.streamInfo(name)
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.StreamFilled{}, err
|
||||||
|
}
|
||||||
|
return streamFillOf(info), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// streamInfo is a stream's info as the bus keeps it, by its name on the bus: one request, whatever the stream holds.
|
||||||
|
func (c *Conn) streamInfo(name string) (*jetstream.StreamInfo, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
js, err := c.JetStream()
|
js, err := c.JetStream()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return buscalls.StreamFilled{}, err
|
return nil, err
|
||||||
}
|
}
|
||||||
s, err := js.Stream(ctx, name)
|
s, err := js.Stream(ctx, name)
|
||||||
if errors.Is(err, jetstream.ErrStreamNotFound) {
|
if errors.Is(err, jetstream.ErrStreamNotFound) {
|
||||||
return buscalls.StreamFilled{}, fmt.Errorf("the stream %s is bound and not on the bus", name)
|
return nil, fmt.Errorf("the stream %s is bound and not on the bus", name)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return buscalls.StreamFilled{}, err
|
return nil, err
|
||||||
}
|
|
||||||
info, err := s.Info(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return buscalls.StreamFilled{}, err
|
|
||||||
}
|
}
|
||||||
|
return s.Info(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// streamFillOf is a stream's fill and its first and last sequence from its info.
|
||||||
|
func streamFillOf(info *jetstream.StreamInfo) buscalls.StreamFilled {
|
||||||
max := uint64(0)
|
max := uint64(0)
|
||||||
if info.Config.MaxBytes > 0 {
|
if info.Config.MaxBytes > 0 {
|
||||||
max = uint64(info.Config.MaxBytes)
|
max = uint64(info.Config.MaxBytes)
|
||||||
}
|
}
|
||||||
return buscalls.StreamFilled{Fill: buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: max},
|
return buscalls.StreamFilled{Fill: buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: max},
|
||||||
First: info.State.FirstSeq, Last: info.State.LastSeq}, nil
|
First: info.State.FirstSeq, Last: info.State.LastSeq}
|
||||||
}
|
}
|
||||||
|
|
||||||
// streamBinding is the module's binding of a stream by its local name, a work queue among them.
|
// streamBinding is the module's binding of a stream by its local name, a work queue among them.
|
||||||
@@ -276,6 +319,41 @@ func (c *Conn) StreamFill(module string, r buscalls.StreamRequest) (buscalls.Str
|
|||||||
return c.streamFill(b.Stream)
|
return c.streamFill(b.Stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StreamPublish says one event on the module's own bound stream, by an acknowledged publish on the binding's subject plus
|
||||||
|
// "." plus the event, the id as the message id (design 42 zfs-owns-zfs, A-42). The module's own binding alone: another
|
||||||
|
// module's, and a binding that is not a stream, are refused by Binding.
|
||||||
|
func (c *Conn) StreamPublish(module string, r buscalls.StreamPublishRequest) (buscalls.StreamPublished, error) {
|
||||||
|
b, err := c.streamBinding(module, r.Stream)
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.StreamPublished{}, err
|
||||||
|
}
|
||||||
|
if b.Subject == "" {
|
||||||
|
return buscalls.StreamPublished{}, fmt.Errorf("%s's stream %q has no subject to say an event on", module, r.Stream)
|
||||||
|
}
|
||||||
|
if r.Event == "" || strings.ContainsAny(r.Event, " *>\t\r\n") || strings.HasPrefix(r.Event, ".") || strings.HasSuffix(r.Event, ".") {
|
||||||
|
return buscalls.StreamPublished{}, fmt.Errorf("the event %q is not a name to say on %s's stream %q", r.Event, module, r.Stream)
|
||||||
|
}
|
||||||
|
body := []byte(r.Body)
|
||||||
|
if len(body) == 0 {
|
||||||
|
body = []byte("null")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
js, err := c.JetStream()
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.StreamPublished{}, err
|
||||||
|
}
|
||||||
|
var opts []jetstream.PublishOpt
|
||||||
|
if r.ID != "" {
|
||||||
|
opts = append(opts, jetstream.WithMsgID(r.ID))
|
||||||
|
}
|
||||||
|
ack, err := js.Publish(ctx, b.Subject+"."+r.Event, body, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.StreamPublished{}, fmt.Errorf("the event %s was not acknowledged on %s's stream %q: %w", r.Event, module, r.Stream, err)
|
||||||
|
}
|
||||||
|
return buscalls.StreamPublished{Sequence: ack.Sequence}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// StreamReadMost is the most messages one read answers.
|
// StreamReadMost is the most messages one read answers.
|
||||||
const StreamReadMost = 1000
|
const StreamReadMost = 1000
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package bus_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -32,6 +33,9 @@ func TestABundleReachesItsOwnBoundObjectsAndStreamsOnly(t *testing.T) {
|
|||||||
if _, err := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "m_files"}); err != nil {
|
if _, err := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "m_files"}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
if _, err := js.CreateObjectStore(ctx, jetstream.ObjectStoreConfig{Bucket: "m_old"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "m_events", Subjects: []string{"mesh.state.m.events.>"}}); err != nil {
|
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "m_events", Subjects: []string{"mesh.state.m.events.>"}}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -91,6 +95,18 @@ func TestABundleReachesItsOwnBoundObjectsAndStreamsOnly(t *testing.T) {
|
|||||||
if listed, err := conn.ObjectsList("m", buscalls.ObjectsRequest{Objects: "files"}); err != nil || len(listed.Objects) != 1 {
|
if listed, err := conn.ObjectsList("m", buscalls.ObjectsRequest{Objects: "files"}); err != nil || len(listed.Objects) != 1 {
|
||||||
t.Fatalf("listed %+v, %v", listed, err)
|
t.Fatalf("listed %+v, %v", listed, err)
|
||||||
}
|
}
|
||||||
|
// H-A-227: the fill is the stream's own figures, its live subjects as the count (a's chunk and description, big's
|
||||||
|
// description left by its delete), never the count of its listed objects.
|
||||||
|
if fill, err := conn.ObjectsInfo("m", buscalls.ObjectsRequest{Objects: "files"}); err != nil || fill.Count != 3 || fill.Bytes == 0 {
|
||||||
|
t.Fatalf("objects fill %+v, %v", fill, err)
|
||||||
|
}
|
||||||
|
// A-380: an old `objects` entry is reached by the store grants creates for it, `<module>_<name>`, with no binding of that name.
|
||||||
|
if _, err := conn.ObjectsPut("m", buscalls.ObjectsPutRequest{Objects: "old", Name: "r", Data: []byte("old section")}); err != nil {
|
||||||
|
t.Fatalf("put into the old objects section: %v", err)
|
||||||
|
}
|
||||||
|
if listed, err := conn.ObjectsList("m", buscalls.ObjectsRequest{Objects: "old"}); err != nil || len(listed.Objects) != 1 {
|
||||||
|
t.Fatalf("listed the old objects section %+v, %v", listed, err)
|
||||||
|
}
|
||||||
page, err := conn.StreamRead("m", buscalls.StreamReadRequest{Stream: "events", Limit: 1})
|
page, err := conn.StreamRead("m", buscalls.StreamReadRequest{Stream: "events", Limit: 1})
|
||||||
if err != nil || len(page.Messages) != 1 || page.Next != 2 || page.Last != 2 {
|
if err != nil || len(page.Messages) != 1 || page.Next != 2 || page.Last != 2 {
|
||||||
t.Fatalf("read %+v, %v", page, err)
|
t.Fatalf("read %+v, %v", page, err)
|
||||||
@@ -99,11 +115,28 @@ func TestABundleReachesItsOwnBoundObjectsAndStreamsOnly(t *testing.T) {
|
|||||||
t.Fatalf("fill %+v, %v", fill, err)
|
t.Fatalf("fill %+v, %v", fill, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A-42: an event said on the module's own stream lands on the binding's subject plus the event, acknowledged, and a
|
||||||
|
// second say with the same id is the same message.
|
||||||
|
said, err := conn.StreamPublish("m", buscalls.StreamPublishRequest{Stream: "events", Event: "scrub.requested",
|
||||||
|
Body: json.RawMessage(`{"pool":"tank"}`), ID: "id-1"})
|
||||||
|
if err != nil || said.Sequence != 3 {
|
||||||
|
t.Fatalf("said %+v, %v", said, err)
|
||||||
|
}
|
||||||
|
if again, err := conn.StreamPublish("m", buscalls.StreamPublishRequest{Stream: "events", Event: "scrub.requested",
|
||||||
|
Body: json.RawMessage(`{"pool":"tank"}`), ID: "id-1"}); err != nil || again.Sequence != 3 {
|
||||||
|
t.Fatalf("said again %+v, %v", again, err)
|
||||||
|
}
|
||||||
|
if page, err := conn.StreamRead("m", buscalls.StreamReadRequest{Stream: "events", From: 3,
|
||||||
|
Subjects: "mesh.state.m.events.scrub.requested"}); err != nil || len(page.Messages) != 1 ||
|
||||||
|
string(page.Messages[0].Body) != `{"pool":"tank"}` {
|
||||||
|
t.Fatalf("read back %+v, %v", page, err)
|
||||||
|
}
|
||||||
|
|
||||||
for _, c := range []struct {
|
for _, c := range []struct {
|
||||||
name, module, refusal string
|
name, module, refusal string
|
||||||
call func(module string) error
|
call func(module string) error
|
||||||
}{
|
}{
|
||||||
{"a local name not bound", "m", `bound no object-store called "photos"`, func(module string) error {
|
{"a local name not bound", "m", `bound no object-store called "photos", and the store m_photos grants creates`, func(module string) error {
|
||||||
_, err := conn.ObjectsGet(module, buscalls.ObjectsNameRequest{Objects: "photos", Name: "a"})
|
_, err := conn.ObjectsGet(module, buscalls.ObjectsNameRequest{Objects: "photos", Name: "a"})
|
||||||
return err
|
return err
|
||||||
}},
|
}},
|
||||||
@@ -115,6 +148,14 @@ func TestABundleReachesItsOwnBoundObjectsAndStreamsOnly(t *testing.T) {
|
|||||||
_, err := conn.ObjectsList(module, buscalls.ObjectsRequest{Objects: "events"})
|
_, err := conn.ObjectsList(module, buscalls.ObjectsRequest{Objects: "events"})
|
||||||
return err
|
return err
|
||||||
}},
|
}},
|
||||||
|
{"say on another module's stream", "other", `other was bound no stream called "events"`, func(module string) error {
|
||||||
|
_, err := conn.StreamPublish(module, buscalls.StreamPublishRequest{Stream: "events", Event: "x"})
|
||||||
|
return err
|
||||||
|
}},
|
||||||
|
{"say on a binding that is not a stream", "m", `"files" is bound with the storage type object-store, not stream`, func(module string) error {
|
||||||
|
_, err := conn.StreamPublish(module, buscalls.StreamPublishRequest{Stream: "files", Event: "x"})
|
||||||
|
return err
|
||||||
|
}},
|
||||||
{"a work queue not bound", "m", `bound no stream called "jobs"`, func(module string) error {
|
{"a work queue not bound", "m", `bound no stream called "jobs"`, func(module string) error {
|
||||||
_, err := conn.WorkQueueSize(module, buscalls.WorkQueueRequest{Queue: "jobs"})
|
_, err := conn.WorkQueueSize(module, buscalls.WorkQueueRequest{Queue: "jobs"})
|
||||||
return err
|
return err
|
||||||
|
|||||||
+269
-45
@@ -7,6 +7,8 @@
|
|||||||
// mesh.seat.<seat>.tool.<verb> a role's verb, answered by whoever holds the seat
|
// mesh.seat.<seat>.tool.<verb> a role's verb, answered by whoever holds the seat
|
||||||
// mesh.mod.<module>.call.<tool>.<caller>, mesh.seat.<seat>.call.<verb>.<caller>
|
// mesh.mod.<module>.call.<tool>.<caller>, mesh.seat.<seat>.call.<verb>.<caller>
|
||||||
// the same, naming the bus user that called (caller.go, hq issue 365)
|
// the same, naming the bus user that called (caller.go, hq issue 365)
|
||||||
|
//
|
||||||
|
// Design 47 H1, proof 2: the SDK and its importer delivered in one merge call, 2026-11-21.
|
||||||
package bus
|
package bus
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -18,6 +20,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
"log"
|
"log"
|
||||||
"regexp"
|
"regexp"
|
||||||
@@ -32,9 +35,18 @@ import (
|
|||||||
"github.com/novox/mesh-tools/node-tools/internal/wire"
|
"github.com/novox/mesh-tools/node-tools/internal/wire"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RequestTimeout is how long a call waits for its answer — what modules already expect.
|
// RequestTimeout is how long a call waits for its answer when its verb's definition names no `timeout`: the tool runner's own
|
||||||
|
// bound, what modules already expect (design 47 H §760, H-A-43).
|
||||||
const RequestTimeout = 30 * time.Second
|
const RequestTimeout = 30 * time.Second
|
||||||
|
|
||||||
|
// waitOf is the bound a call waits: within where the verb's definition names one, else the tool runner's own.
|
||||||
|
func waitOf(within time.Duration) time.Duration {
|
||||||
|
if within > 0 {
|
||||||
|
return within
|
||||||
|
}
|
||||||
|
return RequestTimeout
|
||||||
|
}
|
||||||
|
|
||||||
// Credential is a broker credential as the mesh delivers it (novox/hq ADR 0120).
|
// Credential is a broker credential as the mesh delivers it (novox/hq ADR 0120).
|
||||||
type Credential struct {
|
type Credential struct {
|
||||||
URL string `json:"url"`
|
URL string `json:"url"`
|
||||||
@@ -179,12 +191,23 @@ type Conn struct {
|
|||||||
cred Credential
|
cred Credential
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
issued map[string]*Membership // module → membership; present with nil = followed, none issued
|
issued map[string]*Membership // module → membership; present with nil = followed, none issued
|
||||||
onNew []*func(Membership)
|
// withdrawn are the modules whose membership the grants part deleted: no longer assigned on this node (design 47 H2,
|
||||||
subs []*nats.Subscription
|
// H-A-472 ninth addendum); their twins are removed and not made again, until a membership is issued again.
|
||||||
Logf func(format string, args ...any)
|
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
|
// answering is every subject this runtime answers on, so a subscription the bus refused can be
|
||||||
// asked for again (novox/hq issue 222).
|
// asked for again (novox/hq issue 222).
|
||||||
answering map[string]*answered
|
answering map[string]*answered
|
||||||
|
// proofs are the subscriptions that answer a seat's proofs (SeatAnswer), so the stop takes them down with the rest.
|
||||||
|
proofs map[*nats.Subscription]bool
|
||||||
|
// answersDown is set once the runner took down every subscription it answers calls on at its stop (StopAnswering):
|
||||||
|
// from then on it subscribes none again, so every later call meets no responders here (design 47 H2 H-A-570 (1)).
|
||||||
|
answersDown bool
|
||||||
|
// subscribedHook, when a test set it (SetSubscribedHook), is called between making an answering subscription and keeping
|
||||||
|
// it, so a test runs the stop in between (tests only).
|
||||||
|
subscribedHook func(subject string)
|
||||||
// RetryAfter is how long after a refusal a subscription is asked for again, by attempt; past the
|
// RetryAfter is how long after a refusal a subscription is asked for again, by attempt; past the
|
||||||
// last, it is given up and said. A variable so a test need not wait minutes.
|
// last, it is given up and said. A variable so a test need not wait minutes.
|
||||||
RetryAfter []time.Duration
|
RetryAfter []time.Duration
|
||||||
@@ -194,6 +217,15 @@ type Conn struct {
|
|||||||
waits map[string]map[chan string]bool
|
waits map[string]map[chan string]bool
|
||||||
// inboxSaid is when a refused answer publish was last said, by subject (answerRefused).
|
// inboxSaid is when a refused answer publish was last said, by subject (answerRefused).
|
||||||
inboxSaid map[string]time.Time
|
inboxSaid map[string]time.Time
|
||||||
|
// bound is each state's binding, kept for the process and bound again only when the bus says its bucket is gone
|
||||||
|
// (state.go, design 47 H lead answers H-A-251): one Conn is one account's connection, so a binding is per account
|
||||||
|
// and bucket.
|
||||||
|
bindMu sync.Mutex
|
||||||
|
bound map[string]*binding
|
||||||
|
// bind binds one bucket: jetstream's KeyValue (a stream-info request on the bus) unless a test replaces it.
|
||||||
|
bind func(ctx context.Context, bucket string) (jetstream.KeyValue, error)
|
||||||
|
// pulls are the workers bound and the messages pulled on this connection (seat_pull.go).
|
||||||
|
pulls pulls
|
||||||
}
|
}
|
||||||
|
|
||||||
// answered is one subject the runtime answers on: what to subscribe again with, and how often it was
|
// answered is one subject the runtime answers on: what to subscribe again with, and how often it was
|
||||||
@@ -268,7 +300,7 @@ func (c *Conn) refused(err error) {
|
|||||||
time.AfterFunc(wait, func() {
|
time.AfterFunc(wait, func() {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.Unlock()
|
||||||
if a.stopped {
|
if a.stopped || c.answersDown {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if a.sub != nil {
|
if a.sub != nil {
|
||||||
@@ -390,6 +422,7 @@ var (
|
|||||||
func (c *Conn) issue(module string, m Membership) {
|
func (c *Conn) issue(module string, m Membership) {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
c.issued[module] = &m
|
c.issued[module] = &m
|
||||||
|
delete(c.withdrawn, module)
|
||||||
handlers := make([]func(Membership), 0, len(c.onNew))
|
handlers := make([]func(Membership), 0, len(c.onNew))
|
||||||
for _, h := range c.onNew {
|
for _, h := range c.onNew {
|
||||||
handlers = append(handlers, *h)
|
handlers = append(handlers, *h)
|
||||||
@@ -407,29 +440,33 @@ func (c *Conn) issue(module string, m Membership) {
|
|||||||
// right after its boot, a timeout), is said once and read again, with a growing wait, until it can be or the
|
// right after its boot, a timeout), is said once and read again, with a growing wait, until it can be or the
|
||||||
// connection closes: Follow runs once per module, so nothing else would ever read it again.
|
// connection closes: Follow runs once per module, so nothing else would ever read it again.
|
||||||
func (c *Conn) followGrants(module string) {
|
func (c *Conn) followGrants(module string) {
|
||||||
if c.watchGrants(module, true) {
|
// Read here, not in the loop: the loop outlives Follow, and a test sets them back as it ends (design 47 H, H-A-363).
|
||||||
|
patience, timeout := GrantsPatience, StateTimeout
|
||||||
|
if c.watchGrants(module, true, patience, timeout) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
wait, most := GrantsRetry, GrantsRetryMost
|
||||||
go func() {
|
go func() {
|
||||||
wait := GrantsRetry
|
|
||||||
for !c.nc.IsClosed() {
|
for !c.nc.IsClosed() {
|
||||||
time.Sleep(wait)
|
time.Sleep(wait)
|
||||||
if c.nc.IsClosed() {
|
if c.nc.IsClosed() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if c.watchGrants(module, false) {
|
if c.watchGrants(module, false, patience, timeout) {
|
||||||
c.Logf("[mesh-tools] the grants part's memberships are read again; %s on %s follows its key", module, c.node)
|
c.Logf("[mesh-tools] the grants part's memberships are read again; %s on %s follows its key", module, c.node)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if wait *= 2; wait > GrantsRetryMost {
|
if wait *= 2; wait > most {
|
||||||
wait = GrantsRetryMost
|
wait = most
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// watchGrants is one attempt of followGrants: true once the key is watched. A failure is said when say is true.
|
// watchGrants is one attempt of followGrants: true once the key is watched. A failure is said when say is true. Its
|
||||||
func (c *Conn) watchGrants(module string, say bool) bool {
|
// bounds, patience for the key's direct get and timeout for the bucket and its current value, are GrantsPatience and
|
||||||
|
// StateTimeout as they stood when followGrants began.
|
||||||
|
func (c *Conn) watchGrants(module string, say bool, patience, timeout time.Duration) bool {
|
||||||
logf := func(format string, a ...any) {
|
logf := func(format string, a ...any) {
|
||||||
if say {
|
if say {
|
||||||
c.Logf(format, a...)
|
c.Logf(format, a...)
|
||||||
@@ -439,7 +476,7 @@ func (c *Conn) watchGrants(module string, say bool) bool {
|
|||||||
// First the key's direct get, which the account is granted alone: a bus that refuses it, or a state not there yet,
|
// First the key's direct get, which the account is granted alone: a bus that refuses it, or a state not there yet,
|
||||||
// answers at once, where binding the bucket would wait out its bound on a refusal.
|
// answers at once, where binding the bucket would wait out its bound on a refusal.
|
||||||
bucket := membership.GrantsBucket
|
bucket := membership.GrantsBucket
|
||||||
probe, err := c.nc.Request("$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+"."+key, nil, GrantsPatience)
|
probe, err := c.nc.Request("$JS.API.DIRECT.GET.KV_"+bucket+".$KV."+bucket+"."+key, nil, patience)
|
||||||
if err != nil || probe.Header.Get("Status") == "503" {
|
if err != nil || probe.Header.Get("Status") == "503" {
|
||||||
why := "it did not answer"
|
why := "it did not answer"
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -453,7 +490,7 @@ func (c *Conn) watchGrants(module string, say bool) bool {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := js.KeyValue(ctx, bucket)
|
kv, err := js.KeyValue(ctx, bucket)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -469,7 +506,9 @@ func (c *Conn) watchGrants(module string, say bool) bool {
|
|||||||
}
|
}
|
||||||
apply := func(e jetstream.KeyValueEntry) {
|
apply := func(e jetstream.KeyValueEntry) {
|
||||||
if e.Operation() != jetstream.KeyValuePut {
|
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
|
// 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
|
// membership and a wrapper the part wrote before of one published or unchanged, and refuses a held-back one's
|
||||||
@@ -486,7 +525,7 @@ func (c *Conn) watchGrants(module string, say bool) bool {
|
|||||||
}
|
}
|
||||||
c.issue(module, m)
|
c.issue(module, m)
|
||||||
}
|
}
|
||||||
timer := time.NewTimer(StateTimeout)
|
timer := time.NewTimer(timeout)
|
||||||
defer timer.Stop()
|
defer timer.Stop()
|
||||||
for current := true; current; {
|
for current := true; current; {
|
||||||
select {
|
select {
|
||||||
@@ -502,7 +541,7 @@ func (c *Conn) watchGrants(module string, say bool) bool {
|
|||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
_ = w.Stop()
|
_ = w.Stop()
|
||||||
logf("[mesh-tools] %s's key %s of the grants part's memberships did not answer in %s; %s has no membership "+
|
logf("[mesh-tools] %s's key %s of the grants part's memberships did not answer in %s; %s has no membership "+
|
||||||
"until it can be", module, key, StateTimeout, module)
|
"until it can be", module, key, timeout, module)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -516,6 +555,60 @@ func (c *Conn) watchGrants(module string, say bool) bool {
|
|||||||
return true
|
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.
|
// Membership is what the mesh issued a module here, or nil when nothing has been issued.
|
||||||
func (c *Conn) Membership(module string) *Membership {
|
func (c *Conn) Membership(module string) *Membership {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -608,7 +701,7 @@ type reply struct {
|
|||||||
|
|
||||||
// answerOn answers one subject with one handler, and says which machine answered (ADR 0159).
|
// answerOn answers one subject with one handler, and says which machine answered (ADR 0159).
|
||||||
func (c *Conn) answerOn(subject, queue string, h Handler) (func(), error) {
|
func (c *Conn) answerOn(subject, queue string, h Handler) (func(), error) {
|
||||||
return c.answerCalledOn(subject, queue, func(_ string, body json.RawMessage) (any, error) { return h(body) })
|
return c.answerCalledOn(subject, queue, func(_, _ string, body json.RawMessage) (any, error) { return h(body) })
|
||||||
}
|
}
|
||||||
|
|
||||||
// answerCalledOn answers one subject, handing the handler the caller the subject a call arrived on names:
|
// answerCalledOn answers one subject, handing the handler the caller the subject a call arrived on names:
|
||||||
@@ -618,7 +711,17 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e
|
|||||||
cb := func(msg *nats.Msg) {
|
cb := func(msg *nats.Msg) {
|
||||||
go func() {
|
go func() {
|
||||||
var r reply
|
var r reply
|
||||||
result, err := h(callerOn(subject, msg.Subject), json.RawMessage(msg.Data))
|
ask := ""
|
||||||
|
if msg.Header != nil {
|
||||||
|
ask = msg.Header.Get(stdio.AskHeader)
|
||||||
|
}
|
||||||
|
result, err := h(callerOn(subject, msg.Subject), ask, json.RawMessage(msg.Data))
|
||||||
|
// A call the runner's drain cut at its stop is answered nothing: its caller sees a transport fault (design 47 H2
|
||||||
|
// §813 (12)).
|
||||||
|
var unanswered interface{ Unanswered() bool }
|
||||||
|
if errors.As(err, &unanswered) && unanswered.Unanswered() {
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
r.Error = err.Error()
|
r.Error = err.Error()
|
||||||
} else {
|
} else {
|
||||||
@@ -633,6 +736,9 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
if err := c.answersAreDown(subject); err != nil {
|
||||||
|
return func() {}, err
|
||||||
|
}
|
||||||
var sub *nats.Subscription
|
var sub *nats.Subscription
|
||||||
var err error
|
var err error
|
||||||
if queue != "" {
|
if queue != "" {
|
||||||
@@ -643,11 +749,13 @@ func (c *Conn) answerCalledOn(subject, queue string, h CalledHandler) (func(), e
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return func() {}, err
|
return func() {}, err
|
||||||
}
|
}
|
||||||
c.track(sub)
|
c.subscribed(subject)
|
||||||
a := &answered{subject: subject, queue: queue, cb: cb, sub: sub}
|
a := &answered{subject: subject, queue: queue, cb: cb, sub: sub}
|
||||||
c.mu.Lock()
|
// Kept, or taken down, under the one lock the stop takes its subscriptions down under, so a serve racing the stop is
|
||||||
c.answering[answeringKey(subject, queue)] = a
|
// never missed by it (design 47 H2 H-A-570 (1)).
|
||||||
c.mu.Unlock()
|
if err := c.keepAnswering(sub, func() { c.answering[answeringKey(subject, queue)] = a }); err != nil {
|
||||||
|
return func() {}, err
|
||||||
|
}
|
||||||
return func() {
|
return func() {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
a.stopped = true
|
a.stopped = true
|
||||||
@@ -671,7 +779,7 @@ func nullable(v any) any {
|
|||||||
|
|
||||||
// HandleSubject answers a subject outright: a seat's verb where the mesh issued it.
|
// HandleSubject answers a subject outright: a seat's verb where the mesh issued it.
|
||||||
func (c *Conn) HandleSubject(subject string, h Handler) (func(), error) {
|
func (c *Conn) HandleSubject(subject string, h Handler) (func(), error) {
|
||||||
return c.HandleSubjectCalled(subject, func(_ string, body json.RawMessage) (any, error) { return h(body) })
|
return c.HandleSubjectCalled(subject, func(_, _ string, body json.RawMessage) (any, error) { return h(body) })
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleSubjectCalled answers a tool subject and its caller-named counterpart (novox/hq issue 365): a call on
|
// HandleSubjectCalled answers a tool subject and its caller-named counterpart (novox/hq issue 365): a call on
|
||||||
@@ -682,6 +790,12 @@ func (c *Conn) HandleSubjectCalled(subject string, h CalledHandler) (func(), err
|
|||||||
return c.answerBoth(subject, "", h)
|
return c.answerBoth(subject, "", h)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// HandleSubjectCalledQueue is HandleSubjectCalled in one queue group: of every holder that serves the subject in the
|
||||||
|
// group, one answers (lead answer A-393: a node-scoped seat's verb asked with no machine).
|
||||||
|
func (c *Conn) HandleSubjectCalledQueue(subject, queue string, h CalledHandler) (func(), error) {
|
||||||
|
return c.answerBoth(subject, queue, h)
|
||||||
|
}
|
||||||
|
|
||||||
// answerBoth answers a subject and, when it is a tool's, the caller-named pattern beside it, in one queue.
|
// answerBoth answers a subject and, when it is a tool's, the caller-named pattern beside it, in one queue.
|
||||||
func (c *Conn) answerBoth(subject, queue string, h CalledHandler) (func(), error) {
|
func (c *Conn) answerBoth(subject, queue string, h CalledHandler) (func(), error) {
|
||||||
stop, err := c.answerCalledOn(subject, queue, h)
|
stop, err := c.answerCalledOn(subject, queue, h)
|
||||||
@@ -703,7 +817,7 @@ func (c *Conn) answerBoth(subject, queue string, h CalledHandler) (func(), error
|
|||||||
// Handle serves `<module>.<tool>` where the mesh issued that module, and follows its membership:
|
// Handle serves `<module>.<tool>` where the mesh issued that module, and follows its membership:
|
||||||
// when a new one arrives, it serves where it now says and stops where it no longer does.
|
// when a new one arrives, it serves where it now says and stops where it no longer does.
|
||||||
func (c *Conn) Handle(key string, h Handler) (func(), error) {
|
func (c *Conn) Handle(key string, h Handler) (func(), error) {
|
||||||
return c.HandleCalled(key, func(_ string, body json.RawMessage) (any, error) { return h(body) })
|
return c.HandleCalled(key, func(_, _ string, body json.RawMessage) (any, error) { return h(body) })
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleCalled is Handle telling the handler who called: the bus user a caller-named subject names, or "" for
|
// HandleCalled is Handle telling the handler who called: the bus user a caller-named subject names, or "" for
|
||||||
@@ -725,25 +839,35 @@ func (c *Conn) HandleCalled(key string, h CalledHandler) (func(), error) {
|
|||||||
"those of the modules it follows", c.self, key)
|
"those of the modules it follows", c.self, key)
|
||||||
}
|
}
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
var stops []func()
|
stops := map[Served]func(){}
|
||||||
stopped := false
|
stopped := false
|
||||||
|
// **Make before break** (novox/hq design 47 H, H-A-158): a membership issued again keeps every subscription
|
||||||
|
// whose subject and queue it still names, subscribes those it newly names, and only then stops those it no
|
||||||
|
// longer names — a call the bus routes while the membership is followed is never dropped in silence.
|
||||||
serve := func() {
|
serve := func() {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
if stopped {
|
if stopped {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
for _, s := range stops {
|
named := map[Served]bool{}
|
||||||
s()
|
|
||||||
}
|
|
||||||
stops = nil
|
|
||||||
for _, s := range c.servedOn(module, tool) {
|
for _, s := range c.servedOn(module, tool) {
|
||||||
|
named[s] = true
|
||||||
|
if _, kept := stops[s]; kept {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if stop, err := c.answerBoth(s.Subject, s.Queue, h); err == nil {
|
if stop, err := c.answerBoth(s.Subject, s.Queue, h); err == nil {
|
||||||
stops = append(stops, stop)
|
stops[s] = stop
|
||||||
} else {
|
} else {
|
||||||
c.Logf("[mesh-tools] cannot serve %s on %s: %v", key, s.Subject, err)
|
c.Logf("[mesh-tools] cannot serve %s on %s: %v", key, s.Subject, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
for s, stop := range stops {
|
||||||
|
if !named[s] {
|
||||||
|
stop()
|
||||||
|
delete(stops, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
serve()
|
serve()
|
||||||
// Its stop drops the membership handler too: a handler left behind would bind the stopped tool again
|
// Its stop drops the membership handler too: a handler left behind would bind the stopped tool again
|
||||||
@@ -758,10 +882,10 @@ func (c *Conn) HandleCalled(key string, h CalledHandler) (func(), error) {
|
|||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
stopped = true
|
stopped = true
|
||||||
for _, s := range stops {
|
for s, stop := range stops {
|
||||||
s()
|
stop()
|
||||||
|
delete(stops, s)
|
||||||
}
|
}
|
||||||
stops = nil
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -787,6 +911,12 @@ func (c *Conn) reachedAt(key string) (string, error) {
|
|||||||
// Ask calls a tool by key — or on a subject the mesh listed for it — and learns which machine
|
// Ask calls a tool by key — or on a subject the mesh listed for it — and learns which machine
|
||||||
// answered. Core request/reply: a tool call is never persisted (design 25 §3).
|
// answered. Core request/reply: a tool call is never persisted (design 25 §3).
|
||||||
func (c *Conn) Ask(key string, body any, on string) (Answered, error) {
|
func (c *Conn) Ask(key string, body any, on string) (Answered, error) {
|
||||||
|
return c.AskWithin(key, body, on, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AskWithin is Ask that waits within for its answer, the `timeout` its verb's definition names (design 47 H §760, H-A-43);
|
||||||
|
// zero waits the tool runner's own bound, RequestTimeout.
|
||||||
|
func (c *Conn) AskWithin(key string, body any, on string, within time.Duration) (Answered, error) {
|
||||||
subject := on
|
subject := on
|
||||||
if subject == "" {
|
if subject == "" {
|
||||||
s, err := c.reachedAt(key)
|
s, err := c.reachedAt(key)
|
||||||
@@ -803,12 +933,12 @@ func (c *Conn) Ask(key string, body any, on string) (Answered, error) {
|
|||||||
// account publish with its own name alone; asked again on the subject that names no caller only when the
|
// account publish with its own name alone; asked again on the subject that names no caller only when the
|
||||||
// first reached nobody — nothing serves it yet, or the bus does not grant it yet — so no call is done twice.
|
// first reached nobody — nothing serves it yet, or the bus does not grant it yet — so no call is done twice.
|
||||||
if called := CalledSubject(subject, c.cred.User); called != "" {
|
if called := CalledSubject(subject, c.cred.User); called != "" {
|
||||||
answered, fallBack, err := c.askCalled(called, data)
|
answered, fallBack, err := c.askCalled(called, data, within)
|
||||||
if !fallBack {
|
if !fallBack {
|
||||||
return answered, err
|
return answered, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return c.askOnce(subject, data)
|
return c.askOnce(subject, data, within)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrNoResponders is the bus's own refusal: nothing subscribes to the subject asked. It is told apart
|
// ErrNoResponders is the bus's own refusal: nothing subscribes to the subject asked. It is told apart
|
||||||
@@ -816,8 +946,8 @@ func (c *Conn) Ask(key string, body any, on string) (Answered, error) {
|
|||||||
var ErrNoResponders = errors.New("503 no responders")
|
var ErrNoResponders = errors.New("503 no responders")
|
||||||
|
|
||||||
// askOnce asks once.
|
// askOnce asks once.
|
||||||
func (c *Conn) askOnce(subject string, data []byte) (Answered, error) {
|
func (c *Conn) askOnce(subject string, data []byte, within time.Duration) (Answered, error) {
|
||||||
msg, err := c.nc.Request(subject, data, RequestTimeout)
|
msg, err := c.nc.Request(subject, data, waitOf(within))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, nats.ErrNoResponders) {
|
if errors.Is(err, nats.ErrNoResponders) {
|
||||||
return Answered{}, ErrNoResponders
|
return Answered{}, ErrNoResponders
|
||||||
@@ -849,6 +979,12 @@ func answerOf(data []byte) (Answered, error) {
|
|||||||
// PublishAs emits an event as a module: published into JetStream and awaited, de-duplicated by its
|
// PublishAs emits an event as a module: published into JetStream and awaited, de-duplicated by its
|
||||||
// own id (ADR 0042). The body is the payload; the metadata rides as headers.
|
// own id (ADR 0042). The body is the payload; the metadata rides as headers.
|
||||||
func (c *Conn) PublishAs(module string, env Envelope) error {
|
func (c *Conn) PublishAs(module string, env Envelope) error {
|
||||||
|
_, err := c.PublishAsAcked(module, env)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublishAsAcked is PublishAs that also answers the sequence the bus acknowledged the event at.
|
||||||
|
func (c *Conn) PublishAsAcked(module string, env Envelope) (uint64, error) {
|
||||||
// On the module's own stream when its membership names one carrying the event (ADR 0363 §2), on EVENTS
|
// On the module's own stream when its membership names one carrying the event (ADR 0363 §2), on EVENTS
|
||||||
// otherwise — and only there, as before, for a membership that names no stream.
|
// otherwise — and only there, as before, for a membership that names no stream.
|
||||||
msg := nats.NewMsg(eventSubject(c.Membership(module), module, env.Key))
|
msg := nats.NewMsg(eventSubject(c.Membership(module), module, env.Key))
|
||||||
@@ -870,8 +1006,11 @@ func (c *Conn) PublishAs(module string, env Envelope) error {
|
|||||||
if id := env.Headers["x-event-id"]; id != "" {
|
if id := env.Headers["x-event-id"]; id != "" {
|
||||||
opts = append(opts, nats.MsgId(id))
|
opts = append(opts, nats.MsgId(id))
|
||||||
}
|
}
|
||||||
_, err := c.js.PublishMsg(msg, opts...)
|
ack, err := c.js.PublishMsg(msg, opts...)
|
||||||
return err
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return ack.Sequence, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Say publishes one message on core NATS, kept by nobody: a heartbeat, whose loss is the next one.
|
// Say publishes one message on core NATS, kept by nobody: a heartbeat, whose loss is the next one.
|
||||||
@@ -966,6 +1105,75 @@ func (c *Conn) MaxPayload() int64 { return c.nc.MaxPayload() }
|
|||||||
// when this returns.
|
// when this returns.
|
||||||
func (c *Conn) Flush() { _ = c.nc.Flush() }
|
func (c *Conn) Flush() { _ = c.nc.Flush() }
|
||||||
|
|
||||||
|
// StopAnswering is the runner's first act once told to stop, before it finishes the calls in flight (design 47 H2 H-A-570
|
||||||
|
// (1)): it unsubscribes from every subject it answers calls on, a tool's, a seat verb's and a seat proof's, by the bus's
|
||||||
|
// own drain of each subscription, and subscribes none again, so a call made from now on meets no responders at once
|
||||||
|
// wherever no other tool runner serves it, until the new runner subscribes. A call already taken is answered as before:
|
||||||
|
// a reply needs no subscription. It returns once the bus holds the unsubscriptions.
|
||||||
|
func (c *Conn) StopAnswering() {
|
||||||
|
c.mu.Lock()
|
||||||
|
c.answersDown = true
|
||||||
|
var subs []*nats.Subscription
|
||||||
|
for _, a := range c.answering {
|
||||||
|
a.stopped = true
|
||||||
|
if a.sub != nil {
|
||||||
|
subs = append(subs, a.sub)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for s := range c.proofs {
|
||||||
|
subs = append(subs, s)
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
for _, s := range subs {
|
||||||
|
if err := s.Drain(); err != nil && !errors.Is(err, nats.ErrBadSubscription) {
|
||||||
|
c.Logf("[mesh-tools] at its stop the tool runner could not take down its subscription to %s: %v", s.Subject, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = c.nc.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// answersAreDown refuses a new subscription that would answer calls once the runner took its subscriptions down at its stop
|
||||||
|
// (StopAnswering, design 47 H2 H-A-570 (1)).
|
||||||
|
func (c *Conn) answersAreDown(subject string) error {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if c.answersDown {
|
||||||
|
return answersDownError(subject)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func answersDownError(subject string) error {
|
||||||
|
return fmt.Errorf("%s is not served: at its stop the tool runner took down every subscription it answers calls on", subject)
|
||||||
|
}
|
||||||
|
|
||||||
|
// keepAnswering keeps a subscription just made that answers calls, with keep registering it, in one section under c.mu,
|
||||||
|
// the lock StopAnswering takes its subscriptions down under: when the stop began meanwhile, it drains the subscription
|
||||||
|
// instead and refuses it, so none outlives the stop (design 47 H2 H-A-570 (1)).
|
||||||
|
func (c *Conn) keepAnswering(sub *nats.Subscription, keep func()) error {
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.answersDown {
|
||||||
|
c.mu.Unlock()
|
||||||
|
_ = sub.Drain()
|
||||||
|
return answersDownError(sub.Subject)
|
||||||
|
}
|
||||||
|
c.subs = append(c.subs, sub)
|
||||||
|
keep()
|
||||||
|
c.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// subscribed calls the connection's subscribedHook, when a test set one, between making an answering subscription and
|
||||||
|
// keeping it.
|
||||||
|
func (c *Conn) subscribed(subject string) {
|
||||||
|
c.mu.Lock()
|
||||||
|
hook := c.subscribedHook
|
||||||
|
c.mu.Unlock()
|
||||||
|
if hook != nil {
|
||||||
|
hook(subject)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Close unsubscribes everything and drains, so an in-flight reply is finished rather than dropped.
|
// Close unsubscribes everything and drains, so an in-flight reply is finished rather than dropped.
|
||||||
func (c *Conn) Close() {
|
func (c *Conn) Close() {
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
@@ -1021,6 +1229,11 @@ func SeatToolSubject(seat, verb, scope, node string) string {
|
|||||||
// `<module>.<tool>` another's, `seat:<seat>.<verb>[@<node>]` a role's — resolved through what the
|
// `<module>.<tool>` another's, `seat:<seat>.<verb>[@<node>]` a role's — resolved through what the
|
||||||
// mesh issued that module to reach, as its own runtime resolved it, else the derived shape.
|
// mesh issued that module to reach, as its own runtime resolved it, else the derived shape.
|
||||||
func (c *Conn) AskAs(module, key string, body any) (Answered, error) {
|
func (c *Conn) AskAs(module, key string, body any) (Answered, error) {
|
||||||
|
return c.AskAsWithin(module, key, body, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AskAsWithin is AskAs that waits within for its answer (design 47 H §760); zero waits RequestTimeout.
|
||||||
|
func (c *Conn) AskAsWithin(module, key string, body any, within time.Duration) (Answered, error) {
|
||||||
name, wanted, _ := strings.Cut(key, "@")
|
name, wanted, _ := strings.Cut(key, "@")
|
||||||
subject := ""
|
subject := ""
|
||||||
if m := c.Membership(module); m != nil {
|
if m := c.Membership(module); m != nil {
|
||||||
@@ -1043,7 +1256,7 @@ func (c *Conn) AskAs(module, key string, body any) (Answered, error) {
|
|||||||
}
|
}
|
||||||
subject = s
|
subject = s
|
||||||
}
|
}
|
||||||
return c.Ask(key, body, subject)
|
return c.AskWithin(key, body, subject, within)
|
||||||
}
|
}
|
||||||
|
|
||||||
// EventsStream is where every module's events land, and ConsumerOf the durable consumer the
|
// EventsStream is where every module's events land, and ConsumerOf the durable consumer the
|
||||||
@@ -1060,6 +1273,13 @@ func ConsumerOf(node, module string) string {
|
|||||||
return node + "_" + module
|
return node + "_" + module
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ToolsSuffix ends the name of the tool runner's own durable consumer of a module: the runner and the module's program each
|
||||||
|
// need every event, so each reads under a name of its own (lead answer A-397); only a work queue shares one name.
|
||||||
|
const ToolsSuffix = "_tools"
|
||||||
|
|
||||||
|
// ToolsConsumerOf is the tool runner's durable consumer of a module on a machine: `<node>_<module>_tools`.
|
||||||
|
func ToolsConsumerOf(node, module string) string { return ConsumerOf(node, module) + ToolsSuffix }
|
||||||
|
|
||||||
// NakDelay is how long an event a handler failed waits before it is offered again: a transient cause
|
// NakDelay is how long an event a handler failed waits before it is offered again: a transient cause
|
||||||
// gets another attempt, a permanent one exhausts the consumer's max-deliver rather than spinning. The
|
// gets another attempt, a permanent one exhausts the consumer's max-deliver rather than spinning. The
|
||||||
// consumer then gives the event up, and the mesh keeps it in DEAD_LETTERS until a person delivers
|
// consumer then gives the event up, and the mesh keeps it in DEAD_LETTERS until a person delivers
|
||||||
@@ -1110,7 +1330,7 @@ var tickHook func()
|
|||||||
// answers true (nil is always): a module whose children asked for no heartbeat costs the bus no consumer-info request.
|
// answers true (nil is always): a module whose children asked for no heartbeat costs the bus no consumer-info request.
|
||||||
func (c *Conn) ConsumeAsBeatingWhen(module string, deliver func(Envelope) error, beat func(Beat), wanted func() bool) (func(), error) {
|
func (c *Conn) ConsumeAsBeatingWhen(module string, deliver func(Envelope) error, beat func(Beat), wanted func() bool) (func(), error) {
|
||||||
asked := func() bool { return beat != nil && (wanted == nil || wanted()) }
|
asked := func() bool { return beat != nil && (wanted == nil || wanted()) }
|
||||||
durable := ConsumerOf(c.node, module)
|
durable := ToolsConsumerOf(c.node, module)
|
||||||
js, err := jetstream.New(c.nc)
|
js, err := jetstream.New(c.nc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1127,9 +1347,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
|
missed.Store(false) // an event arrived: the consumer is heard, whatever was said before
|
||||||
return deliver(env)
|
return deliver(env)
|
||||||
})
|
})
|
||||||
// Bound by name, never created and never matched against a subject: the consumer and its
|
// Made first from the membership's spec where its EVENTS entry carries one (H-A-472 fifth to eighth addenda), else bound
|
||||||
// filters are the mesh's (design 29 §3), exactly as the module's own runtime bound it.
|
// by name: then 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) {
|
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) {
|
if errors.Is(err, jetstream.ErrNoHeartbeat) {
|
||||||
say("the bus's heartbeat to the consumer " + durable + " stopped arriving")
|
say("the bus's heartbeat to the consumer " + durable + " stopped arriving")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSubjectsAreTheOnesTheTypeScriptRuntimeUses(t *testing.T) {
|
func TestSubjectsAreTheOnesTheTypeScriptRuntimeUses(t *testing.T) {
|
||||||
@@ -60,3 +61,12 @@ func TestAnEventDeliveredAgainHasItsOwnKey(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Design 47 H §760: a call waits the bound its verb's definition names, else the tool runner's own.
|
||||||
|
func TestWaitOfIsTheVerbsBoundElseTheRunnersOwn(t *testing.T) {
|
||||||
|
for within, want := range map[time.Duration]time.Duration{0: RequestTimeout, 40 * time.Second: 40 * time.Second, 600 * time.Second: 600 * time.Second} {
|
||||||
|
if got := waitOf(within); got != want {
|
||||||
|
t.Errorf("waitOf(%s) = %s, want %s", within, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
)
|
)
|
||||||
@@ -105,8 +106,9 @@ func callerOn(pattern, subject string) string {
|
|||||||
return UserOfToken(subject[dot+1:])
|
return UserOfToken(subject[dot+1:])
|
||||||
}
|
}
|
||||||
|
|
||||||
// CalledHandler answers one call, told who called: the bus user the subject named, or "" when it named none.
|
// CalledHandler answers one call, told who called: the bus user the subject named, or "" when it named none; and the ask id the
|
||||||
type CalledHandler func(caller string, body json.RawMessage) (any, error)
|
// call carried in its request header stdio.AskHeader, or "" (design 47 H2 §775, H-A-351).
|
||||||
|
type CalledHandler func(caller, ask string, body json.RawMessage) (any, error)
|
||||||
|
|
||||||
// callers is what a connection keeps of its caller-named calls: those in flight, by subject, so a refused
|
// callers is what a connection keeps of its caller-named calls: those in flight, by subject, so a refused
|
||||||
// publish ends its call at once instead of after RequestTimeout.
|
// publish ends its call at once instead of after RequestTimeout.
|
||||||
@@ -150,9 +152,9 @@ func (c *Conn) publishRefused(err error) bool {
|
|||||||
// askCalled asks once on a caller-named subject. fallBack says the call reached nobody — nothing serves that
|
// askCalled asks once on a caller-named subject. fallBack says the call reached nobody — nothing serves that
|
||||||
// subject yet, or the bus refused this user its publish — so it may be asked on the subject that names no
|
// subject yet, or the bus refused this user its publish — so it may be asked on the subject that names no
|
||||||
// caller without being done twice.
|
// caller without being done twice.
|
||||||
func (c *Conn) askCalled(subject string, data []byte) (answered Answered, fallBack bool, err error) {
|
func (c *Conn) askCalled(subject string, data []byte, within time.Duration) (answered Answered, fallBack bool, err error) {
|
||||||
ctx, cancel := context.WithCancelCause(context.Background())
|
ctx, cancel := context.WithCancelCause(context.Background())
|
||||||
ctx, stop := context.WithTimeout(ctx, RequestTimeout)
|
ctx, stop := context.WithTimeout(ctx, waitOf(within))
|
||||||
defer stop()
|
defer stop()
|
||||||
c.calls.mu.Lock()
|
c.calls.mu.Lock()
|
||||||
if c.calls.pending == nil {
|
if c.calls.pending == nil {
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ func grantedBus(t *testing.T, publish map[string][]string) string {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
go s.Start()
|
go s.Start()
|
||||||
if !s.ReadyForConnections(10 * time.Second) {
|
if !s.ReadyForConnections(mt.Bound(t)) {
|
||||||
t.Fatal("the bus did not come up")
|
t.Fatal("the bus did not come up")
|
||||||
}
|
}
|
||||||
t.Cleanup(s.Shutdown)
|
t.Cleanup(s.Shutdown)
|
||||||
@@ -58,7 +58,7 @@ type heard struct {
|
|||||||
callers []string
|
callers []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *heard) handler(caller string, _ json.RawMessage) (any, error) {
|
func (h *heard) handler(caller, _ string, _ json.RawMessage) (any, error) {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
defer h.mu.Unlock()
|
defer h.mu.Unlock()
|
||||||
h.callers = append(h.callers, caller)
|
h.callers = append(h.callers, caller)
|
||||||
@@ -79,7 +79,7 @@ func TestACallerFallsBackAtOnceWhereNothingServesTheCallerNamedSubject(t *testin
|
|||||||
h := &heard{}
|
h := &heard{}
|
||||||
// An older runtime: the subject that names no caller, alone.
|
// An older runtime: the subject that names no caller, alone.
|
||||||
stop, err := server.HandleSubject("mesh.mod.ledger.tool.who", func(body json.RawMessage) (any, error) {
|
stop, err := server.HandleSubject("mesh.mod.ledger.tool.who", func(body json.RawMessage) (any, error) {
|
||||||
return h.handler("", body)
|
return h.handler("", "", body)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -92,7 +92,7 @@ func TestACallerFallsBackAtOnceWhereNothingServesTheCallerNamedSubject(t *testin
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if took := time.Since(began); took > 2*time.Second {
|
if took := time.Since(began); took > bus.RequestTimeout/2 { // 1754/AC4: at once, not after the caller-named call's timeout
|
||||||
t.Errorf("the fall-back took %s", took)
|
t.Errorf("the fall-back took %s", took)
|
||||||
}
|
}
|
||||||
if got := h.all(); len(got) != 1 || got[0] != "" || !strings.Contains(string(answered.Result), `"caller":""`) {
|
if got := h.all(); len(got) != 1 || got[0] != "" || !strings.Contains(string(answered.Result), `"caller":""`) {
|
||||||
@@ -129,7 +129,7 @@ func TestACallerTheBusRefusesTheCallerNamedSubjectFallsBackAtOnce(t *testing.T)
|
|||||||
t.Errorf("the refusal was not said: %v", said)
|
t.Errorf("the refusal was not said: %v", said)
|
||||||
}
|
}
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
if took := time.Since(began); took > 3*time.Second {
|
if took := time.Since(began); took > bus.RequestTimeout/2 { // 1754/AC4: at once, not after RequestTimeout
|
||||||
t.Errorf("the refused caller-named call held the caller %s", took)
|
t.Errorf("the refused caller-named call held the caller %s", took)
|
||||||
}
|
}
|
||||||
if got := h.all(); len(got) != 1 || got[0] != "" {
|
if got := h.all(); len(got) != 1 || got[0] != "" {
|
||||||
@@ -173,7 +173,7 @@ func TestAGrantedCallerIsHeardAsItselfAndCannotNameAnother(t *testing.T) {
|
|||||||
if !errors.Is(err, nats.ErrPermissionViolation) {
|
if !errors.Is(err, nats.ErrPermissionViolation) {
|
||||||
t.Errorf("the bus said %v, want a permissions violation", err)
|
t.Errorf("the bus said %v, want a permissions violation", err)
|
||||||
}
|
}
|
||||||
case <-time.After(3 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Error("the bus did not refuse a call naming another caller")
|
t.Error("the bus did not refuse a call naming another caller")
|
||||||
}
|
}
|
||||||
if got := h.all(); len(got) != 1 || got[0] != "shanks.node-tools" {
|
if got := h.all(); len(got) != 1 || got[0] != "shanks.node-tools" {
|
||||||
@@ -216,3 +216,95 @@ func TestAFallBackForWantOfAResponderIsSaidOncePerSubject(t *testing.T) {
|
|||||||
t.Errorf("the fall-back was said %d times, want once: %v", n, said)
|
t.Errorf("the fall-back was said %d times, want once: %v", n, said)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Design 47 H §760: a call waits the bound its verb's definition names, and ends there with the timeout; the caller of a verb whose
|
||||||
|
// definition names none waits the tool runner's own bound, RequestTimeout.
|
||||||
|
func TestACallWaitsTheBoundItsVerbNamesAndTimesOutThere(t *testing.T) {
|
||||||
|
url := grantedBus(t, map[string][]string{"anchor.node-tools": {"_INBOX.>"}, "shanks.node-tools": {"mesh.mod.*.tool.>"}})
|
||||||
|
server := dial(t, url, "node-tools", "anchor", "anchor.node-tools")
|
||||||
|
release := make(chan struct{})
|
||||||
|
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.slow", func(string, string, json.RawMessage) (any, error) {
|
||||||
|
<-release
|
||||||
|
return map[string]any{}, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
defer close(release)
|
||||||
|
server.Flush()
|
||||||
|
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
|
||||||
|
began := time.Now()
|
||||||
|
_, err = asker.AskWithin("ledger.slow", map[string]any{}, "", 200*time.Millisecond)
|
||||||
|
if err == nil || err.Error() != "timeout" {
|
||||||
|
t.Fatalf("a call whose verb names a bound the holder outlasts: %v, want the timeout", err)
|
||||||
|
}
|
||||||
|
if took := time.Since(began); took > bus.RequestTimeout/2 {
|
||||||
|
t.Errorf("the call waited %s, want its own bound of 200ms, not the tool runner's %s", took, bus.RequestTimeout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 721/AC4: once told to stop, the tool runner unsubscribes from every subject it answers calls on before it finishes the
|
||||||
|
// calls in flight (design 47 H2 H-A-570 (1)): a call heard after the stop began gets no answer from it, no typed fault, and its
|
||||||
|
// caller meets no responders at once; the call in flight at the stop is still answered; a subject served once the stop began
|
||||||
|
// is not subscribed, and says so.
|
||||||
|
// 1754/AC3: its order is held (StopAnswering returns once the bus holds the unsubscriptions), so it needs no clock of its
|
||||||
|
// own: each call and the held call's arrival wait meshtest.Bound(t), and "at once" is the bus's word, no responders, where a
|
||||||
|
// subscription left behind would end the call at its bound in a timeout. It failed on a loaded build node (main.505)
|
||||||
|
// while it asked 1 s of two round trips and 5 s and 10 s of its waits.
|
||||||
|
func TestARunnerAtItsStopAnswersNoCallAndItsCallersMeetNoResponders(t *testing.T) {
|
||||||
|
url := mt.URL(t)
|
||||||
|
server := dial(t, url, "ledger", "anchor", "")
|
||||||
|
began, release := make(chan struct{}, 1), make(chan struct{})
|
||||||
|
stop, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.who", func(_, _ string, body json.RawMessage) (any, error) {
|
||||||
|
if strings.Contains(string(body), "held") {
|
||||||
|
began <- struct{}{}
|
||||||
|
<-release
|
||||||
|
}
|
||||||
|
return map[string]any{"who": "ledger"}, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
server.Flush()
|
||||||
|
asker := dial(t, url, "node-tools", "shanks", "shanks.node-tools")
|
||||||
|
held := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := asker.AskWithin("ledger.who", map[string]any{"held": true}, "", mt.Bound(t))
|
||||||
|
held <- err
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-began:
|
||||||
|
case <-time.After(mt.Bound(t)):
|
||||||
|
t.Fatal("the call to hold never reached the runner")
|
||||||
|
}
|
||||||
|
server.StopAnswering()
|
||||||
|
at, within := time.Now(), mt.Bound(t)
|
||||||
|
answered, err := asker.AskWithin("ledger.who", map[string]any{}, "", within)
|
||||||
|
if took := time.Since(at); !errors.Is(err, bus.ErrNoResponders) || took > within/2 {
|
||||||
|
t.Errorf("a call after the stop began was answered %s, %v in %s; want no responders at once", answered.Result, err, took)
|
||||||
|
}
|
||||||
|
if _, err := server.HandleSubjectCalled("mesh.mod.ledger.tool.late", func(string, string, json.RawMessage) (any, error) {
|
||||||
|
return nil, nil
|
||||||
|
}); err == nil || !strings.Contains(err.Error(), "took down every subscription") {
|
||||||
|
t.Errorf("a subject served once the stop began was subscribed (%v), want it refused and said", err)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
if err := <-held; err != nil {
|
||||||
|
t.Errorf("the call in flight at the stop ended %v, want it answered", err)
|
||||||
|
}
|
||||||
|
// A serve racing the stop (a membership change, a bundle's new tool): the stop begins between its subscription and its
|
||||||
|
// keeping, and still the subject is not left answered, its subscription taken down and the serve refused.
|
||||||
|
raced := dial(t, url, "ledger", "anchor", "")
|
||||||
|
var once sync.Once
|
||||||
|
bus.SetSubscribedHook(raced, func(string) { once.Do(raced.StopAnswering) })
|
||||||
|
if _, err := raced.HandleSubjectCalled("mesh.mod.ledger.tool.raced", func(string, string, json.RawMessage) (any, error) {
|
||||||
|
return map[string]any{"raced": true}, nil
|
||||||
|
}); err == nil {
|
||||||
|
t.Error("a serve that raced the stop was kept, want it refused")
|
||||||
|
}
|
||||||
|
if answered, err := asker.AskWithin("ledger.raced", map[string]any{}, "", mt.Bound(t)); !errors.Is(err, bus.ErrNoResponders) {
|
||||||
|
t.Errorf("a call of a tool whose serve raced the stop was answered %s, %v; want no responders", answered.Result, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -25,9 +25,17 @@ const FileField = "file"
|
|||||||
// counts with buscalls.SeatChunks, each acknowledged before the next, and answers the verb's own answer with the whole
|
// counts with buscalls.SeatChunks, each acknowledged before the next, and answers the verb's own answer with the whole
|
||||||
// file added as FileField. The asking bundle receives no chunk itself.
|
// file added as FileField. The asking bundle receives no chunk itself.
|
||||||
func (c *Conn) AskAsChunked(module, key string, body any) (Answered, error) {
|
func (c *Conn) AskAsChunked(module, key string, body any) (Answered, error) {
|
||||||
seat, verb, ok := strings.Cut(strings.TrimPrefix(key, "seat:"), ".")
|
return c.AskAsChunkedWithin(module, key, body, 0)
|
||||||
if !strings.HasPrefix(key, "seat:") || !ok || strings.Contains(verb, "@") {
|
}
|
||||||
return Answered{}, fmt.Errorf("%q is no seat:<seat>.<verb> of no one machine, which a chunked answer needs", key)
|
|
||||||
|
// AskAsChunkedWithin is AskAsChunked that waits within for the verb's answer (design 47 H §760); zero waits RequestTimeout.
|
||||||
|
func (c *Conn) AskAsChunkedWithin(module, key string, body any, within time.Duration) (Answered, error) {
|
||||||
|
// The verb may be asked of the machine that ran the ask (`@<node>`, A-254): the chunk subjects name the seat, the verb and
|
||||||
|
// the call alone.
|
||||||
|
name, _, _ := strings.Cut(key, "@")
|
||||||
|
seat, verb, ok := strings.Cut(strings.TrimPrefix(name, "seat:"), ".")
|
||||||
|
if !strings.HasPrefix(key, "seat:") || !ok {
|
||||||
|
return Answered{}, fmt.Errorf("%q is no seat:<seat>.<verb>, which a chunked answer needs", key)
|
||||||
}
|
}
|
||||||
args := map[string]any{}
|
args := map[string]any{}
|
||||||
if raw, err := json.Marshal(body); err != nil {
|
if raw, err := json.Marshal(body); err != nil {
|
||||||
@@ -49,7 +57,7 @@ func (c *Conn) AskAsChunked(module, key string, body any) (Answered, error) {
|
|||||||
return Answered{}, fmt.Errorf("the chunks of %s cannot be heard: %w", key, err)
|
return Answered{}, fmt.Errorf("the chunks of %s cannot be heard: %w", key, err)
|
||||||
}
|
}
|
||||||
defer func() { _ = sub.Unsubscribe() }()
|
defer func() { _ = sub.Unsubscribe() }()
|
||||||
answered, err := c.AskAs(module, key, args)
|
answered, err := c.AskAsWithin(module, key, args, within)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return answered, err
|
return answered, err
|
||||||
}
|
}
|
||||||
@@ -93,3 +101,48 @@ func (c *Conn) AskAsChunked(module, key string, body any) (Answered, error) {
|
|||||||
answered.Result = out
|
answered.Result = out
|
||||||
return answered, nil
|
return answered, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AnswerChunked is a seat verb's answer as its definition says `chunks` (design 47 G A-257, §681): a bundle answers the whole file
|
||||||
|
// as the member FileField (base64), and the runner that serves the verb sends it in chunks with buscalls.SeatChunks on the call
|
||||||
|
// token the body names, each acknowledged by the caller before the next, and answers the verb's own members with `chunks`, the
|
||||||
|
// count, in place of the file. The bundle sends no chunk itself. An answer with no file is answered as it is. The send runs after
|
||||||
|
// the answer is returned: the caller hears the chunks before it asks (AskAsChunked) and acknowledges each once it has the answer.
|
||||||
|
func (c *Conn) AnswerChunked(seat, verb string, body json.RawMessage, answer any) (any, error) {
|
||||||
|
raw, err := json.Marshal(answer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
fields := map[string]json.RawMessage{}
|
||||||
|
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||||
|
return answer, nil
|
||||||
|
}
|
||||||
|
enc, has := fields[FileField]
|
||||||
|
if !has {
|
||||||
|
return answer, nil
|
||||||
|
}
|
||||||
|
var text string
|
||||||
|
if err := json.Unmarshal(enc, &text); err != nil {
|
||||||
|
return nil, fmt.Errorf("%s.%s answers a %s that is no string: %w", seat, verb, FileField, err)
|
||||||
|
}
|
||||||
|
file, err := base64.StdEncoding.DecodeString(text)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s.%s answers a %s in no base64: %w", seat, verb, FileField, err)
|
||||||
|
}
|
||||||
|
var asked struct {
|
||||||
|
Call string `json:"call"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(body, &asked); err != nil || asked.Call == "" {
|
||||||
|
return nil, fmt.Errorf("%s.%s is asked in chunks with no call token", seat, verb)
|
||||||
|
}
|
||||||
|
delete(fields, FileField)
|
||||||
|
count := int64((len(file) + buscalls.SeatChunkBytes - 1) / buscalls.SeatChunkBytes)
|
||||||
|
fields["chunks"], _ = json.Marshal(count)
|
||||||
|
send := buscalls.SeatChunks{Seat: seat, Verb: verb, Call: asked.Call}
|
||||||
|
go func() { _ = send.Send(c.nc, file, buscalls.SeatAckWithin, c.Logf) }()
|
||||||
|
return json.RawMessage(mustMarshal(fields)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustMarshal(v any) []byte {
|
||||||
|
b, _ := json.Marshal(v)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ func TestAChunkedSeatAnswerIsReceivedByTheRunnerAndHandedWhole(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer stop()
|
defer stop()
|
||||||
|
holder.Flush() // the bus holds the verb's subscription before it is asked: the asker is another connection
|
||||||
got, err := asker.AskAsChunked("mesh-build-go", "seat:mesh-catalog.input", map[string]any{"digest": "d1"})
|
got, err := asker.AskAsChunked("mesh-build-go", "seat:mesh-catalog.input", map[string]any{"digest": "d1"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -72,4 +73,45 @@ func TestAChunkedSeatAnswerIsReceivedByTheRunnerAndHandedWhole(t *testing.T) {
|
|||||||
if body, err := base64.StdEncoding.DecodeString(ans.File); err != nil || string(body) != string(file) {
|
if body, err := base64.StdEncoding.DecodeString(ans.File); err != nil || string(body) != string(file) {
|
||||||
t.Errorf("the file handed is %d bytes, want the %d sent: %v", len(body), len(file), err)
|
t.Errorf("the file handed is %d bytes, want the %d sent: %v", len(body), len(file), err)
|
||||||
}
|
}
|
||||||
|
// Design 47 G A-257, A-254: a bundle answers a chunked verb with the whole file in the member `file`; the runner that serves the
|
||||||
|
// verb sends the file in chunks (each acknowledged before the next) and answers the count, so the bundle sends none, and the asker
|
||||||
|
// of one node's verb receives it whole.
|
||||||
|
t.Run("ABundlesChunkedAnswerIsSentByTheRunner", func(t *testing.T) {
|
||||||
|
url := mt.URL(t)
|
||||||
|
holder := dial(t, url, "mesh-build-go", "anchor", "")
|
||||||
|
asker := dial(t, url, "mesh-delivery-indexer", "anchor", "")
|
||||||
|
file := make([]byte, buscalls.SeatChunkBytes*2+7)
|
||||||
|
for i := range file {
|
||||||
|
file[i] = byte(i * 7)
|
||||||
|
}
|
||||||
|
stop, err := holder.Handle("seat:node-build-go.output@anchor", func(body json.RawMessage) (any, error) {
|
||||||
|
answer := map[string]any{"ask": "a1", "file": base64.StdEncoding.EncodeToString(file)}
|
||||||
|
return holder.AnswerChunked("node-build-go", "output", body, answer)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
holder.Flush() // the bus holds the verb's subscription before it is asked: the asker is another connection
|
||||||
|
got, err := asker.AskAsChunked("mesh-delivery-indexer", "seat:node-build-go.output@anchor", map[string]any{"ask": "a1"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var ans struct {
|
||||||
|
Ask string `json:"ask"`
|
||||||
|
Chunks int `json:"chunks"`
|
||||||
|
File string `json:"file"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(got.Result, &ans); err != nil || ans.Ask != "a1" || ans.Chunks != 3 {
|
||||||
|
t.Fatalf("the answer %s: %v", got.Result, err)
|
||||||
|
}
|
||||||
|
if body, err := base64.StdEncoding.DecodeString(ans.File); err != nil || string(body) != string(file) {
|
||||||
|
t.Errorf("the file handed is %d bytes, want the %d sent: %v", len(body), len(file), err)
|
||||||
|
}
|
||||||
|
// an answer with no file is the verb's own: no chunks are sent
|
||||||
|
plain, err := holder.AnswerChunked("node-build-go", "output", json.RawMessage(`{"call":"c"}`), map[string]any{"ask": "x", "chunks": 0})
|
||||||
|
if m, _ := plain.(map[string]any); err != nil || m["chunks"] != 0 {
|
||||||
|
t.Fatalf("an answer with no file was %v, %v", plain, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ func TestAConsumerSaysItIsBoundWhileIdleAndOnceWhenTheBusEndedIt(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
mesh.Consumer(t, "anchor", "quiet", []string{"mesh.mod.alpha.event.>"}, time.Second)
|
mesh.Consumer(t, "anchor", "quiet", []string{"mesh.mod.alpha.event.>"}, time.Second)
|
||||||
|
// The unasked consume below pulls a durable of its own: a second loop on quiet's is refused (H-A-196, H-A-197).
|
||||||
|
mesh.Consumer(t, "anchor", "unasked", []string{"mesh.mod.alpha.event.>"}, time.Second)
|
||||||
c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "anchor"})
|
c, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "anchor"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -97,7 +99,7 @@ func TestAConsumerSaysItIsBoundWhileIdleAndOnceWhenTheBusEndedIt(t *testing.T) {
|
|||||||
t.Cleanup(stop)
|
t.Cleanup(stop)
|
||||||
// A consume nobody asked a heartbeat of says nothing and asks the bus nothing, however many intervals pass.
|
// A consume nobody asked a heartbeat of says nothing and asks the bus nothing, however many intervals pass.
|
||||||
var unaskedBeats atomic.Int32
|
var unaskedBeats atomic.Int32
|
||||||
unasked, err := c.ConsumeAsBeatingWhen("quiet", func(bus.Envelope) error { return nil },
|
unasked, err := c.ConsumeAsBeatingWhen("unasked", func(bus.Envelope) error { return nil },
|
||||||
func(bus.Beat) { unaskedBeats.Add(1) }, func() bool { return false })
|
func(bus.Beat) { unaskedBeats.Add(1) }, func() bool { return false })
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -135,7 +137,7 @@ func TestAConsumerSaysItIsBoundWhileIdleAndOnceWhenTheBusEndedIt(t *testing.T) {
|
|||||||
for n := 0; n < 3; n++ { // three more intervals pass, counted by the loop's own tick
|
for n := 0; n < 3; n++ { // three more intervals pass, counted by the loop's own tick
|
||||||
select {
|
select {
|
||||||
case <-ticks:
|
case <-ticks:
|
||||||
case <-time.After(10 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatal("the heartbeat loop handled no more intervals")
|
t.Fatal("the heartbeat loop handled no more intervals")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,3 +6,11 @@ func SetTickHook(f func()) (restore func()) {
|
|||||||
tickHook = f
|
tickHook = f
|
||||||
return func() { tickHook = old }
|
return func() { tickHook = old }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetSubscribedHook makes c call f with the subject between making each answering subscription and keeping it, so a test can
|
||||||
|
// run the stop in between (design 47 H2 H-A-570 (1)).
|
||||||
|
func SetSubscribedHook(c *Conn, f func(subject string)) {
|
||||||
|
c.mu.Lock()
|
||||||
|
c.subscribedHook = f
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
@@ -143,6 +144,76 @@ func (h *busHistory) Read(keys string, from uint64, limit int) ([]ledger.Kept, e
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Purge removes every operation of one instance from the history stream, on the module's ledger connection, the one
|
||||||
|
// granted the purge of its own ledger's streams.
|
||||||
|
func (h *busHistory) Purge(key string) error {
|
||||||
|
return purgeSubject(h.read, h.write, h.stream, h.prefix+"."+key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill is the history stream's fill against its cap, the cap the manifest gives the ledger.
|
||||||
|
func (h *busHistory) Fill() (buscalls.Fill, error) {
|
||||||
|
name := h.stream
|
||||||
|
if name == "" {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
js, err := h.read.JetStream()
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.Fill{}, err
|
||||||
|
}
|
||||||
|
if name, err = js.StreamNameBySubject(ctx, h.prefix+".>"); err != nil {
|
||||||
|
return buscalls.Fill{}, fmt.Errorf("no stream on the bus keeps %s: %w", h.prefix, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f, err := h.read.streamFill(name)
|
||||||
|
return f.Fill, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// purgeSubject purges one subject's messages from the stream that keeps it: the stream named, or found on the runner's
|
||||||
|
// own connection by its subject, purged on the ledger connection.
|
||||||
|
func purgeSubject(read, write *Conn, stream, subject string) error {
|
||||||
|
if write == nil {
|
||||||
|
return errors.New("a ledger's streams are purged only on its module's ledger connection, and none is held")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if stream == "" {
|
||||||
|
js, err := read.JetStream()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if stream, err = js.StreamNameBySubject(ctx, subject); err != nil {
|
||||||
|
return fmt.Errorf("no stream on the bus keeps %s: %w", subject, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The purge is asked of the stream by its name, with no read of its info first: the ledger account is granted the
|
||||||
|
// purge of its own ledger's two streams and nothing else (PurgeAPI).
|
||||||
|
body, err := json.Marshal(map[string]string{"filter": subject})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reply, err := write.nc.RequestWithContext(ctx, PurgeAPI(stream), body)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("purging %s from %s: %w", subject, stream, err)
|
||||||
|
}
|
||||||
|
var ack struct {
|
||||||
|
Success bool `json:"success"`
|
||||||
|
Error *struct {
|
||||||
|
Description string `json:"description"`
|
||||||
|
} `json:"error"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(reply.Data, &ack); err != nil || !ack.Success {
|
||||||
|
why := string(reply.Data)
|
||||||
|
if ack.Error != nil {
|
||||||
|
why = ack.Error.Description
|
||||||
|
}
|
||||||
|
return fmt.Errorf("the bus refused the purge of %s from %s: %s", subject, stream, why)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PurgeAPI is the bus's subject that purges a stream, the one a ledger account is granted for its own ledger's streams.
|
||||||
|
func PurgeAPI(stream string) string { return "$JS.API.STREAM.PURGE." + stream }
|
||||||
|
|
||||||
type busState struct {
|
type busState struct {
|
||||||
c *Conn
|
c *Conn
|
||||||
bucket string
|
bucket string
|
||||||
@@ -231,6 +302,11 @@ func (s *busSnapshots) Get(key string) ([]byte, uint64, error) {
|
|||||||
return lastOn(s.read, "", s.prefix+"."+key)
|
return lastOn(s.read, "", s.prefix+"."+key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Purge removes one instance's snapshot, on the module's ledger connection.
|
||||||
|
func (s *busSnapshots) Purge(key string) error {
|
||||||
|
return purgeSubject(s.read, s.write, "", s.prefix+"."+key)
|
||||||
|
}
|
||||||
|
|
||||||
func (s *busSnapshots) Put(key string, value []byte, expect uint64) error {
|
func (s *busSnapshots) Put(key string, value []byte, expect uint64) error {
|
||||||
if s.write == nil {
|
if s.write == nil {
|
||||||
return errors.New("a ledger's snapshot is published only on its module's ledger connection, and none is held")
|
return errors.New("a ledger's snapshot is published only on its module's ledger connection, and none is held")
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func TestAnAnswerLargerThanOneMessage(t *testing.T) {
|
|||||||
if err == nil || !strings.Contains(err.Error(), "more than the bus carries") {
|
if err == nil || !strings.Contains(err.Error(), "more than the bus carries") {
|
||||||
t.Fatalf("a module's answer too large for one message read as %v", err)
|
t.Fatalf("a module's answer too large for one message read as %v", err)
|
||||||
}
|
}
|
||||||
if took := time.Since(asked); took > 5*time.Second {
|
if took := time.Since(asked); took > bus.RequestTimeout/2 { // 1754/AC4: said at once, not at the call's timeout
|
||||||
t.Fatalf("it took %s to say", took)
|
t.Fatalf("it took %s to say", took)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package bus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QueueWaitingMost is the most a waiting read holds, in its asks' ids and modules (design 47 H2 H-A-410).
|
||||||
|
const QueueWaitingMost = 768 << 10
|
||||||
|
|
||||||
|
// WaitingAsk is one ask that waits on a seat's work queue: its id (the publisher's own, as it published it), the module that
|
||||||
|
// put it and how long it has waited.
|
||||||
|
type WaitingAsk struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Module string `json:"module"`
|
||||||
|
AgeSeconds int64 `json:"age_seconds"`
|
||||||
|
// Again says the ask was handed to a worker at least once and not acknowledged: held now, or handed back to wait again;
|
||||||
|
// the holder tells the two apart by its own state taken (H-A-410, second addendum).
|
||||||
|
Again bool `json:"again,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueueWaiting is what waits on a seat's work queue, oldest first, and whether the read stopped at QueueWaitingMost.
|
||||||
|
type QueueWaiting struct {
|
||||||
|
Asks []WaitingAsk `json:"asks"`
|
||||||
|
Capped bool `json:"capped,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueueWaitingOf reads, without consuming, the asks that wait on the seat's work queue for module, the holder whose
|
||||||
|
// membership lists the queue's workers: its own store (ADR 0596). For each of its workers on the seat's stream, every message
|
||||||
|
// after the worker's acknowledgement floor is read by a direct get by subject, never by a consumer of its own; one at or
|
||||||
|
// below the worker's delivered sequence is marked again (design 47 H2 H-A-410 and its addenda).
|
||||||
|
func (c *Conn) QueueWaitingOf(module, seat string) (QueueWaiting, error) {
|
||||||
|
t, err := c.trafficOf(module)
|
||||||
|
if err != nil {
|
||||||
|
return QueueWaiting{}, err
|
||||||
|
}
|
||||||
|
// The work-queue stream a seat's asks are kept on, by the one derivation every part takes (H-A-410, P9).
|
||||||
|
stream := buscompose.SeatQueueStreamName(seat)
|
||||||
|
var workers []SeatWorker
|
||||||
|
for _, w := range t.Workers {
|
||||||
|
if w.Stream == stream {
|
||||||
|
workers = append(workers, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(workers) == 0 {
|
||||||
|
return QueueWaiting{}, fmt.Errorf("%s holds no work queue of the seat %s: its membership lists no worker on %s "+
|
||||||
|
"(novox/hq ADR 0596: a holder reads its own queue)", module, seat, stream)
|
||||||
|
}
|
||||||
|
js, err := jetstream.New(c.nc)
|
||||||
|
if err != nil {
|
||||||
|
return QueueWaiting{}, err
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
kept, err := js.Stream(ctx, stream)
|
||||||
|
if err != nil {
|
||||||
|
return QueueWaiting{}, fmt.Errorf("reading %s's queue %s: %w", module, stream, err)
|
||||||
|
}
|
||||||
|
out := QueueWaiting{Asks: []WaitingAsk{}}
|
||||||
|
size, now := 0, time.Now()
|
||||||
|
for _, w := range workers {
|
||||||
|
bound, err := c.pullConsumer(module, w)
|
||||||
|
if err != nil {
|
||||||
|
return QueueWaiting{}, err
|
||||||
|
}
|
||||||
|
info, err := bound.Info(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return QueueWaiting{}, fmt.Errorf("reading %s's worker %s: %w", module, w.Consumer, err)
|
||||||
|
}
|
||||||
|
filter := w.Filter
|
||||||
|
if filter == "" {
|
||||||
|
filter = ">"
|
||||||
|
}
|
||||||
|
for seq := info.AckFloor.Stream + 1; ; {
|
||||||
|
m, err := kept.GetMsg(ctx, seq, jetstream.WithGetMsgSubject(filter))
|
||||||
|
if errors.Is(err, jetstream.ErrMsgNotFound) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return QueueWaiting{}, fmt.Errorf("reading %s's queue %s: %w", module, stream, err)
|
||||||
|
}
|
||||||
|
seq = m.Sequence + 1
|
||||||
|
ask := WaitingAsk{Module: m.Header.Get("x-source"), AgeSeconds: int64(now.Sub(m.Time) / time.Second),
|
||||||
|
Again: m.Sequence <= info.Delivered.Stream}
|
||||||
|
ask.ID = strings.TrimPrefix(m.Header.Get("x-event-id"), ask.Module+".")
|
||||||
|
if size += len(ask.ID) + len(ask.Module) + 48; size > QueueWaitingMost {
|
||||||
|
out.Capped = true
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
out.Asks = append(out.Asks, ask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -195,7 +195,8 @@ func (c *Conn) SeatProve(module, subject string, body json.RawMessage) (json.Raw
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SeatAnswer answers every proof on a subject the module's seat traffic lists among its answers, with what
|
// SeatAnswer answers every proof on a subject the module's seat traffic lists among its answers, with what
|
||||||
// answer returns. A returned error is answered as `{"error": "<words>"}`, never as silence.
|
// answer returns. A returned error is answered as `{"error": "<words>"}`, never as silence, but for one that says it is
|
||||||
|
// unanswered (a proof after the stop or cut at the bound). The runner's stop takes the subscription down (StopAnswering).
|
||||||
func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, body json.RawMessage) (json.RawMessage, error)) (func(), error) {
|
func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, body json.RawMessage) (json.RawMessage, error)) (func(), error) {
|
||||||
t, err := c.trafficOf(module)
|
t, err := c.trafficOf(module)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -209,6 +210,9 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo
|
|||||||
return nil, fmt.Errorf("%s does not answer %s: its membership lists %s (novox/hq ADR 0259)", module,
|
return nil, fmt.Errorf("%s does not answer %s: its membership lists %s (novox/hq ADR 0259)", module,
|
||||||
subject, strings.Join(t.Answers, ", "))
|
subject, strings.Join(t.Answers, ", "))
|
||||||
}
|
}
|
||||||
|
if err := c.answersAreDown(subject); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
sub, err := c.nc.Subscribe(subject, func(msg *nats.Msg) {
|
sub, err := c.nc.Subscribe(subject, func(msg *nats.Msg) {
|
||||||
if msg.Reply == "" {
|
if msg.Reply == "" {
|
||||||
return
|
return
|
||||||
@@ -219,6 +223,12 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
out, err := answer(msg.Subject, body)
|
out, err := answer(msg.Subject, body)
|
||||||
|
// A proof arriving after the runner's stop, or cut at its bound, is answered nothing, as answerCalledOn does
|
||||||
|
// (design 47 H2 §813 (12), H-A-369).
|
||||||
|
var unanswered interface{ Unanswered() bool }
|
||||||
|
if errors.As(err, &unanswered) && unanswered.Unanswered() {
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
b, _ := json.Marshal(map[string]string{"error": err.Error()})
|
b, _ := json.Marshal(map[string]string{"error": err.Error()})
|
||||||
_ = msg.Respond(b)
|
_ = msg.Respond(b)
|
||||||
@@ -234,9 +244,26 @@ func (c *Conn) SeatAnswer(module, subject string, answer func(subject string, bo
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
c.track(sub)
|
c.subscribed(subject)
|
||||||
|
// Kept among the proofs the stop takes down, or taken down at once when the stop began meanwhile (design 47 H2 H-A-570
|
||||||
|
// (1)).
|
||||||
|
if err := c.keepAnswering(sub, func() {
|
||||||
|
if c.proofs == nil {
|
||||||
|
c.proofs = map[*nats.Subscription]bool{}
|
||||||
|
}
|
||||||
|
c.proofs[sub] = true
|
||||||
|
}); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
var once sync.Once
|
var once sync.Once
|
||||||
return func() { once.Do(func() { _ = sub.Unsubscribe() }) }, nil
|
return func() {
|
||||||
|
once.Do(func() {
|
||||||
|
c.mu.Lock()
|
||||||
|
delete(c.proofs, sub)
|
||||||
|
c.mu.Unlock()
|
||||||
|
_ = sub.Unsubscribe()
|
||||||
|
})
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Work is one message a holder took from a seat's work queue.
|
// Work is one message a holder took from a seat's work queue.
|
||||||
@@ -279,6 +306,8 @@ func (c *Conn) SeatTake(module, consumer string, deliver func(Work) error) (func
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err)
|
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err)
|
||||||
}
|
}
|
||||||
|
// Read once, as the take starts: its loop outlives SeatTake, and a test sets it back as it ends (design 47 H, H-A-363).
|
||||||
|
heartbeat := WorkHeartbeat
|
||||||
reading, err := bound.Consume(func(msg jetstream.Msg) {
|
reading, err := bound.Consume(func(msg jetstream.Msg) {
|
||||||
if !json.Valid(msg.Data()) {
|
if !json.Valid(msg.Data()) {
|
||||||
_ = msg.Term()
|
_ = msg.Term()
|
||||||
@@ -292,7 +321,7 @@ func (c *Conn) SeatTake(module, consumer string, deliver func(Work) error) (func
|
|||||||
// that died, not one that is slow.
|
// that died, not one that is slow.
|
||||||
done := make(chan struct{})
|
done := make(chan struct{})
|
||||||
go func() {
|
go func() {
|
||||||
tick := time.NewTicker(WorkHeartbeat)
|
tick := time.NewTicker(heartbeat)
|
||||||
defer tick.Stop()
|
defer tick.Stop()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -427,11 +456,7 @@ func (c *Conn) stateWrite(module, name, key string, value json.RawMessage,
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := c.bucket(ctx, s)
|
rev, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (uint64, error) { return write(ctx, kv) })
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
rev, err := write(ctx, kv)
|
|
||||||
if errors.Is(err, jetstream.ErrKeyExists) || isWrongSequence(err) {
|
if errors.Is(err, jetstream.ErrKeyExists) || isWrongSequence(err) {
|
||||||
return 0, changed{name + "." + key}
|
return 0, changed{name + "." + key}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,8 +33,10 @@ type Pulled struct {
|
|||||||
Delivered uint64 `json:"delivered"`
|
Delivered uint64 `json:"delivered"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// pulls are the messages modules pulled and have not settled, by id; each kept with the module it was pulled for, so
|
// pulls are the messages modules pulled on one connection and have not settled, by id, each kept with the module it was
|
||||||
// one module never settles another's.
|
// pulled for, so one module never settles another's; and the workers bound on that connection. They are the Conn's, not
|
||||||
|
// the process's: a worker bound on a connection since closed answered every later pull "connection closed" (design
|
||||||
|
// 47 H, H-A-363: state outliving the connection it was made on).
|
||||||
type pulls struct {
|
type pulls struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
held map[string]pulledMsg
|
held map[string]pulledMsg
|
||||||
@@ -46,8 +48,6 @@ type pulledMsg struct {
|
|||||||
msg jetstream.Msg
|
msg jetstream.Msg
|
||||||
}
|
}
|
||||||
|
|
||||||
var seatPulls = &pulls{held: map[string]pulledMsg{}, cons: map[string]jetstream.Consumer{}}
|
|
||||||
|
|
||||||
func pullID() string {
|
func pullID() string {
|
||||||
var b [8]byte
|
var b [8]byte
|
||||||
_, _ = rand.Read(b[:])
|
_, _ = rand.Read(b[:])
|
||||||
@@ -111,17 +111,20 @@ func (c *Conn) SeatPull(module, consumer string, wait time.Duration) (*Pulled, e
|
|||||||
}
|
}
|
||||||
p := &Pulled{ID: pullID(), Worker: w.Consumer, Subject: msg.Subject(), Body: json.RawMessage(msg.Data()),
|
p := &Pulled{ID: pullID(), Worker: w.Consumer, Subject: msg.Subject(), Body: json.RawMessage(msg.Data()),
|
||||||
Headers: headers, Delivered: delivered}
|
Headers: headers, Delivered: delivered}
|
||||||
seatPulls.mu.Lock()
|
c.pulls.mu.Lock()
|
||||||
seatPulls.held[p.ID] = pulledMsg{module: module, msg: msg}
|
if c.pulls.held == nil {
|
||||||
seatPulls.mu.Unlock()
|
c.pulls.held = map[string]pulledMsg{}
|
||||||
|
}
|
||||||
|
c.pulls.held[p.ID] = pulledMsg{module: module, msg: msg}
|
||||||
|
c.pulls.mu.Unlock()
|
||||||
return p, nil
|
return p, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, error) {
|
func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, error) {
|
||||||
key := module + " " + w.Consumer
|
key := module + " " + w.Consumer
|
||||||
seatPulls.mu.Lock()
|
c.pulls.mu.Lock()
|
||||||
bound, ok := seatPulls.cons[key]
|
bound, ok := c.pulls.cons[key]
|
||||||
seatPulls.mu.Unlock()
|
c.pulls.mu.Unlock()
|
||||||
if ok {
|
if ok {
|
||||||
return bound, nil
|
return bound, nil
|
||||||
}
|
}
|
||||||
@@ -135,9 +138,12 @@ func (c *Conn) pullConsumer(module string, w SeatWorker) (jetstream.Consumer, er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err)
|
return nil, fmt.Errorf("binding %s's worker %s on %s: %w", module, w.Consumer, w.Stream, err)
|
||||||
}
|
}
|
||||||
seatPulls.mu.Lock()
|
c.pulls.mu.Lock()
|
||||||
seatPulls.cons[key] = bound
|
if c.pulls.cons == nil {
|
||||||
seatPulls.mu.Unlock()
|
c.pulls.cons = map[string]jetstream.Consumer{}
|
||||||
|
}
|
||||||
|
c.pulls.cons[key] = bound
|
||||||
|
c.pulls.mu.Unlock()
|
||||||
return bound, nil
|
return bound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,15 +174,15 @@ func (c *Conn) SeatSettleAfter(module, id string, delay time.Duration) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
|
func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
|
||||||
seatPulls.mu.Lock()
|
c.pulls.mu.Lock()
|
||||||
p, ok := seatPulls.held[id]
|
p, ok := c.pulls.held[id]
|
||||||
if ok && p.module != module {
|
if ok && p.module != module {
|
||||||
ok = false
|
ok = false
|
||||||
}
|
}
|
||||||
if ok && fate != SettleProgress {
|
if ok && fate != SettleProgress {
|
||||||
delete(seatPulls.held, id)
|
delete(c.pulls.held, id)
|
||||||
}
|
}
|
||||||
seatPulls.mu.Unlock()
|
c.pulls.mu.Unlock()
|
||||||
if !ok {
|
if !ok {
|
||||||
return fmt.Errorf("%s holds no pulled message %s", module, id)
|
return fmt.Errorf("%s holds no pulled message %s", module, id)
|
||||||
}
|
}
|
||||||
@@ -192,8 +198,8 @@ func (c *Conn) settle(module, id, fate string, delay time.Duration) error {
|
|||||||
case SettleNakAfter:
|
case SettleNakAfter:
|
||||||
return p.msg.NakWithDelay(delay)
|
return p.msg.NakWithDelay(delay)
|
||||||
}
|
}
|
||||||
seatPulls.mu.Lock()
|
c.pulls.mu.Lock()
|
||||||
seatPulls.held[id] = p // an unknown fate settles nothing
|
c.pulls.held[id] = p // an unknown fate settles nothing
|
||||||
seatPulls.mu.Unlock()
|
c.pulls.mu.Unlock()
|
||||||
return fmt.Errorf("a pulled message's fate is ack, nak, nak-after, term or progress, not %q", fate)
|
return fmt.Errorf("a pulled message's fate is ack, nak, nak-after, term or progress, not %q", fate)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,17 +19,22 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
first, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0)
|
// A pull that wants a message waits for it: the worker learns of a stored message after the publish is answered, so
|
||||||
|
// a pull that waits for nothing can find none yet on a loaded machine (design 47 H, H-A-363). A wait is a bound, not a
|
||||||
|
// measure: it ends at the delivery.
|
||||||
|
first, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second)
|
||||||
if err != nil || first == nil || string(first.Body) != `{"id":"a1"}` || first.Delivered != 1 {
|
if err != nil || first == nil || string(first.Body) != `{"id":"a1"}` || first.Delivered != 1 {
|
||||||
t.Fatalf("the first pull = %+v, %v", first, err)
|
t.Fatalf("the first pull = %+v, %v", first, err)
|
||||||
}
|
}
|
||||||
// One pulled, one still waiting on the stream: nothing was fetched ahead.
|
// One pulled and in hand, the other never delivered: nothing was fetched ahead. What is in hand is the worker's own
|
||||||
|
// count, set by the delivery itself; the count still waiting is the worker's figure of the stream, learnt later, so
|
||||||
|
// the second message's first delivery says it instead.
|
||||||
info, err := js.ConsumerInfo("SEAT_OPERATOR_CHANNEL", "SEAT_OPERATOR_CHANNEL_worker")
|
info, err := js.ConsumerInfo("SEAT_OPERATOR_CHANNEL", "SEAT_OPERATOR_CHANNEL_worker")
|
||||||
if err != nil || info.NumPending != 1 || info.NumAckPending != 1 {
|
if err != nil || info.NumAckPending != 1 {
|
||||||
t.Fatalf("after one pull: pending %d, in hand %d (%v); want 1 and 1", info.NumPending, info.NumAckPending, err)
|
t.Fatalf("after one pull: in hand %d (%v); want 1", info.NumAckPending, err)
|
||||||
}
|
}
|
||||||
second, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0)
|
second, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second)
|
||||||
if err != nil || second == nil || string(second.Body) != `{"id":"a2"}` {
|
if err != nil || second == nil || string(second.Body) != `{"id":"a2"}` || second.Delivered != 1 {
|
||||||
t.Fatalf("the second pull = %+v, %v", second, err)
|
t.Fatalf("the second pull = %+v, %v", second, err)
|
||||||
}
|
}
|
||||||
if none, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || none != nil {
|
if none, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || none != nil {
|
||||||
@@ -54,22 +59,23 @@ func TestAHolderPullsOneMessageWhenItHasRoom(t *testing.T) {
|
|||||||
if err := conn.SeatSettle("messenger", second.ID, bus.SettleNak); err != nil {
|
if err := conn.SeatSettle("messenger", second.ID, bus.SettleNak); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
again, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", time.Second)
|
again, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second)
|
||||||
if err != nil || again == nil || string(again.Body) != `{"id":"a2"}` || again.Delivered != 2 {
|
if err != nil || again == nil || string(again.Body) != `{"id":"a2"}` || again.Delivered != 2 {
|
||||||
t.Fatalf("the message handed back = %+v, %v", again, err)
|
t.Fatalf("the message handed back = %+v, %v", again, err)
|
||||||
}
|
}
|
||||||
// Issue 1748: a message settled with a delay is not given again at once, is after it, one delivery higher; a delay
|
// Issue 1748: a message settled with a delay is not given again at once, is after it, one delivery higher; a delay
|
||||||
// of 0 settles nothing.
|
// of 0 settles nothing. The delay is what the next pull must come within to see nothing, so it is a second, not a
|
||||||
|
// moment a loaded machine can spend between two calls.
|
||||||
if err := conn.SeatSettleAfter("messenger", again.ID, 0); err == nil {
|
if err := conn.SeatSettleAfter("messenger", again.ID, 0); err == nil {
|
||||||
t.Error("a delay of 0 was accepted")
|
t.Error("a delay of 0 was accepted")
|
||||||
}
|
}
|
||||||
if err := conn.SeatSettleAfter("messenger", again.ID, 300*time.Millisecond); err != nil {
|
if err := conn.SeatSettleAfter("messenger", again.ID, time.Second); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if early, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || early != nil {
|
if early, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 0); err != nil || early != nil {
|
||||||
t.Fatalf("a message given again after a delay came at once: %+v, %v", early, err)
|
t.Fatalf("a message given again after a delay came at once: %+v, %v", early, err)
|
||||||
}
|
}
|
||||||
late, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 2*time.Second)
|
late, err := conn.SeatPull("messenger", "SEAT_OPERATOR_CHANNEL_worker", 10*time.Second)
|
||||||
if err != nil || late == nil || late.Delivered != 3 {
|
if err != nil || late == nil || late.Delivered != 3 {
|
||||||
t.Fatalf("the message given again after its delay = %+v, %v", late, err)
|
t.Fatalf("the message given again after its delay = %+v, %v", late, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,11 +34,13 @@ func seatMesh(t *testing.T) (*mt.Mesh, *bus.Conn, nats.JetStreamContext) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// The workers' acknowledgement wait is wider than a test spends holding a message on a loaded machine: a message
|
||||||
|
// held past it is delivered again, and a pull that wants none would get it (design 47 H, H-A-363).
|
||||||
for stream, c := range map[string]*nats.ConsumerConfig{
|
for stream, c := range map[string]*nats.ConsumerConfig{
|
||||||
"SEAT_OPERATOR_CHANNEL": {Durable: "SEAT_OPERATOR_CHANNEL_worker", AckPolicy: nats.AckExplicitPolicy,
|
"SEAT_OPERATOR_CHANNEL": {Durable: "SEAT_OPERATOR_CHANNEL_worker", AckPolicy: nats.AckExplicitPolicy,
|
||||||
FilterSubject: "mesh.seat.operator-channel.accept.>", AckWait: 2 * time.Second},
|
FilterSubject: "mesh.seat.operator-channel.accept.>", AckWait: 30 * time.Second},
|
||||||
"SEAT_CHANNEL": {Durable: "SEAT_CHANNEL_TELEGRAM_worker", AckPolicy: nats.AckExplicitPolicy,
|
"SEAT_CHANNEL": {Durable: "SEAT_CHANNEL_TELEGRAM_worker", AckPolicy: nats.AckExplicitPolicy,
|
||||||
FilterSubject: "mesh.seat.channel.accept.*.telegram", AckWait: 2 * time.Second},
|
FilterSubject: "mesh.seat.channel.accept.*.telegram", AckWait: 30 * time.Second},
|
||||||
} {
|
} {
|
||||||
if _, err := js.AddConsumer(stream, c); err != nil {
|
if _, err := js.AddConsumer(stream, c); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -143,7 +145,7 @@ func TestTheHolderTakesItsWorkOnceAndAFailureComesBack(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer stop()
|
defer stop()
|
||||||
deadline := time.Now().Add(15 * time.Second)
|
deadline := time.Now().Add(mt.Bound(t))
|
||||||
for {
|
for {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
n := len(got)
|
n := len(got)
|
||||||
@@ -164,12 +166,21 @@ func TestTheHolderTakesItsWorkOnceAndAFailureComesBack(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// unansweredProof is the error the runner's drain hands for a call after its stop or cut at its bound.
|
||||||
|
type unansweredProof struct{}
|
||||||
|
|
||||||
|
func (unansweredProof) Error() string { return "answered nothing" }
|
||||||
|
func (unansweredProof) Unanswered() bool { return true }
|
||||||
|
|
||||||
func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
|
func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
|
||||||
_, conn, js := seatMesh(t)
|
_, conn, js := seatMesh(t)
|
||||||
stop, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(subject string, body json.RawMessage) (json.RawMessage, error) {
|
stop, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(subject string, body json.RawMessage) (json.RawMessage, error) {
|
||||||
if !strings.HasSuffix(subject, ".telegram") {
|
if !strings.HasSuffix(subject, ".telegram") {
|
||||||
return nil, errors.New("asked by another kind")
|
return nil, errors.New("asked by another kind")
|
||||||
}
|
}
|
||||||
|
if string(body) == `{"cut":true}` {
|
||||||
|
return nil, unansweredProof{}
|
||||||
|
}
|
||||||
return json.RawMessage(`{"linked":true}`), nil
|
return json.RawMessage(`{"linked":true}`), nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -184,6 +195,26 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
|
|||||||
if string(answer) != `{"linked":true}` {
|
if string(answer) != `{"linked":true}` {
|
||||||
t.Fatalf("the proof was answered %s", answer)
|
t.Fatalf("the proof was answered %s", answer)
|
||||||
}
|
}
|
||||||
|
// A proof arriving after the stop, or cut at the bound, is answered nothing (design 47 H2 §813 (12), H-A-369): the
|
||||||
|
// answerer handles proofs in order, so the first reply on one inbox after a cut proof and a whole one is the whole one's.
|
||||||
|
raw, err := nats.Connect(mt.URL(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer raw.Close()
|
||||||
|
inbox := nats.NewInbox()
|
||||||
|
replies, err := raw.SubscribeSync(inbox)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, body := range []string{`{"cut":true}`, `{"code":"123456"}`} {
|
||||||
|
if err := raw.PublishRequest("mesh.seat.intake.proof.code.telegram", inbox, []byte(body)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if first, err := replies.NextMsg(mt.Bound(t)); err != nil || string(first.Data) != `{"linked":true}` {
|
||||||
|
t.Fatalf("a proof cut at the stop was answered, or the whole one not: %v %v", first, err)
|
||||||
|
}
|
||||||
if _, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.desktop", json.RawMessage(`{}`)); err == nil {
|
if _, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.desktop", json.RawMessage(`{}`)); err == nil {
|
||||||
t.Error("a channel asked a proof as another kind")
|
t.Error("a channel asked a proof as another kind")
|
||||||
}
|
}
|
||||||
@@ -198,6 +229,26 @@ func TestAProofIsAskedAndAnsweredAndNeverKept(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 721/AC4: at its stop the runner takes its proofs' subscriptions down with the rest (design 47 H2 H-A-570 (1)): a proof
|
||||||
|
// after it meets no responders, never an answer of the old runner's, and a proof answered after it is not subscribed. The
|
||||||
|
// stop begins here while a second answerer of the proofs subscribes, between its subscription and its keeping: that one
|
||||||
|
// is taken down and refused too.
|
||||||
|
var once sync.Once
|
||||||
|
bus.SetSubscribedHook(conn, func(string) { once.Do(conn.StopAnswering) })
|
||||||
|
if _, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(string, json.RawMessage) (json.RawMessage, error) {
|
||||||
|
return json.RawMessage(`{"raced":true}`), nil
|
||||||
|
}); err == nil {
|
||||||
|
t.Error("a proof answerer that raced the stop was kept, want it refused")
|
||||||
|
}
|
||||||
|
if raw, err := conn.SeatProve("telegram", "mesh.seat.intake.proof.code.telegram", json.RawMessage(`{"code":"123456"}`)); err == nil ||
|
||||||
|
!strings.Contains(err.Error(), "nothing answers") {
|
||||||
|
t.Errorf("a proof after the stop was answered %s, %v; want no responders", raw, err)
|
||||||
|
}
|
||||||
|
if _, err := conn.SeatAnswer("messenger", "mesh.seat.intake.proof.code.*", func(string, json.RawMessage) (json.RawMessage, error) {
|
||||||
|
return nil, nil
|
||||||
|
}); err == nil {
|
||||||
|
t.Error("a proof answered after the stop was subscribed")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestAnAskerReadsItsOwnRecordAndNoOther(t *testing.T) {
|
func TestAnAskerReadsItsOwnRecordAndNoOther(t *testing.T) {
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
package bus
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Design 47 G §347, §59, §462: a sent object is read by the reference that carried it, from a sender's sent store only; a
|
|
||||||
// state's objects, and a reference that is none are refused before the bus is asked.
|
|
||||||
func TestSentGetRefusesWhatIsNoSentObjectsReference(t *testing.T) {
|
|
||||||
digest := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
|
||||||
for _, c := range []struct {
|
|
||||||
name string
|
|
||||||
req buscalls.ObjectsSentGetRequest
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{"no digest", buscalls.ObjectsSentGetRequest{Store: "m_sent-objects", Object: "o", Size: 3}, "named by the reference"},
|
|
||||||
{"a state's objects", buscalls.ObjectsSentGetRequest{Store: "m_asks-objects", Object: "o", Size: 3, Digest: digest}, "no sent store"},
|
|
||||||
} {
|
|
||||||
_, err := (&Conn{}).SentGet(c.req)
|
|
||||||
if err == nil || !strings.Contains(err.Error(), c.want) {
|
|
||||||
t.Errorf("%s: got %v, want an error containing %q", c.name, err, c.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+313
-147
@@ -7,12 +7,14 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
"git.novox.be/novox/mesh-sdk/go/pernode"
|
"github.com/nats-io/nats.go"
|
||||||
"github.com/nats-io/nats.go/jetstream"
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -38,11 +40,18 @@ type StateIssued struct {
|
|||||||
|
|
||||||
// StateEntry is one key's current value.
|
// StateEntry is one key's current value.
|
||||||
type StateEntry struct {
|
type StateEntry struct {
|
||||||
Key string `json:"key"`
|
Key string `json:"key"`
|
||||||
Value json.RawMessage `json:"value"`
|
// Value is none on a delete a page hands (Deleted).
|
||||||
|
Value json.RawMessage `json:"value,omitempty"`
|
||||||
Revision uint64 `json:"revision"`
|
Revision uint64 `json:"revision"`
|
||||||
// At is when the bus wrote this value (the entry's created time), as stdio.StateEntry.At reads it.
|
// At is when the bus wrote this value (the entry's created time), as stdio.StateEntry.At reads it.
|
||||||
At time.Time `json:"at,omitzero"`
|
At time.Time `json:"at,omitzero"`
|
||||||
|
// SeenAgain is set in a page on a value the bus wrote after the read reached its bucket, so a reader knows it replaces
|
||||||
|
// any value it holds for the key (design 47 H2 §779, H-A-382).
|
||||||
|
SeenAgain bool `json:"seen-again,omitempty"`
|
||||||
|
// Deleted is set in a page on a key's kept delete (a purge reads as one), handed at its sequence with no value, so a
|
||||||
|
// reader following pages removes the key and a deleted key never comes back alive (design 47 H2 §779, H-A-451 (1)).
|
||||||
|
Deleted bool `json:"deleted,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StateChange is one change a watch delivers: a key put, deleted, or expired (its own time to live, or the
|
// StateChange is one change a watch delivers: a key put, deleted, or expired (its own time to live, or the
|
||||||
@@ -90,20 +99,107 @@ func (c *Conn) issuedState(module, name string) (StateIssued, error) {
|
|||||||
"issued: %s (novox/hq ADR 0201, ADR 0595 §1)", module, name, issued)
|
"issued: %s (novox/hq ADR 0201, ADR 0595 §1)", module, name, issued)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// binding is one bucket's binding, or the bind in flight for it: the first asker binds, an asker meanwhile waits for
|
||||||
|
// that bind (done) instead of asking the bus again.
|
||||||
|
type binding struct {
|
||||||
|
done chan struct{}
|
||||||
|
kv jetstream.KeyValue
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// bucket is the state's binding, bound once for the process (design 47 H lead answers H-A-251): binding a bucket is a
|
||||||
|
// stream-info request on the bus, and asked before every get it made each read two answers. A bind that fails is not
|
||||||
|
// kept, so the next ask binds again.
|
||||||
func (c *Conn) bucket(ctx context.Context, s StateIssued) (jetstream.KeyValue, error) {
|
func (c *Conn) bucket(ctx context.Context, s StateIssued) (jetstream.KeyValue, error) {
|
||||||
|
c.bindMu.Lock()
|
||||||
|
b := c.bound[s.Bucket]
|
||||||
|
if b == nil {
|
||||||
|
if c.bound == nil {
|
||||||
|
c.bound = map[string]*binding{}
|
||||||
|
}
|
||||||
|
b = &binding{done: make(chan struct{})}
|
||||||
|
c.bound[s.Bucket] = b
|
||||||
|
c.bindMu.Unlock()
|
||||||
|
b.kv, b.err = c.bindBucket(ctx, s.Bucket)
|
||||||
|
if b.err != nil {
|
||||||
|
c.bindMu.Lock()
|
||||||
|
if c.bound[s.Bucket] == b {
|
||||||
|
delete(c.bound, s.Bucket)
|
||||||
|
}
|
||||||
|
c.bindMu.Unlock()
|
||||||
|
}
|
||||||
|
close(b.done)
|
||||||
|
} else {
|
||||||
|
c.bindMu.Unlock()
|
||||||
|
select {
|
||||||
|
case <-b.done:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if b.err != nil {
|
||||||
|
if errors.Is(b.err, jetstream.ErrBucketNotFound) {
|
||||||
|
return nil, fmt.Errorf("the state %q is issued and its bucket is not on the bus yet: the mesh "+
|
||||||
|
"creates it from the catalogue on its next raise", s.Name)
|
||||||
|
}
|
||||||
|
return nil, b.err
|
||||||
|
}
|
||||||
|
return b.kv, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) bindBucket(ctx context.Context, bucket string) (jetstream.KeyValue, error) {
|
||||||
|
if c.bind != nil {
|
||||||
|
return c.bind(ctx, bucket)
|
||||||
|
}
|
||||||
js, err := jetstream.New(c.nc)
|
js, err := jetstream.New(c.nc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
kv, err := js.KeyValue(ctx, s.Bucket)
|
return js.KeyValue(ctx, bucket)
|
||||||
if err != nil {
|
}
|
||||||
if errors.Is(err, jetstream.ErrBucketNotFound) {
|
|
||||||
return nil, fmt.Errorf("the state %q is issued and its bucket is not on the bus yet: the mesh "+
|
// unbind drops a bucket's binding the bus said is gone, when it is still the one kept, so the next ask binds again.
|
||||||
"creates it from the catalogue on its next raise", s.Name)
|
func (c *Conn) unbind(bucket string, kv jetstream.KeyValue) {
|
||||||
}
|
c.bindMu.Lock()
|
||||||
return nil, err
|
defer c.bindMu.Unlock()
|
||||||
|
b := c.bound[bucket]
|
||||||
|
if b == nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
return kv, nil
|
select {
|
||||||
|
case <-b.done: // bound: its kv is written
|
||||||
|
default:
|
||||||
|
return // bound again already, in flight
|
||||||
|
}
|
||||||
|
if b.kv == kv {
|
||||||
|
delete(c.bound, bucket)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// bucketGone is the bus saying a kept binding's bucket is not there (deleted, or deleted and created again): no stream of
|
||||||
|
// the name, or nobody answers on its subjects.
|
||||||
|
func bucketGone(err error) bool {
|
||||||
|
return errors.Is(err, jetstream.ErrStreamNotFound) || errors.Is(err, jetstream.ErrBucketNotFound) ||
|
||||||
|
errors.Is(err, jetstream.ErrNoStreamResponse) || errors.Is(err, nats.ErrNoResponders)
|
||||||
|
}
|
||||||
|
|
||||||
|
// inBucket does one act on the state's kept binding; when the bus says its bucket is gone, the binding is dropped, the
|
||||||
|
// bucket bound again once and the act done once more on the new binding (H-A-251).
|
||||||
|
func inBucket[T any](c *Conn, ctx context.Context, s StateIssued, do func(jetstream.KeyValue) (T, error)) (T, error) {
|
||||||
|
var none T
|
||||||
|
kv, err := c.bucket(ctx, s)
|
||||||
|
if err != nil {
|
||||||
|
return none, err
|
||||||
|
}
|
||||||
|
got, err := do(kv)
|
||||||
|
if !bucketGone(err) {
|
||||||
|
return got, err
|
||||||
|
}
|
||||||
|
c.unbind(s.Bucket, kv)
|
||||||
|
if kv, err = c.bucket(ctx, s); err != nil {
|
||||||
|
return none, err
|
||||||
|
}
|
||||||
|
return do(kv)
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkKey(key string) error {
|
func checkKey(key string) error {
|
||||||
@@ -128,11 +224,7 @@ func (c *Conn) StateGet(module, name, key string) (*StateEntry, error) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := c.bucket(ctx, s)
|
e, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueEntry, error) { return kv.Get(ctx, key) })
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
e, err := kv.Get(ctx, key)
|
|
||||||
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -142,7 +234,8 @@ func (c *Conn) StateGet(module, name, key string) (*StateEntry, error) {
|
|||||||
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
|
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// StatePage is the current values after a key, in key order, and the key to ask after for the rest.
|
// StatePage is one page of a read: the values the bus wrote after the cursor's sequence, in sequence order, and the
|
||||||
|
// opaque cursor that continues the read, empty at its end (design 47 H2 §779).
|
||||||
type StatePage struct {
|
type StatePage struct {
|
||||||
Entries []StateEntry `json:"entries"`
|
Entries []StateEntry `json:"entries"`
|
||||||
Next string `json:"next,omitempty"`
|
Next string `json:"next,omitempty"`
|
||||||
@@ -151,114 +244,181 @@ type StatePage struct {
|
|||||||
// StatePageBudget is the time a page spends reading when the asker names none: well under the 30 s a reader waits.
|
// StatePageBudget is the time a page spends reading when the asker names none: well under the 30 s a reader waits.
|
||||||
const StatePageBudget = 10 * time.Second
|
const StatePageBudget = 10 * time.Second
|
||||||
|
|
||||||
|
// StatePageMost is the most a page holds, in keys and values, whatever the asker names (design 47 H2 §779).
|
||||||
|
const StatePageMost = 768 << 10
|
||||||
|
|
||||||
// PageClock is the time a page's budget counts by, replaced by a test.
|
// PageClock is the time a page's budget counts by, replaced by a test.
|
||||||
var PageClock = time.Now
|
var PageClock = time.Now
|
||||||
|
|
||||||
// StatePage reads the values in key order after `after` in one pass, as many as fit maxBytes (each key and value),
|
// pageCursor is where a read stands, written into the opaque cursor a page answers as next: the bucket's node for a state
|
||||||
// stopping when budget is spent, at least one value, so a bundle asks one request for many values, where StateGet
|
// kept one bucket per node (empty for one bucket), the sequence of the last message handed, and mark, the bucket's last
|
||||||
// is one request each. Access is checked once and the bucket bound once. It is a read like StateGet: served to the
|
// sequence when the read reached it, after which every message is marked seen-again (H-A-382 (1)). The runner keeps
|
||||||
// owner and to every reader, and writes nothing. Next is the last key given when more follow.
|
// nothing per read: the cursor carries it all.
|
||||||
func (c *Conn) StatePage(module, name, after string, maxBytes int, budget time.Duration) (StatePage, error) {
|
type pageCursor struct {
|
||||||
|
node string
|
||||||
|
after, mark uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p pageCursor) String() string {
|
||||||
|
return fmt.Sprintf("%s.%d.%d", p.node, p.mark, p.after)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cursorOf(raw string) (pageCursor, error) {
|
||||||
|
if raw == "" {
|
||||||
|
return pageCursor{}, nil
|
||||||
|
}
|
||||||
|
parts := strings.Split(raw, ".")
|
||||||
|
var p pageCursor
|
||||||
|
var err1, err2 error
|
||||||
|
if len(parts) == 3 {
|
||||||
|
p.node = parts[0]
|
||||||
|
p.mark, err1 = strconv.ParseUint(parts[1], 10, 64)
|
||||||
|
p.after, err2 = strconv.ParseUint(parts[2], 10, 64)
|
||||||
|
}
|
||||||
|
if len(parts) != 3 || err1 != nil || err2 != nil {
|
||||||
|
return pageCursor{}, fmt.Errorf("%q is not a cursor a page answered: hand back the next of the page before", raw)
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StatePage reads one page of a state in the order the bus wrote it (design 47 H2 §779, H-A-254, H-A-382): from an ordered
|
||||||
|
// consumer starting after the cursor's sequence, never a replay of the bucket per page, each kept message once across the
|
||||||
|
// pages of a read, a key's older kept revisions included; a message written after the read reached its bucket comes
|
||||||
|
// marked seen-again, and a deleted key gets no entry. A page holds as many values as fit maxBytes (each key and value; at
|
||||||
|
// most StatePageMost) or the budget allows, at least one, and next continues the read, empty at its end. A state kept one
|
||||||
|
// bucket per node is read one node's bucket after another, in node order. It is a read like StateGet: served to the owner
|
||||||
|
// and to every reader, and writes nothing.
|
||||||
|
func (c *Conn) StatePage(module, name, cursor string, maxBytes int, budget time.Duration) (StatePage, error) {
|
||||||
s, err := c.issuedState(module, name)
|
s, err := c.issuedState(module, name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return StatePage{}, err
|
return StatePage{}, err
|
||||||
}
|
}
|
||||||
|
at, err := cursorOf(cursor)
|
||||||
|
if err != nil {
|
||||||
|
return StatePage{}, err
|
||||||
|
}
|
||||||
if budget <= 0 {
|
if budget <= 0 {
|
||||||
budget = StatePageBudget
|
budget = StatePageBudget
|
||||||
}
|
}
|
||||||
// The bind and the listing have a StateTimeout of their own, and each get another: the page's time budget is what
|
if maxBytes <= 0 || maxBytes > StatePageMost {
|
||||||
// ends a slow page (with Next), never a deadline spread over the whole of it.
|
maxBytes = StatePageMost
|
||||||
// ctx covers the bind and the listing alone; every bus request inside the loop takes each().
|
}
|
||||||
|
r := &pageRead{page: StatePage{Entries: []StateEntry{}}, maxBytes: maxBytes, budget: budget, started: PageClock()}
|
||||||
|
if !s.PerNode {
|
||||||
|
if at.node != "" {
|
||||||
|
return StatePage{}, fmt.Errorf("%q is not a cursor of %s's state %s: it names a node's bucket", cursor, module, name)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if _, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (struct{}, error) {
|
||||||
|
return struct{}{}, r.bucket(kv, at, cursor != "")
|
||||||
|
}); err != nil {
|
||||||
|
return StatePage{}, err
|
||||||
|
}
|
||||||
|
return r.page, nil
|
||||||
|
}
|
||||||
|
fam := c.family(s)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
nodes, err := fam.Nodes(ctx)
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
return StatePage{}, err
|
||||||
|
}
|
||||||
|
sort.Strings(nodes)
|
||||||
|
for _, node := range nodes {
|
||||||
|
if node < at.node {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
from, reached := pageCursor{node: node}, cursor != "" && node == at.node
|
||||||
|
if reached {
|
||||||
|
from = at
|
||||||
|
}
|
||||||
|
octx, ocancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
kv, err := fam.Open(octx, node)
|
||||||
|
if err == nil && kv != nil {
|
||||||
|
err = r.bucket(kv, from, reached)
|
||||||
|
}
|
||||||
|
ocancel()
|
||||||
|
if err != nil {
|
||||||
|
return StatePage{}, err
|
||||||
|
}
|
||||||
|
if r.page.Next != "" {
|
||||||
|
return r.page, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r.page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageRead is one page being filled.
|
||||||
|
type pageRead struct {
|
||||||
|
page StatePage
|
||||||
|
size int
|
||||||
|
maxBytes int
|
||||||
|
budget time.Duration
|
||||||
|
started time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// bucket reads one bucket after from into the page, until the bucket is read to its end (the page then goes on with the
|
||||||
|
// next bucket, or ends with no next) or the page is full (next set). reached says an earlier page of the read already
|
||||||
|
// reached the bucket, so from carries its mark.
|
||||||
|
func (r *pageRead) bucket(kv jetstream.KeyValue, from pageCursor, reached bool) error {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
each := func() (context.Context, context.CancelFunc) {
|
if !reached {
|
||||||
return context.WithTimeout(context.Background(), StateTimeout)
|
// The read reaches this bucket: what the bus writes into it from now on is marked seen-again (H-A-382 (1)).
|
||||||
}
|
status, err := kv.Status(ctx)
|
||||||
var keys []string
|
|
||||||
var get func(key string) (*StateEntry, error)
|
|
||||||
if s.PerNode {
|
|
||||||
fam := c.family(s)
|
|
||||||
if keys, err = fam.Keys(ctx); err != nil {
|
|
||||||
return StatePage{}, err
|
|
||||||
}
|
|
||||||
buckets := map[string]jetstream.KeyValue{} // each node's bucket bound once
|
|
||||||
get = func(key string) (*StateEntry, error) {
|
|
||||||
node, err := pernode.NodeOf(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
kv, bound := buckets[node]
|
|
||||||
if !bound {
|
|
||||||
octx, ocancel := each() // the open is a bus request in the loop: its own deadline, never ctx's
|
|
||||||
kv, err = fam.Open(octx, node)
|
|
||||||
ocancel()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
buckets[node] = kv
|
|
||||||
}
|
|
||||||
if kv == nil {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
gctx, gcancel := each()
|
|
||||||
defer gcancel()
|
|
||||||
e, err := kv.Get(gctx, key)
|
|
||||||
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
kv, err := c.bucket(ctx, s)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return StatePage{}, err
|
return err
|
||||||
}
|
}
|
||||||
if keys, err = keysOf(ctx, kv); err != nil {
|
bs, ok := status.(*jetstream.KeyValueBucketStatus)
|
||||||
return StatePage{}, err
|
if !ok || bs.StreamInfo() == nil {
|
||||||
}
|
return fmt.Errorf("%s's last sequence is not read, so no page of it can say what is seen again", kv.Bucket())
|
||||||
get = func(key string) (*StateEntry, error) {
|
|
||||||
gctx, gcancel := each()
|
|
||||||
defer gcancel()
|
|
||||||
e, err := kv.Get(gctx, key)
|
|
||||||
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &StateEntry{Key: e.Key(), Value: valueOf(e.Value()), Revision: e.Revision(), At: e.Created().UTC()}, nil
|
|
||||||
}
|
}
|
||||||
|
from.mark = bs.StreamInfo().State.LastSeq
|
||||||
}
|
}
|
||||||
sort.Strings(keys)
|
// Deletes are handed too: a page that dropped them would bring a deleted key with history back alive (H-A-451 (1)).
|
||||||
page := StatePage{Entries: []StateEntry{}}
|
opts := []jetstream.WatchOpt{jetstream.IncludeHistory()}
|
||||||
started := PageClock()
|
if from.after > 0 {
|
||||||
size := 0
|
opts = append(opts, jetstream.ResumeFromRevision(from.after+1))
|
||||||
for _, k := range keys {
|
}
|
||||||
if after != "" && k <= after {
|
w, err := kv.WatchAll(ctx, opts...)
|
||||||
continue
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = w.Stop()
|
||||||
|
// What the watch still hands after its stop is taken and dropped, so its delivery never blocks on a page read no more.
|
||||||
|
go func() {
|
||||||
|
for range w.Updates() {
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
var e jetstream.KeyValueEntry
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return fmt.Errorf("a page of %s is not read: %w", kv.Bucket(), ctx.Err())
|
||||||
|
case got, ok := <-w.Updates():
|
||||||
|
if !ok || got == nil {
|
||||||
|
return nil // the bucket is read to its end
|
||||||
|
}
|
||||||
|
e = got
|
||||||
}
|
}
|
||||||
if len(page.Entries) > 0 && PageClock().Sub(started) >= budget {
|
deleted := e.Operation() != jetstream.KeyValuePut
|
||||||
page.Next = page.Entries[len(page.Entries)-1].Key
|
var value json.RawMessage
|
||||||
break
|
if !deleted {
|
||||||
|
value = valueOf(e.Value())
|
||||||
}
|
}
|
||||||
e, err := get(k)
|
full := len(r.page.Entries) > 0 && (r.size+len(e.Key())+len(value) > r.maxBytes || PageClock().Sub(r.started) >= r.budget)
|
||||||
if err != nil {
|
if full {
|
||||||
return StatePage{}, err
|
r.page.Next = from.String()
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
if e == nil {
|
r.page.Entries = append(r.page.Entries, StateEntry{Key: e.Key(), Value: value, Revision: e.Revision(), At: e.Created().UTC(),
|
||||||
continue
|
SeenAgain: e.Revision() > from.mark, Deleted: deleted})
|
||||||
}
|
r.size += len(e.Key()) + len(value)
|
||||||
if size > 0 && size+len(k)+len(e.Value) > maxBytes {
|
from.after = e.Revision()
|
||||||
page.Next = page.Entries[len(page.Entries)-1].Key
|
|
||||||
break
|
|
||||||
}
|
|
||||||
page.Entries = append(page.Entries, *e)
|
|
||||||
size += len(k) + len(e.Value)
|
|
||||||
}
|
}
|
||||||
return page, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// StateKept is one value a bucket still keeps for a key: a put, or a delete (a purge reads as one).
|
// StateKept is one value a bucket still keeps for a key: a put, or a delete (a purge reads as one).
|
||||||
@@ -285,11 +445,9 @@ func (c *Conn) StateHistory(module, name, key string) ([]StateKept, error) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := c.bucket(ctx, s)
|
entries, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) ([]jetstream.KeyValueEntry, error) {
|
||||||
if err != nil {
|
return kv.History(ctx, key)
|
||||||
return nil, err
|
})
|
||||||
}
|
|
||||||
entries, err := kv.History(ctx, key)
|
|
||||||
kept := []StateKept{}
|
kept := []StateKept{}
|
||||||
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
if errors.Is(err, jetstream.ErrKeyNotFound) {
|
||||||
return kept, nil
|
return kept, nil
|
||||||
@@ -329,33 +487,48 @@ type StateInfo struct {
|
|||||||
|
|
||||||
// StateInfo reads a state's bucket's fill and caps. It is a read like StateGet: served to the owner and every reader.
|
// StateInfo reads a state's bucket's fill and caps. It is a read like StateGet: served to the owner and every reader.
|
||||||
func (c *Conn) StateInfo(module, name string) (*StateInfo, error) {
|
func (c *Conn) StateInfo(module, name string) (*StateInfo, error) {
|
||||||
s, err := c.issuedState(module, name)
|
status, info, err := c.bucketStatus(module, name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if s.PerNode {
|
|
||||||
return nil, perNodeRefusal(module, name, "fill")
|
|
||||||
}
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
|
||||||
defer cancel()
|
|
||||||
kv, err := c.bucket(ctx, s)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
status, err := kv.Status(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
b, ok := status.(*jetstream.KeyValueBucketStatus)
|
|
||||||
if !ok || b.StreamInfo() == nil {
|
|
||||||
return nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name)
|
|
||||||
}
|
|
||||||
info := b.StreamInfo()
|
|
||||||
return &StateInfo{State: name, Bucket: status.Bucket(), Bytes: info.State.Bytes, Keys: uint64(info.State.NumSubjects),
|
return &StateInfo{State: name, Bucket: status.Bucket(), Bytes: info.State.Bytes, Keys: uint64(info.State.NumSubjects),
|
||||||
MaxBytes: info.Config.MaxBytes, MaxValueBytes: info.Config.MaxMsgSize, History: status.History(),
|
MaxBytes: info.Config.MaxBytes, MaxValueBytes: info.Config.MaxMsgSize, History: status.History(),
|
||||||
TTLSeconds: int64(status.TTL() / time.Second), KeyTTL: info.Config.AllowMsgTTL && status.LimitMarkerTTL() > 0}, nil
|
TTLSeconds: int64(status.TTL() / time.Second), KeyTTL: info.Config.AllowMsgTTL && status.LimitMarkerTTL() > 0}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StateFill is a state's bucket's fill against its cap, buscalls.Fill's form: the messages it keeps, their bytes and its
|
||||||
|
// cap in bytes (0 is none). A put answers it, read from the bound stream's info once per put, since the bus's key-value
|
||||||
|
// put answers no figures of its own (design 47 H2 DMC-14, H-A-386).
|
||||||
|
func (c *Conn) StateFill(module, name string) (buscalls.Fill, error) {
|
||||||
|
_, info, err := c.bucketStatus(module, name)
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.Fill{}, err
|
||||||
|
}
|
||||||
|
return buscalls.Fill{Count: info.State.Msgs, Bytes: info.State.Bytes, MaxBytes: uint64(max(info.Config.MaxBytes, 0))}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// bucketStatus is a state's bucket's status and the info of the stream behind it.
|
||||||
|
func (c *Conn) bucketStatus(module, name string) (jetstream.KeyValueStatus, *jetstream.StreamInfo, error) {
|
||||||
|
s, err := c.issuedState(module, name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if s.PerNode {
|
||||||
|
return nil, nil, perNodeRefusal(module, name, "fill")
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
status, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (jetstream.KeyValueStatus, error) { return kv.Status(ctx) })
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
b, ok := status.(*jetstream.KeyValueBucketStatus)
|
||||||
|
if !ok || b.StreamInfo() == nil {
|
||||||
|
return nil, nil, fmt.Errorf("the bus answered no stream behind %s's state %s", module, name)
|
||||||
|
}
|
||||||
|
return status, b.StreamInfo(), nil
|
||||||
|
}
|
||||||
|
|
||||||
// StatePut writes one key, as the module, where the module keeps the state. It answers the revision.
|
// StatePut writes one key, as the module, where the module keeps the state. It answers the revision.
|
||||||
func (c *Conn) StatePut(module, name, key string, value json.RawMessage) (uint64, error) {
|
func (c *Conn) StatePut(module, name, key string, value json.RawMessage) (uint64, error) {
|
||||||
s, err := c.writable(module, name)
|
s, err := c.writable(module, name)
|
||||||
@@ -375,11 +548,7 @@ func (c *Conn) StatePut(module, name, key string, value json.RawMessage) (uint64
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := c.bucket(ctx, s)
|
return inBucket(c, ctx, s, func(kv jetstream.KeyValue) (uint64, error) { return kv.Put(ctx, key, value) })
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return kv.Put(ctx, key, value)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MinKeyTTL is the shortest time to live a key may be given: the bus counts a key's age in whole seconds (mesh-sdk
|
// MinKeyTTL is the shortest time to live a key may be given: the bus counts a key's age in whole seconds (mesh-sdk
|
||||||
@@ -449,11 +618,8 @@ func (c *Conn) StateDelete(module, name, key string) error {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := c.bucket(ctx, s)
|
_, err = inBucket(c, ctx, s, func(kv jetstream.KeyValue) (struct{}, error) { return struct{}{}, kv.Delete(ctx, key) })
|
||||||
if err != nil {
|
return err
|
||||||
return err
|
|
||||||
}
|
|
||||||
return kv.Delete(ctx, key)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// StateKeys is every key with a current value, sorted.
|
// StateKeys is every key with a current value, sorted.
|
||||||
@@ -467,11 +633,7 @@ func (c *Conn) StateKeys(module, name string) ([]string, error) {
|
|||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
kv, err := c.bucket(ctx, s)
|
return inBucket(c, ctx, s, func(kv jetstream.KeyValue) ([]string, error) { return keysOf(ctx, kv) })
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return keysOf(ctx, kv)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// keysOf is every key with a current value in one bucket, sorted.
|
// keysOf is every key with a current value in one bucket, sorted.
|
||||||
@@ -541,12 +703,16 @@ func (c *Conn) StateWatch(module, name, pattern string, deliver func(StateChange
|
|||||||
return c.perNodeWatch(module, s, pattern, deliver)
|
return c.perNodeWatch(module, s, pattern, deliver)
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
kv, err := c.bucket(ctx, s)
|
defer cancel()
|
||||||
cancel()
|
type watching struct{ stop func() }
|
||||||
|
w, err := inBucket(c, ctx, s, func(kv jetstream.KeyValue) (watching, error) {
|
||||||
|
stop, err := c.watchBucket(module, name, kv, filter, deliver)
|
||||||
|
return watching{stop}, err
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return c.watchBucket(module, name, kv, filter, deliver)
|
return w.stop, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// watchBucket is StateWatch over one bucket: the current values, then every change.
|
// watchBucket is StateWatch over one bucket: the current values, then every change.
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package bus_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// **On the bus, a read of a state is one answer: its bucket is bound once, and bound again when it was made afresh or
|
||||||
|
// is gone** (design 47 H lead answers H-A-251). The runtime asked the bucket's stream info before every get, so each
|
||||||
|
// read was two answers; a third of a night's bus flood came this way.
|
||||||
|
func TestAStateReadOnTheBusBindsItsBucketOnce(t *testing.T) {
|
||||||
|
conn, kv := owedWatcher(t)
|
||||||
|
const bucket = "mesh-delivery-assigner_pins"
|
||||||
|
if _, err := kv.Put("a", []byte(`{"v":1}`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
watcher, err := nats.Connect(mt.URL(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(watcher.Close)
|
||||||
|
// Each bind the runtime asks is heard onto a channel by the watcher's reader itself, so what the bus sent before a
|
||||||
|
// flush's answer is on it when the flush returns. A counter a callback raised was read before the callback ran, on a
|
||||||
|
// loaded machine, and counted one bind short (design 47 H, H-A-363).
|
||||||
|
infos := make(chan *nats.Msg, 16)
|
||||||
|
if _, err := watcher.ChanSubscribe("$JS.API.STREAM.INFO.KV_"+bucket, infos); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := watcher.Flush(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
read := func() {
|
||||||
|
t.Helper()
|
||||||
|
e, err := conn.StateGet("gitea", "mesh-delivery-assigner.pins", "a")
|
||||||
|
if err != nil || e == nil {
|
||||||
|
t.Fatalf("read: %+v, %v", e, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read()
|
||||||
|
read()
|
||||||
|
read()
|
||||||
|
if err := watcher.Flush(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := len(infos); got != 1 {
|
||||||
|
t.Fatalf("three reads asked the bucket's stream info %d times, want once", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The bucket deleted under the runtime: the read binds again, once, and says the bucket is not on the bus.
|
||||||
|
js, _ := watcher.JetStream()
|
||||||
|
if err := js.DeleteKeyValue(bucket); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = conn.StateGet("gitea", "mesh-delivery-assigner.pins", "a")
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "not on the bus yet") {
|
||||||
|
t.Fatalf("a read of a deleted bucket answered %v, want that its bucket is not on the bus", err)
|
||||||
|
}
|
||||||
|
// And made afresh: read again from the new bucket.
|
||||||
|
again, err := js.CreateKeyValue(&nats.KeyValueConfig{Bucket: bucket, History: 1})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := again.Put("a", []byte(`{"v":2}`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e, err := conn.StateGet("gitea", "mesh-delivery-assigner.pins", "a")
|
||||||
|
if err != nil || e == nil || string(e.Value) != `{"v":2}` {
|
||||||
|
t.Fatalf("a read of the bucket made afresh: %+v, %v", e, err)
|
||||||
|
}
|
||||||
|
read()
|
||||||
|
if err := watcher.Flush(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := len(infos); got != 3 {
|
||||||
|
t.Fatalf("the bucket's stream info was asked %d times in all, want 3: once, once more when it was gone, once when made afresh", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
package bus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
|
)
|
||||||
|
|
||||||
|
// boundKV is a bucket's binding in a test: it answers every get with one value, or, once gone, as the bus answers a
|
||||||
|
// binding whose bucket was deleted.
|
||||||
|
type boundKV struct {
|
||||||
|
jetstream.KeyValue
|
||||||
|
gone atomic.Bool
|
||||||
|
puts atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type boundEntry struct {
|
||||||
|
jetstream.KeyValueEntry
|
||||||
|
key string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e boundEntry) Key() string { return e.key }
|
||||||
|
func (e boundEntry) Value() []byte { return []byte(`{"v":1}`) }
|
||||||
|
func (e boundEntry) Revision() uint64 { return 1 }
|
||||||
|
func (boundEntry) Created() time.Time { return time.Time{} }
|
||||||
|
func (*boundKV) Bucket() string { return "gitea_pins" }
|
||||||
|
func (kv *boundKV) Get(_ context.Context, key string) (jetstream.KeyValueEntry, error) {
|
||||||
|
if kv.gone.Load() {
|
||||||
|
return nil, jetstream.ErrStreamNotFound
|
||||||
|
}
|
||||||
|
return boundEntry{key: key}, nil
|
||||||
|
}
|
||||||
|
func (kv *boundKV) Put(context.Context, string, []byte) (uint64, error) {
|
||||||
|
if kv.gone.Load() {
|
||||||
|
return 0, jetstream.ErrNoStreamResponse
|
||||||
|
}
|
||||||
|
return uint64(kv.puts.Add(1)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// **A state is bound once for the process, and bound again only when the bus says its bucket is gone** (design 47 H
|
||||||
|
// lead answers H-A-251): binding is a stream-info request on the bus, and asked before every get it made each read two
|
||||||
|
// answers on the bus.
|
||||||
|
func TestAStateIsBoundOnceAndBoundAgainWhenItsBucketIsGone(t *testing.T) {
|
||||||
|
setup := func() (*Conn, *atomic.Int32, *[]*boundKV) {
|
||||||
|
var binds atomic.Int32
|
||||||
|
var mu sync.Mutex
|
||||||
|
made := []*boundKV{}
|
||||||
|
c := &Conn{node: "anchor", issued: map[string]*Membership{"gitea": {Module: "gitea",
|
||||||
|
State: []StateIssued{{Name: "pins", Bucket: "gitea_pins", Writes: true}}}}}
|
||||||
|
c.bind = func(_ context.Context, bucket string) (jetstream.KeyValue, error) {
|
||||||
|
binds.Add(1)
|
||||||
|
if bucket != "gitea_pins" {
|
||||||
|
t.Errorf("bound %s, want gitea_pins", bucket)
|
||||||
|
}
|
||||||
|
kv := &boundKV{}
|
||||||
|
mu.Lock()
|
||||||
|
made = append(made, kv)
|
||||||
|
mu.Unlock()
|
||||||
|
return kv, nil
|
||||||
|
}
|
||||||
|
return c, &binds, &made
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("two reads, one bind", func(t *testing.T) {
|
||||||
|
c, binds, _ := setup()
|
||||||
|
for range 2 {
|
||||||
|
if e, err := c.StateGet("gitea", "pins", "a"); err != nil || e == nil || e.Key != "a" {
|
||||||
|
t.Fatalf("read: %+v, %v", e, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := c.StatePut("gitea", "pins", "a", json.RawMessage(`{"v":2}`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := binds.Load(); got != 1 {
|
||||||
|
t.Fatalf("two reads and a write bound the bucket %d times, want once", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("many readers at once, one bind", func(t *testing.T) {
|
||||||
|
c, binds, _ := setup()
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for range 16 {
|
||||||
|
wg.Go(func() {
|
||||||
|
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
if got := binds.Load(); got != 1 {
|
||||||
|
t.Fatalf("16 readers bound the bucket %d times, want once", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a bucket gone under the runner is bound again once", func(t *testing.T) {
|
||||||
|
c, binds, made := setup()
|
||||||
|
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
(*made)[0].gone.Store(true)
|
||||||
|
if e, err := c.StateGet("gitea", "pins", "a"); err != nil || e == nil {
|
||||||
|
t.Fatalf("the read after the bucket was made again: %+v, %v", e, err)
|
||||||
|
}
|
||||||
|
if got := binds.Load(); got != 2 {
|
||||||
|
t.Fatalf("the bucket was bound %d times, want twice (once more after it was gone)", got)
|
||||||
|
}
|
||||||
|
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
(*made)[1].gone.Store(true)
|
||||||
|
if _, err := c.StatePut("gitea", "pins", "a", json.RawMessage(`{"v":2}`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, puts := binds.Load(), (*made)[2].puts.Load(); got != 3 || puts != 1 {
|
||||||
|
t.Fatalf("a write to a gone bucket bound it %d times in all (want 3) and wrote %d times on the new binding (want 1)", got, puts)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("a bucket still gone after the bind again is said", func(t *testing.T) {
|
||||||
|
c, binds, made := setup()
|
||||||
|
if _, err := c.StateGet("gitea", "pins", "a"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
(*made)[0].gone.Store(true)
|
||||||
|
c.bind = func(context.Context, string) (jetstream.KeyValue, error) {
|
||||||
|
binds.Add(1)
|
||||||
|
return nil, jetstream.ErrBucketNotFound
|
||||||
|
}
|
||||||
|
if _, err := c.StateGet("gitea", "pins", "a"); err == nil {
|
||||||
|
t.Fatal("a read of a bucket no longer on the bus answered no error")
|
||||||
|
}
|
||||||
|
if got := binds.Load(); got != 2 {
|
||||||
|
t.Fatalf("the bucket was bound %d times, want twice: the bind again is once", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -69,6 +69,7 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
|
|||||||
|
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
var current, live []string
|
var current, live []string
|
||||||
|
heard := make(chan struct{}, 1)
|
||||||
stop, err := conn.StateWatch("mesh-provisioner", "mesh-host.composed", "", func(ch bus.StateChange) error {
|
stop, err := conn.StateWatch("mesh-provisioner", "mesh-host.composed", "", func(ch bus.StateChange) error {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
@@ -77,6 +78,10 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
|
|||||||
} else {
|
} else {
|
||||||
live = append(live, ch.Key)
|
live = append(live, ch.Key)
|
||||||
}
|
}
|
||||||
|
select {
|
||||||
|
case heard <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -98,7 +103,10 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
|
|||||||
if _, err := a.Put("a.m1.f5", []byte(`{"v":1}`)); err != nil {
|
if _, err := a.Put("a.m1.f5", []byte(`{"v":1}`)); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
mt.Until(t, func() error {
|
// Waited for as the watch hands each change over, not polled within a fixed five seconds: the new bucket is taken
|
||||||
|
// in on the bus's creation advisory, which a loaded machine delivers later (design 47 H, H-A-363). The bound only
|
||||||
|
// ends a watch that never hears it.
|
||||||
|
missing := func() error {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
got := strings.Join(append(append([]string(nil), current...), live...), ",")
|
got := strings.Join(append(append([]string(nil), current...), live...), ",")
|
||||||
@@ -108,5 +116,13 @@ func TestAPerNodeStateIsServedAcrossEveryNodesBucket(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
}
|
||||||
|
bound := time.After(mt.Bound(t))
|
||||||
|
for err := missing(); err != nil; err = missing() {
|
||||||
|
select {
|
||||||
|
case <-heard:
|
||||||
|
case <-bound:
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// **A watch whose current values take longer than the bound to hand over still holds** (novox/hq issue
|
// **A watch whose current values take longer than the bound to hand over still holds** (novox/hq issue
|
||||||
// 1726). The gitea module watches the checker's owed: one key per pull request head, each a round trip
|
// 1726). The gitea module watches another module's state (the assigner's pins stand for it): one key per pull request head, each a round trip
|
||||||
// to the bundle. With a few hundred keys the hand-over outlasted StateTimeout at every attempt, the
|
// to the bundle. With a few hundred keys the hand-over outlasted StateTimeout at every attempt, the
|
||||||
// watch was refused, and the newest keys, handed over last, never reached mesh/check: a group's passing
|
// watch was refused, and the newest keys, handed over last, never reached mesh/check: a group's passing
|
||||||
// verdict was never written on its members' heads. The bound is on progress: a watch fails only when
|
// verdict was never written on its members' heads. The bound is on progress: a watch fails only when
|
||||||
@@ -45,7 +45,7 @@ func TestAWatchHoldsWhileItsCurrentValuesKeepArriving(t *testing.T) {
|
|||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
var current, live []string
|
var current, live []string
|
||||||
// Each value takes 40 ms to be taken: 33 values take about 1.3 s, three times the bound.
|
// Each value takes 40 ms to be taken: 33 values take about 1.3 s, three times the bound.
|
||||||
stop, err := conn.StateWatch("gitea", "mesh-delivery-checker.owed", "", func(ch bus.StateChange) error {
|
stop, err := conn.StateWatch("gitea", "mesh-delivery-assigner.pins", "", func(ch bus.StateChange) error {
|
||||||
if ch.Current {
|
if ch.Current {
|
||||||
time.Sleep(40 * time.Millisecond)
|
time.Sleep(40 * time.Millisecond)
|
||||||
}
|
}
|
||||||
@@ -87,6 +87,74 @@ func TestAWatchHoldsWhileItsCurrentValuesKeepArriving(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
// **A watch given up, or stopped, hands over nothing more** (issue 774). The runtime's watch stopped its watcher
|
||||||
|
// when the current values did not arrive within the bound, but the watcher still held values, and its goroutine
|
||||||
|
// went on handing them over: to a watch id the bundle no longer held (on the provisioner, 51 failed watches were
|
||||||
|
// followed by 1257 orphan changes). Each row blocks the bundle on its first value, gives the watch up, lets the
|
||||||
|
// bundle go and counts what it is still handed.
|
||||||
|
t.Run("AWatchGivenUpHandsOverNothingMore", func(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
refused bool // the bound gives it up, or the caller stops it
|
||||||
|
}{
|
||||||
|
{"refused at the bound", true},
|
||||||
|
{"stopped by its caller", false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
was := bus.StateTimeout
|
||||||
|
bus.StateTimeout = 300 * time.Millisecond
|
||||||
|
t.Cleanup(func() { bus.StateTimeout = was })
|
||||||
|
conn, kv := owedWatcher(t)
|
||||||
|
put := func(i int) {
|
||||||
|
if _, err := kv.Put(fmt.Sprintf("novox/hq.%d.%040x.status=mesh/check", i+1, i), []byte(`{"v":1}`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tc.refused {
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
put(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var calls atomic.Int32
|
||||||
|
first := make(chan struct{}, 1)
|
||||||
|
release := make(chan struct{})
|
||||||
|
deliver := func(ch bus.StateChange) error {
|
||||||
|
if calls.Add(1) == 1 {
|
||||||
|
first <- struct{}{}
|
||||||
|
<-release
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var stop func()
|
||||||
|
if tc.refused {
|
||||||
|
if _, err := conn.StateWatch("gitea", "mesh-delivery-assigner.pins", "", deliver); err == nil {
|
||||||
|
t.Fatal("the watch whose bundle took nothing was not refused")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if stop, err = conn.StateWatch("gitea", "mesh-delivery-assigner.pins", "", deliver); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
put(i)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-first:
|
||||||
|
case <-time.After(mt.Bound(t)):
|
||||||
|
t.Fatal("the bundle was handed no change")
|
||||||
|
}
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
// Let the watcher's server side deliver what it held, then free the bundle.
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
close(release)
|
||||||
|
time.Sleep(500 * time.Millisecond)
|
||||||
|
if n := calls.Load(); n != 1 {
|
||||||
|
t.Fatalf("the bundle was handed %d changes of a watch given up, want 1 (the one in hand)", n)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// A watch whose bundle takes nothing for longer than the bound is still refused, so a bundle that hangs
|
// A watch whose bundle takes nothing for longer than the bound is still refused, so a bundle that hangs
|
||||||
@@ -105,14 +173,14 @@ func TestAWatchIsRefusedWhenNoCurrentValueIsTakenWithinTheBound(t *testing.T) {
|
|||||||
release := make(chan struct{})
|
release := make(chan struct{})
|
||||||
t.Cleanup(func() { close(release) })
|
t.Cleanup(func() { close(release) })
|
||||||
began := time.Now()
|
began := time.Now()
|
||||||
_, err := conn.StateWatch("gitea", "mesh-delivery-checker.owed", "", func(bus.StateChange) error {
|
_, err := conn.StateWatch("gitea", "mesh-delivery-assigner.pins", "", func(bus.StateChange) error {
|
||||||
<-release
|
<-release
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err == nil || !strings.Contains(err.Error(), "did not arrive in") {
|
if err == nil || !strings.Contains(err.Error(), "did not arrive in") {
|
||||||
t.Fatalf("a watch whose first value was never taken: want refused, got %v", err)
|
t.Fatalf("a watch whose first value was never taken: want refused, got %v", err)
|
||||||
}
|
}
|
||||||
if took := time.Since(began); took > 3*time.Second {
|
if took := time.Since(began); took > was/2 { // 1754/AC4: at the bound it was set, half the default StateTimeout it replaced
|
||||||
t.Fatalf("the refusal took %s, far past the bound", took)
|
t.Fatalf("the refusal took %s, far past the bound", took)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -161,16 +229,16 @@ func TestAMembershipTheGrantsPartWroteWrappedIsServed(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// owedWatcher is the gitea module's view of the checker's owed: the bucket, and a runtime connection
|
// owedWatcher is the gitea module's view of another module's state: the bucket, and a runtime connection
|
||||||
// that serves gitea with the owed issued for reading.
|
// that serves gitea with that state issued for reading.
|
||||||
func owedWatcher(t *testing.T) (*bus.Conn, interface {
|
func owedWatcher(t *testing.T) (*bus.Conn, interface {
|
||||||
Put(string, []byte) (uint64, error)
|
Put(string, []byte) (uint64, error)
|
||||||
}) {
|
}) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
mesh := mt.New(t)
|
mesh := mt.New(t)
|
||||||
kv := mesh.Bucket(t, "mesh-delivery-checker_owed")
|
kv := mesh.Bucket(t, "mesh-delivery-assigner_pins")
|
||||||
gitea := mt.MembershipOf("gitea", "anchor", false, nil)
|
gitea := mt.MembershipOf("gitea", "anchor", false, nil)
|
||||||
gitea.State = []bus.StateIssued{{Name: "mesh-delivery-checker.owed", Bucket: "mesh-delivery-checker_owed"}}
|
gitea.State = []bus.StateIssued{{Name: "mesh-delivery-assigner.pins", Bucket: "mesh-delivery-assigner_pins"}}
|
||||||
mesh.Issue(t, gitea)
|
mesh.Issue(t, gitea)
|
||||||
conn, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "anchor"})
|
conn, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "anchor"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -187,72 +255,3 @@ func owedWatcher(t *testing.T) (*bus.Conn, interface {
|
|||||||
})
|
})
|
||||||
return conn, kv
|
return conn, kv
|
||||||
}
|
}
|
||||||
|
|
||||||
// **A watch given up, or stopped, hands over nothing more** (issue 774). The runtime's watch stopped its watcher
|
|
||||||
// when the current values did not arrive within the bound, but the watcher still held values, and its goroutine
|
|
||||||
// went on handing them over: to a watch id the bundle no longer held (on the provisioner, 51 failed watches were
|
|
||||||
// followed by 1257 orphan changes). Each row blocks the bundle on its first value, gives the watch up, lets the
|
|
||||||
// bundle go and counts what it is still handed.
|
|
||||||
func TestAWatchGivenUpHandsOverNothingMore(t *testing.T) {
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
refused bool // the bound gives it up, or the caller stops it
|
|
||||||
}{
|
|
||||||
{"refused at the bound", true},
|
|
||||||
{"stopped by its caller", false},
|
|
||||||
} {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
was := bus.StateTimeout
|
|
||||||
bus.StateTimeout = 300 * time.Millisecond
|
|
||||||
t.Cleanup(func() { bus.StateTimeout = was })
|
|
||||||
conn, kv := owedWatcher(t)
|
|
||||||
put := func(i int) {
|
|
||||||
if _, err := kv.Put(fmt.Sprintf("novox/hq.%d.%040x.status=mesh/check", i+1, i), []byte(`{"v":1}`)); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if tc.refused {
|
|
||||||
for i := 0; i < 4; i++ {
|
|
||||||
put(i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var calls atomic.Int32
|
|
||||||
first := make(chan struct{}, 1)
|
|
||||||
release := make(chan struct{})
|
|
||||||
deliver := func(ch bus.StateChange) error {
|
|
||||||
if calls.Add(1) == 1 {
|
|
||||||
first <- struct{}{}
|
|
||||||
<-release
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
var stop func()
|
|
||||||
if tc.refused {
|
|
||||||
if _, err := conn.StateWatch("gitea", "mesh-delivery-checker.owed", "", deliver); err == nil {
|
|
||||||
t.Fatal("the watch whose bundle took nothing was not refused")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
var err error
|
|
||||||
if stop, err = conn.StateWatch("gitea", "mesh-delivery-checker.owed", "", deliver); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
for i := 0; i < 4; i++ {
|
|
||||||
put(i)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-first:
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("the bundle was handed no change")
|
|
||||||
}
|
|
||||||
stop()
|
|
||||||
}
|
|
||||||
// Let the watcher's server side deliver what it held, then free the bundle.
|
|
||||||
time.Sleep(300 * time.Millisecond)
|
|
||||||
close(release)
|
|
||||||
time.Sleep(500 * time.Millisecond)
|
|
||||||
if n := calls.Load(); n != 1 {
|
|
||||||
t.Fatalf("the bundle was handed %d changes of a watch given up, want 1 (the one in hand)", n)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package bus
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -10,6 +11,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/nats-io/nats.go/jetstream"
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/process"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A module's own stream, as the runtime publishes to it and hears it (novox/hq ADR 0363 §8, issue 725).
|
// A module's own stream, as the runtime publishes to it and hears it (novox/hq ADR 0363 §8, issue 725).
|
||||||
@@ -29,11 +33,54 @@ type StreamIssued struct {
|
|||||||
Subject string `json:"subject"`
|
Subject string `json:"subject"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// HeardIssued is one module stream an assignment hears: the stream and the durable consumer on it the
|
// HeardIssued is one stream an assignment hears, EVENTS like any other: the stream, the module's durable consumer the
|
||||||
// runtime binds. The consumer is the mesh's to make, to filter and to delete.
|
// runner's twin on it is named from, and, from a grants part that writes it, the twin's whole spec (mesh-sdk's
|
||||||
type HeardIssued struct {
|
// membership.HeardIssued; design 47 H2, H-A-472 seventh and eighth addenda). An entry with a spec is created or updated
|
||||||
Stream string `json:"stream"`
|
// from it by the runner at a child's first subscribe; one without, an older writer's, is bound by name as before.
|
||||||
Consumer string `json:"consumer"`
|
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
|
// eventSubject is where a module's event is published: on the subject of the first of its membership's
|
||||||
@@ -92,31 +139,42 @@ type hearing struct {
|
|||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
stopped bool
|
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
|
// 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.
|
// another time, and a loop bound to the old one is not reading the new one.
|
||||||
made map[HeardIssued]time.Time
|
made map[heardKey]time.Time
|
||||||
said map[HeardIssued]bool
|
said map[heardKey]bool
|
||||||
// why is the last error the bus gave a consumer's loop, said when the loop ends on it.
|
// 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.
|
// Guarded by whyMu, not mu: the bus hands errors from its own goroutines, possibly while mu is held.
|
||||||
whyMu sync.Mutex
|
whyMu sync.Mutex
|
||||||
why map[HeardIssued]error
|
why map[heardKey]error
|
||||||
kick chan struct{}
|
kick chan struct{}
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
unhear func()
|
unhear func()
|
||||||
|
|
||||||
|
// rebind, nakDelay and heartbeat are RebindEvery, NakDelay and EventHeartbeat as they stood when the hearing was
|
||||||
|
// made: its loops outlive the call that started them, so they never read a setting again, which a test may set
|
||||||
|
// back as it ends (design 47 H, H-A-363: a goroutine outliving its settings).
|
||||||
|
rebind, nakDelay, heartbeat time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func newHearing(c *Conn, js jetstream.JetStream, module string, deliver func(Envelope) error) *hearing {
|
func newHearing(c *Conn, js jetstream.JetStream, module string, deliver func(Envelope) error) *hearing {
|
||||||
return &hearing{c: c, js: js, module: module, deliver: deliver,
|
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{})}
|
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
|
// bind reads the runner's twin of one heard entry, made first from the entry's spec where it carries one (makeTwin), else
|
||||||
// the loop afterwards are handed to onErr, when given.
|
// bound by name, and on failure says what it was doing. Errors the bus gives the loop afterwards are handed to onErr, when
|
||||||
func (h *hearing) bind(stream, durable string, onErr func(error)) (jetstream.ConsumeContext, time.Time, string, error) {
|
// 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)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
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)
|
consumer, err := h.js.Consumer(ctx, stream, durable)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, time.Time{}, "binding", err
|
return nil, time.Time{}, "binding", err
|
||||||
@@ -129,7 +187,10 @@ func (h *hearing) bind(stream, durable string, onErr func(error)) (jetstream.Con
|
|||||||
if onErr != nil {
|
if onErr != nil {
|
||||||
opts = append(opts, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { onErr(err) }))
|
opts = append(opts, jetstream.ConsumeErrHandler(func(_ jetstream.ConsumeContext, err error) { onErr(err) }))
|
||||||
}
|
}
|
||||||
reading, err := consumer.Consume(h.handle, opts...)
|
// Claimed through the SDK's one guard as it is pulled (design 47 H, H-A-196, H-A-197): a second pull loop on a durable
|
||||||
|
// this process pulls already would take every other event from the first, so it is refused here, loud. The claim is
|
||||||
|
// released as the loop is stopped, or once the bus ended it, before its Closed is closed.
|
||||||
|
reading, err := process.ConsumeOnce(consumer, "the tool runner's hearing of "+h.module, h.handle, opts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, time.Time{}, "reading", err
|
return nil, time.Time{}, "reading", err
|
||||||
}
|
}
|
||||||
@@ -153,7 +214,7 @@ func (h *hearing) handle(msg jetstream.Msg) {
|
|||||||
done, stopped := make(chan struct{}), make(chan struct{})
|
done, stopped := make(chan struct{}), make(chan struct{})
|
||||||
go func() {
|
go func() {
|
||||||
defer close(stopped)
|
defer close(stopped)
|
||||||
tick := time.NewTicker(EventHeartbeat)
|
tick := time.NewTicker(h.heartbeat)
|
||||||
defer tick.Stop()
|
defer tick.Stop()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -181,7 +242,7 @@ func (h *hearing) handle(msg jetstream.Msg) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = msg.NakWithDelay(NakDelay)
|
_ = msg.NakWithDelay(h.nakDelay)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
_ = msg.Ack()
|
_ = msg.Ack()
|
||||||
@@ -198,7 +259,7 @@ func (h *hearing) start() {
|
|||||||
h.nudge()
|
h.nudge()
|
||||||
})
|
})
|
||||||
go func() {
|
go func() {
|
||||||
tick := time.NewTicker(RebindEvery)
|
tick := time.NewTicker(h.rebind)
|
||||||
defer tick.Stop()
|
defer tick.Stop()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -213,7 +274,7 @@ func (h *hearing) start() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// forget drops the last error a consumer's loop was given.
|
// 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()
|
h.whyMu.Lock()
|
||||||
delete(h.why, heard)
|
delete(h.why, heard)
|
||||||
h.whyMu.Unlock()
|
h.whyMu.Unlock()
|
||||||
@@ -249,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
|
// 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.
|
// 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)
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
consumer, err := h.js.Consumer(ctx, heard.Stream, heard.Consumer)
|
consumer, err := h.js.Consumer(ctx, heard.Stream, heard.Consumer)
|
||||||
@@ -265,11 +326,14 @@ func (h *hearing) replaced(heard HeardIssued) bool {
|
|||||||
|
|
||||||
// reconcile makes what is bound what the module's membership names now.
|
// reconcile makes what is bound what the module's membership names now.
|
||||||
func (h *hearing) reconcile() {
|
func (h *hearing) reconcile() {
|
||||||
want := map[HeardIssued]bool{}
|
want := map[heardKey]HeardIssued{}
|
||||||
if m := h.c.Membership(h.module); m != nil {
|
// 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 {
|
for _, heard := range m.Hears {
|
||||||
if heard.Stream != "" && heard.Consumer != "" {
|
// EVENTS is its caller's, bound beside the hearing (ConsumeAsBeatingWhen).
|
||||||
want[heard] = true
|
if heard.Stream != "" && heard.Consumer != "" && heard.Stream != EventsStream {
|
||||||
|
// The runner's own durable beside the program's (A-397).
|
||||||
|
want[heardKey{heard.Stream, heard.Consumer + ToolsSuffix}] = heard
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,7 +343,7 @@ func (h *hearing) reconcile() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
for heard, reading := range h.bound {
|
for heard, reading := range h.bound {
|
||||||
if !want[heard] {
|
if _, still := want[heard]; !still {
|
||||||
reading.Stop()
|
reading.Stop()
|
||||||
delete(h.bound, heard)
|
delete(h.bound, heard)
|
||||||
delete(h.made, heard)
|
delete(h.made, heard)
|
||||||
@@ -288,7 +352,7 @@ func (h *hearing) reconcile() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
for heard := range h.said {
|
for heard := range h.said {
|
||||||
if !want[heard] {
|
if _, still := want[heard]; !still {
|
||||||
delete(h.said, heard)
|
delete(h.said, heard)
|
||||||
h.forget(heard)
|
h.forget(heard)
|
||||||
}
|
}
|
||||||
@@ -327,7 +391,7 @@ func (h *hearing) reconcile() {
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
missing := make([]HeardIssued, 0, len(want))
|
missing := make([]heardKey, 0, len(want))
|
||||||
for heard := range want {
|
for heard := range want {
|
||||||
if h.bound[heard] == nil {
|
if h.bound[heard] == nil {
|
||||||
missing = append(missing, heard)
|
missing = append(missing, heard)
|
||||||
@@ -337,7 +401,7 @@ func (h *hearing) reconcile() {
|
|||||||
for _, heard := range missing {
|
for _, heard := range missing {
|
||||||
heard := heard
|
heard := heard
|
||||||
h.forget(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.whyMu.Lock()
|
||||||
h.why[heard] = err
|
h.why[heard] = err
|
||||||
h.whyMu.Unlock()
|
h.whyMu.Unlock()
|
||||||
@@ -346,7 +410,7 @@ func (h *hearing) reconcile() {
|
|||||||
// Said once, not at every attempt; said again when it is bound.
|
// Said once, not at every attempt; said again when it is bound.
|
||||||
if !h.said[heard] {
|
if !h.said[heard] {
|
||||||
h.c.Logf("[mesh-tools] %s does not hear %s yet: %s its consumer %s failed: %v; tried again every %s",
|
h.c.Logf("[mesh-tools] %s does not hear %s yet: %s its consumer %s failed: %v; tried again every %s",
|
||||||
h.module, heard.Stream, doing, heard.Consumer, err, RebindEvery)
|
h.module, heard.Stream, doing, heard.Consumer, err, h.rebind)
|
||||||
h.said[heard] = true
|
h.said[heard] = true
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
package bus
|
package bus
|
||||||
|
|
||||||
import "testing"
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
|
)
|
||||||
|
|
||||||
// novox/hq ADR 0363 §2, §3: an event goes to the stream whose pattern carries it, as the bus matches subjects.
|
// novox/hq ADR 0363 §2, §3: an event goes to the stream whose pattern carries it, as the bus matches subjects.
|
||||||
func TestAnEventFallsUnderAStreamsPatternAsTheBusMatchesIt(t *testing.T) {
|
func TestAnEventFallsUnderAStreamsPatternAsTheBusMatchesIt(t *testing.T) {
|
||||||
@@ -22,6 +28,24 @@ func TestAnEventFallsUnderAStreamsPatternAsTheBusMatchesIt(t *testing.T) {
|
|||||||
t.Errorf("%q under %q: %v, want %v", c.event, c.pattern, got, c.want)
|
t.Errorf("%q under %q: %v, want %v", c.event, c.pattern, got, c.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Design 47 G §347, §59, §462: a sent object is read by the reference that carried it, from a sender's sent store only; a
|
||||||
|
// state's objects, and a reference that is none are refused before the bus is asked.
|
||||||
|
t.Run("SentGetRefusesWhatIsNoSentObjectsReference", func(t *testing.T) {
|
||||||
|
digest := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||||
|
for _, c := range []struct {
|
||||||
|
name string
|
||||||
|
req buscalls.ObjectsSentGetRequest
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"no digest", buscalls.ObjectsSentGetRequest{Store: "m_sent-objects", Object: "o", Size: 3}, "named by the reference"},
|
||||||
|
{"a state's objects", buscalls.ObjectsSentGetRequest{Store: "m_asks-objects", Object: "o", Size: 3, Digest: digest}, "no sent store"},
|
||||||
|
} {
|
||||||
|
_, err := (&Conn{}).SentGet(c.req)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||||
|
t.Errorf("%s: got %v, want an error containing %q", c.name, err, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// A membership naming no stream publishes every event on EVENTS, exactly as before (issue 725).
|
// A membership naming no stream publishes every event on EVENTS, exactly as before (issue 725).
|
||||||
@@ -46,3 +70,19 @@ func TestAnEventNoStreamCarriesIsPublishedOnEvents(t *testing.T) {
|
|||||||
t.Errorf("a stream's event reaches its consumer as %q, not as on EVENTS", got)
|
t.Errorf("a stream's event reaches its consumer as %q, not as on EVENTS", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Design 47 H lead answers H-A-227: an object store's fill is the figures the bus keeps for its stream, its live
|
||||||
|
// subjects as the count, never a count of its descriptions: a store holding twenty thousand messages, deleted chunks'
|
||||||
|
// leftovers among them, answers its bytes, its cap and its four live subjects.
|
||||||
|
func TestAnObjectStoresFillIsItsStreamsOwnFigures(t *testing.T) {
|
||||||
|
info := &jetstream.StreamInfo{
|
||||||
|
Config: jetstream.StreamConfig{MaxBytes: 8 << 30},
|
||||||
|
State: jetstream.StreamState{Msgs: 20653, Bytes: 1 << 30, NumSubjects: 4, FirstSeq: 9, LastSeq: 20661},
|
||||||
|
}
|
||||||
|
if got, want := objectsFillOf(info), (buscalls.Fill{Count: 4, Bytes: 1 << 30, MaxBytes: 8 << 30}); got != want {
|
||||||
|
t.Fatalf("fill %+v, want %+v", got, want)
|
||||||
|
}
|
||||||
|
if got := objectsFillOf(&jetstream.StreamInfo{State: jetstream.StreamState{Bytes: 7}}); got != (buscalls.Fill{Bytes: 7}) {
|
||||||
|
t.Fatalf("a store with no cap and no live subject: fill %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,11 +4,15 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
)
|
)
|
||||||
@@ -59,7 +63,7 @@ func TestAnEventADeclaredStreamCarriesIsPublishedOnItsSubjectAlone(t *testing.T)
|
|||||||
if got != "mesh.stream.mail.event.mail.home.message.added" {
|
if got != "mesh.stream.mail.event.mail.home.message.added" {
|
||||||
t.Errorf("published on %s", got)
|
t.Errorf("published on %s", got)
|
||||||
}
|
}
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatal("the event did not land on its stream's subject")
|
t.Fatal("the event did not land on its stream's subject")
|
||||||
}
|
}
|
||||||
if err := conn.PublishAs("mail", bus.Envelope{Key: "status", Body: json.RawMessage(`{}`)}); err != nil {
|
if err := conn.PublishAs("mail", bus.Envelope{Key: "status", Body: json.RawMessage(`{}`)}); err != nil {
|
||||||
@@ -258,6 +262,34 @@ func TestAConsumerNamedBeforeItExistsIsBoundOnceItDoes(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// A second pull loop on the durable the runner pulls is refused, naming it and both binders (design 47 H, H-A-196,
|
||||||
|
// H-A-197); a re-serve that stops its loop first binds again without a refusal, its module stream's durable too.
|
||||||
|
if _, err := conn.ConsumeAs("reader", func(bus.Envelope) error { return nil }); err == nil ||
|
||||||
|
!strings.Contains(err.Error(), "pulled in this process already") || !strings.Contains(err.Error(), "anchor_reader") ||
|
||||||
|
strings.Count(err.Error(), "the tool runner's hearing of reader") != 2 {
|
||||||
|
t.Fatalf("a second pull loop on the durable the runner pulls was not refused naming it and both binders: %v", err)
|
||||||
|
}
|
||||||
|
stop()
|
||||||
|
again, err := conn.ConsumeAs("reader", func(env bus.Envelope) error {
|
||||||
|
mu.Lock()
|
||||||
|
heard[env.Key]++
|
||||||
|
mu.Unlock()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("the re-serve was refused after its old loop stopped: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(again)
|
||||||
|
mesh.Emit(t, "mesh.stream.mail.event.mail.home.message.added", map[string]any{})
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if heard["mail.mail.home.message.added"] != 2 {
|
||||||
|
return fmt.Errorf("after the re-serve heard %v", heard)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// novox/hq ADR 0363 §6 (issue 725): a consumer the controller deletes and makes again under the same name, its
|
// novox/hq ADR 0363 §6 (issue 725): a consumer the controller deletes and makes again under the same name, its
|
||||||
@@ -340,3 +372,117 @@ func (l *syncLogs) Has(fragment string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package bus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||||
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SubscribeNew hears one event, named `<emitter>.<event>`, from the next message on, on an ordered consumer of its own on each
|
||||||
|
// stream that carries it, and hands every message to deliver as the envelope a module sees. The subjects the name lands on are
|
||||||
|
// mesh-sdk's one rule (buscompose.EventSubjects, design 47 G §559, A-153), so a name with a wildcard is refused, naming the rule;
|
||||||
|
// a name no stream on the bus carries is an error, never a subscription that hears nothing. stop ends every consumer.
|
||||||
|
func (c *Conn) SubscribeNew(name string, deliver func(json.RawMessage) error) (func(), error) {
|
||||||
|
subjects, err := buscompose.EventSubjects(name, "")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
js, err := c.JetStream()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), StateTimeout)
|
||||||
|
defer cancel()
|
||||||
|
// The streams that carry each subject, found by the bus: a namespace no stream carries hears nothing and is skipped.
|
||||||
|
byStream := map[string][]string{}
|
||||||
|
for _, subject := range subjects {
|
||||||
|
if strings.HasSuffix(subject, ".>") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stream, err := js.StreamNameBySubject(ctx, subject)
|
||||||
|
if err != nil || stream == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
byStream[stream] = append(byStream[stream], subject, subject+".>")
|
||||||
|
}
|
||||||
|
if len(byStream) == 0 {
|
||||||
|
return nil, fmt.Errorf("no stream on the bus carries %s (%s): nothing would be heard", name, strings.Join(subjects, ", "))
|
||||||
|
}
|
||||||
|
var stops []func()
|
||||||
|
stopAll := func() {
|
||||||
|
for _, s := range stops {
|
||||||
|
s()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, stream := range slices.Sorted(mapKeys(byStream)) {
|
||||||
|
cons, err := js.OrderedConsumer(ctx, stream, jetstream.OrderedConsumerConfig{FilterSubjects: byStream[stream],
|
||||||
|
DeliverPolicy: jetstream.DeliverNewPolicy})
|
||||||
|
if err != nil {
|
||||||
|
stopAll()
|
||||||
|
return nil, fmt.Errorf("an ordered consumer of %s on %s: %w", name, stream, err)
|
||||||
|
}
|
||||||
|
cc, err := cons.Consume(func(m jetstream.Msg) {
|
||||||
|
env, ok := envelopeOf(m.Subject(), m.Headers(), m.Data())
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(env)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := deliver(raw); err != nil && c.Logf != nil {
|
||||||
|
c.Logf("[mesh-tools] a subscription for new %s messages did not take one: %v", name, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
stopAll()
|
||||||
|
return nil, fmt.Errorf("consuming %s on %s: %w", name, stream, err)
|
||||||
|
}
|
||||||
|
stops = append(stops, cc.Stop)
|
||||||
|
}
|
||||||
|
return stopAll, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mapKeys(m map[string][]string) func(func(string) bool) {
|
||||||
|
return func(yield func(string) bool) {
|
||||||
|
for k := range m {
|
||||||
|
if !yield(k) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,7 +29,7 @@ func TestTheBusRefusesAWaitOutsideTheGrant(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
go s.Start()
|
go s.Start()
|
||||||
if !s.ReadyForConnections(10 * time.Second) {
|
if !s.ReadyForConnections(mt.Bound(t)) {
|
||||||
t.Fatal("the bus did not come up")
|
t.Fatal("the bus did not come up")
|
||||||
}
|
}
|
||||||
t.Cleanup(s.Shutdown)
|
t.Cleanup(s.Shutdown)
|
||||||
@@ -38,7 +38,8 @@ func TestTheBusRefusesAWaitOutsideTheGrant(t *testing.T) {
|
|||||||
// Every subscription refused: answered after the timeout, never at once, in §16's words.
|
// Every subscription refused: answered after the timeout, never at once, in §16's words.
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
_, ok, refused, err := c.HearFirst(context.Background(), []string{other}, 300*time.Millisecond, nil)
|
_, ok, refused, err := c.HearFirst(context.Background(), []string{other}, 300*time.Millisecond, nil)
|
||||||
if took := time.Since(start); took < 300*time.Millisecond || took > 3*time.Second {
|
// 1754/AC4: after its timeout, never at once; a wait that never ended would meet the test's own deadline
|
||||||
|
if took := time.Since(start); took < 300*time.Millisecond {
|
||||||
t.Errorf("a wait refused whole answered after %s, want its timeout of 300ms", took)
|
t.Errorf("a wait refused whole answered after %s, want its timeout of 300ms", took)
|
||||||
}
|
}
|
||||||
if ok || err == nil || !strings.Contains(err.Error(), "the bus refused this account a subscription on "+other) ||
|
if ok || err == nil || !strings.Contains(err.Error(), "the bus refused this account a subscription on "+other) ||
|
||||||
@@ -62,7 +63,7 @@ func TestTheBusRefusesAWaitOutsideTheGrant(t *testing.T) {
|
|||||||
}
|
}
|
||||||
done := make(chan result, 1)
|
done := make(chan result, 1)
|
||||||
go func() {
|
go func() {
|
||||||
h, ok, refused, err := c.HearFirst(context.Background(), []string{other, granted}, 5*time.Second, nil)
|
h, ok, refused, err := c.HearFirst(context.Background(), []string{other, granted}, mt.Bound(t), nil)
|
||||||
if !ok && err == nil {
|
if !ok && err == nil {
|
||||||
err = errors.New("timed out")
|
err = errors.New("timed out")
|
||||||
}
|
}
|
||||||
@@ -103,12 +104,12 @@ func TestAWaitEndsWhenItsCallerIsGone(t *testing.T) {
|
|||||||
before := c.Subscriptions()
|
before := c.Subscriptions()
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
time.AfterFunc(200*time.Millisecond, cancel)
|
time.AfterFunc(200*time.Millisecond, cancel)
|
||||||
start := time.Now()
|
start, within := time.Now(), mt.Bound(t)
|
||||||
_, ok, _, err := c.HearFirst(ctx, []string{"mesh.mod.mesh-knowledge.event.reviewed"}, time.Minute, nil)
|
_, ok, _, err := c.HearFirst(ctx, []string{"mesh.mod.mesh-knowledge.event.reviewed"}, within, nil)
|
||||||
if ok || !errors.Is(err, context.Canceled) {
|
if ok || !errors.Is(err, context.Canceled) {
|
||||||
t.Errorf("a cancelled wait answered %v, %v", ok, err)
|
t.Errorf("a cancelled wait answered %v, %v", ok, err)
|
||||||
}
|
}
|
||||||
if took := time.Since(start); took > 2*time.Second {
|
if took := time.Since(start); took > within/2 { // 1754/AC4: at the cancel, not at its own timeout
|
||||||
t.Errorf("a cancelled wait ended after %s", took)
|
t.Errorf("a cancelled wait ended after %s", took)
|
||||||
}
|
}
|
||||||
if after := c.Subscriptions(); after != before {
|
if after := c.Subscriptions(); after != before {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ package console
|
|||||||
import (
|
import (
|
||||||
assigner "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
assigner "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
||||||
"git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
"git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||||
|
|
||||||
"context"
|
"context"
|
||||||
@@ -927,6 +927,34 @@ func schemaWithoutNode(raw json.RawMessage) map[string]any {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// answerText is a discovery verb's answer as MCP content: JSON, indented.
|
// answerText is a discovery verb's answer as MCP content: JSON, indented.
|
||||||
|
// withinOf is how long a call of the target waits: the `timeout` its seat verb's definition names (design 47 H §760), else the
|
||||||
|
// runner's own bound, RequestTimeout.
|
||||||
|
func (s *Surface) withinOf(t target) time.Duration {
|
||||||
|
if t.Seat && s.Definitions != nil {
|
||||||
|
for _, v := range s.Definitions()[t.Tool.Module].Verbs {
|
||||||
|
if v.Name == t.Tool.Name && v.Timeout != nil {
|
||||||
|
return time.Duration(*v.Timeout) * time.Second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bus.RequestTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
// callFailed is why a call failed, as mesh_call says it: a marked tool or verb that reaches no responder names `withheld`
|
||||||
|
// and the grants part's read (design 46 7-approval-mark §6), and a target known only from an earlier round says so.
|
||||||
|
func (s *Surface) callFailed(t target, err error) string {
|
||||||
|
why := whyItFailedWithin(t.Address, err, s.withinOf(t))
|
||||||
|
if ok, _ := s.markedTool(t); ok && errors.Is(err, bus.ErrNoResponders) {
|
||||||
|
// A marked subject withheld from a machine whose tool runner does not honour the mark (§6).
|
||||||
|
why += "; it needs the operator's approval, so it may be withheld where the machine's tool runner does not state " +
|
||||||
|
"approval-mark/1: mesh-grants.grants_user_list names it under withheld"
|
||||||
|
}
|
||||||
|
if t.Stale != nil {
|
||||||
|
why += " (" + t.Stale.say() + ")"
|
||||||
|
}
|
||||||
|
return why
|
||||||
|
}
|
||||||
|
|
||||||
func answerText(v any) map[string]any {
|
func answerText(v any) map[string]any {
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
enc := json.NewEncoder(&b)
|
enc := json.NewEncoder(&b)
|
||||||
@@ -1132,21 +1160,12 @@ func (s *Surface) discover(ctx context.Context, name string, args map[string]any
|
|||||||
}
|
}
|
||||||
var got bus.Answered
|
var got bus.Answered
|
||||||
if t.Seat {
|
if t.Seat {
|
||||||
got, err = s.conn.Ask(t.Key, callArgs, "")
|
got, err = s.conn.AskWithin(t.Key, callArgs, "", s.withinOf(t))
|
||||||
} else {
|
} else {
|
||||||
got, err = callTool(s.conn, t.Key, callArgs, nil, x.Listing)
|
got, err = callTool(s.conn, t.Key, callArgs, nil, x.Listing)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
why := whyItFailed(t.Address, err)
|
return failure(s.callFailed(t, err))
|
||||||
if ok, _ := s.markedTool(t); ok && errors.Is(err, bus.ErrNoResponders) {
|
|
||||||
// A marked subject withheld from a machine whose tool runner does not honour the mark (§6).
|
|
||||||
why += "; it needs the operator's approval, so it may be withheld where the machine's tool runner does not state " +
|
|
||||||
"approval-mark/1: mesh-grants.grants_user_list names it under withheld"
|
|
||||||
}
|
|
||||||
if t.Stale != nil {
|
|
||||||
why += " (" + t.Stale.say() + ")"
|
|
||||||
}
|
|
||||||
return failure(why)
|
|
||||||
}
|
}
|
||||||
result, unread := resolveSent(s.conn, got.Result)
|
result, unread := resolveSent(s.conn, got.Result)
|
||||||
content := []map[string]any{{"type": "text", "text": pretty(result)}}
|
content := []map[string]any{{"type": "text", "text": pretty(result)}}
|
||||||
|
|||||||
@@ -210,7 +210,7 @@ func TestTheMeshsToolsAreFoundByAddress(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer stopLate()
|
defer stopLate()
|
||||||
var found string
|
var found string
|
||||||
for i := 0; i < 30; i++ {
|
for deadline := time.Now().Add(mt.Bound(t)); time.Now().Before(deadline); {
|
||||||
found, _ = call(t, endpoint, "mesh_search", map[string]any{"query": "gamma given"})
|
found, _ = call(t, endpoint, "mesh_search", map[string]any{"query": "gamma given"})
|
||||||
if strings.Contains(found, "desk/gamma.given") {
|
if strings.Contains(found, "desk/gamma.given") {
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
@@ -120,6 +121,11 @@ var (
|
|||||||
|
|
||||||
// whyItFailed says why a call failed, so the remedy is in the words.
|
// whyItFailed says why a call failed, so the remedy is in the words.
|
||||||
func whyItFailed(key string, err error) string {
|
func whyItFailed(key string, err error) string {
|
||||||
|
return whyItFailedWithin(key, err, bus.RequestTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// whyItFailedWithin is whyItFailed for a call that waited within, the bound its verb's definition names or the runner's own.
|
||||||
|
func whyItFailedWithin(key string, err error, within time.Duration) string {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = errors.New("failed")
|
err = errors.New("failed")
|
||||||
}
|
}
|
||||||
@@ -139,7 +145,7 @@ func whyItFailed(key string, err error) string {
|
|||||||
case timedOut.MatchString(msg):
|
case timedOut.MatchString(msg):
|
||||||
// **A timeout is not a failure** (novox/hq issue 265). Something took the call, so it may
|
// **A timeout is not a failure** (novox/hq issue 265). Something took the call, so it may
|
||||||
// still be running and may already have done what was asked: a push said this while it pushed.
|
// still be running and may already have done what was asked: a push said this while it pushed.
|
||||||
said := key + " did not answer within " + bus.RequestTimeout.String() + ". That is not a failure: " +
|
said := key + " did not answer within " + within.String() + ". That is not a failure: " +
|
||||||
"something is serving it, so it may still be running and may already have done what was " +
|
"something is serving it, so it may still be running and may already have done what was " +
|
||||||
"asked — check before repeating a call that changes the mesh."
|
"asked — check before repeating a call that changes the mesh."
|
||||||
return said
|
return said
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/process"
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,6 +21,10 @@ type FirstViewer interface {
|
|||||||
// state and since when.
|
// state and since when.
|
||||||
type entryLister interface{ Entries() any }
|
type entryLister interface{ Entries() any }
|
||||||
|
|
||||||
|
// ownBuilder is a FirstViewer that also says the build the tool runner itself was started with (design 47 G §205, §424):
|
||||||
|
// mesh_first_views names it, or says `own build unknown` and why.
|
||||||
|
type ownBuilder interface{ OwnBuild() process.Build }
|
||||||
|
|
||||||
// firstViewsAnswer is mesh_first_views and mesh_first_view_again.
|
// firstViewsAnswer is mesh_first_views and mesh_first_view_again.
|
||||||
func (s *Surface) firstViewsAnswer(ctx context.Context, name string, args map[string]any) map[string]any {
|
func (s *Surface) firstViewsAnswer(ctx context.Context, name string, args map[string]any) map[string]any {
|
||||||
fv, ok := s.src.(FirstViewer)
|
fv, ok := s.src.(FirstViewer)
|
||||||
@@ -29,6 +34,9 @@ func (s *Surface) firstViewsAnswer(ctx context.Context, name string, args map[st
|
|||||||
}
|
}
|
||||||
if name == verbFirstViews {
|
if name == verbFirstViews {
|
||||||
out := map[string]any{"first views": fv.Status()}
|
out := map[string]any{"first views": fv.Status()}
|
||||||
|
if ob, ok := fv.(ownBuilder); ok {
|
||||||
|
out["own build"] = ob.OwnBuild().String()
|
||||||
|
}
|
||||||
if el, ok := fv.(entryLister); ok {
|
if el, ok := fv.(entryLister); ok {
|
||||||
out["entries"] = el.Entries()
|
out["entries"] = el.Entries()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/process"
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -14,12 +15,16 @@ import (
|
|||||||
type viewer struct {
|
type viewer struct {
|
||||||
busSource
|
busSource
|
||||||
asked []string
|
asked []string
|
||||||
|
build process.Build
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *viewer) Status() []views.Status {
|
func (v *viewer) Status() []views.Status {
|
||||||
return []views.Status{{Owner: "mesh-delivery-assigner", Tool: "assignments", State: "assignments", Revision: 4, Asks: 1}}
|
return []views.Status{{Owner: "mesh-delivery-assigner", Tool: "assignments", State: "assignments", Revision: 4, Asks: 1}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OwnBuild is the build the viewer was started with.
|
||||||
|
func (v *viewer) OwnBuild() process.Build { return v.build }
|
||||||
|
|
||||||
// Entries are the entries by fingerprint the viewer keeps (design 47 G A-103).
|
// Entries are the entries by fingerprint the viewer keeps (design 47 G A-103).
|
||||||
func (v *viewer) Entries() any { return []string{"fp:a asked"} }
|
func (v *viewer) Entries() any { return []string{"fp:a asked"} }
|
||||||
|
|
||||||
@@ -41,6 +46,13 @@ func TestTheConsoleShowsAndAsksAgainTheRunnersFirstViews(t *testing.T) {
|
|||||||
if got := text(s.discover(context.Background(), "mesh_first_views", nil)); !strings.Contains(got, "mesh-delivery-assigner") || !strings.Contains(got, "assignments") || !strings.Contains(got, "fp:a asked") {
|
if got := text(s.discover(context.Background(), "mesh_first_views", nil)); !strings.Contains(got, "mesh-delivery-assigner") || !strings.Contains(got, "assignments") || !strings.Contains(got, "fp:a asked") {
|
||||||
t.Errorf("mesh_first_views shows %s", got)
|
t.Errorf("mesh_first_views shows %s", got)
|
||||||
}
|
}
|
||||||
|
// The tool runner's own build is named, or said unknown with the reason (design 47 G §205, §424).
|
||||||
|
for build, want := range map[string]string{"abcd1234": "abcd1234", "": "own build unknown"} {
|
||||||
|
v.build = process.ReadOwnBuild(func(string) string { return build })
|
||||||
|
if got := text(s.discover(context.Background(), "mesh_first_views", nil)); !strings.Contains(got, `own build`) || !strings.Contains(got, want) {
|
||||||
|
t.Errorf("mesh_first_views with the build %q shows %s", build, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
got := s.discover(context.Background(), "mesh_first_view_again", map[string]any{"why": "doubted"})
|
got := s.discover(context.Background(), "mesh_first_view_again", map[string]any{"why": "doubted"})
|
||||||
if len(v.asked) != 1 || v.asked[0] != "doubted" || !strings.Contains(text(got), "asked again") {
|
if len(v.asked) != 1 || v.asked[0] != "doubted" || !strings.Contains(text(got), "asked again") {
|
||||||
t.Errorf("mesh_first_view_again asked %v and answered %s", v.asked, text(got))
|
t.Errorf("mesh_first_view_again asked %v and answered %s", v.asked, text(got))
|
||||||
|
|||||||
@@ -70,8 +70,8 @@ func TestTheManifestNamesNoWaitsAndKeepsItsApprovals(t *testing.T) {
|
|||||||
// `registration-changed`, and the gate's `source-moved`; never the indexer's `views.modules` or `views.manifests`), the two
|
// `registration-changed`, and the gate's `source-moved`; never the indexer's `views.modules` or `views.manifests`), the two
|
||||||
// events of the seat that serves the seat list (ADR 0636 §4) and the keeper's `findings-asked`, and nothing else.
|
// events of the seat that serves the seat list (ADR 0636 §4) and the keeper's `findings-asked`, and nothing else.
|
||||||
wantConsumes := []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-catalog.seat-definition-changed",
|
wantConsumes := []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-catalog.seat-definition-changed",
|
||||||
"mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", "mesh-delivery-assigner.views.assignments",
|
"mesh-catalog.seat-definition-removed", "mesh-conditions.findings-asked", "seat:mesh-module-assigner.views.assignments",
|
||||||
"mesh-delivery-assigner.views.seat-holders", "mesh-delivery.source-moved"}
|
"seat:mesh-module-assigner.views.seat-holders", "mesh-delivery.source-moved"}
|
||||||
if !reflect.DeepEqual(m.Consumes, wantConsumes) {
|
if !reflect.DeepEqual(m.Consumes, wantConsumes) {
|
||||||
t.Errorf("the tool runner consumes %v, want %v", m.Consumes, wantConsumes)
|
t.Errorf("the tool runner consumes %v, want %v", m.Consumes, wantConsumes)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
"git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -65,6 +66,9 @@ type Surface struct {
|
|||||||
Record func(args map[string]any) error
|
Record func(args map[string]any) error
|
||||||
// Approvals is this machine's approval gate, read by mesh_approvals and mesh_describe; nil when the runner has none.
|
// Approvals is this machine's approval gate, read by mesh_approvals and mesh_describe; nil when the runner has none.
|
||||||
Approvals Approvals
|
Approvals Approvals
|
||||||
|
// Definitions is the seat definitions this runner holds, by seat, which name a verb's `timeout` (design 47 H §760); nil when it
|
||||||
|
// holds none, and a call then waits the runner's own bound.
|
||||||
|
Definitions func() map[string]seatdef.Definition
|
||||||
}
|
}
|
||||||
|
|
||||||
// MethodSeats is the console's JSON-RPC method beside MCP's that answers every seat's verbs and holders, in the shape
|
// MethodSeats is the console's JSON-RPC method beside MCP's that answers every seat's verbs and holders, in the shape
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ import (
|
|||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A tool's own error that mentions 503 is the tool's answer, not a routing fault (issue 1529); a real no-responders still says
|
// A marked tool or verb that reaches no responder names withheld and the grants part's read (design 46 7-approval-mark §6);
|
||||||
|
// an unmarked one, or a marked one failing otherwise, does not. A tool's own error that mentions 503 is the tool's answer, not a routing fault (issue 1529); a real no-responders still says
|
||||||
// nothing serves.
|
// nothing serves.
|
||||||
func TestARealNoRespondersStillSaysNothingServes(t *testing.T) {
|
func TestARealNoRespondersStillSaysNothingServes(t *testing.T) {
|
||||||
got := whyItFailed("scanner.scan", errors.New("the scanner refused the scan job: 503 Service Unavailable"))
|
got := whyItFailed("scanner.scan", errors.New("the scanner refused the scan job: 503 Service Unavailable"))
|
||||||
@@ -23,4 +24,20 @@ func TestARealNoRespondersStillSaysNothingServes(t *testing.T) {
|
|||||||
t.Fatalf("%v: got %q", err, got)
|
t.Fatalf("%v: got %q", err, got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
s := &Surface{Approvals: &fakeApprovals{marked: "shell.wipe"}}
|
||||||
|
for _, c := range []struct {
|
||||||
|
target target
|
||||||
|
err error
|
||||||
|
hinted bool
|
||||||
|
}{
|
||||||
|
{target{Address: "shell.wipe", Tool: Tool{Module: "shell", Name: "wipe"}}, bus.ErrNoResponders, true},
|
||||||
|
{target{Address: "node-login-shell.execute", Seat: true, Tool: Tool{Module: "node-login-shell", Name: "execute"}}, bus.ErrNoResponders, false},
|
||||||
|
{target{Address: "shell.tidy", Tool: Tool{Module: "shell", Name: "tidy"}}, bus.ErrNoResponders, false},
|
||||||
|
{target{Address: "shell.wipe", Tool: Tool{Module: "shell", Name: "wipe"}}, errors.New("its own failure"), false},
|
||||||
|
} {
|
||||||
|
got := s.callFailed(c.target, c.err)
|
||||||
|
if hinted := strings.Contains(got, "approval-mark/1: mesh-grants.grants_user_list names it under withheld"); hinted != c.hinted {
|
||||||
|
t.Errorf("%s (%v): %q", c.target.Address, c.err, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,19 @@
|
|||||||
package console
|
package console
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/stateobjects"
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
|
"github.com/nats-io/nats.go/jetstream"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A refusal is said only for the bus's own refusals; a tool's answer that mentions authorization is the
|
// A refusal is said only for the bus's own refusals; a tool's answer that mentions authorization is the
|
||||||
@@ -19,6 +29,45 @@ func TestARefusalIsSaidOnlyForTheBussOwn(t *testing.T) {
|
|||||||
t.Errorf("%q read as a refusal: %v, want %v", msg, got, refusal)
|
t.Errorf("%q read as a refusal: %v, want %v", msg, got, refusal)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// ADR 0666 §16: an answer a module sent as a reference is read from its sent store for the person asking; one the bus does
|
||||||
|
// not let the runner read is shown as its reference with its size and why it was not read.
|
||||||
|
t.Run("AnAnswerSentAsAReferenceIsReadForThePersonAsking", func(t *testing.T) {
|
||||||
|
nc, err := nats.Connect(meshtest.URL(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer nc.Close()
|
||||||
|
js, _ := jetstream.New(nc)
|
||||||
|
obs, err := js.CreateObjectStore(context.Background(), jetstream.ObjectStoreConfig{Bucket: "m_sent-objects"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
conn, err := bus.Connect(bus.Credential{URL: meshtest.URL(t), Module: "console", Node: "anchor"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
body := []byte(`{"lines":"` + strings.Repeat("x", 9<<20) + `"}`)
|
||||||
|
sum := sha256.Sum256(body)
|
||||||
|
ref := stateobjects.Ref{Store: "m_sent-objects", Object: "tool.lines." + hex.EncodeToString(sum[:]), Size: int64(len(body)),
|
||||||
|
Digest: hex.EncodeToString(sum[:]), Form: stateobjects.FormVersion}
|
||||||
|
if _, err := obs.PutBytes(context.Background(), ref.Object, body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got, unread := resolveSent(conn, stateobjects.Wrap(ref)); unread != "" || string(got) != string(body) {
|
||||||
|
t.Fatalf("read %d bytes of %d, %q", len(got), len(body), unread)
|
||||||
|
}
|
||||||
|
missing := ref
|
||||||
|
missing.Store = "gone_sent-objects"
|
||||||
|
wrapped := stateobjects.Wrap(missing)
|
||||||
|
got, unread := resolveSent(conn, wrapped)
|
||||||
|
if string(got) != string(wrapped) || !strings.Contains(unread, "9437") || !strings.Contains(unread, "gone_sent-objects") {
|
||||||
|
t.Fatalf("an unread answer showed %q and %q", got, unread)
|
||||||
|
}
|
||||||
|
if got, unread := resolveSent(conn, []byte(`{"a":1}`)); unread != "" || string(got) != `{"a":1}` {
|
||||||
|
t.Fatalf("a plain answer showed %q, %q", got, unread)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// **A timeout says it is not a failure** (novox/hq issue 265): a push that outlasted the wait had
|
// **A timeout says it is not a failure** (novox/hq issue 265): a push that outlasted the wait had
|
||||||
@@ -26,6 +75,27 @@ func TestARefusalIsSaidOnlyForTheBussOwn(t *testing.T) {
|
|||||||
// the grammar's example, the handshake's instructions and a timeout's remedy named the controller's verbs.
|
// the grammar's example, the handshake's instructions and a timeout's remedy named the controller's verbs.
|
||||||
func TestATimeoutIsNotAFailure(t *testing.T) {
|
func TestATimeoutIsNotAFailure(t *testing.T) {
|
||||||
got := whyItFailed("seat:mesh-delivery.deliveries", errors.New("timeout"))
|
got := whyItFailed("seat:mesh-delivery.deliveries", errors.New("timeout"))
|
||||||
|
// Design 47 H §760: mesh_call waits the `timeout` the verb's definition names and a timeout says that bound; a verb naming none,
|
||||||
|
// a module's tool and a surface holding no definitions wait and say the runner's own 30s.
|
||||||
|
forty := 40
|
||||||
|
s := &Surface{Definitions: func() map[string]seatdef.Definition {
|
||||||
|
return map[string]seatdef.Definition{"mesh-broker": {Verbs: []seatdef.Verb{{Name: "rates", Timeout: &forty}, {Name: "plain"}}}}
|
||||||
|
}}
|
||||||
|
for _, row := range []struct {
|
||||||
|
t target
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{target{Address: "mesh-broker.rates", Seat: true, Tool: Tool{Module: "mesh-broker", Name: "rates"}}, "within 40s"},
|
||||||
|
{target{Address: "mesh-broker.plain", Seat: true, Tool: Tool{Module: "mesh-broker", Name: "plain"}}, "within 30s"},
|
||||||
|
{target{Address: "mesh-broker.rates", Tool: Tool{Module: "mesh-broker", Name: "rates"}}, "within 30s"},
|
||||||
|
} {
|
||||||
|
if said := s.callFailed(row.t, errors.New("timeout")); !strings.Contains(said, row.want) {
|
||||||
|
t.Errorf("%s: a timeout says %q, want it to say %q", row.t.Address, said, row.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if said := (&Surface{}).callFailed(target{Seat: true, Tool: Tool{Module: "mesh-broker", Name: "rates"}}, errors.New("timeout")); !strings.Contains(said, "within 30s") {
|
||||||
|
t.Errorf("a surface that holds no definitions says %q, want 30s", said)
|
||||||
|
}
|
||||||
for _, want := range []string{"not a failure", "may already have done"} {
|
for _, want := range []string{"not a failure", "may already have done"} {
|
||||||
if !strings.Contains(got, want) {
|
if !strings.Contains(got, want) {
|
||||||
t.Errorf("a seat's timeout does not say %q: %s", want, got)
|
t.Errorf("a seat's timeout does not say %q: %s", want, got)
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
package console
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/stateobjects"
|
|
||||||
"github.com/nats-io/nats.go"
|
|
||||||
"github.com/nats-io/nats.go/jetstream"
|
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ADR 0666 §16: an answer a module sent as a reference is read from its sent store for the person asking; one the bus does
|
|
||||||
// not let the runner read is shown as its reference with its size and why it was not read.
|
|
||||||
func TestAnAnswerSentAsAReferenceIsReadForThePersonAsking(t *testing.T) {
|
|
||||||
nc, err := nats.Connect(meshtest.URL(t))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer nc.Close()
|
|
||||||
js, _ := jetstream.New(nc)
|
|
||||||
obs, err := js.CreateObjectStore(context.Background(), jetstream.ObjectStoreConfig{Bucket: "m_sent-objects"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
conn, err := bus.Connect(bus.Credential{URL: meshtest.URL(t), Module: "console", Node: "anchor"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
body := []byte(`{"lines":"` + strings.Repeat("x", 9<<20) + `"}`)
|
|
||||||
sum := sha256.Sum256(body)
|
|
||||||
ref := stateobjects.Ref{Store: "m_sent-objects", Object: "tool.lines." + hex.EncodeToString(sum[:]), Size: int64(len(body)),
|
|
||||||
Digest: hex.EncodeToString(sum[:]), Form: stateobjects.FormVersion}
|
|
||||||
if _, err := obs.PutBytes(context.Background(), ref.Object, body); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got, unread := resolveSent(conn, stateobjects.Wrap(ref)); unread != "" || string(got) != string(body) {
|
|
||||||
t.Fatalf("read %d bytes of %d, %q", len(got), len(body), unread)
|
|
||||||
}
|
|
||||||
missing := ref
|
|
||||||
missing.Store = "gone_sent-objects"
|
|
||||||
wrapped := stateobjects.Wrap(missing)
|
|
||||||
got, unread := resolveSent(conn, wrapped)
|
|
||||||
if string(got) != string(wrapped) || !strings.Contains(unread, "9437") || !strings.Contains(unread, "gone_sent-objects") {
|
|
||||||
t.Fatalf("an unread answer showed %q and %q", got, unread)
|
|
||||||
}
|
|
||||||
if got, unread := resolveSent(conn, []byte(`{"a":1}`)); unread != "" || string(got) != `{"a":1}` {
|
|
||||||
t.Fatalf("a plain answer showed %q, %q", got, unread)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||||
|
|
||||||
@@ -202,10 +202,14 @@ func (s *Surface) emitters() (known knownEmitters, unchecked string) {
|
|||||||
return known, "the catalog half is not yet read (" + err.Error() + "); its first view is in mesh_first_views"
|
return known, "the catalog half is not yet read (" + err.Error() + "); its first view is in mesh_first_views"
|
||||||
}
|
}
|
||||||
seatEvents := map[string][]string{} // a seat's events, as its definition in the seat list declares them
|
seatEvents := map[string][]string{} // a seat's events, as its definition in the seat list declares them
|
||||||
|
known.seats, known.modules = map[string][]string{}, map[string][]string{}
|
||||||
|
// Every seat of the seat list is an emitter, by the events its definition declares under its events family, whichever
|
||||||
|
// repository defines it (design 47 H2 §821, H-A-343): a seat the catalog half's own definitions do not name, such as one the
|
||||||
|
// delivery repository's contracts module defines, is waited on by its seat and event name.
|
||||||
for _, st := range catalogue.Seats() {
|
for _, st := range catalogue.Seats() {
|
||||||
seatEvents[st.Name] = st.Emits
|
seatEvents[st.Name] = st.Emits
|
||||||
|
known.seats[st.Name] = st.Emits
|
||||||
}
|
}
|
||||||
known.seats, known.modules = map[string][]string{}, map[string][]string{}
|
|
||||||
branches := make([]string, 0, len(halves))
|
branches := make([]string, 0, len(halves))
|
||||||
for b := range halves {
|
for b := range halves {
|
||||||
branches = append(branches, b)
|
branches = append(branches, b)
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ import (
|
|||||||
|
|
||||||
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
"git.novox.be/novox/mesh-contracts/operator-and-conversation/go/clients/operatorchannelclient"
|
||||||
opseat "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
opseat "git.novox.be/novox/mesh-contracts/operator-and-conversation/go/seats/operatorchannel"
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"git.novox.be/novox/mesh-sdk/go/approval"
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
@@ -124,14 +124,14 @@ func TestMeshWaitAnswersTheFirstMatchingEvent(t *testing.T) {
|
|||||||
var got answer
|
var got answer
|
||||||
select {
|
select {
|
||||||
case got = <-done:
|
case got = <-done:
|
||||||
case <-time.After(10 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatal("mesh_wait did not answer the matching event")
|
t.Fatal("mesh_wait did not answer the matching event")
|
||||||
}
|
}
|
||||||
if got.isErr {
|
if got.isErr {
|
||||||
t.Fatalf("mesh_wait failed: %s", got.text)
|
t.Fatalf("mesh_wait failed: %s", got.text)
|
||||||
}
|
}
|
||||||
if got.at.Sub(published) > time.Second {
|
if got.at.Sub(published) > 10*time.Second { // 1754/AC4: half its timeout of 20 s, on the event and not at its timeout
|
||||||
t.Errorf("answered %s after the event was published, want within a second", got.at.Sub(published))
|
t.Errorf("answered %s after the event was published, want on the event, not at its timeout", got.at.Sub(published))
|
||||||
}
|
}
|
||||||
var heard heardAnswer
|
var heard heardAnswer
|
||||||
if err := json.Unmarshal([]byte(got.text), &heard); err != nil {
|
if err := json.Unmarshal([]byte(got.text), &heard); err != nil {
|
||||||
@@ -161,7 +161,7 @@ func TestMeshWaitAnswersTheFirstMatchingEvent(t *testing.T) {
|
|||||||
h.Published != nil || !strings.Contains(heard.Read, "claude_code_answer") {
|
h.Published != nil || !strings.Contains(heard.Read, "claude_code_answer") {
|
||||||
t.Errorf("the asker's decided: %s", got.text)
|
t.Errorf("the asker's decided: %s", got.text)
|
||||||
}
|
}
|
||||||
case <-time.After(10 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatal("mesh_wait did not answer the asker's decided")
|
t.Fatal("mesh_wait did not answer the asker's decided")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -172,7 +172,7 @@ func TestMeshWaitSaysItTimedOutAndKeepsNothing(t *testing.T) {
|
|||||||
before := s.conn.Subscriptions()
|
before := s.conn.Subscriptions()
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
text, isErr := callWait(s, map[string]any{"subjects": []any{"mesh-knowledge.reviewed"}, "timeout": 1})
|
text, isErr := callWait(s, map[string]any{"subjects": []any{"mesh-knowledge.reviewed"}, "timeout": 1})
|
||||||
if took := time.Since(start); took < time.Second || took > 3*time.Second {
|
if took := time.Since(start); took < time.Second || took > WaitDefault/2 { // 1754/AC4: at its timeout, not WaitDefault's
|
||||||
t.Errorf("a one-second wait took %s", took)
|
t.Errorf("a one-second wait took %s", took)
|
||||||
}
|
}
|
||||||
// Before the catalog half is read, names are not checked, and the answer says so (design 34 every-event §14).
|
// Before the catalog half is read, names are not checked, and the answer says so (design 34 every-event §14).
|
||||||
@@ -203,7 +203,7 @@ func TestMeshWaitsTimeoutIsBounded(t *testing.T) {
|
|||||||
// a wildcard, of one token, more than 16 names, none, or a from of another word is refused at once naming the rule; a
|
// a wildcard, of one token, more than 16 names, none, or a from of another word is refused at once naming the rule; a
|
||||||
// wait whose every subscription the bus refuses answers after its timeout, in words naming no wait grant.
|
// wait whose every subscription the bus refuses answers after its timeout, in words naming no wait grant.
|
||||||
func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
|
func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
|
||||||
s, mesh := waitingRuntime(t)
|
s, _ := waitingRuntime(t)
|
||||||
var seventeen []any
|
var seventeen []any
|
||||||
for i := 0; i < 17; i++ {
|
for i := 0; i < 17; i++ {
|
||||||
seventeen = append(seventeen, fmt.Sprintf("mesh-knowledge.reviewed%d", i))
|
seventeen = append(seventeen, fmt.Sprintf("mesh-knowledge.reviewed%d", i))
|
||||||
@@ -219,74 +219,92 @@ func TestMeshWaitRefusesLoudlyAndNeverLoops(t *testing.T) {
|
|||||||
{map[string]any{"subjects": []any{}}, "at least one event"},
|
{map[string]any{"subjects": []any{}}, "at least one event"},
|
||||||
{map[string]any{"subjects": []any{"mesh-knowledge.reviewed"}, "from": "bench"}, "seat, module or stream"},
|
{map[string]any{"subjects": []any{"mesh-knowledge.reviewed"}, "from": "bench"}, "seat, module or stream"},
|
||||||
} {
|
} {
|
||||||
c.args["timeout"] = 1
|
start := time.Now() // no timeout: the wait's would be WaitDefault
|
||||||
start := time.Now()
|
|
||||||
text, isErr := callWait(s, c.args)
|
text, isErr := callWait(s, c.args)
|
||||||
if !isErr || !strings.Contains(text, c.says) || strings.Contains(text, "manifest") {
|
if !isErr || !strings.Contains(text, c.says) || strings.Contains(text, "manifest") {
|
||||||
t.Errorf("%v: %s, want refused saying %q", c.args, text, c.says)
|
t.Errorf("%v: %s, want refused saying %q", c.args, text, c.says)
|
||||||
}
|
}
|
||||||
if took := time.Since(start); took > 500*time.Millisecond {
|
if took := time.Since(start); took > WaitDefault/2 { // 1754/AC4: half the wait's timeout, refused before any wait
|
||||||
t.Errorf("%v was refused after %s, want at once", c.args, took)
|
t.Errorf("%v was refused after %s, want at once", c.args, took)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// E §14: against the catalog half, a misspelt emitter is refused naming the half and its revision, a known emitter's
|
t.Run("the catalog half", func(t *testing.T) {
|
||||||
// undeclared event is waited on and its timeout says so, and a declared one says nothing of it.
|
t.Parallel()
|
||||||
half := NewSurface(s.conn, halfSource{busSource{s.conn}, map[string]meshcatalogclient.Half{"main": {
|
// E §14: against the catalog half, a misspelt emitter is refused naming the half and its revision, a known emitter's
|
||||||
Revision: catalogseat.CatalogRevision{Revision: 7, Definitions: []catalogseat.CatalogRevisionDefinitionsItem{{Seat: "mesh-catalog"}}},
|
// undeclared event is waited on and its timeout says so, and a declared one says nothing of it.
|
||||||
Entries: map[string]catalogseat.CatalogEntry{"mesh-delivery-view": {Module: "mesh-delivery-view",
|
half := NewSurface(s.conn, halfSource{busSource{s.conn}, map[string]meshcatalogclient.Half{"main": {
|
||||||
Manifest: map[string]any{"emits": []any{"delivered"}}}},
|
Revision: catalogseat.CatalogRevision{Revision: 7, Definitions: []catalogseat.CatalogRevisionDefinitionsItem{{Seat: "mesh-catalog"}}},
|
||||||
}}}, "desk.node-tools")
|
Entries: map[string]catalogseat.CatalogEntry{"mesh-delivery-view": {Module: "mesh-delivery-view",
|
||||||
for _, c := range []struct {
|
Manifest: map[string]any{"emits": []any{"delivered"}}}},
|
||||||
name, says string
|
}}}, "desk.node-tools")
|
||||||
refused bool
|
for _, c := range []struct {
|
||||||
}{
|
name, says string
|
||||||
{"mesh-delivry-view.delivered", "mesh-delivry-view is neither a seat nor a module of the catalog half (mesh-catalog.revision, revision 7 of main)", true},
|
refused bool
|
||||||
{"mesh-delivery-view.planned", "no declaration names mesh-delivery-view.planned", false},
|
}{
|
||||||
{"mesh-catalog.catalog-revision", "", false},
|
{"mesh-delivry-view.delivered", "mesh-delivry-view is neither a seat nor a module of the catalog half (mesh-catalog.revision, revision 7 of main)", true},
|
||||||
} {
|
{"mesh-delivery-view.planned", "no declaration names mesh-delivery-view.planned", false},
|
||||||
text, isErr := callWait(half, map[string]any{"subjects": []any{c.name}, "timeout": 1})
|
{"mesh-catalog.catalog-revision", "", false},
|
||||||
if isErr != c.refused || c.says != "" && !strings.Contains(text, c.says) ||
|
// a seat of the seat list the half's definitions do not name is waited on by its declared event (design 47 H2 §821)
|
||||||
c.says == "" && (strings.Contains(text, "undeclared") || strings.Contains(text, "unchecked")) {
|
{"mesh-wants.wanted", "", false},
|
||||||
t.Errorf("%s against the catalog half: %s", c.name, text)
|
} {
|
||||||
|
text, isErr := callWait(half, map[string]any{"subjects": []any{c.name}, "timeout": 1})
|
||||||
|
if isErr != c.refused || c.says != "" && !strings.Contains(text, c.says) ||
|
||||||
|
c.says == "" && (strings.Contains(text, "undeclared") || strings.Contains(text, "unchecked")) {
|
||||||
|
t.Errorf("%s against the catalog half: %s", c.name, text)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|
||||||
|
t.Run("a bus that refuses every subscription", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
// The bus refusing every subscription of the call: answered after the timeout, in §16's words.
|
||||||
|
b, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: server.RANDOM_PORT, NoLog: true, NoSigs: true,
|
||||||
|
Users: []*server.User{{Username: "desk.node-tools", Password: "pw", Permissions: &server.Permissions{
|
||||||
|
Subscribe: &server.SubjectPermission{Allow: []string{"_INBOX.desk.node-tools.>", "mesh.assignment.desk.*"}},
|
||||||
|
}}}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
go b.Start()
|
||||||
|
if !b.ReadyForConnections(mt.Bound(t)) {
|
||||||
|
t.Fatal("the bus did not come up")
|
||||||
|
}
|
||||||
|
t.Cleanup(b.Shutdown)
|
||||||
|
conn, err := bus.Connect(bus.Credential{URL: b.ClientURL(), Module: "node-tools", Node: "desk", User: "desk.node-tools", Password: "pw"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
conn.Logf = func(string, ...any) {}
|
||||||
|
t.Cleanup(conn.Close)
|
||||||
|
start := time.Now()
|
||||||
|
text, isErr := callWait(NewSurface(conn, nil, "desk.node-tools"), map[string]any{"subjects": []any{"mesh-delivery-view.delivered"}, "timeout": 1})
|
||||||
|
if took := time.Since(start); took < time.Second || took > WaitDefault/2 { // 1754/AC4: at its timeout, not WaitDefault's
|
||||||
|
t.Errorf("a wait the bus refused whole answered after %s, want its timeout of 1s", took)
|
||||||
|
}
|
||||||
|
if !isErr || !strings.Contains(text, "the bus refused this account a subscription on mesh.seat.mesh-delivery-view.event.delivered") ||
|
||||||
|
!strings.Contains(text, "novox/hq ADR 0670 §1") || strings.Contains(text, "wait grant") || strings.Contains(text, "0367 §2") {
|
||||||
|
t.Errorf("a wait the bus refused whole: %s", text)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
// The bus refusing every subscription of the call: answered after the timeout, in §16's words.
|
|
||||||
b, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: server.RANDOM_PORT, NoLog: true, NoSigs: true,
|
|
||||||
Users: []*server.User{{Username: "desk.node-tools", Password: "pw", Permissions: &server.Permissions{
|
|
||||||
Subscribe: &server.SubjectPermission{Allow: []string{"_INBOX.desk.node-tools.>", "mesh.assignment.desk.*"}},
|
|
||||||
}}}})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
go b.Start()
|
|
||||||
if !b.ReadyForConnections(10 * time.Second) {
|
|
||||||
t.Fatal("the bus did not come up")
|
|
||||||
}
|
|
||||||
t.Cleanup(b.Shutdown)
|
|
||||||
conn, err := bus.Connect(bus.Credential{URL: b.ClientURL(), Module: "node-tools", Node: "desk", User: "desk.node-tools", Password: "pw"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
conn.Logf = func(string, ...any) {}
|
|
||||||
t.Cleanup(conn.Close)
|
|
||||||
start := time.Now()
|
|
||||||
text, isErr := callWait(NewSurface(conn, nil, "desk.node-tools"), map[string]any{"subjects": []any{"mesh-delivery-view.delivered"}, "timeout": 1})
|
|
||||||
if took := time.Since(start); took < time.Second || took > 3*time.Second {
|
|
||||||
t.Errorf("a wait the bus refused whole answered after %s, want its timeout of 1s", took)
|
|
||||||
}
|
|
||||||
if !isErr || !strings.Contains(text, "the bus refused this account a subscription on mesh.seat.mesh-delivery-view.event.delivered") ||
|
|
||||||
!strings.Contains(text, "novox/hq ADR 0670 §1") || strings.Contains(text, "wait grant") || strings.Contains(text, "0367 §2") {
|
|
||||||
t.Errorf("a wait the bus refused whole: %s", text)
|
|
||||||
}
|
|
||||||
// Design 34 every-event §37: a wait whose subjects overlap a marked event's, or a stream's with a `grant`, runs only on the
|
// Design 34 every-event §37: a wait whose subjects overlap a marked event's, or a stream's with a `grant`, runs only on the
|
||||||
// operator's warrant for that one wait; with none it subscribes nothing, asks once and answers at its timeout or the choice.
|
// operator's warrant for that one wait; with none it subscribes nothing, asks once and answers at its timeout or the choice.
|
||||||
markedWaits(t, s, mesh)
|
// Each group of rows has a runtime of its own, so the waits of the groups run side by side (A-311: the one-second floor of
|
||||||
|
// a wait's timeout stands, and no clock is injected).
|
||||||
|
for name, group := range map[string]func(*testing.T, *Surface, *mt.Mesh){
|
||||||
|
"no warrant": markedWaitsWithNoWarrant, "a warrant": markedWaitsOnAWarrant, "the catalog half unread": markedWaitsBeforeTheHalfIsRead,
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
s, mesh := waitingRuntime(t)
|
||||||
|
group(t, s, mesh)
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// markedWaits are §37's rows, against a gate on the test bus, the router's records written there as the router writes them.
|
// markedWaitsWithNoWarrant are §37's rows of a wait with no warrant, against a gate on the test bus, the router's records written there as the router writes them.
|
||||||
func markedWaits(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
func markedWaitsWithNoWarrant(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
||||||
gw := newGatedWaits(t, s, mesh, "src2:runner")
|
gw := newGatedWaits(t, s, mesh, "src2:runner")
|
||||||
g := gw.surface
|
g := gw.surface
|
||||||
took := func(args map[string]any) (string, bool, time.Duration) {
|
took := func(args map[string]any) (string, bool, time.Duration) {
|
||||||
@@ -321,6 +339,17 @@ func markedWaits(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
|||||||
!strings.Contains(text, `"timed-out": true`) || gw.asks() != 3 {
|
!strings.Contains(text, `"timed-out": true`) || gw.asks() != 3 {
|
||||||
t.Errorf("from a seat: %s, %d asks", text, gw.asks())
|
t.Errorf("from a seat: %s, %d asks", text, gw.asks())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// markedWaitsOnAWarrant are §37's rows of a wait chosen while it waits and of one on a warrant.
|
||||||
|
func markedWaitsOnAWarrant(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
||||||
|
gw := newGatedWaits(t, s, mesh, "src2:runner")
|
||||||
|
g := gw.surface
|
||||||
|
took := func(args map[string]any) (string, bool, time.Duration) {
|
||||||
|
start := time.Now()
|
||||||
|
text, isErr := callWait(g, args)
|
||||||
|
return text, isErr, time.Since(start)
|
||||||
|
}
|
||||||
// The most timeout a wait takes, its ask chosen while it waits: answered at the choice; the same call made then
|
// The most timeout a wait takes, its ask chosen while it waits: answered at the choice; the same call made then
|
||||||
// subscribes and hears the event published after it, answered with its approval; a warrant for other names, another
|
// subscribes and hears the event published after it, answered with its approval; a warrant for other names, another
|
||||||
// filter or another timeout is refused, asked anew.
|
// filter or another timeout is refused, asked anew.
|
||||||
@@ -328,7 +357,7 @@ func markedWaits(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
|||||||
done := make(chan string, 1)
|
done := make(chan string, 1)
|
||||||
go func() { text, _, d := took(long); done <- fmt.Sprintf("%s after %s", text, d) }()
|
go func() { text, _, d := took(long); done <- fmt.Sprintf("%s after %s", text, d) }()
|
||||||
mt.Until(t, func() error {
|
mt.Until(t, func() error {
|
||||||
if gw.asks() < 4 {
|
if gw.asks() < 1 {
|
||||||
return os.ErrNotExist
|
return os.ErrNotExist
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -339,10 +368,10 @@ func markedWaits(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
|||||||
if !strings.Contains(got, "make this wait again within 30 minutes") {
|
if !strings.Contains(got, "make this wait again within 30 minutes") {
|
||||||
t.Errorf("a long wait chosen while it waits: %s", got)
|
t.Errorf("a long wait chosen while it waits: %s", got)
|
||||||
}
|
}
|
||||||
case <-time.After(10 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatal("a long marked wait was not answered at the choice")
|
t.Fatal("a long marked wait was not answered at the choice")
|
||||||
}
|
}
|
||||||
before = g.conn.Subscriptions()
|
before := g.conn.Subscriptions()
|
||||||
go func() {
|
go func() {
|
||||||
listening(t, g, before, 6)
|
listening(t, g, before, 6)
|
||||||
mesh.Emit(t, "mesh.mod.mail.event.message", map[string]any{"n": 2})
|
mesh.Emit(t, "mesh.mod.mail.event.message", map[string]any{"n": 2})
|
||||||
@@ -361,6 +390,17 @@ func markedWaits(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
|||||||
t.Errorf("another wait than the warrant's %v: %s", other, text)
|
t.Errorf("another wait than the warrant's %v: %s", other, text)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// markedWaitsBeforeTheHalfIsRead are §37's rows of a wait before the catalog half is read, and of one whose runner build is unknown.
|
||||||
|
func markedWaitsBeforeTheHalfIsRead(t *testing.T, s *Surface, mesh *mt.Mesh) {
|
||||||
|
gw := newGatedWaits(t, s, mesh, "src2:runner")
|
||||||
|
g := gw.surface
|
||||||
|
took := func(args map[string]any) (string, bool, time.Duration) {
|
||||||
|
start := time.Now()
|
||||||
|
text, isErr := callWait(g, args)
|
||||||
|
return text, isErr, time.Since(start)
|
||||||
|
}
|
||||||
// Before the catalog half is read nothing is asked: judged when its first view comes within the timeout, refused at
|
// Before the catalog half is read nothing is asked: judged when its first view comes within the timeout, refused at
|
||||||
// the timeout when it does not.
|
// the timeout when it does not.
|
||||||
gw.cat.mu.Lock()
|
gw.cat.mu.Lock()
|
||||||
@@ -562,17 +602,23 @@ func TestMeshWaitIsAnnouncedAmongSeven(t *testing.T) {
|
|||||||
func fmtAnswer(out map[string]any) string { raw, _ := json.Marshal(out); return string(raw) }
|
func fmtAnswer(out map[string]any) string { raw, _ := json.Marshal(out); return string(raw) }
|
||||||
|
|
||||||
// fakeApprovals is a gate as mesh_approvals reads it.
|
// fakeApprovals is a gate as mesh_approvals reads it.
|
||||||
type fakeApprovals struct{ cancelled string }
|
type fakeApprovals struct {
|
||||||
|
cancelled string
|
||||||
|
// marked is the one `<module>.<tool>` its Describe says is marked.
|
||||||
|
marked string
|
||||||
|
}
|
||||||
|
|
||||||
func (f *fakeApprovals) List() ([]approval.Listed, error) {
|
func (f *fakeApprovals) List() ([]approval.Listed, error) {
|
||||||
return []approval.Listed{{Ask: "a1", State: "asked"}}, nil
|
return []approval.Listed{{Ask: "a1", State: "asked"}}, nil
|
||||||
}
|
}
|
||||||
func (f *fakeApprovals) Read(id string) (approval.Whole, error) { return approval.Whole{}, nil }
|
func (f *fakeApprovals) Read(id string) (approval.Whole, error) { return approval.Whole{}, nil }
|
||||||
func (f *fakeApprovals) Applied() []approval.Marks { return nil }
|
func (f *fakeApprovals) Applied() []approval.Marks { return nil }
|
||||||
func (f *fakeApprovals) Describe(_, _, _ string) (bool, string) { return false, "" }
|
func (f *fakeApprovals) Describe(module, _, name string) (bool, string) {
|
||||||
func (f *fakeApprovals) Again(string) error { return nil }
|
return f.marked != "" && f.marked == module+"."+name, "entry " + module
|
||||||
func (f *fakeApprovals) Cancel(id string) error { f.cancelled = id; return nil }
|
}
|
||||||
func (f *fakeApprovals) Fill() (uint64, int64, error) { return 10, 64 << 20, nil }
|
func (f *fakeApprovals) Again(string) error { return nil }
|
||||||
|
func (f *fakeApprovals) Cancel(id string) error { f.cancelled = id; return nil }
|
||||||
|
func (f *fakeApprovals) Fill() (uint64, int64, error) { return 10, 64 << 20, nil }
|
||||||
|
|
||||||
// A client that hangs up or cancels ends its wait at once: the subscription is closed and nothing is left
|
// A client that hangs up or cancels ends its wait at once: the subscription is closed and nothing is left
|
||||||
// waiting for the timeout (the review of issue 745). Over the console's own HTTP, as an agent host calls it.
|
// waiting for the timeout (the review of issue 745). Over the console's own HTTP, as an agent host calls it.
|
||||||
@@ -597,12 +643,10 @@ func TestMeshWaitEndsWhenItsClientHangsUp(t *testing.T) {
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
cancel()
|
cancel()
|
||||||
start := time.Now()
|
for deadline := time.Now().Add(mt.Bound(t)); s.conn.Subscriptions() > before; time.Sleep(20 * time.Millisecond) {
|
||||||
for s.conn.Subscriptions() > before {
|
if time.Now().After(deadline) {
|
||||||
if time.Since(start) > 3*time.Second {
|
t.Fatalf("%d subscriptions at the test's bound after the client hung up, %d before the wait", s.conn.Subscriptions(), before)
|
||||||
t.Fatalf("%d subscriptions 3s after the client hung up, %d before the wait", s.conn.Subscriptions(), before)
|
|
||||||
}
|
}
|
||||||
time.Sleep(20 * time.Millisecond)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -629,11 +673,13 @@ func TestMeshWaitEndsWhenTheConsoleCloses(t *testing.T) {
|
|||||||
go func() { closed <- up.Close() }()
|
go func() { closed <- up.Close() }()
|
||||||
select {
|
select {
|
||||||
case <-closed:
|
case <-closed:
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatal("closing the console waited on a mesh_wait in flight")
|
t.Fatal("closing the console waited on a mesh_wait in flight")
|
||||||
}
|
}
|
||||||
if took := time.Since(start); took > 3*time.Second {
|
// 1754/AC4: half the bound it tells apart, the console's own backstop ShutdownWithin, which ends a close whose waits
|
||||||
t.Errorf("closing took %s", took)
|
// were never cancelled
|
||||||
|
if took := time.Since(start); took > ShutdownWithin/2 {
|
||||||
|
t.Errorf("closing took %s, want the waits cancelled at once, not ended by the backstop of %s", took, ShutdownWithin)
|
||||||
}
|
}
|
||||||
mt.Until(t, func() error {
|
mt.Until(t, func() error {
|
||||||
if s.conn.Subscriptions() > before {
|
if s.conn.Subscriptions() > before {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||||
"git.novox.be/novox/mesh-sdk/go/approval"
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
|
|
||||||
|
|||||||
@@ -20,53 +20,57 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||||
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
|
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"git.novox.be/novox/mesh-sdk/go/approval"
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/keys"
|
"git.novox.be/novox/mesh-sdk/go/keys"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/process"
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The owner and its first-view tools (the tools' addresses are `<owner>.<tool>`).
|
// AssignerSeat is the seat whose holder's views the runner follows: the holder is read from the catalog half's claims of the
|
||||||
const Assigner = "mesh-delivery-assigner"
|
// seat, never named in code (design 47 G §616, §428), and the names the console reads the two states by are the seat's
|
||||||
|
// (`<seat>.<state>`; the manifest's `consumes` names their views families by the seat, as `seat:<seat>.views.<state>`).
|
||||||
|
const AssignerSeat = meshmoduleassigner.Seat
|
||||||
|
|
||||||
// The names the console reads the assigner's two states by (`<owner>.<state>`), as the manifest's `consumes` names their views
|
|
||||||
// families (no seat's client names a holder, novox/hq ADR 0625 §4; TestTheFirstViewsAreTheManifestsViews).
|
|
||||||
const (
|
const (
|
||||||
AssignmentsRead = Assigner + ".assignments"
|
AssignmentsRead = AssignerSeat + ".assignments"
|
||||||
SeatHoldersRead = Assigner + ".seat-holders"
|
SeatHoldersRead = AssignerSeat + ".seat-holders"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Spec is one first view the runner holds.
|
// Spec is one first view the runner holds of the seat's holder: its first-view tool and the state.
|
||||||
type Spec struct{ Owner, Tool, State string }
|
type Spec struct{ Tool, State string }
|
||||||
|
|
||||||
// Specs are the two owner states asked of an owner's tool; the catalog half's views are adopted by the branch follower.
|
// Specs are the two states asked of the holder's tool; the catalog half's views are adopted by the branch follower.
|
||||||
var Specs = []Spec{
|
var Specs = []Spec{
|
||||||
{Assigner, "assignments", "assignments"},
|
{"assignments", "assignments"},
|
||||||
{Assigner, "seat-holders", "seat-holders"},
|
{"seat-holders", "seat-holders"},
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name is the name a state is read by, `<owner>.<state>`: AssignmentsRead and SeatHoldersRead.
|
// Name is the name a state is read by, `<seat>.<state>`: AssignmentsRead and SeatHoldersRead.
|
||||||
func (s Spec) Name() string { return s.Owner + "." + s.State }
|
func (s Spec) Name() string { return AssignerSeat + "." + s.State }
|
||||||
|
|
||||||
// Views is the first views: the assigner's two, and the catalog half's per watched branch.
|
// Views is the first views: the assigner's two, and the catalog half's per watched branch.
|
||||||
type Views struct {
|
type Views struct {
|
||||||
logf func(string, ...any)
|
logf func(string, ...any)
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
followers map[string]*views.Follower // by `<owner>.<state>`
|
followers map[string]*views.Follower // by `<owner>.<state>`
|
||||||
byState map[string]*views.Follower // by the state an event names, the owners' views families
|
byState map[string]*views.Follower // by the state an event names, the owners' views families
|
||||||
adopted map[string]*adoption // by `<owner>.<state>`, the views the branch follower adopted
|
adopted map[string]*adoption // by `<owner>.<state>`, the views the branch follower adopted
|
||||||
hearers map[string][]*adoption // event key `<seat>.<event>` -> the adopted views that hear it
|
unheardKeys map[string]bool // event keys said as heard by no view
|
||||||
branches *meshcatalogclient.Branches
|
hearers map[string][]*adoption // event key `<seat>.<event>` -> the adopted views that hear it
|
||||||
ctx context.Context
|
branches *meshcatalogclient.Branches
|
||||||
cancel context.CancelFunc
|
holder *holding // the module that claims the assigner seat, once the catalog half names it
|
||||||
wg sync.WaitGroup
|
ctx context.Context
|
||||||
deps Deps
|
cancel context.CancelFunc
|
||||||
|
wg sync.WaitGroup
|
||||||
|
deps Deps
|
||||||
// heard is closed and made again at every event heard, so a wait for the picture wakes on events, never on a timer.
|
// heard is closed and made again at every event heard, so a wait for the picture wakes on events, never on a timer.
|
||||||
heard chan struct{}
|
heard chan struct{}
|
||||||
// onKey are the hearers of one key of an owner's state, by `<state> <key>` (OnSeatHolder).
|
// onKey are the hearers of one key of an owner's state, by `<state> <key>` (OnSeatHolder).
|
||||||
@@ -89,6 +93,9 @@ type Deps struct {
|
|||||||
Findings FindingWriter
|
Findings FindingWriter
|
||||||
// StartFindings starts that writer, and its stop ends it; nil starts none.
|
// StartFindings starts that writer, and its stop ends it; nil starts none.
|
||||||
StartFindings func(ctx context.Context) (stop func(), err error)
|
StartFindings func(ctx context.Context) (stop func(), err error)
|
||||||
|
// Build is the build this process was started with (process.OwnBuild, read once at the start): its fingerprint, or
|
||||||
|
// why it is unknown (design 47 G §205, §424).
|
||||||
|
Build process.Build
|
||||||
// Node is the machine the runner is on, named in its findings' subject.
|
// Node is the machine the runner is on, named in its findings' subject.
|
||||||
Node string
|
Node string
|
||||||
// Bound and Wait are the follower's (zero: two minutes, five seconds).
|
// Bound and Wait are the follower's (zero: two minutes, five seconds).
|
||||||
@@ -111,7 +118,7 @@ func Start(parent context.Context, conn *bus.Conn, logf func(string, ...any)) (*
|
|||||||
// state adapter, JetStream and node are this connection's, in this one place (design 47 G A-16, A-27).
|
// state adapter, JetStream and node are this connection's, in this one place (design 47 G A-16, A-27).
|
||||||
func DepsOf(conn *bus.Conn, logf func(string, ...any)) Deps {
|
func DepsOf(conn *bus.Conn, logf func(string, ...any)) Deps {
|
||||||
me := conn.Module()
|
me := conn.Module()
|
||||||
d := Deps{Module: me, Node: conn.Node(),
|
d := Deps{Module: me, Node: conn.Node(), Build: process.OwnBuild(),
|
||||||
Ask: func(address string, body any) (json.RawMessage, error) {
|
Ask: func(address string, body any) (json.RawMessage, error) {
|
||||||
got, err := conn.Ask(address, body, "")
|
got, err := conn.Ask(address, body, "")
|
||||||
return got.Result, err
|
return got.Result, err
|
||||||
@@ -168,22 +175,6 @@ func StartWith(parent context.Context, d Deps, logf func(string, ...any)) (*View
|
|||||||
ctx, cancel := context.WithCancel(parent)
|
ctx, cancel := context.WithCancel(parent)
|
||||||
v := &Views{logf: logf, ctx: ctx, cancel: cancel, followers: map[string]*views.Follower{}, byState: map[string]*views.Follower{},
|
v := &Views{logf: logf, ctx: ctx, cancel: cancel, followers: map[string]*views.Follower{}, byState: map[string]*views.Follower{},
|
||||||
adopted: map[string]*adoption{}, hearers: map[string][]*adoption{}, deps: d}
|
adopted: map[string]*adoption{}, hearers: map[string][]*adoption{}, deps: d}
|
||||||
for _, s := range Specs {
|
|
||||||
s := s
|
|
||||||
call := func(tool string, body any) (json.RawMessage, error) { return d.Ask(s.Owner+"."+tool, body) }
|
|
||||||
f := &views.Follower{Owner: s.Owner, Tool: s.Tool, State: s.State, Ask: views.AskVia(call, s.Tool), Logf: logf,
|
|
||||||
Bound: d.Bound, Wait: d.Wait,
|
|
||||||
Raise: func(st views.Status) {
|
|
||||||
v.finding(unansweredFinding(v.deps.Module, v.deps.Node, st, time.Now()), st.Tool, true)
|
|
||||||
},
|
|
||||||
Clear: func(st views.Status) {
|
|
||||||
v.finding(unansweredFinding(v.deps.Module, v.deps.Node, st, time.Now()), st.Tool, false)
|
|
||||||
}}
|
|
||||||
v.followers[s.Name()] = f
|
|
||||||
v.byState[s.State] = f
|
|
||||||
v.wg.Add(1)
|
|
||||||
go func() { defer v.wg.Done(); _ = f.Start(ctx) }()
|
|
||||||
}
|
|
||||||
stopFindings := func() {}
|
stopFindings := func() {}
|
||||||
if d.StartFindings != nil {
|
if d.StartFindings != nil {
|
||||||
if stop, err := d.StartFindings(ctx); err != nil {
|
if stop, err := d.StartFindings(ctx); err != nil {
|
||||||
@@ -199,6 +190,9 @@ func StartWith(parent context.Context, d Deps, logf func(string, ...any)) (*View
|
|||||||
logf("[mesh-tools] the catalog half is not followed (%v): the console cannot say which modules exist", err)
|
logf("[mesh-tools] the catalog half is not followed (%v): the console cannot say which modules exist", err)
|
||||||
} else {
|
} else {
|
||||||
branches.Logf = func(format string, args ...any) { logf("[mesh-tools] "+format, args...) }
|
branches.Logf = func(format string, args ...any) { logf("[mesh-tools] "+format, args...) }
|
||||||
|
branches.Changed = func(_, module string, entry json.RawMessage, deleted bool, _ time.Time) {
|
||||||
|
v.claimed(module, entry, deleted)
|
||||||
|
}
|
||||||
v.branches = branches
|
v.branches = branches
|
||||||
}
|
}
|
||||||
stop, err := d.Consume(v.hear)
|
stop, err := d.Consume(v.hear)
|
||||||
@@ -214,7 +208,7 @@ func StartWith(parent context.Context, d Deps, logf func(string, ...any)) (*View
|
|||||||
func (v *Views) hear(env bus.Envelope) error {
|
func (v *Views) hear(env bus.Envelope) error {
|
||||||
defer v.heardOne()
|
defer v.heardOne()
|
||||||
v.mu.Lock()
|
v.mu.Lock()
|
||||||
hs := append([]*adoption(nil), v.hearers[env.Key]...)
|
hs := v.hearersOf(env.Key)
|
||||||
v.mu.Unlock()
|
v.mu.Unlock()
|
||||||
if len(hs) > 0 { // an event of the catalog half or the gate's source, heard by the views the branch follower adopted
|
if len(hs) > 0 { // an event of the catalog half or the gate's source, heard by the views the branch follower adopted
|
||||||
for _, a := range hs {
|
for _, a := range hs {
|
||||||
@@ -226,9 +220,12 @@ func (v *Views) hear(env bus.Envelope) error {
|
|||||||
}
|
}
|
||||||
ev, err := views.DecodeEvent(env.Body)
|
ev, err := views.DecodeEvent(env.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
v.unheard(env.Key)
|
||||||
return nil // not a views event: nothing to hold, nothing to retry
|
return nil // not a views event: nothing to hold, nothing to retry
|
||||||
}
|
}
|
||||||
|
v.mu.Lock()
|
||||||
f := v.byState[ev.State]
|
f := v.byState[ev.State]
|
||||||
|
v.mu.Unlock()
|
||||||
if f == nil || f.Owner != ev.Owner {
|
if f == nil || f.Owner != ev.Owner {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -240,6 +237,37 @@ func (v *Views) hear(env bus.Envelope) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hearersOf are the adopted views that hear the event key `<seat>.<event>` or, as its subject carries further tokens
|
||||||
|
// (`<event>.<branch>`, the mesh-catalog seat's catalog-revision), the key's shorter prefixes: the way mesh-sdk's views reader
|
||||||
|
// finds its adopted hears. The caller holds v.mu.
|
||||||
|
func (v *Views) hearersOf(key string) []*adoption {
|
||||||
|
for k := key; k != ""; {
|
||||||
|
if hs := v.hearers[k]; len(hs) > 0 {
|
||||||
|
return append([]*adoption(nil), hs...)
|
||||||
|
}
|
||||||
|
i := strings.LastIndex(k, ".")
|
||||||
|
if i <= 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
k = k[:i]
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// unheard says once per key an event no adopted view and no owner's state hears, never dropping it silently.
|
||||||
|
func (v *Views) unheard(key string) {
|
||||||
|
v.mu.Lock()
|
||||||
|
if v.unheardKeys == nil {
|
||||||
|
v.unheardKeys = map[string]bool{}
|
||||||
|
}
|
||||||
|
seen := v.unheardKeys[key]
|
||||||
|
v.unheardKeys[key] = true
|
||||||
|
v.mu.Unlock()
|
||||||
|
if !seen {
|
||||||
|
v.logf("[mesh-tools] an event %s is heard by no view of this tool runner: it is dropped (said once per key)", key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// finding writes or clears the runner's finding of a first view unanswered past its bound, through its writer (design 47 G A-28).
|
// finding writes or clears the runner's finding of a first view unanswered past its bound, through its writer (design 47 G A-28).
|
||||||
func (v *Views) finding(f condseat.Finding, tool string, raised bool) {
|
func (v *Views) finding(f condseat.Finding, tool string, raised bool) {
|
||||||
if v.deps.Findings == nil {
|
if v.deps.Findings == nil {
|
||||||
@@ -261,6 +289,13 @@ func (v *Views) finding(f condseat.Finding, tool string, raised bool) {
|
|||||||
// not answered yet, so nothing is claimed of it.
|
// not answered yet, so nothing is claimed of it.
|
||||||
func (v *Views) State(name string) (map[string][]byte, error) {
|
func (v *Views) State(name string) (map[string][]byte, error) {
|
||||||
v.mu.Lock()
|
v.mu.Lock()
|
||||||
|
if state, ok := strings.CutPrefix(name, AssignerSeat+"."); ok { // the seat's name stands for its holder's
|
||||||
|
if v.holder == nil {
|
||||||
|
v.mu.Unlock()
|
||||||
|
return nil, fmt.Errorf("the catalog half names no holder of the seat %s yet, so %s has no first view", AssignerSeat, name)
|
||||||
|
}
|
||||||
|
name = v.holder.module + "." + state
|
||||||
|
}
|
||||||
f := v.followers[name]
|
f := v.followers[name]
|
||||||
v.mu.Unlock()
|
v.mu.Unlock()
|
||||||
if f == nil {
|
if f == nil {
|
||||||
@@ -297,6 +332,10 @@ func (v *Views) Status() []views.Status {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OwnBuild is the build the tool runner was started with: the fingerprint of the want its node-engine applied, or why it is
|
||||||
|
// unknown (`own build unknown: started without MESH_FINGERPRINT`).
|
||||||
|
func (v *Views) OwnBuild() process.Build { return v.deps.Build }
|
||||||
|
|
||||||
// Entries are the entries by fingerprint the catalog half's follower keeps, with their state and since when (design 47 G A-103).
|
// Entries are the entries by fingerprint the catalog half's follower keeps, with their state and since when (design 47 G A-103).
|
||||||
func (v *Views) Entries() any {
|
func (v *Views) Entries() any {
|
||||||
if v.branches == nil {
|
if v.branches == nil {
|
||||||
@@ -489,3 +528,78 @@ func (v *Views) Modules() (map[string]catalogseat.CatalogEntry, error) {
|
|||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// holding is the views of the module that claims the assigner seat, and what stops them.
|
||||||
|
type holding struct {
|
||||||
|
module string
|
||||||
|
cancel context.CancelFunc
|
||||||
|
views []*views.Follower
|
||||||
|
}
|
||||||
|
|
||||||
|
// claimed is the branch follower's word of one entry changed: an entry that serves a verb of the assigner seat makes its module
|
||||||
|
// the holder whose views the runner follows (a holder before it is dropped), the deletion of the holder's entry drops them
|
||||||
|
// (design 47 G §616, §428). It acts on the event alone; nothing waits on a timer for the claim.
|
||||||
|
func (v *Views) claimed(module string, entry json.RawMessage, deleted bool) {
|
||||||
|
claims := false
|
||||||
|
if !deleted {
|
||||||
|
var e catalogseat.CatalogEntry
|
||||||
|
if json.Unmarshal(entry, &e) == nil {
|
||||||
|
claims = slices.ContainsFunc(e.Serves, func(s string) bool { return strings.HasPrefix(s, AssignerSeat+".") })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.mu.Lock()
|
||||||
|
cur := v.holder
|
||||||
|
switch {
|
||||||
|
case claims && cur != nil && cur.module == module, !claims && (cur == nil || cur.module != module), v.ctx.Err() != nil:
|
||||||
|
v.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if cur != nil {
|
||||||
|
v.dropHolderLocked()
|
||||||
|
}
|
||||||
|
if claims {
|
||||||
|
v.startHolderLocked(module)
|
||||||
|
}
|
||||||
|
v.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// startHolderLocked follows the first views of module, the holder of the seat, on the runner's own consumer.
|
||||||
|
func (v *Views) startHolderLocked(module string) {
|
||||||
|
ctx, cancel := context.WithCancel(v.ctx)
|
||||||
|
h := &holding{module: module, cancel: cancel}
|
||||||
|
d := v.deps
|
||||||
|
for _, s := range Specs {
|
||||||
|
s := s
|
||||||
|
call := func(tool string, body any) (json.RawMessage, error) { return d.Ask(module+"."+tool, body) }
|
||||||
|
f := &views.Follower{Owner: module, Tool: s.Tool, State: s.State, Ask: views.AskVia(call, s.Tool), Logf: v.logf,
|
||||||
|
Bound: d.Bound, Wait: d.Wait,
|
||||||
|
Raise: func(st views.Status) {
|
||||||
|
v.finding(unansweredFinding(d.Module, d.Node, st, time.Now()), st.Tool, true)
|
||||||
|
},
|
||||||
|
Clear: func(st views.Status) {
|
||||||
|
v.finding(unansweredFinding(d.Module, d.Node, st, time.Now()), st.Tool, false)
|
||||||
|
}}
|
||||||
|
v.followers[module+"."+s.State] = f
|
||||||
|
v.byState[s.State] = f
|
||||||
|
h.views = append(h.views, f)
|
||||||
|
v.wg.Add(1)
|
||||||
|
go func() { defer v.wg.Done(); _ = f.Start(ctx) }()
|
||||||
|
}
|
||||||
|
v.holder = h
|
||||||
|
v.logf("[mesh-tools] the seat %s is held by %s: its views are followed", AssignerSeat, module)
|
||||||
|
}
|
||||||
|
|
||||||
|
// dropHolderLocked stops the views of the holder and clears the findings they raised.
|
||||||
|
func (v *Views) dropHolderLocked() {
|
||||||
|
h := v.holder
|
||||||
|
v.holder = nil
|
||||||
|
h.cancel()
|
||||||
|
for _, f := range h.views {
|
||||||
|
delete(v.followers, f.Owner+"."+f.State)
|
||||||
|
delete(v.byState, f.State)
|
||||||
|
if st := f.Status(); st.Raised {
|
||||||
|
go v.finding(unansweredFinding(v.deps.Module, v.deps.Node, st, time.Now()), st.Tool, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
v.logf("[mesh-tools] %s no longer holds the seat %s: its views are no longer followed", h.module, AssignerSeat)
|
||||||
|
}
|
||||||
|
|||||||
@@ -17,6 +17,10 @@ import (
|
|||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||||
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
|
delivery "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
)
|
)
|
||||||
@@ -41,7 +45,9 @@ func TestTheRunnersConsumerCarriesTheOwnersViewsFamiliesWhenTheOwnersAreDownThen
|
|||||||
if err := json.Unmarshal(raw, &manifest); err != nil {
|
if err := json.Unmarshal(raw, &manifest); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
streamOf := map[string]string{Assigner: catalogue.StreamBusName("assigner-views")}
|
// the manifest names the assigner's views by the seat; the module the catalog half says claims it is the fixture's
|
||||||
|
const holder = "assigner-fixture"
|
||||||
|
streamOf := map[string]string{"seat:" + AssignerSeat: catalogue.StreamBusName("assigner-views")}
|
||||||
filters := map[string][]string{}
|
filters := map[string][]string{}
|
||||||
families := 0
|
families := 0
|
||||||
for _, c := range manifest.Consumes {
|
for _, c := range manifest.Consumes {
|
||||||
@@ -53,16 +59,16 @@ func TestTheRunnersConsumerCarriesTheOwnersViewsFamiliesWhenTheOwnersAreDownThen
|
|||||||
if stream == "" {
|
if stream == "" {
|
||||||
t.Fatalf("the manifest consumes %s, whose views stream the test does not know", c)
|
t.Fatalf("the manifest consumes %s, whose views stream the test does not know", c)
|
||||||
}
|
}
|
||||||
filters[stream] = append(filters[stream], process.ModuleStreamSubject(emitter, views.EventPrefix+event))
|
filters[stream] = append(filters[stream], process.ModuleStreamSubject(holder, views.EventPrefix+event))
|
||||||
families++
|
families++
|
||||||
}
|
}
|
||||||
if families != len(Specs) {
|
if families != len(Specs) {
|
||||||
t.Fatalf("the manifest consumes %d families, the runner holds %d first views", families, len(Specs))
|
t.Fatalf("the manifest consumes %d families, the runner holds %d first views", families, len(Specs))
|
||||||
}
|
}
|
||||||
runner := mt.MembershipOf("node-tools", "anchor", false, nil)
|
runner := mt.MembershipOf("node-tools", "anchor", false, nil)
|
||||||
for _, owner := range []string{Assigner} {
|
for _, seat := range []string{"seat:" + AssignerSeat} {
|
||||||
stream := streamOf[owner]
|
stream := streamOf[seat]
|
||||||
mesh.ModuleStream(t, owner, stream)
|
mesh.ModuleStream(t, holder, stream)
|
||||||
mesh.ConsumerOn(t, stream, "anchor", "node-tools", filters[stream], 2*time.Second)
|
mesh.ConsumerOn(t, stream, "anchor", "node-tools", filters[stream], 2*time.Second)
|
||||||
runner.Hears = append(runner.Hears, bus.HeardIssued{Stream: stream, Consumer: "anchor_node-tools"})
|
runner.Hears = append(runner.Hears, bus.HeardIssued{Stream: stream, Consumer: "anchor_node-tools"})
|
||||||
}
|
}
|
||||||
@@ -93,13 +99,13 @@ func TestTheRunnersConsumerCarriesTheOwnersViewsFamiliesWhenTheOwnersAreDownThen
|
|||||||
t.Cleanup(stop)
|
t.Cleanup(stop)
|
||||||
|
|
||||||
// The owners are down: no tool answers, nothing is claimed, and past the bound each view is a finding.
|
// The owners are down: no tool answers, nothing is claimed, and past the bound each view is a finding.
|
||||||
if _, err := v.State(Assigner + ".assignments"); err == nil {
|
if _, err := v.State(AssignmentsRead); err == nil {
|
||||||
t.Fatal("a state its owner has not answered is claimed")
|
t.Fatal("a state its owner has not answered is claimed")
|
||||||
}
|
}
|
||||||
mt.Until(t, func() error {
|
mt.Until(t, func() error {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
if len(findings) != len(Specs)+catalogViews {
|
if len(findings) != catalogViews {
|
||||||
return errFindings(len(findings))
|
return errFindings(len(findings))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -111,10 +117,25 @@ func TestTheRunnersConsumerCarriesTheOwnersViewsFamiliesWhenTheOwnersAreDownThen
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Cleanup(nc.Close)
|
t.Cleanup(nc.Close)
|
||||||
|
respond := func(subject string, answer any) {
|
||||||
|
if _, err := nc.Subscribe(subject, func(m *nats.Msg) {
|
||||||
|
raw, _ := json.Marshal(answer)
|
||||||
|
body, _ := json.Marshal(map[string]json.RawMessage{"result": raw})
|
||||||
|
_ = m.Respond(body)
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// the catalog half answers: the gate's source names main, whose entries say the fixture claims the assigner seat
|
||||||
|
respond("mesh.seat.mesh-delivery.tool.source", delivery.SourceAnswer{Branches: []string{"main"}})
|
||||||
|
respond("mesh.seat.mesh-catalog.tool.registrations", catalogseat.RegistrationsAnswer{Registrations: []catalogseat.Registration{}})
|
||||||
|
respond("mesh.seat.mesh-catalog.tool.revision", catalogseat.RevisionAnswer{
|
||||||
|
Revision: &catalogseat.CatalogRevision{Revision: 3, Kind: meshcatalogclient.KindTrunk, Branch: "main"},
|
||||||
|
Entries: []catalogseat.CatalogEntry{{Module: holder, Serves: []string{AssignerSeat + ".assignments"}}}})
|
||||||
for _, s := range Specs {
|
for _, s := range Specs {
|
||||||
s := s
|
s := s
|
||||||
if _, err := nc.Subscribe("mesh.mod."+s.Owner+".tool."+s.Tool, func(m *nats.Msg) {
|
if _, err := nc.Subscribe("mesh.mod."+holder+".tool."+s.Tool, func(m *nats.Msg) {
|
||||||
answer, _ := json.Marshal(views.Answer{V: 1, Owner: s.Owner, State: s.State, Revision: 4, Created: time.Unix(1000, 0).UTC(),
|
answer, _ := json.Marshal(views.Answer{V: 1, Owner: holder, State: s.State, Revision: 4, Created: time.Unix(1000, 0).UTC(),
|
||||||
Values: map[string]json.RawMessage{"first": json.RawMessage(`{"n":1}`)}})
|
Values: map[string]json.RawMessage{"first": json.RawMessage(`{"n":1}`)}})
|
||||||
body, _ := json.Marshal(map[string]json.RawMessage{"result": answer})
|
body, _ := json.Marshal(map[string]json.RawMessage{"result": answer})
|
||||||
_ = m.Respond(body)
|
_ = m.Respond(body)
|
||||||
@@ -130,7 +151,7 @@ func TestTheRunnersConsumerCarriesTheOwnersViewsFamiliesWhenTheOwnersAreDownThen
|
|||||||
mt.Until(t, func() error {
|
mt.Until(t, func() error {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
if len(findings) != catalogViews { // the seats' verbs are not served in this test: the catalog half stays unanswered
|
if len(findings) != 0 { // every view answered clears its finding
|
||||||
return errFindings(len(findings))
|
return errFindings(len(findings))
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
@@ -138,9 +159,9 @@ func TestTheRunnersConsumerCarriesTheOwnersViewsFamiliesWhenTheOwnersAreDownThen
|
|||||||
|
|
||||||
// Each owner's next event arrives on the runner's consumer: all four families are bound.
|
// Each owner's next event arrives on the runner's consumer: all four families are bound.
|
||||||
for _, s := range Specs {
|
for _, s := range Specs {
|
||||||
ev, _ := json.Marshal(views.Event{V: 1, Owner: s.Owner, State: s.State, Key: "next", Revision: 5, Created: time.Unix(1000, 0).UTC(),
|
ev, _ := json.Marshal(views.Event{V: 1, Owner: holder, State: s.State, Key: "next", Revision: 5, Created: time.Unix(1000, 0).UTC(),
|
||||||
Value: json.RawMessage(`{"n":2}`)})
|
Value: json.RawMessage(`{"n":2}`)})
|
||||||
mesh.Emit(t, process.ModuleStreamSubject(s.Owner, views.EventPrefix+s.State), json.RawMessage(ev))
|
mesh.Emit(t, process.ModuleStreamSubject(holder, views.EventPrefix+s.State), json.RawMessage(ev))
|
||||||
}
|
}
|
||||||
for _, s := range Specs {
|
for _, s := range Specs {
|
||||||
name := s.Name()
|
name := s.Name()
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
condseat "git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshconditions"
|
||||||
"git.novox.be/novox/mesh-delivery/contracts/go/clients/meshcatalogclient"
|
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/meshcatalogclient"
|
||||||
catalogseat "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
catalogseat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
delivery "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshdelivery"
|
delivery "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshdelivery"
|
||||||
"git.novox.be/novox/mesh-sdk/go/views"
|
"git.novox.be/novox/mesh-sdk/go/views"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
@@ -32,12 +32,14 @@ type owners struct {
|
|||||||
// catalog is the revision of the watched branch main the seat mesh-catalog answers, and modules its entries
|
// catalog is the revision of the watched branch main the seat mesh-catalog answers, and modules its entries
|
||||||
catalog int64
|
catalog int64
|
||||||
modules []string
|
modules []string
|
||||||
|
// holder is the module among them that claims the assigner seat
|
||||||
|
holder string
|
||||||
}
|
}
|
||||||
|
|
||||||
func newOwners() *owners {
|
func newOwners() *owners {
|
||||||
return &owners{state: map[string]map[string]string{"assignments": {"anchor": `{"p":1}`}, "seat-holders": {"seat": `{"h":1}`}},
|
return &owners{state: map[string]map[string]string{"assignments": {"anchor": `{"p":1}`}, "seat-holders": {"seat": `{"h":1}`}},
|
||||||
rev: map[string]uint64{"assignments": 4, "seat-holders": 2}, asked: map[string]int{}, finds: map[string]bool{},
|
rev: map[string]uint64{"assignments": 4, "seat-holders": 2}, asked: map[string]int{}, finds: map[string]bool{},
|
||||||
catalog: 3, modules: []string{"web"}}
|
catalog: 3, modules: []string{"web", fixtureHolder}, holder: fixtureHolder}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write and Clear are the runner's finding writer in a test: the findings written and not cleared, by their key.
|
// Write and Clear are the runner's finding writer in a test: the findings written and not cleared, by their key.
|
||||||
@@ -71,7 +73,11 @@ func (o *owners) ask(address string, _ any) (json.RawMessage, error) {
|
|||||||
case "seat:mesh-catalog.revision":
|
case "seat:mesh-catalog.revision":
|
||||||
a := catalogseat.RevisionAnswer{Revision: &catalogseat.CatalogRevision{Revision: o.catalog, Kind: meshcatalogclient.KindTrunk, Branch: "main"}}
|
a := catalogseat.RevisionAnswer{Revision: &catalogseat.CatalogRevision{Revision: o.catalog, Kind: meshcatalogclient.KindTrunk, Branch: "main"}}
|
||||||
for _, m := range o.modules {
|
for _, m := range o.modules {
|
||||||
a.Entries = append(a.Entries, catalogseat.CatalogEntry{Module: m, Manifest: map[string]any{"module": m, "tools": []string{m + "_check"}}})
|
e := catalogseat.CatalogEntry{Module: m, Manifest: map[string]any{"module": m, "tools": []string{m + "_check"}}}
|
||||||
|
if m == o.holder {
|
||||||
|
e.Serves = []string{AssignerSeat + ".assignments", AssignerSeat + ".seat-holders"}
|
||||||
|
}
|
||||||
|
a.Entries = append(a.Entries, e)
|
||||||
}
|
}
|
||||||
return json.Marshal(a)
|
return json.Marshal(a)
|
||||||
}
|
}
|
||||||
@@ -94,14 +100,10 @@ func (o *owners) say(t *testing.T, state, key, value string, revision uint64, ga
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func owner(state string) string {
|
// fixtureHolder is the module the fixture catalog half says claims the assigner seat: no name is in the code.
|
||||||
for _, s := range Specs {
|
const fixtureHolder = "assigner-fixture"
|
||||||
if s.State == state {
|
|
||||||
return s.Owner
|
func owner(state string) string { return fixtureHolder }
|
||||||
}
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func eventually(t *testing.T, what string, ok func() bool) {
|
func eventually(t *testing.T, what string, ok func() bool) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
@@ -127,39 +129,43 @@ func TestTheRunnerHoldsTheFourStatesFromTheOwnersFirstViewsAndTheirEvents(t *tes
|
|||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
// Down: nothing is claimed, and past the bound each unanswered view is a finding.
|
// Down: nothing is claimed, and past the bound each unanswered view is a finding.
|
||||||
if _, err := v.State("mesh-delivery-assigner.assignments"); err == nil || !strings.Contains(err.Error(), "not been answered") {
|
if _, err := v.State(AssignmentsRead); err == nil || !strings.Contains(err.Error(), "names no holder") {
|
||||||
t.Fatalf("a state its owner has not answered is claimed: %v", err)
|
t.Fatalf("a state whose holder is not known is claimed: %v", err)
|
||||||
}
|
}
|
||||||
eventually(t, "no finding past the bound", func() bool { o.mu.Lock(); defer o.mu.Unlock(); return len(o.finds) == 4 })
|
eventually(t, "no finding past the bound", func() bool { o.mu.Lock(); defer o.mu.Unlock(); return len(o.finds) == 2 })
|
||||||
|
|
||||||
// Up: answered, the findings are cleared, and the pictures hold the owners' values.
|
// Up: answered, the findings are cleared, and the pictures hold the owners' values.
|
||||||
o.mu.Lock()
|
o.mu.Lock()
|
||||||
o.down = false
|
o.down = false
|
||||||
o.mu.Unlock()
|
o.mu.Unlock()
|
||||||
eventually(t, "not answered", func() bool { _, err := v.State("mesh-delivery-assigner.seat-holders"); return err == nil })
|
eventually(t, "not answered", func() bool { _, err := v.State(SeatHoldersRead); return err == nil })
|
||||||
eventually(t, "findings not cleared", func() bool { o.mu.Lock(); defer o.mu.Unlock(); return len(o.finds) == 0 })
|
eventually(t, "findings not cleared", func() bool { o.mu.Lock(); defer o.mu.Unlock(); return len(o.finds) == 0 })
|
||||||
if got, _ := v.Entry("mesh-delivery-assigner.seat-holders", "none"); got != nil {
|
if got, _ := v.Entry(AssignerSeat+".seat-holders", "none"); got != nil {
|
||||||
t.Errorf("an absent key is %q", got)
|
t.Errorf("an absent key is %q", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
// The catalog half is followed by the shared branch follower on the runner's own consumer: the gate's source names main,
|
// The catalog half is followed by the shared branch follower on the runner's own consumer: the gate's source names main,
|
||||||
// main's view is adopted, and its entries are the modules, each with its manifest (design 47 G §196, §614).
|
// main's view is adopted, and its entries are the modules, each with its manifest (design 47 G §196, §614).
|
||||||
eventually(t, "the catalog half holds no modules", func() bool { m, err := v.Modules(); return err == nil && len(m) == 1 })
|
eventually(t, "the catalog half holds no modules", func() bool { m, err := v.Modules(); return err == nil && len(m) == 2 })
|
||||||
m, _ := v.Modules()
|
m, _ := v.Modules()
|
||||||
if m["web"].Manifest["module"] != "web" {
|
if m["web"].Manifest["module"] != "web" {
|
||||||
t.Errorf("the module web is %+v", m["web"])
|
t.Errorf("the module web is %+v", m["web"])
|
||||||
}
|
}
|
||||||
// A catalog-revision of the branch is heard on the same consumer and asks the view once more.
|
// A catalog-revision of the branch is heard on the same consumer and asks the view once more.
|
||||||
o.mu.Lock()
|
o.mu.Lock()
|
||||||
o.catalog, o.modules = 4, []string{"web", "db"}
|
o.catalog, o.modules = 4, []string{"web", "db", fixtureHolder}
|
||||||
o.mu.Unlock()
|
o.mu.Unlock()
|
||||||
ev, _ := json.Marshal(catalogseat.CatalogRevisionEvent{V: 1, Branch: "main", Kind: meshcatalogclient.KindTrunk, Revision: 4})
|
ev, _ := json.Marshal(catalogseat.CatalogRevisionEvent{V: 1, Branch: "main", Kind: meshcatalogclient.KindTrunk, Revision: 4})
|
||||||
if err := o.deliver(bus.Envelope{Key: catalogseat.Seat + "." + catalogseat.EventCatalogRevision, Body: ev}); err != nil {
|
if err := o.deliver(bus.Envelope{Key: catalogseat.Seat + "." + catalogseat.EventCatalogRevision + ".main", Body: ev}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
eventually(t, "the catalog-revision was not taken", func() bool { m, err := v.Modules(); return err == nil && len(m) == 2 })
|
eventually(t, "the catalog-revision was not taken", func() bool { m, err := v.Modules(); return err == nil && len(m) == 3 })
|
||||||
|
// An event no view hears is said once per key, not dropped silently.
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
_ = o.deliver(bus.Envelope{Key: "some-seat.unknown-event.x", Body: json.RawMessage(`"x"`)})
|
||||||
|
}
|
||||||
// And the halves by branch, with their revision, which mesh_wait names checking an emitter (design 34 every-event §14).
|
// And the halves by branch, with their revision, which mesh_wait names checking an emitter (design 34 every-event §14).
|
||||||
if h, err := v.Halves(); err != nil || h["main"].Revision.Revision != 4 || len(h["main"].Entries) != 2 {
|
if h, err := v.Halves(); err != nil || h["main"].Revision.Revision != 4 || len(h["main"].Entries) != 3 {
|
||||||
t.Errorf("the halves: %+v, %v", h, err)
|
t.Errorf("the halves: %+v, %v", h, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,7 +176,7 @@ func TestTheRunnerHoldsTheFourStatesFromTheOwnersFirstViewsAndTheirEvents(t *tes
|
|||||||
o.say(t, "assignments", "laptop", `{"p":0}`, 5, false)
|
o.say(t, "assignments", "laptop", `{"p":0}`, 5, false)
|
||||||
o.say(t, "assignments", "anchor", "", 6, false)
|
o.say(t, "assignments", "anchor", "", 6, false)
|
||||||
// (a deleted mark carries no value: Deleted is the encoding's, set below)
|
// (a deleted mark carries no value: Deleted is the encoding's, set below)
|
||||||
if got, _ := v.Entry("mesh-delivery-assigner.assignments", "laptop"); string(got) != `{"p":2}` {
|
if got, _ := v.Entry(AssignerSeat+".assignments", "laptop"); string(got) != `{"p":2}` {
|
||||||
t.Errorf("the next revision is not applied: %q", got)
|
t.Errorf("the next revision is not applied: %q", got)
|
||||||
}
|
}
|
||||||
if n := asked("assignments"); n != before {
|
if n := asked("assignments"); n != before {
|
||||||
@@ -188,7 +194,7 @@ func TestTheRunnerHoldsTheFourStatesFromTheOwnersFirstViewsAndTheirEvents(t *tes
|
|||||||
assignments = s
|
assignments = s
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if assignments.Owner != "mesh-delivery-assigner" || assignments.Tool != "assignments" || assignments.Asks < 2 || assignments.Answered.IsZero() {
|
if assignments.Owner != fixtureHolder || assignments.Tool != "assignments" || assignments.Asks < 2 || assignments.Answered.IsZero() {
|
||||||
t.Errorf("the status of assignments is %+v", assignments)
|
t.Errorf("the status of assignments is %+v", assignments)
|
||||||
}
|
}
|
||||||
manifests := asked("seat-holders")
|
manifests := asked("seat-holders")
|
||||||
@@ -205,6 +211,9 @@ func TestTheRunnerHoldsTheFourStatesFromTheOwnersFirstViewsAndTheirEvents(t *tes
|
|||||||
}
|
}
|
||||||
lmu.Lock()
|
lmu.Lock()
|
||||||
defer lmu.Unlock()
|
defer lmu.Unlock()
|
||||||
|
if n := strings.Count(strings.Join(logs, "\n"), "heard by no view"); n != 1 {
|
||||||
|
t.Errorf("an unheard event was said %d times, want once: %v", n, logs)
|
||||||
|
}
|
||||||
if !strings.Contains(strings.Join(logs, "\n"), "a gap in") {
|
if !strings.Contains(strings.Join(logs, "\n"), "a gap in") {
|
||||||
t.Errorf("the gap was not said in the log: %v", logs)
|
t.Errorf("the gap was not said in the log: %v", logs)
|
||||||
}
|
}
|
||||||
@@ -228,13 +237,19 @@ func TestTheFirstViewsAreTheManifestsViews(t *testing.T) {
|
|||||||
t.Errorf("the first view %s is read by no name here", s.Name())
|
t.Errorf("the first view %s is read by no name here", s.Name())
|
||||||
}
|
}
|
||||||
delete(want, s.Name())
|
delete(want, s.Name())
|
||||||
if view := s.Owner + ".views." + s.Tool; !slices.Contains(m.Consumes, view) {
|
// the family is named by the seat, never by its holder (design 47 G §616)
|
||||||
|
if view := "seat:" + AssignerSeat + ".views." + s.Tool; !slices.Contains(m.Consumes, view) {
|
||||||
t.Errorf("the first view %s has no family in the manifest's consumes %v", view, m.Consumes)
|
t.Errorf("the first view %s has no family in the manifest's consumes %v", view, m.Consumes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(want) > 0 {
|
if len(want) > 0 {
|
||||||
t.Errorf("no first view reads %v", want)
|
t.Errorf("no first view reads %v", want)
|
||||||
}
|
}
|
||||||
|
for _, c := range m.Consumes {
|
||||||
|
if strings.Contains(c, "assigner") && !strings.HasPrefix(c, "seat:") {
|
||||||
|
t.Errorf("the manifest names the assigner by a module: %s", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
// the catalog half's follower hears these events and asks these verbs, and the manifest says so (design 47 G §614)
|
// the catalog half's follower hears these events and asks these verbs, and the manifest says so (design 47 G §614)
|
||||||
for _, ev := range []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved"} {
|
for _, ev := range []string{"mesh-catalog.catalog-revision", "mesh-catalog.registration-changed", "mesh-delivery.source-moved"} {
|
||||||
if !slices.Contains(m.Consumes, ev) {
|
if !slices.Contains(m.Consumes, ev) {
|
||||||
@@ -246,4 +261,42 @@ func TestTheFirstViewsAreTheManifestsViews(t *testing.T) {
|
|||||||
t.Errorf("the manifest still consumes the indexer's %s", ev)
|
t.Errorf("the manifest still consumes the indexer's %s", ev)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// design 47 G §616: the holder of the assigner seat is whichever module the catalog half says serves it; when another one
|
||||||
|
// claims it the views are of the new holder, and when none does the seat's names answer that the catalog half names no holder.
|
||||||
|
t.Run("TheAssignersViewsFollowTheModuleThatClaimsTheSeat", func(t *testing.T) {
|
||||||
|
o := newOwners()
|
||||||
|
deps := Deps{Module: "node-tools", Ask: o.ask, Bound: time.Second, Wait: 10 * time.Millisecond,
|
||||||
|
Consume: func(deliver func(bus.Envelope) error) (func(), error) { o.deliver = deliver; return func() {}, nil }, Findings: o}
|
||||||
|
v, stop := StartWith(context.Background(), deps, func(string, ...any) {})
|
||||||
|
defer stop()
|
||||||
|
eventually(t, "not answered", func() bool { _, err := v.State(AssignmentsRead); return err == nil })
|
||||||
|
ownerOf := func() string {
|
||||||
|
for _, s := range v.Status() {
|
||||||
|
if s.State == "assignments" {
|
||||||
|
return s.Owner
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if ownerOf() != fixtureHolder {
|
||||||
|
t.Fatalf("the views are of %q", ownerOf())
|
||||||
|
}
|
||||||
|
revise := func(rev int64, holder string, modules ...string) {
|
||||||
|
o.mu.Lock()
|
||||||
|
o.catalog, o.modules, o.holder = rev, modules, holder
|
||||||
|
o.mu.Unlock()
|
||||||
|
ev, _ := json.Marshal(catalogseat.CatalogRevisionEvent{V: 1, Branch: "main", Kind: meshcatalogclient.KindTrunk, Revision: rev})
|
||||||
|
if err := o.deliver(bus.Envelope{Key: catalogseat.Seat + "." + catalogseat.EventCatalogRevision, Body: ev}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
revise(4, "other-holder", "web", "other-holder")
|
||||||
|
eventually(t, "the views did not move to the new holder", func() bool { return ownerOf() == "other-holder" })
|
||||||
|
eventually(t, "not answered", func() bool { _, err := v.State(SeatHoldersRead); return err == nil })
|
||||||
|
revise(5, "", "web")
|
||||||
|
eventually(t, "the views stayed after the claim went", func() bool {
|
||||||
|
_, err := v.State(AssignmentsRead)
|
||||||
|
return err != nil && strings.Contains(err.Error(), "names no holder")
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package launch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DrainBoundSetting is the tool runner module's setting of how long, once told to stop, it waits for the calls in flight in its
|
||||||
|
// bundles to finish, a duration text; DefaultDrainBound is its default (design 47 H2 §813 (12), H-A-342 (2), H-A-377).
|
||||||
|
const (
|
||||||
|
DrainBoundSetting = "drain-bound"
|
||||||
|
DefaultDrainBound = 30 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// inFlight is one ask the runner made of a bundle and is still waiting on: the bundle, the verb (a tool's name, else the
|
||||||
|
// method), when it was asked, and closed when the drain cuts it.
|
||||||
|
type inFlight struct {
|
||||||
|
module, verb string
|
||||||
|
at time.Time
|
||||||
|
cut chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// asks is every ask in flight in every bundle the runner launched, and whether the runner is draining: from then on it makes
|
||||||
|
// no new ask (design 47 H2 §813 (12)).
|
||||||
|
var asks = struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
draining bool
|
||||||
|
next uint64
|
||||||
|
of map[uint64]*inFlight
|
||||||
|
// ended is signalled at each ask's end while draining, so the drain hears the last end instead of looking again.
|
||||||
|
ended chan struct{}
|
||||||
|
}{of: map[uint64]*inFlight{}}
|
||||||
|
|
||||||
|
// afterStop is an ask made after the stop began that still reached the runner: a call the bus handed it before its
|
||||||
|
// subscriptions were down, or a message a consumer hands on. It is not taken and its caller is answered nothing, never
|
||||||
|
// refused, so the caller's kept call paces and meets the new runner (design 47 H2 §813 (12) as H-A-369 has it); a call made
|
||||||
|
// once the subscriptions are down meets no responders instead (H-A-570 (1)).
|
||||||
|
type afterStop struct{ module, verb string }
|
||||||
|
|
||||||
|
func (e *afterStop) Error() string {
|
||||||
|
return fmt.Sprintf("%s's %s was not taken: the tool runner is stopping, and a call after its stop is answered nothing", e.module, e.verb)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unanswered says the call is left without an answer, so its kept call asks again and meets the new runner.
|
||||||
|
func (e *afterStop) Unanswered() bool { return true }
|
||||||
|
|
||||||
|
// cutCall is a call the drain cut at its bound. Its caller is answered nothing, so it sees a transport fault (§813 (12)): the
|
||||||
|
// bus reads Unanswered and sends no reply.
|
||||||
|
type cutCall struct{ module, verb string }
|
||||||
|
|
||||||
|
func (e *cutCall) Error() string {
|
||||||
|
return fmt.Sprintf("%s's %s was cut: it outlived the tool runner's drain bound at its stop", e.module, e.verb)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unanswered says the call is left without an answer, so its caller sees a transport fault.
|
||||||
|
func (e *cutCall) Unanswered() bool { return true }
|
||||||
|
|
||||||
|
// begin records an ask about to be made; once the runner drains it takes none, and its caller is answered nothing.
|
||||||
|
func begin(module, verb string) (uint64, *inFlight, error) {
|
||||||
|
asks.mu.Lock()
|
||||||
|
defer asks.mu.Unlock()
|
||||||
|
if asks.draining {
|
||||||
|
return 0, nil, &afterStop{module: module, verb: verb}
|
||||||
|
}
|
||||||
|
asks.next++
|
||||||
|
f := &inFlight{module: module, verb: verb, at: time.Now(), cut: make(chan struct{})}
|
||||||
|
asks.of[asks.next] = f
|
||||||
|
return asks.next, f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// end is an ask's end, answered or not.
|
||||||
|
func end(id uint64) {
|
||||||
|
asks.mu.Lock()
|
||||||
|
defer asks.mu.Unlock()
|
||||||
|
delete(asks.of, id)
|
||||||
|
if asks.draining {
|
||||||
|
select {
|
||||||
|
case asks.ended <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drain is the runner's stop (design 47 H2 §813 (12), H-A-342 (2), H-A-353), once it took down every subscription it answers
|
||||||
|
// calls on (the bus's StopAnswering, H-A-570 (1)): from now on no new ask is made of any bundle, the
|
||||||
|
// asks in flight are waited for within bound, and each still in flight at the bound is cut, with a journal line naming the
|
||||||
|
// bundle, the verb and the call's age; its caller is answered nothing. It returns once no ask is in flight or the bound
|
||||||
|
// passed; the runner then stops its bundles itself.
|
||||||
|
func Drain(bound time.Duration, logf func(string, ...any)) {
|
||||||
|
asks.mu.Lock()
|
||||||
|
asks.draining = true
|
||||||
|
asks.ended = make(chan struct{}, 1)
|
||||||
|
ended := asks.ended
|
||||||
|
asks.mu.Unlock()
|
||||||
|
timer := time.NewTimer(bound)
|
||||||
|
defer timer.Stop()
|
||||||
|
for {
|
||||||
|
asks.mu.Lock()
|
||||||
|
left := len(asks.of)
|
||||||
|
asks.mu.Unlock()
|
||||||
|
if left == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ended:
|
||||||
|
case <-timer.C:
|
||||||
|
asks.mu.Lock()
|
||||||
|
ids := make([]uint64, 0, len(asks.of))
|
||||||
|
for id := range asks.of {
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||||
|
now := time.Now()
|
||||||
|
for _, id := range ids {
|
||||||
|
f := asks.of[id]
|
||||||
|
logf("[mesh-tools] at its stop the tool runner cut %s's call %s, %s old: it outlived the drain bound of %s, and its "+
|
||||||
|
"caller is answered nothing (design 47 H2 §813 (12))", f.module, f.verb, now.Sub(f.at).Round(time.Millisecond), bound)
|
||||||
|
close(f.cut)
|
||||||
|
delete(asks.of, id)
|
||||||
|
}
|
||||||
|
asks.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// undrain is a test's: the runner serves again as before its stop.
|
||||||
|
func undrain() {
|
||||||
|
asks.mu.Lock()
|
||||||
|
asks.draining = false
|
||||||
|
asks.of = map[uint64]*inFlight{}
|
||||||
|
asks.mu.Unlock()
|
||||||
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
package launch
|
package launch
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -51,6 +53,11 @@ done
|
|||||||
// to stop, the power bundle among them dialling the system bus again, which restarted the bus during the
|
// to stop, the power bundle among them dialling the system bus again, which restarted the bus during the
|
||||||
// shutdown and held it 29 minutes). A bundle that exits while it serves is started again; once the runtime
|
// shutdown and held it 29 minutes). A bundle that exits while it serves is started again; once the runtime
|
||||||
// itself is stopping, none is, by a restart or by a call.
|
// itself is stopping, none is, by a restart or by a call.
|
||||||
|
//
|
||||||
|
// **The tool runner drains at a stop** (design 47 H2 §813 (12), H-A-342 (2), H-A-353, H-A-369): once it drains, no new call is
|
||||||
|
// taken and its caller is answered nothing (Unanswered), never refused; a call
|
||||||
|
// in flight that ends within the drain bound is answered; one still in flight at the bound is cut, said with its bundle, its verb
|
||||||
|
// and its age, and left unanswered (Unanswered, so the bus sends its caller nothing: a transport fault).
|
||||||
func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
|
func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
|
||||||
saved := RestartFirst
|
saved := RestartFirst
|
||||||
RestartFirst = 10 * time.Millisecond
|
RestartFirst = 10 * time.Millisecond
|
||||||
@@ -59,12 +66,108 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
|
|||||||
name string
|
name string
|
||||||
stopping bool
|
stopping bool
|
||||||
starts int
|
starts int
|
||||||
|
drain time.Duration // a drain row: the runner drains its calls in flight within this bound
|
||||||
|
release bool // a drain row's held call ends within the bound
|
||||||
}{
|
}{
|
||||||
{"a bundle that dies while the runtime serves", false, 2},
|
{"a bundle that dies while the runtime serves", false, 2, 0, false},
|
||||||
{"a bundle signalled with the stopping runtime", true, 1},
|
{"a bundle signalled with the stopping runtime", true, 1, 0, false},
|
||||||
|
{"a call that ends within the drain bound is answered, and a call after the stop is answered nothing", false, 0, 10 * time.Second, true},
|
||||||
|
{"a call that outlives the drain bound is cut and said", false, 0, 50 * time.Millisecond, false},
|
||||||
} {
|
} {
|
||||||
t.Run(row.name, func(t *testing.T) {
|
t.Run(row.name, func(t *testing.T) {
|
||||||
shuttingDown.Store(false)
|
shuttingDown.Store(false)
|
||||||
|
if row.drain > 0 {
|
||||||
|
t.Cleanup(undrain)
|
||||||
|
dir := t.TempDir()
|
||||||
|
entry, hold := filepath.Join(dir, "bundle"), filepath.Join(dir, "hold")
|
||||||
|
if err := os.WriteFile(entry, []byte(holdingBundle), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := syscall.Mkfifo(hold, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l, err := Start("holding", entry, append(os.Environ(), "HOLD="+hold), &subscribing{}, t.Logf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(l.Stop)
|
||||||
|
run := l.Registrations[0].Tools[0].Run
|
||||||
|
type answer struct {
|
||||||
|
raw json.RawMessage
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
first := make(chan answer, 1)
|
||||||
|
go func() { raw, err := run("", json.RawMessage(`{}`)); first <- answer{raw, err} }()
|
||||||
|
// The call is in flight once the runner counted it.
|
||||||
|
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) {
|
||||||
|
asks.mu.Lock()
|
||||||
|
n := len(asks.of)
|
||||||
|
asks.mu.Unlock()
|
||||||
|
if n == 1 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("the call was never in flight")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var mu sync.Mutex
|
||||||
|
var said []string
|
||||||
|
drained := make(chan struct{})
|
||||||
|
began := time.Now()
|
||||||
|
go func() {
|
||||||
|
Drain(row.drain, func(f string, a ...any) { mu.Lock(); said = append(said, fmt.Sprintf(f, a...)); mu.Unlock() })
|
||||||
|
close(drained)
|
||||||
|
}()
|
||||||
|
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(time.Millisecond) {
|
||||||
|
asks.mu.Lock()
|
||||||
|
d := asks.draining
|
||||||
|
asks.mu.Unlock()
|
||||||
|
if d {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("the drain never began")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if row.release {
|
||||||
|
// 721/AC4: a call that still reaches the runner after its stop began gets no answer from it, no typed fault
|
||||||
|
// (H-A-570, withdrawing H-A-542's answer): every later one meets no responders on the bus.
|
||||||
|
var unanswered interface{ Unanswered() bool }
|
||||||
|
var kinded interface{ ErrorKind() string }
|
||||||
|
if _, err := run("", json.RawMessage(`{}`)); !errors.As(err, &unanswered) || !unanswered.Unanswered() ||
|
||||||
|
errors.As(err, &kinded) {
|
||||||
|
t.Errorf("a call made after the stop ended %v, want it answered nothing, never refused", err)
|
||||||
|
}
|
||||||
|
f, err := os.OpenFile(hold, os.O_WRONLY, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = f.WriteString("go\n")
|
||||||
|
_ = f.Close()
|
||||||
|
}
|
||||||
|
got := <-first
|
||||||
|
<-drained
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if row.release {
|
||||||
|
if got.err != nil || !strings.Contains(string(got.raw), "held") {
|
||||||
|
t.Errorf("the call in flight was answered %s, %v; want it finished", got.raw, got.err)
|
||||||
|
}
|
||||||
|
if time.Since(began) >= row.drain || len(said) != 0 {
|
||||||
|
t.Errorf("the drain took %s and said %q; want it ended at the call's end, saying nothing", time.Since(began), said)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var unanswered interface{ Unanswered() bool }
|
||||||
|
if !errors.As(got.err, &unanswered) || !unanswered.Unanswered() {
|
||||||
|
t.Errorf("the call past the bound ended %v, want it cut and unanswered", got.err)
|
||||||
|
}
|
||||||
|
if len(said) != 1 || !strings.Contains(said[0], "holding") || !strings.Contains(said[0], "hold,") ||
|
||||||
|
!strings.Contains(said[0], "old") {
|
||||||
|
t.Errorf("the cut was said %q, want one line naming the bundle, the verb and the call's age", said)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
entry, out := filepath.Join(dir, "bundle"), filepath.Join(dir, "out")
|
entry, out := filepath.Join(dir, "bundle"), filepath.Join(dir, "out")
|
||||||
if err := os.WriteFile(entry, []byte(notingBundle), 0o755); err != nil {
|
if err := os.WriteFile(entry, []byte(notingBundle), 0o755); err != nil {
|
||||||
@@ -114,3 +217,17 @@ func TestABundleIsStartedAgainUnlessTheRuntimeIsStopping(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// holdingBundle serves one tool, hold, which answers only once a line can be read from the fifo $HOLD: a call that lasts as long
|
||||||
|
// as the test keeps it.
|
||||||
|
const holdingBundle = `#!/bin/sh
|
||||||
|
while IFS= read -r line; do
|
||||||
|
id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\)[,}].*/\1/p')
|
||||||
|
case "$line" in
|
||||||
|
*'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
|
||||||
|
*'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"hold","inputSchema":{}}]}}\n' "$id" ;;
|
||||||
|
*'"method":"tools/call"'*) read -r go < "$HOLD"
|
||||||
|
printf '{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"{\\"held\\":true}"}]}}\n' "$id" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
`
|
||||||
|
|||||||
@@ -46,6 +46,35 @@ type Tool struct {
|
|||||||
// Run calls the tool for caller: the bus user the call's subject named, or "" when it named none. A
|
// Run calls the tool for caller: the bus user the call's subject named, or "" when it named none. A
|
||||||
// caller is handed to the bundle in the call's `_meta` (MetaCaller), never among its arguments.
|
// caller is handed to the bundle in the call's `_meta` (MetaCaller), never among its arguments.
|
||||||
Run func(caller string, args json.RawMessage) (json.RawMessage, error)
|
Run func(caller string, args json.RawMessage) (json.RawMessage, error)
|
||||||
|
// RunWithin is Run that waits within for the bundle's answer, the `timeout` the verb's seat definition names (design 47 H §760,
|
||||||
|
// H-A-43); zero waits CallTimeout. A tool the runtime serves itself has none: Run is its call.
|
||||||
|
RunWithin func(caller, ask string, args json.RawMessage, within time.Duration) (json.RawMessage, error)
|
||||||
|
// within is the wait Within set, which Call hands RunWithin.
|
||||||
|
within time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call runs the tool for caller, handing a bundle the ask id the call carried in its request header (stdio.AskHeader; design 47 H2
|
||||||
|
// §775, H-A-351), which the runtime names in the call's `_meta` under stdio.MetaAsk; "" when it carried none. A tool the runtime
|
||||||
|
// serves itself is its Run.
|
||||||
|
func (t Tool) Call(caller, ask string, args json.RawMessage) (json.RawMessage, error) {
|
||||||
|
if t.RunWithin == nil {
|
||||||
|
return t.Run(caller, args)
|
||||||
|
}
|
||||||
|
return t.RunWithin(caller, ask, args, t.within)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Within is the tool as called for a verb whose definition names a timeout: its Run waits within for the bundle's answer. A zero
|
||||||
|
// within, and a tool that has no RunWithin, are the tool as it is.
|
||||||
|
func (t Tool) Within(within time.Duration) Tool {
|
||||||
|
if within <= 0 || t.RunWithin == nil {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
run := t.RunWithin
|
||||||
|
t.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) {
|
||||||
|
return run(caller, "", args, within)
|
||||||
|
}
|
||||||
|
t.within = within
|
||||||
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
// MetaCaller is where in a `tools/call`'s `_meta` the runtime names the caller it took from the subject the
|
// MetaCaller is where in a `tools/call`'s `_meta` the runtime names the caller it took from the subject the
|
||||||
@@ -56,8 +85,9 @@ const MetaCaller = "mesh/caller"
|
|||||||
// callParams is a `tools/call`'s params: the tool, its arguments as the caller sent them, and in `_meta`, which the
|
// callParams is a `tools/call`'s params: the tool, its arguments as the caller sent them, and in `_meta`, which the
|
||||||
// runtime writes and no caller can, the caller — only when the subject named one — and the id of the call in flight
|
// runtime writes and no caller can, the caller — only when the subject named one — and the id of the call in flight
|
||||||
// (mesh-sdk buscalls.MetaCall), which a ledger's apply names so the runtime stamps the caller it proved (novox/hq ADR
|
// (mesh-sdk buscalls.MetaCall), which a ledger's apply names so the runtime stamps the caller it proved (novox/hq ADR
|
||||||
// 0597 §7).
|
// 0597 §7), and the ask id the call carried in its request header, only when it carried one (stdio.MetaAsk; design 47 H2
|
||||||
func callParams(name, caller, call string, args json.RawMessage) map[string]any {
|
// §775, H-A-351).
|
||||||
|
func callParams(name, caller, call, ask string, args json.RawMessage) map[string]any {
|
||||||
params := map[string]any{"name": name, "arguments": args}
|
params := map[string]any{"name": name, "arguments": args}
|
||||||
meta := map[string]any{}
|
meta := map[string]any{}
|
||||||
if caller != "" {
|
if caller != "" {
|
||||||
@@ -66,6 +96,9 @@ func callParams(name, caller, call string, args json.RawMessage) map[string]any
|
|||||||
if call != "" {
|
if call != "" {
|
||||||
meta[buscalls.MetaCall] = call
|
meta[buscalls.MetaCall] = call
|
||||||
}
|
}
|
||||||
|
if ask != "" {
|
||||||
|
meta[stdio.MetaAsk] = ask
|
||||||
|
}
|
||||||
if len(meta) > 0 {
|
if len(meta) > 0 {
|
||||||
params["_meta"] = meta
|
params["_meta"] = meta
|
||||||
}
|
}
|
||||||
@@ -121,7 +154,7 @@ type Bus interface {
|
|||||||
// busStateCalls are the methods of mesh-sdk buscalls a bundle asks and BusState answers.
|
// busStateCalls are the methods of mesh-sdk buscalls a bundle asks and BusState answers.
|
||||||
var busStateCalls = map[string]bool{
|
var busStateCalls = map[string]bool{
|
||||||
buscalls.ObjectsPut: true, buscalls.ObjectsGet: true, buscalls.ObjectsList: true, buscalls.ObjectsDelete: true,
|
buscalls.ObjectsPut: true, buscalls.ObjectsGet: true, buscalls.ObjectsList: true, buscalls.ObjectsDelete: true,
|
||||||
buscalls.ObjectsInfo: true, buscalls.StreamRead: true, buscalls.StreamFill: true, buscalls.WorkQueueSize: true,
|
buscalls.ObjectsInfo: true, buscalls.StreamRead: true, buscalls.StreamFill: true, buscalls.StreamPublish: true, buscalls.WorkQueueSize: true,
|
||||||
buscalls.WorkQueueDead: true, buscalls.LedgerApply: true, buscalls.LedgerGet: true, buscalls.LedgerHistory: true,
|
buscalls.WorkQueueDead: true, buscalls.LedgerApply: true, buscalls.LedgerGet: true, buscalls.LedgerHistory: true,
|
||||||
buscalls.LedgerQuery: true, buscalls.LedgerRebuild: true, buscalls.LedgerReindex: true, buscalls.LedgerSnapshot: true,
|
buscalls.LedgerQuery: true, buscalls.LedgerRebuild: true, buscalls.LedgerReindex: true, buscalls.LedgerSnapshot: true,
|
||||||
buscalls.LedgerLag: true, buscalls.ObjectsSentGet: true, buscalls.ObjectsPutChunk: true, buscalls.ObjectsGetChunk: true,
|
buscalls.LedgerLag: true, buscalls.ObjectsSentGet: true, buscalls.ObjectsPutChunk: true, buscalls.ObjectsGetChunk: true,
|
||||||
@@ -387,7 +420,29 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
|
|||||||
asked := time.Now()
|
asked := time.Now()
|
||||||
switch m.Method {
|
switch m.Method {
|
||||||
case "mesh/publish":
|
case "mesh/publish":
|
||||||
err = mesh.Publish(m.Params)
|
var said struct {
|
||||||
|
Ack bool `json:"ack"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(m.Params, &said)
|
||||||
|
if !said.Ack {
|
||||||
|
err = mesh.Publish(m.Params)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// With ack the runtime answers only once the bus acknowledged the event: its sequence, or {error}
|
||||||
|
// (design 47 G §559). A refusal is an answer, so a writer says it as a finding's resend.
|
||||||
|
acker, ok := mesh.(interface {
|
||||||
|
PublishAcked(params json.RawMessage) (uint64, error)
|
||||||
|
})
|
||||||
|
switch {
|
||||||
|
case !ok:
|
||||||
|
result = map[string]any{"error": "this tool runner's bus publishes no event with an acknowledgement"}
|
||||||
|
default:
|
||||||
|
if seq, perr := acker.PublishAcked(m.Params); perr != nil {
|
||||||
|
result = map[string]any{"error": perr.Error()}
|
||||||
|
} else {
|
||||||
|
result = map[string]any{"sequence": seq}
|
||||||
|
}
|
||||||
|
}
|
||||||
case "mesh/ask":
|
case "mesh/ask":
|
||||||
var asked json.RawMessage
|
var asked json.RawMessage
|
||||||
if asked, err = mesh.Ask(m.Params); err == nil {
|
if asked, err = mesh.Ask(m.Params); err == nil {
|
||||||
@@ -404,6 +459,38 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
|
|||||||
result = json.RawMessage(raw)
|
result = json.RawMessage(raw)
|
||||||
}
|
}
|
||||||
case "mesh/subscribe":
|
case "mesh/subscribe":
|
||||||
|
var said struct {
|
||||||
|
Pattern string `json:"pattern"`
|
||||||
|
Deliver string `json:"deliver"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(m.Params, &said)
|
||||||
|
if said.Deliver == "new" {
|
||||||
|
// An ordered consumer of its own from the next message on (design 47 G §559, A-153): each message
|
||||||
|
// is handed to this child as an event is, and the consumer ends with the child.
|
||||||
|
newer, ok := mesh.(interface {
|
||||||
|
SubscribeNew(pattern string, deliver func(json.RawMessage) error) (func(), error)
|
||||||
|
})
|
||||||
|
if !ok {
|
||||||
|
err = errors.New("this tool runner's bus makes no subscription for new messages")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
var stop func()
|
||||||
|
stop, err = newer.SubscribeNew(said.Pattern, func(envelope json.RawMessage) error {
|
||||||
|
_, err := c.ask(module, "mesh/event", map[string]any{"envelope": envelope}, EventTimeout)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.why != nil {
|
||||||
|
c.mu.Unlock()
|
||||||
|
stop()
|
||||||
|
} else {
|
||||||
|
c.watches = append(c.watches, stop)
|
||||||
|
c.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
subscriber = c
|
subscriber = c
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
@@ -413,6 +500,12 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
|
|||||||
if answered, err = mesh.Seat(strings.TrimPrefix(m.Method, "mesh/seat."), m.Params, nil); err == nil {
|
if answered, err = mesh.Seat(strings.TrimPrefix(m.Method, "mesh/seat."), m.Params, nil); err == nil {
|
||||||
result = answered
|
result = answered
|
||||||
}
|
}
|
||||||
|
case "mesh/queue.waiting":
|
||||||
|
// The asks that wait on the holder's own queue of a seat (design 47 H2 H-A-410).
|
||||||
|
var answered json.RawMessage
|
||||||
|
if answered, err = mesh.Seat("waiting", m.Params, nil); err == nil {
|
||||||
|
result = answered
|
||||||
|
}
|
||||||
case "mesh/seat.take", "mesh/seat.answer":
|
case "mesh/seat.take", "mesh/seat.answer":
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
seatTaker = c
|
seatTaker = c
|
||||||
@@ -745,13 +838,17 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
|
|||||||
input = json.RawMessage("{}")
|
input = json.RawMessage("{}")
|
||||||
}
|
}
|
||||||
tool := Tool{Name: name, Description: t.Description, Input: input,
|
tool := Tool{Name: name, Description: t.Description, Input: input,
|
||||||
Run: func(caller string, args json.RawMessage) (json.RawMessage, error) {
|
Run: nil, RunWithin: func(caller, ask string, args json.RawMessage, within time.Duration) (json.RawMessage, error) {
|
||||||
if len(args) == 0 || string(args) == "null" {
|
if len(args) == 0 || string(args) == "null" {
|
||||||
args = json.RawMessage("{}")
|
args = json.RawMessage("{}")
|
||||||
}
|
}
|
||||||
call, end := mesh.Begin(caller)
|
call, end := mesh.Begin(caller)
|
||||||
defer end()
|
defer end()
|
||||||
res, err := asking("tools/call", callParams(full, caller, call, args), CallTimeout)
|
bound := CallTimeout
|
||||||
|
if within > 0 {
|
||||||
|
bound = within
|
||||||
|
}
|
||||||
|
res, err := asking("tools/call", callParams(full, caller, call, ask, args), bound)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, errNoAnswer) {
|
if errors.Is(err, errNoAnswer) {
|
||||||
// Its caller is gone by now and nobody else would hear of it (issue 1966).
|
// Its caller is gone by now and nobody else would hear of it (issue 1966).
|
||||||
@@ -787,6 +884,9 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
|
|||||||
b, _ := json.Marshal(text)
|
b, _ := json.Marshal(text)
|
||||||
return b, nil
|
return b, nil
|
||||||
}}
|
}}
|
||||||
|
tool.Run = func(caller string, args json.RawMessage) (json.RawMessage, error) {
|
||||||
|
return tool.RunWithin(caller, "", args, 0)
|
||||||
|
}
|
||||||
if _, seen := groups[under]; !seen {
|
if _, seen := groups[under]; !seen {
|
||||||
order = append(order, under)
|
order = append(order, under)
|
||||||
}
|
}
|
||||||
@@ -815,6 +915,18 @@ func Start(module, entry string, env []string, mesh Bus, logf func(string, ...an
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *child) ask(module, method string, params any, timeout time.Duration) (json.RawMessage, error) {
|
func (c *child) ask(module, method string, params any, timeout time.Duration) (json.RawMessage, error) {
|
||||||
|
// Counted for the drain at a stop, and refused once it began (design 47 H2 §813 (12)).
|
||||||
|
verb := method
|
||||||
|
if p, ok := params.(map[string]any); ok && method == "tools/call" {
|
||||||
|
if name, ok := p["name"].(string); ok {
|
||||||
|
verb = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
asked, flight, err := begin(module, verb)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer end(asked)
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
if c.why != nil {
|
if c.why != nil {
|
||||||
c.mu.Unlock()
|
c.mu.Unlock()
|
||||||
@@ -850,6 +962,11 @@ func (c *child) ask(module, method string, params any, timeout time.Duration) (j
|
|||||||
return m.Result, nil
|
return m.Result, nil
|
||||||
case <-c.dead:
|
case <-c.dead:
|
||||||
return nil, c.deathReason()
|
return nil, c.deathReason()
|
||||||
|
case <-flight.cut:
|
||||||
|
c.mu.Lock()
|
||||||
|
delete(c.pending, id)
|
||||||
|
c.mu.Unlock()
|
||||||
|
return nil, &cutCall{module: module, verb: verb}
|
||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
delete(c.pending, id)
|
delete(c.pending, id)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -68,6 +69,93 @@ func TestABundleTakesASeatsWorkThroughItsOwnChannel(t *testing.T) {
|
|||||||
if err != nil || string(got) != `{"taken":true}` {
|
if err != nil || string(got) != `{"taken":true}` {
|
||||||
t.Fatalf("the work was not handed to the bundle: %s %v", got, err)
|
t.Fatalf("the work was not handed to the bundle: %s %v", got, err)
|
||||||
}
|
}
|
||||||
|
// Design 47 G §576, §518: a bundle reads the runner's capability words with mesh/capabilities, then runs its put session
|
||||||
|
// through the runner's put-chunk, and the sessions of its channel are dropped when the channel closes.
|
||||||
|
t.Run("ABundleReadsTheCapabilityWordsRunsAPutSessionAndItsChannelsClosingDropsThem", func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
entry := filepath.Join(dir, "bundle")
|
||||||
|
if err := os.WriteFile(entry, []byte(puttingBundle), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b := &sessionBus{dropped: make(chan struct{})}
|
||||||
|
l, err := Start("putter", entry, os.Environ(), b, func(string, ...any) {})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(l.Stop)
|
||||||
|
select {
|
||||||
|
case <-b.dropped:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("the bundle's sessions were not dropped when its channel closed")
|
||||||
|
}
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
if len(b.chunks) != 1 || !strings.HasPrefix(b.chunks[0], "mesh/objects.put-chunk ") || !strings.Contains(b.chunks[0], `"seq":1`) {
|
||||||
|
t.Fatalf("the runner took %v", b.chunks)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// Design 47 G §559: `mesh/publish` with `ack` is answered with its sequence once the bus acknowledged it, or `{error}`;
|
||||||
|
// `mesh/subscribe` with `deliver: new` makes a subscription for new messages that ends with the bundle's channel.
|
||||||
|
t.Run("APublishWithAckIsAnsweredWithItsSequenceAndASubscriptionForNewMessagesEndsWithTheChannel", func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
entry, out := filepath.Join(dir, "bundle"), filepath.Join(dir, "out")
|
||||||
|
if err := os.WriteFile(entry, []byte(findingBundle), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b := &findingBus{stopped: make(chan struct{})}
|
||||||
|
l, err := Start("writer", entry, append(os.Environ(), "FINDING_OUT="+out), b, func(string, ...any) {})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(l.Stop)
|
||||||
|
select {
|
||||||
|
case <-b.stopped:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("the subscription for new messages was not ended with the bundle's channel")
|
||||||
|
}
|
||||||
|
got, _ := os.ReadFile(out)
|
||||||
|
for _, want := range []string{`"sequence":42`, `"error":"the bus refused it"`} {
|
||||||
|
if !strings.Contains(string(got), want) {
|
||||||
|
t.Errorf("the bundle was answered %s, want it to hold %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.mu.Lock()
|
||||||
|
defer b.mu.Unlock()
|
||||||
|
if b.pattern != "mesh-conditions.findings-asked" {
|
||||||
|
t.Errorf("the subscription was made for %q", b.pattern)
|
||||||
|
}
|
||||||
|
if len(b.published) != 0 {
|
||||||
|
t.Errorf("a publish with ack went the unacknowledged way: %v", b.published)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// 1887/A11: a bundle's pull reaches the runtime's bus from its own channel, as its other seat traffic does.
|
||||||
|
t.Run("ABundlesPullReachesTheRuntimeThroughItsOwnChannel", func(t *testing.T) {
|
||||||
|
entry := filepath.Join(t.TempDir(), "bundle")
|
||||||
|
if err := os.WriteFile(entry, []byte(pullingBundle), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b := &seating{}
|
||||||
|
l, err := Start("mesh-build-go", entry, os.Environ(), b, t.Logf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(l.Stop)
|
||||||
|
for i := 0; ; i++ {
|
||||||
|
b.mu.Lock()
|
||||||
|
verb, params := b.verb, b.params
|
||||||
|
b.mu.Unlock()
|
||||||
|
if verb == "pull" {
|
||||||
|
if params != `{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":0}` {
|
||||||
|
t.Fatalf("pulled with %s", params)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if i > 100 {
|
||||||
|
t.Fatal("the bundle's pull never reached the runtime")
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// A bundle that pulls one ask from its worker when it is listed.
|
// A bundle that pulls one ask from its worker when it is listed.
|
||||||
@@ -82,32 +170,3 @@ while IFS= read -r line; do
|
|||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
`
|
`
|
||||||
|
|
||||||
// 1887/A11: a bundle's pull reaches the runtime's bus from its own channel, as its other seat traffic does.
|
|
||||||
func TestABundlePullsASeatsWorkThroughItsOwnChannel(t *testing.T) {
|
|
||||||
entry := filepath.Join(t.TempDir(), "bundle")
|
|
||||||
if err := os.WriteFile(entry, []byte(pullingBundle), 0o755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
b := &seating{}
|
|
||||||
l, err := Start("mesh-build-go", entry, os.Environ(), b, t.Logf)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
t.Cleanup(l.Stop)
|
|
||||||
for i := 0; ; i++ {
|
|
||||||
b.mu.Lock()
|
|
||||||
verb, params := b.verb, b.params
|
|
||||||
b.mu.Unlock()
|
|
||||||
if verb == "pull" {
|
|
||||||
if params != `{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":0}` {
|
|
||||||
t.Fatalf("pulled with %s", params)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if i > 100 {
|
|
||||||
t.Fatal("the bundle's pull never reached the runtime")
|
|
||||||
}
|
|
||||||
time.Sleep(20 * time.Millisecond)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,12 +2,9 @@ package launch
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
"errors"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// puttingBundle asks the capability words, and once they are answered with put-sessions sends the one chunk of a put
|
// puttingBundle asks the capability words, and once they are answered with put-sessions sends the one chunk of a put
|
||||||
@@ -41,28 +38,41 @@ func (b *sessionBus) BusState(method string, params json.RawMessage) (json.RawMe
|
|||||||
}
|
}
|
||||||
func (b *sessionBus) DropSessions() { close(b.dropped) }
|
func (b *sessionBus) DropSessions() { close(b.dropped) }
|
||||||
|
|
||||||
// Design 47 G §576, §518: a bundle reads the runner's capability words with mesh/capabilities, then runs its put session
|
// findingBundle asks, as mesh-sdk's finding writer does, a publish with ack that the bus takes, one it refuses, and a
|
||||||
// through the runner's put-chunk, and the sessions of its channel are dropped when the channel closes.
|
// subscription for new messages; each answer it gets is written to $FINDING_OUT, and it ends after the subscription's.
|
||||||
func TestABundleReadsTheCapabilityWordsRunsAPutSessionAndItsChannelsClosingDropsThem(t *testing.T) {
|
const findingBundle = `#!/bin/sh
|
||||||
dir := t.TempDir()
|
while IFS= read -r line; do
|
||||||
entry := filepath.Join(dir, "bundle")
|
id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\)[,}].*/\1/p')
|
||||||
if err := os.WriteFile(entry, []byte(puttingBundle), 0o755); err != nil {
|
case "$line" in
|
||||||
t.Fatal(err)
|
*'"method":"initialize"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
|
||||||
|
*'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[]}}\n' "$id"
|
||||||
|
printf '{"jsonrpc":"2.0","id":"a1","method":"mesh/publish","params":{"key":"taken","ack":true,"body":{}}}\n' ;;
|
||||||
|
*'"id":"a1"'*) printf '%s\n' "$line" >>"$FINDING_OUT"
|
||||||
|
printf '{"jsonrpc":"2.0","id":"a2","method":"mesh/publish","params":{"key":"refused","ack":true,"body":{}}}\n' ;;
|
||||||
|
*'"id":"a2"'*) printf '%s\n' "$line" >>"$FINDING_OUT"
|
||||||
|
printf '{"jsonrpc":"2.0","id":"s1","method":"mesh/subscribe","params":{"pattern":"mesh-conditions.findings-asked","deliver":"new"}}\n' ;;
|
||||||
|
*'"id":"s1"'*) printf '%s\n' "$line" >>"$FINDING_OUT"; exit 0 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
`
|
||||||
|
|
||||||
|
type findingBus struct {
|
||||||
|
subscribing
|
||||||
|
mu sync.Mutex
|
||||||
|
pattern string
|
||||||
|
stopped chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *findingBus) PublishAcked(params json.RawMessage) (uint64, error) {
|
||||||
|
if strings.Contains(string(params), `"refused"`) {
|
||||||
|
return 0, errors.New("the bus refused it")
|
||||||
}
|
}
|
||||||
b := &sessionBus{dropped: make(chan struct{})}
|
return 42, nil
|
||||||
l, err := Start("putter", entry, os.Environ(), b, func(string, ...any) {})
|
}
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
func (b *findingBus) SubscribeNew(pattern string, _ func(json.RawMessage) error) (func(), error) {
|
||||||
}
|
|
||||||
t.Cleanup(l.Stop)
|
|
||||||
select {
|
|
||||||
case <-b.dropped:
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("the bundle's sessions were not dropped when its channel closed")
|
|
||||||
}
|
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
defer b.mu.Unlock()
|
b.pattern = pattern
|
||||||
if len(b.chunks) != 1 || !strings.HasPrefix(b.chunks[0], "mesh/objects.put-chunk ") || !strings.Contains(b.chunks[0], `"seq":1`) {
|
b.mu.Unlock()
|
||||||
t.Fatalf("the runner took %v", b.chunks)
|
return func() { close(b.stopped) }, nil
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,7 +82,8 @@ while IFS= read -r line; do
|
|||||||
case "$line" in
|
case "$line" in
|
||||||
*'"method":"initialize"'*) echo started >&2; printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
|
*'"method":"initialize"'*) echo started >&2; printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id" ;;
|
||||||
*'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"t","description":"d"}]}}\n' "$id" ;;
|
*'"method":"tools/list"'*) printf '{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"t","description":"d"}]}}\n' "$id" ;;
|
||||||
*'"method":"tools/call"'*) [ "$MODE" = long ] && printf '%4096s\n' x ;;
|
*'"method":"tools/call"'*) [ "$MODE" = long ] && printf '%4096s\n' x
|
||||||
|
[ "$MODE" = late ] && { sleep 0.3; printf '{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"{}"}]}}\n' "$id"; } ;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
`
|
`
|
||||||
@@ -150,3 +151,28 @@ func TestAnOverlongLineAndAnUnansweredCallAreSaid(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Design 47 H §760: a verb served from a bundle waits the `timeout` its definition names, not the runner's own bound: a bundle
|
||||||
|
// that answers after CallTimeout is answered through Within and fails through Run.
|
||||||
|
func TestAToolWithinWaitsTheBoundItsVerbNames(t *testing.T) {
|
||||||
|
oldCall := CallTimeout
|
||||||
|
CallTimeout = 100 * time.Millisecond
|
||||||
|
t.Cleanup(func() { CallTimeout = oldCall })
|
||||||
|
dir := t.TempDir()
|
||||||
|
entry := filepath.Join(dir, "bundle")
|
||||||
|
if err := os.WriteFile(entry, []byte(callingBundle), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l, err := Start("caller", entry, append(os.Environ(), "MODE=late"), &refusingState{}, func(string, ...any) {})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(l.Stop)
|
||||||
|
tool := l.Registrations[0].Tools[0]
|
||||||
|
if _, err := tool.Run("caller-1", nil); err == nil || !strings.Contains(err.Error(), "did not answer") {
|
||||||
|
t.Fatalf("a call that waits the runner's own bound of 100ms: %v, want it unanswered", err)
|
||||||
|
}
|
||||||
|
if got, err := tool.Within(5*time.Second).Run("caller-1", nil); err != nil || string(got) != "{}" {
|
||||||
|
t.Fatalf("a call that waits the verb's 5s: %s, %v, want its answer", got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package launch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A-42: a launched bundle may ask mesh/stream.publish.
|
||||||
|
func TestABundleMayAskStreamPublish(t *testing.T) {
|
||||||
|
if !busStateCalls[buscalls.StreamPublish] {
|
||||||
|
t.Fatal("mesh/stream.publish is not among the methods a bundle may ask")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,6 +58,10 @@ type History interface {
|
|||||||
// Read is the operations of the instances keys names (a key, with `*` for one name and `>` for the rest) from a
|
// Read is the operations of the instances keys names (a key, with `*` for one name and `>` for the rest) from a
|
||||||
// sequence on, oldest first, at most limit of them (every one when limit is 0).
|
// sequence on, oldest first, at most limit of them (every one when limit is 0).
|
||||||
Read(keys string, from uint64, limit int) ([]Kept, error)
|
Read(keys string, from uint64, limit int) ([]Kept, error)
|
||||||
|
// Purge removes every operation of the instance key names, and nothing of another (an instance's removal).
|
||||||
|
Purge(key string) error
|
||||||
|
// Fill is the history's fill against its cap, the ledger's cap (buscalls.LedgerFill; design 47 G §587).
|
||||||
|
Fill() (buscalls.Fill, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// State is a ledger's state bucket: each instance's record under its key.
|
// State is a ledger's state bucket: each instance's record under its key.
|
||||||
@@ -69,6 +73,8 @@ type State interface {
|
|||||||
Write(key string, value []byte, revision uint64) (uint64, error)
|
Write(key string, value []byte, revision uint64) (uint64, error)
|
||||||
// Keys is every key the bucket holds.
|
// Keys is every key the bucket holds.
|
||||||
Keys() ([]string, error)
|
Keys() ([]string, error)
|
||||||
|
// Delete removes the key; a key it does not hold is no fault.
|
||||||
|
Delete(key string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshots are a ledger's snapshots: the latest record of each instance, on a subject of its own, never expiring.
|
// Snapshots are a ledger's snapshots: the latest record of each instance, on a subject of its own, never expiring.
|
||||||
@@ -77,6 +83,8 @@ type Snapshots interface {
|
|||||||
Get(key string) ([]byte, uint64, error)
|
Get(key string) ([]byte, uint64, error)
|
||||||
// Put writes the key's snapshot, expecting its last to be at expect (0: none); ErrRaced when it is not.
|
// Put writes the key's snapshot, expecting its last to be at expect (0: none); ErrRaced when it is not.
|
||||||
Put(key string, value []byte, expect uint64) error
|
Put(key string, value []byte, expect uint64) error
|
||||||
|
// Purge removes the key's snapshot; one it does not hold is no fault.
|
||||||
|
Purge(key string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ledger is one ledger of one module: its types and where it is kept.
|
// Ledger is one ledger of one module: its types and where it is kept.
|
||||||
@@ -495,3 +503,74 @@ func (l *Ledger) Apply(r buscalls.ApplyRequest, author buscalls.Author) (buscall
|
|||||||
}
|
}
|
||||||
return buscalls.Applied{Taken: true, Sequence: seq, StateBehind: behind}, nil
|
return buscalls.Applied{Taken: true, Sequence: seq, StateBehind: behind}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fill is the fill of the ledger's history against the ledger's cap (buscalls.LedgerFill; design 47 G §587): its messages,
|
||||||
|
// its bytes and the cap in bytes. The history holds every operation, and the cap is its alone: neither the fullest of the
|
||||||
|
// stores nor their sum is answered. A history that cannot say its fill is an error naming the ledger, never a fill of
|
||||||
|
// nothing.
|
||||||
|
func (l *Ledger) Fill(buscalls.LedgerRequest) (buscalls.Fill, error) {
|
||||||
|
f, err := l.History.Fill()
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.Fill{}, fmt.Errorf("%s's ledger %s cannot say the fill of its history: %w", l.Module, l.Name, err)
|
||||||
|
}
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove removes one instance with everything it kept (buscalls.LedgerRemove; design 47 G §587, §155): its operations, its
|
||||||
|
// snapshot, its key in the state bucket and its keys in every declared index, and answers how many operations and how many
|
||||||
|
// bytes of the history that was. An instance the ledger does not hold answers 0 and 0, and a removal that left something
|
||||||
|
// (said, and answered as an error) is made again by calling it again, which removes the rest.
|
||||||
|
func (l *Ledger) Remove(r buscalls.LedgerRemoveRequest) (buscalls.LedgerRemoved, error) {
|
||||||
|
key, err := KeyOf(r.Instance)
|
||||||
|
if err != nil {
|
||||||
|
return buscalls.LedgerRemoved{}, err
|
||||||
|
}
|
||||||
|
out := buscalls.LedgerRemoved{Instance: r.Instance}
|
||||||
|
before, err := l.History.Fill()
|
||||||
|
if err != nil {
|
||||||
|
return out, fmt.Errorf("%s's ledger %s cannot say the fill of its history, so a removal is not made: %w", l.Module, l.Name, err)
|
||||||
|
}
|
||||||
|
ops, err := l.History.Read(key, 1, 0)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
for _, step := range []struct {
|
||||||
|
what string
|
||||||
|
remove func(string) error
|
||||||
|
}{{"operations", l.History.Purge}, {"snapshot", l.Snapshots.Purge}, {"state", l.State.Delete}, {"index entries", l.dropFromIndexes}} {
|
||||||
|
if err := step.remove(key); err != nil {
|
||||||
|
l.say("[mesh-tools] %s's ledger %s removes %s and its %s could not be removed: %v; removing it again removes what "+
|
||||||
|
"is left", l.Module, l.Name, r.Instance, step.what, err)
|
||||||
|
return out, fmt.Errorf("%s's ledger %s removed part of %s and its %s are left: %w", l.Module, l.Name, r.Instance, step.what, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
after, err := l.History.Fill()
|
||||||
|
if err != nil {
|
||||||
|
return out, fmt.Errorf("%s's ledger %s removed %s and cannot say the fill of its history after: %w", l.Module, l.Name, r.Instance, err)
|
||||||
|
}
|
||||||
|
out.Operations = uint64(len(ops))
|
||||||
|
if before.Bytes > after.Bytes {
|
||||||
|
out.Bytes = before.Bytes - after.Bytes
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// dropFromIndexes removes the entries of the instance key names from every index bucket the ledger is bound to.
|
||||||
|
func (l *Ledger) dropFromIndexes(key string) error {
|
||||||
|
instance := InstanceOf(key)
|
||||||
|
for name, ix := range l.Indexes {
|
||||||
|
held, err := ix.Entries("", 0)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("the index %s: %w", name, err)
|
||||||
|
}
|
||||||
|
for _, e := range held {
|
||||||
|
var v buscalls.IndexEntry
|
||||||
|
if json.Unmarshal(e.Value, &v) == nil && v.Instance == instance {
|
||||||
|
if err := ix.Delete(e.Key); err != nil {
|
||||||
|
return fmt.Errorf("the index %s: %w", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -99,4 +99,50 @@ func TestApplyAppendsDerivesAndSnapshots(t *testing.T) {
|
|||||||
c.run(t, l, f)
|
c.run(t, l, f)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
// design 47 G §587: a ledger's fill is its history's against the ledger's cap, a store that cannot say it is an error naming
|
||||||
|
// the ledger; a removal takes an instance's operations, snapshot, state and index entries and answers what that was, an
|
||||||
|
// unknown instance answers none, and nothing of another instance goes.
|
||||||
|
t.Run("TheLedgerSaysItsFillAndRemovesAnInstanceWhole", func(t *testing.T) {
|
||||||
|
l, f := newLedger()
|
||||||
|
f.history.MaxBytes = 1 << 20
|
||||||
|
for _, n := range []string{"a", "b"} {
|
||||||
|
applied(t, l, "decision/0290", "note", `{"says":"`+n+`"}`, owner)
|
||||||
|
}
|
||||||
|
applied(t, l, "decision/0291", "note", `{"says":"other"}`, owner)
|
||||||
|
entry, _ := json.Marshal(buscalls.IndexEntry{Instance: "decision/0290", Sequence: 2})
|
||||||
|
other, _ := json.Marshal(buscalls.IndexEntry{Instance: "decision/0291", Sequence: 1})
|
||||||
|
_ = f.index.Put("t.decision.0290", entry)
|
||||||
|
_ = f.index.Put("t.decision.0291", other)
|
||||||
|
|
||||||
|
fill, err := l.Fill(buscalls.LedgerRequest{Ledger: "records"})
|
||||||
|
if err != nil || fill.Count != 3 || fill.Bytes == 0 || fill.MaxBytes != 1<<20 {
|
||||||
|
t.Fatalf("the fill is %+v (%v), want 3 messages against 1 MiB", fill, err)
|
||||||
|
}
|
||||||
|
got, err := l.Remove(buscalls.LedgerRemoveRequest{Ledger: "records", Instance: "decision/0290"})
|
||||||
|
if err != nil || got.Instance != "decision/0290" || got.Operations != 2 || got.Bytes == 0 {
|
||||||
|
t.Fatalf("the removal answered %+v (%v), want 2 operations and their bytes", got, err)
|
||||||
|
}
|
||||||
|
if kept, _ := f.history.Read("decision.0290", 1, 0); len(kept) != 0 {
|
||||||
|
t.Errorf("operations are left: %d", len(kept))
|
||||||
|
}
|
||||||
|
if raw, _, _ := f.state.Get("decision.0290"); raw != nil {
|
||||||
|
t.Errorf("the state is left: %s", raw)
|
||||||
|
}
|
||||||
|
if raw, _, _ := f.snapshots.Get("decision.0290"); raw != nil {
|
||||||
|
t.Errorf("the snapshot is left: %s", raw)
|
||||||
|
}
|
||||||
|
if held, _ := f.index.Entries("", 0); len(held) != 1 || held[0].Key != "t.decision.0291" {
|
||||||
|
t.Errorf("the index holds %v, want the other instance's entry alone", held)
|
||||||
|
}
|
||||||
|
if kept, _ := f.history.Read("decision.0291", 1, 0); len(kept) != 1 {
|
||||||
|
t.Errorf("another instance lost operations: %d left", len(kept))
|
||||||
|
}
|
||||||
|
if again, err := l.Remove(buscalls.LedgerRemoveRequest{Ledger: "records", Instance: "decision/0290"}); err != nil || again.Operations != 0 || again.Bytes != 0 {
|
||||||
|
t.Errorf("a removal said twice answered %+v (%v), want none", again, err)
|
||||||
|
}
|
||||||
|
f.history.FillFails = true
|
||||||
|
if _, err := l.Fill(buscalls.LedgerRequest{}); err == nil || !strings.Contains(err.Error(), "ledger records cannot say the fill") {
|
||||||
|
t.Errorf("a history that cannot say its fill answered %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package ledger
|
package ledger
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The memory stores keep what the bus keeps, as the bus answers it, for a test of a ledger without a bus: a stream whose
|
// The memory stores keep what the bus keeps, as the bus answers it, for a test of a ledger without a bus: a stream whose
|
||||||
@@ -12,9 +15,13 @@ import (
|
|||||||
|
|
||||||
// MemoryHistory is a history in memory.
|
// MemoryHistory is a history in memory.
|
||||||
type MemoryHistory struct {
|
type MemoryHistory struct {
|
||||||
mu sync.Mutex
|
// MaxBytes is the cap its fill is said against.
|
||||||
seq uint64
|
MaxBytes uint64
|
||||||
kept []struct {
|
// FillFails makes Fill an error, as a store that cannot say its fill.
|
||||||
|
FillFails bool
|
||||||
|
mu sync.Mutex
|
||||||
|
seq uint64
|
||||||
|
kept []struct {
|
||||||
key string
|
key string
|
||||||
Kept
|
Kept
|
||||||
}
|
}
|
||||||
@@ -73,6 +80,32 @@ func (h *MemoryHistory) Read(keys string, from uint64, limit int) ([]Kept, error
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *MemoryHistory) Purge(key string) error {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
kept := h.kept[:0]
|
||||||
|
for _, k := range h.kept {
|
||||||
|
if k.key != key {
|
||||||
|
kept = append(kept, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.kept = kept
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MemoryHistory) Fill() (buscalls.Fill, error) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
if h.FillFails {
|
||||||
|
return buscalls.Fill{}, errors.New("the history does not say its fill")
|
||||||
|
}
|
||||||
|
f := buscalls.Fill{Count: uint64(len(h.kept)), MaxBytes: h.MaxBytes}
|
||||||
|
for _, k := range h.kept {
|
||||||
|
f.Bytes += uint64(len(k.Data))
|
||||||
|
}
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Expire drops every operation of the history, as a ledger's keeping days end them.
|
// Expire drops every operation of the history, as a ledger's keeping days end them.
|
||||||
func (h *MemoryHistory) Expire() {
|
func (h *MemoryHistory) Expire() {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
@@ -129,6 +162,13 @@ func (s *MemoryState) Keys() ([]string, error) {
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *MemoryState) Delete(key string) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
delete(s.kv, key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// MemorySnapshots are snapshots in memory.
|
// MemorySnapshots are snapshots in memory.
|
||||||
type MemorySnapshots struct {
|
type MemorySnapshots struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
@@ -157,6 +197,13 @@ func (s *MemorySnapshots) Put(key string, value []byte, expect uint64) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *MemorySnapshots) Purge(key string) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
delete(s.kv, key)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// MemoryIndex is an index's bucket in memory.
|
// MemoryIndex is an index's bucket in memory.
|
||||||
type MemoryIndex struct {
|
type MemoryIndex struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import (
|
|||||||
|
|
||||||
assigner "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
assigner "git.novox.be/novox/mesh-contracts/go/clients/meshmoduleassignerclient"
|
||||||
seatassigner "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
seatassigner "git.novox.be/novox/mesh-contracts/go/seats/meshmoduleassigner"
|
||||||
meshcatalog "git.novox.be/novox/mesh-delivery/contracts/go/seats/meshcatalog"
|
meshcatalog "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog"
|
||||||
"git.novox.be/novox/mesh-sdk/go/membership"
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
|
|
||||||
"github.com/nats-io/nats-server/v2/server"
|
"github.com/nats-io/nats-server/v2/server"
|
||||||
@@ -57,9 +57,9 @@ func URL(t *testing.T) string {
|
|||||||
t.Fatalf("a bus for this test could not be made: %v", err)
|
t.Fatalf("a bus for this test could not be made: %v", err)
|
||||||
}
|
}
|
||||||
go s.Start()
|
go s.Start()
|
||||||
if !s.ReadyForConnections(30 * time.Second) {
|
if !s.ReadyForConnections(Bound(t)) {
|
||||||
s.Shutdown()
|
s.Shutdown()
|
||||||
t.Fatal("a bus for this test did not come up within 30s")
|
t.Fatal("a bus for this test did not come up within its bound")
|
||||||
}
|
}
|
||||||
url := s.ClientURL()
|
url := s.ClientURL()
|
||||||
buses.Store(t, url)
|
buses.Store(t, url)
|
||||||
@@ -156,7 +156,7 @@ func sdkMembership(t *testing.T, mem bus.Membership) membership.Membership {
|
|||||||
// no holder).
|
// no holder).
|
||||||
const (
|
const (
|
||||||
catalogHolder = "mesh-catalog"
|
catalogHolder = "mesh-catalog"
|
||||||
assignerHolder = "mesh-delivery-assigner"
|
assignerHolder = "mesh-module-assigner" // the seat's name stands for its holder in the console's state names (firstview.AssignmentsRead)
|
||||||
// AssignmentsBucket and SeatHoldersBucket are the assigner's states assignments and seat-holders.
|
// AssignmentsBucket and SeatHoldersBucket are the assigner's states assignments and seat-holders.
|
||||||
AssignmentsBucket = assignerHolder + "_assignments"
|
AssignmentsBucket = assignerHolder + "_assignments"
|
||||||
SeatHoldersBucket = assignerHolder + "_seat-holders"
|
SeatHoldersBucket = assignerHolder + "_seat-holders"
|
||||||
@@ -260,15 +260,52 @@ func Fixture(name string) string {
|
|||||||
return filepath.Join(filepath.Dir(here), "..", "..", "test", "fixtures", name)
|
return filepath.Join(filepath.Dir(here), "..", "..", "test", "fixtures", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Until retries while the bus answers "no responders" — something not yet served.
|
// Bound is how long, from now, a test waits for what the bus is to carry (an event, an answer, a watch's change, a key's
|
||||||
|
// expiry, a bus coming up) before it fails: the test's own deadline, go test's -timeout that the build step sets, less
|
||||||
|
// cleanupMargin for the test's cleanup, never a few seconds written into a test (issue 1754: a 1 s key's expire not heard
|
||||||
|
// in 5 s on a loaded build node; the lead's answers on the issue of 2026-11-23 20:00 and of round 2, principles 11 and 7;
|
||||||
|
// 1754/AC1). It only ends a wait that never hears what it waits for: a wait that hears ends then, so a passing test is no
|
||||||
|
// longer for it. With less than the margin left it answers what is left, at least a millisecond, so a cleanup's wait runs
|
||||||
|
// to the deadline and go test's own timeout names the test (principle 3).
|
||||||
|
func Bound(t *testing.T) time.Duration {
|
||||||
|
deadline, ok := t.Deadline()
|
||||||
|
if !ok {
|
||||||
|
deadline = started.Add(goTestTimeout)
|
||||||
|
}
|
||||||
|
return boundOf(time.Until(deadline))
|
||||||
|
}
|
||||||
|
|
||||||
|
// boundOf is Bound for what is left until the deadline.
|
||||||
|
func boundOf(left time.Duration) time.Duration {
|
||||||
|
if left > cleanupMargin {
|
||||||
|
return left - cleanupMargin
|
||||||
|
}
|
||||||
|
return max(left, time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupMargin is what Bound leaves of a test's deadline for its cleanup: 30 s, the longest bound these tests used
|
||||||
|
// (Until's), which covers their cleanups (the lead's answer on issue 1754, round 2).
|
||||||
|
const cleanupMargin = 30 * time.Second
|
||||||
|
|
||||||
|
// goTestTimeout is go test's own default -timeout, the deadline of a run that names none, from the run's start.
|
||||||
|
const goTestTimeout = 10 * time.Minute
|
||||||
|
|
||||||
|
// started is when this test binary began.
|
||||||
|
var started = time.Now()
|
||||||
|
|
||||||
|
// Until retries while the bus answers "no responders" — something not yet served — until the test's Bound has passed: a
|
||||||
|
// deadline, so a try that itself waits does not multiply it (fix-a-bug-met-twice: a fixed bound a loaded machine overruns,
|
||||||
|
// fixed for every package that waits here).
|
||||||
func Until(t *testing.T, try func() error) {
|
func Until(t *testing.T, try func() error) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var err error
|
var err error
|
||||||
for i := 0; i < 50; i++ {
|
for deadline := time.Now().Add(Bound(t)); ; time.Sleep(100 * time.Millisecond) {
|
||||||
if err = try(); err == nil {
|
if err = try(); err == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
time.Sleep(100 * time.Millisecond)
|
if time.Now().After(deadline) {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -303,7 +340,7 @@ func (l *Logs) All() string { return strings.Join(l.lines, "\n") }
|
|||||||
// redelivery in seconds rather than the mesh's minutes.
|
// redelivery in seconds rather than the mesh's minutes.
|
||||||
func (m *Mesh) Consumer(t *testing.T, node, module string, filters []string, ackWait time.Duration) {
|
func (m *Mesh) Consumer(t *testing.T, node, module string, filters []string, ackWait time.Duration) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
cfg := &nats.ConsumerConfig{Durable: node + "_" + module, AckPolicy: nats.AckExplicitPolicy,
|
cfg := &nats.ConsumerConfig{Durable: node + "_" + module + "_tools", AckPolicy: nats.AckExplicitPolicy,
|
||||||
AckWait: ackWait, MaxDeliver: 10, DeliverPolicy: nats.DeliverNewPolicy}
|
AckWait: ackWait, MaxDeliver: 10, DeliverPolicy: nats.DeliverNewPolicy}
|
||||||
if len(filters) == 1 {
|
if len(filters) == 1 {
|
||||||
cfg.FilterSubject = filters[0]
|
cfg.FilterSubject = filters[0]
|
||||||
@@ -340,7 +377,7 @@ func (m *Mesh) Publish(t *testing.T, subject string, body any) {
|
|||||||
// delivered.
|
// delivered.
|
||||||
func (m *Mesh) Pending(t *testing.T, node, module string) (ackPending, notDelivered uint64) {
|
func (m *Mesh) Pending(t *testing.T, node, module string) (ackPending, notDelivered uint64) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
info, err := m.js.ConsumerInfo("EVENTS", node+"_"+module)
|
info, err := m.js.ConsumerInfo("EVENTS", node+"_"+module+"_tools")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -379,7 +416,7 @@ func (m *Mesh) BucketKeyTTL(t *testing.T, name string) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), Bound(t))
|
||||||
defer cancel()
|
defer cancel()
|
||||||
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: 1, MaxValueSize: 256 * 1024,
|
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: name, History: 1, MaxValueSize: 256 * 1024,
|
||||||
LimitMarkerTTL: time.Minute}); err != nil {
|
LimitMarkerTTL: time.Minute}); err != nil {
|
||||||
@@ -430,7 +467,7 @@ func (m *Mesh) ModuleStream(t *testing.T, module, name string) {
|
|||||||
// ConsumerOn makes a module's durable consumer on a machine on any stream, as Consumer does on EVENTS.
|
// ConsumerOn makes a module's durable consumer on a machine on any stream, as Consumer does on EVENTS.
|
||||||
func (m *Mesh) ConsumerOn(t *testing.T, stream, node, module string, filters []string, ackWait time.Duration) {
|
func (m *Mesh) ConsumerOn(t *testing.T, stream, node, module string, filters []string, ackWait time.Duration) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
cfg := &nats.ConsumerConfig{Durable: node + "_" + module, AckPolicy: nats.AckExplicitPolicy,
|
cfg := &nats.ConsumerConfig{Durable: node + "_" + module + "_tools", AckPolicy: nats.AckExplicitPolicy,
|
||||||
AckWait: ackWait, MaxDeliver: 10, DeliverPolicy: nats.DeliverNewPolicy}
|
AckWait: ackWait, MaxDeliver: 10, DeliverPolicy: nats.DeliverNewPolicy}
|
||||||
if len(filters) == 1 {
|
if len(filters) == 1 {
|
||||||
cfg.FilterSubject = filters[0]
|
cfg.FilterSubject = filters[0]
|
||||||
@@ -445,7 +482,7 @@ func (m *Mesh) ConsumerOn(t *testing.T, stream, node, module string, filters []s
|
|||||||
// PendingOn is what a module's consumer on a stream still holds, as Pending is on EVENTS.
|
// PendingOn is what a module's consumer on a stream still holds, as Pending is on EVENTS.
|
||||||
func (m *Mesh) PendingOn(t *testing.T, stream, node, module string) (ackPending, notDelivered uint64) {
|
func (m *Mesh) PendingOn(t *testing.T, stream, node, module string) (ackPending, notDelivered uint64) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
info, err := m.js.ConsumerInfo(stream, node+"_"+module)
|
info, err := m.js.ConsumerInfo(stream, node+"_"+module+"_tools")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -466,7 +503,7 @@ func (m *Mesh) Messages(t *testing.T, stream string) uint64 {
|
|||||||
// it cannot narrow is withdrawn (novox/hq ADR 0363 §6).
|
// it cannot narrow is withdrawn (novox/hq ADR 0363 §6).
|
||||||
func (m *Mesh) RemoveConsumer(t *testing.T, stream, node, module string) {
|
func (m *Mesh) RemoveConsumer(t *testing.T, stream, node, module string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
if err := m.js.DeleteConsumer(stream, node+"_"+module); err != nil {
|
if err := m.js.DeleteConsumer(stream, node+"_"+module+"_tools"); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,252 @@
|
|||||||
|
package meshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go/ast"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 1754/AC1: a wait's bound is the test's deadline less the cleanup margin, and what is left once less than the margin is,
|
||||||
|
// never zero or less (the lead's answer on issue 1754, round 2).
|
||||||
|
func TestABoundIsTheTestsDeadlineLessItsCleanupMargin(t *testing.T) {
|
||||||
|
for _, row := range []struct{ left, want time.Duration }{
|
||||||
|
{10 * time.Minute, 10*time.Minute - cleanupMargin},
|
||||||
|
{cleanupMargin + time.Second, time.Second},
|
||||||
|
{cleanupMargin, cleanupMargin},
|
||||||
|
{time.Second, time.Second},
|
||||||
|
{0, time.Millisecond},
|
||||||
|
{-time.Minute, time.Millisecond},
|
||||||
|
} {
|
||||||
|
if got := boundOf(row.left); got != row.want {
|
||||||
|
t.Errorf("with %s left the bound is %s, want %s", row.left, got, row.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
deadline, ok := t.Deadline()
|
||||||
|
if !ok {
|
||||||
|
deadline = started.Add(goTestTimeout)
|
||||||
|
}
|
||||||
|
left := time.Until(deadline)
|
||||||
|
if b := Bound(t); b <= 0 || b > left-cleanupMargin {
|
||||||
|
t.Errorf("this test's bound is %s, with %s left until its deadline", b, left)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitBound is, for each call that waits, which argument is its bound.
|
||||||
|
var waitBound = map[string]int{
|
||||||
|
"After": 0, "NewTimer": 0, "WithTimeout": 1, "NextMsg": 0, "ReadyForConnections": 0, "Request": 2, "RequestMsg": 1,
|
||||||
|
"AskWithin": 3, "HearFirst": 2, "MaxWait": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1754/AC1: no test that starts a bus (a test file importing this package, and this package itself) waits for what the
|
||||||
|
// bus carries with a fixed bound of a second or more: each such wait takes the test's own deadline, Bound(t). A few
|
||||||
|
// seconds is what a loaded build node overran (issue 1754: state_counter_test.go's 5 s for a 1 s key's expire, failed on
|
||||||
|
// a build node); a bound under a second is the bound under test or the window an absence is given, and is not this guard's.
|
||||||
|
func TestNoWaitOnTheBusHasAFixedBound(t *testing.T) {
|
||||||
|
root := moduleRoot()
|
||||||
|
var found []string
|
||||||
|
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.IsDir() {
|
||||||
|
if path != root && (d.Name() == "node_modules" || strings.HasPrefix(d.Name(), ".")) {
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
ours := filepath.Base(dir) == "meshtest" && filepath.Base(filepath.Dir(dir)) == "internal"
|
||||||
|
if !strings.HasSuffix(path, ".go") || !ours && !strings.HasSuffix(path, "_test.go") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
found = append(found, fixedWaits(t, path, ours)...)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(found) > 0 {
|
||||||
|
t.Errorf("waits on the bus with a fixed bound, which a loaded build node overruns: give each the test's own, meshtest.Bound(t)\n%s",
|
||||||
|
strings.Join(found, "\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fixedWaits are the waits of one file that starts a bus whose bound is a constant of a second or more.
|
||||||
|
func fixedWaits(t *testing.T, path string, ours bool) []string {
|
||||||
|
t.Helper()
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
f, err := parser.ParseFile(fset, path, nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ours && !importsMeshtest(f) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
consts := packageConsts(t, filepath.Dir(path))
|
||||||
|
var found []string
|
||||||
|
flag := func(what string, bound ast.Expr) {
|
||||||
|
if d, ok := duration(bound, consts); ok && d >= time.Second {
|
||||||
|
rel, _ := filepath.Rel(moduleRoot(), fset.Position(bound.Pos()).Filename)
|
||||||
|
found = append(found, rel+":"+strconv.Itoa(fset.Position(bound.Pos()).Line)+": "+what+" "+d.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ast.Inspect(f, func(n ast.Node) bool {
|
||||||
|
switch n := n.(type) {
|
||||||
|
case *ast.CallExpr:
|
||||||
|
name := ""
|
||||||
|
switch fn := n.Fun.(type) {
|
||||||
|
case *ast.SelectorExpr:
|
||||||
|
name = fn.Sel.Name
|
||||||
|
case *ast.Ident:
|
||||||
|
name = fn.Name
|
||||||
|
}
|
||||||
|
if i, ok := waitBound[name]; ok && i < len(n.Args) {
|
||||||
|
flag(name, n.Args[i])
|
||||||
|
}
|
||||||
|
case *ast.AssignStmt:
|
||||||
|
// a deadline kept in a name, for a loop that polls until it passes
|
||||||
|
for _, v := range n.Rhs {
|
||||||
|
if bound, ok := nowAdd(v); ok {
|
||||||
|
flag("a deadline", bound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case *ast.ValueSpec:
|
||||||
|
for _, v := range n.Values {
|
||||||
|
if bound, ok := nowAdd(v); ok {
|
||||||
|
flag("a deadline", bound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
func importsMeshtest(f *ast.File) bool {
|
||||||
|
for _, i := range f.Imports {
|
||||||
|
if strings.HasSuffix(strings.Trim(i.Path.Value, `"`), "/internal/meshtest") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// nowAdd is d of time.Now().Add(d).
|
||||||
|
func nowAdd(e ast.Expr) (ast.Expr, bool) {
|
||||||
|
call, ok := e.(*ast.CallExpr)
|
||||||
|
if !ok || len(call.Args) != 1 {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
sel, ok := call.Fun.(*ast.SelectorExpr)
|
||||||
|
if !ok || sel.Sel.Name != "Add" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
now, ok := sel.X.(*ast.CallExpr)
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if s, ok := now.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "Now" && isIdent(s.X, "time") {
|
||||||
|
return call.Args[0], true
|
||||||
|
}
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isIdent(e ast.Expr, name string) bool {
|
||||||
|
id, ok := e.(*ast.Ident)
|
||||||
|
return ok && id.Name == name
|
||||||
|
}
|
||||||
|
|
||||||
|
// packageConsts are the constants a package's files declare at their top, by name, unevaluated.
|
||||||
|
func packageConsts(t *testing.T, dir string) map[string]ast.Expr {
|
||||||
|
t.Helper()
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
consts := map[string]ast.Expr{}
|
||||||
|
for _, e := range entries {
|
||||||
|
if !strings.HasSuffix(e.Name(), ".go") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
f, err := parser.ParseFile(token.NewFileSet(), filepath.Join(dir, e.Name()), nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, d := range f.Decls {
|
||||||
|
g, ok := d.(*ast.GenDecl)
|
||||||
|
if !ok || g.Tok != token.CONST {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, s := range g.Specs {
|
||||||
|
v := s.(*ast.ValueSpec)
|
||||||
|
for i, n := range v.Names {
|
||||||
|
if i < len(v.Values) {
|
||||||
|
consts[n.Name] = v.Values[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return consts
|
||||||
|
}
|
||||||
|
|
||||||
|
// duration is the value of a constant duration written as the tests write one: a number, time's units, a constant of
|
||||||
|
// the package, and their products and sums. Anything else (a variable, Bound(t), another package's bound) is not constant.
|
||||||
|
func duration(e ast.Expr, consts map[string]ast.Expr) (time.Duration, bool) {
|
||||||
|
switch e := e.(type) {
|
||||||
|
case *ast.ParenExpr:
|
||||||
|
return duration(e.X, consts)
|
||||||
|
case *ast.BasicLit:
|
||||||
|
if e.Kind == token.INT {
|
||||||
|
n, err := strconv.ParseInt(e.Value, 0, 64)
|
||||||
|
return time.Duration(n), err == nil
|
||||||
|
}
|
||||||
|
if e.Kind == token.FLOAT {
|
||||||
|
f, err := strconv.ParseFloat(e.Value, 64)
|
||||||
|
return time.Duration(f), err == nil
|
||||||
|
}
|
||||||
|
case *ast.SelectorExpr:
|
||||||
|
if isIdent(e.X, "time") {
|
||||||
|
unit, ok := map[string]time.Duration{"Nanosecond": time.Nanosecond, "Microsecond": time.Microsecond,
|
||||||
|
"Millisecond": time.Millisecond, "Second": time.Second, "Minute": time.Minute, "Hour": time.Hour}[e.Sel.Name]
|
||||||
|
return unit, ok
|
||||||
|
}
|
||||||
|
case *ast.Ident:
|
||||||
|
if v, ok := consts[e.Name]; ok {
|
||||||
|
delete(consts, e.Name) // a constant read once, so none refers to itself
|
||||||
|
d, ok := duration(v, consts)
|
||||||
|
consts[e.Name] = v
|
||||||
|
return d, ok
|
||||||
|
}
|
||||||
|
case *ast.UnaryExpr:
|
||||||
|
if d, ok := duration(e.X, consts); ok && e.Op == token.SUB {
|
||||||
|
return -d, true
|
||||||
|
}
|
||||||
|
case *ast.BinaryExpr:
|
||||||
|
a, okA := duration(e.X, consts)
|
||||||
|
b, okB := duration(e.Y, consts)
|
||||||
|
if !okA || !okB {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
switch e.Op {
|
||||||
|
case token.MUL:
|
||||||
|
return a * b, true
|
||||||
|
case token.ADD:
|
||||||
|
return a + b, true
|
||||||
|
case token.SUB:
|
||||||
|
return a - b, true
|
||||||
|
case token.QUO:
|
||||||
|
if b != 0 {
|
||||||
|
return a / b, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
@@ -2,11 +2,15 @@ package runtime
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
|
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
"github.com/nats-io/nats.go/micro"
|
"github.com/nats-io/nats.go/micro"
|
||||||
|
|
||||||
@@ -40,7 +44,7 @@ func TestTheRuntimeAnnouncesWhatItServesInTheServicesProtocol(t *testing.T) {
|
|||||||
defer nc.Close()
|
defer nc.Close()
|
||||||
info := func() micro.Info {
|
info := func() micro.Info {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, 2*time.Second)
|
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, mt.Bound(t))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -98,13 +102,13 @@ func TestTheRuntimeAnnouncesWhatItServesInTheServicesProtocol(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PING answers with the same identity, and a request for another service is not answered.
|
// PING answers with the same identity, and a request for another service is not answered.
|
||||||
if msg, err := nc.Request("$SRV.PING", nil, 2*time.Second); err != nil || !strings.Contains(string(msg.Data), micro.PingResponseType) {
|
if msg, err := nc.Request("$SRV.PING", nil, mt.Bound(t)); err != nil || !strings.Contains(string(msg.Data), micro.PingResponseType) {
|
||||||
t.Errorf("ping: %v %v", msg, err)
|
t.Errorf("ping: %v %v", msg, err)
|
||||||
}
|
}
|
||||||
// alpha is re-issued a plain subject: the announcement says so, and says it is interchangeable.
|
// alpha is re-issued a plain subject: the announcement says so, and says it is interchangeable.
|
||||||
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", true, nil))
|
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", true, nil))
|
||||||
var after string
|
var after string
|
||||||
for i := 0; i < 40; i++ {
|
for deadline := time.Now().Add(mt.Bound(t)); time.Now().Before(deadline); {
|
||||||
after = subjects(info())
|
after = subjects(info())
|
||||||
if strings.Contains(after, "mesh.mod.alpha.tool.one|serve.alpha|tool|alpha|||true") {
|
if strings.Contains(after, "mesh.mod.alpha.tool.one|serve.alpha|tool|alpha|||true") {
|
||||||
break
|
break
|
||||||
@@ -121,6 +125,7 @@ func TestTheRuntimeAnnouncesWhatItServesInTheServicesProtocol(t *testing.T) {
|
|||||||
// issue 1966 TLS-3 (ENG-2): the runner states the capabilities of the calls it answers in its PING, on its own instance, which
|
// issue 1966 TLS-3 (ENG-2): the runner states the capabilities of the calls it answers in its PING, on its own instance, which
|
||||||
// is what its machine's node-engine asks and takes into the node's record; no bundle is needed for it.
|
// is what its machine's node-engine asks and takes into the node's record; no bundle is needed for it.
|
||||||
func TestTheRunnerStatesTheCapabilitiesOfItsCallsInItsPing(t *testing.T) {
|
func TestTheRunnerStatesTheCapabilitiesOfItsCallsInItsPing(t *testing.T) {
|
||||||
|
t.Setenv(FingerprintWord, "sha256:runner")
|
||||||
mesh := mt.New(t)
|
mesh := mt.New(t)
|
||||||
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", false, nil))
|
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", false, nil))
|
||||||
nodeTools := connect(t, "node-tools", "anchor")
|
nodeTools := connect(t, "node-tools", "anchor")
|
||||||
@@ -134,12 +139,68 @@ func TestTheRunnerStatesTheCapabilitiesOfItsCallsInItsPing(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer nc.Close()
|
defer nc.Close()
|
||||||
msg, err := nc.Request("$SRV.PING.node-tools.anchor", nil, 2*time.Second)
|
msg, err := nc.Request("$SRV.PING.node-tools.anchor", nil, mt.Bound(t))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("ping of the instance: %v", err)
|
t.Fatalf("ping of the instance: %v", err)
|
||||||
}
|
}
|
||||||
var ping micro.Ping
|
var ping micro.Ping
|
||||||
if err := json.Unmarshal(msg.Data, &ping); err != nil || ping.Metadata[announce.Capabilities] != "approval-mark/1,bus-state-calls,ledger-calls,put-sessions,seat-settle-delay" {
|
if err := json.Unmarshal(msg.Data, &ping); err != nil || ping.Metadata[announce.Capabilities] != "approval-mark/1,bus-state-calls,finding-calls,ledger-calls,ledger-upkeep-calls,put-sessions,seat-settle-delay,sent-objects-calls,stream-publish" {
|
||||||
t.Errorf("the runner states %q (%v), want its bus-state and ledger calls", ping.Metadata[announce.Capabilities], err)
|
t.Errorf("the runner states %q (%v), want its bus-state and ledger calls", ping.Metadata[announce.Capabilities], err)
|
||||||
}
|
}
|
||||||
|
// Its own fingerprint beside them (design 46 approval mark §6).
|
||||||
|
if ping.Metadata[announce.Fingerprint] != "sha256:runner" {
|
||||||
|
t.Errorf("the runner states its fingerprint as %q", ping.Metadata[announce.Fingerprint])
|
||||||
|
}
|
||||||
|
// Design 47 G §462, §488, §622: each call is stated under the capability word of its own family, the words mesh-sdk's buscalls
|
||||||
|
// names: the read of a sent object under sent-objects-calls (no longer under bus-state-calls), the ledger's fill and removal
|
||||||
|
// under ledger-upkeep-calls, the others where they were.
|
||||||
|
t.Run("EachCallIsStatedUnderTheWordOfItsFamily", func(t *testing.T) {
|
||||||
|
for method, word := range map[string]string{
|
||||||
|
buscalls.ObjectsSentGet: buscalls.SentObjectsCalls,
|
||||||
|
buscalls.LedgerFill: buscalls.LedgerUpkeepCalls,
|
||||||
|
buscalls.LedgerRemove: buscalls.LedgerUpkeepCalls,
|
||||||
|
buscalls.LedgerApply: buscalls.LedgerCalls,
|
||||||
|
buscalls.ObjectsPut: buscalls.BusStateCalls,
|
||||||
|
buscalls.StreamPublish: buscalls.StreamPublishWord,
|
||||||
|
} {
|
||||||
|
var in []string
|
||||||
|
for c, methods := range callFamilies {
|
||||||
|
if slices.Contains(methods, method) {
|
||||||
|
in = append(in, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(in) != 1 || in[0] != word {
|
||||||
|
t.Errorf("%s is stated under %v, want %s alone", method, in, word)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// Design 47 G §545: the words the tool runner states are exactly its manifest's artifact `states`, so the delivery plan's edge
|
||||||
|
// of §605 runs to it for each word a module's artifact `calls`.
|
||||||
|
t.Run("TheWordsTheRunnerStatesAreItsManifestsStates", func(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile("../../module.json")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var m struct {
|
||||||
|
Build struct {
|
||||||
|
Artifacts []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
States []string `json:"states"`
|
||||||
|
} `json:"artifacts"`
|
||||||
|
} `json:"build"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &m); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var declared []string
|
||||||
|
for _, a := range m.Build.Artifacts {
|
||||||
|
if a.Name == "runtime" {
|
||||||
|
declared = a.States
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slices.Sort(declared)
|
||||||
|
if got := CallCapabilities(); !slices.Equal(got, declared) {
|
||||||
|
t.Errorf("the runner states %v, its manifest's states are %v", got, declared)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"sort"
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
@@ -18,28 +19,39 @@ import (
|
|||||||
// (announce.Capabilities) for its machine's node-engine to take into the node's record. A module whose manifest asks for one is
|
// (announce.Capabilities) for its machine's node-engine to take into the node's record. A module whose manifest asks for one is
|
||||||
// held off a machine whose runner does not state it.
|
// held off a machine whose runner does not state it.
|
||||||
const (
|
const (
|
||||||
CapBusStateCalls = "bus-state-calls"
|
CapBusStateCalls = buscalls.BusStateCalls
|
||||||
CapLedgerCalls = "ledger-calls"
|
CapLedgerCalls = buscalls.LedgerCalls
|
||||||
|
// CapLedgerUpkeepCalls is the ledger's fill and removal (§462, §488) and CapSentObjectsCalls the read of a sent object (§488):
|
||||||
|
// each is stated once the runner answers its family, the words mesh-sdk's buscalls names (§622).
|
||||||
|
CapLedgerUpkeepCalls = buscalls.LedgerUpkeepCalls
|
||||||
|
CapSentObjectsCalls = buscalls.SentObjectsCalls
|
||||||
// CapPutSessions is the put and get sessions' word (design 47 G §518, §622), mesh-sdk's.
|
// CapPutSessions is the put and get sessions' word (design 47 G §518, §622), mesh-sdk's.
|
||||||
CapPutSessions = stdio.CapPutSessions
|
CapPutSessions = stdio.CapPutSessions
|
||||||
// CapApprovalMark says the runner honours the approval mark: its gate sits on every handler it serves (design 46
|
// CapApprovalMark says the runner honours the approval mark: its gate sits on every handler it serves (design 46
|
||||||
// 7-approval-mark §6, §20), so the grants part composes no deny of its modules' marked subjects.
|
// 7-approval-mark §6, §20), so the grants part composes no deny of its modules' marked subjects.
|
||||||
CapApprovalMark = "approval-mark/1"
|
CapApprovalMark = "approval-mark/1"
|
||||||
|
// CapStreamPublish is the call that says an event on the module's own bound stream (design 42 zfs-owns-zfs, A-44), the
|
||||||
|
// word mesh-sdk's buscalls names (§622).
|
||||||
|
CapStreamPublish = buscalls.StreamPublishWord
|
||||||
)
|
)
|
||||||
|
|
||||||
// callFamilies are the methods each capability stands for, the ones BusState and BusStateWatch answer.
|
// callFamilies are the methods each capability stands for, the ones BusState and BusStateWatch answer.
|
||||||
var callFamilies = map[string][]string{
|
var callFamilies = map[string][]string{
|
||||||
CapBusStateCalls: {buscalls.ObjectsPut, buscalls.ObjectsGet, buscalls.ObjectsList, buscalls.ObjectsDelete, buscalls.ObjectsInfo,
|
CapBusStateCalls: {buscalls.ObjectsPut, buscalls.ObjectsGet, buscalls.ObjectsList, buscalls.ObjectsDelete, buscalls.ObjectsInfo,
|
||||||
buscalls.ObjectsWatch, buscalls.ObjectsSentGet, buscalls.StreamRead, buscalls.StreamFill, buscalls.WorkQueueSize, buscalls.WorkQueueDead},
|
buscalls.ObjectsWatch, buscalls.StreamRead, buscalls.StreamFill, buscalls.WorkQueueSize, buscalls.WorkQueueDead},
|
||||||
|
CapStreamPublish: {buscalls.StreamPublish},
|
||||||
CapLedgerCalls: {buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerHistory, buscalls.LedgerWatch, buscalls.LedgerQuery,
|
CapLedgerCalls: {buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerHistory, buscalls.LedgerWatch, buscalls.LedgerQuery,
|
||||||
buscalls.LedgerRebuild, buscalls.LedgerReindex, buscalls.LedgerSnapshot, buscalls.LedgerLag},
|
buscalls.LedgerRebuild, buscalls.LedgerReindex, buscalls.LedgerSnapshot, buscalls.LedgerLag},
|
||||||
CapPutSessions: {buscalls.ObjectsPutChunk, buscalls.ObjectsGetChunk},
|
CapLedgerUpkeepCalls: {buscalls.LedgerFill, buscalls.LedgerRemove},
|
||||||
|
CapSentObjectsCalls: {buscalls.ObjectsSentGet},
|
||||||
|
CapPutSessions: {buscalls.ObjectsPutChunk, buscalls.ObjectsGetChunk},
|
||||||
}
|
}
|
||||||
|
|
||||||
// CallCapabilities is every capability of the calls this runner answers, sorted. The delayed settle of a pulled seat
|
// CallCapabilities is every capability of the calls this runner answers, sorted. The delayed settle of a pulled seat
|
||||||
// message names a fate, not a method, so it stands beside the method families (novox/hq ADR 0664 §5).
|
// message names a fate, not a method, so it stands beside the method families (novox/hq ADR 0664 §5); so does `finding-calls`,
|
||||||
|
// the acknowledged `mesh/publish` and the `mesh/subscribe` for new messages the launch answers (design 47 G §559).
|
||||||
func CallCapabilities() []string {
|
func CallCapabilities() []string {
|
||||||
out := []string{stdio.CapSeatSettleDelay, CapApprovalMark}
|
out := []string{stdio.CapSeatSettleDelay, stdio.CapFindingCalls, CapApprovalMark}
|
||||||
for c := range callFamilies {
|
for c := range callFamilies {
|
||||||
out = append(out, c)
|
out = append(out, c)
|
||||||
}
|
}
|
||||||
@@ -103,6 +115,11 @@ func (b *moduleBus) BusState(method string, params json.RawMessage) (json.RawMes
|
|||||||
if err = decode(method, params, &r); err == nil {
|
if err = decode(method, params, &r); err == nil {
|
||||||
answer, err = conn.StreamFill(b.module, r)
|
answer, err = conn.StreamFill(b.module, r)
|
||||||
}
|
}
|
||||||
|
case buscalls.StreamPublish:
|
||||||
|
var r buscalls.StreamPublishRequest
|
||||||
|
if err = decode(method, params, &r); err == nil {
|
||||||
|
answer, err = conn.StreamPublish(b.module, r)
|
||||||
|
}
|
||||||
case buscalls.WorkQueueSize:
|
case buscalls.WorkQueueSize:
|
||||||
var r buscalls.WorkQueueRequest
|
var r buscalls.WorkQueueRequest
|
||||||
if err = decode(method, params, &r); err == nil {
|
if err = decode(method, params, &r); err == nil {
|
||||||
@@ -114,7 +131,7 @@ func (b *moduleBus) BusState(method string, params json.RawMessage) (json.RawMes
|
|||||||
answer, err = conn.WorkQueueDead(b.module, r)
|
answer, err = conn.WorkQueueDead(b.module, r)
|
||||||
}
|
}
|
||||||
case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerHistory, buscalls.LedgerQuery, buscalls.LedgerRebuild,
|
case buscalls.LedgerApply, buscalls.LedgerGet, buscalls.LedgerHistory, buscalls.LedgerQuery, buscalls.LedgerRebuild,
|
||||||
buscalls.LedgerReindex, buscalls.LedgerSnapshot, buscalls.LedgerLag:
|
buscalls.LedgerReindex, buscalls.LedgerSnapshot, buscalls.LedgerLag, buscalls.LedgerFill, buscalls.LedgerRemove:
|
||||||
answer, err = b.ledgerCall(method, params)
|
answer, err = b.ledgerCall(method, params)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("the runtime answers no %s", method)
|
return nil, fmt.Errorf("the runtime answers no %s", method)
|
||||||
@@ -161,15 +178,18 @@ func (c *consumers) objectsGet(module string, r buscalls.ObjectsNameRequest) (an
|
|||||||
if st == nil {
|
if st == nil {
|
||||||
return nil, fmt.Errorf("the runner has no bus to read %s of %s from", r.Name, module)
|
return nil, fmt.Errorf("the runner has no bus to read %s of %s from", r.Name, module)
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), bus.StateTimeout)
|
ctx, cancel, opened := openingContext()
|
||||||
defer cancel()
|
|
||||||
info, rd, found, err := st.ObjectsOpen(ctx, module, r)
|
info, rd, found, err := st.ObjectsOpen(ctx, module, r)
|
||||||
|
opened()
|
||||||
if err != nil || !found {
|
if err != nil || !found {
|
||||||
|
cancel()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if info.Size > buscalls.ChunkBytes {
|
if info.Size > buscalls.ChunkBytes {
|
||||||
return c.openGet(module, info, rd, sessionDigest(info.Digest), false)
|
// the reader reads on ctx after this call returns: it ends with the session, not with this call
|
||||||
|
return c.openGet(module, info, cancelOnClose{rd, cancel}, sessionDigest(info.Digest), false)
|
||||||
}
|
}
|
||||||
|
defer cancel()
|
||||||
defer rd.Close()
|
defer rd.Close()
|
||||||
data, err := io.ReadAll(rd)
|
data, err := io.ReadAll(rd)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -192,11 +212,32 @@ func (c *consumers) sentGet(module string, r buscalls.ObjectsSentGetRequest) (an
|
|||||||
if st == nil {
|
if st == nil {
|
||||||
return nil, fmt.Errorf("the runner has no bus to read %s from", r.Object)
|
return nil, fmt.Errorf("the runner has no bus to read %s from", r.Object)
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), bus.StateTimeout)
|
ctx, cancel, opened := openingContext()
|
||||||
defer cancel()
|
|
||||||
info, rd, err := st.SentOpen(ctx, r)
|
info, rd, err := st.SentOpen(ctx, r)
|
||||||
|
opened()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
cancel()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return c.openGet(module, info, rd, sessionDigest(r.Digest), true)
|
return c.openGet(module, info, cancelOnClose{rd, cancel}, sessionDigest(r.Digest), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// openingContext is the context an object is opened on: it is bound at bus.StateTimeout while opening, and once opened (the
|
||||||
|
// returned function) is bound no more: a reader of an object that outlives the call reads on it until its session ends.
|
||||||
|
func openingContext() (context.Context, context.CancelFunc, func()) {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
t := time.AfterFunc(bus.StateTimeout, cancel)
|
||||||
|
return ctx, cancel, func() { t.Stop() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// cancelOnClose ends the context an object's reader reads on when the reader is closed: at the end of its get session.
|
||||||
|
type cancelOnClose struct {
|
||||||
|
io.ReadCloser
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c cancelOnClose) Close() error {
|
||||||
|
err := c.ReadCloser.Close()
|
||||||
|
c.cancel()
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,21 +2,26 @@ package runtime
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
|
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
|
||||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
)
|
)
|
||||||
|
|
||||||
type saidCaller struct {
|
type saidCaller struct {
|
||||||
Caller string `json:"caller"`
|
Caller string `json:"caller"`
|
||||||
Call string `json:"call"`
|
Call string `json:"call"`
|
||||||
|
Ask *string `json:"ask"`
|
||||||
Arguments map[string]any `json:"arguments"`
|
Arguments map[string]any `json:"arguments"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,18 +67,49 @@ func TestACallOnTheCallerNamedSubjectReachesTheModuleWithItsCaller(t *testing.T)
|
|||||||
if got.Arguments["caller"] != "novox.node-tools" {
|
if got.Arguments["caller"] != "novox.node-tools" {
|
||||||
t.Errorf("%s: the arguments did not reach the module as sent: %v", key, got.Arguments)
|
t.Errorf("%s: the arguments did not reach the module as sent: %v", key, got.Arguments)
|
||||||
}
|
}
|
||||||
|
// A call that carries no ask id in its header names none in `_meta` (design 47 H2 §775, H-A-351).
|
||||||
|
if got.Ask != nil {
|
||||||
|
t.Errorf("%s reached the module with ask %q, want none for a call whose header carries none", key, *got.Ask)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
// **The ask id a kept call sets in its request header is copied into the call's `_meta` as mesh/ask** (design 47 H2 §775,
|
||||||
|
// H-A-351), for a module's tool and for a seat's verb.
|
||||||
|
url := mt.URL(t)
|
||||||
|
t.Run("TheAskIdOfTheHeaderReachesTheModule", func(t *testing.T) {
|
||||||
|
raw, err := nats.Connect(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer raw.Close()
|
||||||
|
for _, subject := range []string{"mesh.mod.ledger.tool.who", "mesh.seat.node-desk.tool.who.anchor"} {
|
||||||
|
msg := nats.NewMsg(subject)
|
||||||
|
msg.Header.Set(stdio.AskHeader, "ask-7f3a")
|
||||||
|
msg.Data = []byte(`{}`)
|
||||||
|
var reply struct {
|
||||||
|
Result saidCaller `json:"result"`
|
||||||
|
}
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
answer, err := raw.RequestMsg(msg, mt.Bound(t))
|
||||||
|
if err == nil {
|
||||||
|
err = json.Unmarshal(answer.Data, &reply)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if reply.Result.Ask == nil || *reply.Result.Ask != "ask-7f3a" {
|
||||||
|
t.Errorf("%s reached the module with ask %v, want the header's ask-7f3a under mesh/ask", subject, reply.Result.Ask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// deskDefined is the seat list's definition of the fixture seat node-desk, its verb who taking its class's default.
|
// deskDefined is the seat list's definition of the fixture seat node-desk, its verb who.
|
||||||
var deskDefined = WithSeatDefinitions(func() map[string]seatdef.Definition {
|
var deskDefined = WithSeatDefinitions(func() map[string]seatdef.Definition {
|
||||||
return map[string]seatdef.Definition{"node-desk": {Seat: "node-desk", Verbs: []seatdef.Verb{{Name: "who"}}}}
|
return map[string]seatdef.Definition{"node-desk": {Seat: "node-desk", Verbs: []seatdef.Verb{{Name: "who"}}}}
|
||||||
})
|
})
|
||||||
|
|
||||||
// The subject that names no caller is still served for a module's tool, for one release (retired by hq issue 464), and says
|
// The subject that names no caller is still served for a module's tool, for one release (retired by hq issue 464), and says
|
||||||
// so: the module is named no caller, whatever the body claims. A seat's verb refuses it before the bundle runs (design 47 G
|
// so: the module is named no caller, whatever the body claims. A seat's verb answers every caller, an unproven one too (design 47
|
||||||
// §610; lead answers A-165, A-179), and refuses every caller while the seat's definition is unread, names no such verb or
|
// H §752).
|
||||||
// opens it to none.
|
|
||||||
func TestTheSubjectThatNamesNoCallerStillWorksAndNamesNone(t *testing.T) {
|
func TestTheSubjectThatNamesNoCallerStillWorksAndNamesNone(t *testing.T) {
|
||||||
mesh := mt.New(t)
|
mesh := mt.New(t)
|
||||||
mesh.Issue(t, mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who"}}))
|
mesh.Issue(t, mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who"}}))
|
||||||
@@ -95,15 +131,16 @@ func TestTheSubjectThatNamesNoCallerStillWorksAndNamesNone(t *testing.T) {
|
|||||||
Error string `json:"error"`
|
Error string `json:"error"`
|
||||||
}
|
}
|
||||||
mt.Until(t, func() error {
|
mt.Until(t, func() error {
|
||||||
msg, err := old.Request(subject, body, 5*time.Second)
|
msg, err := old.Request(subject, body, mt.Bound(t))
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = json.Unmarshal(msg.Data, &reply)
|
err = json.Unmarshal(msg.Data, &reply)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
// Every caller is answered, an unproven one too (design 47 H §752).
|
||||||
if strings.HasPrefix(subject, "mesh.seat.") {
|
if strings.HasPrefix(subject, "mesh.seat.") {
|
||||||
if !strings.Contains(reply.Error, "node-desk.who takes no unproven caller") || reply.Result.Call != "" {
|
if reply.Error != "" {
|
||||||
t.Errorf("%s: an unproven caller of a seat's verb was answered %+v (error %q), want refused before the bundle", subject, reply.Result, reply.Error)
|
t.Errorf("%s: an unproven caller of a seat's verb was refused: %q, want answered", subject, reply.Error)
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -111,19 +148,173 @@ func TestTheSubjectThatNamesNoCallerStillWorksAndNamesNone(t *testing.T) {
|
|||||||
t.Errorf("%s: the module was named caller %q (error %q), want none", subject, reply.Result.Caller, reply.Error)
|
t.Errorf("%s: the module was named caller %q (error %q), want none", subject, reply.Result.Caller, reply.Error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, c := range []struct {
|
// Design 47 G A-249: a bundle's seat call is received by the runner in chunks only for a verb whose definition says `chunks`,
|
||||||
defs map[string]seatdef.Definition
|
// of any machine: a verb a node holds is asked of the node that ran the ask (A-254).
|
||||||
says string
|
t.Run("OnlyAChunkedSeatVerbIsAskedInChunks", func(t *testing.T) {
|
||||||
}{
|
c := &consumers{definitions: func() map[string]seatdef.Definition {
|
||||||
{nil, "is not yet read"},
|
return map[string]seatdef.Definition{"mesh-catalog": {Verbs: []seatdef.Verb{{Name: "input", Chunks: true}, {Name: "entry"}}}}
|
||||||
{map[string]seatdef.Definition{"node-desk": {Seat: "node-desk"}}, "names no verb who"},
|
}}
|
||||||
{map[string]seatdef.Definition{"node-desk": {Seat: "node-desk", Verbs: []seatdef.Verb{{Name: "who", Callers: &seatdef.Callers{List: []string{}}}}}}, "open to no caller"},
|
for key, want := range map[string]bool{
|
||||||
{map[string]seatdef.Definition{"node-desk": {Seat: "node-desk", Verbs: []seatdef.Verb{{Name: "who", Class: seatdef.ClassAct}}}}, ""},
|
"seat:mesh-catalog.input": true,
|
||||||
} {
|
"seat:mesh-catalog.entry": false,
|
||||||
defs := c.defs
|
"seat:mesh-catalog.input@home-server": true,
|
||||||
err := (&consumers{definitions: func() map[string]seatdef.Definition { return defs }}).admitted("node-desk", "who", "shanks.node-tools")
|
"seat:mesh-catalog.entry@home-server": false,
|
||||||
if c.says == "" && err != nil || c.says != "" && (err == nil || !strings.Contains(err.Error(), c.says)) {
|
"seat:mesh-unread.input": false,
|
||||||
t.Errorf("a proven caller with the definitions %v: %v, want %q", c.defs, err, c.says)
|
"mesh-delivery-indexer.indexer": false,
|
||||||
|
} {
|
||||||
|
if got := c.chunked(key); got != want {
|
||||||
|
t.Errorf("chunked(%s) = %v, want %v", key, got, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
if (&consumers{}).chunked("seat:mesh-catalog.input") {
|
||||||
|
t.Error("a runner that holds no seat definitions asks no chunks")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// Design 47 H §760: a bundle's ask waits the `timeout` its verb's definition names, whole seconds; a verb that names none, a
|
||||||
|
// seat the definitions do not hold, a module's tool and a runner that holds no definitions wait the runner's own bound (zero).
|
||||||
|
t.Run("AVerbsTimeoutIsTheBoundItsAskWaits", func(t *testing.T) {
|
||||||
|
forty, six := 40, 600
|
||||||
|
defs := map[string]seatdef.Definition{"mesh-broker": {Verbs: []seatdef.Verb{{Name: "rates", Timeout: &forty}, {Name: "slow", Chunks: true, Timeout: &six}, {Name: "plain"}}}}
|
||||||
|
for _, row := range []struct {
|
||||||
|
key string
|
||||||
|
want time.Duration
|
||||||
|
way string
|
||||||
|
}{
|
||||||
|
{"seat:mesh-broker.rates", 40 * time.Second, "plain"},
|
||||||
|
{"seat:mesh-broker.rates@home-server", 40 * time.Second, "plain"},
|
||||||
|
{"seat:mesh-broker.slow", 600 * time.Second, "chunked"},
|
||||||
|
{"seat:mesh-broker.plain", 0, "plain"},
|
||||||
|
{"seat:mesh-unread.rates", 0, "plain"},
|
||||||
|
{"mesh-delivery-indexer.indexer", 0, "plain"},
|
||||||
|
} {
|
||||||
|
var got time.Duration
|
||||||
|
var way string
|
||||||
|
c := &consumers{definitions: func() map[string]seatdef.Definition { return defs },
|
||||||
|
askPlain: func(_, _ string, _ any, within time.Duration) (bus.Answered, error) {
|
||||||
|
got, way = within, "plain"
|
||||||
|
return bus.Answered{}, nil
|
||||||
|
},
|
||||||
|
askChunked: func(_, _ string, _ any, within time.Duration) (bus.Answered, error) {
|
||||||
|
got, way = within, "chunked"
|
||||||
|
return bus.Answered{}, nil
|
||||||
|
}}
|
||||||
|
if _, err := (&moduleBus{all: c, module: "m"}).Ask(json.RawMessage(`{"key":"` + row.key + `","body":{}}`)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != row.want || way != row.way {
|
||||||
|
t.Errorf("Ask %s waited %s (%s), want %s (%s)", row.key, got, way, row.want, row.way)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := (&consumers{}).withinOf("seat:mesh-broker.rates"); got != 0 {
|
||||||
|
t.Errorf("a runner that holds no definitions waits %s, want its own bound", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// Design 47 G A-490m: a verb of a seat the list defines whose definition does not name it is read again once and never asked
|
||||||
|
// without its call; a seat the list does not define, a module's tool and a bundle asking through moduleBus.Ask behave as before.
|
||||||
|
t.Run("AVerbTheDefinitionDoesNotNameIsReadAgainAndNeverAskedWithoutItsCall", func(t *testing.T) {
|
||||||
|
stale := map[string]seatdef.Definition{"mesh-wants": {Verbs: []seatdef.Verb{{Name: "revision"}}}}
|
||||||
|
fresh := map[string]seatdef.Definition{"mesh-wants": {Verbs: []seatdef.Verb{{Name: "revision"}, {Name: "input", Chunks: true}}}}
|
||||||
|
for _, row := range []struct {
|
||||||
|
name string
|
||||||
|
key string
|
||||||
|
again func(held *map[string]seatdef.Definition) error
|
||||||
|
wantWay string // "plain", "chunked" or "" for a refusal
|
||||||
|
wantErr string
|
||||||
|
wantReads int
|
||||||
|
}{
|
||||||
|
{"a defined seat's verb the read names", "seat:mesh-wants.input", func(h *map[string]seatdef.Definition) error { *h = fresh; return nil }, "chunked", "", 1},
|
||||||
|
{"a read that fails", "seat:mesh-wants.input", func(h *map[string]seatdef.Definition) error { return errors.New("the seat does not answer") }, "", "does not answer", 1},
|
||||||
|
{"a read that still does not name it", "seat:mesh-wants.input@node-a", func(h *map[string]seatdef.Definition) error { return nil }, "", "names no verb input", 1},
|
||||||
|
{"a seat the list does not define", "seat:issue-tracker.list", func(h *map[string]seatdef.Definition) error { return nil }, "plain", "", 0},
|
||||||
|
{"a module's tool", "mesh-delivery-indexer.indexer", func(h *map[string]seatdef.Definition) error { return nil }, "plain", "", 0},
|
||||||
|
{"a verb the list names without chunks", "seat:mesh-wants.revision", func(h *map[string]seatdef.Definition) error { return nil }, "plain", "", 0},
|
||||||
|
} {
|
||||||
|
t.Run(row.name, func(t *testing.T) {
|
||||||
|
held, reads, way := stale, 0, ""
|
||||||
|
c := &consumers{definitions: func() map[string]seatdef.Definition { return held }, reread: func() error { reads++; return row.again(&held) },
|
||||||
|
askPlain: func(_, _ string, _ any, _ time.Duration) (bus.Answered, error) {
|
||||||
|
way = "plain"
|
||||||
|
return bus.Answered{}, nil
|
||||||
|
},
|
||||||
|
askChunked: func(_, _ string, _ any, _ time.Duration) (bus.Answered, error) {
|
||||||
|
way = "chunked"
|
||||||
|
return bus.Answered{}, nil
|
||||||
|
}}
|
||||||
|
_, err := (&moduleBus{all: c, module: "m"}).Ask(json.RawMessage(`{"key":"` + row.key + `","body":{}}`))
|
||||||
|
if way != row.wantWay || reads != row.wantReads || (row.wantErr == "") != (err == nil) || (err != nil && !strings.Contains(err.Error(), row.wantErr)) {
|
||||||
|
t.Errorf("Ask %s: asked %q, %v after %d reads, want %q, %q after %d", row.key, way, err, reads, row.wantWay, row.wantErr, row.wantReads)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// the asks that wait on a read share it
|
||||||
|
release, reads := make(chan struct{}), 0
|
||||||
|
held := stale
|
||||||
|
c := &consumers{definitions: func() map[string]seatdef.Definition { return held }, reread: func() error { reads++; <-release; held = fresh; return nil }}
|
||||||
|
done := make(chan bool, 3)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
go func() { got, err := c.chunkedAsked("seat:mesh-wants.input"); done <- got && err == nil }()
|
||||||
|
}
|
||||||
|
for deadline := time.Now().Add(mt.Bound(t)); c.rereadWaiting() < 2; runtime.Gosched() {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("two asks never joined the read running")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if !<-done {
|
||||||
|
t.Error("an ask waiting on the shared read was not answered chunked")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reads != 1 {
|
||||||
|
t.Errorf("%d reads of the seat list for three waiting asks, want 1", reads)
|
||||||
|
}
|
||||||
|
if got, err := (&consumers{}).chunkedAsked("seat:mesh-wants.input"); got || err != nil {
|
||||||
|
t.Errorf("a runner that holds no definitions asks no chunks: %v, %v", got, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// **The tool runner answers a held seat's marked verb by caller and serves the seat's `approvals`** (design 47 G §677; lead
|
||||||
|
// answers A-265, A-271), with zsh's node-login-shell `execute` as the case: the marked verb reaches the gate with the caller
|
||||||
|
// its subject names, and `approvals` is answered from the runner's own record of the calls its gate holds, with the
|
||||||
|
// arguments for the call's own caller only, though no bundle names the verb.
|
||||||
|
t.Run("TheRunnerServesApprovalsForTheSeatsItsBundlesHold", func(t *testing.T) {
|
||||||
|
mesh := mt.New(t)
|
||||||
|
mesh.Issue(t, mt.MembershipOf("zsh", "anchor", true, map[string][]string{"node-login-shell": {"execute", seatdef.ApprovalsVerb}}))
|
||||||
|
nodeTools := connect(t, "node-tools", "anchor")
|
||||||
|
gate := &gateHolding{}
|
||||||
|
defined := WithSeatDefinitions(func() map[string]seatdef.Definition {
|
||||||
|
return map[string]seatdef.Definition{"node-login-shell": {Seat: "node-login-shell", Verbs: []seatdef.Verb{
|
||||||
|
{Name: "execute", NeedsApproval: true}, {Name: seatdef.ApprovalsVerb}}}}
|
||||||
|
})
|
||||||
|
stop, err := Run(nodeTools, []Served{{"zsh", []string{mt.Fixture("login-shell-execute.py")}}}, nil, func(string, ...any) {}, defined, WithGate(gate))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
asker, err := bus.Connect(bus.Credential{URL: mt.URL(t), Module: "node-tools", Node: "workstation", User: "workstation.node-tools", Password: "unused"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
asker.Logf = func(string, ...any) {}
|
||||||
|
defer asker.Close()
|
||||||
|
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
_, err := asker.Ask("seat:node-login-shell.execute@anchor", map[string]any{"command": "ls"}, "")
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if len(gate.calls) != 1 || gate.calls[0].Seat != "node-login-shell" || gate.calls[0].Name != "execute" || gate.calls[0].Caller != "workstation.node-tools" {
|
||||||
|
t.Fatalf("the marked verb reached the gate as %+v, want the seat's execute by workstation.node-tools", gate.calls)
|
||||||
|
}
|
||||||
|
var got approval.Approvals
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
answered, err := asker.Ask("seat:node-login-shell.approvals@anchor", map[string]any{}, "")
|
||||||
|
if err == nil {
|
||||||
|
err = json.Unmarshal(answered.Result, &got)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if len(got.Calls) != 1 || got.Calls[0].Caller != "workstation.node-tools" || got.Calls[0].Verb != "node-login-shell.execute" ||
|
||||||
|
string(got.Calls[0].Arguments) != `{"command":"ls"}` {
|
||||||
|
t.Fatalf("approvals answered %+v, want the one call the gate holds, with its caller's arguments", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
package runtime
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Design 47 G A-249: a bundle's seat call is received by the runner in chunks only for a verb whose definition says `chunks`,
|
|
||||||
// of no one machine.
|
|
||||||
func TestOnlyAChunkedSeatVerbIsAskedInChunks(t *testing.T) {
|
|
||||||
c := &consumers{definitions: func() map[string]seatdef.Definition {
|
|
||||||
return map[string]seatdef.Definition{"mesh-catalog": {Verbs: []seatdef.Verb{{Name: "input", Chunks: true}, {Name: "entry"}}}}
|
|
||||||
}}
|
|
||||||
for key, want := range map[string]bool{
|
|
||||||
"seat:mesh-catalog.input": true,
|
|
||||||
"seat:mesh-catalog.entry": false,
|
|
||||||
"seat:mesh-catalog.input@ace": false,
|
|
||||||
"seat:mesh-unread.input": false,
|
|
||||||
"mesh-delivery-indexer.indexer": false,
|
|
||||||
} {
|
|
||||||
if got := c.chunked(key); got != want {
|
|
||||||
t.Errorf("chunked(%s) = %v, want %v", key, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (&consumers{}).chunked("seat:mesh-catalog.input") {
|
|
||||||
t.Error("a runner that holds no seat definitions asks no chunks")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -96,7 +96,7 @@ func TestTheRuntimeHandsAModulesEventsToItsBundleAndAcknowledgesThemOnlyWhenTake
|
|||||||
// The bundle dies on the first offer: not acknowledged, the bundle is started again and the
|
// The bundle dies on the first offer: not acknowledged, the bundle is started again and the
|
||||||
// event is offered again once its ack wait has passed.
|
// event is offered again once its ack wait has passed.
|
||||||
mesh.Emit(t, "mesh.mod.alpha.event.happened", map[string]any{"n": 3, "die": true})
|
mesh.Emit(t, "mesh.mod.alpha.event.happened", map[string]any{"n": 3, "die": true})
|
||||||
deadline := time.Now().Add(20 * time.Second)
|
deadline := time.Now().Add(mt.Bound(t))
|
||||||
for time.Now().Before(deadline) {
|
for time.Now().Before(deadline) {
|
||||||
if countLines(t, log, "handled 2") == 1 && countLines(t, log, "handled 3") == 1 {
|
if countLines(t, log, "handled 2") == 1 && countLines(t, log, "handled 3") == 1 {
|
||||||
break
|
break
|
||||||
@@ -193,3 +193,44 @@ func TestAHeartbeatHandlerSetAgainWhileWordsAreHandedOnIsNotARace(t *testing.T)
|
|||||||
t.Error("a bundle gave a handler and no heartbeat is asked")
|
t.Error("a bundle gave a handler and no heartbeat is asked")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// In a module's own runtime the module's consumer is bound once: one event on it reaches the bundle and then the runtime's
|
||||||
|
// hearer (the branch follower), and an event the bundle did not take is offered again before the hearer hears it (design 47
|
||||||
|
// H §752, H-A-132).
|
||||||
|
func TestOneEventOnAModulesConsumerReachesTheBundleAndTheHearer(t *testing.T) {
|
||||||
|
var order []string
|
||||||
|
all := &consumers{logf: t.Logf, of: map[string]*moduleEvents{}}
|
||||||
|
WithHearer("mod", func(env bus.Envelope) error { order = append(order, "hearer "+env.Key); return nil })(all)
|
||||||
|
m := &moduleEvents{}
|
||||||
|
all.of["mod"] = m
|
||||||
|
bundle := &deliverSlot{}
|
||||||
|
refuse := false
|
||||||
|
bundle.set(func(raw json.RawMessage) error {
|
||||||
|
if refuse {
|
||||||
|
return errorf("not now")
|
||||||
|
}
|
||||||
|
var env bus.Envelope
|
||||||
|
if err := json.Unmarshal(raw, &env); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
order = append(order, "bundle "+env.Key)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
m.delivers = []*deliverSlot{bundle}
|
||||||
|
if err := all.handOut("mod", m, bus.Envelope{Key: "mesh-catalog.catalog-revision.main", Body: json.RawMessage(`{}`)}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := strings.Join(order, ", "); got != "bundle mesh-catalog.catalog-revision.main, hearer mesh-catalog.catalog-revision.main" {
|
||||||
|
t.Fatalf("the event reached %q, want the bundle and then the hearer", got)
|
||||||
|
}
|
||||||
|
order, refuse = nil, true
|
||||||
|
if err := all.handOut("mod", m, bus.Envelope{Key: "a.b", Body: json.RawMessage(`{}`)}); err == nil || len(order) != 0 {
|
||||||
|
t.Fatalf("an event the bundle did not take: err %v, reached %q; want it offered again, heard by none", err, order)
|
||||||
|
}
|
||||||
|
// Another module's events are handed to its bundles alone.
|
||||||
|
other := &moduleEvents{delivers: []*deliverSlot{{f: func(json.RawMessage) error { order = append(order, "other"); return nil }}}}
|
||||||
|
all.of["other"] = other
|
||||||
|
if err := all.handOut("other", other, bus.Envelope{Key: "a.b", Body: json.RawMessage(`{}`)}); err != nil || strings.Join(order, ",") != "other" {
|
||||||
|
t.Fatalf("another module's event: err %v, reached %q", err, order)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package runtime
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/approval"
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
"git.novox.be/novox/mesh-sdk/go/seatdef"
|
||||||
@@ -19,59 +20,41 @@ type Gate interface {
|
|||||||
Unserved(module, fingerprint string, registered []string) []string
|
Unserved(module, fingerprint string, registered []string) []string
|
||||||
// Run is a call through the gate: run is called only when the call may run now, once.
|
// Run is a call through the gate: run is called only when the call may run now, once.
|
||||||
Run(call approval.Call, run func() (any, error)) (any, error)
|
Run(call approval.Call, run func() (any, error)) (any, error)
|
||||||
|
// Approvals is the seat verb `approvals` for a caller: the calls the gate holds, its acts and claims (A-265, A-271).
|
||||||
|
Approvals(caller string) (approval.Approvals, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// gatedRun is how a handler calls a tool: through the gate where there is one.
|
// gatedRun is how a handler calls a tool: through the gate where there is one.
|
||||||
type gatedRun func(call approval.Call, t launch.Tool, caller string) (any, error)
|
type gatedRun func(call approval.Call, t launch.Tool, caller, ask string) (any, error)
|
||||||
|
|
||||||
// gated calls the tool through the gate, or straight where the runner has none.
|
// gated calls the tool through the gate, or straight where the runner has none.
|
||||||
func (c *consumers) gated(call approval.Call, t launch.Tool, caller string) (any, error) {
|
func (c *consumers) gated(call approval.Call, t launch.Tool, caller, ask string) (any, error) {
|
||||||
run := func() (any, error) { return t.Run(caller, call.Args) }
|
run := func() (any, error) { return t.Call(caller, ask, call.Args) }
|
||||||
if c.gate == nil {
|
if c.gate == nil {
|
||||||
return run()
|
return run()
|
||||||
}
|
}
|
||||||
return c.gate.Run(call, run)
|
return c.gate.Run(call, run)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// approvalsOf is how the runner answers a held seat's verb `approvals`: from its gate's record, nil without a gate.
|
||||||
|
func (r *runner) approvalsOf() func(caller string) (any, error) {
|
||||||
|
if r.events.gate == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return func(caller string) (any, error) { return r.events.gate.Approvals(caller) }
|
||||||
|
}
|
||||||
|
|
||||||
// WithGate serves every call through the approval gate.
|
// WithGate serves every call through the approval gate.
|
||||||
func WithGate(g Gate) Option { return func(c *consumers) { c.gate = g } }
|
func WithGate(g Gate) Option { return func(c *consumers) { c.gate = g } }
|
||||||
|
|
||||||
var _ Gate = (*approval.Gate)(nil)
|
var _ Gate = (*approval.Gate)(nil)
|
||||||
|
|
||||||
// WithSeatDefinitions refuses, where a seat's verb is answered, a caller outside the verb's effective callers, before the
|
// WithSeatDefinitions gives the runner the seat definitions its seat list holds: a verb's `chunks` and `timeout` are read from them
|
||||||
// bundle runs (design 47 G §610; lead answers A-165, A-179): defs are the seat definitions the runner's seat list holds.
|
// (design 47 H §760). No definition names who may call: every caller is answered (design 47 H §752).
|
||||||
// Without it a verb is answered for every caller, as before.
|
|
||||||
func WithSeatDefinitions(defs func() map[string]seatdef.Definition) Option {
|
func WithSeatDefinitions(defs func() map[string]seatdef.Definition) Option {
|
||||||
return func(c *consumers) { c.definitions = defs }
|
return func(c *consumers) { c.definitions = defs }
|
||||||
}
|
}
|
||||||
|
|
||||||
// admitted says why a seat's verb is refused to a caller, nil when it is answered: an unproven caller is refused, and so is
|
|
||||||
// every caller while the seat's definition is not read, names no such verb, or the verb's effective callers are empty; a
|
|
||||||
// proven caller is among them, since the grants part composes a verb's call subject only for its effective callers (A-179).
|
|
||||||
func (c *consumers) admitted(seat, verb, caller string) error {
|
|
||||||
if c.definitions == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if caller == "" {
|
|
||||||
return fmt.Errorf("Not run: %s.%s takes no unproven caller: call it on its subject that names its caller, "+
|
|
||||||
"mesh.seat.%s.call.%s.<caller>", seat, verb, seat, verb)
|
|
||||||
}
|
|
||||||
def, ok := c.definitions()[seat]
|
|
||||||
if !ok {
|
|
||||||
return fmt.Errorf("Not run: the definition of the seat %s is not yet read by this tool runner's seat list, so no caller "+
|
|
||||||
"of %s.%s is admitted", seat, seat, verb)
|
|
||||||
}
|
|
||||||
for _, v := range def.Verbs {
|
|
||||||
if v.Name == verb {
|
|
||||||
if len(v.EffectiveCallers()) == 0 {
|
|
||||||
return fmt.Errorf("Not run: %s.%s is open to no caller", seat, verb)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf("Not run: the seat %s's definition names no verb %s, so no caller is admitted", seat, verb)
|
|
||||||
}
|
|
||||||
|
|
||||||
// unservedMarks is, of the module's marked tools, those its bundle's registrations under its own name do not register.
|
// unservedMarks is, of the module's marked tools, those its bundle's registrations under its own name do not register.
|
||||||
func (r *runner) unservedMarks(module string, regs []launch.Registration) []string {
|
func (r *runner) unservedMarks(module string, regs []launch.Registration) []string {
|
||||||
if r.events.gate == nil {
|
if r.events.gate == nil {
|
||||||
@@ -88,14 +71,100 @@ func (r *runner) unservedMarks(module string, regs []launch.Registration) []stri
|
|||||||
return r.events.gate.Unserved(module, r.fingerprintOf(module), registered)
|
return r.events.gate.Unserved(module, r.fingerprintOf(module), registered)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithSeatDefinitionsAgain gives the runner the way to read the seat list again (the seat list reader's Reload): a seat verb a bundle asks
|
||||||
|
// that the definitions held do not name is looked up again after it, never taken for a verb that sends no chunks.
|
||||||
|
func WithSeatDefinitionsAgain(again func() error) Option {
|
||||||
|
return func(c *consumers) { c.reread = again }
|
||||||
|
}
|
||||||
|
|
||||||
|
// chunkedAsked is chunked for a verb a bundle asks, where the answer decides whether the runner chooses the `call` the holder
|
||||||
|
// requires (AskAsChunked) (design 47 G A-490m). A verb of a seat the definitions held DEFINE, whose definition does not name it,
|
||||||
|
// is not taken for one that sends no chunks, since the holder then refuses an ask that carries no call: the seat list is read
|
||||||
|
// again once (one read shared by the asks that wait on it) and a verb still unnamed is an error saying so. An ask of a seat the
|
||||||
|
// definitions do not define at all, a module's tool and a runner that holds no definitions (nil) are asked as before.
|
||||||
|
func (c *consumers) chunkedAsked(key string) (bool, error) {
|
||||||
|
if c.definitions == nil || !strings.HasPrefix(key, "seat:") {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
name, _, _ := strings.Cut(key, "@")
|
||||||
|
seat, verb, ok := strings.Cut(strings.TrimPrefix(name, "seat:"), ".")
|
||||||
|
if !ok {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
find := func() (chunks, defined, named bool) {
|
||||||
|
d, defined := c.definitions()[seat]
|
||||||
|
for _, v := range d.Verbs {
|
||||||
|
if v.Name == verb {
|
||||||
|
return v.Chunks, true, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, defined, false
|
||||||
|
}
|
||||||
|
chunks, defined, named := find()
|
||||||
|
if named || !defined {
|
||||||
|
return chunks, nil
|
||||||
|
}
|
||||||
|
var why string
|
||||||
|
if c.reread != nil {
|
||||||
|
if err := c.rereadShared(); err != nil {
|
||||||
|
why = " (reading the seat list again failed: " + err.Error() + ")"
|
||||||
|
}
|
||||||
|
chunks, defined, named = find()
|
||||||
|
if named {
|
||||||
|
return chunks, nil
|
||||||
|
}
|
||||||
|
if !defined {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, fmt.Errorf("the definition of the seat %s names no verb %s, so the runner cannot tell whether it sends its answer in chunks and does not ask it%s", seat, verb, why)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rereadShared reads the seat list again; asks that arrive while a read runs wait for it and share its result.
|
||||||
|
func (c *consumers) rereadShared() error {
|
||||||
|
c.rereadMu.Lock()
|
||||||
|
if f := c.rereading; f != nil {
|
||||||
|
f.waiters++
|
||||||
|
c.rereadMu.Unlock()
|
||||||
|
<-f.done
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
f := &rereadFlight{done: make(chan struct{})}
|
||||||
|
c.rereading = f
|
||||||
|
c.rereadMu.Unlock()
|
||||||
|
f.err = c.reread()
|
||||||
|
c.rereadMu.Lock()
|
||||||
|
c.rereading = nil
|
||||||
|
c.rereadMu.Unlock()
|
||||||
|
close(f.done)
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
type rereadFlight struct {
|
||||||
|
done chan struct{}
|
||||||
|
err error
|
||||||
|
waiters int // the asks that joined the read (under rereadMu)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rereadWaiting is how many asks have joined the read now running; a test waits on it instead of sleeping.
|
||||||
|
func (c *consumers) rereadWaiting() int {
|
||||||
|
c.rereadMu.Lock()
|
||||||
|
defer c.rereadMu.Unlock()
|
||||||
|
if c.rereading == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return c.rereading.waiters
|
||||||
|
}
|
||||||
|
|
||||||
// chunked says whether key names a seat's verb whose definition says `chunks` (design 47 G A-249): its answer is received in
|
// chunked says whether key names a seat's verb whose definition says `chunks` (design 47 G A-249): its answer is received in
|
||||||
// chunks by the runner, whose call hands the bundle the whole.
|
// chunks by the runner, whose call hands the bundle the whole.
|
||||||
func (c *consumers) chunked(key string) bool {
|
func (c *consumers) chunked(key string) bool {
|
||||||
if c.definitions == nil || !strings.HasPrefix(key, "seat:") {
|
if c.definitions == nil || !strings.HasPrefix(key, "seat:") {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
seat, verb, ok := strings.Cut(strings.TrimPrefix(key, "seat:"), ".")
|
name, _, _ := strings.Cut(key, "@") // a verb asked of the machine that ran the ask is chunked as the verb is (A-254)
|
||||||
if !ok || strings.Contains(verb, "@") {
|
seat, verb, ok := strings.Cut(strings.TrimPrefix(name, "seat:"), ".")
|
||||||
|
if !ok {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
for _, v := range c.definitions()[seat].Verbs {
|
for _, v := range c.definitions()[seat].Verbs {
|
||||||
@@ -105,3 +174,23 @@ func (c *consumers) chunked(key string) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// withinOf is how long a call of key waits for its answer: the `timeout` the verb's definition names, in whole seconds (design 47
|
||||||
|
// H §760, H-A-43); zero, which the bus reads as the tool runner's own bound, for a key that is no seat's verb, a seat the
|
||||||
|
// definitions do not hold, a verb they do not name and a verb that names none.
|
||||||
|
func (c *consumers) withinOf(key string) time.Duration {
|
||||||
|
if c.definitions == nil || !strings.HasPrefix(key, "seat:") {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
name, _, _ := strings.Cut(key, "@")
|
||||||
|
seat, verb, ok := strings.Cut(strings.TrimPrefix(name, "seat:"), ".")
|
||||||
|
if !ok {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
for _, v := range c.definitions()[seat].Verbs {
|
||||||
|
if v.Name == verb && v.Timeout != nil {
|
||||||
|
return time.Duration(*v.Timeout) * time.Second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
|
)
|
||||||
|
|
||||||
|
// gateHolding is the runner's gate as far as the runtime reaches it: it records the calls it is run for and answers
|
||||||
|
// `approvals` from them.
|
||||||
|
type gateHolding struct{ calls []approval.Call }
|
||||||
|
|
||||||
|
func (g *gateHolding) Unserved(string, string, []string) []string { return nil }
|
||||||
|
func (g *gateHolding) Run(c approval.Call, run func() (any, error)) (any, error) {
|
||||||
|
g.calls = append(g.calls, c)
|
||||||
|
return run()
|
||||||
|
}
|
||||||
|
func (g *gateHolding) Approvals(caller string) (approval.Approvals, error) {
|
||||||
|
out := approval.Approvals{Calls: []approval.ListedCall{}, Acts: []approval.ListedAct{}, Claims: []string{}}
|
||||||
|
for i, c := range g.calls {
|
||||||
|
l := approval.ListedCall{Call: string(rune('a' + i)), Caller: c.Caller, Verb: c.Seat + "." + c.Name, State: "waiting"}
|
||||||
|
if caller == c.Caller {
|
||||||
|
l.Arguments = c.Args
|
||||||
|
}
|
||||||
|
out.Calls = append(out.Calls, l)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The call a module's tool reaches the gate by carries the module's composed environment. The gate no longer tells a first-view tool
|
||||||
|
// by an environment word: it knows one by its name forms <module>_first_views and <module>_first_view_again (H-A-69), and the runner
|
||||||
|
// sets no view-callers word.
|
||||||
|
func TestAModuleToolsCallCarriesItsBundlesComposedEnvironment(t *testing.T) {
|
||||||
|
for name, tc := range map[string]struct {
|
||||||
|
envs map[string]map[string]string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
"a module with an environment": {map[string]map[string]string{"ledger": {"LEDGER_WORD": "x"}}, true},
|
||||||
|
"a module with none": {nil, false},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
mesh := mt.New(t)
|
||||||
|
mesh.Issue(t, mt.MembershipOf("ledger", "anchor", true, map[string][]string{"node-desk": {"who"}}))
|
||||||
|
nodeTools := connect(t, "node-tools", "anchor")
|
||||||
|
gate := &gateHolding{}
|
||||||
|
stop, err := Run(nodeTools, []Served{{"ledger", []string{mt.Fixture("caller-echo.py")}}}, tc.envs, func(string, ...any) {}, deskDefined, WithGate(gate))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
asker := connect(t, "node-tools", "anchor")
|
||||||
|
mt.Until(t, func() error { _, err := asker.Ask("ledger.who@anchor", map[string]any{}, ""); return err })
|
||||||
|
var found bool
|
||||||
|
for _, c := range gate.calls {
|
||||||
|
if c.Seat == "" && c.Name == "who" {
|
||||||
|
_, found = c.Env["LEDGER_WORD"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found != tc.want {
|
||||||
|
t.Errorf("the gate saw the composed word: %v, want %v (calls %+v)", found, tc.want, gate.calls)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
"git.novox.be/novox/mesh-sdk/go/buscompose"
|
||||||
@@ -42,7 +41,7 @@ func TestALedgerIsWrittenOnlyOnItsModulesLedgerConnection(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
go s.Start()
|
go s.Start()
|
||||||
if !s.ReadyForConnections(30 * time.Second) {
|
if !s.ReadyForConnections(mt.Bound(t)) {
|
||||||
t.Fatal("the bus did not come up")
|
t.Fatal("the bus did not come up")
|
||||||
}
|
}
|
||||||
t.Cleanup(s.Shutdown)
|
t.Cleanup(s.Shutdown)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
@@ -240,6 +241,35 @@ func TestTheLedgerKeepsItsPromisesOnTheBus(t *testing.T) {
|
|||||||
t.Fatalf("queried %+v, %v", q, err)
|
t.Fatalf("queried %+v, %v", q, err)
|
||||||
}
|
}
|
||||||
}},
|
}},
|
||||||
|
{"fill and removal are answered through the calls and remove an instance from the bus whole", "decision.gone", func(t *testing.T) {
|
||||||
|
must(t, open(t), "decision/gone", "title", `{"title":"Gone"}`)
|
||||||
|
must(t, open(t), "decision/gone", "note", `{"says":"two"}`)
|
||||||
|
must(t, open(t), "decision/stays", "note", `{"says":"kept"}`)
|
||||||
|
raw, err := m.BusState(buscalls.LedgerFill, json.RawMessage(`{"ledger":"records"}`))
|
||||||
|
var fill buscalls.Fill
|
||||||
|
if _ = json.Unmarshal(raw, &fill); err != nil || fill.Count < 3 || fill.Bytes == 0 {
|
||||||
|
t.Fatalf("the fill answered %s (%v)", raw, err)
|
||||||
|
}
|
||||||
|
raw, err = m.BusState(buscalls.LedgerRemove, json.RawMessage(`{"ledger":"records","instance":"decision/gone"}`))
|
||||||
|
var removed buscalls.LedgerRemoved
|
||||||
|
if _ = json.Unmarshal(raw, &removed); err != nil || removed.Operations != 2 || removed.Bytes == 0 {
|
||||||
|
t.Fatalf("the removal answered %s (%v)", raw, err)
|
||||||
|
}
|
||||||
|
l := open(t)
|
||||||
|
if last, _ := l.History.Last("decision.gone"); last != 0 {
|
||||||
|
t.Fatalf("operations are left, at %d", last)
|
||||||
|
}
|
||||||
|
if st, _, _ := l.State.Get("decision.gone"); st != nil {
|
||||||
|
t.Fatalf("the state is left: %s", st)
|
||||||
|
}
|
||||||
|
if last, _ := l.History.Last("decision.stays"); last == 0 {
|
||||||
|
t.Fatal("another instance lost its operations")
|
||||||
|
}
|
||||||
|
if raw, err = m.BusState(buscalls.LedgerRemove, json.RawMessage(`{"ledger":"records","instance":"decision/gone"}`)); err != nil ||
|
||||||
|
!strings.Contains(string(raw), `"operations":0`) {
|
||||||
|
t.Fatalf("a removal said twice answered %s (%v)", raw, err)
|
||||||
|
}
|
||||||
|
}},
|
||||||
{"a forged author is refused", "decision.forged", func(t *testing.T) {
|
{"a forged author is refused", "decision.forged", func(t *testing.T) {
|
||||||
_, err := m.BusState(buscalls.LedgerApply, json.RawMessage(`{"ledger":"records","instance":"decision/forged","operation":"title","body":{"title":"T","author":"op@shanks"},"call":"forged"}`))
|
_, err := m.BusState(buscalls.LedgerApply, json.RawMessage(`{"ledger":"records","instance":"decision/forged","operation":"title","body":{"title":"T","author":"op@shanks"},"call":"forged"}`))
|
||||||
if err == nil || !strings.Contains(err.Error(), "the call forged, which is not a tool call in flight") {
|
if err == nil || !strings.Contains(err.Error(), "the call forged, which is not a tool call in flight") {
|
||||||
@@ -258,4 +288,70 @@ func TestTheLedgerKeepsItsPromisesOnTheBus(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
// Design 47 G §559, A-153: against the real bus a publish with ack answers the sequence the bus gave it, and a subscription
|
||||||
|
// for new messages hears only what is published after it was made, on the subject mesh-sdk's one rule names for the event;
|
||||||
|
// a wildcard is refused.
|
||||||
|
t.Run("AnAckedPublishAnswersItsSequenceAndANewSubscriptionHearsOnlyWhatComesAfter", func(t *testing.T) {
|
||||||
|
mt.New(t)
|
||||||
|
nc, err := nats.Connect(mt.URL(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(nc.Close)
|
||||||
|
js, _ := jetstream.New(nc)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "SEATEVENTS", Subjects: []string{"mesh.seat.mesh-conditions.event.>"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
conn := connect(t, "node-tools", "anchor")
|
||||||
|
publish := func(body string) {
|
||||||
|
t.Helper()
|
||||||
|
if _, err := js.Publish(ctx, "mesh.seat.mesh-conditions.event.findings-asked", []byte(body)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
publish(`{"before":true}`)
|
||||||
|
|
||||||
|
var mu sync.Mutex
|
||||||
|
var heard []string
|
||||||
|
stop, err := conn.SubscribeNew("mesh-conditions.findings-asked", func(raw json.RawMessage) error {
|
||||||
|
var env bus.Envelope
|
||||||
|
_ = json.Unmarshal(raw, &env)
|
||||||
|
mu.Lock()
|
||||||
|
heard = append(heard, env.Key+" "+string(env.Body))
|
||||||
|
mu.Unlock()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stop()
|
||||||
|
publish(`{"after":true}`)
|
||||||
|
publish(`{"after":2}`)
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if len(heard) < 2 {
|
||||||
|
return context.DeadlineExceeded
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
mu.Lock()
|
||||||
|
if len(heard) != 2 || heard[0] != `mesh-conditions.findings-asked {"after":true}` {
|
||||||
|
t.Errorf("heard %v, want the messages after the subscription alone, in order", heard)
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
|
||||||
|
for name, want := range map[string]string{"mesh-conditions.*": "[A-Za-z0-9_-]"} {
|
||||||
|
if _, err := conn.SubscribeNew(name, func(json.RawMessage) error { return nil }); err == nil || !strings.Contains(err.Error(), want) {
|
||||||
|
t.Errorf("a subscription for %s answered %v, want one naming %q", name, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
first, err := conn.PublishAsAcked("node-tools", bus.Envelope{Key: "finding-written", Body: json.RawMessage(`{}`)})
|
||||||
|
second, err2 := conn.PublishAsAcked("node-tools", bus.Envelope{Key: "finding-written", Body: json.RawMessage(`{}`)})
|
||||||
|
if err != nil || err2 != nil || first == 0 || second != first+1 {
|
||||||
|
t.Errorf("acknowledged publishes answered %d (%v) and %d (%v), want consecutive sequences", first, err, second, err2)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -171,6 +171,17 @@ func (b *moduleBus) ledgerCall(method string, params json.RawMessage) (any, erro
|
|||||||
var r buscalls.LedgerRequest
|
var r buscalls.LedgerRequest
|
||||||
_ = json.Unmarshal(params, &r)
|
_ = json.Unmarshal(params, &r)
|
||||||
return l.Lag(r)
|
return l.Lag(r)
|
||||||
|
case buscalls.LedgerFill:
|
||||||
|
var r buscalls.LedgerRequest
|
||||||
|
_ = json.Unmarshal(params, &r)
|
||||||
|
return l.Fill(r)
|
||||||
|
case buscalls.LedgerRemove:
|
||||||
|
// Never on an apply: a removal is no operation of the history and has no author (design 47 G §587).
|
||||||
|
var r buscalls.LedgerRemoveRequest
|
||||||
|
if err := decode(method, params, &r); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return l.Remove(r)
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("the runtime answers no %s", method)
|
return nil, fmt.Errorf("the runtime answers no %s", method)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"slices"
|
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -40,7 +39,7 @@ func TestTheLedgerRepairsAreToolsOfEveryLedgerOwner(t *testing.T) {
|
|||||||
defer stop()
|
defer stop()
|
||||||
asker := connect(t, "console", "workstation")
|
asker := connect(t, "console", "workstation")
|
||||||
listed := func(module string) (string, error) {
|
listed := func(module string) (string, error) {
|
||||||
answered, err := asker.Ask(module+"."+ToolsVerb, map[string]any{}, "")
|
answered, err := asker.AskWithin(module+"."+ToolsVerb, map[string]any{}, "", mt.Bound(t))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
@@ -68,6 +67,18 @@ func TestTheLedgerRepairsAreToolsOfEveryLedgerOwner(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
t.Run("a ledger bound later brings them", func(t *testing.T) {
|
t.Run("a ledger bound later brings them", func(t *testing.T) {
|
||||||
|
// Its own tool answers the first call after each binding comes or goes: the repairs' refresh keeps the
|
||||||
|
// subscriptions it still names (design 47 H, H-A-160).
|
||||||
|
for round := 1; round <= 10; round++ {
|
||||||
|
plain.Bindings = nil
|
||||||
|
if round%2 == 1 {
|
||||||
|
plain.Bindings = owner.Bindings
|
||||||
|
}
|
||||||
|
mesh.Issue(t, plain)
|
||||||
|
if _, err := asker.AskWithin("plain.who@anchor", map[string]any{}, "", mt.Bound(t)); err != nil {
|
||||||
|
t.Fatalf("binding change %d: the first call of plain.who failed: %v — dropped while its tools were served again", round, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
plain.Bindings = owner.Bindings
|
plain.Bindings = owner.Bindings
|
||||||
mesh.Issue(t, plain)
|
mesh.Issue(t, plain)
|
||||||
mt.Until(t, func() error {
|
mt.Until(t, func() error {
|
||||||
@@ -205,13 +216,9 @@ func TestABundleToolNamedAsALedgerRepairIsRefused(t *testing.T) {
|
|||||||
// no other name; none answers "the runtime answers no ...".
|
// no other name; none answers "the runtime answers no ...".
|
||||||
func TestEveryCallOfAStatedCapabilityIsAnswered(t *testing.T) {
|
func TestEveryCallOfAStatedCapabilityIsAnswered(t *testing.T) {
|
||||||
m, _, _ := aLedger(t)
|
m, _, _ := aLedger(t)
|
||||||
if got := strings.Join(CallCapabilities(), ","); got != "approval-mark/1,bus-state-calls,ledger-calls,put-sessions,seat-settle-delay" {
|
if got := strings.Join(CallCapabilities(), ","); got != "approval-mark/1,bus-state-calls,finding-calls,ledger-calls,ledger-upkeep-calls,put-sessions,seat-settle-delay,sent-objects-calls,stream-publish" {
|
||||||
t.Fatalf("the runner states %s", got)
|
t.Fatalf("the runner states %s", got)
|
||||||
}
|
}
|
||||||
// Design 47 G §462: the call that reads a sent object is listed under the bus state capability.
|
|
||||||
if !slices.Contains(callFamilies[CapBusStateCalls], buscalls.ObjectsSentGet) {
|
|
||||||
t.Errorf("%s does not list %s", CapBusStateCalls, buscalls.ObjectsSentGet)
|
|
||||||
}
|
|
||||||
for capability, methods := range callFamilies {
|
for capability, methods := range callFamilies {
|
||||||
for _, method := range methods {
|
for _, method := range methods {
|
||||||
t.Run(capability+" "+method, func(t *testing.T) {
|
t.Run(capability+" "+method, func(t *testing.T) {
|
||||||
|
|||||||
@@ -247,7 +247,7 @@ func TestALogAnswersEachVerbOnTheBus(t *testing.T) {
|
|||||||
if e.Sequence != want || e.Key != "12" {
|
if e.Sequence != want || e.Key != "12" {
|
||||||
t.Fatalf("the watch handed %d %s, want %d", e.Sequence, e.Key, want)
|
t.Fatalf("the watch handed %d %s, want %d", e.Sequence, e.Key, want)
|
||||||
}
|
}
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatalf("the watch did not hand entry %d", want)
|
t.Fatalf("the watch did not hand entry %d", want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,25 @@ func TestNoBusWordReachesABundle(t *testing.T) {
|
|||||||
t.Errorf("%s did not reach the bundle", want)
|
t.Errorf("%s did not reach the bundle", want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// design 47 G §618, §519: the runtime's own fingerprint reaches no bundle; the fingerprint a module's composed words hold does.
|
||||||
|
t.Run("TheRuntimesOwnFingerprintReachesNoBundle", func(t *testing.T) {
|
||||||
|
base := []string{"MESH_FINGERPRINT=runner-build", "PATH=/usr/bin"}
|
||||||
|
for name, c := range map[string]struct {
|
||||||
|
given map[string]string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"composed with none sees none": {nil, ""},
|
||||||
|
"composed with one sees its own": {map[string]string{"MESH_FINGERPRINT": "module-build"}, "MESH_FINGERPRINT=module-build"},
|
||||||
|
} {
|
||||||
|
env := strings.Join(BundleEnv(base, c.given, "telegram", "anchor"), "\n")
|
||||||
|
if strings.Contains(env, "runner-build") {
|
||||||
|
t.Errorf("%s: the runtime's own fingerprint reached the bundle: %s", name, env)
|
||||||
|
}
|
||||||
|
if c.want == "" && strings.Contains(env, "MESH_FINGERPRINT") || !strings.Contains(env, c.want) {
|
||||||
|
t.Errorf("%s: the environment is %s", name, env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// A tool call reaches only a tool's subject: whatever key a caller names, it is never a seat's event, accept
|
// A tool call reaches only a tool's subject: whatever key a caller names, it is never a seat's event, accept
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ func TestABundlesWatchIsHandedTheValueAndEachChange(t *testing.T) {
|
|||||||
select {
|
select {
|
||||||
case c := <-handed:
|
case c := <-handed:
|
||||||
return c
|
return c
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatalf("nothing handed: %s", what)
|
t.Fatalf("nothing handed: %s", what)
|
||||||
}
|
}
|
||||||
return ProvisionChange{}
|
return ProvisionChange{}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package runtime
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -10,6 +11,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/membership"
|
||||||
"github.com/nats-io/nats.go"
|
"github.com/nats-io/nats.go"
|
||||||
"github.com/nats-io/nats.go/micro"
|
"github.com/nats-io/nats.go/micro"
|
||||||
|
|
||||||
@@ -154,13 +157,17 @@ func newReloadBed(t *testing.T) *reloadBed {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *reloadBed) run(t *testing.T) {
|
// run starts the runtime, stopped at the test's end or once by what it returns.
|
||||||
|
func (b *reloadBed) run(t *testing.T) func() {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
stop, err := Run(b.nodeTools, []Served{{"ledger", []string{b.entry}}}, nil, b.logs.Logf)
|
stop, err := Run(b.nodeTools, []Served{{"ledger", []string{b.entry}}}, nil, b.logs.Logf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Cleanup(stop)
|
var once sync.Once
|
||||||
|
stopOnce := func() { once.Do(stop) }
|
||||||
|
t.Cleanup(stopOnce)
|
||||||
|
return stopOnce
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *reloadBed) answers(t *testing.T, tool string) {
|
func (b *reloadBed) answers(t *testing.T, tool string) {
|
||||||
@@ -194,7 +201,7 @@ func announced(t *testing.T) string {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer nc.Close()
|
defer nc.Close()
|
||||||
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, 2*time.Second)
|
msg, err := nc.Request("$SRV.INFO.node-tools.anchor", nil, mt.Bound(t))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -263,23 +270,66 @@ func TestAReplacedBundleIsReloaded(t *testing.T) {
|
|||||||
|
|
||||||
// A replaced bundle's old tool stays gone when the module's membership is issued again: a stopped tool
|
// A replaced bundle's old tool stays gone when the module's membership is issued again: a stopped tool
|
||||||
// leaves no membership handler behind to bind it once more, and a call on it starts no unmanaged second
|
// leaves no membership handler behind to bind it once more, and a call on it starts no unmanaged second
|
||||||
// copy of the bundle (issue 1945, review round 2).
|
// copy of the bundle (issue 1945, review round 2). And the tool still served answers the first call asked
|
||||||
|
// after each membership, within the test's own bound: the runner keeps the subscriptions the membership
|
||||||
|
// still names, so no call is dropped while it follows one (design 47 H, H-A-158).
|
||||||
func TestAReplacedBundlesOldToolStaysGoneOnTheNextMembership(t *testing.T) {
|
func TestAReplacedBundlesOldToolStaysGoneOnTheNextMembership(t *testing.T) {
|
||||||
b := newReloadBed(t)
|
b := newReloadBed(t)
|
||||||
place(t, b.entry, "first")
|
place(t, b.entry, "first")
|
||||||
b.run(t)
|
stop := b.run(t)
|
||||||
b.answers(t, "first")
|
b.answers(t, "first")
|
||||||
place(t, b.entry, "second")
|
place(t, b.entry, "second")
|
||||||
b.answers(t, "second")
|
b.answers(t, "second")
|
||||||
b.silent(t, "first")
|
b.silent(t, "first")
|
||||||
|
|
||||||
b.mesh.Issue(t, mt.MembershipOf("ledger", "anchor", false, nil))
|
for round := 1; round <= 5; round++ {
|
||||||
b.answers(t, "second")
|
b.mesh.Issue(t, mt.MembershipOf("ledger", "anchor", false, nil))
|
||||||
|
if got, err := call(t, b.asker, "ledger.second@anchor", map[string]any{}); err != nil || !strings.Contains(got, `"tool":"second"`) {
|
||||||
|
t.Fatalf("membership %d issued again: the first call of ledger.second answered %s, %v — dropped while the runner "+
|
||||||
|
"followed the membership\n%s", round, got, err, b.logs.All())
|
||||||
|
}
|
||||||
|
}
|
||||||
// Long enough for the reissued membership to have been heard, before the old tool is asked.
|
// Long enough for the reissued membership to have been heard, before the old tool is asked.
|
||||||
time.Sleep(300 * time.Millisecond)
|
time.Sleep(300 * time.Millisecond)
|
||||||
if got, err := call(t, b.asker, "ledger.first@anchor", map[string]any{}); err == nil {
|
if got, err := call(t, b.asker, "ledger.first@anchor", map[string]any{}); err == nil {
|
||||||
t.Fatalf("ledger.first is served again after the membership was reissued, and answered %s\n%s", got, b.logs.All())
|
t.Fatalf("ledger.first is served again after the membership was reissued, and answered %s\n%s", got, b.logs.All())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A ledger bound while the bundle is loaded again: its repairs are served once, by the module loaded, and none is
|
||||||
|
// left behind on the stand-in the reload served nothing on (design 47 H, H-A-160). The bundle placed holds its
|
||||||
|
// start until the test lets it go, so the membership is heard inside the reload.
|
||||||
|
held, release := filepath.Join(t.TempDir(), "held"), filepath.Join(t.TempDir(), "release")
|
||||||
|
placeScript(t, b.entry, strings.Replace(bundleServing("third"), "import json, os, sys\n",
|
||||||
|
"import json, os, sys, time\nopen("+fmt.Sprintf("%q", held)+", \"w\").close()\nwhile not os.path.exists("+
|
||||||
|
fmt.Sprintf("%q", release)+"):\n time.sleep(0.01)\n", 1))
|
||||||
|
mt.Until(t, func() error { _, err := os.Stat(held); return err })
|
||||||
|
bound := mt.MembershipOf("ledger", "anchor", false, nil)
|
||||||
|
bound.Bindings = []membership.BusBinding{{Local: "records", Storage: catalogue.StorageLedger, Template: catalogue.TemplateLedger,
|
||||||
|
History: "LEDGER_ledger_records", Subject: "mesh.ledger.ledger.records.history", State: "ledger_records",
|
||||||
|
Snapshot: "mesh.ledger.ledger.records.snapshot"}}
|
||||||
|
b.mesh.Issue(t, bound)
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
if m := b.nodeTools.Membership("ledger"); m == nil || len(m.Bindings) == 0 {
|
||||||
|
return errors.New("the ledger's binding is not heard yet")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err := os.WriteFile(release, nil, 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b.answers(t, "third")
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
_, err := call(t, b.asker, "ledger."+RepairLag+"@anchor", map[string]any{})
|
||||||
|
if errors.Is(err, bus.ErrNoResponders) || (err != nil && err.Error() == "timeout") {
|
||||||
|
return fmt.Errorf("the ledger's repairs are not served after its reload: %v", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
stop()
|
||||||
|
if _, err := call(t, b.asker, "ledger."+RepairLag+"@anchor", map[string]any{}); !errors.Is(err, bus.ErrNoResponders) {
|
||||||
|
t.Fatalf("the runtime stopped, and ledger.%s still answered (%v): served on the reload's stand-in and never stopped\n%s",
|
||||||
|
RepairLag, err, b.logs.All())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1945/AC21: a bundle removed while served is no longer served, and its module says why.
|
// 1945/AC21: a bundle removed while served is no longer served, and its module says why.
|
||||||
|
|||||||
@@ -62,6 +62,10 @@ type ListedTool struct {
|
|||||||
// NodeRuntimeModule is the module that is a machine's runtime, serving every module on it.
|
// NodeRuntimeModule is the module that is a machine's runtime, serving every module on it.
|
||||||
const NodeRuntimeModule = "node-tools"
|
const NodeRuntimeModule = "node-tools"
|
||||||
|
|
||||||
|
// fingerprintEnv is the word the node-engine starts each process with, the fingerprint of the want it applies (mesh-sdk's
|
||||||
|
// process.FingerprintEnv; this package imports no SDK): the runtime's own is no bundle's.
|
||||||
|
const fingerprintEnv = "MESH_FINGERPRINT"
|
||||||
|
|
||||||
// runtimeOnly are the words of the runtime's own environment no bundle is given.
|
// runtimeOnly are the words of the runtime's own environment no bundle is given.
|
||||||
var runtimeOnly = map[string]bool{ToolEnv: true, ToolModules: true, "MESH_BROKER_FILE": true,
|
var runtimeOnly = map[string]bool{ToolEnv: true, ToolModules: true, "MESH_BROKER_FILE": true,
|
||||||
"MESH_BROKER_URL": true, "MESH_CONSOLE_LISTEN": true, LedgersFile: true}
|
"MESH_BROKER_URL": true, "MESH_CONSOLE_LISTEN": true, LedgersFile: true}
|
||||||
@@ -173,6 +177,11 @@ func (r *runner) refreshRepairs() {
|
|||||||
changed := false
|
changed := false
|
||||||
for _, m := range r.modules {
|
for _, m := range r.modules {
|
||||||
l := r.of[m]
|
l := r.of[m]
|
||||||
|
// A module being loaded again is left to its reload, which serves its repairs as its binding is then: served
|
||||||
|
// here on the stand-in, they would be served twice and never stopped (design 47 H, H-A-160).
|
||||||
|
if l.reloading {
|
||||||
|
continue
|
||||||
|
}
|
||||||
served := false
|
served := false
|
||||||
for _, reg := range l.own {
|
for _, reg := range l.own {
|
||||||
served = served || reg.repairs
|
served = served || reg.repairs
|
||||||
@@ -181,10 +190,6 @@ func (r *runner) refreshRepairs() {
|
|||||||
if served == (repairs != nil) {
|
if served == (repairs != nil) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for i := len(l.serving) - 1; i >= 0; i-- {
|
|
||||||
l.serving[i]()
|
|
||||||
}
|
|
||||||
l.serving, l.names = nil, nil
|
|
||||||
l.own, l.regs = withRepairs(l.own, repairs), withRepairs(l.regs, repairs)
|
l.own, l.regs = withRepairs(l.own, repairs), withRepairs(l.regs, repairs)
|
||||||
r.serve(l)
|
r.serve(l)
|
||||||
changed = true
|
changed = true
|
||||||
@@ -203,14 +208,16 @@ type loadedModule struct {
|
|||||||
regs []registration // every registration its bundles made
|
regs []registration // every registration its bundles made
|
||||||
own []registration // those under the name of a module served here
|
own []registration // those under the name of a module served here
|
||||||
failed string
|
failed string
|
||||||
names []string // the tools it serves, as module.tool
|
names []string // the tools it serves, as module.tool
|
||||||
serving []func() // its tools' subscriptions
|
serving map[string]func() // its tools' subscriptions, by module.tool; serve alone changes it
|
||||||
|
// reloading marks the stand-in a reload puts in place while it loads the module again: it serves nothing.
|
||||||
|
reloading bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// unload stops serving the module's tools and stops its bundles.
|
// unload stops serving the module's tools and stops its bundles.
|
||||||
func (l *loadedModule) unload() {
|
func (l *loadedModule) unload() {
|
||||||
for i := len(l.serving) - 1; i >= 0; i-- {
|
for _, stop := range l.serving {
|
||||||
l.serving[i]()
|
stop()
|
||||||
}
|
}
|
||||||
l.serving, l.names = nil, nil
|
l.serving, l.names = nil, nil
|
||||||
for i := len(l.children) - 1; i >= 0; i-- {
|
for i := len(l.children) - 1; i >= 0; i-- {
|
||||||
@@ -237,6 +244,9 @@ type runner struct {
|
|||||||
// §424, §618), never the runner's own.
|
// §424, §618), never the runner's own.
|
||||||
fingerprintOf func(module string) string
|
fingerprintOf func(module string) string
|
||||||
|
|
||||||
|
// envOf is a module's composed environment, the words the gate tells a first-view tool by (lead answers A-377).
|
||||||
|
envOf func(module string) map[string]string
|
||||||
|
|
||||||
seatsAgain func()
|
seatsAgain func()
|
||||||
stops []func() // the watch, the announcement and the seats, in the order they began
|
stops []func() // the watch, the announcement and the seats, in the order they began
|
||||||
}
|
}
|
||||||
@@ -249,6 +259,19 @@ func WithLedgerWriters(writer func(module string) (*bus.Conn, error)) Option {
|
|||||||
return func(c *consumers) { c.ledgers.writer = writer }
|
return func(c *consumers) { c.ledgers.writer = writer }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithHearer hands every event of module's consumer also to hear, in process, after the module's bundles took it: the
|
||||||
|
// consumer is bound once, for the bundles, and no second pull loop reads the same durable, so in a module's own runtime the
|
||||||
|
// branch follower and the bundle each hear every event (design 47 H §752, H-A-113, H-A-132). An error of hear offers the
|
||||||
|
// event again, as a bundle's does.
|
||||||
|
func WithHearer(module string, hear func(bus.Envelope) error) Option {
|
||||||
|
return func(c *consumers) {
|
||||||
|
if c.hearers == nil {
|
||||||
|
c.hearers = map[string][]func(bus.Envelope) error{}
|
||||||
|
}
|
||||||
|
c.hearers[module] = append(c.hearers[module], hear)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Run launches, binds and serves, and serves each module's bundle again when it appears, changes or
|
// Run launches, binds and serves, and serves each module's bundle again when it appears, changes or
|
||||||
// goes, with no restart. It answers a stop function.
|
// goes, with no restart. It answers a stop function.
|
||||||
func Run(conn *bus.Conn, served []Served, envs map[string]map[string]string, logf func(string, ...any), opts ...Option) (func(), error) {
|
func Run(conn *bus.Conn, served []Served, envs map[string]map[string]string, logf func(string, ...any), opts ...Option) (func(), error) {
|
||||||
@@ -271,6 +294,7 @@ func Run(conn *bus.Conn, served []Served, envs map[string]map[string]string, log
|
|||||||
base := os.Environ()
|
base := os.Environ()
|
||||||
r.envFor = func(module string) []string { return BundleEnv(base, envs[module], module, node) }
|
r.envFor = func(module string) []string { return BundleEnv(base, envs[module], module, node) }
|
||||||
r.fingerprintOf = func(module string) string { return envs[module][FingerprintWord] }
|
r.fingerprintOf = func(module string) string { return envs[module][FingerprintWord] }
|
||||||
|
r.envOf = func(module string) map[string]string { return envs[module] }
|
||||||
|
|
||||||
// The module's events, for every child of it that subscribes (ADR 0198): one consumer per module,
|
// The module's events, for every child of it that subscribes (ADR 0198): one consumer per module,
|
||||||
// bound the first time any of its children subscribes, each event handed to every child that did.
|
// bound the first time any of its children subscribes, each event handed to every child that did.
|
||||||
@@ -306,7 +330,8 @@ func Run(conn *bus.Conn, served []Served, envs map[string]map[string]string, log
|
|||||||
}
|
}
|
||||||
logf("%s", line)
|
logf("%s", line)
|
||||||
conn.OnMembership(func(bus.Membership) { go func() { r.refreshRepairs(); conn.Flush() }() })
|
conn.OnMembership(func(bus.Membership) { go func() { r.refreshRepairs(); conn.Flush() }() })
|
||||||
stopSeats, again := serveSeats(conn, r.modules, r.registrations, r.events.gated, r.events.admitted, r.fingerprintOf, logf)
|
stopSeats, again := serveSeats(conn, r.modules, r.registrations, r.events.gated, r.events.chunked, r.events.withinOf, r.approvalsOf(),
|
||||||
|
r.fingerprintOf, logf)
|
||||||
r.seatsAgain = again
|
r.seatsAgain = again
|
||||||
r.stops = append(r.stops, stopSeats)
|
r.stops = append(r.stops, stopSeats)
|
||||||
|
|
||||||
@@ -316,7 +341,10 @@ func Run(conn *bus.Conn, served []Served, envs map[string]map[string]string, log
|
|||||||
announced, err := announce.Serve(conn, announce.Service{
|
announced, err := announce.Serve(conn, announce.Service{
|
||||||
Name: conn.Module(), ID: instanceOf(conn),
|
Name: conn.Module(), ID: instanceOf(conn),
|
||||||
Description: "the mesh's tool runtime on " + node + ": every assigned module's tools and the seats they hold",
|
Description: "the mesh's tool runtime on " + node + ": every assigned module's tools and the seats they hold",
|
||||||
Metadata: map[string]string{"node": node, announce.Capabilities: strings.Join(CallCapabilities(), ",")},
|
// Its own fingerprint beside the capabilities, so a reading is tied to the runner that made it (design 46 approval
|
||||||
|
// mark §6, lead answer A-203).
|
||||||
|
Metadata: map[string]string{"node": node, announce.Capabilities: strings.Join(CallCapabilities(), ","),
|
||||||
|
announce.Fingerprint: os.Getenv(FingerprintWord)},
|
||||||
}, func() []announce.Endpoint { return endpointsOf(conn, r.own(), r.registrations(), r.modules) })
|
}, func() []announce.Endpoint { return endpointsOf(conn, r.own(), r.registrations(), r.modules) })
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logf("[mesh-tools] cannot announce what it serves: %v", err)
|
logf("[mesh-tools] cannot announce what it serves: %v", err)
|
||||||
@@ -387,6 +415,7 @@ func (r *runner) claimed() map[string]bool {
|
|||||||
func (r *runner) load(s Served) *loadedModule {
|
func (r *runner) load(s Served) *loadedModule {
|
||||||
l := &loadedModule{served: s, seen: map[string]string{}}
|
l := &loadedModule{served: s, seen: map[string]string{}}
|
||||||
claimed := r.claimed()
|
claimed := r.claimed()
|
||||||
|
var all []launch.Registration // every bundle's registrations, the module's marks checked against them together (A-398)
|
||||||
for _, entry := range s.Entrypoints {
|
for _, entry := range s.Entrypoints {
|
||||||
path, _ := filepath.Abs(entry)
|
path, _ := filepath.Abs(entry)
|
||||||
module := s.Module
|
module := s.Module
|
||||||
@@ -417,13 +446,7 @@ func (r *runner) load(s Served) *loadedModule {
|
|||||||
fail(clashed)
|
fail(clashed)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// A bundle whose marks name a tool it does not register is not loaded: no tool of its module is served here, rather
|
all = append(all, child.Registrations...)
|
||||||
// than one served unmarked that the manifest meant to mark (design 46 7-approval-mark §4).
|
|
||||||
if unserved := r.unservedMarks(module, child.Registrations); len(unserved) > 0 {
|
|
||||||
child.Stop()
|
|
||||||
fail(fmt.Sprintf("its marks name %s, which it does not register (design 46 7-approval-mark §4)", strings.Join(unserved, ", ")))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
l.children = append(l.children, child.Stop)
|
l.children = append(l.children, child.Stop)
|
||||||
for _, reg := range child.Registrations {
|
for _, reg := range child.Registrations {
|
||||||
got := registration{module: reg.Module, owner: module, tools: reg.Tools}
|
got := registration{module: reg.Module, owner: module, tools: reg.Tools}
|
||||||
@@ -437,6 +460,18 @@ func (r *runner) load(s Served) *loadedModule {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// A module whose marks name a tool none of its bundles registers is not loaded: no tool of it is served here, rather
|
||||||
|
// than one served unmarked that the manifest meant to mark (design 46 7-approval-mark §4). Checked once, against every
|
||||||
|
// bundle of the module together (lead answer A-398: gitea's eight bundles each overwrote the gate's set).
|
||||||
|
if unserved := r.unservedMarks(s.Module, all); len(unserved) > 0 {
|
||||||
|
for _, stop := range l.children {
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
l.children, l.regs, l.own = nil, nil, nil
|
||||||
|
l.failed = fmt.Sprintf("its marks name %s, which none of its bundles registers (design 46 7-approval-mark §4)", strings.Join(unserved, ", "))
|
||||||
|
r.logf("[mesh-tools] %s is not loaded: %s; its tools are not served here", s.Module, l.failed)
|
||||||
|
return l
|
||||||
|
}
|
||||||
if repairs := r.repairsOf(s.Module); repairs != nil {
|
if repairs := r.repairsOf(s.Module); repairs != nil {
|
||||||
l.regs, l.own = append(l.regs, *repairs), append(l.own, *repairs)
|
l.regs, l.own = append(l.regs, *repairs), append(l.own, *repairs)
|
||||||
}
|
}
|
||||||
@@ -461,24 +496,47 @@ func refusal(own []registration) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// serve binds a loaded module's tools. r.mu is held.
|
// serve binds a loaded module's tools as its registrations name them now, and is the one routine that changes its
|
||||||
|
// subscriptions (design 47 H, H-A-158, H-A-160): a tool still named keeps its subscription, a newly named one is
|
||||||
|
// subscribed, and only then is one no longer named stopped — no tool is served twice, and none is dropped while the
|
||||||
|
// module's tools are served again. r.mu is held.
|
||||||
func (r *runner) serve(l *loadedModule) {
|
func (r *runner) serve(l *loadedModule) {
|
||||||
|
if l.serving == nil {
|
||||||
|
l.serving = map[string]func(){}
|
||||||
|
}
|
||||||
|
named := map[string]bool{}
|
||||||
|
l.names = nil
|
||||||
for _, reg := range l.own {
|
for _, reg := range l.own {
|
||||||
for _, t := range reg.tools {
|
for _, t := range reg.tools {
|
||||||
t := t
|
t := t
|
||||||
// Told who called, from the subject the call arrived on, never from its body (novox/hq issue 365).
|
address := reg.module + "." + t.Name
|
||||||
// Through the approval gate, before the bundle or the runner's own tool (design 46 7-approval-mark §20).
|
if named[address] {
|
||||||
module, own := reg.module, reg.repairs
|
|
||||||
stop, err := r.conn.HandleCalled(reg.module+"."+t.Name, func(caller string, body json.RawMessage) (any, error) {
|
|
||||||
return r.events.gated(approval.Call{Address: module + "." + t.Name, Module: module, Name: t.Name, Own: own,
|
|
||||||
Fingerprint: r.fingerprintOf(module), Caller: caller, Args: argsOf(body), Description: t.Description}, t, caller)
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
r.logf("[mesh-tools] cannot serve %s.%s: %v", reg.module, t.Name, err)
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
l.names = append(l.names, reg.module+"."+t.Name)
|
named[address] = true
|
||||||
l.serving = append(l.serving, stop)
|
if _, kept := l.serving[address]; !kept {
|
||||||
|
// Told who called, from the subject the call arrived on, never from its body (novox/hq issue 365).
|
||||||
|
// Through the approval gate, before the bundle or the runner's own tool (design 46 7-approval-mark §20).
|
||||||
|
module, own := reg.module, reg.repairs
|
||||||
|
stop, err := r.conn.HandleCalled(address, func(caller, ask string, body json.RawMessage) (any, error) {
|
||||||
|
return r.events.gated(approval.Call{Address: module + "." + t.Name, Module: module, Name: t.Name, Own: own,
|
||||||
|
Fingerprint: r.fingerprintOf(module), Env: r.envOf(module), Caller: caller, Args: argsOf(body),
|
||||||
|
Description: t.Description}, t, caller, ask)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
r.logf("[mesh-tools] cannot serve %s.%s: %v", reg.module, t.Name, err)
|
||||||
|
delete(named, address)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
l.serving[address] = stop
|
||||||
|
}
|
||||||
|
l.names = append(l.names, address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for address, stop := range l.serving {
|
||||||
|
if !named[address] {
|
||||||
|
stop()
|
||||||
|
delete(l.serving, address)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -580,7 +638,7 @@ func (r *runner) reconcile() {
|
|||||||
func (r *runner) reload(module, what string) {
|
func (r *runner) reload(module, what string) {
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
old := r.of[module]
|
old := r.of[module]
|
||||||
r.of[module] = &loadedModule{served: old.served, seen: old.seen}
|
r.of[module] = &loadedModule{served: old.served, seen: old.seen, reloading: true}
|
||||||
r.mu.Unlock()
|
r.mu.Unlock()
|
||||||
// Its events are refused first, so one heard while the old bundle stops is refused at once.
|
// Its events are refused first, so one heard while the old bundle stops is refused at once.
|
||||||
r.events.dropModule(module)
|
r.events.dropModule(module)
|
||||||
@@ -595,6 +653,11 @@ func (r *runner) reload(module, what string) {
|
|||||||
r.logf("[mesh-tools] %s's bundle is refused: %v; its tools are not served here", module, err)
|
r.logf("[mesh-tools] %s's bundle is refused: %v; its tools are not served here", module, err)
|
||||||
}
|
}
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
|
// Its repairs as its binding is now, not as it was when the load began: the refresh left the stand-in alone.
|
||||||
|
if fresh.failed == "" {
|
||||||
|
repairs := r.repairsOf(module)
|
||||||
|
fresh.own, fresh.regs = withRepairs(fresh.own, repairs), withRepairs(fresh.regs, repairs)
|
||||||
|
}
|
||||||
r.of[module] = fresh
|
r.of[module] = fresh
|
||||||
r.serve(fresh)
|
r.serve(fresh)
|
||||||
r.bindVerbs()
|
r.bindVerbs()
|
||||||
@@ -655,6 +718,9 @@ func endpointsOf(conn *bus.Conn, own []registration, registrations []registratio
|
|||||||
}
|
}
|
||||||
for _, v := range m.Seats {
|
for _, v := range m.Seats {
|
||||||
t, ok := impl[v.Seat][v.Verb]
|
t, ok := impl[v.Seat][v.Verb]
|
||||||
|
if v.Verb == seatdef.ApprovalsVerb && !ok {
|
||||||
|
t, ok = launch.Tool{Name: v.Verb, Description: "The calls this seat's holder holds for the operator's approval, its acts and its claims."}, true
|
||||||
|
}
|
||||||
if !ok || have[v.Subject] {
|
if !ok || have[v.Subject] {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -710,7 +776,8 @@ func subjectsOf(conn *bus.Conn, module, tool string) []string {
|
|||||||
// whenever a membership changes, and when again is called because a bundle was loaded again. Whether
|
// whenever a membership changes, and when again is called because a bundle was loaded again. Whether
|
||||||
// this machine holds the seat is the bus's to decide. It answers its stop and again.
|
// this machine holds the seat is the bus's to decide. It answers its stop and again.
|
||||||
func serveSeats(conn *bus.Conn, modules []string, current func() []registration, gated gatedRun,
|
func serveSeats(conn *bus.Conn, modules []string, current func() []registration, gated gatedRun,
|
||||||
admitted func(seat, verb, caller string) error, fingerprintOf func(string) string, logf func(string, ...any)) (func(), func()) {
|
chunked func(key string) bool, within func(key string) time.Duration, approvals func(caller string) (any, error),
|
||||||
|
fingerprintOf func(string) string, logf func(string, ...any)) (func(), func()) {
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
var stops []func()
|
var stops []func()
|
||||||
stopped := false
|
stopped := false
|
||||||
@@ -744,27 +811,57 @@ func serveSeats(conn *bus.Conn, modules []string, current func() []registration,
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
have[v.Subject] = true
|
have[v.Subject] = true
|
||||||
|
// The seat's verb `approvals` is the gate's own, served wherever a marked verb is: the runner answers it from its
|
||||||
|
// record of the calls its gate holds, by caller, and no bundle names it (lead answers A-265, A-266, A-271).
|
||||||
|
if v.Verb == seatdef.ApprovalsVerb && approvals != nil {
|
||||||
|
seat := v.Seat
|
||||||
|
stop, err := conn.HandleSubjectCalled(v.Subject, func(caller, _ string, _ json.RawMessage) (any, error) {
|
||||||
|
return approvals(caller)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
logf("[mesh-tools] cannot serve %s's approvals on %s: %v", seat, v.Subject, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stops = append(stops, stop)
|
||||||
|
logf("[mesh-tools] serving %s's approvals on %s, the gate's own verb", seat, v.Subject)
|
||||||
|
continue
|
||||||
|
}
|
||||||
t, ok := impl[v.Seat][v.Verb]
|
t, ok := impl[v.Seat][v.Verb]
|
||||||
if !ok {
|
if !ok {
|
||||||
logf("[mesh-tools] %s claims %s and implements no %s, which that seat promises; not served", module, v.Seat, v.Verb)
|
logf("[mesh-tools] %s claims %s and implements no %s, which that seat promises; not served", module, v.Seat, v.Verb)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Its callers checked, then through the approval gate, before the bundle (design 47 G §610, A-179; design 46
|
// Through the approval gate, for any caller, before the bundle (design 47 H §752; design 46
|
||||||
// 7-approval-mark §20).
|
// 7-approval-mark §20).
|
||||||
module, v := module, v
|
module, v := module, v
|
||||||
stop, err := conn.HandleSubjectCalled(v.Subject, func(caller string, body json.RawMessage) (any, error) {
|
handle := func(caller, ask string, body json.RawMessage) (any, error) {
|
||||||
if err := admitted(v.Seat, v.Verb, caller); err != nil {
|
answer, err := gated(approval.Call{Address: v.Seat + "." + v.Verb, Module: module, Seat: v.Seat, Name: v.Verb,
|
||||||
return nil, err
|
Fingerprint: fingerprintOf(module), Caller: caller, Args: argsOf(body), Description: t.Description}, t.Within(within("seat:"+v.Seat+"."+v.Verb)), caller, ask)
|
||||||
|
if err != nil || !chunked("seat:"+v.Seat+"."+v.Verb) {
|
||||||
|
return answer, err
|
||||||
}
|
}
|
||||||
return gated(approval.Call{Address: v.Seat + "." + v.Verb, Module: module, Seat: v.Seat, Name: v.Verb,
|
// A verb marked chunks: the bundle answers the whole file, the runner sends it in chunks (design 47 G A-257).
|
||||||
Fingerprint: fingerprintOf(module), Caller: caller, Args: argsOf(body), Description: t.Description}, t, caller)
|
return conn.AnswerChunked(v.Seat, v.Verb, body, answer)
|
||||||
})
|
}
|
||||||
|
stop, err := conn.HandleSubjectCalled(v.Subject, handle)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logf("[mesh-tools] cannot serve %s's %s on %s: %v", v.Seat, v.Verb, v.Subject, err)
|
logf("[mesh-tools] cannot serve %s's %s on %s: %v", v.Seat, v.Verb, v.Subject, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
stops = append(stops, stop)
|
stops = append(stops, stop)
|
||||||
logf("[mesh-tools] serving %s's %s on %s, admitted where %s holds the seat", v.Seat, v.Verb, v.Subject, module)
|
logf("[mesh-tools] serving %s's %s on %s, where %s holds the seat", v.Seat, v.Verb, v.Subject, module)
|
||||||
|
// A verb of a node-scoped seat is also answered on the subject that names no machine, by any one holder, in
|
||||||
|
// one queue group per seat and verb (lead answer A-393).
|
||||||
|
if open, ok := anyHolderSubject(v, m.Node); ok && !have[open] {
|
||||||
|
have[open] = true
|
||||||
|
openStop, err := conn.HandleSubjectCalledQueue(open, "seat."+v.Seat+"."+v.Verb, handle)
|
||||||
|
if err != nil {
|
||||||
|
logf("[mesh-tools] cannot serve %s's %s on %s: %v", v.Seat, v.Verb, open, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stops = append(stops, openStop)
|
||||||
|
logf("[mesh-tools] serving %s's %s on %s, in a queue group, for a call that names no machine", v.Seat, v.Verb, open)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -781,6 +878,15 @@ func serveSeats(conn *bus.Conn, modules []string, current func() []registration,
|
|||||||
}, serve
|
}, serve
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// anyHolderSubject is a node-scoped seat verb's subject without its machine, the one asked with no machine named; false
|
||||||
|
// where the verb's subject does not end in the machine (a seat held once).
|
||||||
|
func anyHolderSubject(v bus.SeatVerb, node string) (string, bool) {
|
||||||
|
if node == "" || !strings.HasSuffix(v.Subject, "."+v.Verb+"."+node) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return strings.TrimSuffix(v.Subject, "."+node), true
|
||||||
|
}
|
||||||
|
|
||||||
// consumers holds, per module the runtime serves, the one durable consumer its events arrive on and
|
// consumers holds, per module the runtime serves, the one durable consumer its events arrive on and
|
||||||
// the children its events are handed to (novox/hq ADR 0198).
|
// the children its events are handed to (novox/hq ADR 0198).
|
||||||
type consumers struct {
|
type consumers struct {
|
||||||
@@ -800,8 +906,16 @@ type consumers struct {
|
|||||||
sessions sessionTable
|
sessions sessionTable
|
||||||
// gate is the approval gate every call is served through (gate.go); nil serves every call as before.
|
// gate is the approval gate every call is served through (gate.go); nil serves every call as before.
|
||||||
gate Gate
|
gate Gate
|
||||||
// definitions are the seat definitions a seat verb's callers are read from (gate.go); nil admits every caller.
|
// definitions are the seat definitions a seat verb's `chunks` and `timeout` are read from (gate.go); nil reads none.
|
||||||
definitions func() map[string]seatdef.Definition
|
definitions func() map[string]seatdef.Definition
|
||||||
|
// reread reads the seat list again (gate.go, chunkedAsked); nil reads nothing.
|
||||||
|
reread func() error
|
||||||
|
rereadMu sync.Mutex
|
||||||
|
rereading *rereadFlight
|
||||||
|
// hearers hear every event of a module's consumer in process, after the module's bundles took it (WithHearer).
|
||||||
|
hearers map[string][]func(bus.Envelope) error
|
||||||
|
// askPlain and askChunked are how a bundle's ask is sent (the bus connection's AskAs and AskAsChunked); a test gives its own.
|
||||||
|
askPlain, askChunked func(module, key string, body any, within time.Duration) (bus.Answered, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type moduleEvents struct {
|
type moduleEvents struct {
|
||||||
@@ -902,6 +1016,21 @@ func (b *moduleBus) Publish(params json.RawMessage) error {
|
|||||||
return b.all.conn.PublishAs(b.module, env)
|
return b.all.conn.PublishAs(b.module, env)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PublishAcked is Publish that answers the sequence the bus acknowledged the event at (`mesh/publish` with `ack`, design 47 G §559).
|
||||||
|
func (b *moduleBus) PublishAcked(params json.RawMessage) (uint64, error) {
|
||||||
|
var env bus.Envelope
|
||||||
|
if err := json.Unmarshal(params, &env); err != nil {
|
||||||
|
return 0, fmt.Errorf("not an event envelope: %w", err)
|
||||||
|
}
|
||||||
|
return b.all.conn.PublishAsAcked(b.module, env)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SubscribeNew hands the bundle one event's messages published from now on, on an ordered consumer of its own (`mesh/subscribe`
|
||||||
|
// with `deliver: new`, design 47 G §559); the consumer ends with the bundle's channel.
|
||||||
|
func (b *moduleBus) SubscribeNew(pattern string, deliver func(json.RawMessage) error) (func(), error) {
|
||||||
|
return b.all.conn.SubscribeNew(pattern, deliver)
|
||||||
|
}
|
||||||
|
|
||||||
// Ask calls a tool as the module: `{key, body}`, answered with the tool's result (ADR 0198).
|
// Ask calls a tool as the module: `{key, body}`, answered with the tool's result (ADR 0198).
|
||||||
func (b *moduleBus) Ask(params json.RawMessage) (json.RawMessage, error) {
|
func (b *moduleBus) Ask(params json.RawMessage) (json.RawMessage, error) {
|
||||||
var asked struct {
|
var asked struct {
|
||||||
@@ -915,11 +1044,21 @@ func (b *moduleBus) Ask(params json.RawMessage) (json.RawMessage, error) {
|
|||||||
if len(asked.Body) == 0 {
|
if len(asked.Body) == 0 {
|
||||||
body = map[string]any{}
|
body = map[string]any{}
|
||||||
}
|
}
|
||||||
ask := b.all.conn.AskAs
|
ask := b.all.askPlain
|
||||||
if b.all.chunked(asked.Key) {
|
if ask == nil {
|
||||||
ask = b.all.conn.AskAsChunked // the runner receives the chunks of the answer; the bundle receives none (design 47 G A-249)
|
ask = b.all.conn.AskAsWithin
|
||||||
}
|
}
|
||||||
answered, err := ask(b.module, asked.Key, body)
|
chunks, err := b.all.chunkedAsked(asked.Key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if chunks {
|
||||||
|
if ask = b.all.askChunked; ask == nil {
|
||||||
|
ask = b.all.conn.AskAsChunkedWithin
|
||||||
|
}
|
||||||
|
// the runner receives the chunks of the answer; the bundle receives none (design 47 G A-249)
|
||||||
|
}
|
||||||
|
answered, err := ask(b.module, asked.Key, body, b.all.withinOf(asked.Key))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -979,7 +1118,7 @@ func (b *moduleBus) Subscribe(deliver func(json.RawMessage) error, beat func(jso
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
m.stop = stop
|
m.stop = stop
|
||||||
c.logf("[mesh-tools] %s's events arrive on its consumer %s", module, bus.ConsumerOf(c.conn.Node(), module))
|
c.logf("[mesh-tools] %s's events arrive on its consumer %s", module, bus.ToolsConsumerOf(c.conn.Node(), module))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1017,6 +1156,7 @@ func (c *consumers) handOut(module string, m *moduleEvents, env bus.Envelope) er
|
|||||||
return errModuleReloading
|
return errModuleReloading
|
||||||
}
|
}
|
||||||
targets := append([]*deliverSlot(nil), m.delivers...)
|
targets := append([]*deliverSlot(nil), m.delivers...)
|
||||||
|
hearers := append([]func(bus.Envelope) error(nil), c.hearers[module]...)
|
||||||
c.mu.Unlock()
|
c.mu.Unlock()
|
||||||
for _, d := range targets {
|
for _, d := range targets {
|
||||||
if err := d.get()(raw); err != nil {
|
if err := d.get()(raw); err != nil {
|
||||||
@@ -1025,6 +1165,14 @@ func (c *consumers) handOut(module string, m *moduleEvents, env bus.Envelope) er
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// And the runtime's own hearers of the module's events, on this same consumer (WithHearer).
|
||||||
|
for _, hear := range hearers {
|
||||||
|
if err := hear(env); err != nil {
|
||||||
|
c.logf("[mesh-tools] the tool runner did not take %s%s of %s's consumer: %v; offered again in %s", env.Key,
|
||||||
|
eventRef(env), module, err, bus.NakDelay)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1058,8 +1206,9 @@ type stateAsked struct {
|
|||||||
// TTLSeconds gives a created or put key its own time to live (issue 1952): create makes it only when it has no
|
// TTLSeconds gives a created or put key its own time to live (issue 1952): create makes it only when it has no
|
||||||
// value, put renews it whole. Zero is none.
|
// value, put renews it whole. Zero is none.
|
||||||
TTLSeconds int `json:"ttl_seconds"`
|
TTLSeconds int `json:"ttl_seconds"`
|
||||||
// After and MaxBytes are a `page`'s start key and its size in keys and values (zero is a megabyte).
|
// Cursor and MaxBytes are a `page`'s opaque cursor, the next of the page before (empty: from the start), and its size in
|
||||||
After string `json:"after"`
|
// keys and values (zero, or above 768 KB, is 768 KB; design 47 H2 §779).
|
||||||
|
Cursor string `json:"cursor"`
|
||||||
MaxBytes int `json:"max_bytes"`
|
MaxBytes int `json:"max_bytes"`
|
||||||
// BudgetMS is the time a `page` may spend reading, in milliseconds (zero is the runtime's own, well under 30 s).
|
// BudgetMS is the time a `page` may spend reading, in milliseconds (zero is the runtime's own, well under 30 s).
|
||||||
BudgetMS int `json:"budget_ms"`
|
BudgetMS int `json:"budget_ms"`
|
||||||
@@ -1091,11 +1240,8 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
|
|||||||
}
|
}
|
||||||
answer = entry
|
answer = entry
|
||||||
case "page":
|
case "page":
|
||||||
// The values after a key in key order, one request for many (a first view's page of a slow state).
|
// One page of the state in the order the bus wrote it, after the cursor, one request for many (design 47 H2 §779).
|
||||||
if asked.MaxBytes <= 0 {
|
page, err := conn.StatePage(b.module, asked.State, asked.Cursor, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond)
|
||||||
asked.MaxBytes = 1 << 20
|
|
||||||
}
|
|
||||||
page, err := conn.StatePage(b.module, asked.State, asked.After, asked.MaxBytes, time.Duration(asked.BudgetMS)*time.Millisecond)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1118,7 +1264,12 @@ func (b *moduleBus) State(verb string, params json.RawMessage) (json.RawMessage,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
answer = map[string]any{"revision": revision}
|
// With the bucket's fill, so a bundle's prune reads it from the put (design 47 H2 DMC-14, H-A-386).
|
||||||
|
fill, err := conn.StateFill(b.module, asked.State)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s was put at revision %d, but its state's fill is not read: %w", asked.Key, revision, err)
|
||||||
|
}
|
||||||
|
answer = map[string]any{"revision": revision, "fill": fill}
|
||||||
case "delete":
|
case "delete":
|
||||||
if err := conn.StateDelete(b.module, asked.State, asked.Key); err != nil {
|
if err := conn.StateDelete(b.module, asked.State, asked.Key); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -1290,8 +1441,10 @@ type seatAsked struct {
|
|||||||
Body json.RawMessage `json:"body"`
|
Body json.RawMessage `json:"body"`
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Worker string `json:"worker"`
|
Worker string `json:"worker"`
|
||||||
Bucket string `json:"bucket"`
|
// Seat is the seat whose work queue a waiting read reads (design 47 H2 H-A-410).
|
||||||
Key string `json:"key"`
|
Seat string `json:"seat"`
|
||||||
|
Bucket string `json:"bucket"`
|
||||||
|
Key string `json:"key"`
|
||||||
// WaitMS is how long a pull waits for a message (none when 0); Fate what a settle gives one (issue 1887 A11).
|
// WaitMS is how long a pull waits for a message (none when 0); Fate what a settle gives one (issue 1887 A11).
|
||||||
WaitMS int `json:"wait_ms"`
|
WaitMS int `json:"wait_ms"`
|
||||||
// DelayMS is how long a settle with the fate nak-after waits before the bus gives the message again.
|
// DelayMS is how long a settle with the fate nak-after waits before the bus gives the message again.
|
||||||
@@ -1330,6 +1483,14 @@ func (b *moduleBus) Seat(verb string, params json.RawMessage, handOn func(string
|
|||||||
return json.RawMessage("null"), err
|
return json.RawMessage("null"), err
|
||||||
}
|
}
|
||||||
return json.Marshal(entry)
|
return json.Marshal(entry)
|
||||||
|
case "waiting":
|
||||||
|
// mesh/queue.waiting: the asks that wait on the holder's own queue of a seat, read without consuming them (design 47
|
||||||
|
// H2 H-A-410, ADR 0596).
|
||||||
|
waiting, err := conn.QueueWaitingOf(b.module, asked.Seat)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return json.Marshal(waiting)
|
||||||
case "pull":
|
case "pull":
|
||||||
// One message from a worker the membership lists, never a prefetch: a build module pulls an ask only when it
|
// One message from a worker the membership lists, never a prefetch: a build module pulls an ask only when it
|
||||||
// has room, from its workers in their order (novox/hq ADR 0525 §4; issue 1887 A11).
|
// has room, from its workers in their order (novox/hq ADR 0525 §4; issue 1887 A11).
|
||||||
@@ -1403,11 +1564,13 @@ func (b *moduleBus) bind(key string, stop func()) {
|
|||||||
// BundleEnv is what one module's bundle is started with: the runtime's environment without its own words,
|
// BundleEnv is what one module's bundle is started with: the runtime's environment without its own words,
|
||||||
// the module's composed words over it, and the module's and machine's names. **No bus word reaches a
|
// the module's composed words over it, and the module's and machine's names. **No bus word reaches a
|
||||||
// bundle** (security review of 2026-10-08): the credential and the bus's address are the runtime's, and a
|
// bundle** (security review of 2026-10-08): the credential and the bus's address are the runtime's, and a
|
||||||
// bundle reaches the bus only through the runtime.
|
// bundle reaches the bus only through the runtime. **The runtime's own fingerprint reaches none either**: a bundle reads
|
||||||
|
// only the `MESH_FINGERPRINT` its module's composed words hold, the build the node-engine applied for that module, and with
|
||||||
|
// none it has none (design 47 G §519, §618).
|
||||||
func BundleEnv(base []string, given map[string]string, module, node string) []string {
|
func BundleEnv(base []string, given map[string]string, module, node string) []string {
|
||||||
words := map[string]string{}
|
words := map[string]string{}
|
||||||
for _, kv := range base {
|
for _, kv := range base {
|
||||||
if k, v, ok := strings.Cut(kv, "="); ok && !runtimeOnly[k] {
|
if k, v, ok := strings.Cut(kv, "="); ok && !runtimeOnly[k] && k != fingerprintEnv {
|
||||||
words[k] = v
|
words[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,10 +4,12 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/approval"
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/launch"
|
"github.com/novox/mesh-tools/node-tools/internal/launch"
|
||||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
@@ -24,9 +26,12 @@ func connect(t *testing.T, module, node string) *bus.Conn {
|
|||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// call waits the test's own bound, meshtest.Bound(t), where 2 s were what a loaded build node overran (1754/AC1; the lead's
|
||||||
|
// answer on issue 1754 of 2026-11-23 20:00): a call that is never answered fails there, and Until, a deadline of the same
|
||||||
|
// bound, does not try it again past it.
|
||||||
func call(t *testing.T, asker *bus.Conn, key string, args any) (string, error) {
|
func call(t *testing.T, asker *bus.Conn, key string, args any) (string, error) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
got, err := asker.Ask(key, args, "")
|
got, err := asker.AskWithin(key, args, "", mt.Bound(t))
|
||||||
return string(got.Result), err
|
return string(got.Result), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,7 +118,7 @@ func TestTheNodesRuntimeServesFiveModulesAndFollowsAReissuedMembership(t *testin
|
|||||||
if subject != "mesh.mod.alpha.event.happened" {
|
if subject != "mesh.mod.alpha.event.happened" {
|
||||||
t.Errorf("the event landed on %s", subject)
|
t.Errorf("the event landed on %s", subject)
|
||||||
}
|
}
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Error("the event never landed")
|
t.Error("the event never landed")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,10 +197,50 @@ func TestEachBundleIsGivenItsOwnEnvironment(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// An entrypoint that is not executable is refused by name, and the others serve (ADR 0193).
|
// unservingGate is an approval gate whose marks of each module name the tools given, so a bundle not registering them is
|
||||||
|
// refused at the load (design 46 7-approval-mark §4).
|
||||||
|
type unservingGate map[string][]string
|
||||||
|
|
||||||
|
func (g unservingGate) Unserved(module, _ string, registered []string) []string {
|
||||||
|
var missing []string
|
||||||
|
for _, tool := range g[module] {
|
||||||
|
if !slices.Contains(registered, tool) {
|
||||||
|
missing = append(missing, tool)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return missing
|
||||||
|
}
|
||||||
|
func (unservingGate) Run(_ approval.Call, run func() (any, error)) (any, error) { return run() }
|
||||||
|
func (unservingGate) Approvals(string) (approval.Approvals, error) { return approval.Approvals{}, nil }
|
||||||
|
|
||||||
|
// An entrypoint that is not executable is refused by name, and the others serve (ADR 0193). A bundle whose marks name a
|
||||||
|
// tool it does not register is refused at the load, serving no tool of its module, and one that registers it serves
|
||||||
|
// (design 46 7-approval-mark §4).
|
||||||
func TestAnEntrypointThatIsNotExecutableIsRefused(t *testing.T) {
|
func TestAnEntrypointThatIsNotExecutableIsRefused(t *testing.T) {
|
||||||
mt.NeedBundles(t)
|
|
||||||
mesh := mt.New(t)
|
mesh := mt.New(t)
|
||||||
|
{
|
||||||
|
mesh.Issue(t, mt.MembershipOf("marked", "anchor", true, nil))
|
||||||
|
mesh.Issue(t, mt.MembershipOf("served", "anchor", true, nil))
|
||||||
|
nodeTools := connect(t, "node-tools", "anchor")
|
||||||
|
asker := connect(t, "console", "workstation")
|
||||||
|
logs := &mt.Logs{}
|
||||||
|
stop, err := Run(nodeTools, []Served{{"marked", []string{mt.Fixture("caller-echo.py")}}, {"served", []string{mt.Fixture("caller-echo.py")}}},
|
||||||
|
nil, logs.Logf, WithGate(unservingGate{"marked": {"wipe"}, "served": {"who"}}))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !logs.Has("marked is not loaded: its marks name wipe, which none of its bundles registers (design 46 7-approval-mark §4)") {
|
||||||
|
t.Errorf("a bundle not serving its marked tool was not refused at the load:\n%s", logs.All())
|
||||||
|
}
|
||||||
|
if _, err := call(t, asker, "served.who@anchor", map[string]any{}); err != nil {
|
||||||
|
t.Errorf("a bundle serving its marked tool: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := asker.Ask("marked.who@anchor", map[string]any{}, ""); !errors.Is(err, bus.ErrNoResponders) {
|
||||||
|
t.Errorf("a refused bundle's tool answered: %v", err)
|
||||||
|
}
|
||||||
|
stop()
|
||||||
|
}
|
||||||
|
mt.NeedBundles(t)
|
||||||
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", false, nil))
|
mesh.Issue(t, mt.MembershipOf("alpha", "anchor", false, nil))
|
||||||
mesh.Issue(t, mt.MembershipOf("plain", "anchor", false, nil))
|
mesh.Issue(t, mt.MembershipOf("plain", "anchor", false, nil))
|
||||||
nodeTools := connect(t, "node-tools", "anchor")
|
nodeTools := connect(t, "node-tools", "anchor")
|
||||||
@@ -270,3 +315,46 @@ func TestAnUntakenEventSaysWhoFailed(t *testing.T) {
|
|||||||
t.Errorf("the event is not named by its id: %q", got)
|
t.Errorf("the event is not named by its id: %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A node-scoped seat's verb asked with no machine is answered by a holder, by the tool form the SDK asks
|
||||||
|
// (lead answer A-393).
|
||||||
|
func TestANodeScopedSeatVerbIsAlsoAnsweredWithNoMachine(t *testing.T) {
|
||||||
|
mesh := mt.New(t)
|
||||||
|
mesh.Issue(t, mt.MembershipOf("theta", "anchor", false, map[string][]string{"node-shelf": {"list"}}))
|
||||||
|
nodeTools := connect(t, "node-tools", "anchor")
|
||||||
|
asker := connect(t, "console", "workstation")
|
||||||
|
regs := func() []registration {
|
||||||
|
return []registration{{module: "node-shelf", owner: "theta", tools: []launch.Tool{{Name: "list",
|
||||||
|
Run: func(string, json.RawMessage) (json.RawMessage, error) { return json.RawMessage(`{"shelf":["x"]}`), nil }}}}}
|
||||||
|
}
|
||||||
|
gated := func(_ approval.Call, tool launch.Tool, caller, _ string) (any, error) {
|
||||||
|
return tool.Run(caller, nil)
|
||||||
|
}
|
||||||
|
nodeTools.Follow("theta")
|
||||||
|
stop, _ := serveSeats(nodeTools, []string{"theta"}, regs, gated, func(string) bool { return false }, func(string) time.Duration { return 0 }, nil, func(string) string { return "" }, (&mt.Logs{}).Logf)
|
||||||
|
defer stop()
|
||||||
|
for _, key := range []string{"seat:node-shelf.list@anchor", "seat:node-shelf.list"} {
|
||||||
|
t.Run(key, func(t *testing.T) {
|
||||||
|
mt.Until(t, func() error {
|
||||||
|
got, err := call(t, asker, key, map[string]any{})
|
||||||
|
if err == nil {
|
||||||
|
same(t, got, `{"shelf":["x"]}`)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAnyHolderSubject(t *testing.T) {
|
||||||
|
for _, c := range []struct{ subject, node, want string }{
|
||||||
|
{"mesh.seat.node-build-go.tool.steps.shanks", "shanks", "mesh.seat.node-build-go.tool.steps"},
|
||||||
|
{"mesh.seat.mesh-delivery.tool.show", "shanks", ""},
|
||||||
|
{"mesh.seat.node-build-go.tool.steps.shanks", "", ""},
|
||||||
|
} {
|
||||||
|
got, ok := anyHolderSubject(bus.SeatVerb{Seat: "s", Verb: "steps", Subject: c.subject}, c.node)
|
||||||
|
if got != c.want || ok != (c.want != "") {
|
||||||
|
t.Errorf("%s on %q: %q %v", c.subject, c.node, got, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package runtime
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -92,7 +93,7 @@ func TestABundlesSeatTrafficGoesThroughItsModulesBus(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
deadline := time.Now().Add(10 * time.Second)
|
deadline := time.Now().Add(mt.Bound(t))
|
||||||
for {
|
for {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
n := len(taken)
|
n := len(taken)
|
||||||
@@ -219,4 +220,64 @@ func TestABundlePullsAndSettlesThroughItsModulesBus(t *testing.T) {
|
|||||||
if none, err := building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker"}`), nil); err != nil || string(none) != "null" {
|
if none, err := building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker"}`), nil); err != nil || string(none) != "null" {
|
||||||
t.Fatalf("an empty worker answered %s, %v", none, err)
|
t.Fatalf("an empty worker answered %s, %v", none, err)
|
||||||
}
|
}
|
||||||
|
// Design 47 H2 H-A-410: the holder reads what waits on its own queue of the seat without consuming it (mesh/queue.waiting),
|
||||||
|
// each ask with its id, the module that put it and its age; another module is refused, as is a seat it holds no queue of.
|
||||||
|
waiting := func(want string, spelled ...string) {
|
||||||
|
t.Helper()
|
||||||
|
seat := "node-build-go"
|
||||||
|
if len(spelled) > 0 {
|
||||||
|
seat = spelled[0]
|
||||||
|
}
|
||||||
|
raw, err := building.Seat("waiting", json.RawMessage(`{"seat":"`+seat+`"}`), nil)
|
||||||
|
var w bus.QueueWaiting
|
||||||
|
if err != nil || json.Unmarshal(raw, &w) != nil || w.Capped {
|
||||||
|
t.Fatalf("waiting = %s, %v", raw, err)
|
||||||
|
}
|
||||||
|
var got []string
|
||||||
|
for _, a := range w.Asks {
|
||||||
|
got = append(got, fmt.Sprintf("%s:%s:%v", a.Module, a.ID, a.AgeSeconds < 60)+map[bool]string{true: ":again"}[a.Again])
|
||||||
|
}
|
||||||
|
if strings.Join(got, ",") != want {
|
||||||
|
t.Errorf("waiting is %s, want %s", raw, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
waiting("")
|
||||||
|
for _, id := range []string{"ask2", "ask3"} {
|
||||||
|
m := nats.NewMsg("mesh.seat.node-build-go.accept.delivery")
|
||||||
|
m.Header.Set("x-source", "mesh-delivery-pipeline")
|
||||||
|
m.Header.Set("x-event-id", "mesh-delivery-pipeline."+id)
|
||||||
|
m.Data = []byte(`{"id":"` + id + `"}`)
|
||||||
|
if _, err := js.PublishMsg(m); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
waiting("mesh-delivery-pipeline:ask2:true,mesh-delivery-pipeline:ask3:true")
|
||||||
|
waiting("mesh-delivery-pipeline:ask2:true,mesh-delivery-pipeline:ask3:true") // read again: nothing was consumed
|
||||||
|
if _, err := elsewhere.Seat("waiting", json.RawMessage(`{"seat":"node-build-go"}`), nil); err == nil {
|
||||||
|
t.Error("another module read the Go build seat's queue")
|
||||||
|
}
|
||||||
|
if _, err := building.Seat("waiting", json.RawMessage(`{"seat":"operator-channel"}`), nil); err == nil {
|
||||||
|
t.Error("the holder read the queue of a seat it holds no worker on")
|
||||||
|
}
|
||||||
|
raw, err = building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":1000}`), nil)
|
||||||
|
if err != nil || json.Unmarshal(raw, &p) != nil {
|
||||||
|
t.Fatal(raw, err)
|
||||||
|
}
|
||||||
|
// a pulled ask, held or handed back, is listed again (the holder tells the two apart by its state taken); one acknowledged
|
||||||
|
// is gone
|
||||||
|
waiting("mesh-delivery-pipeline:ask2:true:again,mesh-delivery-pipeline:ask3:true")
|
||||||
|
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"nak-after","delay_ms":60000}`), nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waiting("mesh-delivery-pipeline:ask2:true:again,mesh-delivery-pipeline:ask3:true")
|
||||||
|
raw, err = building.Seat("pull", json.RawMessage(`{"worker":"SEAT_NODE_BUILD_GO_DELIVERY_worker","wait_ms":1000}`), nil)
|
||||||
|
if err != nil || json.Unmarshal(raw, &p) != nil {
|
||||||
|
t.Fatal(raw, err)
|
||||||
|
}
|
||||||
|
if _, err := building.Seat("settle", json.RawMessage(`{"id":"`+p.ID+`","fate":"ack"}`), nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
waiting("mesh-delivery-pipeline:ask2:true:again")
|
||||||
|
// the seat's stream is the one mesh-sdk's buscompose names, '.' as '_' too (H-A-410, P9)
|
||||||
|
waiting("mesh-delivery-pipeline:ask2:true:again", "node-build.go")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,12 +37,26 @@ func (f *fakeObjects) ObjectsPutStream(ctx context.Context, _ string, r buscalls
|
|||||||
return buscalls.ObjectInfo{Name: r.Name, Size: uint64(len(data)), Description: description}, nil
|
return buscalls.ObjectInfo{Name: r.Name, Size: uint64(len(data)), Description: description}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeObjects) ObjectsOpen(context.Context, string, buscalls.ObjectsNameRequest) (buscalls.ObjectInfo, io.ReadCloser, bool, error) {
|
// ctxReader reads as the bus's object reader does: on the context it was opened on, failing once that is cancelled.
|
||||||
return buscalls.ObjectInfo{Name: "o", Size: uint64(len(f.read))}, io.NopCloser(bytes.NewReader(f.read)), true, nil
|
type ctxReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
r io.Reader
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeObjects) SentOpen(context.Context, buscalls.ObjectsSentGetRequest) (buscalls.ObjectInfo, io.ReadCloser, error) {
|
func (c ctxReader) Read(p []byte) (int, error) {
|
||||||
return buscalls.ObjectInfo{Size: uint64(len(f.read))}, io.NopCloser(bytes.NewReader(f.read)), nil
|
if err := c.ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return c.r.Read(p)
|
||||||
|
}
|
||||||
|
func (c ctxReader) Close() error { return nil }
|
||||||
|
|
||||||
|
func (f *fakeObjects) ObjectsOpen(ctx context.Context, _ string, _ buscalls.ObjectsNameRequest) (buscalls.ObjectInfo, io.ReadCloser, bool, error) {
|
||||||
|
return buscalls.ObjectInfo{Name: "o", Size: uint64(len(f.read))}, ctxReader{ctx, bytes.NewReader(f.read)}, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeObjects) SentOpen(ctx context.Context, _ buscalls.ObjectsSentGetRequest) (buscalls.ObjectInfo, io.ReadCloser, error) {
|
||||||
|
return buscalls.ObjectInfo{Size: uint64(len(f.read))}, ctxReader{ctx, bytes.NewReader(f.read)}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func aSession(t *testing.T, f *fakeObjects) *moduleBus {
|
func aSession(t *testing.T, f *fakeObjects) *moduleBus {
|
||||||
@@ -64,66 +78,6 @@ func asked(t *testing.T, b *moduleBus, method string, req any, into any) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Design 47 G §518, A-21, A-25: a put session writes each chunk as it is taken, carries the description of its first chunk,
|
|
||||||
// and answers the put's own info for the last; a chunk out of order fails the put naming both sequences and leaves none.
|
|
||||||
func TestAPutSessionSealsOnTheLastChunkAndDropsOnADisorder(t *testing.T) {
|
|
||||||
f := &fakeObjects{put: map[string][]byte{}}
|
|
||||||
b := aSession(t, f)
|
|
||||||
whole := bytes.Repeat([]byte("x"), 2*buscalls.ChunkBytes+5)
|
|
||||||
var taken buscalls.ObjectsChunkTaken
|
|
||||||
for seq, at := uint32(1), 0; ; seq++ {
|
|
||||||
end := min(at+buscalls.ChunkBytes, len(whole))
|
|
||||||
req := buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "a", Call: "c1", Seq: seq, Last: end == len(whole), Data: whole[at:end]}
|
|
||||||
if seq == 1 {
|
|
||||||
req.Description = "what it is"
|
|
||||||
}
|
|
||||||
if req.Last {
|
|
||||||
var info buscalls.ObjectInfo
|
|
||||||
asked(t, b, buscalls.ObjectsPutChunk, req, &info)
|
|
||||||
if info.Size != uint64(len(whole)) || info.Description != "what it is" {
|
|
||||||
t.Fatalf("the put answered %+v", info)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
asked(t, b, buscalls.ObjectsPutChunk, req, &taken)
|
|
||||||
if taken.Seq != seq || taken.Error != "" {
|
|
||||||
t.Fatalf("chunk %d was answered %+v", seq, taken)
|
|
||||||
}
|
|
||||||
at = end
|
|
||||||
}
|
|
||||||
if !bytes.Equal(f.put["a"], whole) {
|
|
||||||
t.Fatalf("the store holds %d bytes, want %d", len(f.put["a"]), len(whole))
|
|
||||||
}
|
|
||||||
|
|
||||||
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "b", Call: "c2", Seq: 1, Data: []byte("one")}, &taken)
|
|
||||||
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "b", Call: "c2", Seq: 3, Data: []byte("three")}, &taken)
|
|
||||||
if !strings.Contains(taken.Error, "chunk 3") || !strings.Contains(taken.Error, "chunk 2") {
|
|
||||||
t.Fatalf("a disorder was answered %+v", taken)
|
|
||||||
}
|
|
||||||
if _, ok := f.put["b"]; ok || len(f.deleted) != 1 || f.deleted[0] != "b" {
|
|
||||||
t.Fatalf("a dropped put left %v, deleted %v", f.put, f.deleted)
|
|
||||||
}
|
|
||||||
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "b", Call: "c2", Seq: 2, Data: []byte("two")}, &taken)
|
|
||||||
if taken.Error == "" {
|
|
||||||
t.Fatal("a chunk of a dropped put was taken")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// §518 "The bound": a put not sealed within the bound is dropped, its object deleted.
|
|
||||||
func TestAPutNotSealedWithinTheBoundIsDropped(t *testing.T) {
|
|
||||||
was := SessionBound
|
|
||||||
SessionBound = time.Millisecond
|
|
||||||
t.Cleanup(func() { SessionBound = was })
|
|
||||||
f := &fakeObjects{put: map[string][]byte{}, ctxEnded: make(chan struct{})}
|
|
||||||
b := aSession(t, f)
|
|
||||||
var taken buscalls.ObjectsChunkTaken
|
|
||||||
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "a", Call: "c", Seq: 1, Data: []byte("x")}, &taken)
|
|
||||||
<-f.ctxEnded
|
|
||||||
if len(f.deleted) != 1 {
|
|
||||||
t.Fatalf("the unsealed object was left: %v", f.deleted)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// §490, §518, §620: a value over one chunk is got as a session (the chunked answer, then each chunk by its call and sequence,
|
// §490, §518, §620: a value over one chunk is got as a session (the chunked answer, then each chunk by its call and sequence,
|
||||||
// the whole checked against the digest); a sent object over one chunk the same, with `chunked` true.
|
// the whole checked against the digest); a sent object over one chunk the same, with `chunked` true.
|
||||||
func TestAGetOverOneChunkRunsAsASession(t *testing.T) {
|
func TestAGetOverOneChunkRunsAsASession(t *testing.T) {
|
||||||
@@ -192,4 +146,62 @@ func TestAGetOverOneChunkRunsAsASession(t *testing.T) {
|
|||||||
if string(small.Data) != "small" {
|
if string(small.Data) != "small" {
|
||||||
t.Fatalf("a small value was answered %+v", small)
|
t.Fatalf("a small value was answered %+v", small)
|
||||||
}
|
}
|
||||||
|
// Design 47 G §518, A-21, A-25: a put session writes each chunk as it is taken, carries the description of its first chunk,
|
||||||
|
// and answers the put's own info for the last; a chunk out of order fails the put naming both sequences and leaves none.
|
||||||
|
t.Run("APutSessionSealsOnTheLastChunkAndDropsOnADisorder", func(t *testing.T) {
|
||||||
|
f := &fakeObjects{put: map[string][]byte{}}
|
||||||
|
b := aSession(t, f)
|
||||||
|
whole := bytes.Repeat([]byte("x"), 2*buscalls.ChunkBytes+5)
|
||||||
|
var taken buscalls.ObjectsChunkTaken
|
||||||
|
for seq, at := uint32(1), 0; ; seq++ {
|
||||||
|
end := min(at+buscalls.ChunkBytes, len(whole))
|
||||||
|
req := buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "a", Call: "c1", Seq: seq, Last: end == len(whole), Data: whole[at:end]}
|
||||||
|
if seq == 1 {
|
||||||
|
req.Description = "what it is"
|
||||||
|
}
|
||||||
|
if req.Last {
|
||||||
|
var info buscalls.ObjectInfo
|
||||||
|
asked(t, b, buscalls.ObjectsPutChunk, req, &info)
|
||||||
|
if info.Size != uint64(len(whole)) || info.Description != "what it is" {
|
||||||
|
t.Fatalf("the put answered %+v", info)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
asked(t, b, buscalls.ObjectsPutChunk, req, &taken)
|
||||||
|
if taken.Seq != seq || taken.Error != "" {
|
||||||
|
t.Fatalf("chunk %d was answered %+v", seq, taken)
|
||||||
|
}
|
||||||
|
at = end
|
||||||
|
}
|
||||||
|
if !bytes.Equal(f.put["a"], whole) {
|
||||||
|
t.Fatalf("the store holds %d bytes, want %d", len(f.put["a"]), len(whole))
|
||||||
|
}
|
||||||
|
|
||||||
|
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "b", Call: "c2", Seq: 1, Data: []byte("one")}, &taken)
|
||||||
|
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "b", Call: "c2", Seq: 3, Data: []byte("three")}, &taken)
|
||||||
|
if !strings.Contains(taken.Error, "chunk 3") || !strings.Contains(taken.Error, "chunk 2") {
|
||||||
|
t.Fatalf("a disorder was answered %+v", taken)
|
||||||
|
}
|
||||||
|
if _, ok := f.put["b"]; ok || len(f.deleted) != 1 || f.deleted[0] != "b" {
|
||||||
|
t.Fatalf("a dropped put left %v, deleted %v", f.put, f.deleted)
|
||||||
|
}
|
||||||
|
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "b", Call: "c2", Seq: 2, Data: []byte("two")}, &taken)
|
||||||
|
if taken.Error == "" {
|
||||||
|
t.Fatal("a chunk of a dropped put was taken")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// §518 "The bound": a put not sealed within the bound is dropped, its object deleted.
|
||||||
|
t.Run("APutNotSealedWithinTheBoundIsDropped", func(t *testing.T) {
|
||||||
|
was := SessionBound
|
||||||
|
SessionBound = time.Millisecond
|
||||||
|
t.Cleanup(func() { SessionBound = was })
|
||||||
|
f := &fakeObjects{put: map[string][]byte{}, ctxEnded: make(chan struct{})}
|
||||||
|
b := aSession(t, f)
|
||||||
|
var taken buscalls.ObjectsChunkTaken
|
||||||
|
asked(t, b, buscalls.ObjectsPutChunk, buscalls.ObjectsPutChunkRequest{Objects: "files", Name: "a", Call: "c", Seq: 1, Data: []byte("x")}, &taken)
|
||||||
|
<-f.ctxEnded
|
||||||
|
if len(f.deleted) != 1 {
|
||||||
|
t.Fatalf("the unsealed object was left: %v", f.deleted)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,7 +78,10 @@ func increment(b launch.Bus, key string, attempts int) (n uint64, lost int, err
|
|||||||
|
|
||||||
// Two writers incrementing one counter a thousand times each, against a real bus, end at two thousand:
|
// Two writers incrementing one counter a thousand times each, against a real bus, end at two thousand:
|
||||||
// every number handed out once and none lost, because the runtime writes only at the revision read
|
// every number handed out once and none lost, because the runtime writes only at the revision read
|
||||||
// (novox/hq research 042: an issue's number is handed out once).
|
// (novox/hq research 042: an issue's number is handed out once). A write is lost only to the other writer's
|
||||||
|
// write, so one increment loses at most as many times as the other writer increments: that, not a guess,
|
||||||
|
// is the bound on its tries, and a machine whose scheduler lets one writer win every round still passes
|
||||||
|
// (one processor starved a writer of a thousand tries; principle 11, design 47 H §774).
|
||||||
func TestTwoWritersIncrementingOneCounterOnTheBusLoseNoUpdate(t *testing.T) {
|
func TestTwoWritersIncrementingOneCounterOnTheBusLoseNoUpdate(t *testing.T) {
|
||||||
b := counterBus(t)
|
b := counterBus(t)
|
||||||
const each = 1000
|
const each = 1000
|
||||||
@@ -91,7 +94,7 @@ func TestTwoWritersIncrementingOneCounterOnTheBusLoseNoUpdate(t *testing.T) {
|
|||||||
go func(w int) {
|
go func(w int) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
for i := 0; i < each; i++ {
|
for i := 0; i < each; i++ {
|
||||||
n, l, err := increment(b, "issue", 1000)
|
n, l, err := increment(b, "issue", each+1)
|
||||||
lost[w] += l
|
lost[w] += l
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errs[w] = err
|
errs[w] = err
|
||||||
@@ -137,7 +140,8 @@ func TestTwoWritersIncrementingOneCounterOnTheBusLoseNoUpdate(t *testing.T) {
|
|||||||
// revision it read, never zero.
|
// revision it read, never zero.
|
||||||
// A key's own time to live (issue 1952, mesh-sdk process.State.CreateTTL and RenewTTL): created once, renewed whole by a
|
// A key's own time to live (issue 1952, mesh-sdk process.State.CreateTTL and RenewTTL): created once, renewed whole by a
|
||||||
// put, its end heard by a watch as an expiry; refused, writing nothing, on a bucket that takes none, under a second, and
|
// put, its end heard by a watch as an expiry; refused, writing nothing, on a bucket that takes none, under a second, and
|
||||||
// on an update.
|
// on an update. 1754/AC2: each change the watch is to hear is waited meshtest.Bound(t), the test's own deadline:
|
||||||
|
// the 5 s it was given for a 1 s key's expire were overrun on a loaded build node (main.505).
|
||||||
func TestAStaleWriteIsRefusedAndWritesNothing(t *testing.T) {
|
func TestAStaleWriteIsRefusedAndWritesNothing(t *testing.T) {
|
||||||
b := counterBus(t)
|
b := counterBus(t)
|
||||||
state := func(verb string, extra map[string]any) (uint64, error) {
|
state := func(verb string, extra map[string]any) (uint64, error) {
|
||||||
@@ -262,7 +266,7 @@ func TestAStaleWriteIsRefusedAndWritesNothing(t *testing.T) {
|
|||||||
if c.Op == "put" && len(ops) == 3 && string(c.Value) != "3" {
|
if c.Op == "put" && len(ops) == 3 && string(c.Value) != "3" {
|
||||||
t.Fatalf("the renewed key holds %s", c.Value)
|
t.Fatalf("the renewed key holds %s", c.Value)
|
||||||
}
|
}
|
||||||
case <-time.After(5 * time.Second):
|
case <-time.After(mt.Bound(t)):
|
||||||
t.Fatalf("the watch heard %q, want %q", strings.Join(ops, " "), want)
|
t.Fatalf("the watch heard %q, want %q", strings.Join(ops, " "), want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
|
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
"github.com/novox/mesh-tools/node-tools/internal/bus"
|
||||||
"github.com/novox/mesh-tools/node-tools/internal/launch"
|
"github.com/novox/mesh-tools/node-tools/internal/launch"
|
||||||
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
mt "github.com/novox/mesh-tools/node-tools/internal/meshtest"
|
||||||
@@ -71,16 +73,26 @@ func TestAKeysHistoryIsEveryValueKeptOldestFirst(t *testing.T) {
|
|||||||
owner, reader, _ := historyBuses(t)
|
owner, reader, _ := historyBuses(t)
|
||||||
before := time.Now().Add(-time.Second)
|
before := time.Now().Add(-time.Second)
|
||||||
var revisions []uint64
|
var revisions []uint64
|
||||||
for _, v := range []string{`{"state":"open"}`, `{"state":"fixing"}`, `{"state":"resolved"}`} {
|
// each put answers the bucket's fill with its revision, buscalls.Fill's form (design 47 H2 DMC-14, H-A-386): the messages
|
||||||
|
// kept (every value of the key, the bucket keeping 8), their bytes, and no cap (0)
|
||||||
|
var bytes uint64
|
||||||
|
for i, v := range []string{`{"state":"open"}`, `{"state":"fixing"}`, `{"state":"resolved"}`} {
|
||||||
raw, err := ask(owner, "put", map[string]any{"state": "issues", "key": "502", "value": json.RawMessage(v)})
|
raw, err := ask(owner, "put", map[string]any{"state": "issues", "key": "502", "value": json.RawMessage(v)})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
var r struct {
|
var r struct {
|
||||||
Revision uint64 `json:"revision"`
|
Revision uint64 `json:"revision"`
|
||||||
|
Fill *buscalls.Fill `json:"fill"`
|
||||||
}
|
}
|
||||||
_ = json.Unmarshal(raw, &r)
|
_ = json.Unmarshal(raw, &r)
|
||||||
revisions = append(revisions, r.Revision)
|
revisions = append(revisions, r.Revision)
|
||||||
|
if r.Fill == nil || r.Fill.Count != uint64(i+1) || r.Fill.Bytes <= bytes || r.Fill.MaxBytes != 0 {
|
||||||
|
t.Errorf("put %d answered %s, want its revision and the fill of %d messages, more bytes than %d, no cap", i, raw, i+1, bytes)
|
||||||
|
}
|
||||||
|
if r.Fill != nil {
|
||||||
|
bytes = r.Fill.Bytes
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "503", "value": 1}); err != nil {
|
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "503", "value": 1}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -150,35 +162,79 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
|
|||||||
!strings.Contains(err.Error(), "not a key") {
|
!strings.Contains(err.Error(), "not a key") {
|
||||||
t.Errorf("history of a key the bus cannot hold: %v", err)
|
t.Errorf("history of a key the bus cannot hold: %v", err)
|
||||||
}
|
}
|
||||||
// A page is the values in key order after a key, in one request, to the owner and to a reader, never to a
|
// A page is the values in the order the bus wrote them after the cursor, in one request, to the owner and to a reader,
|
||||||
// module not issued the state; a page too small for two values still gives one and says where it goes on.
|
// never to a module not issued the state; a page too small for two values still gives one and says where the read goes
|
||||||
for k, v := range map[string]string{"2": `"bb"`, "3": `"cc"`} {
|
// on; a value written after the read began comes marked seen-again, and a fresh read hands each kept message, a key's
|
||||||
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": k, "value": json.RawMessage(v)}); err != nil {
|
// older kept revision included (design 47 H2 §779, H-A-382).
|
||||||
|
for _, kv := range [][2]string{{"2", `"bb"`}, {"3", `"cc"`}} {
|
||||||
|
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": kv[0], "value": json.RawMessage(kv[1])}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
type page struct {
|
type entry struct {
|
||||||
Entries []kept `json:"entries"`
|
Key string `json:"key"`
|
||||||
Next string `json:"next"`
|
Value json.RawMessage `json:"value"`
|
||||||
|
SeenAgain bool `json:"seen-again"`
|
||||||
|
Deleted bool `json:"deleted"`
|
||||||
}
|
}
|
||||||
for _, c := range []struct {
|
type page struct {
|
||||||
who, state, after string
|
Entries []entry `json:"entries"`
|
||||||
max int
|
Next string `json:"next"`
|
||||||
keys []string
|
}
|
||||||
next string
|
read := func(who launch.Bus, state, cursor string, most int) page {
|
||||||
}{{"owner", "issues", "", 1 << 20, []string{"1", "2", "3"}, ""}, {"reader", "issues.issues", "1", 1 << 20, []string{"2", "3"}, ""},
|
t.Helper()
|
||||||
{"owner", "issues", "", 1, []string{"1"}, "1"}, {"owner", "issues", "1", 9, []string{"2"}, "2"}} {
|
raw, err := ask(who, "page", map[string]any{"state": state, "cursor": cursor, "max_bytes": most})
|
||||||
b := map[string]launch.Bus{"owner": owner, "reader": reader}[c.who]
|
|
||||||
raw, err := ask(b, "page", map[string]any{"state": c.state, "after": c.after, "max_bytes": c.max})
|
|
||||||
var p page
|
var p page
|
||||||
if err != nil || json.Unmarshal(raw, &p) != nil || p.Next != c.next || len(p.Entries) != len(c.keys) {
|
if err != nil || json.Unmarshal(raw, &p) != nil {
|
||||||
t.Fatalf("page %+v = %s, %v", c, raw, err)
|
t.Fatalf("page of %s after %q = %s, %v", state, cursor, raw, err)
|
||||||
}
|
}
|
||||||
for i, k := range c.keys {
|
return p
|
||||||
if p.Entries[i].Key != k {
|
}
|
||||||
t.Errorf("page %+v: entry %d is %s, want %s", c, i, p.Entries[i].Key, k)
|
said := func(p page) string {
|
||||||
|
var out []string
|
||||||
|
for _, e := range p.Entries {
|
||||||
|
out = append(out, e.Key+map[bool]string{true: "+again"}[e.SeenAgain]+map[bool]string{true: "+deleted"}[e.Deleted])
|
||||||
|
if e.Deleted == (e.Value != nil) {
|
||||||
|
out = append(out, "(value "+string(e.Value)+")")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return strings.Join(out, ",") + map[bool]string{true: " (more)"}[p.Next != ""]
|
||||||
|
}
|
||||||
|
for who, b := range map[string]launch.Bus{"issues": owner, "issues.issues": reader} {
|
||||||
|
if got := said(read(b, who, "", 1<<20)); got != "1,2,3" {
|
||||||
|
t.Errorf("a whole page of %s is %s, want 1,2,3", who, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first := read(owner, "issues", "", 1)
|
||||||
|
second := read(owner, "issues", first.Next, 1)
|
||||||
|
if said(first) != "1 (more)" || said(second) != "2 (more)" {
|
||||||
|
t.Fatalf("pages of one value are %s and %s, want 1 (more) and 2 (more)", said(first), said(second))
|
||||||
|
}
|
||||||
|
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "1", "value": 11}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := said(read(owner, "issues", second.Next, 1<<20)); got != "3,1+again" {
|
||||||
|
t.Errorf("the rest of the read is %s, want 3 and 1 written again since the read began, marked: 3,1+again", got)
|
||||||
|
}
|
||||||
|
if got := said(read(owner, "issues", "", 1<<20)); got != "1,2,3,1" {
|
||||||
|
t.Errorf("a fresh read is %s, want each kept message once, 1's older revision first: 1,2,3,1", got)
|
||||||
|
}
|
||||||
|
// A kept delete is handed as an entry deleted, with no value, at its sequence, so a deleted key never comes back alive
|
||||||
|
// from a bucket with history (H-A-451 (1)).
|
||||||
|
for _, v := range []int{1, 2} {
|
||||||
|
if _, err := ask(owner, "put", map[string]any{"state": "issues", "key": "gone", "value": v}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := ask(owner, "delete", map[string]any{"state": "issues", "key": "gone"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := said(read(owner, "issues", "", 1<<20)); got != "1,2,3,1,gone,gone,gone+deleted" {
|
||||||
|
t.Errorf("a read past a delete is %s, want its two values and then the delete: 1,2,3,1,gone,gone,gone+deleted", got)
|
||||||
|
}
|
||||||
|
if _, err := ask(owner, "page", map[string]any{"state": "issues", "cursor": "2"}); err == nil ||
|
||||||
|
!strings.Contains(err.Error(), "not a cursor") {
|
||||||
|
t.Errorf("a page after a key, not a cursor, answered %v; want it refused", err)
|
||||||
}
|
}
|
||||||
// A page stops when its time budget is spent, after one value at least, and says where it goes on.
|
// A page stops when its time budget is spent, after one value at least, and says where it goes on.
|
||||||
step := time.Time{}
|
step := time.Time{}
|
||||||
@@ -186,7 +242,7 @@ func TestAKeysHistoryAndAPageOfAStateAreServedToOwnerAndReaderAndRefusedToAModul
|
|||||||
defer func() { bus.PageClock = time.Now }()
|
defer func() { bus.PageClock = time.Now }()
|
||||||
raw, err := ask(owner, "page", map[string]any{"state": "issues", "max_bytes": 1 << 20, "budget_ms": 10000})
|
raw, err := ask(owner, "page", map[string]any{"state": "issues", "max_bytes": 1 << 20, "budget_ms": 10000})
|
||||||
var cut page
|
var cut page
|
||||||
if err != nil || json.Unmarshal(raw, &cut) != nil || len(cut.Entries) != 1 || cut.Next != "1" {
|
if err != nil || json.Unmarshal(raw, &cut) != nil || said(cut) != "1 (more)" {
|
||||||
t.Fatalf("a page past its budget = %s, %v", raw, err)
|
t.Fatalf("a page past its budget = %s, %v", raw, err)
|
||||||
}
|
}
|
||||||
if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil {
|
if _, err := ask(other, "page", map[string]any{"state": "issues.issues"}); err == nil {
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package runtime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.novox.be/novox/mesh-sdk/go/buscalls"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A-44: mesh/stream.publish is a family of its own, the capability stream-publish, and no longer of bus-state-calls.
|
||||||
|
func TestStreamPublishIsACapabilityOfItsOwn(t *testing.T) {
|
||||||
|
if !slices.Equal(callFamilies[CapStreamPublish], []string{buscalls.StreamPublish}) || CapStreamPublish != "stream-publish" {
|
||||||
|
t.Fatal("stream-publish does not state only mesh/stream.publish")
|
||||||
|
}
|
||||||
|
if slices.Contains(callFamilies[CapBusStateCalls], buscalls.StreamPublish) {
|
||||||
|
t.Fatal("bus-state-calls still states mesh/stream.publish")
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
-3
@@ -37,6 +37,29 @@
|
|||||||
"why": "the mesh's tools for whoever is on this machine, over MCP on loopback; the machine's login is the authority (novox/hq ADR 0152, 0175)"
|
"why": "the mesh's tools for whoever is on this machine, over MCP on loopback; the machine's login is the authority (novox/hq ADR 0152, 0175)"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
"config": {
|
||||||
|
"drain-bound": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "how long the tool runner, once told to stop, finishes the calls in flight before it cuts them and stops its bundles, a Go duration such as 30s (design 47 H2 §813 (12), H-A-377).",
|
||||||
|
"trusted": false,
|
||||||
|
"runtime": true,
|
||||||
|
"default": "30s"
|
||||||
|
},
|
||||||
|
"kept-call-pace-first": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "how long the tool runner's kept call waits after its first transport fault before it calls again, doubling to kept-call-pace-max, a Go duration such as 1s (design 47 H2 §775).",
|
||||||
|
"trusted": false,
|
||||||
|
"runtime": true,
|
||||||
|
"default": "1s"
|
||||||
|
},
|
||||||
|
"kept-call-pace-max": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "the longest wait of the tool runner's kept call between two calls, a Go duration such as 30s (design 47 H2 §775).",
|
||||||
|
"trusted": false,
|
||||||
|
"runtime": true,
|
||||||
|
"default": "30s"
|
||||||
|
}
|
||||||
|
},
|
||||||
"resources": [
|
"resources": [
|
||||||
{
|
{
|
||||||
"id": "mesh-state",
|
"id": "mesh-state",
|
||||||
@@ -58,7 +81,18 @@
|
|||||||
"language": "go",
|
"language": "go",
|
||||||
"system": "arch",
|
"system": "arch",
|
||||||
"from": "cmd/node-tools",
|
"from": "cmd/node-tools",
|
||||||
"binary": "node-tools"
|
"binary": "node-tools",
|
||||||
|
"states": [
|
||||||
|
"approval-mark/1",
|
||||||
|
"bus-state-calls",
|
||||||
|
"finding-calls",
|
||||||
|
"ledger-calls",
|
||||||
|
"ledger-upkeep-calls",
|
||||||
|
"put-sessions",
|
||||||
|
"seat-settle-delay",
|
||||||
|
"sent-objects-calls",
|
||||||
|
"stream-publish"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -77,8 +111,8 @@
|
|||||||
"mesh-catalog.seat-definition-changed",
|
"mesh-catalog.seat-definition-changed",
|
||||||
"mesh-catalog.seat-definition-removed",
|
"mesh-catalog.seat-definition-removed",
|
||||||
"mesh-conditions.findings-asked",
|
"mesh-conditions.findings-asked",
|
||||||
"mesh-delivery-assigner.views.assignments",
|
"seat:mesh-module-assigner.views.assignments",
|
||||||
"mesh-delivery-assigner.views.seat-holders",
|
"seat:mesh-module-assigner.views.seat-holders",
|
||||||
"mesh-delivery.source-moved"
|
"mesh-delivery.source-moved"
|
||||||
],
|
],
|
||||||
"streams": [
|
"streams": [
|
||||||
|
|||||||
+3
-2
@@ -1,7 +1,8 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# A tools bundle that says who the runtime said called it (novox/hq issue 365): MCP over stdio, no SDK. Its tool
|
# A tools bundle that says who the runtime said called it (novox/hq issue 365): MCP over stdio, no SDK. Its tool
|
||||||
# and its seat verb answer the caller the call's `_meta` named — "" when it named none —, the id of the call in flight
|
# and its seat verb answer the caller the call's `_meta` named — "" when it named none —, the id of the call in flight
|
||||||
# it named (novox/hq ADR 0597 §7), and the arguments as given.
|
# it named (novox/hq ADR 0597 §7), the ask id it named under mesh/ask — null when it named none (design 47 H2 §775, H-A-351) —,
|
||||||
|
# and the arguments as given.
|
||||||
import json, sys
|
import json, sys
|
||||||
|
|
||||||
def say(m):
|
def say(m):
|
||||||
@@ -19,7 +20,7 @@ for line in sys.stdin:
|
|||||||
say({"id": rid, "result": {"tools": TOOLS}})
|
say({"id": rid, "result": {"tools": TOOLS}})
|
||||||
elif m == "tools/call":
|
elif m == "tools/call":
|
||||||
meta = p.get("_meta") or {}
|
meta = p.get("_meta") or {}
|
||||||
said = {"caller": meta.get("mesh/caller", ""), "call": meta.get("mesh/call", ""), "arguments": p.get("arguments") or {}}
|
said = {"caller": meta.get("mesh/caller", ""), "call": meta.get("mesh/call", ""), "ask": meta.get("mesh/ask"), "arguments": p.get("arguments") or {}}
|
||||||
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(said)}]}})
|
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(said)}]}})
|
||||||
elif rid is not None:
|
elif rid is not None:
|
||||||
say({"id": rid, "result": {}})
|
say({"id": rid, "result": {}})
|
||||||
|
|||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# The login shell's bundle as the seat node-login-shell has it: MCP over stdio, no SDK, one seat verb, execute, which says
|
||||||
|
# the command it was given and the caller the call's `_meta` named.
|
||||||
|
import json, sys
|
||||||
|
|
||||||
|
def say(m):
|
||||||
|
m["jsonrpc"] = "2.0"; sys.stdout.write(json.dumps(m) + "\n"); sys.stdout.flush()
|
||||||
|
|
||||||
|
TOOLS = [
|
||||||
|
{"name": "node-login-shell.execute", "description": "run a command", "inputSchema": {"type": "object", "properties": {"command": {"type": "string"}}}},
|
||||||
|
]
|
||||||
|
for line in sys.stdin:
|
||||||
|
req = json.loads(line); rid = req.get("id"); m = req.get("method"); p = req.get("params") or {}
|
||||||
|
if m == "initialize":
|
||||||
|
say({"id": rid, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "zsh", "version": "1"}}})
|
||||||
|
elif m == "tools/list":
|
||||||
|
say({"id": rid, "result": {"tools": TOOLS}})
|
||||||
|
elif m == "tools/call":
|
||||||
|
meta = p.get("_meta") or {}
|
||||||
|
said = {"ran": (p.get("arguments") or {}).get("command", ""), "caller": meta.get("mesh/caller", "")}
|
||||||
|
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(said)}]}})
|
||||||
|
elif rid is not None:
|
||||||
|
say({"id": rid, "result": {}})
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# A tools bundle for the tool runner's whole test (design 47 H §774): MCP over stdio, no SDK. A tool `who`, the seat node-desk's verbs
|
||||||
|
# `who` (answers at once) and `slow` (answers after three seconds), and a tool `reach` that asks the seat verb node-desk.fresh as the
|
||||||
|
# bundle does, through the runtime's `mesh/ask`, and says what came back; a tool `hold`, which answers after the seconds it is given,
|
||||||
|
# beside other calls (design 47 H2 §813 (12)); a tool `page`, which reads one page of its state `pages` after the cursor it is given,
|
||||||
|
# through the runtime's `mesh/state.page`, and says the keys, those seen again and the next cursor (design 47 H2 §779).
|
||||||
|
import json, os, sys, threading, time
|
||||||
|
|
||||||
|
LOCK = threading.Lock()
|
||||||
|
|
||||||
|
def say(m):
|
||||||
|
m["jsonrpc"] = "2.0"
|
||||||
|
with LOCK:
|
||||||
|
sys.stdout.write(json.dumps(m) + "\n"); sys.stdout.flush()
|
||||||
|
|
||||||
|
def text(rid, value):
|
||||||
|
say({"id": rid, "result": {"content": [{"type": "text", "text": json.dumps(value)}]}})
|
||||||
|
|
||||||
|
TOOLS = [
|
||||||
|
{"name": "who", "description": "the module's own tool", "inputSchema": {"type": "object", "properties": {}}},
|
||||||
|
{"name": "reach", "description": "asks the seat verb node-desk.fresh", "inputSchema": {"type": "object", "properties": {}}},
|
||||||
|
{"name": "hold", "description": "answers after the seconds it is given, beside other calls", "inputSchema": {"type": "object", "properties": {"seconds": {"type": "number"}}}},
|
||||||
|
{"name": "page", "description": "one page of the state pages after a cursor", "inputSchema": {"type": "object", "properties": {"cursor": {"type": "string"}}}},
|
||||||
|
{"name": "node-desk.who", "description": "the seat's verb", "inputSchema": {"type": "object", "properties": {}}},
|
||||||
|
{"name": "node-desk.slow", "description": "the seat's verb that answers late", "inputSchema": {"type": "object", "properties": {}}},
|
||||||
|
]
|
||||||
|
for line in sys.stdin:
|
||||||
|
req = json.loads(line); rid = req.get("id"); m = req.get("method"); p = req.get("params") or {}
|
||||||
|
if m == "initialize":
|
||||||
|
say({"id": rid, "result": {"protocolVersion": "2025-03-26", "capabilities": {"tools": {}}, "serverInfo": {"name": "ledger", "version": "1"}}})
|
||||||
|
elif m == "tools/list":
|
||||||
|
say({"id": rid, "result": {"tools": TOOLS}})
|
||||||
|
elif m == "tools/call":
|
||||||
|
name = p.get("name")
|
||||||
|
if name == "hold":
|
||||||
|
seconds = (p.get("arguments") or {}).get("seconds", 0)
|
||||||
|
with open(os.environ["HELD_FILE"], "a") as noted:
|
||||||
|
noted.write("hold %s\n" % seconds)
|
||||||
|
threading.Thread(target=lambda r=rid, n=seconds: (time.sleep(n), text(r, {"held": n})), daemon=True).start()
|
||||||
|
continue
|
||||||
|
if name == "node-desk.slow":
|
||||||
|
time.sleep(3)
|
||||||
|
if name == "page":
|
||||||
|
cursor = (p.get("arguments") or {}).get("cursor", "")
|
||||||
|
say({"id": "p1", "method": "mesh/state.page", "params": {"state": "pages", "cursor": cursor}})
|
||||||
|
for answer in sys.stdin:
|
||||||
|
a = json.loads(answer)
|
||||||
|
if a.get("id") == "p1":
|
||||||
|
if "error" in a:
|
||||||
|
text(rid, {"error": a["error"]})
|
||||||
|
else:
|
||||||
|
r = a.get("result") or {}
|
||||||
|
es = r.get("entries") or []
|
||||||
|
text(rid, {"keys": [e["key"] for e in es if not e.get("seen-again")],
|
||||||
|
"again": [e["key"] for e in es if e.get("seen-again")], "next": r.get("next", "")})
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
if name == "reach":
|
||||||
|
say({"id": "q1", "method": "mesh/ask", "params": {"key": "seat:node-desk.fresh", "body": {}}})
|
||||||
|
for answer in sys.stdin:
|
||||||
|
a = json.loads(answer)
|
||||||
|
if a.get("id") == "q1":
|
||||||
|
text(rid, a.get("result") if "error" not in a else {"error": a["error"]})
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
text(rid, {"tool": name})
|
||||||
|
elif rid is not None:
|
||||||
|
say({"id": rid, "result": {}})
|
||||||
Reference in New Issue
Block a user