Records, files and sign-ins

Keeping an app's records in its own store, the files they point at in mounts (a folder, a GitHub repo, an S3 or GCS bucket, or a SharePoint or OneDrive folder), and the sign-ins that reach them in connections, through a small notes app.

Picture a notes app. Each note has a title, an author and a date, and the app keeps those in its own store, the way it keeps anything else. The note’s text is a different matter. One team wants its notes in a folder on the server. Another wants them in a private GitHub repo, where each save is a commit they can review. So the app keeps the text in a mount, and the record says which mount and which path.

goapplib’s storage module splits things three ways:

  • Records live in the app’s own store. The library never sees them.
  • Files live in mounts. A mount is a named place: a folder, a GitHub repo, a prefix in an S3 or GCS bucket, or a folder in SharePoint or OneDrive. A file in one is mount://<name>/<path>.
  • Sign-ins live in connections. A connection is a sign-in the server holds for a service, such as a GitHub token or an AWS key. Its record names where the token is, such as the environment variable env:NOTES_GITHUB_TOKEN, and never holds the token.

The storage module is its own Go module, so an app that wants it adds a second go get:

go get github.com/panyam/goapplib/storage

The app

Here is the whole app, docsite/examples/notes in goapplib’s repo. Its test and the storage exercise compile and run it, so this is the code that runs:

// Package notes is the example app on the storage guide page. It keeps its own records, one per
// note, in a JSON file of its own. It keeps each note's text in a mount: a folder on the server, or
// a GitHub repo it reaches through a connection. A connection's record names where its token is,
// and never holds it.
//
// The storage exercise (exercise/exercise_test.go, `make exercise-storage`) runs it against a fake
// GitHub and restarts it over the same folders.
package notes

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io/fs"
	"net/http"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/panyam/goapplib/storage/blobs"
	"github.com/panyam/goapplib/storage/connections"
	connstore "github.com/panyam/goapplib/storage/connections/fsstore"
	"github.com/panyam/goapplib/storage/mounts"
	"github.com/panyam/goapplib/storage/mounts/folder"
	mountstore "github.com/panyam/goapplib/storage/mounts/fsstore"
	"github.com/panyam/goapplib/storage/mounts/github"
)

// Config says where the app keeps things. Everything lives on disk, so a restart over the same
// Config sees the same notes, mounts and connections.
type Config struct {
	// StoreDir holds the app's notes.json, the mount and connection records, the blob store for
	// GitHub snapshots, and their folder views.
	StoreDir string

	// NotesDir is the folder the fixed "local" mount serves.
	NotesDir string

	// GitHubAPI is GitHub's API root. Empty means api.github.com, and the exercise sets a fake's.
	GitHubAPI string
}

// Note is the app's own record of a note. The text isn't in it. Mount and Path say where it is.
type Note struct {
	ID      string    `json:"id"`
	Title   string    `json:"title"`
	Author  string    `json:"author"`
	Mount   string    `json:"mount"`
	Path    string    `json:"path"`
	Created time.Time `json:"created"`
}

// NoteWithText is a note and its text, as GET /notes/{id} answers it.
type NoteWithText struct {
	Note
	Text string `json:"text"`
}

// App is the notes app: its records, a mounts registry, and a connection store.
type App struct {
	records string
	mounts  *mounts.Registry
	conns   connections.Store
	mu      sync.Mutex
}

// Open builds the app over cfg's folders, creating them as needed.
func Open(cfg Config) (*App, error) {
	mountRecords, err := mountstore.New(filepath.Join(cfg.StoreDir, "mounts"))
	if err != nil {
		return nil, err
	}
	connRecords, err := connstore.New(filepath.Join(cfg.StoreDir, "connections"))
	if err != nil {
		return nil, err
	}
	blobStore, err := blobs.NewDir(filepath.Join(cfg.StoreDir, "blobs"))
	if err != nil {
		return nil, err
	}
	ghOpts := []github.Option{github.WithViews(filepath.Join(cfg.StoreDir, "views"))}
	if cfg.GitHubAPI != "" {
		ghOpts = append(ghOpts, github.WithBaseURL(cfg.GitHubAPI))
	}
	a := &App{records: filepath.Join(cfg.StoreDir, "notes.json"), conns: connRecords}
	tokens := connections.NewService(connRecords)
	a.mounts = mounts.NewRegistry(mountRecords,
		[]mounts.Driver{folder.New(), github.New(blobStore, ghOpts...)},
		mounts.WithFixed(mounts.Mount{Name: "local", Kind: mounts.KindFolder, Source: cfg.NotesDir, Mode: mounts.ModeLive}),
		mounts.WithCredentials(tokens.Credentials),
		mounts.WithInUse(a.pointsInto),
	)
	return a, nil
}

