Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/plan9/synfs/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186409 max_deposit = "6000000ugnot"
synfs.gno
// Package synfs builds a synthetic, read-only ninep file server whose contents
// are computed by a function at read time.
//
// This is the package that makes the rest of the suite adoptable. Plan 9's
// device drivers are not storage, they are code behind a name: reading
// /dev/time runs a function. A realm that wants to publish its state as a
// browsable tree does the same thing here, in a few lines, and gets ls, cat,
// stat and mountability for free:
//
// t := synfs.New("dev", "g1...", func() int64 { return runtime.ChainHeight() })
// t.Root().
// Add("sysname", func() string { return runtime.ChainID() }).
// Add("height", func() string { return strconv.FormatInt(runtime.ChainHeight(), 10) })
//
// The tree is READ-ONLY by construction, which is what makes it safe to hand
// to another realm's namespace: every method is free of side effects, so it
// can be called from a frame that does not own these objects.
//
// A synthetic file reports Qid.Version 0 forever. Its contents can change on
// every block, so a version would be a lie; clients that need change detection
// should read the file.
//
// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research
// Center at Bell Labs; the name and the marks are theirs, and the copyright is
// held by the Plan 9 Foundation (https://p9f.org). This package is not
// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9
// code: it borrows the vocabulary so that the design reads without a glossary,
// and it is an homage, asking what that ecosystem's spirit looks like on a
// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.
package synfs
import (
"gno.land/p/nt/avl/v0"
ninep "gno.land/p/nym-moultest123/x/plan9/ninep/v0"
)
// ReadFn computes a whole file.
type ReadFn func() string
// RangeFn serves a 9P read window directly, for files that are cheaper (or
// only possible) to generate a slice at a time, such as an endless one.
type RangeFn func(off, count int64) (string, error)
// Tree owns the qid allocator, the clock and the owner name shared by every
// node in one synthetic server.
type Tree struct {
root *Dir
next uint64
clock func() int64
uid string
}
// New returns a tree whose root directory is named name, owned by uid, using
// clock (normally the block height) as every node's mtime. clock may be nil,
// in which case the mtime is zero.
func New(name, uid string, clock func() int64) *Tree {
t := &Tree{clock: clock, uid: uid}
t.root = t.NewDir(name)
return t
}
// Root returns the tree's root directory.
func (t *Tree) Root() *Dir { return t.root }
// Uid returns the owner stamped on every node.
func (t *Tree) Uid() string { return t.uid }
func (t *Tree) now() int64 {
if t.clock == nil {
return 0
}
return t.clock()
}
func (t *Tree) qid(dir bool) ninep.Qid {
t.next++
qt := ninep.QTFILE
if dir {
qt = ninep.QTDIR
}
return ninep.Qid{Type: qt, Version: 0, Path: t.next}
}
// NewDir returns a detached directory belonging to this tree. Attach it with
// AddDir.
func (t *Tree) NewDir(name string) *Dir {
return &Dir{
tree: t,
name: name,
perm: ninep.DMDIR | 0555,
qid: t.qid(true),
children: avl.NewTree(),
}
}
// Dir is a synthetic directory. Its children are held in an avl tree, so a
// listing is ordered by name and identical on every node.
type Dir struct {
tree *Tree
name string
perm ninep.Perm
qid ninep.Qid
children *avl.Tree // name -> ninep.File
}
// Add attaches a read-only file computed by fn, mode 0444. It returns the
// directory, so calls chain.
func (d *Dir) Add(name string, fn ReadFn) *Dir {
return d.AddPerm(name, 0444, fn)
}
// AddPerm is Add with an explicit mode.
func (d *Dir) AddPerm(name string, perm ninep.Perm, fn ReadFn) *Dir {
whole := fn
return d.AddRange(name, perm, func(off, count int64) (string, error) {
return ninep.Slice(whole(), off, count), nil
})
}
// AddRange attaches a file that serves a read window itself. Use it for a file
// with no natural end, where materialising the whole thing would be wrong.
func (d *Dir) AddRange(name string, perm ninep.Perm, fn RangeFn) *Dir {
if !ninep.ValidName(name) {
panic("synfs: invalid file name: " + name)
}
d.children.Set(name, &file{
tree: d.tree,
name: name,
perm: perm &^ ninep.DMDIR,
qid: d.tree.qid(false),
fn: fn,
})
return d
}
// AddDir attaches a subdirectory built with Tree.NewDir.
func (d *Dir) AddDir(sub *Dir) *Dir {
if !ninep.ValidName(sub.name) {
panic("synfs: invalid directory name: " + sub.name)
}
d.children.Set(sub.name, sub)
return d
}
// AddFile attaches any ninep.File under the given name, which is how a
// synthetic tree splices in a tree served by something else.
func (d *Dir) AddFile(name string, f ninep.File) *Dir {
if !ninep.ValidName(name) {
panic("synfs: invalid file name: " + name)
}
d.children.Set(name, f)
return d
}
// Names returns the directory's entries, in order. Useful for a file that
// wants to describe its own directory, as /dev/drivers does.
func (d *Dir) Names() []string {
out := []string{}
d.children.Iterate("", "", func(k string, _ any) bool {
out = append(out, k)
return false
})
return out
}
// Stat implements ninep.File.
func (d *Dir) Stat() ninep.Stat {
return ninep.Stat{
Qid: d.qid,
Mode: d.perm,
Mtime: d.tree.now(),
Name: d.name,
Uid: d.tree.uid,
Gid: d.tree.uid,
Muid: d.tree.uid,
}
}
// Walk implements ninep.File.
func (d *Dir) Walk(name string) (ninep.File, error) {
if !ninep.ValidName(name) {
return nil, ninep.ErrBadName
}
v := d.children.Get(name)
if v == nil {
return nil, ninep.ErrNotExist
}
return v.(ninep.File), nil
}
// Read implements ninep.File.
func (d *Dir) Read(off, count int64) (string, error) { return "", ninep.ErrIsDir }
// ReadDir implements ninep.File.
func (d *Dir) ReadDir() ([]ninep.Stat, error) {
out := []ninep.Stat{}
d.children.Iterate("", "", func(_ string, v any) bool {
out = append(out, v.(ninep.File).Stat())
return false
})
return out, nil
}
type file struct {
tree *Tree
name string
perm ninep.Perm
qid ninep.Qid
fn RangeFn
}
func (f *file) Stat() ninep.Stat {
// A synthetic file has no stored length. 9P servers for such files report
// zero rather than run the generator just to measure it, and so does this.
return ninep.Stat{
Qid: f.qid,
Mode: f.perm,
Mtime: f.tree.now(),
Name: f.name,
Uid: f.tree.uid,
Gid: f.tree.uid,
Muid: f.tree.uid,
}
}
func (f *file) Walk(name string) (ninep.File, error) { return nil, ninep.ErrNotDir }
func (f *file) Read(off, count int64) (string, error) { return f.fn(off, count) }
func (f *file) ReadDir() ([]ninep.Stat, error) { return nil, ninep.ErrNotDir }
synfs_test.gno
package synfs
import (
"strconv"
"strings"
"testing"
ninep "gno.land/p/nym-moultest123/x/plan9/ninep/v0"
)
func fixedClock(h int64) func() int64 { return func() int64 { return h } }
func TestTreeShape(t *testing.T) {
tr := New("dev", "sys", fixedClock(42))
tr.Root().
Add("sysname", func() string { return "gnoland-1" }).
Add("height", func() string { return "42" })
st := tr.Root().Stat()
if st.Name != "dev" {
t.Errorf("root name %q", st.Name)
}
if !st.IsDir() {
t.Error("root should be a directory")
}
if st.Mtime != 42 {
t.Errorf("mtime %d, want 42", st.Mtime)
}
if st.Mode.String() != "dr-xr-xr-x" {
t.Errorf("mode %q, want dr-xr-xr-x", st.Mode.String())
}
}
func TestReadComputed(t *testing.T) {
height := int64(100)
tr := New("dev", "sys", func() int64 { return height })
tr.Root().Add("height", func() string { return strconv.FormatInt(height, 10) })
f, err := tr.Root().Walk("height")
if err != nil {
t.Fatalf("walk: %v", err)
}
got, _ := ninep.ReadAll(f)
if got != "100" {
t.Errorf("got %q", got)
}
// The generator runs on every read, so the file follows the chain.
height = 101
got, _ = ninep.ReadAll(f)
if got != "101" {
t.Errorf("after the block advanced: got %q", got)
}
if v := f.Stat().Qid.Version; v != 0 {
t.Errorf("a synthetic file pins version 0, got %d", v)
}
}
func TestReadWindow(t *testing.T) {
tr := New("dev", "sys", nil)
tr.Root().Add("msg", func() string { return "hello world" })
f, _ := tr.Root().Walk("msg")
tests := []struct {
off, count int64
want string
}{
{0, -1, "hello world"},
{0, 5, "hello"},
{6, 5, "world"},
{99, 5, ""},
}
for _, tt := range tests {
got, err := f.Read(tt.off, tt.count)
if err != nil {
t.Fatalf("read: %v", err)
}
if got != tt.want {
t.Errorf("Read(%d,%d): got %q, want %q", tt.off, tt.count, got, tt.want)
}
}
}
func TestAddRangeEndlessFile(t *testing.T) {
// /dev/zero has no end: it must serve the window rather than a value.
tr := New("dev", "sys", nil)
tr.Root().AddRange("zero", 0444, func(off, count int64) (string, error) {
if count < 0 {
count = 0
}
return strings.Repeat("0", int(count)), nil
})
f, _ := tr.Root().Walk("zero")
got, _ := f.Read(0, 4)
if got != "0000" {
t.Errorf("got %q", got)
}
got, _ = f.Read(0, -1)
if got != "" {
t.Errorf("an unbounded read of an endless file must not hang or grow: got %q", got)
}
}
func TestReadDirIsOrdered(t *testing.T) {
tr := New("dev", "sys", fixedClock(1))
tr.Root().
Add("zero", func() string { return "" }).
Add("null", func() string { return "" }).
Add("time", func() string { return "" })
ents, err := tr.Root().ReadDir()
if err != nil {
t.Fatalf("readdir: %v", err)
}
want := []string{"null", "time", "zero"}
if len(ents) != len(want) {
t.Fatalf("got %d entries", len(ents))
}
for i, w := range want {
if ents[i].Name != w {
t.Errorf("entry %d: got %q, want %q", i, ents[i].Name, w)
}
}
if got := tr.Root().Names(); len(got) != 3 || got[0] != "null" {
t.Errorf("Names: %v", got)
}
}
func TestSubdirectories(t *testing.T) {
tr := New("proc", "sys", fixedClock(7))
sub := tr.NewDir("1")
sub.Add("status", func() string { return "running" })
tr.Root().AddDir(sub)
f, err := ninep.Walk(tr.Root(), ninep.Elems("/1/status"))
if err != nil {
t.Fatalf("walk: %v", err)
}
got, _ := ninep.ReadAll(f)
if got != "running" {
t.Errorf("got %q", got)
}
}
func TestErrors(t *testing.T) {
tr := New("dev", "sys", nil)
tr.Root().Add("null", func() string { return "" })
if _, err := tr.Root().Read(0, -1); err != ninep.ErrIsDir {
t.Errorf("read a directory: got %v", err)
}
if _, err := tr.Root().Walk("absent"); err != ninep.ErrNotExist {
t.Errorf("walk missing: got %v", err)
}
if _, err := tr.Root().Walk("a/b"); err != ninep.ErrBadName {
t.Errorf("walk bad name: got %v", err)
}
f, _ := tr.Root().Walk("null")
if _, err := f.Walk("x"); err != ninep.ErrNotDir {
t.Errorf("walk through a file: got %v", err)
}
if _, err := f.ReadDir(); err != ninep.ErrNotDir {
t.Errorf("readdir a file: got %v", err)
}
}
func TestSyntheticTreeIsReadOnly(t *testing.T) {
// The whole point: a synthetic tree implements File and NOT Mutable, so
// it is safe to hand to a namespace owned by somebody else.
tr := New("dev", "sys", nil)
var f ninep.File = tr.Root()
if _, ok := f.(ninep.Mutable); ok {
t.Error("a synthetic tree must not be Mutable")
}
}