Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/pausable/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186405 max_deposit = "7000000ugnot"
pausable.gno
// Package pausable is the switch a realm checks before it acts: a parsed pause
// state, the rule for combining two of them, and the asserts that stop a call.
//
// # Three levels, because "paused" is usually too blunt
//
// Taking a realm fully offline hides the thing people came to read. Most
// incidents only need the writes stopped: a board keeps rendering, an exchange
// keeps quoting, and nothing new lands while the fix is prepared. So the
// levels are Running, ReadOnly and Paused, and a realm normally guards its
// mutating functions with AssertWritable and leaves Render alone.
//
// func Post(cur realm, body string) {
// config.AssertWritable() // aborts while the realm is ReadOnly or Paused
// …
// }
//
// func Render(path string) string {
// return config.TopBlock() + body // the banner explains itself
// }
//
// # It fails closed
//
// MustParse turns a value it does not recognise into Paused, not Running. A
// pause switch that a typo silently disables is not a pause switch, and the
// failure is loud and one transaction from fixed, where the opposite failure
// is silent and discovered during the incident it was meant to cover.
//
// The cost of that choice is a typo taking a realm offline, so the writer is
// expected to validate: Parse reports ok=false and the storing realm refuses
// the write. Validate on the way in, fail closed on the way out.
//
// # The stricter of two states wins
//
// A global pause and a per-realm pause combine with Strictest, so a stale
// per-realm entry can never re-open a realm during a global halt. The cost is
// that exempting one realm from a global pause is not expressible; clear the
// global and set the others instead.
package pausable
import "strings"
// Level is how much of a realm is still allowed to work.
type Level int
const (
// Running is the normal state, and what an unset value means.
Running Level = iota
// ReadOnly still renders and still answers queries; it refuses writes.
ReadOnly
// Paused refuses everything, reads included.
Paused
)
// The canonical spelling of each level, which is what a value round-trips to.
const (
runningWord = "running"
readOnlyWord = "readonly"
pausedWord = "paused"
)
// reasonSep separates the level from the human explanation in a stored value:
// "paused: migrating storage, back in an hour".
const reasonSep = ":"
func (l Level) String() string {
switch l {
case Running:
return runningWord
case ReadOnly:
return readOnlyWord
case Paused:
return pausedWord
default:
// Not reachable through Parse, and not worth panicking over in a
// Render path: an unknown level reads as the strictest one.
return pausedWord
}
}
// AllowsRead reports whether rendering and querying are still allowed.
func (l Level) AllowsRead() bool { return l != Paused }
// AllowsWrite reports whether state-changing calls are still allowed.
func (l Level) AllowsWrite() bool { return l == Running }
// State is a parsed pause setting: a level and an optional reason to show.
//
// The zero State is Running with no reason, which is what an unset setting
// means, so a realm that never configures anything is never paused.
type State struct {
Level Level
Reason string
}
// Parse reads a stored value: "", "running", "readonly", "paused", each
// optionally followed by ": <reason>".
//
// ok is false for anything else. A caller that is STORING the value should
// refuse on !ok; a caller that is READING one should use MustParse, which
// fails closed instead.
func Parse(raw string) (State, bool) {
raw = strings.TrimSpace(raw)
if raw == "" {
return State{}, true
}
word, reason := raw, ""
if i := strings.Index(raw, reasonSep); i >= 0 {
word = strings.TrimSpace(raw[:i])
reason = strings.TrimSpace(raw[i+1:])
}
switch strings.ToLower(word) {
case runningWord:
return State{Level: Running, Reason: reason}, true
case readOnlyWord:
return State{Level: ReadOnly, Reason: reason}, true
case pausedWord:
return State{Level: Paused, Reason: reason}, true
default:
return State{}, false
}
}
// MustParse is Parse for a reader, failing closed: a value it cannot read
// becomes Paused, carrying the raw text as the reason so whoever hits it can
// see what is wrong.
func MustParse(raw string) State {
if s, ok := Parse(raw); ok {
return s
}
return State{Level: Paused, Reason: "unreadable pause setting: " + strings.TrimSpace(raw)}
}
// String renders a State back into a storable value. It round-trips through
// Parse, and the zero State renders empty so an unset setting stays unset.
func (s State) String() string {
if s.Level == Running && s.Reason == "" {
return ""
}
if s.Reason == "" {
return s.Level.String()
}
return s.Level.String() + reasonSep + " " + s.Reason
}
// Strictest returns whichever of the two stops more, keeping the reason that
// belongs to the level it returns. On a tie the first argument wins, so a
// caller passing (global, scoped) keeps the global explanation when both say
// the same thing, and the scoped one when it is the stricter.
func Strictest(a, b State) State {
if b.Level > a.Level {
return b
}
return a
}
// AllowsRead reports whether rendering and querying are still allowed.
func (s State) AllowsRead() bool { return s.Level.AllowsRead() }
// AllowsWrite reports whether state-changing calls are still allowed.
func (s State) AllowsWrite() bool { return s.Level.AllowsWrite() }
// IsPaused reports whether anything at all is being held back. It is true for
// ReadOnly as well as Paused, because the question a caller usually means by
// "is it paused" is "is it behaving normally".
func (s State) IsPaused() bool { return s.Level != Running }
// AssertWritable aborts unless writes are allowed. This is the one a realm
// puts at the top of every state-changing function.
func (s State) AssertWritable() {
if !s.AllowsWrite() {
panic(s.message("writes are paused"))
}
}
// AssertReadable aborts unless reads are allowed. Most realms do not want this
// in Render: a page that aborts tells a reader nothing, while Notice tells
// them what happened and when to come back.
func (s State) AssertReadable() {
if !s.AllowsRead() {
panic(s.message("paused"))
}
}
func (s State) message(what string) string {
if s.Reason == "" {
return what
}
return what + reasonSep + " " + s.Reason
}
// Notice is the banner a Render puts above its content, or "" while running.
//
// It is a markdown blockquote, so it reads as set apart from the page without
// needing any style the renderer might not have.
func (s State) Notice() string {
if s.Level == Running {
return ""
}
head := "**Paused.** This realm is not accepting anything right now."
if s.Level == ReadOnly {
head = "**Read-only.** This realm is still readable, but not accepting changes."
}
if s.Reason == "" {
return "> " + head
}
// The reason is text a manager typed, and it lands inside a blockquote
// where a newline would end the quote and let the rest render as page
// content. Folding it to a single line keeps the banner one block.
return "> " + head + " " + oneLine(s.Reason)
}
// oneLine collapses every run of whitespace, newlines included, into single
// spaces.
func oneLine(s string) string {
var b strings.Builder
space := false
for i := 0; i < len(s); i++ {
c := s[i]
if c == ' ' || c == '\t' || c == '\n' || c == '\r' {
space = true
continue
}
if space && b.Len() > 0 {
b.WriteByte(' ')
}
space = false
b.WriteByte(c)
}
return b.String()
}
pausable_test.gno
package pausable
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestParse(t *testing.T) {
tests := []struct {
raw string
wantLevel Level
wantReason string
wantOK bool
}{
{"", Running, "", true},
{" ", Running, "", true},
{"running", Running, "", true},
{"readonly", ReadOnly, "", true},
{"paused", Paused, "", true},
{"Paused", Paused, "", true}, // case-insensitive
{" paused ", Paused, "", true},
{"paused: migrating storage", Paused, "migrating storage", true},
{"readonly: spaced ", ReadOnly, "spaced", true},
{"running: nothing wrong", Running, "nothing wrong", true},
// A reason containing the separator keeps everything after the first
// one, so a URL or a time survives.
{"paused: back at 14:00 UTC", Paused, "back at 14:00 UTC", true},
// Not recognised. These are exactly the values that must NOT read as
// Running.
{"yes", Running, "", false},
{"true", Running, "", false},
{"1", Running, "", false},
{"stop", Running, "", false},
{"read-only", Running, "", false},
}
for _, tt := range tests {
got, ok := Parse(tt.raw)
uassert.Equal(t, tt.wantOK, ok, "Parse("+tt.raw+") ok")
if !ok {
continue
}
uassert.Equal(t, int(tt.wantLevel), int(got.Level), "Parse("+tt.raw+") level")
uassert.Equal(t, tt.wantReason, got.Reason, "Parse("+tt.raw+") reason")
}
}
// TestMustParseFailsClosed is the whole safety argument of this package. Every
// value here is something a person might plausibly type, and every one of them
// has to stop the realm rather than quietly leave it running.
func TestMustParseFailsClosed(t *testing.T) {
for _, raw := range []string{"yes", "true", "1", "on", "stop", "PAUSE", "pasued"} {
got := MustParse(raw)
uassert.Equal(t, int(Paused), int(got.Level), "MustParse("+raw+") must fail closed")
uassert.False(t, got.AllowsWrite(), "MustParse("+raw+") must refuse writes")
uassert.True(t, len(got.Reason) > 0, "MustParse("+raw+") must say why")
}
// And the values it does understand are untouched.
uassert.Equal(t, int(Running), int(MustParse("").Level))
uassert.Equal(t, int(ReadOnly), int(MustParse("readonly").Level))
}
func TestAllows(t *testing.T) {
tests := []struct {
level Level
read bool
write bool
isPaused bool
}{
{Running, true, true, false},
{ReadOnly, true, false, true},
{Paused, false, false, true},
}
for _, tt := range tests {
s := State{Level: tt.level}
uassert.Equal(t, tt.read, s.AllowsRead(), tt.level.String()+" read")
uassert.Equal(t, tt.write, s.AllowsWrite(), tt.level.String()+" write")
uassert.Equal(t, tt.isPaused, s.IsPaused(), tt.level.String()+" isPaused")
}
}
func TestStrictest(t *testing.T) {
run := State{Level: Running}
ro := State{Level: ReadOnly, Reason: "scoped"}
paused := State{Level: Paused, Reason: "global"}
uassert.Equal(t, int(ReadOnly), int(Strictest(run, ro).Level))
uassert.Equal(t, int(ReadOnly), int(Strictest(ro, run).Level))
uassert.Equal(t, int(Paused), int(Strictest(paused, ro).Level))
uassert.Equal(t, int(Paused), int(Strictest(ro, paused).Level))
// A stale per-realm entry can never re-open a realm during a global halt.
// This is the property the whole precedence rule exists for.
uassert.Equal(t, int(Paused), int(Strictest(paused, run).Level),
"a per-realm 'running' cannot defeat a global pause")
// The reason travels with the level that won.
uassert.Equal(t, "global", Strictest(paused, ro).Reason)
uassert.Equal(t, "scoped", Strictest(run, ro).Reason)
// On a tie the first argument wins, so a caller passing (global, scoped)
// keeps the global explanation.
a := State{Level: Paused, Reason: "first"}
b := State{Level: Paused, Reason: "second"}
uassert.Equal(t, "first", Strictest(a, b).Reason)
}
func TestStringRoundTrips(t *testing.T) {
for _, raw := range []string{"", "readonly", "paused", "paused: migrating storage"} {
s, ok := Parse(raw)
uassert.True(t, ok, "Parse("+raw+")")
again, ok := Parse(s.String())
uassert.True(t, ok, "Parse(String()) for "+raw)
uassert.Equal(t, int(s.Level), int(again.Level), "level round-trip for "+raw)
uassert.Equal(t, s.Reason, again.Reason, "reason round-trip for "+raw)
}
// The zero State renders empty, so an unset setting stays unset rather
// than being written back as the word "running".
uassert.Equal(t, "", State{}.String())
uassert.Equal(t, "running: why", State{Reason: "why"}.String())
}
func TestAsserts(cur realm, t *testing.T) {
State{}.AssertWritable()
State{}.AssertReadable()
State{Level: ReadOnly}.AssertReadable()
uassert.PanicsWithMessage(t, cur, "writes are paused", func() {
State{Level: ReadOnly}.AssertWritable()
})
uassert.PanicsWithMessage(t, cur, "writes are paused: migrating", func() {
State{Level: Paused, Reason: "migrating"}.AssertWritable()
})
uassert.PanicsWithMessage(t, cur, "paused: migrating", func() {
State{Level: Paused, Reason: "migrating"}.AssertReadable()
})
}
func TestNotice(t *testing.T) {
uassert.Equal(t, "", State{}.Notice(), "a running realm shows no banner")
uassert.Equal(t,
"> **Read-only.** This realm is still readable, but not accepting changes.",
State{Level: ReadOnly}.Notice())
uassert.Equal(t,
"> **Paused.** This realm is not accepting anything right now. back in an hour",
State{Level: Paused, Reason: "back in an hour"}.Notice())
}
// TestNoticeStaysOneBlock covers the reason a manager typed. It lands inside a
// markdown blockquote, where a newline ends the quote and lets the rest render
// as ordinary page content, so it is folded to one line.
func TestNoticeStaysOneBlock(t *testing.T) {
s := State{Level: Paused, Reason: "line one\n\nline two\n# not a heading"}
uassert.Equal(t,
"> **Paused.** This realm is not accepting anything right now. line one line two # not a heading",
s.Notice())
}