// Handler serves the app's JSON API.
func (a *App) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /notes", a.listNotes)
	mux.HandleFunc("POST /notes", a.createNote)
	mux.HandleFunc("GET /notes/{id}", a.readNote)
	mux.HandleFunc("GET /mounts", a.listMounts)
	mux.HandleFunc("POST /mounts", a.createMount)
	mux.HandleFunc("DELETE /mounts/{name}", a.deleteMount)
	mux.HandleFunc("GET /connections", a.listConnections)
	mux.HandleFunc("POST /connections", a.putConnection)
	mux.HandleFunc("GET /files/{mount}/{path...}", a.readFile)
	return mux
}

// createNote writes the text into the mount first, and keeps the record only if that worked. In
// a GitHub mount the write is a commit.
func (a *App) createNote(w http.ResponseWriter, r *http.Request) {
	var in struct{ Title, Author, Mount, Text string }
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	id := make([]byte, 4)
	rand.Read(id)
	n := Note{ID: hex.EncodeToString(id), Title: in.Title, Author: in.Author, Mount: in.Mount, Created: time.Now().UTC()}
	n.Path = "notes/" + n.ID + ".md"
	_, err := a.mounts.Put(r.Context(), n.Mount, mounts.PutRequest{Path: n.Path, Data: []byte(in.Text), Message: "Add note: " + n.Title})
	if err != nil {
		fail(w, err)
		return
	}
	a.mu.Lock()
	defer a.mu.Unlock()
	all, err := a.load()
	if err == nil {
		err = a.save(append(all, n))
	}
	if err != nil {
		fail(w, err)
		return
	}
	reply(w, n)
}

func (a *App) listNotes(w http.ResponseWriter, r *http.Request) {
	a.mu.Lock()
	all, err := a.load()
	a.mu.Unlock()
	if err != nil {
		fail(w, err)
		return
	}
	reply(w, all)
}

// readNote finds the record, then reads the text from wherever the record says it is.
func (a *App) readNote(w http.ResponseWriter, r *http.Request) {
	a.mu.Lock()
	all, err := a.load()
	a.mu.Unlock()
	if err != nil {
		fail(w, err)
		return
	}
	for _, n := range all {
		if n.ID != r.PathValue("id") {
			continue
		}
		text, err := fs.ReadFile(a.mounts.FS(r.Context()), n.Mount+"/"+n.Path)
		if err != nil {
			fail(w, err)
			return
		}
		reply(w, NoteWithText{Note: n, Text: string(text)})
		return
	}
	fail(w, mounts.ErrNotFound)
}

// readFile answers a file's bytes, or a folder's names as JSON.
func (a *App) readFile(w http.ResponseWriter, r *http.Request) {
	u, err := mounts.NewURI(r.PathValue("mount"), r.PathValue("path"))
	if err != nil {
		fail(w, err)
		return
	}
	name := u.Mount
	if u.Path != "" {
		name += "/" + u.Path
	}
	fsys := a.mounts.FS(r.Context())
	if ents, err := fs.ReadDir(fsys, name); err == nil {
		names := []string{}
		for _, e := range ents {
			names = append(names, e.Name())
		}
		reply(w, names)
		return
	}
	b, err := fs.ReadFile(fsys, name)
	if err != nil {
		fail(w, err)
		return
	}
	w.Write(b)
}

func (a *App) listMounts(w http.ResponseWriter, r *http.Request) {
	ms, err := a.mounts.List(r.Context())
	if err != nil {
		fail(w, err)
		return
	}
	reply(w, ms)
}

// createMount makes a GitHub mount. The registry resolves its ref and, for a snapshot, downloads
// the commit through the mount's connection, before it writes the record. The request names the
// repo but never the kind, so a client can't ask for a folder on the server.
func (a *App) createMount(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Name       string
		Source     string
		Ref        string
		Mode       mounts.Mode
		Connection string
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	m, err := a.mounts.Create(r.Context(), mounts.Mount{Name: in.Name, Kind: mounts.KindGitHub,
		Source: in.Source, Ref: in.Ref, Mode: in.Mode, Connection: in.Connection})
	if err != nil {
		fail(w, err)
		return
	}
	reply(w, m)
}

