Mounts
The design of the storage module's mounts: the record, mount:// URIs, snapshot and live modes, the driver and record-store contracts, the registry, the limits the library enforces, and its errors.
Picture agni saving a circuit design that points at mount://jetson/baseboard.kicad_sch. A month later someone opens it. If jetson reads the repo’s latest commit, the design now means different bytes from the ones it was made from. So agni pins a GitHub mount at the commit it resolved to, and keeps that commit’s files. notation needs the opposite. A notation’s text sits in a repo, a person edits it, and each save should become a new commit on the branch.
A mount is a named place an app’s files live: a folder, a GitHub repo, and later an S3 or GCS bucket. The app keeps its own records in its own store, and they point into mounts by mount:// URI. This page is the design for #152. The storage/mounts package holds the record, the URI rules, the interfaces, the registry and the errors, and they are rendered at the bottom of the page from the source. The folder driver, the GitHub driver and the folder record store are in packages beside it. Connections covers how a mount over a private repo signs in, and the storage module covers where the code lives.
How agni and notation use it ¶
| agni | notation | |
|---|---|---|
| Kinds | folder (from flags), GitHub | GitHub, and later Bitbucket and S3 |
| Mode | snapshot, pinned at a commit | live, at the branch’s head |
| Writes | folder mounts only, through its own code | Put and Delete of one file, each a commit |
| Views | a host path, since it runs kicad-cli and os.Open |
an fs.FS |
| Connection | server-held: an App installation, or a token (agni#1724) | the person’s own GitHub account |
| Record store | one YAML file per mount, shared by agni serve and agnids |
Datastore |
The record and the two modes ¶
Mount keeps the name, the kind, the source, the ref it was asked for, the version that ref resolved to, the mode, the connection and its owner, and for a snapshot the hash of its manifest. ConnectionOwner is empty for a server connection. For a person’s connection it names the person, and only they can open the mount, since only they get its token. The library owns those fields. An app keeps anything else in its own records, keyed by the mount’s name.
- Snapshot. The driver resolves the ref to a version when the mount is made, then serves the files at that version for as long as the mount exists. A GitHub snapshot downloads the commit’s tarball into the blob store (#154). It then writes a manifest of paths and hashes, and keeps the manifest’s hash in the record. After a restart, the manifest rebuilds the view. agni keeps its file list in the record today, and that list can run to 100,000 entries, past Datastore’s 1 MB entity limit. So the list moves into a blob.
- Live. Each open reads the source’s latest version. A driver that implements
Writercan change it. A GitHub write goes through the Contents API, and eachPutorDeleteis one commit. GitHub refuses a write whose file sha isn’t the current one, and the driver returnsErrConflict, so two people saving the same notation can’t silently overwrite each other.
Each driver says which modes it supports. GitHub supports both. A folder is live, and later may also snapshot by hashing its files the way agni’s uploads do.
Version is a string in the driver’s own format. agni checks for 40 hex characters, which fits SHA-1 commits and nothing else. S3 version IDs and SHA-256 git repos don’t fit, so the library leaves the check to the driver.
URIs and names ¶
A file is mount://<name>/<path>. ParseURI takes agni’s rules:
- The path is relative. A leading
/is refused,\becomes/, andpath.Cleanruns before any check. - A path that climbs out with
..is refused, so resolving a URI against a mount’s root can’t reach outside it. - The empty path is the mount’s root, and
Stringwrites it asmount://<name>.
Resolve(ref) reads a reference against a URI the way a browser reads an href against its page, which is how agni’s readers find a schematic’s child sheets and a design’s libraries (#175). A full mount:// URI replaces the whole thing, /x names x from the mount’s root, and anything else resolves against the URI’s folder. A result that climbs out of the mount is ErrInvalidPath. RFC 3986 would drop a leading .. on /../x and read /x, and Resolve refuses it instead, since quietly fixing a traversal attempt hides it. Dir, Base and IsZero round the type out.
A runtime mount’s name, the one a record store keeps, is 1 to 64 characters, a-z and 0-9 first, then also -, _ and .. ValidName checks it, and it keeps a name safe as a folder name, a URL path element and a YAML file name on any OS. A URI takes any name that isn’t empty, . or .. and holds no separator. An app names a fixed mount after a folder, such as agni’s --mount-root, and a folder can have capitals or spaces in its name.
Drivers ¶
A Driver serves one kind. It resolves a ref to a version, and opens a mount as an fs.FS. It gets Credentials from the registry, or nil for a public source, and it knows nothing about connections or viewers.
Each service signs in its own way, so Credentials is an interface with one method, CredentialKind, and a driver type-switches on the value. GitHub and GCS take a bearer token, which BearerCredentials carries. mounts.Bearer(ts) wraps an oauth2.TokenSource, and TokenSourceOf and BearerToken unwrap it. S3 signs each request with SigV4 and has no bearer token, so it takes AWSCredentials: a key pair, or the AWS default chain, with an optional role to assume. That value holds a resolved secret, and its String and GoString leave the secret out. A driver given a kind it can’t sign with returns ErrInvalidArgument, naming the kind. Another package can add a kind by implementing CredentialKind, so this package imports no cloud SDK.
Optional interfaces sit on top:
WriteraddsStat,PutandDeletefor live mounts. A write passesIfMatch, the file’s version fromStat. Empty means create only, andAnyVersionmeans overwrite whatever is there.LocalizeraddsHostPathfor code that needs a real file, such as agni runningkicad-cli. A folder mount has one. A GitHub, S3, GCS or msgraph snapshot has one when its driver has a views folder and a blob store that can link. A mount with no folder here returnsErrNotLocal, so code that needs a host path fails clearly on GAE or in wasm.FetchingLocalizeraddsHostPathWith, which takes the mount’s credentials because it may download the files first, andFetches(m), which says whether it may for that mount. The registry looks up credentials and callsHostPathWithonly for a mountFetchesreports, so a reader with no credentials, such as agnids, still serves an eager snapshot from its view.PrepareraddsPrepare, which the registry calls when a mount is made, afterResolve. A GitHub snapshot downloads its files there and sets the mount’sManifest. IfPreparefails, no record is written.VersionReaderreads a mount’s source at any version, not only the one a snapshot pins (#172). Say agni links a design’s schematic to a repo at a commit, then moves the link to a newer commit. It needs that commit’s files, and it shouldn’t download the sheets that didn’t change.Movessays whether a ref moves: a branch or the default does, and a tag or a commit doesn’t.ListAtlists the regular files at a version under a path, each with a content ID, the git blob id on GitHub.FetchAtputs one file in the blob store and says whether it had to download it.RefListerlists the versions a source has, so an app can offer revisions to link to (#177).ListRefslists tags newest first, or the commits on one branch newest first, a page at a time. EachRefhas the name to put in a mount’sRef, the commit it points at, the commit’s date and the commit’s first line. A source with no history returns an empty page.SourceMatchersays when two sources name one place, where string equality isn’t enough. GitHub’s owner and repo names ignore case, sogithub://Acme/Boardandgithub://acme/boardmatch.WebhookManagermakes a source send the app a webhook on each change, so the app syncs a mount when its branch moves rather than polling it (#185).EnsureWebhookmakes the hook, or updates the one already sending to the same URL, so calling it twice leaves one hook.DeleteWebhookremoves the hooks sending to a URL, and a hook that is already gone isn’t an error. A hook is named by its URL, so the app keeps no hook id.
The folder driver is storage/mounts/folder. Its mounts are live, writable and local, and it refuses a link anywhere in a path, so a link inside the folder can’t reach outside it. A file’s version is the SHA-256 of its contents. A write goes through a temp file and a rename, under a lock per file. So its IfMatch check holds between writers in one process, sharing one folder.Driver. Two processes writing one file can both pass the check, and the second rename wins. By default the folder driver refuses every link. folder.WithLinksInside() lets reads follow a link whose target stays inside the folder, in listings, Open, HostPath, ListAt and FetchAt, so a folder whose libraries are links still reads (#175). A link that leads out, directly or through another link, is still refused and left out of listings, and writes never go through a link. Go’s os.Root decides what stays inside, and it counts a link with an absolute target as leading out, even when the target is inside the folder. A walk in ListAt visits each real folder once, so two links that make a loop don’t repeat it. It’s a VersionReader too, once folder.WithBlobs gives it a blob store. A folder has no history, so every ref moves, and ListAt reads the folder as it is now.
A checkout made without git lfs pull holds a pointer in place of each LFS file, and the folder has no remote to fetch the object from. So Open, FetchAt and HostPath on a file refuse a pointer with ErrLFS, naming the path. HostPath on a folder returns its path without looking inside, so a native tool given a folder can still meet a pointer.
A folder’s version is mtime: and a SHA-256 over each regular file’s path, size and modification time, in path order (#178). Resolve computes it with a walk and reads no file’s contents. Say agni follows a board folder and polls it every few minutes. It calls ResolveAt, and when the version didn’t move it reads nothing more. A touch moves the version without changing any bytes, so a moved version only means “go and look”. A write that keeps both the size and the mtime doesn’t move it, and the driver accepts that. ListAt and FetchAt take "" or an mtime: version and read the folder as it is now, since a folder can’t be read as of an older version. ListRefs returns an empty page.
The GitHub driver is storage/mounts/github, built with a blob store and options for the API root, the HTTP client, the limits and the views folder:
gh := github.New(blobStore, github.WithViews(filepath.Join(storeDir, "views")))
Resolvereads the repo’s default branch when the ref is empty, then asks GitHub which commit the ref points at.- For a snapshot,
Preparestreams the commit’s tarball into the blob store. It keeps regular files only, refuses a path that is absolute, unclean or climbs out, and stops at the limits withErrTooLarge. Then it writes the manifest.Openserves the snapshot from the manifest and the blob store without asking GitHub, after a restart too. - Say a hardware repo holds nine boards. Each board fits the limits, and the repo together doesn’t, so an eager snapshot refuses the mount (agni issue 1877).
github.WithLazySnapshots()makesPreparepin the commit and list its tree, with no download, and leaveManifestempty.Openlists folders from the tree and fetches a file on first open throughFetchAt.HostPathWithfetches the file a path names, or every file under the folder it names, into the view, and links each into place one at a time. The limits apply to that one read, asListAtapplies them to a subtree, so a call for one board works and a call for the repo’s root fails withErrTooLarge. A file already in the view isn’t fetched again. With a views folder, the view is the cache. The listing is kept at<views>/<mount>/<commit>.tree.json, andOpenreads each file through the view too. So after a restart the mount lists, and serves what it fetched, without asking GitHub. A lazy mount has no manifest, soBlobRefskeeps none of its blobs, and a sweep removes them while the view’s hard links keep their contents. A file is fetched again only when its view is gone.Preparealways lists the tree from GitHub with the mount’s credentials, so a new mount is checked against the repo even when a kept listing exists. A snapshot an eager driver made keeps its manifest, so a server can turn the option on over the mounts it has.github.WithLazyPastLimits()makes a mount lazy only when its commit passes the limits.Preparelists the tree first, with each LFS object at its own size, then snapshots a commit that fits whole, and makes one past the limits lazy before downloading anything. A mount under the limits keeps an eager snapshot’s guarantee that its view rebuilds from the blobs alone. A lazy mount whose view folder is lost needs GitHub to list its tree again, though the blobs it fetched are not downloaded again. HostPathon a snapshot builds a folder of hard links to its blobs, at<views>/<name>/<commit>, the first time it is asked. A restart that lost the folder rebuilds it from the manifest.- For a live mount,
Preparefills in the default branch whenRefis empty, since a write commits onto a branch.Openreads the branch through the Contents API on every open.Statreturns a file’s git blob sha, andPutandDeleteeach make one commit. GitHub refuses a stale sha with 409, and an update without a sha with 422, and the driver returnsErrConflictfor both. - For
VersionReader,ListAtreads the trees API once per commit and caches the list per commit and token, so one connection’s list never reaches a caller with another token or none. It leaves out links and submodules, and stops at the limits withErrTooLarge.FetchAtdownloads a file from the raw host by commit and path, which doesn’t count against the API’s hourly limit of 60 requests without a token.WithRawURLsets the host. With a non-default API root, such as GitHub Enterprise, and no raw URL, it uses the git blobs API. Each download is checked against its git blob id before it’s kept. When the blob store is ablobs.Aliases, asblobs.Diris, the driver records each git blob id against its blob, and skips the download of a file it already holds. That’s what makes a second commit’s read cheap. - Say a repo keeps its board files in Git LFS. GitHub’s tarball, raw host and Contents API all send each LFS file as a short pointer, and a reader would get that pointer with no error (#203). So the driver checks every file under 1 KB with
mounts.ParseLFSPointer. A snapshot,FetchAtand a live read each swap a pointer for its object. The driver asks the repo’s LFS batch API, at<host>/<owner>/<repo>.git/info/lfs/objects/batch, with the mount’s token as the basic-auth password. The host ishttps://github.comfor GitHub’s own API, or the API root without/api/v3for an Enterprise host, andWithLFSURLoverrides it. The download goes to thehrefGitHub returns, with only the headers GitHub gives for it. The bytes must match the pointer’s size and SHA-256, and a blob’s hash is that same SHA-256, so an object the blob store holds already isn’t downloaded again. An object’s size counts toward the limits, not the pointer’s. A pointer that can’t be resolved fails the snapshot or the read withErrLFS, naming the path, plusErrNotFoundfor a missing object orErrPermissionDeniedfor a 401 or 403. GitHub answers a repo over its LFS quota with 403 too, and the error carries GitHub’s message, which tells the two apart.ListAtreports an LFS file’s object size, not its pointer’s (#208). When a.gitattributesat the commit hasfilter=lfs, it reads each blob under 1 KB once. Without one, it reads only blobs of 125 to 144 bytes, the size of a pointer with no extension lines. A repo can set its LFS paths in.git/info/attributes, outside the tree, andFetchAtswaps every pointer it meets, soListAthas to look too (#218). It remembers by git blob id whether each blob was a pointer, so a later commit reads only the small blobs that changed. ListRefslists tags through one GraphQL query per page, ordered byTAG_COMMIT_DATE. The REST tags API gives names and commits but no dates, so it can’t order them. GitHub’s GraphQL API refuses a request without a token, so on a mount with no connection the driver lists tags through the REST tags API instead (#182). GitHub orders those by version, newest first, sov1.10comes beforev1.9. They come with no dates, so the driver reads each tag’s commit too, and a page holds at most 10 tags, since every request counts against GitHub’s limit of 60 an hour without a token. When GitHub refuses for that limit, the error says a connection lifts it. GitHub orders by the commit’s day and then by name, so the driver sorts each page by time. Two tags made on one day can still come out of order across a page break. Commits come from the REST commits API, which needs no token for a public repo. The GraphQL endpoint is<root>/graphql, or<host>/api/graphqlfor a GitHub Enterprise root ending in/api/v3.EnsureWebhooklists the repo’s hooks, then updates the one sending to the URL or makes a new one, withcontent_typeset to JSON soParsePushreads each delivery as sent. It always sends the update, since GitHub never shows a hook’s secret. Say a person’s token can read the repo but isn’t an admin on it. GitHub answers 404 from the hooks API, so the driver returnsErrPermissionDeniedfor 404 and 403, with a message naming admin rights or a fine-grained token’s webhooks permission. GitHub’s 422, such as for a URL it won’t send to, becomesErrInvalidArgument. One page of 100 holds every hook, since GitHub allows 20 per event.github.ParsePush(r, secret)reads a GitHub webhook delivery (#179). It checksX-Hub-Signature-256against the raw body in constant time before reading anything from it, reads at most 25 MB, and takes a JSON body or a form-encoded one. It returns aPush, which is amounts.Changeplus GitHub’s delivery id. A bad signature isErrBadSignature(answer 401), a ping isErrPing(answer 200), and any other event isErrNotPush. The app resolves the secret from a secret reference, as connections do.- 404 becomes
ErrNotFound, which is also what a private repo answers without a valid token. Rate limits, rejected tokens and server errors becomeErrUnavailable. An error from the connection’s token source, such as a person who has to connect again, passes through unchanged.
Bucket drivers ¶
Say agni links a design from s3://designs/boards/jetson. A bucket has no commit, since no change spans several objects at once. So Resolve lists the prefix and records each object’s version: its version id where the bucket keeps versions (S3 VersionId, GCS generation), or its ETag where it doesn’t. The listing goes in the blob store, and its hash is the mount’s version. A snapshot’s Prepare points Manifest at a one-entry manifest whose entry is the listing, so BlobRefs keeps the listing through a sweep. Open on a snapshot then reads exactly the listed versions. Where an object is pinned by its ETag and has changed since, opening it fails with an fs.PathError naming the file and wrapping ErrConflict. A snapshot never serves new bytes as the old version. A live mount reads each object’s latest version, and lists a folder each time it is read.
The version doubles as a change check. A poll calls ResolveAt, and a new version means an object under the prefix was added, removed or changed. Bucket event notifications can replace the poll (see Bucket events below). A bucket has no refs, so a non-empty ref is ErrInvalidArgument, and a prefix with no objects under it is ErrNotFound. For VersionReader, ListAt reads a stored listing, each file’s ID is version:<id> or etag:<etag>, and FetchAt copies that pinned version into the blob store.
Say agni syncs a folder of 15 sheets after one of them changes. The sync lists the new version and calls FetchAt for each file, and only the changed sheet downloads (#234). FetchAt records an alias from each object’s identity to its blob: the scheme, bucket and key, plus the version id, or the ETag on a bucket without versions. The next fetch of the same object finds the alias, checks that the store still holds the blob, and returns fetched=false. A snapshot’s Prepare with views does the same. It needs a blob store that keeps aliases, which blobs.Dir does, and blobs.Cached does in its local folder. Another store downloads every file, as before.
storage/mounts/bucket holds this logic once, over a three-method Bucket interface (List, ListDir, Get), and imports no SDK. bucket/buckettest is an in-memory Bucket, with or without versions. The SDK drivers each live in their own module, so an app that doesn’t mount a bucket never downloads an SDK:
s3d := s3.New(blobStore) // github.com/panyam/goapplib/storage/drivers/s3
gcsd := gcs.New(blobStore) // github.com/panyam/goapplib/storage/drivers/gcs
reg := mounts.NewRegistry(store, []mounts.Driver{github, s3d, gcsd}, mounts.WithCredentials(conns.Credentials))
- S3 (
KindS3,s3://<bucket>/<prefix>) signs withAWSCredentials, and with no credentials it reads a public bucket unsigned. It lists withListObjectVersionsand pins eachVersionId. On a bucket with versioning off or suspended, the version id isnull, and it pins the ETag and reads withIf-Match. A connection withouts3:ListBucketVersionsgets a refusal there, and the driver falls back toListObjectsV2and ETags. Clients are kept per set of credentials, so an assumed role’s session is reused until it expires.WithEndpointpoints it at an S3-compatible store such as MinIO, with path-style addressing. - GCS (
KindGCS,gs://<bucket>/<prefix>) signs withBearerCredentials. Every GCS object has a generation, so a snapshot always pins generations. With versioning on, the bucket keeps the old generation, and the snapshot keeps serving it. With versioning off, GCS drops it, and the read fails withErrConflict.
Views of bucket snapshots ¶
Say agni links a folder in S3 as a snapshot, and its engine opens real files. A bucket snapshot’s listing pins each object’s version, but the contents stay in the bucket. A view needs them on disk, so s3.WithViews(dir), gcs.WithViews and msgraph.WithViews (all bucket.WithViews) make Prepare fetch them (#220).
- With a views folder and a store that is a
blobs.Linker,Preparedownloads every listed object at its pinned version into the store. The manifest lists each one underfiles/, beside the listing, soBlobRefskeeps them through a sweep. Creating the mount downloads all of it, up toWithLimits. Openon such a snapshot reads from the blob store and never asks the bucket. A changed object on a bucket without versions no longer fails the read, since the bytes were captured atPrepare.HostPathbuilds<views>/<name>/<version hex>/from links to those blobs the first time it’s asked. A restart that lost the folder rebuilds it from the store, without credentials or the bucket.- An object that changed between
ResolveandPrepareon a bucket without versions failsPreparewithErrConflict, and no record is written. - A live mount, a driver without views, or a store that can’t link returns
ErrNotLocal. So does a snapshot made before the driver had views, since its manifest has no files. Making it again fixes it.
HostPath takes no credentials, so it can’t reach the bucket. The fetch happens in Prepare, which has them. Fetching then also keeps the bytes the listing pinned, where a later fetch would meet ErrConflict on a bucket without versions. GitHub and the bucket drivers share mounts.BuildView, which builds in a temp folder and renames, so nobody sees a half-built view.
With blobs in a bucket, the store is a blobs.Cached (see the blobs page), and the view links to its local copies.
A view downloads the whole source, which suits a tool that opens neighbouring files, as a KiCad project does. Say instead the bucket holds 1000 files and a tool needs one of them on disk. Leave out WithViews, so creating the mount downloads nothing, and fetch that one file at the snapshot’s version:
files, _ := reg.ListAt(ctx, m.Name, m.Version, "board/main.kicad_sch")
h, _, _ := reg.FetchAt(ctx, m.Name, m.Version, files[0])
_ = store.Link(h, filepath.Join(workDir, "main.kicad_sch")) // store is the driver's blobs.Linker
ListAt with a file’s path lists just that file. FetchAt downloads it at the pinned version, so a later change in the bucket doesn’t reach it. The app keeps h in its own records and passes a referrer to Sweep, since the mount’s manifest doesn’t list the file. A mode where HostPath fetches only the files it’s asked for waits on a second app (#225).
Bucket events ¶
Say agni follows s3://designs/boards/jetson, and someone uploads a new power.kicad_sch there. Polling ResolveAt finds it on the next tick. A bucket event finds it within seconds (#210). The bucket sends an event for one object, and each driver module turns that event into a mounts.Change whose Source names the object, such as s3://designs/boards/jetson/power.kicad_sch. bucket.Driver is a mounts.SourceContainer, so Registry.Following returns every mount whose prefix holds the object. Here that’s the jetson mount and a mount of s3://designs, but not one of s3://designs/boards/jet. The change’s Ref and Version are empty, since an event doesn’t say what the listing’s hash becomes. The app calls ResolveAt on each mount it gets back, as it does after a GitHub push.
s3.ParseEvent(body)reads S3’s event JSON, as S3 sends it to SQS, or wrapped in SNS’s envelope. Created and removed objects become changes. S3’s test event and other event types give none. An app polling SQS calls it on each message body.- An SNS subscription pushes to the app over HTTPS.
s3.SNSVerifier.ParseSNS(r)checks the message’s signature first, SignatureVersion 1 (SHA1withRSA) or 2 (SHA256withRSA), against the certificate at itsSigningCertURL. It fetches that certificate only over https from a host namedsns.<region>.amazonaws.com(or.amazonaws.com.cn), before any request, and caches it per URL. Anything else isErrBadSignature. A subscription request returns the message withErrSubscriptionConfirmation. The app callsConfirmSubscriptionto accept it, and that refuses aSubscribeURLthat isn’t on an SNS host too. gcs.ParsePush(r, verifier)reads a Pub/Sub push of a GCS notification.OBJECT_FINALIZE,OBJECT_DELETEandOBJECT_METADATA_UPDATEbecome changes, and other event types give none. The push must carry the subscription’s OIDC token.gcs.GoogleVerifier{Audience, Email}checks it against Google’s keys with oneauth’sclient.VerifyIDToken, which fetches the keys on first use and again on an unknown key id. A missing or refused token isErrUnauthenticated, and a nil verifier isErrInvalidArgument, since an open endpoint would let anyone make the app re-resolve its mounts.
Both run mountstest.RunDriver against in-process fakes, gofakes3 and fake-gcs-server. gofakes3 ignores If-Match on a GET, and the S3 test wraps it to answer 412 as S3 does. Another wrapper refuses ListObjectVersions with 403, so a test checks the fallback to ETag pins. TestLiveS3 and TestLiveGCS read a real bucket when STORAGE_LIVE_S3 or STORAGE_LIVE_GCS names a source, signing with the AWS default chain or Application Default Credentials.
SharePoint and OneDrive ¶
The msgraph driver (KindMSGraph, its own module at storage/drivers/msgraph) reads a folder in a SharePoint document library or a OneDrive through Microsoft Graph, with plain HTTP and no Graph SDK (#206). A source names a drive and a folder in it:
msgraph://sites/<site-id>/drives/<drive-id>/root/Boards
msgraph://drives/<drive-id>/root/Boards
msgraph://me/drive/root/Boards
It implements bucket.Bucket, so snapshots, VersionReader and the contract suite come from the bucket package. The source’s first segment is the “bucket”, and the rest is the key. A listing walks the folder’s children, a folder at a time, following @odata.nextLink. A next link off Graph’s own host fails with ErrUnavailable, so a link in an answer can’t carry the token elsewhere.
A snapshot pins each file by its item id, its content tag, its size and its last-modified time. The content tag is cTag, which Graph changes only when the bytes change, or eTag where Graph sends no cTag, since eTag moves on a rename too. Say a design’s README changes after the snapshot. A pinned read finds that the item’s content tag moved, then looks in the item’s version history for the entry with the pinned modified time and size, and reads that version’s content. A library that keeps no versions has no such entry, and the read fails with ErrConflict and the path named. A snapshot makes no request per file up front. Listing a folder takes one request per page, and only a changed file needs the version lookup.
Graph tracks changes per drive. Delta(ctx, m, creds, token) asks the drive’s delta feed what changed since token, and returns the files under the mount’s folder plus the next token, which the app keeps beside the mount. An empty token returns no items and a token for now. SharePoint leaves the path off a deleted item, so a deletion comes back with its item id and an empty path. A token Graph has forgotten returns msgraph.ErrResyncRequired (Graph’s 410), and the app reads the mount again in full. Change notifications are the push form. CreateSubscription asks Graph to POST to the app’s URL when the drive changes, and RenewSubscription moves its expiry, which Graph caps at about 30 days. The app owns the endpoint: AnswerValidation answers Graph’s validation request as text/plain, and ParseNotification checks each entry’s clientState in constant time and returns a mounts.Change naming the drive root. The driver is a mounts.SourceContainer that turns the bucket rule around: a change to a drive holds every mount in it, so Registry.Following returns each of the app’s mounts in that drive. The app then calls Delta on each to learn which files changed.
The driver signs with BearerCredentials from an entra or entra-user connection. msgraph/graphtest is a fake Graph with drives, paged children, content behind a redirect to a download URL, version history, the delta feed and subscriptions. TestLiveMSGraph reads a real drive when STORAGE_LIVE_MSGRAPH names a source and STORAGE_LIVE_MSGRAPH_TOKEN holds a Graph token.
mountstest.RunDriver is the contract suite for drivers, as RunRecordStore is for stores. A fixture gives a driver, a source holding the files the suite asks for, a missing source, credentials, and a way to change a file. For each mode the driver lists, it checks that Open passes fstest.TestFS, refuses paths that climb, and, after a change, that a live mount shows it and a snapshot doesn’t. A fixture whose snapshots can’t keep old bytes sets SnapshotFailsOnChange, and the suite then wants the read to fail with the path named. HostPaths lists the modes that get a folder on disk. The suite then reads every file through HostPath, refuses paths that climb, and wants ErrNotLocal for the other modes. With Views and Offline set, it removes the views, takes the source away, and still wants the view and Open to give the pinned bytes. The folder, GitHub, S3, GCS and msgraph drivers all run it, and the bucket drivers run it once more with views.
storage/mounts/github/githubtest is a fake GitHub for tests, the library’s and an app’s own. It serves a repo’s commits, branches, tags, trees, blobs, tarballs and contents from memory, the GraphQL tags query, and its raw host at RawURL(), and each write makes a real commit. Tag and SetCommitTime set up a repo’s tags and dates. PushRequest builds a signed push for a branch’s head, and SignedRequest builds any other event, so an app tests its webhook handler end to end. A private repo answers only an accepted token, and every request is recorded with the token it carried. Repo.Grant(tokens...) limits a private repo to those tokens. Any other token gets 404 from the REST routes, the raw host and GraphQL, as GitHub answers for a repo the token can’t see. So a test can check that one person can’t read another person’s repo. A private repo with no grants answers any accepted token. It serves the hooks API too. Repo.Hooks() returns each hook with its secret, content type, events and the token that last changed it. Repo.HookManagers(tokens...) limits who may manage the hooks, and gives any other token 404, as GitHub does without admin rights. Repo.Push(branch, put, del) commits, then delivers a signed push to each active push hook before it returns, so a test runs push, webhook and sync with no hand-built request. GitHub delivers in the background, so an app’s own retry logic isn’t exercised here. Repo.CommitLFS(branch, path, content) commits an LFS pointer and keeps the object behind the fake’s batch API at LFSURL(). RemoveLFSObject, FailLFS and CorruptLFS set up a missing object, a refused batch and a download that doesn’t match its pointer. oneauth’s outbound/githubtest mints and refreshes tokens, and AcceptToken lets this fake trust the ones it mints.
New starts the fake on a fresh 127.0.0.1 port. A test whose app runs in a container can’t reach that port, and can’t follow the absolute URLs the fake hands out. So WithListener(l) serves the fake on a listener the test opens, such as one on 0.0.0.0:0. WithBaseURL(u) sets the origin of every URL the fake hands out: URL, RawURL(), LFSURL(), the LFS batch hrefs, pagination Link headers and the device flow’s verification_uri. Pick an origin the container can reach, such as http://host.docker.internal:<port>. The test process may not resolve that name, so it calls the fake at ListenURL(). WithTLS(cfg) serves the fake over HTTPS with cfg’s certificate, or httptest’s own when cfg has none. An app that refuses a plain-HTTP Enterprise host off loopback needs it, as oneauth’s SetEnterpriseURL does.
A real GitHub App can do less than the person who signs in through it. AddApp returns the App, and SetPermissions and Install(account, repos...) model those limits. A sign-in token through the App then reads a private repo only where the App is installed and the person can read it, and gets 404 anywhere else. A file route needs the contents permission, a write needs it at write, and the org membership check needs members. Without the permission the API answers 403 “Resource not accessible by integration”, as GitHub does. POST /app/installations/{id}/access_tokens takes a JWT signed with the App’s key (KeyPEM()), so oneauth’s outbound.GitHubAppInstallation gets an installation token from the fake, and that token reads the installation’s repos. SetWebhook gives the App a webhook, and Repo.Push delivers to it with the installation in the body. An App with no permissions or installations signs people in and limits nothing, as before.
An exercise that runs the app outside the Go test process can start a seeded fake as a command. go run github.com/panyam/goapplib/storage/mounts/github/githubtest/cmd/fakegithub --seed seed.json builds the users, App, tokens and repos the seed file names, as githubtest.Seed describes. --listen and --base-url place it for a container. --tls-cert and --tls-key make it serve HTTPS there, with a certificate naming the address the container dials. Its control address stays plain HTTP. Its control address answers GET / with the fake’s addresses, each tag’s commit and the App’s key and installations. POST /approve approves a device code, and POST /push commits a folder and delivers the push. A Go test gets the same fake from LoadSeed and Seed.Apply.
A test against real GitHub reads octocat/Hello-World, and runs with STORAGE_LIVE_GITHUB=1. With STORAGE_LIVE_GITHUB_TOKEN set too, it lists golang/go’s tags. STORAGE_LIVE_GITHUB_LFS=owner/repo:path reads one LFS file through a snapshot and a live mount.
The fake also serves a GitHub App’s sign-in, so an app tests its GitHub login against the same host its repos live on. Point oneauth’s GithubOAuth2 at it with SetEnterpriseURL(fake.URL). Every API route also answers under /api/v3, as on a GitHub Enterprise Server host.
AddApp(clientID, secret)registers the App. Any other client id, or a wrong secret, gets GitHub’sincorrect_client_credentials.AddUser(login, orgs...)makes a person./useranswers theirlogin,idandname, and/orgs/{org}/members/{login}answers 204 for each oforgsand 404 otherwise.- In the web flow,
SignInAs(login)picks who is signed in at the authorize step. Without it, authorize redirects back witherror=access_denied. A code works once, and only with its PKCE verifier and redirect URI. - In the device flow,
User.Approve(userCode)stands in for the person typing the code. Until then a poll getsauthorization_pending, and a poll sooner than the interval getsslow_down. The interval is one second, andSetDeviceIntervalchanges it. - Each sign-in issues an access token and a refresh token. A refresh issues a new pair and retires both old tokens.
ExpireTokens(login)makes the person’s access tokens get 401, so a test can watch the app refresh. Repo.GrantUser(logins...)andRepo.HookManagerUsers(logins...)name a person rather than a token, so the grant holds across refreshes. They add toGrantandHookManagers.
GitHub answers every OAuth error with status 200 and an error field, and so does the fake. x/oauth2 reads it as a *oauth2.RetrieveError. The error names come from GitHub’s docs, since TestLiveGitHub can’t sign in without a person at a browser.
The registry ¶
Registry joins the fixed mounts from the server’s configuration, the runtime mounts from a RecordStore, and the drivers, and an app goes through it for everything. A nil store serves the fixed mounts alone, for an app with no store of its own, such as agni’s CLI, and Create and Delete then return ErrInvalidArgument:
store, _ := fsstore.New(filepath.Join(storeDir, "mounts"))
reg := mounts.NewRegistry(store, []mounts.Driver{folder.New(), github},
mounts.WithFixed(mounts.Mount{Name: "boards", Kind: mounts.KindFolder, Source: "/srv/boards", Mode: mounts.ModeLive}),
mounts.WithCredentials(conns.Credentials),
mounts.WithInUse(designs.PointsInto),
)
Createresolves the ref, callsPrepare, setsVersionandCreated, and writes the record. It refusesKindFolder, a mode the driver doesn’t serve, a name a fixed mount has, and aConnectionOwnerwith noConnection.Deleterefuses a fixed mount withErrFixed. It asks the app’sWithInUsecheck whether records still point into the mount, and refuses withErrInUsewhen they do. agni#1735 wanted this, and agni doesn’t check it yet.Open,Stat,HostPath,PutandRemovework on one file. A write to a snapshot mount returnsErrReadOnlybefore it reaches the driver, and one overWithLimits’MaxBytesreturnsErrTooLarge.FS(ctx)returns every mount as onefs.FSthrough goutils’mountfs, with each mount’s driver opened when a path first reaches it. It keepsctxfor those opens, because a person’s connection gives a token only to its owner. An app callsFSper request. A background job that needs a person’s mount passes that person’s context.WithCredentialstakes the connections service’sCredentialsmethod, so the registry asks for a mount’s credentials without importing connections. It passes the mount’sConnectionOwnerandConnection.- Before using its list, the registry compares the store’s
Generationwith the last one it read, at most once a second (WithRecheckchanges that). It lists again only when they differ. A registry sees its own creates and deletes at once. If the store fails after a good read, the registry keeps serving the last good list. ResolveAt,ListAtandFetchAtcall aVersionReaderdriver with the mount’s credentials, so an app reads a private repo at any commit through the mount’s connection. A driver that can’t read versions returnsErrInvalidArgument.ListRefscalls aRefListerdriver the same way.EnsureWebhook(ctx, name, req)andDeleteWebhook(ctx, name, url)call aWebhookManagerdriver the same way. They refuse withErrInvalidArgumenta URL that isn’t absolute http or https, an empty secret (an app can’t verify an unsigned delivery), a mount with no connection (a host doesn’t let an anonymous caller manage hooks), and a kind whose driver has none. An emptyEventsmeans push.Following(ctx, kind, change)returns the mounts aChangemoves. A change says that a ref in a source moved, such as a push to a branch. A mount matches when its source names the same place and its ref is the changed one, or is empty and the change is to the default branch. For aSourceContainerdriver, such as a bucket’s, a mount matches when the change’s source lies under its own, and the bucket change’s empty ref matches the bucket mount’s. A mount pinned to a commit never matches. An app’s webhook handler turns the host’s event into aChange, asgithub.ParsePushdoes, and then callsResolveAton each mount it gets back. A folder fits the same shape: a poller that sees a folder’s version move can make aChangetoo.BlobRefs(store)gives a blob sweep the manifest and files of every snapshot mount. An app passes it toSweepbeside its own referrers. A manifest it can’t read fails the sweep, so a snapshot never loses its files to it. The sweep’s grace period should be longer than the recheck interval, since a mount another process just made reaches this registry’s list only at the next check.
Record stores ¶
A RecordStore creates and deletes records, and never changes one in place. Several processes can share a store, and Generation is how each one notices the others’ changes. storage/mounts/mountstest checks a backend against this contract, the way oneauth’s usertokentest checks user-token stores. A backend’s test calls mountstest.RunRecordStore, and RunShared when two of its stores can share data.
- Folder,
storage/mounts/fsstore. One YAML file per mount, read throughos.Root. A create writes a temp file and hard-links it to<name>.yaml. The link fails when the name exists, so of two processes creating one name, one wins.Generationis agni’s stamp of each file’s name, size and mtime. A folder’s own mtime isn’t enough on Windows. - GORM,
gormstore.NewMountStore(db)from the modulegithub.com/panyam/goapplib/storage/backends/gorm, over any database GORM supports. It keeps records in thegoapplib_mountstable. A create inserts with “on conflict do nothing”, and an insert that adds no row returnsErrExists, so of two servers creating one name, one wins.Generationis a counter ingoapplib_mount_generationthat each create and delete bumps in the same transaction. - Datastore,
gaestore.NewMountStore(client, namespace)from the modulegithub.com/panyam/goapplib/storage/backends/gae. Each record is aGoapplibMountentity keyed by the mount’s name. A create reads the key and writes it in one transaction, and so does the generation counter. Every create and delete writes that one counter entity, so writers contend on it, and the store retries a contended transaction up to 32 times rather than Datastore’s default 3.
Both backends are modules of their own, so an app that keeps records in a folder never downloads GORM or the Datastore SDK. Both run mountstest. GORM runs on SQLite in CI. Datastore runs with make test-datastore, which starts the local emulator, and CI skips it.
What the library enforces ¶
These checks live in the library, so an app doesn’t write them again:
- URI and name rules, as above.
- Regular files and folders only. A snapshot skips links, devices and anything else, and refuses a tar entry that is absolute, climbs, or isn’t clean.
Limitson bytes and files, defaulting to agni’s 256 MB and 100,000 files. Past either, the driver returnsErrTooLarge.- Folder mounts come from the server’s configuration only.
CreaterefusesKindFolder, so a client can’t make a mount over a server folder of its choosing.
Errors ¶
Each error wraps one of the package’s sentinels, and an app maps them with errors.Is. agni maps them onto its service errors one to one:
| mounts | agni’s service |
|---|---|
ErrNotFound |
ErrNotFound |
ErrExists |
ErrAlreadyExists |
ErrInvalidArgument |
ErrInvalidArgument |
ErrInvalidPath |
ErrInvalidPath |
ErrFixed, ErrInUse, ErrReadOnly |
ErrFailedPrecondition |
ErrTooLarge |
ErrResourceExhausted |
ErrUnavailable |
ErrUnavailable |
ErrConflict |
ErrAborted, which agni doesn’t have yet |
ErrNotLocal |
ErrFailedPrecondition |
ErrPermissionDenied |
ErrPermissionDenied |
ErrLFS |
the sentinel it also wraps, or ErrFailedPrecondition for a folder |
What agni deleted when it moved over ¶
agni moved onto the library in agni#1762, at storage v0.7.15. It deleted these:
mounts/mounts.go’sMount,Kind,SafeResolveandResolve, andartifact/uri.go.ParseURI,URI.Resolve,DirandBase, andRegistry.HostPathreplace them. A registry with no store covers agni’s CLI, andfolder.WithLinksInsidekeeps its--mountfolders with links working.mounts/table.go:mounts.Registryandfsstorereplace it. agni’s records gainedversionandmode, and itscommitkey becameversion.cmd/agni/mountmaker.go’s GitHub code:resolveRef,snapshot,tarPathand the HTTP error mapping. The GitHub driver replaces them. agni keptCreateMountandDeleteMountas thin calls into the registry.cmd/agni/linkreaders.go, from agni’s linked artifacts:Registry.ResolveAt,ListAtandFetchAtreplace its GitHub and folder readers, its tree cache and its git blob id index. agni’sexercise-linked-sourcesshows a move to a newer commit downloading only the 17 changed files.Record.Files: the manifest blob replaces it. At startup, agni rewrites each record an older agni wrote once, and its file list becomes a manifest blob.
agni kept its Workspace adapter, its archivefs reading, and the flags, in a package now called mountset. make exercise-mounts printed the same lines before and after the move, except the uploads size du reports. The new manifest blob adds 6.7 KB to the uploads.
The package ¶
mounts
import "github.com/panyam/goapplib/storage/mounts"
Package mounts names the places an app's files live. A mount is a folder or a GitHub repo, and later an S3 or GCS bucket. Each is reached by a name, and a file in it by a mount:// URI. An app keeps its own records in its own store, and those records point into mounts by URI.
This package holds the contract: the Mount record, the URI and name rules, the interfaces a driver and a record store implement, and the errors they return. The design, with how agni and notation use it, is at https://panyam.github.io/goapplib/reference/mounts/.
Constants and variables
const MaxLFSPointerSize = 1024MaxLFSPointerSize is the largest file ParseLFSPointer looks at. Git LFS writes pointers well under it, so a driver checks only files this small.
const Scheme = "mount://"Scheme is the URI scheme for a file in a mount.
var (
// ErrNotFound means no mount has that name, or no file has that path in the mount, or the
// source (a repo, a ref) doesn't exist upstream.
ErrNotFound = errors.New("mounts: not found")
// ErrExists means a mount with that name exists already, fixed or runtime.
ErrExists = errors.New("mounts: already exists")
// ErrInvalidArgument means a name, a source or a ref is malformed, or a request asked for
// something the driver doesn't do, such as a mode it doesn't support.
ErrInvalidArgument = errors.New("mounts: invalid argument")
// ErrInvalidPath means a path is absolute, climbs out of its mount, or names a link.
ErrInvalidPath = errors.New("mounts: invalid path")
// ErrFixed means the request would change a mount that comes from the server's
// configuration, which only a restart with new configuration changes.
ErrFixed = errors.New("mounts: mount is fixed")
// ErrTooLarge means a snapshot or a write would pass a Limits cap.
ErrTooLarge = errors.New("mounts: over the size or file-count limit")
// ErrUnavailable means the source failed or refused for now: a network error, a 5xx, or a
// rate limit. Retrying later may work.
ErrUnavailable = errors.New("mounts: source unavailable")
// ErrConflict means a write's IfMatch didn't match the file's current version, because
// someone else changed or created it first. Read it again and retry.
ErrConflict = errors.New("mounts: version conflict")
// ErrReadOnly means the mount can't be written: it is a snapshot, or its driver has no
// Writer.
ErrReadOnly = errors.New("mounts: mount is read-only")
// ErrNotLocal means the mount has no folder on this server's disk, so it has no host path.
ErrNotLocal = errors.New("mounts: no host path")
// ErrInUse means the app's in-use check says records still point into the mount, so it
// can't be deleted.
ErrInUse = errors.New("mounts: mount is in use")
// ErrPermissionDenied means the source refused the mount's token for this request, though
// the token may read the source. A GitHub token needs admin rights on a repo, or a
// fine-grained token's webhooks permission, to manage its hooks.
ErrPermissionDenied = errors.New("mounts: permission denied")
)The errors a driver, a record store and the registry return, wrapped with detail. An app maps them onto its own transport with errors.Is. The mounts design page has the table agni uses.
var DefaultLimits = Limits{MaxBytes: 256 << 20, MaxFiles: 100_000}DefaultLimits are agni's caps for a GitHub snapshot: 256 MB and 100,000 files.
var ErrLFS = errors.New("mounts: Git LFS object not available")ErrLFS means a file is a Git LFS pointer whose object the driver couldn't read. The error also wraps the reason where there is one (ErrNotFound for a missing object, ErrPermissionDenied for no LFS access, ErrUnavailable for a quota or a network failure), and its message names the path. A driver never serves the pointer in place of the file.
BearerToken
func BearerToken(c Credentials) (string, error)BearerToken returns the access token c gives, or "" for nil credentials. It is TokenSourceOf followed by Token, for a driver that sets the header itself.
BuildView
func BuildView(view string, l blobs.Linker, files func() (blobs.Manifest, error)) errorBuildView makes view, a folder on this server's disk holding each file in files as a link to its blob in l, unless view already exists. A snapshot driver's HostPath calls it. files is called only when view is missing, so a driver can read its manifest lazily.
It builds in a temp folder beside view and renames, so nobody sees a half-built view, and two processes building at once leave one whole view. Each entry's Path must be clean and relative, as blobs.GetManifest checks. A blob that l doesn't hold fails the build with blobs.ErrNotFound.
CleanPath
func CleanPath(p string) (string, error)CleanPath applies NewURI's path rules to p, a path inside a mount. It returns the clean, relative, slash-separated form, and "" for the mount's root. An absolute path, or one that climbs out with "..", wraps ErrInvalidPath. Drivers call it on every path they are given, so a path that skipped NewURI still can't leave the mount.
TokenSourceOf
func TokenSourceOf(c Credentials) (oauth2.TokenSource, error)TokenSourceOf returns the token source of bearer credentials. Nil credentials return a nil source and no error, which means "send no token". Any other kind returns ErrInvalidArgument, since a bearer-token driver can't sign with it.
ValidName
func ValidName(name string) errorValidName reports whether name can name a mount. A name is 1 to 64 characters. The first is a-z or 0-9, and the rest may also be '-', '_' or '.'. The rule keeps names safe as a folder name, a URL path element and a YAML file name on any OS. It returns an error wrapping ErrInvalidArgument.
AWSCredentials
type AWSCredentials struct {
AccessKeyID string
SecretAccessKey string
SessionToken string
DefaultChain bool
RoleARN string
Region string
}AWSCredentials is what an S3 driver needs to sign requests with SigV4. The connections service resolves the secret before building it, so the value holds a secret and must not be logged or stored.
With DefaultChain set, the driver ignores the key pair and uses the AWS SDK's default chain: environment variables, the shared config files, an EC2 instance role, or an IRSA role on Kubernetes. Otherwise AccessKeyID and SecretAccessKey must both be set. A non-empty RoleARN makes the driver assume that role with the base credentials first. An empty Region means the driver's own default.
AWSCredentials.CredentialKind
func (AWSCredentials) CredentialKind() stringCredentialKind returns "aws".
AWSCredentials.GoString
func (c AWSCredentials) GoString() stringGoString hides the secret from %#v as well.
AWSCredentials.String
func (c AWSCredentials) String() stringString hides the secret, so a stray %v never prints it.
BearerCredentials
type BearerCredentials struct {
Source oauth2.TokenSource
}BearerCredentials signs each request with a token from Source, as "Authorization: Bearer".
BearerCredentials.CredentialKind
func (BearerCredentials) CredentialKind() stringCredentialKind returns "bearer".
Change
type Change struct {
// Source is the source that changed, in the driver's form, such as "github://owner/repo".
Source string
// Ref is the short name of the ref that moved, such as "main" or "v1.2.0".
Ref string
// RefKind is RefBranch or RefTag.
RefKind RefKind
// Version is what Ref points at now, in the format the driver's Resolve returns. It is empty
// when Deleted is true.
Version string
// Before is what Ref pointed at before, empty when the ref is new.
Before string
// Deleted is true when the ref was removed.
Deleted bool
// Default is true when Ref is the source's default branch, so a mount whose Ref is empty
// follows it.
Default bool
}Change says that a ref in a source moved, such as a push to a branch that a host's webhook reported (goapplib issue 179). A driver's package turns its host's event into a Change, as github.ParsePush does, so an app's handler finds the mounts to check with Registry.Following and never reads the host's own format.
Credentials
type Credentials interface {
// CredentialKind names the kind, such as "bearer" or "aws", for error messages.
CredentialKind() string
}Credentials is how a driver signs its requests to a source. The registry gets them from the mount's connection (WithCredentials) and hands them to the driver unchanged. A nil Credentials means the source is public or local, and the driver sends no sign-in.
Each service signs in its own way, so a driver type-switches on the value and takes the kinds it understands:
- BearerCredentials carries an OAuth bearer token, as GitHub and Google Cloud Storage take.
- AWSCredentials carries what an AWS SDK needs to sign with SigV4, which has no bearer token.
A driver given a kind it can't use returns ErrInvalidArgument, naming the kind. A package can add its own kind by implementing CredentialKind, so this package never imports a cloud SDK.
Bearer
func Bearer(ts oauth2.TokenSource) CredentialsBearer wraps ts as Credentials. A nil ts returns nil, so a public source stays public.
CredentialsFunc
type CredentialsFunc func(ctx context.Context, owner, connection string) (Credentials, error)CredentialsFunc returns the credentials of owner's connection, as WithCredentials takes it. The connections service's Credentials method has this signature.
DeleteRequest
type DeleteRequest struct {
Path string
IfMatch FileVersion
Message string
}DeleteRequest removes Path. IfMatch must be the file's current version, or AnyVersion.
Driver
type Driver interface {
// Kind is the Kind of mount this driver serves.
Kind() Kind
// Modes lists the modes the driver supports. A request for any other returns
// ErrInvalidArgument.
Modes() []Mode
// Resolve checks source and turns ref into a version: a commit for GitHub, an empty string
// for a folder. An empty ref means the source's default, such as the default branch. A
// source or ref that doesn't exist returns ErrNotFound.
Resolve(ctx context.Context, source, ref string, creds Credentials) (version string, err error)
// Open returns the mount's files. For a snapshot mount they are the files at m.Version, and
// the same call returns the same bytes for the life of the mount. For a live mount they are
// the source's latest. Paths in the fs.FS are clean, relative and slash-separated, so a
// URI's Path opens directly. Only regular files and folders appear in it, never links.
Open(ctx context.Context, m Mount, creds Credentials) (fs.FS, error)
}Driver reads one Kind of source. The registry calls it with the Credentials of the mount's connection, or nil for a public or local source. A driver doesn't know about connections or viewers. It signs with the credentials it is given, and returns ErrInvalidArgument for a kind of Credentials it can't sign with.
FetchingLocalizer
type FetchingLocalizer interface {
Localizer
// Fetches reports whether HostPath on m may download, and so needs m's credentials.
Fetches(m Mount) bool
HostPathWith(ctx context.Context, m Mount, creds Credentials, p string) (string, error)
}FetchingLocalizer is a Localizer whose HostPath may download a mount's files first, such as a lazy GitHub snapshot (agni issue 1877), so it takes the mount's credentials. The registry calls HostPathWith instead of HostPath for a mount Fetches reports, and looks up credentials only then. A mount served from what it already holds, such as an eager snapshot, goes to HostPath with no credentials, so a registry that has none, such as a read-only reader's, still serves it. A call for a folder downloads every file under it, within the driver's Limits, and a call for a path that names nothing returns where it would be, as HostPath does.
File
type File struct {
Path string
ID string
Size int64
}File is one file a VersionReader lists. Path is relative to the mount's root, clean and slash-separated. ID is the source's own name for the contents, such as a git blob id, and is empty when the source has none. Size is in bytes.
FileVersion
type FileVersion stringFileVersion identifies one version of one file, in the driver's own format.
const AnyVersion FileVersion = "*"AnyVersion as IfMatch lets a write replace whatever version is there, or create the file.
Kind
type Kind stringKind says which driver serves a mount.
const (
// KindFolder is a folder on the server's disk. Folder mounts come from the server's own
// configuration, never from a request, since a client may not pick a server folder.
KindFolder Kind = "folder"
// KindGitHub is a GitHub repository, read through GitHub's REST API.
KindGitHub Kind = "github"
// KindS3 is a prefix in an S3 bucket, "s3://<bucket>/<prefix>". The driver is in the
// storage/drivers/s3 module.
KindS3 Kind = "s3"
// KindGCS is a prefix in a Google Cloud Storage bucket, "gs://<bucket>/<prefix>". The driver
// is in the storage/drivers/gcs module.
KindGCS Kind = "gcs"
// KindMSGraph is a folder in a SharePoint document library or a OneDrive, read through
// Microsoft Graph, such as "msgraph://sites/<site>/drives/<drive>/root/Boards" or
// "msgraph://me/drive/root/Boards". The driver is in the storage/drivers/msgraph module.
KindMSGraph Kind = "msgraph"
)LFSPointer
type LFSPointer struct {
OID string
Size int64
}LFSPointer is a parsed Git LFS pointer: the SHA-256 of the object's contents, in lowercase hex, and its size in bytes.
ParseLFSPointer
func ParseLFSPointer(b []byte) (LFSPointer, bool)ParseLFSPointer reports whether b is a Git LFS pointer, as the spec at https://github.com/git-lfs/git-lfs/blob/main/docs/spec.md defines it: a first line of "version https://git-lfs.github.com/spec/v1", then "oid sha256:<hex>" and "size <bytes>" lines. A file over MaxLFSPointerSize is never a pointer.
Limits
type Limits struct {
MaxBytes int64
MaxFiles int
}Limits caps what a snapshot or a write may hold. A driver returns ErrTooLarge past either. Zero means the default.
ListRefsRequest
type ListRefsRequest struct {
Kind RefKind
Branch string
PageSize int
PageToken string
}ListRefsRequest picks what ListRefs lists. Kind is RefTag or RefCommit. For RefCommit, Branch names the branch, and empty means the source's default. PageSize is a hint the driver may cap, and zero means the driver's default. PageToken is the NextPageToken of the page before, or empty for the first page.
Localizer
type Localizer interface {
Driver
// HostPath returns the host path of p inside m. It returns ErrNotLocal when m has no
// folder here, and ErrInvalidPath when p would leave the mount.
HostPath(m Mount, p string) (string, error)
}Localizer is a Driver whose mounts can have a folder on this server's disk, for code that needs a host path, such as a native tool. A snapshot driver's view counts too.
Mode
type Mode stringMode says whether a mount's files can change after it is made.
const (
// ModeSnapshot pins the mount at the version its ref resolved to when it was made. Its files
// never change, so a record that points into it keeps meaning the same bytes. agni uses this
// for designs.
ModeSnapshot Mode = "snapshot"
// ModeLive reads the source's latest version on each open, and a Writer can change it.
// notation uses this for notations it edits.
ModeLive Mode = "live"
)Mount
type Mount struct {
// Name is the mount's handle in URIs: mount://<Name>/<path>. ValidName gives the rule.
Name string
Kind Kind
// Source says where the files come from, in the driver's own form: "github://owner/repo"
// for GitHub, or an absolute path for a folder.
Source string
// Ref is what the mount was asked for, such as a branch, a tag or a commit. Empty means the
// source's default.
Ref string
// Version is what Ref resolved to when the mount was made, such as a commit sha. The driver
// defines its format. For a snapshot mount the files are those at Version. A live mount has
// moved on since, and its Writer returns each new version.
Version string
Mode Mode
// Connection is the ID of the connection the driver reads through (package connections).
// Empty means the source is public, or local.
Connection string
// ConnectionOwner is the subject of the person whose connection Connection is. Empty means a
// server connection. Only that person can open a mount over their connection, since the
// connections service gives a person's token to them alone.
ConnectionOwner string
// Manifest is the hash of the blob listing a snapshot's files and their hashes, which is
// what rebuilds a snapshot's view after a restart. It is empty for a live mount, and for a
// snapshot a driver fetches file by file on first use, such as a GitHub driver made with
// github.WithLazySnapshots (agni issue 1877).
Manifest string
Created time.Time
}Mount is the library's record of one mount. An app keeps any fields of its own in its own records, keyed by Name.
Option
type Option func(*Registry)Option configures a Registry.
WithCredentials
func WithCredentials(f CredentialsFunc) OptionWithCredentials sets how the registry gets a mount's Credentials from its ConnectionOwner and Connection. The connections service's Credentials method fits it. It is called with the request's context, so a person's connection sees who is asking. A mount with an empty Connection gets nil Credentials without a call.
WithFixed
func WithFixed(ms ...Mount) OptionWithFixed adds mounts from the server's configuration, such as agni's --mount flags. They can't be deleted, and a runtime record with the same name is ignored. They are the only way to get a KindFolder mount.
WithInUse
func WithInUse(f func(ctx context.Context, name string) (bool, error)) OptionWithInUse sets the app's check for whether its records still point into a mount. Delete calls it, and returns ErrInUse when it says true.
WithLimits
func WithLimits(l Limits) OptionWithLimits caps writes through the registry. A zero field keeps DefaultLimits' value. Drivers that snapshot take their own Limits.
WithRecheck
func WithRecheck(d time.Duration) OptionWithRecheck sets how often the registry asks the store whether another process changed it. The default is a second. Tests set it lower.
Preparer
type Preparer interface {
Driver
Prepare(ctx context.Context, m Mount, creds Credentials) (Mount, error)
}Preparer is a Driver with work to do when a mount is made, after Resolve. A GitHub snapshot downloads the commit's files into the blob store there, and sets the mount's Manifest. The registry stores the Mount that Prepare returns. A Prepare error fails the Create, and no record is written.
PutRequest
type PutRequest struct {
Path string
Data []byte
IfMatch FileVersion
// Message is the commit message, for drivers that commit. Others ignore it.
Message string
}PutRequest writes Data to Path. IfMatch guards against overwriting a change the caller hasn't seen. Empty means the file must not exist yet. AnyVersion means write regardless. Anything else must equal the file's current version. A mismatch returns ErrConflict.
RecordStore
type RecordStore interface {
// ListMounts returns every record, in name order.
ListMounts(ctx context.Context) ([]Mount, error)
// GetMount returns the record named name, or ErrNotFound.
GetMount(ctx context.Context, name string) (Mount, error)
// CreateMount adds m. A record with m.Name returns ErrExists, so of two processes creating
// the same name, one wins.
CreateMount(ctx context.Context, m Mount) error
// DeleteMount removes the record named name. Deleting a missing record is not an error.
DeleteMount(ctx context.Context, name string) error
// Generation returns a value that changes whenever any process creates or deletes a record.
// The registry compares it with the last one it read, and lists again only when they differ.
// The format is the store's own.
Generation(ctx context.Context) (string, error)
}RecordStore keeps the runtime mounts, the ones made by requests rather than by the server's configuration. Records are created and deleted, never changed in place. A live mount's latest version comes from its driver, not from its record.
Several processes may share one store, such as a server and a worker. Each notices the others' changes through Generation.
Ref
type Ref struct {
Name string
Kind RefKind
Version string
Time time.Time
Message string
}Ref is one tag or commit. Name is what a mount's Ref field takes to pin it: the tag's name, or the commit's id. Version is the commit Name resolves to, in the format Resolve returns, so an app can pass it to ListAt without resolving it again. Time is the commit's date. Message is the first line of the commit's message, and may be empty, as it is for a tag on some hosts.
RefKind
type RefKind stringRefKind says what a ref names.
const (
// RefTag is a tag, which doesn't move.
RefTag RefKind = "tag"
// RefBranch is a branch, which moves with each commit on it.
RefBranch RefKind = "branch"
// RefCommit is one commit, named by its id.
RefCommit RefKind = "commit"
)RefLister
type RefLister interface {
Driver
// ListRefs lists source's tags, newest first by their commit's date, or the commits on one
// branch, newest first. A source or branch that doesn't exist returns ErrNotFound. A request
// the driver can't serve, such as tags with no token on a host that needs one, returns
// ErrInvalidArgument.
ListRefs(ctx context.Context, source string, req ListRefsRequest, creds Credentials) (RefPage, error)
}RefLister is a Driver that lists the versions its sources have, so an app can offer a list of revisions to link to (goapplib issue 177). agni lists a linked design's tags and a branch's commits with it. A driver whose sources have no history implements it and returns an empty page.
RefPage
type RefPage struct {
Refs []Ref
NextPageToken string
}RefPage is one page of refs. An empty NextPageToken means it is the last page.
Registry
type Registry struct {
// contains filtered or unexported fields
}Registry is an app's one view of its mounts. It joins the fixed mounts from the server's configuration, the runtime mounts in a RecordStore, and the drivers that read them, and it asks for each mount's credentials when a driver needs them.
Several registries, in one process or several, can share a RecordStore. Each checks the store's Generation at most once per recheck interval (a second by default), and lists the store again only when it changed. A registry sees its own creates and deletes at once.
A Registry is safe for concurrent use.
NewRegistry
func NewRegistry(store RecordStore, drivers []Driver, opts ...Option) *RegistryNewRegistry returns a registry over store, serving the kinds of drivers. Two drivers of one kind keep the later one. A nil store serves the fixed mounts alone, for an app with no store of its own, such as agni's CLI. Create and Delete then return ErrInvalidArgument.
Registry.BlobRefs
func (r *Registry) BlobRefs(store blobs.Store) blobs.ReferrerBlobRefs returns a blobs.Referrer that names, for every snapshot mount, its manifest and every file the manifest lists, so a sweep of store keeps them. Pass it to store's Sweep beside the app's own referrers. A manifest that can't be read fails the referrer, and so the sweep, rather than letting the sweep remove a snapshot's files. The registry rereads its records at most once per recheck interval, so a sweep's grace period should be longer than that.
Registry.Create
func (r *Registry) Create(ctx context.Context, m Mount) (Mount, error)Create makes a runtime mount from m's Name, Kind, Source, Ref, Mode, Connection and ConnectionOwner. An empty Mode takes the driver's first. Create resolves Ref through the driver, calls Prepare when the driver has it, sets Version and Created, and writes the record. It returns ErrInvalidArgument for a bad name, an unknown kind, a mode the driver doesn't serve, KindFolder, or a ConnectionOwner with no Connection. A name taken by a fixed or runtime mount returns ErrExists. Driver errors pass through, such as ErrNotFound for a source that doesn't exist.
Registry.Delete
func (r *Registry) Delete(ctx context.Context, name string) errorDelete removes the runtime mount named name. A fixed mount returns ErrFixed, a missing one ErrNotFound, and one the in-use check says is still referenced ErrInUse. Delete removes only the record. Blobs a snapshot used stay until a blob sweep finds nothing naming them.
Registry.DeleteWebhook
func (r *Registry) DeleteWebhook(ctx context.Context, name, url string) errorDeleteWebhook removes the hooks that send the source's changes of the mount named name to url, through the mount's connection. No such hook is not an error. It returns ErrInvalidArgument in the cases EnsureWebhook does, apart from the secret.
Registry.EnsureWebhook
func (r *Registry) EnsureWebhook(ctx context.Context, name string, req WebhookRequest) (Webhook, error)EnsureWebhook makes or updates the hook that sends the source's changes of the mount named name to req.URL, through the mount's connection. It returns ErrInvalidArgument for a URL that isn't absolute http or https, an empty secret, a mount with no connection (a source doesn't let an anonymous caller manage hooks), or a kind whose driver has no WebhookManager.
Registry.FS
func (r *Registry) FS(ctx context.Context) fs.FSFS returns every mount as one fs.FS, each under its name, through goutils' mountfs. It lists the mounts once, when called, and opens each mount's driver when a path first reaches it. The context is kept for those opens, so the viewer it carries is the one whose connections are used. An app calls FS per request, or per job with that job's context.
Registry.FetchAt
func (r *Registry) FetchAt(ctx context.Context, name, version string, f File) (blobs.Hash, bool, error)FetchAt keeps f's contents at version, in the mount named name, in the driver's blob store.
Registry.Following
func (r *Registry) Following(ctx context.Context, kind Kind, c Change) ([]Mount, error)Following returns the mounts of kind whose source is c.Source and whose ref is c.Ref, or empty when c is a change to the default branch. For a SourceContainer driver, a mount follows a change whose source lies under the mount's, and a bucket change's empty Ref matches a bucket mount's. Snapshot and live mounts both match, since an app may want to move a snapshot's links forward. A mount pinned to a commit never matches. A kind with no driver returns ErrInvalidArgument.
Registry.Get
func (r *Registry) Get(ctx context.Context, name string) (Mount, error)Get returns the mount named name, or ErrNotFound.
Registry.HostPath
func (r *Registry) HostPath(ctx context.Context, u URI) (string, error)HostPath returns the host path of the file u names, for code that needs a real file. A mount whose driver isn't a Localizer returns ErrNotLocal. A FetchingLocalizer that Fetches the mount gets its credentials, since it may download the files first.
Registry.List
func (r *Registry) List(ctx context.Context) ([]Mount, error)List returns every mount, fixed and runtime, in name order. When the store fails after a good read, List keeps returning the last good list rather than dropping every runtime mount.
Registry.ListAt
func (r *Registry) ListAt(ctx context.Context, name, version, under string) ([]File, error)ListAt lists the files at version under the path under, in the mount named name.
Registry.ListRefs
func (r *Registry) ListRefs(ctx context.Context, name string, req ListRefsRequest) (RefPage, error)ListRefs lists the tags, or a branch's commits, of the source of the mount named name, through its connection. A driver that can't list refs returns ErrInvalidArgument, and a Kind other than RefTag or RefCommit does too.
Registry.Open
func (r *Registry) Open(ctx context.Context, u URI) (fs.File, error)Open opens the file or folder u names.
Registry.Put
func (r *Registry) Put(ctx context.Context, name string, req PutRequest) (*WriteResult, error)Put writes a file in the mount named name, with req.Path cleaned by CleanPath. A snapshot mount, or one whose driver isn't a Writer, returns ErrReadOnly. Data over the registry's MaxBytes returns ErrTooLarge. The IfMatch rules are mounts.PutRequest's.
Registry.Remove
func (r *Registry) Remove(ctx context.Context, name string, req DeleteRequest) (*WriteResult, error)Remove deletes a file in the mount named name, under the same rules as Put.
Registry.ResolveAt
func (r *Registry) ResolveAt(ctx context.Context, name, ref string) (version string, moves bool, err error)ResolveAt resolves ref against the source of the mount named name, through its connection. It returns the version, empty for a source with no history, and whether ref moves.
Registry.Stat
func (r *Registry) Stat(ctx context.Context, u URI) (FileVersion, error)Stat returns the current version of the file u names, for a later Put or Remove. A mount that can't be written returns ErrReadOnly.
SourceContainer
type SourceContainer interface {
Driver
// ContainsSource reports whether changed, the Source of a Change, is mountSource or lies
// under it. It works on whole path segments, so "s3://b/ab" isn't under "s3://b/a".
ContainsSource(mountSource, changed string) bool
}SourceContainer is a Driver whose change events name something inside a source, such as one object under a bucket prefix, so a change matches every mount whose source holds it. A bucket event names "s3://designs/boards/jetson/README.md", and a mount of "s3://designs/boards" or "s3://designs" follows it.
SourceMatcher
type SourceMatcher interface {
Driver
// SameSource reports whether a and b name the same source.
SameSource(a, b string) bool
}SourceMatcher is a Driver that says when two of its sources name the same place, when plain string equality isn't enough. GitHub's owner and repo names ignore case, for one.
URI
type URI struct {
Mount string
Path string
}URI names a file or folder in a mount: mount://<Mount>/<Path>. Path is clean and relative, and never leaves the mount, so resolving it against the mount's root can't reach a file outside it. The empty Path is the mount's root.
NewURI
func NewURI(mount, p string) (URI, error)NewURI builds a URI from a mount name and a path inside it. The path may use '\' as a separator and may end in '/'. It may not be absolute or climb out with "..". Both failures wrap ErrInvalidPath, and a bad name wraps ErrInvalidArgument.
A URI's mount name follows a looser rule than ValidName: any name that isn't empty, ".", "..", and holds no '/' or '\'. An app names a fixed mount after a folder, such as agni's --mount-root, and a folder can have capitals or spaces. ValidName still governs the runtime mounts a record store keeps.
ParseURI
func ParseURI(s string) (URI, error)ParseURI parses "mount://<name>/<path>" with the rules of NewURI. Any other scheme wraps ErrInvalidPath.
URI.Base
func (u URI) Base() stringBase returns the last element of the path, as path.Base does, and "" for the mount's root.
URI.Dir
func (u URI) Dir() URIDir returns the URI of the folder holding u, or u itself for the mount's root.
URI.IsZero
func (u URI) IsZero() boolIsZero reports whether the URI names nothing, as an absent optional field does.
URI.Join
func (u URI) Join(elem ...string) (URI, error)Join returns the URI of elem under u, with the rules of NewURI.
URI.Resolve
func (u URI) Resolve(ref string) (URI, error)Resolve reads ref relative to u, the way a browser reads an href against the page it is on. A reader uses it when a file names another, such as a schematic naming its child sheets.
A full mount:// URI replaces u, mount included. "/x" names x from the mount's root. Anything else resolves against u's folder, so "sub/a.kicad_sch" against mount://m/designs/top.kicad_sch is mount://m/designs/sub/a.kicad_sch. A result that would climb out of the mount wraps ErrInvalidPath. Unlike RFC 3986, a leading ".." on an absolute path is an error rather than dropped, since quietly reading "/../x" as "/x" would hide a traversal attempt.
URI.String
func (u URI) String() stringString formats the URI as mount://<Mount>/<Path>, or mount://<Mount> for the mount's root, which ParseURI reads back.
VersionReader
type VersionReader interface {
Driver
// Moves reports whether ref names something that moves, so a later sync should follow it: an
// empty ref, a branch, or any ref of a source with no history. A tag or a commit doesn't move.
Moves(ctx context.Context, source, ref string, creds Credentials) (bool, error)
// ListAt returns the regular files at version that are at or under the path under, sorted by
// path. An empty under is the mount's root. It leaves out links, submodules and anything else
// that isn't a regular file, and returns none for a path that names nothing. Past the
// driver's Limits it returns ErrTooLarge. version is what Resolve returned, empty for a source
// with no history.
ListAt(ctx context.Context, m Mount, creds Credentials, version, under string) ([]File, error)
// FetchAt puts f's contents at version in the driver's blob store and returns their hash.
// fetched is false when the store already held them and nothing was downloaded. A download
// that doesn't match f.ID returns ErrUnavailable and keeps nothing.
FetchAt(ctx context.Context, m Mount, creds Credentials, version string, f File) (h blobs.Hash, fetched bool, err error)
}VersionReader is a Driver that reads a mount's source at any version, not only the one a snapshot mount pins (goapplib issue 172). An app links a record to a file at a commit with it, and later moves the link to a newer commit, downloading only the files that changed. agni's linked artifacts are the first user.
Webhook
type Webhook struct {
ID string
URL string
Events []string
Created bool
}Webhook is a hook as the source holds it. ID is the source's id for it. Created is true when EnsureWebhook made it, and false when it updated a hook already sending to URL.
WebhookManager
type WebhookManager interface {
Driver
// EnsureWebhook makes a hook on source that sends req.Events to req.URL, signed with
// req.Secret, or updates the hook already sending to req.URL. A token that can't manage the
// source's hooks returns ErrPermissionDenied, and a request the source refuses, such as a URL
// it won't send to, returns ErrInvalidArgument.
EnsureWebhook(ctx context.Context, source string, req WebhookRequest, creds Credentials) (Webhook, error)
// DeleteWebhook removes the hooks on source that send to url. No such hook is not an error,
// so deleting twice is safe. A token that can't manage the source's hooks returns
// ErrPermissionDenied.
DeleteWebhook(ctx context.Context, source, url string, creds Credentials) error
}WebhookManager is a Driver that can make a source send a webhook to the app on each change, so the app syncs a mount when its branch moves rather than polling it (goapplib issue 185). A hook is named by the URL it sends to, so making one twice updates the first rather than adding a second.
WebhookRequest
type WebhookRequest struct {
URL string
Secret []byte
Events []string
}WebhookRequest describes a hook. URL is where the source sends each delivery, and must be an absolute http or https URL. Secret signs each delivery, and must not be empty, since the app can't verify an unsigned one. Events names the source's events, and empty means "push".
WriteResult
type WriteResult struct {
// File is the file's new version. It is empty after a Delete.
File FileVersion
// Mount is the mount's new version, such as the commit a GitHub write made. Drivers whose
// sources have no version across files leave it empty.
Mount string
}WriteResult is what a write produced.
Writer
type Writer interface {
Driver
// Stat returns the current version of the file at p, which a later Put or Delete passes as
// IfMatch. For GitHub it is the file's blob sha. A missing file returns ErrNotFound.
Stat(ctx context.Context, m Mount, creds Credentials, p string) (FileVersion, error)
// Put creates or replaces the file at req.Path. A GitHub Put is one commit.
Put(ctx context.Context, m Mount, creds Credentials, req PutRequest) (*WriteResult, error)
// Delete removes the file at req.Path. A GitHub Delete is one commit.
Delete(ctx context.Context, m Mount, creds Credentials, req DeleteRequest) (*WriteResult, error)
}Writer is a Driver that can change a live mount. A write to a snapshot mount returns ErrReadOnly before reaching the driver.