Files
mesh-catalog/modules/nats/cmd/nats-tools/removal.go
T
jschoubben 3443760205 nats: nats_consumer_remove removes only a durable that is itself an orphan
Review round 1: a durable whose twin is current was removed without
reading the durable itself, so of the five live pairs where both twins
have pulls waiting either one would have gone. The tool now reads the
named durable too and refuses it while pulls wait on it, both read from
the bus at the call. "Current" is the setting twin-current-hours (24 by
default) of the manifest, read from the configuration at each call, the
field name the grants part's manifest names too.

Builds: design 47 H2 H-A-472 (1) and its third addendum (1), (2); review round 1 findings (1), (2)
2026-11-22 14:33:01 +01:00

625 lines
30 KiB
Go

package main
// The three tools of this module that change the bus (novox/hq ADR 0564 clause 5, issue 1952 notes 6, 7 and 9):
// remove one named consumer, remove one named stream, and remove one node's keys under a prefix of a key-value bucket. Everything else
// here reads.
//
// **Narrow by what the tool needs, and narrower by what the bus grants.** The tools reach the bus on the
// credential the module's manifest names (NATS_TOOLS_CREDENTIAL); the bus refuses whatever that credential is not
// granted, so a wrong stream, consumer or bucket is refused by the server and said here, not trusted to the
// arguments. Each tool refuses without `why`, reads what it would remove first (and says it, so a person can ask
// with dry_run and then for real), removes, reads that it is gone, and says what it did as an event of the module
// (the audit trail: who asked is in the call the tool runner audits, why and what are in the event).
import (
"context"
"encoding/json"
"errors"
"fmt"
"regexp"
"sort"
"strings"
"time"
"git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient"
stdio "git.novox.be/novox/mesh-sdk/go"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"nats-tools/internal/keeper"
)
// Bus opens JetStream on the bus as the module's credential for one call; close ends the connection.
type Bus func(ctx context.Context) (js jetstream.JetStream, close func(), err error)
// Said keeps the audit line: an event of this module.
type Said func(event string, body any) error
const (
consumerRemoved = "consumer-removed"
bucketKeysRemoved = "bucket-keys-removed"
streamRemoved = "stream-removed"
streamPurged = "stream-purged"
// maxKeysShown bounds the keys an answer lists; the count is always whole.
maxKeysShown = 200
)
var (
// A stream, consumer or bucket is one subject token: no dot, no wildcard, no space.
name = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
// A key prefix is subject tokens and their dots; no wildcard, so it names keys and not a pattern.
keyPrefix = regexp.MustCompile(`^[A-Za-z0-9_./=-]+$`)
)
func why(a map[string]any) (string, error) {
w := strings.TrimSpace(arg(a, "why"))
if w == "" {
return "", errors.New("why is required: say why this is removed, for the audit trail (novox/hq ADR 0564 clause 5); nothing was removed")
}
return w, nil
}
// answerWithin is how long the bus is given to answer one request. **The bus does not refuse a request its
// credential is not granted: it drops it** (a permissions violation is told to the connection's error handler,
// never answered), so an unanswered request is how a refusal shows here.
var answerWithin = 10 * time.Second
// unanswered says what a request with no answer most likely is.
func unanswered(err error, what string) error {
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, nats.ErrTimeout) {
return fmt.Errorf("%s: the bus did not answer within %s; it drops, without an answer, what the module's credential is not granted, "+
"so this is most likely outside its grant (or the bus is not reachable): %w", what, answerWithin, err)
}
return fmt.Errorf("%s: %w", what, err)
}
func step(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(ctx, answerWithin)
}
// readConsumer reads one consumer of any kind. **A push consumer is read as well as a pull consumer**: js.Consumer
// refuses one ("consumer is not a pull consumer", the controller's leftovers on EVENTS and CONTROL were push consumers),
// so the push reading is tried when the pull reading refuses. Both ask only CONSUMER.INFO of that consumer, which is
// all the grant gives (never STREAM.INFO of a stream the tool may not read).
func readConsumer(ctx context.Context, js jetstream.JetStream, stream, consumer string) (*jetstream.ConsumerInfo, error) {
c, err := js.Consumer(ctx, stream, consumer)
if errors.Is(err, jetstream.ErrNotPullConsumer) {
p, perr := js.PushConsumer(ctx, stream, consumer)
if perr != nil {
return nil, perr
}
return p.CachedInfo(), nil
}
if err != nil {
return nil, err
}
return c.CachedInfo(), nil
}
// ConsumerRemoved is what nats_consumer_remove answers and says.
type ConsumerRemoved struct {
Stream string `json:"stream"`
Consumer string `json:"consumer"`
Why string `json:"why"`
Was map[string]any `json:"was"`
Removed bool `json:"removed"`
At time.Time `json:"at"`
}
// RemoveConsumer removes one named consumer of one stream, after reading it, and says so.
func RemoveConsumer(ctx context.Context, bus Bus, said Said, a map[string]any) (any, error) {
w, err := why(a)
if err != nil {
return nil, err
}
stream, consumer := arg(a, "stream"), arg(a, "consumer")
if !name.MatchString(stream) || !name.MatchString(consumer) {
return nil, errors.New("stream and consumer are required, each one name (letters, digits, - and _): nothing was removed")
}
js, closeBus, err := bus(ctx)
if err != nil {
return nil, err
}
defer closeBus()
sctx, cancel := step(ctx)
info, err := readConsumer(sctx, js, stream, consumer)
cancel()
if err != nil {
if errors.Is(err, jetstream.ErrConsumerNotFound) || errors.Is(err, jetstream.ErrStreamNotFound) {
return nil, fmt.Errorf("%s has no consumer %s (%v): nothing was removed", stream, consumer, err)
}
return nil, unanswered(err, fmt.Sprintf("the consumer %s of %s could not be read, so it was not removed", consumer, stream))
}
was := map[string]any{
"durable": info.Config.Durable, "filter_subject": info.Config.FilterSubject, "filter_subjects": info.Config.FilterSubjects,
"deliver_subject": info.Config.DeliverSubject, "pending": info.NumPending, "ack_pending": info.NumAckPending,
"redelivered": info.NumRedelivered, "created": info.Created,
}
sctx, cancel = step(ctx)
err = js.DeleteConsumer(sctx, stream, consumer)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("consumer %s of %s was not removed", consumer, stream))
}
sctx, cancel = step(ctx)
_, err = readConsumer(sctx, js, stream, consumer)
cancel()
// Only the bus saying it is not there is a removal; a read that failed otherwise confirms nothing.
if err == nil {
return nil, fmt.Errorf("consumer %s of %s is still there after the removal was accepted", consumer, stream)
}
if !errors.Is(err, jetstream.ErrConsumerNotFound) && !errors.Is(err, jetstream.ErrStreamNotFound) {
return nil, unanswered(err, fmt.Sprintf("the removal of consumer %s of %s was accepted but could not be confirmed", consumer, stream))
}
out := ConsumerRemoved{Stream: stream, Consumer: consumer, Why: w, Was: was, Removed: true, At: time.Now().UTC()}
if err := said(consumerRemoved, out); err != nil {
return nil, fmt.Errorf("consumer %s of %s WAS removed (%s) but the audit event could not be said: %w", consumer, stream, w, err)
}
return out, nil
}
// KeysRemoved is what nats_bucket_remove answers and says.
type KeysRemoved struct {
Bucket string `json:"bucket"`
Prefix string `json:"prefix"`
Why string `json:"why"`
DryRun bool `json:"dry_run"`
Count int `json:"count"`
Keys []string `json:"keys"`
Cut bool `json:"keys_cut,omitempty"`
Removed int `json:"removed"`
At time.Time `json:"at"`
}
// RemoveKeys removes the keys of a key-value bucket under a prefix: counted first, and only those.
func RemoveKeys(ctx context.Context, bus Bus, said Said, a map[string]any) (any, error) {
w, err := why(a)
if err != nil {
return nil, err
}
bucket, node, prefix := arg(a, "bucket"), arg(a, "node"), arg(a, "prefix")
if !name.MatchString(bucket) {
return nil, errors.New("bucket is required, a bucket's name as nats_buckets lists it: nothing was removed")
}
if (node == "") == (prefix == "") {
return nil, errors.New("give exactly one of node (that node's keys: those starting `<node>.`) or prefix (keys starting so): " +
"a removal of a whole bucket is not this tool's; nothing was removed")
}
if node != "" {
if !name.MatchString(node) {
return nil, errors.New("node is one machine's name: nothing was removed")
}
prefix = node + "."
}
if !keyPrefix.MatchString(prefix) {
return nil, errors.New("prefix is key text without wildcards or spaces: nothing was removed")
}
dry, _ := a["dry_run"].(bool)
js, closeBus, err := bus(ctx)
if err != nil {
return nil, err
}
defer closeBus()
sctx, cancel := step(ctx)
kv, err := js.KeyValue(sctx, bucket)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("bucket %s could not be opened, nothing was removed", bucket))
}
sctx, cancel = step(ctx)
stream, err := js.Stream(sctx, "KV_"+bucket)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("bucket %s has no stream to read its keys from", bucket))
}
// The server narrows to the prefix's tokens when the prefix ends on a token; any other prefix is cut here.
filter := "$KV." + bucket + ".>"
if strings.HasSuffix(prefix, ".") {
filter = "$KV." + bucket + "." + prefix + ">"
}
sctx, cancel = step(ctx)
info, err := stream.Info(sctx, jetstream.WithSubjectFilter(filter))
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the keys of %s could not be read, so none were removed", bucket))
}
var keys []string
for subject := range info.State.Subjects {
if key := strings.TrimPrefix(subject, "$KV."+bucket+"."); strings.HasPrefix(key, prefix) {
keys = append(keys, key)
}
}
sort.Strings(keys)
out := KeysRemoved{Bucket: bucket, Prefix: prefix, Why: w, DryRun: dry, Count: len(keys), Keys: keys, At: time.Now().UTC()}
if len(keys) > maxKeysShown {
out.Keys, out.Cut = keys[:maxKeysShown], true
}
if want, ok := a["expect"].(float64); ok && int(want) != len(keys) {
return nil, fmt.Errorf("%d keys of %s start with %q, not the %d expected: nothing was removed", len(keys), bucket, prefix, int(want))
}
if dry || len(keys) == 0 {
return out, nil
}
for _, k := range keys {
sctx, cancel := step(ctx)
err := kv.Purge(sctx, k)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("removing %q from %s failed after %d of %d keys, the rest were left", k, bucket, out.Removed, len(keys)))
}
out.Removed++
}
if err := said(bucketKeysRemoved, out); err != nil {
return nil, fmt.Errorf("%d keys of %s under %q WERE removed (%s) but the audit event could not be said: %w", out.Removed, bucket, prefix, w, err)
}
return out, nil
}
// StreamRemoved is what nats_stream_remove answers and says.
type StreamRemoved struct {
Stream string `json:"stream"`
Why string `json:"why"`
DryRun bool `json:"dry_run"`
Present bool `json:"present"`
Messages uint64 `json:"messages"`
Bytes uint64 `json:"bytes"`
Consumers int `json:"consumers"`
Removed bool `json:"removed"`
Said string `json:"said"`
At time.Time `json:"at"`
}
// RemoveStream removes one named stream whole, after reading it, and says so (the controller's leftovers: its streams
// CONTROL and ASSIGNMENTS, its buckets' and object stores' streams; novox/hq ADR 0590 §6). **A stream already gone is no error**: the removal is the same act
// however often it is asked, and says it found nothing. A stream with a consumer is refused, naming how many: a reader
// is still attached, and that is for a person to look at before the stream goes.
func RemoveStream(ctx context.Context, bus Bus, said Said, a map[string]any) (any, error) {
w, err := why(a)
if err != nil {
return nil, err
}
stream := arg(a, "stream")
if !name.MatchString(stream) {
return nil, errors.New("stream is required, one stream's name (letters, digits, - and _): nothing was removed")
}
dry, _ := a["dry_run"].(bool)
js, closeBus, err := bus(ctx)
if err != nil {
return nil, err
}
defer closeBus()
out := StreamRemoved{Stream: stream, Why: w, DryRun: dry, At: time.Now().UTC()}
sctx, cancel := step(ctx)
s, err := js.Stream(sctx, stream)
cancel()
if errors.Is(err, jetstream.ErrStreamNotFound) {
out.Said = stream + " is not there: nothing to remove"
return out, nil
}
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the stream %s could not be read, so it was not removed", stream))
}
sctx, cancel = step(ctx)
info, err := s.Info(sctx)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the stream %s could not be read, so it was not removed", stream))
}
out.Present, out.Messages, out.Bytes, out.Consumers = true, info.State.Msgs, info.State.Bytes, info.State.Consumers
if info.State.Consumers > 0 {
return nil, fmt.Errorf("%s has %d consumers: a reader is attached, so it was not removed", stream, info.State.Consumers)
}
if dry {
out.Said = fmt.Sprintf("%s holds %d messages (%d bytes) and no consumer; it would be removed", stream, out.Messages, out.Bytes)
return out, nil
}
sctx, cancel = step(ctx)
err = js.DeleteStream(sctx, stream)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("stream %s was not removed", stream))
}
sctx, cancel = step(ctx)
_, err = js.Stream(sctx, stream)
cancel()
// Only the bus saying it is not there is a removal; a read that failed otherwise confirms nothing.
if err == nil {
return nil, fmt.Errorf("stream %s is still there after the removal was accepted", stream)
}
if !errors.Is(err, jetstream.ErrStreamNotFound) {
return nil, unanswered(err, fmt.Sprintf("the removal of stream %s was accepted but could not be confirmed", stream))
}
out.Removed = true
out.Said = fmt.Sprintf("%s removed: %d messages (%d bytes) and no consumer", stream, out.Messages, out.Bytes)
if err := said(streamRemoved, out); err != nil {
return nil, fmt.Errorf("stream %s WAS removed (%s) but the audit event could not be said: %w", stream, w, err)
}
return out, nil
}
// removalTools are the three removal tools. **They refuse an entry of the new form** (design 25 § 12.3; ADR 0595 §4 as
// its insight of 2026-11-03 has it): the mesh deletes a module's kept data only through the bus module's drop and
// recreate, so a stream, a bucket or a consumer of a stream the keeper made (its state asked, read through newForm) is
// refused, naming nats_drop, before the bus is reached; the old sections' entries are removed as before. A newForm
// that cannot be read refuses too: what cannot be told apart is not removed.
//
// **A consumer is judged by its name, not by its stream** (design 47 H, H-A-126, H-A-127): the mesh names a module's
// durable <node>_<module>, so a durable of that form for a module of an accepted manifest (the keeper's accepted set:
// every module it heard as accepted, its state plans, one key per module of a watched branch's newest revision whether
// it asks for kept data or not, design 47 G §538) is refused, on any stream; every other durable is an orphan and goes, `why` its warrant, at once, and its removal is
// recorded as a hand act through mesh-hand-acts, as nats_bucket_expiry's change is.
func removalTools(bus Bus, said Said, newForm heldEntries, accepted acceptedModules, record Recorded, twinWithin func() time.Duration) []stdio.Tool {
removeConsumer := func(a map[string]any) (any, error) {
within := DefaultTwinCurrentHours * time.Hour
if twinWithin != nil {
within = twinWithin()
}
twin, err := refuseAcceptedDurable(context.Background(), bus, accepted, arg(a, "stream"), arg(a, "consumer"), time.Now(), within)
if err != nil {
return nil, err
}
out, err := RemoveConsumer(context.Background(), bus, said, a)
if err != nil {
return nil, err
}
r := out.(ConsumerRemoved)
what := fmt.Sprintf("removed the consumer %s of the stream %s", r.Consumer, r.Stream)
if twin != "" {
what += fmt.Sprintf(", an orphan: its module's twin %s on that stream is current (design 47 H2, H-A-472)", twin)
}
if record == nil {
return nil, fmt.Errorf("%s WAS done (%s) but the hand-act log cannot be reached here", what, r.Why)
}
if err := record(meshhandactsclient.Request{What: what, Why: r.Why, Cause: "consumer-remove"}); err != nil {
return nil, fmt.Errorf("%s WAS done (%s) but the hand act could not be recorded: %w", what, r.Why, err)
}
return r, nil
}
run := func(f func(context.Context, Bus, Said, map[string]any) (any, error)) func(map[string]any) (any, error) {
return func(a map[string]any) (any, error) {
stream := arg(a, "stream")
if b := arg(a, "bucket"); b != "" {
stream = "KV_" + b
}
if err := refuseNewForm(newForm, stream); err != nil {
return nil, err
}
return f(context.Background(), bus, said, a)
}
}
return []stdio.Tool{
{Name: "nats_consumer_remove",
Description: "Removes (deletes) one named JetStream consumer of one stream, e.g. a consumer the controller left, such as `controller` of DEAD_LETTER_NOTICES or `controller-merges` of EVENTS (novox/hq ADR 0590 §6), or an orphan on a module's kept-data stream. Refuses a durable named <node>_<module> or beginning <node>_<module>_ for a module of an accepted manifest, on any stream, unless it is an orphan: no pulls waiting on it while its twin (<node>_<module> for <node>_<module>_tools, and back) on the same stream is current, with pulls waiting and a delivery within the setting twin-current-hours (24 by default), both read at the call, and the hand act names that twin (design 47 H2, H-A-472); any other durable goes. Needs `why`, its warrant, kept in the audit trail and recorded as a hand act through mesh-hand-acts (design 47 H, H-A-127); refuses an unknown stream or consumer; reads the consumer first and answers what it was (filters, pending, unacknowledged); the stream and its other consumers are not touched. The bus refuses any consumer the module's credential is not granted.",
Input: map[string]any{"stream": str("the stream, e.g. DEAD_LETTER_NOTICES"), "consumer": str("the consumer's name, e.g. controller"), "why": str("why it is removed, for the audit trail (required)")},
Run: removeConsumer},
{Name: "nats_stream_remove",
Description: "Removes (deletes) one named JetStream stream whole, e.g. a stream the controller left: CONTROL, ASSIGNMENTS, one of its buckets as KV_<bucket> or a node's declaration files as OBJ_declaration-files-<node> (novox/hq ADR 0590 §6; a bucket's whole removal is this tool's, never nats_bucket_remove's). Needs `why`, kept in the audit trail; reads the stream first and answers its messages, bytes and consumers; refuses a stream that still has a consumer; a stream already gone is answered as such and is no error, so asking again is safe. `dry_run` only reads. The bus refuses any stream the module's credential is not granted.",
Input: map[string]any{"stream": str("the stream, e.g. ASSIGNMENTS"), "why": str("why it is removed, for the audit trail (required)"), "dry_run": map[string]any{"type": "boolean", "description": "read the stream, remove nothing"}},
Run: run(RemoveStream)},
{Name: "nats_stream_purge",
Description: "Purges (removes) the messages of one named JetStream stream below a sequence, keeping that sequence and every later one: e.g. a build seat's work queue (SEAT_NODE_BUILD_GO) emptied of old asks nobody waits for, up to the first ask still wanted. Needs `why`, kept in the audit trail; reads the stream first and answers its first and last sequence and its messages before and after; the stream and its consumers stay; refuses a `below` past the stream's end (a whole purge is not this tool's). `dry_run` only reads. Read the sequences with nats_stream_messages. The bus refuses any stream the module's credential is not granted.",
Input: map[string]any{"stream": str("the stream, e.g. SEAT_NODE_BUILD_GO"), "below": num("the first sequence kept: every message below it is purged"),
"why": str("why they are purged, for the audit trail (required)"), "dry_run": map[string]any{"type": "boolean", "description": "read the stream, purge nothing"}},
Run: run(PurgeStream)},
{Name: "nats_bucket_remove",
Description: "Removes (purges) keys from a key-value bucket: one node's keys (`node`, the keys starting `<node>.`) or the keys under a `prefix`, e.g. a full acts bucket of the node-engine. Needs `why`, kept in the audit trail; never the whole bucket. Counts the keys first and lists them (`dry_run` only counts; `expect` refuses when the count differs); removes only those keys, and their history. See the buckets and their keys with nats_buckets. The bus refuses any bucket the module's credential is not granted.",
Input: map[string]any{"bucket": str("the bucket as nats_buckets lists it, e.g. mesh-host_acts"), "node": str("a node whose keys (`<node>.`) go"), "prefix": str("key prefix instead of node"),
"why": str("why they are removed, for the audit trail (required)"), "dry_run": map[string]any{"type": "boolean", "description": "count and list the keys, remove none"}, "expect": num("the count of keys expected; refuses when it differs")},
Run: run(RemoveKeys)},
}
}
// refuseAcceptedDurable refuses a durable named <node>_<module>, or beginning <node>_<module>_, for a module of the
// keeper's accepted set, on any node (design 47 H, H-A-127, H-A-128): every module it heard as accepted, read from its
// state plans (design 47 G §538), never from its state asked, which holds only a module that asks for kept data (a
// module keeping none would lose its live durables: H-A-128's silent failure, P3). A set that cannot be read refuses
// too: what cannot be told apart is not removed.
//
// **An orphaned durable goes** (design 47 H2, H-A-472 (1) and its third addendum): a module's durable that is itself an
// orphan (no pulls waiting on it) while its live twin on the same stream exists and is current is not refused, and the
// twin's name is answered, for the hand act to name it; both are read from the bus at the call. The twins are the
// module's program's durable <node>_<module> and its tool runner's <node>_<module>_tools (design 47 G, A-340): a module
// that moved into the tool runner left the first, one that runs its own program again left the second. A module's
// only durable, any other suffix, a durable with pulls waiting, and a durable or twin that cannot be read or a twin
// that is not current, stay refused (H-A-127/128). within is the bound of "current", the setting twin-current-hours.
func refuseAcceptedDurable(ctx context.Context, bus Bus, accepted acceptedModules, stream, consumer string, now time.Time, within time.Duration) (string, error) {
if accepted == nil {
return "", nil
}
node, module, ok := strings.Cut(consumer, "_")
if !ok || node == "" || module == "" {
return "", nil
}
held, err := accepted()
if err != nil {
return "", fmt.Errorf("whether %s is the durable of a module of an accepted manifest cannot be read (%v), so nothing was removed", consumer, err)
}
for m := range held {
if module != m && !strings.HasPrefix(module, m+"_") {
continue
}
refused := fmt.Errorf("%s is %s's durable on %s, a module of an accepted manifest: it is not removed; nothing was removed", consumer, m, node)
twin := twinOf(node, m, module)
if twin == "" || bus == nil || !name.MatchString(stream) {
return "", refused
}
js, closeBus, err := bus(ctx)
if err != nil {
return "", fmt.Errorf("%v (it and its twin %s on %s cannot be read: %v)", refused, twin, stream, err)
}
defer closeBus()
sctx, cancel := step(ctx)
self, err := readConsumer(sctx, js, stream, consumer)
cancel()
if err != nil {
return "", fmt.Errorf("%v (it cannot be read on %s: %v)", refused, stream, err)
}
if self.NumWaiting > 0 {
return "", fmt.Errorf("%v (it is no orphan: %d pulls waiting on it)", refused, self.NumWaiting)
}
sctx, cancel = step(ctx)
info, err := readConsumer(sctx, js, stream, twin)
cancel()
if err != nil {
return "", fmt.Errorf("%v (its twin %s on %s cannot be read: %v)", refused, twin, stream, err)
}
if !current(info, now, within) {
return "", fmt.Errorf("%v (its twin %s on %s is not current: %d pulls waiting, last delivery %s, the bound %s)", refused, twin, stream, info.NumWaiting, lastDelivery(info), within)
}
return twin, nil
}
return "", nil
}
// twinOf names the twin of a module's durable: <node>_<module>_tools for <node>_<module>, and back; "" for any other.
func twinOf(node, module, durable string) string {
switch durable {
case module:
return node + "_" + module + "_tools"
case module + "_tools":
return node + "_" + module
}
return ""
}
// DefaultTwinCurrentHours is the setting twin-current-hours's default (design 47 H2, H-A-472 third addendum): how recent a
// twin's last delivery is for it to be current, within the day; the grants part reads the same field name of its own
// manifest for its orphaned durables.
const DefaultTwinCurrentHours = 24
// twinCurrentWithin is the setting twin-current-hours as the configuration answers it, in hours, as a bound: its default
// when the configuration gives none, or a value that is not a positive whole number.
func twinCurrentWithin(raw json.RawMessage, err error) time.Duration {
var n int
if err != nil || json.Unmarshal(raw, &n) != nil || n < 1 {
n = DefaultTwinCurrentHours
}
return time.Duration(n) * time.Hour
}
// bundleTwinCurrent is the setting twin-current-hours as this bundle's configuration holds it, read at each call
// (never while the tools are listed: see bundleKeepDays).
func bundleTwinCurrent() time.Duration {
return twinCurrentWithin(stdio.Config("twin-current-hours"))
}
// current says whether a durable is live: pulls waiting on it and a delivery within the bound (H-A-472 (1)).
func current(info *jetstream.ConsumerInfo, now time.Time, within time.Duration) bool {
return info != nil && info.NumWaiting > 0 && info.Delivered.Last != nil && now.Sub(*info.Delivered.Last) < within
}
func lastDelivery(info *jetstream.ConsumerInfo) string {
if info == nil || info.Delivered.Last == nil {
return "never"
}
return info.Delivered.Last.UTC().Format(time.RFC3339)
}
// acceptedModules reads the keeper's accepted set: every module it heard as accepted, by name (its state plans, §538).
type acceptedModules func() (map[string]keeper.Planned, error)
// refuseNewForm refuses a stream the keeper made for a module's bus state, naming the tool that removes it.
func refuseNewForm(newForm heldEntries, stream string) error {
if newForm == nil || stream == "" {
return nil
}
held, err := newForm()
if err != nil {
return fmt.Errorf("whether %s is a module's kept data of the new form cannot be read (%v), so nothing was removed", stream, err)
}
for module, a := range held {
for local, m := range a.Made {
for _, o := range m.Plan.Objects {
if o.Stream() == stream {
return fmt.Errorf("%s is %s's kept data %q, which the bus module made: it is removed only by nats_drop (an orphan, on the operator's warrant) or rebuilt by nats_recreate, never by this tool; nothing was removed", stream, module, local)
}
}
}
}
return nil
}
// StreamPurged is what nats_stream_purge answers and says.
type StreamPurged struct {
Stream string `json:"stream"`
Below uint64 `json:"below"`
Why string `json:"why"`
DryRun bool `json:"dry_run"`
First uint64 `json:"first_seq"`
Last uint64 `json:"last_seq"`
Before uint64 `json:"messages_before"`
After uint64 `json:"messages_after"`
Purged uint64 `json:"purged"`
Said string `json:"said"`
At time.Time `json:"at"`
}
// PurgeStream removes the messages of one named stream below a sequence, keeping that sequence and every later one,
// after reading the stream, and says so: a work queue whose old asks nobody waits for any more is emptied up to the
// first ask still wanted (issue 1952's removal tools, one more of their kind). The stream and its consumers stay.
func PurgeStream(ctx context.Context, bus Bus, said Said, a map[string]any) (any, error) {
w, err := why(a)
if err != nil {
return nil, err
}
stream := arg(a, "stream")
if !name.MatchString(stream) {
return nil, errors.New("stream is required, one stream's name (letters, digits, - and _): nothing was purged")
}
below, ok := a["below"].(float64)
if !ok || below < 2 || below != float64(uint64(below)) {
return nil, errors.New("below is required, the first sequence kept (a whole number above 1): nothing was purged")
}
dry, _ := a["dry_run"].(bool)
js, closeBus, err := bus(ctx)
if err != nil {
return nil, err
}
defer closeBus()
out := StreamPurged{Stream: stream, Below: uint64(below), Why: w, DryRun: dry, At: time.Now().UTC()}
sctx, cancel := step(ctx)
s, err := js.Stream(sctx, stream)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the stream %s could not be read, so nothing was purged", stream))
}
sctx, cancel = step(ctx)
info, err := s.Info(sctx)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the stream %s could not be read, so nothing was purged", stream))
}
out.First, out.Last, out.Before = info.State.FirstSeq, info.State.LastSeq, info.State.Msgs
if out.Below > out.Last+1 {
return nil, fmt.Errorf("%s ends at sequence %d: below %d would purge it whole, which is not this tool's; nothing was purged", stream, out.Last, out.Below)
}
if dry {
out.Said = fmt.Sprintf("%s holds %d messages, sequences %d to %d; those below %d would be purged", stream, out.Before, out.First, out.Last, out.Below)
return out, nil
}
sctx, cancel = step(ctx)
err = s.Purge(sctx, jetstream.WithPurgeSequence(out.Below))
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the messages of %s below %d were not purged", stream, out.Below))
}
sctx, cancel = step(ctx)
info, err = s.Info(sctx)
cancel()
if err != nil {
return nil, unanswered(err, fmt.Sprintf("the purge of %s below %d was accepted but could not be confirmed", stream, out.Below))
}
if info.State.FirstSeq < out.Below && info.State.Msgs > 0 {
return nil, fmt.Errorf("%s still starts at sequence %d after the purge below %d was accepted", stream, info.State.FirstSeq, out.Below)
}
out.After = info.State.Msgs
if out.Before > out.After {
out.Purged = out.Before - out.After
}
out.Said = fmt.Sprintf("%s: %d messages below sequence %d purged, %d kept", stream, out.Purged, out.Below, out.After)
if err := said(streamPurged, out); err != nil {
return nil, fmt.Errorf("the messages of %s below %d WERE purged (%s) but the audit event could not be said: %w", stream, out.Below, w, err)
}
return out, nil
}