| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- // Package playground runs AGI scripts the way ArozOS does, on the same Otto
- // interpreter, against an in-memory drive and mocked external services. It is
- // compiled to WebAssembly (cmd/agiwasm) for the docs playground, and runs
- // natively in its tests.
- package playground
- import (
- "errors"
- "io/fs"
- "path"
- "sort"
- "strings"
- "sync"
- "time"
- )
- // File is one entry of the playground drive as the page stores it.
- type File struct {
- Path string `json:"path"` // vpath, e.g. "user:/Desktop/a.txt"
- Dir bool `json:"dir,omitempty"`
- Data []byte `json:"data,omitempty"`
- Mtime int64 `json:"mtime,omitempty"` // unix milliseconds
- }
- // Roots the drive knows. user:/ and tmp:/ are the drives a script may use
- // through filelib; web:/ holds the WebApp's own files (./web on a server),
- // which scripts reach only through includes(), execd() and appdata.
- var Roots = []string{"user", "tmp", "web"}
- var (
- errNotExist = fs.ErrNotExist
- errIsDir = errors.New("is a directory")
- errNotDir = errors.New("not a directory")
- errNoRoot = errors.New("unknown root")
- errNotEmpty = errors.New("directory not empty")
- )
- type node struct {
- dir bool
- data []byte
- mtime time.Time
- }
- // memFS is the drive: every entry keyed by its clean vpath. A root's own key
- // is "user:/". It is safe for concurrent use (execd children share it).
- type memFS struct {
- mu sync.Mutex
- nodes map[string]*node
- touched map[string]bool // vpaths written or removed during the run
- }
- func newMemFS(files []File) *memFS {
- m := &memFS{nodes: map[string]*node{}, touched: map[string]bool{}}
- for _, r := range Roots {
- m.nodes[r+":/"] = &node{dir: true}
- }
- for _, f := range files {
- root, rel, err := splitVpath(f.Path)
- if err != nil {
- continue
- }
- key := joinKey(root, rel)
- mt := time.UnixMilli(f.Mtime)
- if f.Mtime == 0 {
- mt = time.Now()
- }
- m.mkdirAllLocked(root, path.Dir(rel), mt, false)
- if f.Dir {
- m.nodes[key] = &node{dir: true, mtime: mt}
- } else {
- m.nodes[key] = &node{data: f.Data, mtime: mt}
- }
- }
- return m
- }
- // splitVpath cleans a vpath into its root and a slash path inside it ("" for
- // the root itself). "user:" alone is the root.
- func splitVpath(vpath string) (string, string, error) {
- vpath = strings.ReplaceAll(vpath, "\\", "/")
- i := strings.Index(vpath, ":")
- if i <= 0 {
- return "", "", errNoRoot
- }
- root := vpath[:i]
- ok := false
- for _, r := range Roots {
- if r == root {
- ok = true
- }
- }
- if !ok {
- return "", "", errNoRoot
- }
- rel := strings.TrimPrefix(path.Clean("/"+vpath[i+1:]), "/")
- return root, rel, nil
- }
- func joinKey(root, rel string) string {
- if rel == "" || rel == "." {
- return root + ":/"
- }
- return root + ":/" + rel
- }
- // Clean returns the canonical form of a vpath, or "" when it names no root.
- func Clean(vpath string) string {
- root, rel, err := splitVpath(vpath)
- if err != nil {
- return ""
- }
- return joinKey(root, rel)
- }
- func (m *memFS) lookup(vpath string) (string, *node, error) {
- root, rel, err := splitVpath(vpath)
- if err != nil {
- return "", nil, err
- }
- key := joinKey(root, rel)
- return key, m.nodes[key], nil
- }
- func (m *memFS) Stat(vpath string) (dir bool, size int64, mtime time.Time, err error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- _, n, err := m.lookup(vpath)
- if err != nil {
- return false, 0, time.Time{}, err
- }
- if n == nil {
- return false, 0, time.Time{}, errNotExist
- }
- return n.dir, int64(len(n.data)), n.mtime, nil
- }
- func (m *memFS) Exists(vpath string) bool {
- _, _, _, err := m.Stat(vpath)
- return err == nil
- }
- func (m *memFS) IsDir(vpath string) bool {
- d, _, _, err := m.Stat(vpath)
- return err == nil && d
- }
- func (m *memFS) ReadFile(vpath string) ([]byte, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- _, n, err := m.lookup(vpath)
- if err != nil {
- return nil, err
- }
- if n == nil {
- return nil, errNotExist
- }
- if n.dir {
- return nil, errIsDir
- }
- return append([]byte(nil), n.data...), nil
- }
- // WriteFile behaves like os.WriteFile: the parent folder must exist.
- func (m *memFS) WriteFile(vpath string, data []byte) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- key, n, err := m.lookup(vpath)
- if err != nil {
- return err
- }
- if n != nil && n.dir {
- return errIsDir
- }
- if parent := m.nodes[parentKey(key)]; parent == nil {
- return errNotExist
- } else if !parent.dir {
- return errNotDir
- }
- m.nodes[key] = &node{data: append([]byte(nil), data...), mtime: time.Now()}
- m.touched[key] = true
- return nil
- }
- func parentKey(key string) string {
- i := strings.Index(key, ":/")
- root, rel := key[:i], key[i+2:]
- return joinKey(root, strings.TrimPrefix(path.Dir("/"+rel), "/"))
- }
- // MkdirAll behaves like os.MkdirAll.
- func (m *memFS) MkdirAll(vpath string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- root, rel, err := splitVpath(vpath)
- if err != nil {
- return err
- }
- return m.mkdirAllLocked(root, rel, time.Now(), true)
- }
- func (m *memFS) mkdirAllLocked(root, rel string, mt time.Time, track bool) error {
- if rel == "" || rel == "." {
- return nil
- }
- parts := strings.Split(rel, "/")
- for i := range parts {
- key := joinKey(root, strings.Join(parts[:i+1], "/"))
- if n := m.nodes[key]; n != nil {
- if !n.dir {
- return errNotDir
- }
- continue
- }
- m.nodes[key] = &node{dir: true, mtime: mt}
- if track {
- m.touched[key] = true
- }
- }
- return nil
- }
- // Remove behaves like os.Remove: a folder must be empty.
- func (m *memFS) Remove(vpath string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- key, n, err := m.lookup(vpath)
- if err != nil {
- return err
- }
- if n == nil {
- return errNotExist
- }
- if strings.HasSuffix(key, ":/") {
- return errors.New("cannot remove a root")
- }
- if n.dir && len(m.childrenLocked(key)) > 0 {
- return errNotEmpty
- }
- delete(m.nodes, key)
- m.touched[key] = true
- return nil
- }
- // RemoveAll removes a path and everything below it.
- func (m *memFS) RemoveAll(vpath string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- key, n, err := m.lookup(vpath)
- if err != nil || n == nil {
- return err
- }
- if strings.HasSuffix(key, ":/") {
- return errors.New("cannot remove a root")
- }
- prefix := key + "/"
- for k := range m.nodes {
- if k == key || strings.HasPrefix(k, prefix) {
- delete(m.nodes, k)
- m.touched[k] = true
- }
- }
- return nil
- }
- // childrenLocked lists the direct children of a folder key, sorted by name.
- func (m *memFS) childrenLocked(key string) []string {
- prefix := key
- if !strings.HasSuffix(prefix, "/") {
- prefix += "/"
- }
- var out []string
- for k := range m.nodes {
- if k == key || !strings.HasPrefix(k, prefix) {
- continue
- }
- if !strings.Contains(k[len(prefix):], "/") {
- out = append(out, k)
- }
- }
- sort.Strings(out)
- return out
- }
- // Entry describes a file for listings.
- type Entry struct {
- Vpath string
- Name string
- Dir bool
- Size int64
- Mtime time.Time
- }
- func (m *memFS) entryLocked(key string) Entry {
- n := m.nodes[key]
- name := path.Base(key[strings.Index(key, ":/")+1:])
- if strings.HasSuffix(key, ":/") {
- name = strings.TrimSuffix(key, ":/")
- }
- return Entry{Vpath: key, Name: name, Dir: n.dir, Size: int64(len(n.data)), Mtime: n.mtime}
- }
- // ReadDir lists a folder, sorted by name like os.ReadDir.
- func (m *memFS) ReadDir(vpath string) ([]Entry, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- key, n, err := m.lookup(vpath)
- if err != nil {
- return nil, err
- }
- if n == nil {
- return nil, errNotExist
- }
- if !n.dir {
- return nil, errNotDir
- }
- var out []Entry
- for _, k := range m.childrenLocked(key) {
- out = append(out, m.entryLocked(k))
- }
- return out, nil
- }
- // Walk lists a path and everything below it in lexical order, the path
- // itself first, like filepath.Walk.
- func (m *memFS) Walk(vpath string) ([]Entry, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- key, n, err := m.lookup(vpath)
- if err != nil {
- return nil, err
- }
- if n == nil {
- return nil, errNotExist
- }
- var out []Entry
- var visit func(k string)
- visit = func(k string) {
- out = append(out, m.entryLocked(k))
- if m.nodes[k].dir {
- for _, c := range m.childrenLocked(k) {
- visit(c)
- }
- }
- }
- visit(key)
- return out, nil
- }
- // Glob matches the last element of pattern against the entries of its
- // folder, like filepath.Glob for a pattern with wildcards in the file name
- // only (what filelib.glob supports).
- func (m *memFS) Glob(pattern string) ([]Entry, error) {
- root, rel, err := splitVpath(pattern)
- if err != nil {
- return nil, err
- }
- if _, err := path.Match(path.Base("/"+rel), ""); err != nil {
- return nil, err
- }
- dir := joinKey(root, strings.TrimPrefix(path.Dir("/"+rel), "/"))
- base := path.Base("/" + rel)
- m.mu.Lock()
- defer m.mu.Unlock()
- if n := m.nodes[dir]; n == nil || !n.dir {
- return nil, nil
- }
- var out []Entry
- for _, k := range m.childrenLocked(dir) {
- e := m.entryLocked(k)
- if ok, _ := path.Match(base, e.Name); ok {
- out = append(out, e)
- }
- }
- return out, nil
- }
- // UsedBytes is the size of every file under a root.
- func (m *memFS) UsedBytes(root string) int64 {
- m.mu.Lock()
- defer m.mu.Unlock()
- var total int64
- for k, n := range m.nodes {
- if strings.HasPrefix(k, root+":/") {
- total += int64(len(n.data))
- }
- }
- return total
- }
- // Changes reports what the run created, changed or removed: the files to
- // send back to the page (with their data) and the vpaths that are gone.
- func (m *memFS) Changes() (written []File, removed []string) {
- m.mu.Lock()
- defer m.mu.Unlock()
- keys := make([]string, 0, len(m.touched))
- for k := range m.touched {
- keys = append(keys, k)
- }
- sort.Strings(keys)
- for _, k := range keys {
- n := m.nodes[k]
- if n == nil {
- removed = append(removed, k)
- continue
- }
- written = append(written, File{Path: k, Dir: n.dir, Data: n.data, Mtime: n.mtime.UnixMilli()})
- }
- return written, removed
- }
- // isHiddenPath mirrors hidden.IsHidden(path, true): any element starting
- // with a dot hides the entry.
- func isHiddenPath(vpath string) bool {
- _, rel, err := splitVpath(vpath)
- if err != nil {
- return false
- }
- for _, p := range strings.Split(rel, "/") {
- if strings.HasPrefix(strings.TrimSpace(p), ".") {
- return true
- }
- }
- return false
- }
|