func (a *App) deleteMount(w http.ResponseWriter, r *http.Request) {
	if err := a.mounts.Delete(r.Context(), r.PathValue("name")); err != nil {
		fail(w, err)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

// pointsInto is the registry's in-use check: a mount any note lives in can't be deleted.
func (a *App) pointsInto(ctx context.Context, name string) (bool, error) {
	a.mu.Lock()
	defer a.mu.Unlock()
	all, err := a.load()
	for _, n := range all {
		if n.Mount == name {
			return true, err
		}
	}
	return false, err
}

func (a *App) listConnections(w http.ResponseWriter, r *http.Request) {
	cs, err := a.conns.ListConnections(r.Context(), "")
	if err != nil {
		fail(w, err)
		return
	}
	reply(w, cs)
}

// putConnection saves a connection record. The store validates it, so a record holding a pasted
// token, rather than a reference such as env:NAME, is refused.
func (a *App) putConnection(w http.ResponseWriter, r *http.Request) {
	var c connections.Connection
	if err := json.NewDecoder(r.Body).Decode(&c); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	c.Created = time.Now().UTC()
	if err := a.conns.PutConnection(r.Context(), c); err != nil {
		fail(w, err)
		return
	}
	reply(w, c)
}

// load and save keep every note in one JSON file, written through a temp file and a rename. A
// real app keeps them in its database.
func (a *App) load() ([]Note, error) {
	b, err := os.ReadFile(a.records)
	if errors.Is(err, fs.ErrNotExist) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	var all []Note
	return all, json.Unmarshal(b, &all)
}

func (a *App) save(all []Note) error {
	b, err := json.MarshalIndent(all, "", "  ")
	if err != nil {
		return err
	}
	tmp := a.records + ".tmp"
	if err := os.WriteFile(tmp, b, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, a.records)
}

func reply(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(v)
}

// fail maps the storage errors onto HTTP statuses, the way an app maps them onto its transport.
func fail(w http.ResponseWriter, err error) {
	code := http.StatusInternalServerError
	switch {
	case errors.Is(err, mounts.ErrNotFound), errors.Is(err, connections.ErrNotFound), errors.Is(err, fs.ErrNotExist):
		code = http.StatusNotFound
	case errors.Is(err, mounts.ErrInvalidArgument), errors.Is(err, mounts.ErrInvalidPath), errors.Is(err, connections.ErrInvalid):
		code = http.StatusBadRequest
	case errors.Is(err, mounts.ErrExists), errors.Is(err, mounts.ErrConflict), errors.Is(err, mounts.ErrFixed),
		errors.Is(err, mounts.ErrInUse), errors.Is(err, mounts.ErrReadOnly):
		code = http.StatusConflict
	case errors.Is(err, mounts.ErrUnavailable):
		code = http.StatusBadGateway
	}
	http.Error(w, err.Error(), code)
}

Open builds everything from folders under StoreDir, so a restart over the same Config sees the same notes, mounts and connections. It makes three stores and a registry:

  • mountstore keeps the runtime mounts’ records, one YAML file each.
  • connstore keeps the connection records, one YAML file each.
  • blobs.NewDir keeps GitHub snapshots’ files, each stored once under its SHA-256.

The registry joins them with two drivers, folder and github. WithFixed adds the local folder mount, which comes from the server’s configuration and never from a request. WithCredentials hands the registry the connections service’s Credentials, so the GitHub driver sends the mount’s connection token with each request.

Writing and reading a note

createNote writes the text into the mount first, then saves the record. If the write fails, there’s no record pointing at nothing. In the local folder mount, the write is a file. In a GitHub mount, the write is a commit on the branch.

readNote reads the record, then reads the text through FS, which serves every mount as one fs.FS, with each mount as a folder at the top. So local/notes/1a2b3c4d.md and shared/notes/5e6f7a8b.md read the same way, whichever kind of mount each one is.

Pinned or live

A GitHub mount has one of two modes, and the app picks one when it makes the mount:

  • A snapshot pins the commit the ref pointed at when the mount was made. The driver downloads that commit’s files into the blob store once. From then on, the mount serves those bytes, after a restart too, without asking GitHub again.
  • A live mount reads the branch’s latest commit on every open, and each write is one commit on it.

Pin a mount when a record has to keep meaning the same bytes. agni saves circuit designs that point into a repo, and a design made last month should still open the files it was made from, even after the repo moves on. Use live when the app edits the files, as this notes app does.

A live write passes the version of the file it read. If someone changed the file since, GitHub refuses the commit, and the registry returns mounts.ErrConflict. So two people saving the same note can’t silently overwrite each other.

Large files in Git LFS

Say a team keeps its board files in Git LFS. GitHub’s tarball, raw host and Contents API all hand back a short pointer file in place of each LFS file. The GitHub driver sees a pointer, fetches the real file from the repo’s LFS storage with the mount’s token, and checks it against the pointer’s size and SHA-256. So a snapshot, a live read and a read at an older commit all give the real bytes, and the app does nothing extra. When the object can’t be fetched, the read fails with mounts.ErrLFS and names the path, so a short pointer never passes for the file.

A folder mount over a checkout made without git lfs pull holds the same pointers, with no remote to fetch from. Reading one fails with mounts.ErrLFS, which tells the person to run git lfs pull.

Mounting a bucket

A bucket mount works like a GitHub mount, with a prefix in place of a repo. The S3 and GCS drivers are their own modules, so an app that doesn’t use them never downloads a cloud SDK:

go get github.com/panyam/goapplib/storage/drivers/s3
go get github.com/panyam/goapplib/storage/drivers/gcs

The app adds them to the registry beside the others:

reg := mounts.NewRegistry(mountRecords,
	[]mounts.Driver{folder.New(), github.New(blobStore), s3.New(blobStore), gcs.New(blobStore)},
	mounts.WithCredentials(tokens.Credentials))
reg.Create(ctx, mounts.Mount{Name: "jetson", Kind: mounts.KindS3,
	Source: "s3://designs/boards/jetson", Mode: mounts.ModeSnapshot, Connection: "aws-prod"})

A bucket has no commit to pin, so a snapshot pins each object instead. It records each object’s version id where the bucket keeps versions, or its ETag where it doesn’t. With versions on, the snapshot keeps reading the old bytes after someone overwrites an object. With them off, it can’t, so reading a changed object fails with mounts.ErrConflict and names the path, and never serves the new bytes as the old ones. A live mount reads each object’s latest version.

SharePoint and OneDrive

The msgraph driver, storage/drivers/msgraph, mounts a folder in a SharePoint document library or a OneDrive through Microsoft Graph. A source names the drive and the folder, such as msgraph://sites/<site-id>/drives/<drive-id>/root/Boards, or msgraph://me/drive/root/Boards for the signed-in person’s OneDrive. It signs with an entra or entra-user connection. A snapshot pins each file and reads the pinned version from the file’s version history after the file changes. A library that keeps no history fails the read with mounts.ErrConflict, as an unversioned bucket does.

Hearing about changes

An app that follows a branch or a prefix can poll ResolveAt, and a new version means something changed. Each source can also push:

  • GitHub sends a webhook. github.ParsePush checks its signature and returns a mounts.Change.
  • S3 sends object events to SQS or SNS. s3.ParseEvent reads an SQS message, and s3.SNSVerifier.ParseSNS checks an SNS push’s signature first.
  • GCS sends object events through a Pub/Sub push. gcs.ParsePush checks the push’s OIDC token first.
  • Graph sends change notifications to a subscription. msgraph.ParseNotification reads one, and Delta lists what changed since the app’s last token.

Each gives a mounts.Change. Registry.Following turns it into the mounts to check, and a bucket change for one object finds every mount whose prefix holds it. The app then calls ResolveAt on each mount, as it would after a poll.

Blobs in a bucket

The notes app keeps snapshot files in blobs.NewDir, on the server’s disk. A server with no persistent disk, on Kubernetes or Cloud Run, keeps them in a bucket instead, with the same aws or gcp connection:

blobStore, err := s3blobs.New(ctx, "s3://acme-notes/blobs", creds)

gcsblobs.New does the same for gs://. Each blob is stored under its SHA-256, in the layout blobs.Dir uses, so an existing folder copies into a bucket as it is. A bucket can’t make hard links, so a snapshot over a bucket store has no host path. Blobs covers how Put and the sweep work on a bucket.

Connections and secrets

The app saves a connection through PutConnection, and the store validates the record first. A token field has to hold a reference such as env:NOTES_GITHUB_TOKEN or file:/run/secrets/github. A pasted token fails validation, and the app answers 400. So the token never reaches the store, and the store’s folder can be backed up as it is.

The kinds of connection follow the services:

  • github-token is a fixed token, such as a personal access token. github-app is a GitHub App installation, which mints an hour-long token from the App’s private key. github-user is a person’s own GitHub account, connected through OAuth, whose token oneauth keeps sealed and refreshes.
  • aws signs S3 requests with a key pair from secret references, or with the host’s default credential chain, such as an IAM role, and can assume a role on top.
  • gcp sends Cloud Storage a token from a service account key, or from Application Default Credentials, such as workload identity on GKE.
  • entra signs in to Microsoft Graph as an app registration, with a client secret, a certificate, the Azure host’s managed identity, or an AKS workload identity’s token. entra-user is a person’s own Microsoft account, kept and refreshed like github-user.

A public repo or bucket needs no connection. Connections covers each kind, and where a secret can and can’t end up.

Errors

The storage packages return errors that wrap sentinels such as mounts.ErrNotFound and mounts.ErrConflict. fail maps them onto HTTP statuses with errors.Is, the way any app maps them onto its own transport. A private repo the token can’t read answers ErrNotFound, because GitHub answers 404 rather than reveal the repo exists.

Deleting a mount

WithInUse gives the registry the app’s answer to “do any records still point into this mount?” The notes app checks its notes. So deleting a mount that holds a note’s text answers 409, and so does deleting the local mount, which comes from the configuration.

Adding a driver

A driver serves one kind of mount. It implements mounts.Driver, which resolves a ref to a version and opens a mount as an fs.FS. Three optional interfaces sit on top. Writer adds Stat, Put and Delete. Localizer adds HostPath, for code that needs a real file on disk. Preparer adds a step when a mount is made, such as downloading a snapshot. The app passes the driver to NewRegistry beside the others.

A driver gets mounts.Credentials for each call, or nil for a public source, and knows nothing about connections. GitHub takes a bearer token, and S3 takes an AWS key pair or the default chain. One that needs a big SDK goes in its own module under storage/drivers/, as the S3 and GCS drivers do, so apps that don’t use it never download it. Mounts has the contracts, and how the GitHub driver meets them.

Testing against a fake GitHub

storage/mounts/github/githubtest is a fake GitHub that serves a repo’s commits, tarballs and contents from memory, and makes a real commit for each write. A private repo answers only an accepted token, and the fake records the token each request carried. The app’s test uses it, and so does the storage exercise:

make exercise-storage

The exercise writes a note into the folder mount, restarts the app over the same folders, and reads the note back. Then it makes a token connection, writes a note into a private repo on the fake, and pins a snapshot before changing the repo. After a second restart, the snapshot still reads the old commit with no GitHub requests, and the live mount reads the new one. Last, it checks that every request carried the connection’s token, and that the token appears in no file on disk:

exercise-storage: ok   wrote note eb431dc0 into the folder mount at notes/eb431dc0.md
exercise-storage: ok   restarted the app over the same folders
exercise-storage: ok   read note eb431dc0 back after the restart: "eggs, flour, butter"
exercise-storage: ok   made connection acme, whose record names env:NOTES_GITHUB_TOKEN
exercise-storage: ok   wrote note e1289fec to the private repo as commit 1b2349a
exercise-storage: ok   made snapshot mount pinned at commit 1b2349a, then changed the repo
exercise-storage: ok   after a restart, pinned still reads commit 1b2349a with no GitHub requests, and shared reads the latest
exercise-storage: ok   the app holds mounts local (folder live), pinned (github snapshot), shared (github live) and connection acme (github-token)
exercise-storage: ok   every one of 9 requests to GitHub carried the connection's token
exercise-storage: ok   no secret in any of the 8 files on disk
exercise-storage: ok

With GITHUB_TOKEN and STORAGE_EXERCISE_REPO=owner/repo set, it also snapshots a private repo of yours on github.com through a token connection, and lists its top folder.

Further reading

  • The storage module covers why storage is its own module, and how it’s versioned.
  • Mounts, Connections and Blobs cover the design of each package, with its API. Mounts has each driver’s details, the bucket events, and the fakes for tests.