Playground
example_test.gno
package kitindexdemo
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
// seed builds a fixed board without crossing anything, so an example can set up
// its own state.
//
// An Example has no realm token, so it cannot call Post, and the state the
// tests happen to leave is not a contract. Writing the globals directly is the
// escape hatch AGENTS.md names: same package, no crossing, fully deterministic.
func seed() {
reset()
add := func(who address, tag, body string, height int64) {
id := notes.Add(¬e{Author: who, Tag: tag, Body: body, Height: height})
if err := byTag.Add(tag, id); err != nil {
panic(err)
}
if err := byAuthor.Add(who.String(), id); err != nil {
panic(err)
}
}
add(alice, "gno", "the index is two containers and one function", 123)
add(bob, "gno", "and the function is where the correctness is", 124)
add(alice, "storage", "you are charged for objects, not for data", 125)
}
// The root page carries TWO consecutive blank lines, which an // Output: block
// can never pin: gno collapses them, exactly as Go does. So the root is
// asserted with uassert.Equal and a backtick literal, which preserves them,
// and only the pages without that shape get an Example.
//
// This is the order of preference AGENTS.md names, and the root page is the
// case that forces the second rung.
func TestRenderRoot(t *testing.T) {
seed()
want := `# Notes by tag
3 note(s) under 2 tag(s), by 2 author(s).
| tag | notes |
| --- | --- |
| [gno](/r/moul/x/kitindexdemo/v0:tag/gno) | 2 |
| [storage](/r/moul/x/kitindexdemo/v0:tag/storage) | 1 |
[Post a note](/r/moul/x/kitindexdemo/v0$help&func=Post&body=&tag=)
`
uassert.Equal(t, want, Render(""))
}
// ExampleRender_tag pins one tag's page, which is the lookup the library is for.
func ExampleRender_tag() {
seed()
print(Render("tag/gno"))
// Output:
// # #gno
// | # | author | tag | note | height |
// | --- | --- | --- | --- | --- |
// | 1 | `g1v9kxjc…40gh` | `gno` | the index is two containers and one function | 123 |
// | 2 | `g1vfhkyh…vdhu` | `gno` | and the function is where the correctness is | 124 |
}
gnomod.toml
module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/kitindexdemo/v0" gno = "0.9" private = true [addpkg] creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv" height = 914308 max_deposit = "10000000ugnot"
kitindexdemo.gno
// untrusted-render: the tag is charset-checked to [a-z0-9-] at write time and
// is the only stored string interpolated raw; the body is a caller's text and
// goes through ui.Cell at every call site that renders it.
// Package kitindexdemo is a notes board whose only job is to show
// gno.land/p/moul/kit/index doing the thing a realm with a store always ends
// up needing: answering "every note tagged gno" as cheaply as it answers
// "note 7".
//
// There is no logic of its own here. The records are a kit/store, the two
// lookups are kit/index, the page is kit/ui, and what is worth reading is the
// shape: every write touches the store and both indexes in ONE function, which
// is the entire correctness argument for keeping them in separate containers.
//
// Demo of the p/moul/kit/index library.
package kitindexdemo
import (
"chain/markdown"
"strconv"
"strings"
"chain/runtime"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/index/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
)
// MaxBody is the longest note this realm accepts, in bytes.
//
// A bound rather than none: every byte stored here locks a storage deposit,
// paid by whoever signs the write and refunded to whoever signs the delete
// (EFFECTIVE_GNO.md section 9.2), and an unbounded write is an unbounded
// state the realm carries forever.
const MaxBody = 280
// MaxTagLen bounds the index key for the same reason, and small because a tag
// is a label rather than a sentence.
const MaxTagLen = 24
// PageSize is how many tags the root page shows.
const PageSize = 20
// MaxNotes and MaxPerAuthor bound the WHOLE board, which MaxBody does not.
//
// A per-call length limit bounds one write and nothing else: a caller posting
// one-byte notes in a loop grows the store and both indexes without limit. "An unbounded container a third party can grow is an
// unbounded storage deposit someone is paying for" is a rule this realm exists
// to demonstrate, so it had better obey it.
//
// Two caps rather than one, and what each buys is narrower than it looks.
// MaxNotes bounds the state, which is the property this realm promises.
// MaxPerAuthor stops one ADDRESS, not one actor: addresses are free, so fifty
// fresh ones at twenty notes each still fill the board and lock everyone else
// out until somebody retracts. Keeping a board open to strangers needs
// something a griefer cannot mint for free, a deposit or an expiry, which this
// demo does not carry. Retracting frees a slot, so neither cap is a one-way door.
//
// MaxPerAuthor is answered by byAuthor.Count, which is the index doing the job
// it was added for.
const (
MaxNotes = 1000
MaxPerAuthor = 20
)
type note struct {
Author address
Tag string
Body string
Height int64
}
var (
notes = store.Named("note")
byTag index.Index
byAuthor index.Index
)
// Post files a note under a tag and returns its id.
//
// The store write and both index writes happen here, in this order, in one
// frame. An abort anywhere in it leaves none of them applied, which is what
// makes three containers safe to keep apart.
func Post(cur realm, tag, body string) int64 {
who := caller(cur)
tag = normaliseTag(tag)
assertBody(body)
assertRoom(who)
id := notes.Add(¬e{
Author: who,
Tag: tag,
Body: body,
Height: runtime.ChainHeight(),
})
mustIndex(byTag.Add(tag, id))
mustIndex(byAuthor.Add(who.String(), id))
return int64(id)
}
// Retract removes a note. Only its author may, and the store and both indexes
// are unwound together.
func Retract(cur realm, id int64) {
who := caller(cur)
sid, ok := store.ParseID(strconv.FormatInt(id, 10))
if !ok {
panic("kitindexdemo: not an id: " + strconv.FormatInt(id, 10))
}
n, ok := notes.Get(sid)
if !ok {
panic("kitindexdemo: note #" + sid.String() + " not found")
}
rec := n.(*note)
if rec.Author != who {
panic("kitindexdemo: note #" + sid.String() + " is not yours")
}
notes.Remove(sid)
byTag.Remove(rec.Tag, sid)
byAuthor.Remove(rec.Author.String(), sid)
}
// caller is the one place this realm decides who is acting: the realm token is
// checked before it is walked, because an unchecked token is not a caller.
func caller(cur realm) address {
if !cur.IsCurrent() {
panic("kitindexdemo: spoofed realm")
}
return cur.Previous().Address()
}
func mustIndex(err error) {
if err != nil {
panic(err)
}
}
// normaliseTag lowercases and validates the tag.
//
// Validated at WRITE time rather than escaped at render time, deliberately: a
// tag is also an index key and a path segment, so a tag that could carry a
// pipe or a slash would break the table and the URL as well as the page. The
// charset is the narrowest thing that still reads as a label.
func normaliseTag(tag string) string {
tag = strings.ToLower(strings.TrimSpace(tag))
if tag == "" || len(tag) > MaxTagLen {
panic("kitindexdemo: a tag is 1 to " + strconv.Itoa(MaxTagLen) + " characters")
}
for _, r := range tag {
switch {
case r >= 'a' && r <= 'z', r >= '0' && r <= '9', r == '-':
default:
panic("kitindexdemo: a tag is [a-z0-9-], got " + strconv.Quote(tag))
}
}
return tag
}
// assertRoom refuses a write the board has no room for, globally or for this
// address. Checked before the store write, so a refusal costs the caller the
// gas of three reads and nothing is half-applied.
func assertRoom(who address) {
if notes.Len() >= MaxNotes {
panic("kitindexdemo: the board is full at " + strconv.Itoa(MaxNotes) +
" notes; retract one to free a slot")
}
if n := byAuthor.Count(who.String()); n >= MaxPerAuthor {
panic("kitindexdemo: " + who.String() + " already has " + strconv.Itoa(n) +
" notes, the limit is " + strconv.Itoa(MaxPerAuthor))
}
}
func assertBody(body string) {
if strings.TrimSpace(markdown.StripBidiAndZeroWidth(body)) == "" {
panic("kitindexdemo: the body is empty")
}
if len(body) > MaxBody {
panic("kitindexdemo: the body is " + strconv.Itoa(len(body)) +
" bytes, the limit is " + strconv.Itoa(MaxBody))
}
}
kitindexdemo_test.gno
package kitindexdemo
import (
"strconv"
"strings"
"testing"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/index/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
)
// reset puts the realm back to its init() state.
//
// Realm globals persist for the whole test binary and examples run after every
// Test, so without this an ExampleRender's pinned output depends silently on
// which tests ran before it. Assigning the globals directly is allowed here:
// same package, and it crosses nothing.
func reset() {
notes = store.Named("note")
byTag = index.Index{}
byAuthor = index.Index{}
}
func TestPostIndexesInBothDirections(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
id := Post(cross(cur), "gno", "first")
uassert.Equal(t, 1, notes.Len())
uassert.Equal(t, 1, byTag.Count("gno"))
uassert.Equal(t, 1, byAuthor.Count(alice.String()))
got := byTag.Lookup("gno")
urequire.Equal(t, 1, len(got))
uassert.Equal(t, store.ID(id).String(), got[0].String())
}
func TestTagIsNormalisedAtWriteTime(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Post(cross(cur), " GNO ", "mixed case and spaces")
uassert.Equal(t, 1, byTag.Count("gno"))
uassert.Equal(t, 1, byTag.Keys())
}
// The tag is an index key AND a path segment, so it is validated rather than
// escaped: a tag carrying a pipe or a slash breaks the table and the URL, not
// only the sentence.
func TestTagRefusals(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
for _, tc := range []struct {
name string
tag string
want string
}{
{"empty", "", "a tag is 1 to 24 characters"},
{"blank", " ", "a tag is 1 to 24 characters"},
{"too long", "aaaaaaaaaaaaaaaaaaaaaaaaa", "a tag is 1 to 24 characters"},
{"a pipe", "a|b", "a tag is [a-z0-9-]"},
{"a slash", "a/b", "a tag is [a-z0-9-]"},
{"markdown", "a]b", "a tag is [a-z0-9-]"},
{"a space inside", "a b", "a tag is [a-z0-9-]"},
} {
t.Run(tc.name, func(t *testing.T) {
uassert.AbortsContains(t, cur, tc.want, func() {
Post(cross(cur), tc.tag, "body")
})
})
}
uassert.Equal(t, 0, notes.Len())
}
func TestBodyRefusals(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "the body is empty", func() {
Post(cross(cur), "gno", " ")
})
long := ""
for i := 0; i <= MaxBody; i++ {
long += "x"
}
uassert.AbortsContains(t, cur, "the limit is 280", func() {
Post(cross(cur), "gno", long)
})
uassert.Equal(t, 0, notes.Len())
}
func TestOnlyTheAuthorMayRetract(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
id := Post(cross(cur), "gno", "alice's note")
testing.SetRealm(testing.NewUserRealm(bob))
uassert.AbortsContains(t, cur, "is not yours", func() {
Retract(cross(cur), id)
})
uassert.Equal(t, 1, notes.Len())
testing.SetRealm(testing.NewUserRealm(alice))
Retract(cross(cur), id)
uassert.Equal(t, 0, notes.Len())
}
// The store and both indexes have to come apart together, or a later Render
// walks ids the store no longer holds.
func TestRetractUnwindsEveryContainer(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
id := Post(cross(cur), "gno", "one")
Post(cross(cur), "gno", "two")
Retract(cross(cur), id)
uassert.Equal(t, 1, notes.Len())
uassert.Equal(t, 1, byTag.Count("gno"))
uassert.Equal(t, 1, byAuthor.Count(alice.String()))
}
func TestRetractRefusals(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "not found", func() { Retract(cross(cur), 99) })
uassert.AbortsContains(t, cur, "not an id", func() { Retract(cross(cur), 0) })
uassert.AbortsContains(t, cur, "not an id", func() { Retract(cross(cur), -1) })
}
// A body is a caller's markdown and must not be able to write the page around
// it. ui.Cell is what stops a pipe from opening a column.
func TestARenderedBodyCannotBreakTheTable(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
Post(cross(cur), "gno", "a | b [x](http://evil)")
got := Render("tag/gno")
uassert.False(t, strings.Contains(got, "| a | b ["),
"the raw body must not reach the table")
uassert.True(t, strings.Contains(got, "\\|"),
"the pipe must be escaped")
}
func TestRenderOfAnUnknownPage(t *testing.T) {
reset()
uassert.True(t, strings.Contains(Render("nope"), "Not found"))
uassert.True(t, strings.Contains(Render("tag"), "No tag given."))
uassert.True(t, strings.Contains(Render("author"), "No author given."))
}
// MaxBody bounds one write. These bound the bill, which is the thing the realm
// actually pays.
func TestPerAuthorCap(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
for i := 0; i < MaxPerAuthor; i++ {
Post(cross(cur), "gno", "note "+strconv.Itoa(i))
}
uassert.AbortsContains(t, cur, "the limit is 20", func() {
Post(cross(cur), "gno", "one too many")
})
// Another address is unaffected, which is the whole reason the cap is
// per author and not only global.
testing.SetRealm(testing.NewUserRealm(bob))
Post(cross(cur), "gno", "bob still fits")
uassert.Equal(t, MaxPerAuthor+1, notes.Len())
}
// Retracting frees a slot, so the cap is not a one-way door.
func TestRetractingFreesASlot(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
first := Post(cross(cur), "gno", "note 0")
for i := 1; i < MaxPerAuthor; i++ {
Post(cross(cur), "gno", "note "+strconv.Itoa(i))
}
uassert.AbortsContains(t, cur, "the limit is 20", func() {
Post(cross(cur), "gno", "blocked")
})
Retract(cross(cur), first)
Post(cross(cur), "gno", "now it fits")
uassert.Equal(t, MaxPerAuthor, notes.Len())
}
// The page number is user input on the Render path. One outside 1..Pages is
// clamped into it, so it never renders an empty board under a footer that
// says "page -1 of 2".
func TestRenderClampsThePageNumber(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
for i := 0; i < PageSize; i++ {
Post(cross(cur), "t"+strconv.Itoa(i), "x")
}
testing.SetRealm(testing.NewUserRealm(bob))
Post(cross(cur), "t-last", "x")
urequire.Equal(t, 2, byTag.Pages(PageSize))
first, last := Render("?page=1"), Render("?page=2")
uassert.Equal(t, first, Render("?page=-1"))
uassert.Equal(t, first, Render("?page=0"))
uassert.Equal(t, last, Render("?page=999"))
uassert.True(t, strings.Contains(last, "page 2 of 2"))
}
// Links are absolute. gnoweb serves this realm at .../kitindexdemo/v0, so a
// "./kitindexdemo:tag/x" link resolves to .../kitindexdemo/kitindexdemo:tag/x,
// a package that does not exist.
func TestRenderLinksAreAbsolute(cur realm, t *testing.T) {
reset()
testing.SetRealm(testing.NewUserRealm(alice))
for i := 0; i <= PageSize; i++ {
if i == MaxPerAuthor {
testing.SetRealm(testing.NewUserRealm(bob))
}
Post(cross(cur), "t"+strconv.Itoa(i), "x")
}
out := Render("")
uassert.True(t, strings.Contains(out, "](/r/moul/x/kitindexdemo/v0:tag/t0)"), out)
uassert.True(t, strings.Contains(out, "](/r/moul/x/kitindexdemo/v0:?page=2)"), out)
uassert.False(t, strings.Contains(out, "](./"), out)
}
// realmURL must follow the module line, or a version bump ships dead links.
func TestRealmURLMatchesTheModule(cur realm, t *testing.T) {
uassert.Equal(t, "gno.land"+realmURL, cur.PkgPath())
}
// The global cap is what bounds the realm's whole storage bill, so its
// refusal is pinned, and pinned as refusing BEFORE any write: the store and
// both indexes are exactly as full as they were.
func TestTheBoardIsFull(cur realm, t *testing.T) {
reset()
for i := 0; i < MaxNotes; i++ {
notes.Add(¬e{Author: bob, Tag: "gno", Body: "x"})
}
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "the board is full", func() {
Post(cross(cur), "gno", "one too many")
})
uassert.Equal(t, MaxNotes, notes.Len())
uassert.Equal(t, 0, byTag.Len())
uassert.Equal(t, 0, byAuthor.Count(alice.String()))
}
render.gno
package kitindexdemo
import (
"strconv"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/store/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"
)
// realmURL is this realm as gnoweb serves it. Links are absolute because the
// path ends in /v0: a relative "./kitindexdemo:tag/x" resolves against the
// parent directory to .../kitindexdemo/kitindexdemo:tag/x, which does not
// exist. Not derived at runtime: a Render has no cur, and CurrentRealm there
// is the caller. TestRealmURLMatchesTheModule pins it to the module line.
const realmURL = "/r/moul/x/kitindexdemo/v0"
// Render is the whole public surface. Three pages: the tag list, one tag, one
// author.
//
// Every row goes through ui.NewTable rather than concatenated pipes, and every
// caller string through ui.Cell, because a public path is immutable and a
// Render that ships wrong ships forever.
func Render(path string) string {
req := realmpath.Parse(path)
switch req.PathPart(0) {
case "":
return renderIndex(req)
case "tag":
return renderTag(req.PathPart(1))
case "author":
return renderAuthor(req.PathPart(1))
default:
return md.H1("Not found") + ui.Empty("No such page.")
}
}
func renderIndex(req *realmpath.Request) string {
// The page number is user input: clamp it into 1..pages, or ?page=-1
// renders an empty board under a footer saying "page -1 of 2".
pages := byTag.Pages(PageSize)
page := 1
if n, err := strconv.Atoi(req.Query.Get("page")); err == nil {
page = n
}
if page < 1 {
page = 1
}
if page > pages {
page = pages
}
t := ui.NewTable("tag", "notes")
for _, e := range byTag.Page(page, PageSize) {
t.Row(
md.Link(e.Key, realmURL+":tag/"+e.Key),
strconv.Itoa(len(e.IDs)),
)
}
return ui.Join("\n",
md.H1("Notes by tag"),
md.Paragraph(strconv.Itoa(notes.Len())+" note(s) under "+
strconv.Itoa(byTag.Keys())+" tag(s), by "+
strconv.Itoa(byAuthor.Keys())+" author(s)."),
t.OrEmpty("Nothing posted yet."),
pager(page, pages),
md.Paragraph(ui.Action("Post a note", "Post", "tag", "", "body", "")),
)
}
func renderTag(tag string) string {
if tag == "" {
return md.H1("Not found") + ui.Empty("No tag given.")
}
return md.H1("#"+ui.Cell(tag)) + notesTable(byTag.Lookup(tag), "No notes under this tag.")
}
func renderAuthor(addr string) string {
if addr == "" {
return md.H1("Not found") + ui.Empty("No author given.")
}
return md.H1("Notes by "+ui.AddrOf(addr)) +
notesTable(byAuthor.Lookup(addr), "This address has posted nothing.")
}
// notesTable renders a set of ids as rows, skipping any id the store no longer
// holds.
//
// Skipping rather than panicking: an index and a store are two containers, and
// a reader should see the records that exist rather than a page that aborts.
// Retract keeps the two in step, so a miss here means a bug worth surviving,
// not worth hiding.
func notesTable(hits []store.ID, empty string) string {
t := ui.NewTable("#", "author", "tag", "note", "height")
for _, id := range hits {
v, ok := notes.Get(id)
if !ok {
continue
}
n := v.(*note)
t.Row(
id.String(),
ui.Addr(n.Author),
md.InlineCode(n.Tag),
ui.Cell(n.Body),
strconv.FormatInt(n.Height, 10),
)
}
return t.OrEmpty(empty)
}
// pager renders the previous/next links, or nothing when there is one page.
func pager(page, pages int) string {
if pages < 2 {
return ""
}
out := ""
if page > 1 {
out += md.Link("previous", realmURL+":?page="+strconv.Itoa(page-1)) + " "
}
out += "page " + strconv.Itoa(page) + " of " + strconv.Itoa(pages)
if page < pages {
out += " " + md.Link("next", realmURL+":?page="+strconv.Itoa(page+1))
}
return out
}