Go API

Every exported type, function and method of goapplib, page, wasmhost, and the storage module's mounts, connections, blobs, drivers and backends, read from the source on main when the site is built.

This page is generated. When the site builds, it reads goapplib’s Go source on main with go/doc and writes out each package’s exported API: every type, function, method, constant and variable, with its declaration and doc comment. A test fails the build if an exported name is missing, so the page can’t drift from the code the way the hand-kept list it replaces did. (We kept that list by hand, and it still showed Loader[AC] two releases after it was removed.) Where a guide page teaches a symbol, its entry links there.

A declaration marked build: js && wasm exists only in a build for the browser (GOOS=js GOARCH=wasm), and one marked build: !(js && wasm) only in a native one. pkg.go.dev has pretty much the same API for each tagged release, though it lags main until the next tag.

The packages: goapplib, page, wasmhost, and from the storage module, mounts, connections, blobs, the folder, github, bucket, s3 and gcs drivers, and the gormstore and gaestore backends. The s3 and gcs drivers and the two backends are modules of their own.

goapplib

import "github.com/panyam/goapplib"

Constants and variables

const (
	ColorReset  = "\033[0m"
	ColorCyan   = "\033[36m"
	ColorGreen  = "\033[32m"
	ColorYellow = "\033[33m"
	ColorBold   = "\033[1m"
)

ANSI color codes

CORS

func CORS(next http.Handler) http.Handler

CORS adds CORS headers for local development.

DefaultFuncMap

func DefaultFuncMap() template.FuncMap

DefaultFuncMap returns the default template functions.

Guide: /goapplib/guide/templates/#template-functions

DefaultRateLimitKeyFunc

func DefaultRateLimitKeyFunc(r *http.Request) string

DefaultRateLimitKeyFunc extracts the client identifier from the request. Uses X-Forwarded-For for proxied requests, otherwise RemoteAddr.

GetLocalIP

func GetLocalIP() (string, error)

GetLocalIP returns the local network IP address (preferring ethernet/wifi over localhost)

GzipFileServer

func GzipFileServer(root http.FileSystem) http.Handler

GzipFileServer wraps an http.Handler to serve pre-compressed .gz files when available and the client accepts gzip encoding.

For WASM files, this serves .wasm.gz (4.7MB) instead of .wasm (25MB), reducing transfer size by ~81%.

HtmxCurrentURL

func HtmxCurrentURL(r *http.Request) string

HtmxCurrentURL returns the HX-Current-URL header value.

HtmxPrompt

func HtmxPrompt(r *http.Request) string

HtmxPrompt returns the HX-Prompt header value.

HtmxTarget

func HtmxTarget(r *http.Request) string

HtmxTarget returns the HX-Target header value.

HtmxTrigger

func HtmxTrigger(r *http.Request) string

HtmxTrigger returns the HX-Trigger header value.

IsBoostedRequest

func IsBoostedRequest(r *http.Request) bool

IsBoostedRequest checks if the request is a boosted link.

IsHtmxRequest

func IsHtmxRequest(r *http.Request) bool

IsHtmxRequest checks if the request is an HTMX request.

LoadAll

func LoadAll(r *http.Request, w http.ResponseWriter, app any, loaders ...Loader) (error, bool)

LoadAll runs loaders in order with the page's app, and stops at the first one that returns an error or finished = true, returning what it returned. A nil loader is skipped. A page typically calls it from its own Load:

func (p *GamesPage) Load(r *http.Request, w http.ResponseWriter, app *goapplib.App[*Site]) (error, bool) {
	return goapplib.LoadAll(r, w, app, &p.BasePage, &p.WithPagination, goapplib.LoaderFunc[*Site](p.loadGames))
}

Guide: /goapplib/guide/concepts/#loaders

ParseTemplateSpec

func ParseTemplateSpec(spec string) (fileName, blockName string)

ParseTemplateSpec parses a template spec into file name and block name. Format: "path/to/template" or "path/to/template:BlockName"

If no ":" is present, block name is auto-derived from the base filename. If ":" is present, the part after ":" is used as the explicit block name. An empty block name after ":" means render the entire template file.

PrintStartupMessage

func PrintStartupMessage(address string)

PrintStartupMessage prints a colorized startup message with clickable links

Register

func Register[V View[AC], AC any](
	app *App[AC],
	mux *http.ServeMux,
	pattern string,
	opts ...Option,
) *http.ServeMux

Register registers a View at the given pattern. If mux is nil, a new ServeMux is created. Returns the mux for chaining.

Usage:

mux := http.NewServeMux()
goapplib.Register[*HomePage](app, mux, "/")
goapplib.Register[*GameListingPage](app, mux, "/games/")

Guide: /goapplib/guide/routing/#register

RegisterFunc

func RegisterFunc(
	mux *http.ServeMux,
	pattern string,
	handler http.HandlerFunc,
) *http.ServeMux

RegisterFunc registers a handler function at the given pattern. Convenience wrapper for mux.HandleFunc.

RegisterGroup

func RegisterGroup[G PageGroup[AC], AC any](
	app *App[AC],
	mux *http.ServeMux,
	prefix string,
	opts ...Option,
) *http.ServeMux

RegisterGroup registers a PageGroup under the given prefix. The group's routes are mounted with the prefix stripped.

Usage:

goal.RegisterGroup[*GamesGroup](app, rootMux, "/games")

Guide: /goapplib/guide/routing/#groups

RegisterHandler

func RegisterHandler(
	mux *http.ServeMux,
	pattern string,
	handler http.Handler,
) *http.ServeMux

RegisterHandler registers an http.Handler at the given pattern. Convenience wrapper for mux.Handle.

SetupTemplates

func SetupTemplates(paths ...string) *tmplr.TemplateGroup

SetupTemplates creates a TemplateGroup with the given paths. Paths are checked in order, so put your app's templates first for overrides.

Guide: /goapplib/guide/getting-started/#install

SmartRegister

func SmartRegister[V interface {
	View[AC]
	HtmxAware
}, AC any](
	app *App[AC],
	mux *http.ServeMux,
	pattern string,
	fullTemplateSpec string,
	fragmentTemplateSpec string,
	opts ...Option,
) *http.ServeMux

SmartRegister registers a View that renders fullTemplateSpec as a page and fragmentTemplateSpec for an htmx request that wants a fragment. It's Register with WithTemplate(fullTemplateSpec) and WithFragmentTemplate(fragmentTemplateSpec), kept for the code that calls it; new code can pass WithFragmentTemplate to Register or MuxBuilder.Page directly.

Guide: /goapplib/guide/htmx/#one-route-a-page-or-a-fragment

App

type App[AppContext any] struct {
	Context            AppContext
	Templates          *tmplr.TemplateGroup
	RenderTemplateFunc func(w http.ResponseWriter, templateFileName string, templateBlockName string, view any) error
}

App holds app-level shared state and template system. AppContext is the application context type defined by your application (e.g., *WeewarApp).

Guide: /goapplib/guide/concepts/#the-app-and-its-context

NewApp

func NewApp[AppContext any](ctx AppContext, templates *tmplr.TemplateGroup) *App[AppContext]

NewApp creates a new App with the given application context and templates.

Guide: /goapplib/guide/concepts/#the-app-and-its-context

App.NewMux

func (app *App[AppContext]) NewMux() *MuxBuilder[AppContext]

NewMux creates a MuxBuilder for fluent route building.

App.RenderTemplate

func (app *App[AppContext]) RenderTemplate(
	w http.ResponseWriter,
	templateFileName string,
	templateBlockName string,
	view any) error

RenderTemplate renders the named template with the given view data. The page is rendered in full before any of it is written, so on an error nothing has reached w and the caller can still answer with an error status (#108). If RenderTemplateFunc is set, it delegates to that function, which is responsible for its own writes.

AuthProvider

type AuthProvider interface {
	GetLoggedInUserId(r *http.Request) string
	GetUserById(id string) (AuthUser, error)
}

AuthProvider is the interface for auth services.

Guide: /goapplib/guide/views/#goapplibs-mixins

AuthUser

type AuthUser interface {
	Profile() map[string]any
}

AuthUser is a minimal user interface.

BasePage

type BasePage struct {
	Title               string // Page title (internal use, fallback for MetaTitle)
	BodyClass           string // CSS classes for <body>
	ActiveTab           string // Highlight active navigation tab
	CustomHeader        bool   // If true, skip default header rendering
	DisableSplashScreen bool   // If true, hide loading splash
	SplashTitle         string // Custom splash title
	SplashMessage       string // Custom splash message
	BodyDataAttributes  string // HTML data attributes for body

	// SEO fields
	MetaTitle       string // Title for <title> tag and search results (falls back to Title if empty)
	MetaDescription string // Meta description for search engines
	CanonicalUrl    string // Canonical URL for SEO (e.g., https://example.com/page/)
}

BasePage provides common page metadata. Embed this in your page structs.

Guide: /goapplib/guide/views/#goapplibs-mixins

BasePage.Load

func (p *BasePage) Load(r *http.Request, w http.ResponseWriter, vc any) (error, bool)

Load implements Loader for BasePage. Note: This is a generic implementation that works with any ViewContext.

EntityListingData

type EntityListingData[ItemType any] struct {
	// Page header
	Title       string
	Subtitle    string
	CreateUrl   string
	CreateLabel string

	// View configuration
	ViewMode           string // "grid" or "list"
	ViewModeStorageKey string // localStorage key for saving preference
	EnableViewToggle   bool
	GridContainerId    string
	SearchInputId      string
	SortSelectId       string
	SearchPlaceholder  string

	// URL "formats".  To get the Url we would do something like fmt.Sprintf(fmt, Id)
	ViewUrlFormat   string
	EditUrlFormat   string
	DeleteUrlFormat string
	SearchUrl       string
	RefreshUrl      string

	// Sort options
	SortOptions []SortOption

	// Items to display - templates access fields directly (e.g., .Id, .Name, .Description)
	Items []ItemType

	// Actions
	ShowActions    bool
	ShowEditButton bool // Show edit button (typically only when logged in)
	HtmxEnabled    bool
	RefreshTrigger string

	// Empty state
	EmptyTitle   string
	EmptyMessage string
}

EntityListingData provides data for the EntityListing template component. This struct is designed to work with the EntityListing.html template. ItemType is the type of items in the listing - templates access item fields directly (e.g., .Id, .Name).

Guide: /goapplib/guide/templates/#components

NewEntityListingData

func NewEntityListingData[ItemType any](title string, viewUrlFormat string) *EntityListingData[ItemType]

NewEntityListingData creates a new EntityListingData with sensible defaults.

EntityListingData.DeleteUrl

func (d *EntityListingData[ItemType]) DeleteUrl(id string) string

Returns the formatted DeleteUrl

EntityListingData.EditUrl

func (d *EntityListingData[ItemType]) EditUrl(id string) string

Returns the formatted EditUrl

EntityListingData.ViewUrl

func (d *EntityListingData[ItemType]) ViewUrl(id string) string

Returns the formatted ViewUrl

EntityListingData.WithCreate

func (d *EntityListingData[ItemType]) WithCreate(url, label string) *EntityListingData[ItemType]

WithCreate sets the create URL and label

EntityListingData.WithDelete

func (d *EntityListingData[ItemType]) WithDelete(url string) *EntityListingData[ItemType]

WithDelete sets the delete URL

EntityListingData.WithEdit

func (d *EntityListingData[ItemType]) WithEdit(url string) *EntityListingData[ItemType]

WithEdit sets the edit URL

EntityListingData.WithHtmx

func (d *EntityListingData[ItemType]) WithHtmx(searchUrl string) *EntityListingData[ItemType]

WithHtmx enables HTMX for the listing

EntityListingData.WithView

func (d *EntityListingData[ItemType]) WithView(url string) *EntityListingData[ItemType]

WithView sets the viewer URL

HtmxAware

type HtmxAware interface {
	ShouldRenderFragment() bool
}

HtmxAware is implemented by views that can detect HTMX requests.

HtmxResponse

type HtmxResponse struct {
	// contains filtered or unexported fields
}

HtmxResponse provides helpers for setting HTMX response headers.

Guide: /goapplib/guide/htmx/#answering-an-action

NewHtmxResponse

func NewHtmxResponse(w http.ResponseWriter) *HtmxResponse

NewHtmxResponse creates a new HtmxResponse wrapper.

HtmxResponse.Location

func (h *HtmxResponse) Location(url string) *HtmxResponse

Location does a client-side redirect without full page reload.

HtmxResponse.LocationWithContext

func (h *HtmxResponse) LocationWithContext(spec map[string]any) *HtmxResponse

LocationWithContext does a redirect with additional context.

HtmxResponse.PushURL

func (h *HtmxResponse) PushURL(url string) *HtmxResponse

PushURL pushes a new URL onto the browser's history stack.

HtmxResponse.Redirect

func (h *HtmxResponse) Redirect(url string) *HtmxResponse

Redirect tells HTMX to perform a client-side redirect.

HtmxResponse.Refresh

func (h *HtmxResponse) Refresh() *HtmxResponse

Refresh tells HTMX to do a full page refresh.

HtmxResponse.ReplaceURL

func (h *HtmxResponse) ReplaceURL(url string) *HtmxResponse

ReplaceURL replaces the current URL in the browser's history.

HtmxResponse.Reselect

func (h *HtmxResponse) Reselect(selector string) *HtmxResponse

Reselect changes the selection from the response.

HtmxResponse.Reswap

func (h *HtmxResponse) Reswap(style string) *HtmxResponse

Reswap changes the swap method.

HtmxResponse.Retarget

func (h *HtmxResponse) Retarget(selector string) *HtmxResponse

Retarget changes the target element for the swap.

HtmxResponse.StopPolling

func (h *HtmxResponse) StopPolling() *HtmxResponse

StopPolling tells HTMX to stop polling.

HtmxResponse.Trigger

func (h *HtmxResponse) Trigger(event string) *HtmxResponse

Trigger sets the HX-Trigger header to trigger a client-side event.

HtmxResponse.TriggerAfterSettle

func (h *HtmxResponse) TriggerAfterSettle(event string) *HtmxResponse

TriggerAfterSettle sets HX-Trigger-After-Settle header.

HtmxResponse.TriggerAfterSwap

func (h *HtmxResponse) TriggerAfterSwap(event string) *HtmxResponse

TriggerAfterSwap sets HX-Trigger-After-Swap header.

HtmxResponse.TriggerWithData

func (h *HtmxResponse) TriggerWithData(event string, data any) *HtmxResponse

TriggerWithData sets HX-Trigger with JSON data.

Loader

type Loader interface {
	Load(r *http.Request, w http.ResponseWriter, app any) (err error, finished bool)
}

Loader is one step of a page's Load, run in order by LoadAll. goapplib's mixins (BasePage, WithPagination, WithFiltering, WithAuth, WithHtmx) are Loaders as they are, so a page chains them with LoadAll. app is the page's *App[AC], passed through as is; a loader that needs it typed is a LoaderFunc[AC].

Before 0.7.0 this was Loader[AC], with app typed as *App[AC], which no built-in mixin satisfied (issue 107).

Guide: /goapplib/guide/concepts/#loaders

LoaderFunc

type LoaderFunc[AC any] func(r *http.Request, w http.ResponseWriter, app *App[AC]) (error, bool)

LoaderFunc is a typed Loader: an app's own loading step, which gets app as its *App[AC]. Given an app of any other type, it doesn't run, and returns an error naming both types, which LoadAll returns, so a page renders a 500 rather than panicking.

Guide: /goapplib/guide/concepts/#loaders

AuthLoader

func AuthLoader[AC any](auth *WithAuth, provider AuthProvider) LoaderFunc[AC]

AuthLoader returns a LoaderFunc that loads auth info, for LoadAll when you have an AuthProvider. Its app type can't be inferred, so name it: AuthLoader[*Site](&p.WithAuth, provider).

LoaderFunc.Load

func (f LoaderFunc[AC]) Load(r *http.Request, w http.ResponseWriter, app any) (error, bool)

Load implements Loader.

LoginConfig

type LoginConfig struct {
	EnableEmailLogin     bool
	EnableGoogleLogin    bool
	EnableGitHubLogin    bool
	EnableMicrosoftLogin bool
	EnableAppleLogin     bool
}

LoginConfig controls which login methods are available.

MuxBuilder

type MuxBuilder[AC any] struct {
	// contains filtered or unexported fields
}

MuxBuilder builds a ServeMux fluently, as an alternative to calling Register and RegisterGroup:

mux := app.NewMux().
	Page("/{$}", func() goapplib.View[*Site] { return &HomePage{} }).
	Group("/games", func(m *goapplib.MuxBuilder[*Site]) {
		m.Page("/{id}", func() goapplib.View[*Site] { return &GamePage{} })
	}).
	Build()

A Page renders exactly as Register would render the same view type.

Guide: /goapplib/guide/routing/#muxbuilder

MuxBuilder.Build

func (b *MuxBuilder[AC]) Build() *http.ServeMux

Build returns the constructed ServeMux.

MuxBuilder.Group

func (b *MuxBuilder[AC]) Group(prefix string, setup func(*MuxBuilder[AC])) *MuxBuilder[AC]

Group mounts the routes setup adds under prefix, which is stripped before they match, so a route "/{id}" in a Group("/games", ...) answers /games/7. Middleware added by Use before the Group wraps the whole group.

MuxBuilder.HandleFunc

func (b *MuxBuilder[AC]) HandleFunc(pattern string, h http.HandlerFunc) *MuxBuilder[AC]

HandleFunc registers an http.HandlerFunc.

MuxBuilder.Handler

func (b *MuxBuilder[AC]) Handler(pattern string, h http.Handler) *MuxBuilder[AC]

Handler registers an http.Handler.

MuxBuilder.Mux

func (b *MuxBuilder[AC]) Mux() *http.ServeMux

Mux returns the underlying ServeMux for direct access.

MuxBuilder.Page

func (b *MuxBuilder[AC]) Page(pattern string, maker func() View[AC], opts ...Option) *MuxBuilder[AC]

Page registers a view at pattern. maker returns a fresh view for each request, and the view's type picks its template the way Register's does (HomePage renders HomePage.html's HomePage block), unless WithTemplate says otherwise.

MuxBuilder.Static

func (b *MuxBuilder[AC]) Static(pattern string, dir string) *MuxBuilder[AC]

Static serves the files in dir at pattern, with pattern stripped from the path.

MuxBuilder.Use

func (b *MuxBuilder[AC]) Use(mw func(http.Handler) http.Handler) *MuxBuilder[AC]

Use adds middleware to every route registered after it on this builder, groups included. Routes registered before it aren't wrapped. Middleware added by several Uses runs in the order added.

Option

type Option func(*options)

Option configures registration behavior.

WithFragmentTemplate

func WithFragmentTemplate(spec string) Option

WithFragmentTemplate sets the template a page renders for an htmx request that wants a fragment rather than the whole page: when the view is HtmxAware (embedding WithHtmx makes it so, once WithHtmx has loaded) and its ShouldRenderFragment is true, which it is for an htmx request that isn't a boosted link. Any other request, or a view that isn't HtmxAware, gets the page's usual template. spec has WithTemplate's form, "path/File" or "path/File:Block".

Guide: /goapplib/guide/htmx/#one-route-a-page-or-a-fragment

WithMiddleware

func WithMiddleware(mw ...func(http.Handler) http.Handler) Option

WithMiddleware adds middleware to the handler.

Guide: /goapplib/guide/routing/#register

WithTemplate

func WithTemplate(spec string) Option

WithTemplate sets the template file and optional block name. Format: "path/to/template" or "path/to/template:BlockName"

If no ":" is present, block name is auto-derived from the base filename. If ":" is present, the part after ":" is used as the explicit block name. An empty block name after ":" means render the entire template file.

Examples:

  • "CanvasListingPage" -> file: CanvasListingPage.html, block: CanvasListingPage (auto-derived)
  • "canvases/CanvasListingPage" -> file: canvases/CanvasListingPage.html, block: CanvasListingPage (auto-derived)
  • "canvases/CanvasListingPage:MyBlock" -> file: canvases/CanvasListingPage.html, block: MyBlock
  • "canvases/CanvasListingPage:" -> file: canvases/CanvasListingPage.html, block: "" (entire file)

Guide: /goapplib/guide/routing/#register

PageGroup

type PageGroup[AC any] interface {
	// RegisterRoutes returns a ServeMux with all routes for this group.
	// Patterns should be relative (prefix is stripped by RegisterGroup).
	RegisterRoutes(app *App[AC]) *http.ServeMux
}

PageGroup is the interface for a group of related pages. Implement this to define a set of routes under a common prefix.

Guide: /goapplib/guide/routing/#groups

RateLimitConfig

type RateLimitConfig struct {
	// Auth endpoints (login, signup, forgot-password) - stricter limits
	AuthLimit  int
	AuthWindow time.Duration

	// API endpoints - more permissive
	APILimit  int
	APIWindow time.Duration
}

RateLimitConfig holds configuration for different rate limit tiers.

DefaultRateLimitConfig

func DefaultRateLimitConfig() *RateLimitConfig

DefaultRateLimitConfig returns sensible defaults for rate limiting.

RateLimitMiddleware

type RateLimitMiddleware struct {
	// contains filtered or unexported fields
}

RateLimitMiddleware creates HTTP middleware that applies rate limiting.

NewRateLimitMiddleware

func NewRateLimitMiddleware(config *RateLimitConfig) *RateLimitMiddleware

NewRateLimitMiddleware creates rate limiting middleware with the given config.

NewRateLimitMiddlewareWithKeyFunc

func NewRateLimitMiddlewareWithKeyFunc(config *RateLimitConfig, keyFunc func(*http.Request) string) *RateLimitMiddleware

NewRateLimitMiddlewareWithKeyFunc creates middleware with a custom key function.

RateLimitMiddleware.Wrap

func (m *RateLimitMiddleware) Wrap(next http.Handler) http.Handler

Wrap wraps any handler with the API rate limiter. This is a convenience method for handlers that aren't auth-specific.

RateLimitMiddleware.WrapAPI

func (m *RateLimitMiddleware) WrapAPI(next http.Handler) http.Handler

WrapAPI wraps an API handler with rate limiting.

RateLimitMiddleware.WrapAuth

func (m *RateLimitMiddleware) WrapAuth(next http.Handler) http.Handler

WrapAuth wraps an auth handler with rate limiting.

RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides a simple in-memory rate limiting using sliding window. For production with multiple instances, consider using Redis-based rate limiting.

NewRateLimiter

func NewRateLimiter(limit int, window time.Duration) *RateLimiter

NewRateLimiter creates a new rate limiter with the specified limit per window.

RateLimiter.Allow

func (rl *RateLimiter) Allow(key string) bool

Allow checks if a request from the given key should be allowed.

SampleLoginPage

type SampleLoginPage[AC any] struct {
	BasePage
	CallbackURL string
	CsrfToken   string
	Config      LoginConfig
}

SampleLoginPage provides sample login page functionality. Embed this in your app-specific login page struct.

SampleLoginPage.Load

func (p *SampleLoginPage[AC]) Load(r *http.Request, w http.ResponseWriter, app *App[AC]) (err error, finished bool)

Load implements View[AC] for SampleLoginPage.

SampleProfilePage

type SampleProfilePage[AC any] struct {
	BasePage

	// User information
	UserID            string
	Nickname          string
	Email             string
	EmailVerified     bool
	Username          string
	Profile           map[string]any
	VerificationSent  bool
	VerificationError string
}

SampleProfilePage provides sample profile page functionality. Embed this in your app-specific profile page struct.

SampleProfilePage.Load

func (p *SampleProfilePage[AC]) Load(r *http.Request, w http.ResponseWriter, app *App[AC]) (err error, finished bool)

Load implements View[AC] for SampleProfilePage.

SampleRegisterPage

type SampleRegisterPage[AC any] struct {
	BasePage
	CallbackURL    string
	CsrfToken      string
	Name           string
	Email          string
	Password       string
	VerifyPassword string
	Errors         map[string]string
}

SampleRegisterPage provides sample registration page functionality. Embed this in your app-specific register page struct.

SampleRegisterPage.Load

func (p *SampleRegisterPage[AC]) Load(r *http.Request, w http.ResponseWriter, app *App[AC]) (err error, finished bool)

Load implements View[AC] for SampleRegisterPage.

SortOption

type SortOption struct {
	Value    string
	Label    string
	Selected bool
}

SortOption represents a sort dropdown option

View

type View[AC any] interface {
	// Load prepares the view data from the request.
	// app provides access to the application context and templates.
	// Returns (error, finished):
	//   - error: non-nil if an error occurred (will be displayed)
	//   - finished: true if response was already written (redirect, etc.)
	Load(r *http.Request, w http.ResponseWriter, app *App[AC]) (err error, finished bool)
}

View is the interface that all pages/views must implement. AC is the application context type (e.g., *WeewarApp).

Guide: /goapplib/guide/views/

WebAppServer

type WebAppServer struct {
	Address       string
	GrpcAddress   string
	AllowLocalDev bool
}

WebAppServer provides a generic HTTP server with optional CORS and logging.

WebAppServer.StartWithHandler

func (s *WebAppServer) StartWithHandler(ctx context.Context, handler http.Handler, srvErr chan error, stopChan chan bool) error

StartWithHandler starts the HTTP server with the given handler.

WithAuth

type WithAuth struct {
	LoggedInUserId string // Current user's ID
	Username       string // Current user's display name
	IsLoggedIn     bool   // True if user is authenticated
	IsOwner        bool   // True if user owns the current entity
}

WithAuth provides authentication info. Embed this in page structs that need user info.

Guide: /goapplib/guide/views/#goapplibs-mixins

WithAuth.Load

func (p *WithAuth) Load(r *http.Request, w http.ResponseWriter, vc any) (error, bool)

Load is a no-op for WithAuth. Use LoadWithAuth to load auth info with your auth services.

WithAuth.LoadWithAuth

func (p *WithAuth) LoadWithAuth(r *http.Request, provider AuthProvider) (error, bool)

LoadWithAuth loads auth info using the provided auth services.

WithFiltering

type WithFiltering struct {
	Query    string // Search query
	Sort     string // Sort field/direction
	ViewMode string // Display mode: "grid", "table", etc.
}

WithFiltering provides search and sort support. Embed this in page structs that support filtering.

Guide: /goapplib/guide/views/#goapplibs-mixins

WithFiltering.Load

func (p *WithFiltering) Load(r *http.Request, w http.ResponseWriter, vc any) (error, bool)

Load implements Loader for WithFiltering.

WithHtmx

type WithHtmx struct {
	IsHtmx      bool   // True if this is an HTMX request
	IsBoosted   bool   // True if this is a boosted link
	Target      string // HX-Target header value
	Trigger     string // HX-Trigger header value
	TriggerName string // HX-Trigger-Name header value
	CurrentURL  string // HX-Current-URL header value
	Prompt      string // HX-Prompt header value
}

WithHtmx provides HTMX request detection. Embed this in page structs that need HTMX-aware rendering.

Guide: /goapplib/guide/htmx/#one-route-a-page-or-a-fragment

WithHtmx.Load

func (p *WithHtmx) Load(r *http.Request, w http.ResponseWriter, vc any) (error, bool)

Load implements Loader for WithHtmx.

WithHtmx.ShouldRenderFragment

func (p *WithHtmx) ShouldRenderFragment() bool

ShouldRenderFragment returns true if only a fragment should be rendered.

WithPagination

type WithPagination struct {
	CurrentPage int   // 0-indexed current page
	PageSize    int   // Items per page
	TotalCount  int   // Total number of items
	HasPrevPage bool  // True if there's a previous page
	HasNextPage bool  // True if there's a next page
	Pages       []int // Page numbers to display in pagination UI
}

WithPagination provides pagination support. Embed this in page structs that display paginated lists.

Guide: /goapplib/guide/views/#goapplibs-mixins

WithPagination.EvalPages

func (p *WithPagination) EvalPages()

EvalPages calculates page numbers to display.

WithPagination.Load

func (p *WithPagination) Load(r *http.Request, w http.ResponseWriter, vc any) (error, bool)

Load implements Loader for WithPagination.

WithPagination.NextPage

func (p *WithPagination) NextPage() int

NextPage returns the next page number.

WithPagination.Offset

func (p *WithPagination) Offset() int

Offset returns the offset for database queries.

WithPagination.Paginator

func (p *WithPagination) Paginator() *WithPagination

Paginator returns self for template access via .Paginator This allows templates to use {{ .Paginator.HasPrevPage }} etc. when the page struct embeds WithPagination.

WithPagination.PrevPage

func (p *WithPagination) PrevPage() int

PrevPage returns the previous page number.

WithPagination.SetTotal

func (p *WithPagination) SetTotal(total int, hasMore bool)

SetTotal updates pagination state based on total count.

WithPagination.TotalPages

func (p *WithPagination) TotalPages() int

TotalPages is how many pages TotalCount fills at PageSize, or 0 before SetTotal. goapplib's Pagination template shows it.

page

import "github.com/panyam/goapplib/page"

Package page describes which islands a page mounts and where, as a Spec the server writes into the page for the browser to read (tsappkit's island page mounts each island from a registry by name).

A layout template places the slots (elements with data-slot); the Spec says which island goes in each, how it's presented, and its config. The partial templates/page/Islands.html writes it as <script type="application/json" id="page-spec">.

An app that needs more in its spec (the things a page starts with, say) embeds Spec in its own type and writes it with ScriptJSON:

type Spec struct {
	page.Spec
	Things []Thing `json:"things"`
}

func (s Spec) JSON() template.JS {
	c := s
	c.Spec = s.Spec.Normalized()
	return page.ScriptJSON(c)
}

encoding/json flattens the embedded Spec, so the browser sees one object with layout, islands and things.

CheckIslands

func CheckIslands(known []string, specs ...Spec) error

CheckIslands reports every island the specs name that isn't in known, the names the browser's registry can mount. The page itself only finds out at runtime, with a console warning on whichever page names the missing island, so this is for a test that walks an app's specs:

known := append(assets.Names(), "toolbar") // lazy entries, plus those bundled with the entry
if err := page.CheckIslands(known, homeSpec, gameSpec); err != nil {
	t.Fatal(err)
}

It returns nil when every name is known, and otherwise one error listing each unknown name once, sorted, with the layouts that use it. It returns an error rather than taking a *testing.T so the page package doesn't import testing, which would add the test flags to every binary that imports page.

Guide: /goapplib/guide/islands/#checking-and-debugging

ScriptJSON

func ScriptJSON(v any) template.JS

ScriptJSON is v as JSON that's safe inside a <script> element: every '<', '>' and '&' is escaped, so no string in it can close the script or open a comment. A value that can't be encoded is written as null.

Assets

type Assets struct {
	// Entries are the page scripts (esbuild's entry points), by name.
	Entries map[string]Chunk `json:"entries"`
	// Islands are the lazy islands' chunks, by island name.
	Islands map[string]Chunk `json:"islands"`
}

Assets says which built files a page and its islands need, so a page can write <link rel="modulepreload"> for what it loads at once (see For and the IslandPreloads partial in templates/page/Islands.html). Each lazy island (tsappkit's lazy) is its own chunk, and code an island shares with the page's entry script goes into chunks the entry imports. Without preload links the browser only finds those chunks, and then their imports, after the entry has arrived and been parsed.

The JSON form is the shape any bundler's build can write:

{"entries": {"main": {"file": "/static/main.js", "imports": ["/static/chunks/chunk-Z.js"]}},
 "islands": {"hero": {"file": "/static/chunks/hero-X.js", "imports": ["/static/chunks/chunk-Y.js"]}}}

LoadAssets reads that; LoadEsbuildMetafile builds it from esbuild's metafile.

Guide: /goapplib/guide/islands/#lazy-islands-and-preload-links

LoadAssets

func LoadAssets(file string) (*Assets, error)

LoadAssets reads Assets in its JSON form from a file.

LoadEsbuildMetafile

func LoadEsbuildMetafile(file string, opts EsbuildOptions) (*Assets, error)

LoadEsbuildMetafile builds Assets from the metafile of an esbuild build run with --splitting --format=esm --metafile. An output with a source file that some other output reaches through a dynamic import() is an island chunk; any other output with a source file is an entry. Both are named by opts.Name, and their Imports are the chunks they reach through static imports. Two islands, or two entries, with the same name are an error, since the page couldn't tell which one it means.

Guide: /goapplib/guide/islands/#lazy-islands-and-preload-links

Assets.For

func (a *Assets) For(entry string, spec Spec) []string

For lists the chunks to preload on a page whose script is the entry named entry and whose islands are spec's: the entry's imports first, then each island that mounts at once (Load "" or "eager") followed by its imports, in spec order and without repeats. The entry file itself is left out, since the page's <script> loads it. Islands that wait (idle, visible, media) are left out too, since preloading them would download what the page means to put off.

An entry or island Assets doesn't know adds nothing (an island bundled with the entry, say), and a nil Assets gives nothing, so a page can call it whether or not the app loaded a manifest.

Assets.Names

func (a *Assets) Names() []string

Names lists the islands Assets has a chunk for, sorted: the registry's lazy entries, as CheckIslands wants them. Islands bundled with the entry aren't among them. A nil Assets has none.

Chunk

type Chunk struct {
	File    string   `json:"file"`
	Imports []string `json:"imports"`
}

Chunk is one built script and what it needs. File is its URL; Imports are the URLs of every chunk it statically imports, directly or through another chunk, in a stable order. They never include a chunk reached only through a dynamic import(), which is another island and loads when that island does.

EsbuildOptions

type EsbuildOptions struct {
	// OutDir is the output directory as the metafile writes it (the --outdir
	// relative to where esbuild ran, "dist" say). It's cut from the front of
	// each output path before URLPrefix is added.
	OutDir string
	// URLPrefix is where the page serves OutDir, such as "/static/".
	URLPrefix string
	// Name gives the entry or island name for an output's source file (its
	// path as the metafile has it, "web/islands/hero.ts"). The default is the
	// file's base name without its extension ("hero", or "main" for
	// web/main.ts), so a registry entry `hero: lazy(() => import("./islands/hero"))`
	// needs no setting. Returning "" leaves that output out.
	Name func(source string) string
}

EsbuildOptions says how LoadEsbuildMetafile turns the metafile's paths into entry and island names and URLs.

Island

type Island struct {
	Name         string         `json:"name"`
	Slot         string         `json:"slot"`
	Presentation string         `json:"presentation,omitempty"`
	Config       map[string]any `json:"config"`
	// Load says when the browser mounts the island: "eager" (the default,
	// also written as ""), "idle" once the page has settled, "visible" when
	// its slot scrolls into view, or "media:<query>" while the media query
	// matches. Each mounts once. tsappkit's IslandPage (0.6.0 on) waits for
	// it; a deferred island mustn't be something another island or the page
	// needs at startup, since nothing waits for it.
	Load string `json:"load,omitempty"`
}

Island is one island on the page. Name picks the factory from the browser's registry; Slot is the data-slot of the element it mounts in. Presentation says how the layout shows it (an app's own words: "page", "panel", "strip"), for islands that draw differently in each. Config is handed to the factory as is, so it must be JSON.

Guide: /goapplib/guide/islands/#when-each-island-mounts

Spec

type Spec struct {
	// Layout names the arrangement of slots, for code that keeps state per
	// layout. The template that draws it is chosen by the page, not by this.
	Layout  string   `json:"layout"`
	Islands []Island `json:"islands"`
}

Spec is a page's layout and the islands it mounts, in mount order.

Guide: /goapplib/guide/islands/#the-go-side

Spec.JSON

func (s Spec) JSON() template.JS

JSON is the spec for a <script type="application/json"> element, written through ScriptJSON after Normalized.

Spec.Normalized

func (s Spec) Normalized() Spec

Normalized is a copy of the spec with a nil island list as empty and each nil Config as an empty map, so the browser always gets a list and objects rather than null. The spec itself is left alone.

Spec.Slots

func (s Spec) Slots() []string

Slots lists the slots the spec fills, in mount order.

Spec.Validate

func (s Spec) Validate() error

Validate reports a spec the browser couldn't mount as meant: no layout, an island without a name or with a slot name that isn't lowercase letters, digits and dashes, a load that isn't one of Island.Load's forms, or two islands in one slot. An app that extends the spec calls it from its own Validate and adds its own checks.

wasmhost

import "github.com/panyam/goapplib/wasmhost"

Package wasmhost runs an app's HTTP services (typically Connect handlers) as WebAssembly inside a browser Web Worker, answering the same generated clients a server answers.

A page pushes files in by name before it asks anything, and the handler reads them through one fs.FS (Root) whose top-level directories are the mounts. The page side lives in tsappkit (@panyam/tsappkit/wasmhost), which starts the worker and hands the Connect transport a fetch that posts to it.

The rules it encodes, each with a failure behind it (goapplib issue 32):

  • Never block inside a js.FuncOf callback. Every export returns a Promise and does its work on a goroutine, because a callback that waits on something the JS event loop must deliver (a fetch, a timer, a Promise) deadlocks the worker.
  • Push the files in before the request, never pull them during it. fs.FS is synchronous and every browser source of bytes is asynchronous, so the files go into memory first. State a service builds for itself is different: it reads and writes a Cache (BrowserCache in the browser, over the Origin Private File System), whose calls wait on the browser and so are made from a handler's goroutine, which is allowed to wait, never from a js.FuncOf callback.
  • Speak the app's existing wire protocol, so its generated clients don't know whether a server or the worker answered.

Host holds the platform-neutral part (mount table, handler, in-process requests) and builds and tests natively. Serve, ServeRebuild and Host.Export, which talk to JavaScript, are js && wasm only.

Constants and variables

var ErrMiss = errors.New("wasmhost: not in the cache")

ErrMiss is what Get returns for a key the cache has nothing under.

var ErrNoCache = errors.New("wasmhost: no cache in this browser")

ErrNoCache is what BrowserCache's methods return when the browser has no storage to offer the worker (no Origin Private File System, or a worker started without one). A service treats it as a miss and rebuilds.

var ErrNoHandler = errors.New("wasmhost: no handler")

ErrNoHandler is what Do returns before Handle or Rebuild has given the host a handler.

CacheKey

func CacheKey(parts ...[]byte) string

CacheKey is a cache key for inputs: the hex SHA-256 of the parts, each prefixed with its length, so ("ab", "c") and ("a", "bc") get different keys. Put a version string first, so a service that changes what it stores stops finding blobs an older build wrote.

Guide: /goapplib/guide/wasmhost-state/#a-cache-for-state-the-service-can-rebuild

Serve build: js && wasm

func Serve(ns string, handler http.Handler)

Serve answers requests with handler on globalThis[ns] and never returns. It is the whole main of a wasm build whose handler doesn't need the mounted files; one that does builds a Host, so it can pass Root to the handler, and calls Host.Serve.

Guide: /goapplib/guide/wasmhost/#the-pieces

ServeRebuild build: js && wasm

func ServeRebuild(ns string, build func(root fs.FS) (http.Handler, error))

ServeRebuild is Serve for a handler made over the mounted files, rebuilt on every mount change (see Host.Rebuild). A failed first build is logged to the console and reported to each request.

Guide: /goapplib/guide/wasmhost/#fixed-handlers-and-rebuilt-ones

Cache

type Cache interface {
	// Get returns a copy of the blob under key, or ErrMiss. A key that isn't one CacheKey could
	// make is an error rather than a miss.
	Get(ctx context.Context, key string) ([]byte, error)
	// Put stores b under key, replacing what was there. A reader never sees half a blob: it gets
	// the old one, the new one, or ErrMiss. The cache keeps its own copy of b.
	Put(ctx context.Context, key string, b []byte) error
}

Cache keeps state a service builds from its inputs and would rather not build again, such as a parsed design, a model or an index, so a reload or a restarted worker can skip the rebuild. Keys name the inputs (see CacheKey), not the blob, so a service computes the key from a request before it has anything cached, and the same inputs always find the same blob. In the browser it's BrowserCache, over the Origin Private File System, which outlives a reload; natively it's DirCache or MemCache.

Every worker the page starts for the same namespace sees the same BrowserCache, so a throwaway worker (tsappkit's oneShotFetch) can build a result through a large peak and Put it, and the long-lived worker Gets it without ever holding the peak.

It's a cache, not a datastore: anything in it must be rebuildable from its inputs, because a miss, ErrNoCache, a browser clearing the origin's storage, or any other error just means the service builds it again. Data a user would lose belongs in the app's server-side storage.

Get and Put may wait on the browser, so call them from a handler or another goroutine, never from inside a js.FuncOf callback (see the package doc). Implementations are safe for concurrent use.

Guide: /goapplib/guide/wasmhost-state/#a-cache-for-state-the-service-can-rebuild

BrowserCache build: js && wasm

func BrowserCache() Cache

BrowserCache is the Cache tsappkit's worker gives the wasm, over the Origin Private File System (wasmhost/<ns>/ in the page origin's private storage), so a blob Put before a reload is there for Get after it. The worker installs it as globalThis.wasmhostCache before Go starts; without one (no OPFS, or a worker from tsappkit before 0.6.4) every call returns ErrNoCache.

Each call waits on a JS Promise, so it must run on a goroutine, such as a handler's; ctx ends the wait, though the browser may still finish the write.

Guide: /goapplib/guide/wasmhost-state/#a-cache-for-state-the-service-can-rebuild

DirCache build: !(js && wasm)

func DirCache(dir string) Cache

DirCache is a Cache in a directory, one file per key, for a service running natively (on a server, or in tests). The directory is created on the first Put.

Chunk

type Chunk struct {
	Status int
	Header http.Header
	Body   []byte
}

Chunk is part of a response, sent when the handler calls Flush (http.Flusher). The first chunk of a response carries its status and header; later ones carry only body.

Host

type Host struct {
	// contains filtered or unexported fields
}

Host is a mount table and the handler that serves requests over it.

A Host is in one of two modes. After Handle it serves one fixed handler, which reads the live Root and so sees each mount change on its next read. After Rebuild it calls the build function again on every Mount and Unmount, for apps whose handler snapshots the files when it is made. All methods are safe for concurrent use.

Guide: /goapplib/guide/wasmhost/#testing-it-natively

New

func New(ns string) *Host

New returns an empty host whose JavaScript exports, once Export or Serve installs them, live on globalThis[ns].

Host.Add

func (h *Host) Add(name string, files map[string][]byte) error

Add puts files into the mount name, keeping the files it already holds; a file at a path the mount already has replaces it. A missing mount is created, as Mount would. It takes ownership of the byte slices, and in rebuild mode it rebuilds once for the whole batch.

Add checks the whole batch before writing anything, so an error (an invalid path, a path that is already a directory, a file under a file) leaves the mount as it was. With a fixed handler (Handle), a request running at the same moment may see some of the batch and not the rest; in rebuild mode the new handler is built after the last file is in.

Host.Do

func (h *Host) Do(ctx context.Context, req Request) (Response, error)

Do serves req in-process and returns the buffered response. An HTTP error status is a Response, not an error. The error is for no handler (ErrNoHandler), a failed rebuild, an unparseable request, or a handler panic, which is recovered so one bad request can't kill the worker.

Host.DoStream

func (h *Host) DoStream(ctx context.Context, req Request, onChunk func(Chunk)) (res Response, err error)

DoStream is Do for a handler that streams: each time it calls Flush, the bytes it has written since the last Flush go to onChunk, synchronously and in order, while the handler is still running. The returned Response holds only what was written after the last Flush; if anything was flushed, its Status and Header repeat the first chunk's. A nil onChunk buffers the whole response, as Do does. onChunk is called on the handler's goroutine and must not block on it.

Host.Export build: js && wasm

func (h *Host) Export() (release func())

Export installs the host's functions on globalThis[ns], creating that object if it is absent, and then calls globalThis[ns].ready() if the loader put one there. It returns a function that removes the exports and releases them. Serve calls it; tests and custom mains can call it directly.

The exports, all returning Promises:

http(method, url, headers, body, onChunk?, id?)
                                  resolves {status, headers, body: Uint8Array}. With onChunk, each
                                  Flush in the handler calls onChunk({status?, headers?, body})
                                  at once (Host.DoStream), and the final body is what came after
                                  the last flush. With a numeric id, cancel(id) can end the
                                  request's context.
cancel(id)                        cancels the context of request id, if it's still running; a
                                  handler sees it the next time it checks ctx, which a loop that
                                  never yields to JS never gets to do (end its worker instead)
mount(name, {path: Uint8Array})   resolves when the files are mounted (and, in rebuild mode, built)
add(name, {path: Uint8Array})     the same, but keeps the files the mount already holds (Host.Add)
unmount(name)                     resolves when the mount is gone
stats(gc?)                        resolves the Go heap from runtime.MemStats: {heapAlloc,
                                  heapInuse, totalAlloc, sys, numGC}, in bytes. heapAlloc counts
                                  garbage not yet collected; with gc true it runs a collection
                                  first, so heapAlloc is what the worker holds live, at the cost
                                  of a pause.

Arguments are copied into Go before the call returns, so the caller may transfer or reuse its buffers straight away.

Host.Handle

func (h *Host) Handle(handler http.Handler)

Handle makes handler the host's one fixed handler, leaving rebuild mode if it was in it.

Host.Mount

func (h *Host) Mount(name string, files map[string][]byte) error

Mount replaces the mount name with files, keyed by slash-separated path. It takes ownership of the byte slices. In rebuild mode it returns the build's error, and the mount stays in place either way.

Host.Namespace

func (h *Host) Namespace() string

Namespace is the global name the host's exports are installed under.

Host.Rebuild

func (h *Host) Rebuild(build func(root fs.FS) (http.Handler, error)) error

Rebuild puts the host in rebuild mode: build is called now with Root and again after every Mount and Unmount, and its handler serves until the next change. If build fails, requests fail with its error until a later build succeeds. The error from this first build is returned.

Host.Root

func (h *Host) Root() fs.FS

Root is the live mount table as one fs.FS: mount "docs" holding "a/b.txt" reads as "docs/a/b.txt". It is the same value on every call, so a handler can keep it.

Host.Serve build: js && wasm

func (h *Host) Serve(handler http.Handler)

Serve makes handler the host's handler, installs the exports, and never returns.

Host.ServeRebuild build: js && wasm

func (h *Host) ServeRebuild(build func(root fs.FS) (http.Handler, error))

ServeRebuild puts the host in rebuild mode with build, installs the exports, and never returns.

Host.Unmount

func (h *Host) Unmount(name string) error

Unmount removes the mount name, which is not an error if it is absent. In rebuild mode it returns the build's error.

MemCache

type MemCache struct {
	// contains filtered or unexported fields
}

MemCache is a Cache in memory, for tests and for a service with nowhere to persist. It forgets everything when the process ends.

MemCache.Get

func (m *MemCache) Get(_ context.Context, key string) ([]byte, error)

Get implements Cache.

MemCache.Put

func (m *MemCache) Put(_ context.Context, key string, b []byte) error

Put implements Cache.

Request

type Request struct {
	Method string
	URL    string
	Header http.Header
	Body   []byte
}

Request is one HTTP request as the worker receives it. URL is a path with an optional query ("/pkg.Service/Method?x=1"); the scheme and host the page used don't matter here.

Response

type Response struct {
	Status int
	Header http.Header
	Body   []byte
}

Response is the handler's answer, buffered whole.

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 = 1024

MaxLFSPointerSize 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)) error

BuildView 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) error

ValidName 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() string

CredentialKind returns "aws".

AWSCredentials.GoString

func (c AWSCredentials) GoString() string

GoString hides the secret from %#v as well.

AWSCredentials.String

func (c AWSCredentials) String() string

String 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() string

CredentialKind 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) Credentials

Bearer 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 string

FileVersion 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 string

Kind 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 string

Mode 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) Option

WithCredentials 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) Option

WithFixed 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)) Option

WithInUse 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) Option

WithLimits caps writes through the registry. A zero field keeps DefaultLimits' value. Drivers that snapshot take their own Limits.

WithRecheck

func WithRecheck(d time.Duration) Option

WithRecheck 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 string

RefKind 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) *Registry

NewRegistry 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.Referrer

BlobRefs 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) error

Delete 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) error

DeleteWebhook 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.FS

FS 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() string

Base returns the last element of the path, as path.Base does, and "" for the mount's root.

URI.Dir

func (u URI) Dir() URI

Dir returns the URI of the folder holding u, or u itself for the mount's root.

URI.IsZero

func (u URI) IsZero() bool

IsZero 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() string

String 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.

connections

import "github.com/panyam/goapplib/storage/connections"

Package connections names the sign-ins a server holds for third-party services, so a mount over a private repo can read it. Several mounts can share one connection, such as one GitHub App installation over many repos. A connection signs in either as the server or for one person.

A Connection record never holds a secret. It names where the secret is, as an oneauth secret reference ("env:NAME" or "file:/abs/path"), or, for a person's own token, keeps it sealed in oneauth's user-token store. The design and its threat note are at https://panyam.github.io/goapplib/reference/connections/.

Constants and variables

const (
	// DefaultEntraAuthority is the Entra authority host for public Azure. A KindEntra or
	// KindEntraUser connection's BaseURL overrides it, for a national cloud or a test's fake.
	DefaultEntraAuthority = "https://login.microsoftonline.com"

	// GraphScope is the scope a KindEntra connection asks for: every Microsoft Graph application
	// permission an admin granted the app registration.
	GraphScope = "https://graph.microsoft.com/.default"

	// GraphUserScope is the scope a KindEntraUser refresh asks for: the Graph permissions the
	// person consented to, and a new refresh token.
	GraphUserScope = "https://graph.microsoft.com/.default offline_access"

	// GraphResource is the resource a managed identity token is for.
	GraphResource = "https://graph.microsoft.com"

	// DefaultManagedIdentityURL is the Azure Instance Metadata Service's token endpoint, which a
	// VM, a scale set or an AKS node answers for its managed identity. WithManagedIdentityURL
	// overrides it.
	DefaultManagedIdentityURL = "http://169.254.169.254/metadata/identity/oauth2/token"
)
const DefaultAccessTTL = time.Minute

DefaultAccessTTL is how long CanRead keeps an answer for one viewer and source.

const GCSReadScope = "https://www.googleapis.com/auth/devstorage.read_only"

GCSReadScope is the OAuth scope a KindGCP connection's tokens carry. Mounts only read, so the token can't change a bucket.

const GrantedBySource = "grant:"

GrantedBySource is the connection ID CanRead returns when a SourceGrant admits the viewer. No connection can have this ID, since a store refuses a record whose ID fails Validate, and the ':' fails it. A caller compares the ID with GrantedBySource to tell a grant from a connection.

const LastUsedEvery = time.Hour

LastUsedEvery is how often the service writes a connection's LastUsed. A token request inside that window since the last write doesn't touch the record, so reading a token doesn't cost a store write on every request.

var (
	// ErrNotFound means no connection has that ID.
	ErrNotFound = errors.New("connections: not found")

	// ErrInvalid means a record fails Validate: a missing field, a field its Kind doesn't use,
	// or a secret reference that doesn't parse.
	ErrInvalid = errors.New("connections: invalid record")

	// ErrNotOwner means a ScopePerson connection was asked for a token by a request whose
	// viewer isn't its Owner, or by a request with no viewer.
	ErrNotOwner = errors.New("connections: viewer does not own this connection")

	// ErrNotConfigured means the Service lacks what a connection needs, such as a
	// KindGitHubUser connection on a service built without WithUserTokens.
	ErrNotConfigured = errors.New("connections: service not configured for this connection")

	// ErrNoSecret means a Sealed connection has no secret saved yet. SaveServerSecret saves one.
	ErrNoSecret = errors.New("connections: no sealed secret saved")

	// ErrReconnect means a person's token can't be refreshed, so they have to connect again.
	// It wraps oneauth's outbound.ErrReconnect.
	ErrReconnect = errors.New("connections: connect again")
)

The errors a store and the token-source call return, wrapped with detail. An app maps them onto its own transport with errors.Is. None of them carries a secret.

var ErrInvalidGrant = errors.New("connections: invalid source grant")

ErrInvalidGrant means a SourceGrant fails Validate: a missing source or viewer, or a viewer pattern with a '*' anywhere but its end.

var ErrNoAccess = errors.New("connections: no connection of the viewer's can read this source")

ErrNoAccess means none of the viewer's connections can read the source, or the viewer has none to that service.

EntraEndpoint

func EntraEndpoint(c Connection) oauth2.Endpoint

EntraEndpoint returns the OAuth endpoint of c's tenant, which an app's sign-in for a KindEntraUser connection uses, so its tokens come from the same authority the service refreshes them at. c must be a KindEntraUser connection.

UserTokenProvider

func UserTokenProvider(connectionID string) string

UserTokenProvider is the provider key a KindGitHubUser or KindEntraUser connection's token is kept under in oneauth's user-token store, beside the owner's subject. Keying by connection, not by "github", lets one person hold two GitHub connections, such as github.com and an Enterprise host.

Viewer

func Viewer(ctx context.Context) string

Viewer returns the subject WithViewer set, or "" for a request with no person, such as a background job.

ViewerClaims

func ViewerClaims(ctx context.Context) []string

ViewerClaims returns the claims WithViewerClaims set, or nil.

WithViewer

func WithViewer(ctx context.Context, subject string) context.Context

WithViewer returns ctx carrying the subject of the person a request is for. The app sets it from its auth, and a ScopePerson connection gives a token only when it matches Owner.

WithViewerClaims

func WithViewerClaims(ctx context.Context, claims ...string) context.Context

WithViewerClaims returns ctx carrying claims about the viewer that the app vouches for, such as "oidc:group:hw" for a group the identity provider named at sign-in (agni#1896). A SourceGrant pattern matches the viewer's subject or any one of these, so a grant can follow a group rather than a list of people. The app spells each claim so that no subject can equal it. Claims count only beside a viewer, and they never pick a connection or a token.

Connection

type Connection struct {
	// ID names the connection in mount records, beside Owner. It follows the mount name rule.
	// IDs are unique per owner, so two people can each keep a connection named "gh", and a server
	// connection can share an ID with a person's.
	ID string

	Kind  Kind
	Scope Scope

	// Owner is the subject of the person a ScopePerson connection belongs to, as the app's
	// auth knows them. It is empty for ScopeServer. A connection's key is Owner and ID together.
	Owner string

	// Name is what a settings page shows, such as "acme org (App)".
	Name string

	// BaseURL is the service's API root. Empty means https://api.github.com. GitHub Enterprise
	// and tests set it. For KindEntra and KindEntraUser it is the Entra authority host instead,
	// and empty means https://login.microsoftonline.com.
	BaseURL string

	// AppID and InstallationID identify a KindGitHubApp installation.
	AppID          string
	InstallationID int64

	// KeyRef is a secret reference to a KindGitHubApp's private key, a KindAWS secret access
	// key, a KindGCP service account key (its JSON file), a KindEntra or KindEntraUser client
	// secret, a KindEntra certificate's private key, or a KindEntra workload identity's federated
	// token file.
	KeyRef string

	// AccessKeyID is a KindAWS access key's ID. AWS doesn't treat it as a secret, so the record
	// keeps it as it is. It is set exactly when KeyRef is.
	AccessKeyID string

	// RoleARN is a role a KindAWS connection assumes before signing, such as
	// "arn:aws:iam::123456789012:role/reader". Empty means none.
	RoleARN string

	// Region is a KindAWS connection's region, such as "us-east-1". Empty leaves it to the
	// driver.
	Region string

	// TenantID is a KindEntra or KindEntraUser connection's Entra tenant, as a GUID or a domain
	// such as "contoso.onmicrosoft.com".
	TenantID string

	// ClientID is a KindEntra or KindEntraUser connection's app registration (its application
	// ID), or a user-assigned managed identity's client ID.
	ClientID string

	// EntraAuth says how a KindEntra connection signs in.
	EntraAuth EntraAuth

	// CertRef is where a KindEntra EntraCertificate connection's certificate is, as a secret
	// reference to its PEM. The certificate isn't secret, but it sits beside the key it names.
	CertRef string

	// TokenRef is where a KindGitHubToken's token is, as a secret reference.
	TokenRef string

	// Pasted is set on a KindGitHubUser connection when the person pasted the stored token, so
	// the app's OAuth flow never issued it. Disconnect then deletes the token without revoking
	// it, since GitHub refuses to revoke a token through an app that didn't issue it.
	// SavePastedToken sets it and SaveUserToken clears it.
	Pasted bool

	// Sealed is set on a server connection whose secret is sealed in the user-token store, under
	// the service's master key, rather than named by a reference. SaveServerSecret writes it, and
	// nothing reads it back out. The field that would hold the reference stays empty: TokenRef
	// for KindGitHubToken, and KeyRef for KindGitHubApp, KindAWS, KindGCP and a KindEntra secret
	// or certificate. A KindEntra certificate's CertRef is still a reference.
	Sealed bool

	Status Status

	// LastError is the last failure's message, with no secret in it. It is empty when Status
	// is StatusOK.
	LastError string

	Created  time.Time
	LastUsed time.Time
}

Connection is the record of one sign-in. Which fields apply depends on Kind, and Validate checks them.

Connection.Validate

func (c Connection) Validate() error

Validate checks that c's fields fit its Kind and Scope, and that every secret field is a secret reference rather than a secret. It never resolves a reference, so it works without the secret present, and its errors never repeat a field's value. Every failure wraps ErrInvalid.

EntraAuth

type EntraAuth string

EntraAuth says how a KindEntra connection proves it is its app registration.

const (
	// EntraSecret sends the client secret at KeyRef.
	EntraSecret EntraAuth = "secret"

	// EntraCertificate signs a client assertion (RFC 7523) with the private key at KeyRef. The
	// certificate at CertRef names the key to Entra, through the assertion's x5t header.
	EntraCertificate EntraAuth = "certificate"

	// EntraManagedIdentity asks the Azure host's managed identity endpoint for a token, so the
	// record holds no secret. ClientID, when set, picks a user-assigned identity. On App Service
	// or Container Apps, the app passes the host's endpoint with WithIdentityEndpoint.
	EntraManagedIdentity EntraAuth = "managed-identity"

	// EntraWorkloadIdentity sends a Kubernetes service account token as the client assertion,
	// as AKS workload identity does. KeyRef is a "file:" reference to the token, such as the
	// file the AKS webhook names in AZURE_FEDERATED_TOKEN_FILE. The cluster rotates that file, so
	// the service reads it again for each token request. The app registration ClientID needs a
	// federated credential that trusts the cluster's issuer and the service account.
	EntraWorkloadIdentity EntraAuth = "workload-identity"
)

Kind

type Kind string

Kind says how a connection signs in.

const (
	// KindGitHubApp signs in as a GitHub App installation. The server mints a JWT from the
	// App's private key (KeyRef) and trades it for an hour-long installation token.
	KindGitHubApp Kind = "github-app"

	// KindGitHubToken signs in with a fixed token, such as a personal access token, read from
	// TokenRef.
	KindGitHubToken Kind = "github-token"

	// KindGitHubUser signs in as a person who connected their own GitHub account through OAuth.
	// The token is sealed in oneauth's user-token store under UserTokenProvider(ID) and the
	// person's subject, and refreshed there.
	KindGitHubUser Kind = "github-user"

	// KindAWS signs S3 requests with SigV4. With KeyRef set, it uses the key pair of
	// AccessKeyID and the secret access key at KeyRef. With neither, it uses the AWS SDK's default
	// chain, such as an EC2 instance role or an IRSA role on Kubernetes. RoleARN, when set, is a
	// role to assume first. It is a server connection only.
	KindAWS Kind = "aws"

	// KindGCP signs Google Cloud Storage requests with an OAuth token. With KeyRef set, the token
	// comes from the service account key at KeyRef. Without it, from Application Default
	// Credentials, such as workload identity on GKE. It is a server connection only.
	KindGCP Kind = "gcp"

	// KindEntra signs Microsoft Graph requests as an app registration in Microsoft Entra ID,
	// TenantID and ClientID, with an OAuth token for GraphScope. EntraAuth says how it proves
	// itself: a client secret at KeyRef, a certificate (its private key at KeyRef and the
	// certificate at CertRef), the managed identity of the Azure host it runs on, or a Kubernetes
	// service account token at KeyRef through workload identity. It is a server connection only.
	KindEntra Kind = "entra"

	// KindEntraUser signs Microsoft Graph requests as a person who signed in to the app's Entra
	// app registration, TenantID and ClientID. The person's token is sealed in oneauth's
	// user-token store under UserTokenProvider(ID) and their subject, and refreshed there, as for
	// KindGitHubUser. KeyRef, when set, is the app registration's client secret, which a
	// confidential client sends with each refresh.
	KindEntraUser Kind = "entra-user"
)

Option

type Option func(*Service)

Option configures a Service.

WithAccessTTL

func WithAccessTTL(d time.Duration) Option

WithAccessTTL sets how long CanRead keeps an answer. Zero or less means DefaultAccessTTL.

WithClock

func WithClock(now func() time.Time) Option

WithClock sets the service's clock, which stamps LastUsed. Tests use it.

WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the client for calls to GitHub: installation tokens, refreshes and revokes. Nil means http.DefaultClient.

WithIdentityEndpoint

func WithIdentityEndpoint(endpoint, header string) Option

WithIdentityEndpoint points KindEntra EntraManagedIdentity connections at an App Service or Container Apps identity endpoint, in place of IMDS. Such a host sets the endpoint in IDENTITY_ENDPOINT and the secret header in IDENTITY_HEADER, and the app passes both:

connections.WithIdentityEndpoint(os.Getenv("IDENTITY_ENDPOINT"), os.Getenv("IDENTITY_HEADER"))

The service sends the header as X-IDENTITY-HEADER on each token request. Like WithManagedIdentityURL, it belongs to the service, so a stored record can't name another endpoint. An empty endpoint leaves IMDS in place.

WithManagedIdentityURL

func WithManagedIdentityURL(u string) Option

WithManagedIdentityURL points KindEntra EntraManagedIdentity connections at another token endpoint than DefaultManagedIdentityURL, such as a test's fake. It belongs to the service, not the record, so a stored record can never send the host's identity token somewhere else.

WithReadCheck

func WithReadCheck(f ReadCheck) Option

WithReadCheck sets the read check CanRead uses for a source whose scheme has none from WithReadCheckFor. It tries every one of the viewer's connections, so a token can reach a service it wasn't issued for: a KindEntraUser connection's token goes to GitHub, since an empty BaseURL means github.com to the GitHub check. Prefer WithReadCheckFor, which names the kinds. Without either, CanRead returns ErrNotConfigured.

WithReadCheckFor

func WithReadCheckFor(scheme string, f ReadCheck, kinds ...Kind) Option

WithReadCheckFor sets the read check for sources with scheme, such as "github" or "msgraph", and the connection kinds CanRead tries with it. A viewer's connection of any other kind is skipped, so its token never reaches that service:

connections.WithReadCheckFor("github", githubDriver.CanRead, connections.KindGitHubUser, connections.KindGitHubToken)
connections.WithReadCheckFor("msgraph", graphDriver.CanRead, connections.KindEntraUser)

No kinds means every kind, as WithReadCheck does. Setting a scheme again replaces its check.

WithSourceGrants

func WithSourceGrants(grants ...SourceGrant) Option

WithSourceGrants sets the grants CanRead checks before the viewer's connections. A viewer that matches a grant on the source gets GrantedBySource without a read check, even on a service with no read check for that scheme. Grants for one source add up.

The service copies the grants, so they are fixed once NewService returns, and a later WithSourceGrants in the same call replaces them. WithSourceGrants doesn't validate. A pattern that fails Validate matches nobody, so an app calls Validate on each grant first to report a typo.

WithUserTokens

func WithUserTokens(store outbound.UserTokenStore, masterKeyRef string, oauth *oauth2.Config) Option

WithUserTokens lets the service hold people's own tokens. store keeps them sealed with a key derived from the master key, which masterKeyRef names as a secret reference to 64 hex characters ("env:NAME" or "file:/abs/path"). oauth is the GitHub OAuth app's config, which refreshes a KindGitHubUser token and whose client ID and secret revoke one. A KindEntraUser connection builds its own config from its record, so it uses only store and the master key, and oauth may be nil when the service holds no GitHub users.

ReadCheck

type ReadCheck func(ctx context.Context, baseURL, source string, creds mounts.Credentials) (bool, error)

ReadCheck asks a service whether creds can read source, using the API at baseURL. It returns false with a nil error for a definite no, such as GitHub's 404 for a private repo, and also when baseURL isn't the host it serves. Any other failure is an error. The GitHub driver's CanRead method is one.

Scope

type Scope string

Scope says whose sign-in a connection is.

const (
	// ScopeServer signs in as the server. Anyone the app lets read a mount reads it through the
	// connection, so the app's own sharing rules decide who sees what.
	ScopeServer Scope = "server"

	// ScopePerson signs in for Owner alone. Only a request whose viewer is Owner gets a token,
	// so GitHub decides what that person can read.
	ScopePerson Scope = "person"
)

Service

type Service struct {
	// contains filtered or unexported fields
}

Service hands out credentials for connections, and connects and disconnects people. It reads records from a Store and builds each connection's token source from oneauth's outbound package:

  • KindGitHubApp: one outbound.GitHubAppInstallation per connection, kept while the record is unchanged, so every mount on the connection shares its cached installation token.
  • KindGitHubToken: outbound.NewStatic over TokenRef.
  • KindGitHubUser: oneauth's outbound.UserTokens under UserTokenProvider(ID) and the owner's subject. It needs WithUserTokens.
  • KindGCP: a Google token source from the service account key at KeyRef, or Application Default Credentials when KeyRef is empty.
  • KindAWS: an AWS key pair, or the AWS default chain, which the S3 driver signs with.
  • KindEntra: a Microsoft Graph token from the tenant's token endpoint, for a client secret, a certificate or a workload identity's federated token, or from the host's managed identity endpoint.
  • KindEntraUser: oneauth's outbound.UserTokens, as for KindGitHubUser, refreshed at the tenant's token endpoint. It needs WithUserTokens for the store and the master key.

A Service is safe for concurrent use. Several processes can share one Store and one user-token store, since oneauth refreshes a person's token with compare-and-swap.

NewService

func NewService(store Store, opts ...Option) *Service

NewService returns a service over store. Without WithUserTokens, a KindGitHubUser or KindEntraUser connection returns ErrNotConfigured.

Service.CanRead

func (s *Service) CanRead(ctx context.Context, source string) (string, error)

CanRead returns the ID of a connection of the viewer's that can read source, such as "github://acme/board". An app calls it to decide whether to show a person something it linked from a private repo, as agni#1728 does.

A request with no viewer returns ErrNotOwner. Next, a SourceGrant on source that matches the viewer or one of its claims (WithViewerClaims) returns GrantedBySource with a nil error (WithSourceGrants). A grant answer asks no service and isn't kept, since the grants never change.

Otherwise it picks the read check by the source's scheme (WithReadCheckFor), or the WithReadCheck one. It tries the viewer's own connections of that check's kinds in ID order, each with its credentials, and returns the first one the read check says can read. When none can, or the viewer has no connection, it returns ErrNoAccess. When a check failed and none succeeded, it returns that failure instead of ErrNoAccess, since the answer isn't known.

A yes or a no is kept for the access TTL per viewer and source, so a page that checks many links asks GitHub once per repo. A failure isn't kept. SaveUserToken, SavePastedToken and Disconnect forget the owner's kept answers, and so does ForgetAccess. Server connections are never tried, since they would answer for the server rather than the person.

Service.Credentials

func (s *Service) Credentials(ctx context.Context, owner, id string) (mounts.Credentials, error)

Credentials returns how owner's connection id signs in, as mounts.Credentials. An empty owner names a server connection. The signature fits the mounts registry's WithCredentials option.

The GitHub kinds, KindGCP and the Entra kinds return mounts.BearerCredentials. KindAWS returns mounts.AWSCredentials with its secret resolved from KeyRef, or with DefaultChain set when the record names no key.

A person's connection gives credentials only when Viewer(ctx) is owner. Otherwise Credentials returns ErrNotOwner without reading the store, so the error says nothing about whether owner has a connection with that ID. A request with no viewer gets ErrNotOwner too. A missing connection returns ErrNotFound. A user connection without WithUserTokens returns ErrNotConfigured.

A bearer source's Token returns ErrReconnect, wrapping outbound.ErrReconnect, when a person's token can't be refreshed, and sets the record's Status to StatusReconnect. Any other failure sets StatusFailed. LastError gets the message, which never holds a token. The next token that works sets Status back to StatusOK.

Credentials also stamps the record's LastUsed, at most once per LastUsedEvery.

Service.Disconnect

func (s *Service) Disconnect(ctx context.Context, owner, id string) error

Disconnect removes owner's connection id, where an empty owner names a server connection. It doesn't check the viewer, so the app decides who may disconnect what. For a KindGitHubUser connection it first revokes the token at GitHub and deletes it from the user-token store, through oneauth's UserTokens.Revoke. When the revoke fails it returns the error and keeps both the token and the record, so the app can retry. When the record's Pasted is set, it deletes the token with no call to GitHub, since the app didn't issue it and can't revoke it. Other kinds have nothing to revoke here: an App installation is removed on GitHub, and a fixed token by whoever issued it. A Sealed connection's secret is deleted first, and when that fails Disconnect returns the error and keeps the record. Without WithUserTokens that is ErrNotConfigured. A KindEntraUser token is deleted with no call to Entra, since Entra has no endpoint that revokes one token; the person removes the app's consent in their account to end it there. A missing connection is not an error. Once the record is gone, CanRead forgets the owner's kept answers.

Service.ForgetAccess

func (s *Service) ForgetAccess(viewer string)

ForgetAccess drops every answer CanRead keeps for viewer, so the next call asks the service again. The service forgets on its own when SaveUserToken, SavePastedToken or Disconnect changes a person's connection. An app that adds, changes or removes a person's connection through the Store calls ForgetAccess after the write, or the person waits out the access TTL. A CanRead already running for viewer still returns its answer, but doesn't keep it.

Service.SavePastedToken

func (s *Service) SavePastedToken(ctx context.Context, owner, id string, tok *oauth2.Token) error

SavePastedToken keeps tok as the token of owner's KindGitHubUser connection id, as SaveUserToken does, for a token the person pasted rather than one the app's OAuth flow issued. It sets the record's Pasted, so Disconnect deletes the token without asking GitHub to revoke it. GitHub refuses that revoke for a token the app didn't issue. A later SaveUserToken clears Pasted.

Service.SaveServerSecret

func (s *Service) SaveServerSecret(ctx context.Context, id, secret string) error

SaveServerSecret seals secret as server connection id's secret: its token, App private key, AWS secret access key, GCP service account key or Entra client secret or certificate key, by Kind. The record must have Sealed set. Saving again replaces the secret, and every process sharing the stores picks up the new one on its next Credentials call. Saving clears a failed Status, and CanRead forgets its kept answers for requests with no viewer.

It needs WithUserTokens for the store and the master key, and returns ErrNotConfigured without it. A missing connection is ErrNotFound. A person connection, a record without Sealed, or an empty secret is ErrInvalid. The service never hands the secret back.

Service.SaveUserToken

func (s *Service) SaveUserToken(ctx context.Context, owner, id string, tok *oauth2.Token) error

SaveUserToken keeps tok as the token of owner's KindGitHubUser or KindEntraUser connection id, sealed, and sets the record's status back to StatusOK. The app calls it from its OAuth callback after a person connects, with the viewer set to owner. Any other viewer gets ErrNotOwner. The token must come from the app's own OAuth flow, since Disconnect revokes it through the app. A pasted token goes through SavePastedToken. Once the token is saved, CanRead forgets the owner's kept answers, so a no from before the person connected doesn't outlive the connection.

SourceGrant

type SourceGrant struct {
	Source  string
	Viewers []string
}

SourceGrant lets viewers read Source without a connection of their own. An app sets grants when the server's own access to a source stands for the people it signs in, such as a team's server whose operator has already chosen who may sign in (agni#1889).

Source matches a CanRead source byte for byte, such as "github://acme/board". CanRead doesn't fold case, trim a trailing '/' or drop a ".git", so "github://Acme/board" doesn't match. A source spelled another way goes on to the viewer's connections as before.

Each Viewers entry is one of three patterns:

  • "*" matches any viewer.
  • A prefix and a final '*', such as "local:*", matches a viewer that starts with the prefix and has at least one more character, so "local:*" matches "local:carol" but not "local:".
  • Anything else without a '*' matches that one viewer exactly.

A pattern matches the viewer's subject, or any claim WithViewerClaims set, so "oidc:group:hw" admits a viewer whose claims include it. A grant never admits a request with no viewer, whatever its claims.

SourceGrant.Validate

func (g SourceGrant) Validate() error

Validate checks that g has a source of the form scheme://rest with no '*', and at least one viewer pattern. A pattern is non-empty and has no '*' except as its last character. Every failure wraps ErrInvalidGrant and names the bad value, since a grant holds no secret.

Status

type Status string

Status records the last thing the server learned about a connection's sign-in.

const (
	// StatusOK means the last token request worked, or none has been made.
	StatusOK Status = "ok"

	// StatusReconnect means the person's token can't be refreshed, so they have to connect
	// again. It follows oneauth's outbound.ErrReconnect.
	StatusReconnect Status = "reconnect"

	// StatusFailed means the last token request failed for another reason, in LastError.
	StatusFailed Status = "failed"
)

Store

type Store interface {
	// GetConnection returns owner's record with that ID, or ErrNotFound. Another owner's record
	// with the same ID is also ErrNotFound.
	GetConnection(ctx context.Context, owner, id string) (Connection, error)

	// ListConnections returns the connections owned by owner, in ID order. An empty owner lists
	// the ScopeServer ones.
	ListConnections(ctx context.Context, owner string) ([]Connection, error)

	// PutConnection creates c, or replaces the record with c.Owner and c.ID. It calls Validate
	// first.
	PutConnection(ctx context.Context, c Connection) error

	// DeleteConnection removes owner's record with that ID. Deleting a missing record is not an
	// error. Revoking a person's token and deleting it from the user-token store is the caller's
	// job, before this.
	DeleteConnection(ctx context.Context, owner, id string) error
}

Store keeps connection records, keyed by owner and ID. An empty owner names a ScopeServer connection. Several processes may share one store.

blobs

import "github.com/panyam/goapplib/storage/blobs"

Package blobs keeps files by the SHA-256 of their contents. Each file is stored once, never changed, and removed only by a sweep that finds nothing pointing at it. A GitHub snapshot lands here, and so do an app's uploads.

A blob store differs from a cache such as wasmhost's: a cache may lose an entry and rebuild it, and a blob store may not. The design is at https://panyam.github.io/goapplib/reference/blobs/.

Constants and variables

var (
	// ErrNotFound means the store holds no blob with that hash.
	ErrNotFound = errors.New("blobs: not found")

	// ErrInvalidHash means a hash isn't "sha256:" and 64 lowercase hex digits.
	ErrInvalidHash = errors.New("blobs: invalid hash")

	// ErrCorrupt means a blob's bytes no longer hash to its name, because something changed or
	// truncated the stored file. Open's reader returns it at the end of the blob, in place of
	// io.EOF.
	ErrCorrupt = errors.New("blobs: contents don't match the hash")

	// ErrInvalidManifest means a manifest has a path that is absolute, unclean or climbs out,
	// a duplicate path, or a malformed hash.
	ErrInvalidManifest = errors.New("blobs: invalid manifest")
)
var ErrInvalidAlias = errors.New("blobs: invalid alias")

ErrInvalidAlias means an alias's namespace or ID isn't letters, digits, '_', '.' and '-', or is "." or "..".

Key

func Key(h Hash) (string, error)

Key returns where a store keeps h, relative to its root: "sha256/ab/cdef...", split after the first two hex digits. Dir uses this layout on disk, and a bucket store uses it under its prefix, so a tree of blobs copies between them unchanged. It returns ErrInvalidHash for a malformed h.

ManifestRefs

func ManifestRefs(ctx context.Context, s Store, h Hash, keep func(Hash)) error

ManifestRefs calls keep for the manifest h and for every file it lists, which is what a Referrer for a snapshot needs to pass to Sweep.

Verify

func Verify(rc io.ReadCloser, h Hash) io.ReadCloser

Verify wraps rc, the contents a store read for h, so that reading checks them against h. When the bytes don't match, the final Read returns ErrCorrupt in place of io.EOF, as Store.Open promises. A store outside this package returns it from Open.

Aliases

type Aliases interface {
	Store

	// Alias returns the hash id names in ns, and false when it names none.
	Alias(ctx context.Context, ns, id string) (Hash, bool, error)

	// SetAlias records that id in ns names h, replacing any earlier alias.
	SetAlias(ctx context.Context, ns, id string, h Hash) error
}

Aliases is a Store that also remembers which blob an outside ID names. Each ID lives in a namespace, such as "git" for git blob ids. A driver that lists a source's files with their own content IDs uses it to skip downloading a file the store already holds.

An alias is a hint. The blob it names can be swept, so a caller checks Has before trusting it.

Cached

type Cached struct {
	// contains filtered or unexported fields
}

Cached is a Linker that keeps a local Dir in front of a remote Store, such as a bucket store. An app whose blobs live in a bucket can then still build folder views, since views need blobs on this server's disk.

The remote holds every blob, and the local Dir holds copies. Put writes both before it returns, so a server that dies after Put loses nothing. Open and Link serve the local copy, and fetch it from the remote on a miss, so a local folder lost on restart refills on demand. Several servers may share one remote, each with its own Dir.

NewCached

func NewCached(remote Store, local *Dir, opts ...CachedOption) *Cached

NewCached returns a Cached that keeps every blob in remote and copies in local.

Cached.Alias

func (c *Cached) Alias(ctx context.Context, ns, id string) (Hash, bool, error)

Alias implements Aliases from the local Dir, so each server keeps its own aliases. A server whose folder was lost finds none, and its next fetch records them again. Callers check Has before using a hash, and Has asks the remote, so an alias never hands out a blob that is gone.

Cached.Has

func (c *Cached) Has(ctx context.Context, h Hash) (bool, error)

Has implements Store. It asks the local Dir first, then the remote.

func (c *Cached) Link(h Hash, to string) error

Link implements Linker. It fetches the blob from the remote first when the local Dir lacks it, and fails as Open does when it can't.

Cached.Open

func (c *Cached) Open(ctx context.Context, h Hash) (io.ReadCloser, error)

Open implements Store. On a local miss it fetches the blob from the remote and keeps it. A remote blob whose bytes don't match h fails with ErrCorrupt and is never kept locally. A blob neither holds returns ErrNotFound.

Cached.Put

func (c *Cached) Put(ctx context.Context, r io.Reader) (Hash, error)

Put implements Store. It writes the local copy first, then sends that copy to the remote, and returns only after both hold the blob. A remote that stores the bytes under some other hash fails the Put with ErrCorrupt.

Cached.SetAlias

func (c *Cached) SetAlias(ctx context.Context, ns, id string, h Hash) error

SetAlias implements Aliases in the local Dir.

Cached.Sweep

func (c *Cached) Sweep(ctx context.Context, grace time.Duration, refs ...Referrer) (int, error)

Sweep implements Store, and returns how many blobs it removed from the remote. It calls each referrer once and sweeps the remote and then the local Dir with what they named, so a local copy goes when its blob is unreferenced and older than grace. A local copy can outlive its remote blob by one sweep, when it was fetched after the remote wrote it. With WithMaxAge, it then drops every local copy older than the max age.

CachedOption

type CachedOption func(*Cached)

CachedOption configures a Cached.

WithMaxAge

func WithMaxAge(d time.Duration) CachedOption

WithMaxAge lets Sweep drop any local copy fetched or put more than d ago, whether or not a referrer names it, since the remote still holds the blob. The next Open or Link fetches it again. Zero, the default, keeps a referenced local copy for as long as the remote keeps it.

Dir

type Dir struct {
	// contains filtered or unexported fields
}

Dir is a Store and a Linker over a folder on this server's disk. A blob lives at <root>/sha256/ab/cdef..., which is agni's layout, so agni's existing blobs folder works as a Dir's root unchanged.

Writes go through a temp file and a rename, so a reader sees a whole blob or none, and several processes can share one Dir. Every read and removal goes through os.Root, so a link planted in the folder can't lead outside it.

NewDir

func NewDir(root string) (*Dir, error)

NewDir returns the Dir rooted at root, creating its folder if absent.

Dir.Alias

func (d *Dir) Alias(ctx context.Context, ns, id string) (Hash, bool, error)

Alias implements Aliases. An alias file that doesn't hold a valid hash counts as none.

Dir.Has

func (d *Dir) Has(ctx context.Context, h Hash) (bool, error)

Has implements Store.

func (d *Dir) Link(h Hash, to string) error

Link implements Linker. The copy fallback reads through Open, so it copies only a blob that still matches its hash.

Dir.Open

func (d *Dir) Open(ctx context.Context, h Hash) (io.ReadCloser, error)

Open implements Store.

Dir.Path

func (d *Dir) Path(h Hash) (string, error)

Path returns where h's blob is on disk, whether or not the Dir holds it, for a caller that builds a view some other way than Link. It returns ErrInvalidHash for a malformed h.

Dir.Put

func (d *Dir) Put(ctx context.Context, r io.Reader) (Hash, error)

Put implements Store.

Dir.SetAlias

func (d *Dir) SetAlias(ctx context.Context, ns, id string, h Hash) error

SetAlias implements Aliases. It writes through a temp file and a rename, so a reader sees the old alias or the new one.

Dir.Sweep

func (d *Dir) Sweep(ctx context.Context, grace time.Duration, refs ...Referrer) (int, error)

Sweep implements Store. It also removes temp files older than grace, which a Put that crashed left behind.

Hash

type Hash string

Hash names a blob: "sha256:" and 64 lowercase hex digits. It is agni's format.

HashOf

func HashOf(b []byte) Hash

HashOf returns the Hash of b.

HashOfKey

func HashOfKey(key string) (Hash, bool)

HashOfKey is the inverse of Key. It reports false for a key that names no blob, such as a stray object a person put under the store's prefix.

ParseHash

func ParseHash(s string) (Hash, error)

ParseHash checks that s is a Hash, and returns ErrInvalidHash if not.

PutManifest

func PutManifest(ctx context.Context, s Store, m Manifest) (Hash, error)

PutManifest checks m and stores it in s, sorted by path, so the same files give the same hash in any order. It doesn't check that s holds the files' blobs. It returns ErrInvalidManifest for a bad path or hash.

Spool

func Spool(r io.Reader, dir string) (*os.File, Hash, int64, error)

Spool copies r into a new temp file in dir (os.TempDir when empty), hashing as it goes, and returns the file rewound to its start with its hash and size. A store whose backend needs the key before the upload, such as a bucket, spools first. The caller closes and removes the file.

Linker

type Linker interface {
	Store

	// Link makes the file at to hold h's contents. It hard-links where the filesystem allows,
	// so the view takes no extra space, and copies where it doesn't. A linked file keeps its
	// contents after Sweep removes the blob. It returns ErrInvalidHash or ErrNotFound for a bad
	// or missing h.
	Link(h Hash, to string) error
}

Linker is a Store on this server's disk, whose blobs can appear as files in a folder view.

Manifest

type Manifest []ManifestEntry

Manifest lists the files of a view, such as a mount snapshot, and the blob holding each. It is stored as a blob itself, so a record names a whole snapshot with one hash however many files it has.

GetManifest

func GetManifest(ctx context.Context, s Store, h Hash) (Manifest, error)

GetManifest reads the manifest stored under h, checking it as PutManifest does.

ManifestEntry

type ManifestEntry struct {
	// Path is the file's place in the view: relative, clean and slash-separated.
	Path string `json:"path"`

	Hash Hash  `json:"hash"`
	Size int64 `json:"size"`
}

ManifestEntry is one file in a Manifest.

Referrer

type Referrer func(ctx context.Context, keep func(Hash)) error

Referrer lists the hashes one owner still names, by calling keep for each. Every owner of blobs in a store passes one to Sweep, such as an app's designs and the mounts registry's snapshots, and Sweep keeps the union.

Store

type Store interface {
	// Put stores what r yields and returns its hash. Putting contents the store already holds
	// writes nothing new, and counts as a fresh write for Sweep's grace period, so a sweep can't
	// remove the blob before the caller names it.
	Put(ctx context.Context, r io.Reader) (Hash, error)

	// Open returns the blob's contents. The reader checks the hash as it goes. If the bytes
	// don't match, the final Read returns ErrCorrupt in place of io.EOF, so only a caller who
	// reads to the end gets the check. A missing blob returns ErrNotFound.
	Open(ctx context.Context, h Hash) (io.ReadCloser, error)

	// Has reports whether the store holds h.
	Has(ctx context.Context, h Hash) (bool, error)

	// Sweep removes each blob that no referrer names and that was written more than grace ago,
	// and returns how many it removed. The grace period spares a blob that a caller has put but
	// not yet named in a record. If any referrer fails, Sweep removes nothing and returns that
	// error, since it can't know what is in use.
	Sweep(ctx context.Context, grace time.Duration, refs ...Referrer) (int, error)
}

Store keeps blobs. Several processes may share one, and Put is safe to call from all of them at once.

folder

import "github.com/panyam/goapplib/storage/mounts/folder"

Package folder is the mounts driver for a folder on the server's disk. Its mounts are live and writable, and have host paths. Only the server's configuration makes folder mounts (the registry refuses one from Create), so a client never picks the folder.

Every operation refuses links anywhere in a path, so a link inside the folder can't reach a file outside it, or a second name for a file inside it. Listings leave out links, devices and anything else that isn't a regular file or a folder.

Driver

type Driver struct {
	// contains filtered or unexported fields
}

Driver serves mounts.KindFolder mounts, whose Source is the folder's absolute path. It implements mounts.Writer, mounts.Localizer and mounts.VersionReader. It ignores credentials.

A write's IfMatch check and the write itself happen under a lock per file held in this Driver, so two writers in one process can't both pass the check. Writers in two processes, or two Drivers, can. Share one Driver per process.

New

func New(opts ...Option) *Driver

New returns a folder driver.

Driver.Delete

func (d *Driver) Delete(ctx context.Context, m mounts.Mount, creds mounts.Credentials, req mounts.DeleteRequest) (*mounts.WriteResult, error)

Delete removes req.Path when IfMatch is its current version or AnyVersion. Empty IfMatch never matches an existing file, so it returns ErrConflict. A missing file returns ErrNotFound. Delete leaves empty parent folders in place.

Driver.FetchAt

func (d *Driver) FetchAt(ctx context.Context, m mounts.Mount, creds mounts.Credentials, version string, f mounts.File) (blobs.Hash, bool, error)

FetchAt reads f from the folder as it is now and keeps it in the driver's blob store. fetched is true when the store didn't hold the contents yet. version is checked as ListAt checks it.

Driver.HostPath

func (d *Driver) HostPath(m mounts.Mount, p string) (string, error)

HostPath returns the absolute path of p in the folder. The file need not exist, so a native tool can write its output there. A path through a link returns ErrInvalidPath, and a file that is a Git LFS pointer returns ErrLFS. A folder's path is returned without looking at the files in it.

Driver.Kind

func (d *Driver) Kind() mounts.Kind

Kind returns mounts.KindFolder.

Driver.ListAt

func (d *Driver) ListAt(ctx context.Context, m mounts.Mount, creds mounts.Credentials, version, under string) ([]mounts.File, error)

ListAt walks the folder at under as it is now, or returns the one file under names. version is "" or one Resolve returned, and is ignored, since a folder can't be read as of an older version. Any other version returns ErrInvalidArgument. Links and anything else that isn't a regular file are left out, and a path through a link returns ErrInvalidPath.

Driver.ListRefs

func (d *Driver) ListRefs(ctx context.Context, source string, req mounts.ListRefsRequest, creds mounts.Credentials) (mounts.RefPage, error)

ListRefs returns an empty page. A folder has no tags and no commits.

Driver.Modes

func (d *Driver) Modes() []mounts.Mode

Modes returns mounts.ModeLive. A folder mount always shows the folder as it is now.

Driver.Moves

func (d *Driver) Moves(ctx context.Context, source, ref string, creds mounts.Credentials) (bool, error)

Moves returns true. A folder has no history, so a sync always reads it as it is now.

Driver.Open

func (d *Driver) Open(ctx context.Context, m mounts.Mount, creds mounts.Credentials) (fs.FS, error)

Open returns the folder's files as they are now. The fs.FS refuses a path through a link with an error wrapping ErrInvalidPath, and its listings leave links out, so fs.WalkDir sees only regular files and folders. Opening a Git LFS pointer fails with ErrLFS, naming the path.

Driver.Put

func (d *Driver) Put(ctx context.Context, m mounts.Mount, creds mounts.Credentials, req mounts.PutRequest) (*mounts.WriteResult, error)

Put writes req.Data to req.Path through a temp file and a rename, so a reader sees the old file or the new one and never part of either. It creates missing parent folders. The IfMatch check follows mounts.PutRequest. The result's Mount version is empty, since a folder has none.

Driver.Resolve

func (d *Driver) Resolve(ctx context.Context, source, ref string, creds mounts.Credentials) (string, error)

Resolve checks that source is an absolute path to a folder, and returns its version: "mtime:" and a hash over each regular file's path, size and modification time (goapplib issue 178). It reads no file's contents, so an app polls it to see whether a followed folder changed, and reads the files only when the version moved. A folder has no refs, so a non-empty ref returns ErrInvalidArgument, as does a relative path or a file. A missing folder returns ErrNotFound, and one over mounts.DefaultLimits' file count returns ErrTooLarge.

Driver.Stat

func (d *Driver) Stat(ctx context.Context, m mounts.Mount, creds mounts.Credentials, p string) (mounts.FileVersion, error)

Stat returns the file's version, "sha256:" and the hex SHA-256 of its contents. Content hashes, unlike modification times, don't change when nothing did, and can't collide when a file changes twice in one clock tick.

Option

type Option func(*Driver)

Option configures a Driver.

WithBlobs

func WithBlobs(store blobs.Store) Option

WithBlobs sets the blob store FetchAt keeps files in. Without it, FetchAt returns ErrInvalidArgument.

WithLinksInside

func WithLinksInside() Option

WithLinksInside lets reads follow a link whose target stays inside the mount's folder: listings, Open, HostPath, ListAt and FetchAt. A link that leads outside, directly or through another link, is still refused with ErrInvalidPath and left out of listings. Writes never go through a link. Without it, every link is refused, which is the default.

github

import "github.com/panyam/goapplib/storage/mounts/github"

Package github is the mounts driver for GitHub repositories, read and written through GitHub's REST API. A mount's Source is "github://owner/repo".

A snapshot mount pins a commit. When the mount is made, the driver downloads the commit's tarball into a blob store and writes a manifest, so the mount serves the same bytes for its whole life, and after a restart, without asking GitHub again. A live mount reads a branch through the Contents API, and each Put or Delete is one commit on it.

The driver sends each request with the bearer token of the mounts.BearerCredentials the registry hands it, which come from the mount's connection. Other kinds of credentials return ErrInvalidArgument. A private repo answers 404 to a request without a valid token, so the driver reports ErrNotFound for it, as GitHub intends.

Constants and variables

const DefaultBaseURL = "https://api.github.com"

DefaultBaseURL is GitHub's API root. GitHub Enterprise and tests set another with WithBaseURL.

const DefaultRawURL = "https://raw.githubusercontent.com"

DefaultRawURL is the host that serves a repo's files by commit and path. Its downloads don't count against the REST API's hourly limit, which is 60 requests for a caller with no token.

const MaxWebhookBytes = 25 << 20

MaxWebhookBytes caps the body ParsePush reads. GitHub caps a webhook payload at 25 MB.

var (
	// ErrBadSignature means a webhook delivery's X-Hub-Signature-256 is missing, malformed, or
	// isn't the HMAC-SHA256 of the body under the secret. A handler answers 401.
	ErrBadSignature = errors.New("github: bad webhook signature")

	// ErrPing means the delivery is the ping GitHub sends when a webhook is made. Its signature
	// checked out. A handler answers 200.
	ErrPing = errors.New("github: webhook ping")

	// ErrNotPush means the delivery is a signed event other than a push or a ping. A handler
	// answers 200 or 204 and ignores it.
	ErrNotPush = errors.New("github: webhook event isn't a push")
)

Driver

type Driver struct {
	// contains filtered or unexported fields
}

Driver serves mounts.KindGitHub mounts. It implements mounts.Preparer, mounts.Writer, mounts.Localizer, mounts.FetchingLocalizer and mounts.VersionReader. Share one Driver per process, since it caches manifests and builds each snapshot's folder view once.

New

func New(store blobs.Store, opts ...Option) *Driver

New returns a GitHub driver keeping snapshots in store. A nil store serves live mounts only, and Prepare refuses a snapshot with ErrInvalidArgument.

Driver.CanRead

func (d *Driver) CanRead(ctx context.Context, baseURL, source string, creds mounts.Credentials) (bool, error)

CanRead reports whether creds can read the repo at source. It fits connections.ReadCheck, so an app passes it to connections.WithReadCheck.

baseURL is the connection's API root, empty for github.com. A connection to another host than this driver serves gets false with no request, since its token means nothing here. A 404 is a definite no, and it is also how GitHub answers a private repo the token can't see. Any other failure, a rejected token included, is an error, since it says nothing about access.

Driver.Delete

func (d *Driver) Delete(ctx context.Context, m mounts.Mount, creds mounts.Credentials, req mounts.DeleteRequest) (*mounts.WriteResult, error)

Delete removes req.Path as one commit on the mount's branch. IfMatch must be the file's current version or AnyVersion; a stale one returns ErrConflict, and an empty one ErrInvalidArgument.

Driver.DeleteWebhook

func (d *Driver) DeleteWebhook(ctx context.Context, source, url string, creds mounts.Credentials) error

DeleteWebhook removes the repo's hooks that send to url. It lists the hooks first, so a 404 means the token can't manage them, which returns mounts.ErrPermissionDenied, and a hook that is already gone isn't an error.

Driver.EnsureWebhook

func (d *Driver) EnsureWebhook(ctx context.Context, source string, req mounts.WebhookRequest, creds mounts.Credentials) (mounts.Webhook, error)

EnsureWebhook makes a hook on the repo that sends req.Events to req.URL as JSON, signed with req.Secret, or updates the hook already sending to req.URL. It always sends the update, since GitHub never shows a hook's secret, so the driver can't tell whether it changed. The JSON content type lets ParsePush read each delivery as sent.

GitHub lets a token manage a repo's hooks only with admin rights on the repo, or a fine-grained token's webhooks permission. It answers 404 to a token that can read the repo but can't manage its hooks, so 404 and 403 return mounts.ErrPermissionDenied. 422, such as for a URL GitHub won't send to, returns mounts.ErrInvalidArgument with GitHub's message.

Driver.FetchAt

func (d *Driver) FetchAt(ctx context.Context, m mounts.Mount, creds mounts.Credentials, commit string, f mounts.File) (blobs.Hash, bool, error)

FetchAt keeps f's contents in the blob store. When the store is a blobs.Aliases that maps f.ID to a blob it holds, nothing is downloaded. A download is checked against f.ID before it's kept. A Git LFS pointer is swapped for its object, and f.ID then maps to the object's blob.

Driver.Fetches

func (d *Driver) Fetches(m mounts.Mount) bool

Fetches reports whether HostPath on m may download: a lazy snapshot. An eager snapshot is served from its manifest and the blob store, and a live mount has no host path.

Driver.HostPath

func (d *Driver) HostPath(m mounts.Mount, p string) (string, error)

HostPath returns where p of a snapshot mount is on disk, in the folder WithViews set. The first call for a mount builds its view there, as hard links to the blob store (copies where the filesystem refuses links), so a restart that lost the folder rebuilds it from the manifest without asking GitHub. A live mount, or a driver without WithViews or a linking blob store, returns ErrNotLocal. A lazy snapshot is fetched as HostPathWith fetches it, with no credentials, so only a public repo's files can be fetched this way.

Driver.HostPathWith

func (d *Driver) HostPathWith(ctx context.Context, m mounts.Mount, creds mounts.Credentials, p string) (string, error)

HostPathWith returns where p of m is on disk, as HostPath does. For a lazy snapshot it first fetches the file p names, or every file under the folder p names, into the view. The files under p must fit the driver's Limits, or it returns ErrTooLarge and fetches nothing, so a call for the root of a big repo fails while a call for one board in it works. A file already in the view is not fetched again. A snapshot with a Manifest, and a live mount, are handled as HostPath handles them.

Driver.Kind

func (d *Driver) Kind() mounts.Kind

Kind returns mounts.KindGitHub.

Driver.ListAt

func (d *Driver) ListAt(ctx context.Context, m mounts.Mount, creds mounts.Credentials, commit, under string) ([]mounts.File, error)

ListAt lists the files at commit under the path under, from one call to the trees API per commit. A tree GitHub truncates returns ErrTooLarge, since a partial list would hide files.

Driver.ListRefs

func (d *Driver) ListRefs(ctx context.Context, source string, req mounts.ListRefsRequest, creds mounts.Credentials) (mounts.RefPage, error)

ListRefs lists the repo's tags, or a branch's commits, newest first.

With a connection, tags come from one GraphQL query per page, ordered by their commit's date. GitHub orders by the commit's day only, then by name, so the driver sorts each page by time. Two tags made the same day on either side of a page break can still come out of order. A tag on something other than a commit, such as a tree, is left out.

GitHub's GraphQL API refuses a request with no token, so without a connection tags come from the REST tags API, which GitHub orders by version, newest first (v1.10 before v1.9). It gives no dates, so the driver reads each tag's commit too. Every request counts against GitHub's limit of 60 an hour without a token, so a page holds at most 10 tags, and a refusal for the limit returns ErrUnavailable saying a connection lifts it.

Commits come from the REST commits API, following parents from the branch's head. An empty Branch is the default branch. A missing branch returns ErrNotFound.

Driver.Modes

func (d *Driver) Modes() []mounts.Mode

Modes returns snapshot first, so a mount made with no mode is pinned.

Driver.Moves

func (d *Driver) Moves(ctx context.Context, source, ref string, creds mounts.Credentials) (bool, error)

Moves reports whether ref moves: an empty ref, which is the default branch, or a branch. A full commit sha doesn't, and neither does a tag.

Driver.Open

func (d *Driver) Open(ctx context.Context, m mounts.Mount, creds mounts.Credentials) (fs.FS, error)

Open returns the mount's files: a snapshot's from its manifest and the blob store, a lazy snapshot's from its tree, fetching each file on first open, or a live mount's from the Contents API at its branch. A live mount's fs.FS keeps ctx and creds for the requests it makes later.

Driver.Prepare

func (d *Driver) Prepare(ctx context.Context, m mounts.Mount, creds mounts.Credentials) (mounts.Mount, error)

Prepare finishes a new mount after Resolve. For a snapshot it downloads m.Version's tarball into the blob store and sets m.Manifest, or with WithLazySnapshots, and with WithLazyPastLimits for a commit past the limits, lists the tree at m.Version and leaves m.Manifest empty. For a live mount it sets m.Ref to the default branch when it is empty, so later writes name the branch. A live mount's Ref must be a branch, since GitHub commits a write onto a branch.

Driver.Put

func (d *Driver) Put(ctx context.Context, m mounts.Mount, creds mounts.Credentials, req mounts.PutRequest) (*mounts.WriteResult, error)

Put writes req.Data to req.Path as one commit on the mount's branch. An empty IfMatch sends no sha, so GitHub refuses to replace an existing file and Put returns ErrConflict. A stale IfMatch returns ErrConflict too. The result names the new commit and the file's new blob sha.

Driver.Resolve

func (d *Driver) Resolve(ctx context.Context, source, ref string, creds mounts.Credentials) (string, error)

Resolve checks the repo and returns the commit ref points at. An empty ref means the repo's default branch. A missing repo or ref returns ErrNotFound, and so does a private repo the token can't read.

Driver.SameSource

func (d *Driver) SameSource(a, b string) bool

SameSource reports whether a and b name one repo. GitHub ignores case in owner and repo names, and a trailing ".git" names the same repo.

Driver.Stat

func (d *Driver) Stat(ctx context.Context, m mounts.Mount, creds mounts.Credentials, p string) (mounts.FileVersion, error)

Stat returns the file's git blob sha, the version a Put or Delete passes as IfMatch. A folder returns ErrInvalidArgument, and a missing file ErrNotFound. A snapshot mount returns ErrReadOnly, since its files have no versions to write against.

Option

type Option func(*Driver)

Option configures a Driver.

WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL points the driver at another API root, such as a GitHub Enterprise host ("https://ghe.example.com/api/v3") or a test's fake.

WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the client for every request. The default is http.DefaultClient.

WithLFSURL

func WithLFSURL(u string) Option

WithLFSURL sets the web host whose "/{owner}/{repo}.git/info/lfs" serves the repo's LFS batch API, such as a test's fake. The default follows the API base: https://github.com for GitHub's own API, and the base without "/api/v3" for a GitHub Enterprise Server host.

WithLazyPastLimits

func WithLazyPastLimits() Option

WithLazyPastLimits makes Prepare snapshot a commit that fits the Limits whole, as a driver without this option does, and make one past them lazy, as WithLazySnapshots does (agni issue 1877). It lists the tree first, with each LFS object counted at its own size, so a commit past the limits downloads nothing before it is made lazy. A mount under the limits keeps an eager snapshot's guarantees: its view is rebuilt from the blobs alone, with no request to GitHub.

WithLazySnapshots

func WithLazySnapshots() Option

WithLazySnapshots makes Prepare pin a snapshot's commit and list its tree without downloading any file (agni issue 1877). The mount gets no Manifest. Open and HostPath then fetch a file the first time something reads it, so a server keeps only the files it serves. The Limits apply to each read rather than to the whole commit: one file for Open, and the files under a folder for HostPath. A repo whose boards together pass the cap can then be mounted, as long as no one folder that is read passes it.

With WithViews and a linking blob store, the view is the cache. The listing is kept at <views>/<mount>/<commit>.tree.json, and each fetched file is linked into the view, so a restart lists the mount and serves what it fetched without asking GitHub, and a blob sweep, which names no file of a lazy mount, leaves the view's links whole.

A snapshot an eager driver made keeps its Manifest and is served from it as before, so a server can turn this on over mounts it already has.

WithLimits

func WithLimits(l mounts.Limits) Option

WithLimits caps a snapshot's size and file count. A zero field keeps mounts.DefaultLimits' value. Past either, Prepare returns ErrTooLarge and stores no manifest.

WithRawURL

func WithRawURL(u string) Option

WithRawURL sets the host FetchAt downloads files from, by commit and path, such as a test's fake. The default is DefaultRawURL when the API base is GitHub's own. With another API base, such as GitHub Enterprise, and no raw URL, FetchAt uses the git blobs API instead.

WithViews

func WithViews(dir string) Option

WithViews sets the folder where HostPath builds each snapshot's view, as hard links to its blobs, at <dir>/<mount name>/<commit>. It needs a blob store that is a blobs.Linker. Without it, HostPath returns ErrNotLocal, and the snapshot is served only as an fs.FS.

Push

type Push struct {
	mounts.Change
	Delivery string
}

Push is one push event a GitHub webhook sent. Change is the push in the form every driver shares, for Registry.Following. Delivery is GitHub's id for the delivery, the same on a redelivery, so an app can drop a duplicate.

ParsePush

func ParsePush(r *http.Request, secret []byte) (Push, error)

ParsePush checks a GitHub webhook delivery's signature and reads the push it carries (goapplib issue 179). secret is the webhook's secret, which the app resolves from a secret reference, as connections do. An empty secret refuses every delivery, since anyone could sign under it.

It reads at most MaxWebhookBytes of the body, and checks X-Hub-Signature-256 as an HMAC-SHA256 of the raw body in constant time before reading anything from it. A body sent as application/x-www-form-urlencoded carries the JSON in its payload field, as GitHub sends it when the webhook's content type is set that way.

It returns ErrBadSignature for a missing or wrong signature, ErrPing for a ping, and ErrNotPush for any other event. A push's Source is "github://owner/repo", its Ref the branch or tag name with "refs/heads/" or "refs/tags/" taken off, and its Version the new commit. A deleted ref has Deleted set and no Version. A push to anything but a branch or a tag returns ErrNotPush.

bucket

import "github.com/panyam/goapplib/storage/mounts/bucket"

Package bucket serves mounts over an object store bucket, such as S3 or Google Cloud Storage, through the small Bucket interface. The SDK-specific drivers in storage/drivers/s3 and storage/drivers/gcs implement Bucket and hand it to New, so this package holds the listing, pinning and fs.FS logic once and never imports a cloud SDK.

A bucket has no commit, since no change spans several objects atomically. So Resolve lists the source's 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 is stored as a blob, and its hash is the mount's version. A snapshot mount then reads exactly the listed versions. Where an object is pinned by ETag and has changed since, reading it fails with the path named and mounts.ErrConflict, rather than serving the new bytes as the old version.

The same version works as a change check. Resolve again, and a new version means some object under the prefix was added, removed or changed.

Bucket

type Bucket interface {
	// List returns every object under prefix, at any depth, in key order. A prefix of "" lists
	// the whole bucket. It reports versions where the bucket keeps them.
	List(ctx context.Context, prefix string) ([]Object, error)

	// ListDir returns the objects directly under dir, and the names of the folders under it
	// (the common prefixes, without dir or the trailing "/"). dir is "" or ends in "/".
	ListDir(ctx context.Context, dir string) (files []Object, folders []string, err error)

	// Get reads an object. With pin nil it reads key's latest version. Otherwise it reads
	// pin.Version, or, when that is empty, the latest version only if its ETag is still
	// pin.ETag. The returned size is the object's length.
	Get(ctx context.Context, key string, pin *Object) (io.ReadCloser, int64, error)
}

Bucket is one bucket, signed in with one set of credentials. Methods return errors wrapping the mounts sentinels: ErrNotFound for a missing bucket or key, ErrConflict when a pinned version is gone or its ETag no longer matches, ErrPermissionDenied for a refusal, and ErrUnavailable for a network or server failure.

Connector

type Connector func(ctx context.Context, name string, creds mounts.Credentials) (Bucket, error)

Connector opens the bucket named name with creds. A nil creds means a public bucket. A kind of mounts.Credentials the service can't sign with returns mounts.ErrInvalidArgument.

Driver

type Driver struct {
	// contains filtered or unexported fields
}

Driver serves one kind of bucket mount. It implements mounts.Driver, mounts.Preparer, mounts.VersionReader and mounts.Localizer. It can't write, so a live mount is read-only.

New

func New(kind mounts.Kind, scheme string, connect Connector, store blobs.Store, opts ...Option) *Driver

New returns a driver for kind, whose sources look like "<scheme>://<bucket>/<prefix>". connect opens a bucket for each call. store keeps each Resolve's listing, which a snapshot mount and the VersionReader methods read back. With a nil store, live mounts work, Resolve still returns a version, and a snapshot mount returns mounts.ErrInvalidArgument.

Driver.ContainsSource

func (d *Driver) ContainsSource(mountSource, changed string) bool

ContainsSource reports whether changed, an object's source from a bucket event such as "s3://designs/boards/jetson/README.md", is mountSource or lies under it. Both must be this driver's scheme and name the same bucket, and the prefix must match whole path segments.

Driver.FetchAt

func (d *Driver) FetchAt(ctx context.Context, m mounts.Mount, creds mounts.Credentials, version string, f mounts.File) (blobs.Hash, bool, error)

FetchAt copies f's pinned version into the blob store and returns its hash. The object must be in the listing version names, with the same ID. When the store is a blobs.Aliases that maps the object's version id or ETag to a blob it holds, nothing is downloaded and fetched is false.

Driver.HostPath

func (d *Driver) HostPath(m mounts.Mount, p string) (string, error)

HostPath returns where p of a snapshot mount is on disk, in the folder WithViews set. The first call for a mount builds its view there, as links to the files Prepare fetched, so a restart that lost the folder rebuilds it from the blob store without asking the bucket. A live mount, a driver without WithViews or a linking store, or a snapshot made before views were set, returns mounts.ErrNotLocal.

Driver.Kind

func (d *Driver) Kind() mounts.Kind

Kind returns the kind New was given.

Driver.ListAt

func (d *Driver) ListAt(ctx context.Context, m mounts.Mount, creds mounts.Credentials, version, under string) ([]mounts.File, error)

ListAt lists the files of the listing version names, under the path under. Each File's ID is "version:" and the object's version id, or "etag:" and its ETag on a bucket without versions.

Driver.Modes

func (d *Driver) Modes() []mounts.Mode

Modes returns snapshot and live.

Driver.Moves

func (d *Driver) Moves(ctx context.Context, source, ref string, creds mounts.Credentials) (bool, error)

Moves reports true for the empty ref, the only one a bucket has, since the latest objects can change at any time.

Driver.Open

func (d *Driver) Open(ctx context.Context, m mounts.Mount, creds mounts.Credentials) (fs.FS, error)

Open returns a snapshot mount's files at the versions its listing pinned, or a live mount's latest objects. A snapshot whose files Prepare fetched reads them from the blob store and never asks the bucket. Otherwise, opening a snapshot file whose pinned version is gone, or whose ETag changed on a bucket without versions, fails with an fs.PathError naming the file and wrapping mounts.ErrConflict.

Driver.Prepare

func (d *Driver) Prepare(ctx context.Context, m mounts.Mount, creds mounts.Credentials) (mounts.Mount, error)

Prepare pins a snapshot mount to the listing its Resolve kept, by setting Manifest to a blobs.Manifest that lists the listing. With WithViews and a linking store, it also fetches each object at its pinned version into the store and lists it in the manifest, so the registry's BlobRefs keeps the files and a view can be rebuilt without the bucket. An object whose pinned version is gone fails as Open would, with mounts.ErrConflict. A live mount comes back unchanged.

Driver.Resolve

func (d *Driver) Resolve(ctx context.Context, source, ref string, creds mounts.Credentials) (string, error)

Resolve lists the source and returns the hash of the listing as the version, keeping the listing in the blob store when the driver has one. A bucket has no refs, so a non-empty ref returns mounts.ErrInvalidArgument. A missing bucket, or a prefix with no objects under it, returns mounts.ErrNotFound.

Object

type Object struct {
	// Key is the object's full key in the bucket.
	Key string `json:"key"`

	// Version is the bucket's version id for this object's contents, such as an S3 VersionId or
	// a GCS generation. It is empty when the bucket doesn't keep versions.
	Version string `json:"version,omitempty"`

	// ETag is the object's entity tag, as the bucket reports it.
	ETag string `json:"etag,omitempty"`

	Size int64 `json:"size"`
}

Object is one object under a source's prefix.

Option

type Option func(*Driver)

Option configures a Driver.

WithLimits

func WithLimits(l mounts.Limits) Option

WithLimits caps how many objects and bytes a source may hold. A zero field keeps mounts.DefaultLimits' value. Past either, Resolve returns mounts.ErrTooLarge.

WithViews

func WithViews(dir string) Option

WithViews sets the folder where HostPath builds each snapshot's view, as links to the blob store. It takes effect only when the store is a blobs.Linker, such as a blobs.Dir, or a blobs.Cached in front of a bucket store. Then Prepare fetches every file of a new snapshot into the store, so creating a snapshot mount downloads all of it, and Open reads the snapshot from the store instead of the bucket. Without it, HostPath returns mounts.ErrNotLocal.

Source

type Source struct {
	Bucket string
	// Prefix is the folder inside the bucket, clean, with no leading or trailing "/". Empty means
	// the whole bucket.
	Prefix string
}

Source is a parsed bucket source, such as "s3://designs/boards/jetson".

ParseSource

func ParseSource(scheme, source string) (Source, error)

ParseSource parses "<scheme>://<bucket>/<prefix>". The prefix may be empty. A prefix that is unclean, or climbs, returns mounts.ErrInvalidArgument.

s3

import "github.com/panyam/goapplib/storage/drivers/s3"

Package s3 serves mounts over prefixes in S3 buckets, "s3://<bucket>/<prefix>", through the AWS SDK. It is its own module so an app that doesn't mount S3 never downloads the SDK. The listing, pinning and fs.FS logic is in storage/mounts/bucket, and this package adapts S3 to its Bucket interface.

A snapshot pins each object's VersionId where the bucket has versioning on. Where it is off or suspended, or the connection may not list versions (s3:ListBucketVersions), it pins each object's ETag instead and reads it with If-Match. Such a read fails with mounts.ErrConflict once the object changes.

The driver signs with mounts.AWSCredentials, which a connections KindAWS connection gives. Nil credentials read a public bucket without signing. Any other kind returns mounts.ErrInvalidArgument.

Constants and variables

const DefaultRegion = "us-east-1"

DefaultRegion is the region a request goes to when neither the credentials nor WithRegion name one.

var (
	// ErrBadSignature means the request isn't a message SNS signed: the body isn't an SNS
	// message, the signing certificate isn't on an SNS host, or the signature doesn't match.
	// Answer 401 or 403.
	ErrBadSignature = errors.New("s3: SNS message not signed by SNS")

	// ErrSubscriptionConfirmation means the message asks the app to confirm a new SNS
	// subscription, or tells it one was removed. The returned SNSMessage carries SubscribeURL;
	// call ConfirmSubscription to accept, or ignore it to refuse. Answer 200 either way.
	ErrSubscriptionConfirmation = errors.New("s3: SNS subscription confirmation")
)

The errors ParseSNS returns. An app's handler maps them onto its answer with errors.Is.

DefaultSNSHost

func DefaultSNSHost(host string) bool

DefaultSNSHost reports whether host is a regional SNS endpoint, such as "sns.us-east-1.amazonaws.com". SNS serves its signing certificates only from these hosts, so a message naming a certificate anywhere else is forged.

New

func New(store blobs.Store, opts ...Option) *bucket.Driver

New returns a driver for mounts.KindS3. store keeps each Resolve's listing, as bucket.New describes. Clients are kept per set of credentials, so an assumed role's session is reused until it expires.

NewClient

func NewClient(ctx context.Context, creds mounts.Credentials, opts ...Option) (*s3.Client, error)

NewClient returns an S3 client signed with creds, built the way the mount driver builds its own, for other code in this module that talks to S3, such as s3blobs. A nil creds sends unsigned requests, for a public bucket. Bearer credentials return mounts.ErrInvalidArgument, since S3 signs every request with SigV4.

ParseEvent

func ParseEvent(body []byte) ([]mounts.Change, error)

ParseEvent reads an S3 event notification, as S3 delivers it to SQS, or as SNS wraps it, and returns one Change per object created or removed. Each Change's Source names the object, such as "s3://designs/boards/jetson/README.md", so Registry.Following finds every mount whose prefix holds it. Its Ref and Version are empty, since a bucket mount has no ref and an object event doesn't say what the mount's listing hash becomes; an app re-resolves the mounts it finds. S3's test event and other event types return no changes and no error.

Option

type Option func(*options)

Option configures the driver.

WithEndpoint

func WithEndpoint(url string) Option

WithEndpoint sends requests to url, with path-style addressing, in place of AWS's own S3. It is for an S3-compatible store, such as MinIO, or a test's fake.

WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the HTTP client for S3 and STS requests.

WithLimits

func WithLimits(l mounts.Limits) Option

WithLimits caps a source's objects and bytes, as bucket.WithLimits does.

WithRegion

func WithRegion(region string) Option

WithRegion sets the region for credentials that name none. The default is DefaultRegion.

WithViews

func WithViews(dir string) Option

WithViews sets the folder where HostPath builds snapshot views, as bucket.WithViews does. With a store that can link, creating a snapshot mount then downloads all of its files.

SNSMessage

type SNSMessage struct {
	Type      string
	MessageID string
	TopicArn  string
	Subject   string
	Message   string
	Timestamp string

	// SubscribeURL and Token are set on a SubscriptionConfirmation or UnsubscribeConfirmation.
	SubscribeURL string
	Token        string

	// Changes are the S3 changes a Notification carries, from ParseEvent.
	Changes []mounts.Change
	// contains filtered or unexported fields
}

SNSMessage is one message SNS delivered to an HTTPS subscription.

SNSVerifier

type SNSVerifier struct {
	// Client fetches signing certificates and confirms subscriptions. Nil means
	// http.DefaultClient.
	Client *http.Client

	// AllowHost reports whether a certificate or subscribe URL's host is SNS's. Nil means
	// DefaultSNSHost. A test points it at its own server.
	AllowHost func(host string) bool
	// contains filtered or unexported fields
}

SNSVerifier checks SNS message signatures. Its zero value is ready to use and fetches signing certificates with http.DefaultClient. Share one per process, since it caches certificates by URL.

SNSVerifier.ConfirmSubscription

func (v *SNSVerifier) ConfirmSubscription(ctx context.Context, m *SNSMessage) error

ConfirmSubscription accepts the subscription m asks about, by fetching its SubscribeURL. It refuses a URL whose host isn't SNS's, so a forged confirmation can't make the server fetch an address of the sender's choosing.

SNSVerifier.ParseSNS

func (v *SNSVerifier) ParseSNS(r *http.Request) (*SNSMessage, error)

ParseSNS reads one SNS delivery from r and checks its signature with v before trusting anything in it. A Notification returns its S3 changes in Changes. A subscription or unsubscription message returns the message with ErrSubscriptionConfirmation. A message that fails the check returns ErrBadSignature, and a body that isn't an SNS message returns mounts.ErrInvalidArgument.

gcs

import "github.com/panyam/goapplib/storage/drivers/gcs"

Package gcs serves mounts over prefixes in Google Cloud Storage buckets, "gs://<bucket>/<prefix>", through cloud.google.com/go/storage. It is its own module so an app that doesn't mount GCS never downloads the SDK. The listing, pinning and fs.FS logic is in storage/mounts/bucket, and this package adapts GCS to its Bucket interface.

Every GCS object has a generation, whether or not the bucket keeps old versions, so a snapshot always pins generations. On a bucket with versioning on, a snapshot keeps serving the old generation after the object changes. With it off, GCS drops the old generation, and reading it fails with mounts.ErrConflict and the path named.

The driver signs with mounts.BearerCredentials, which a connections KindGCP connection gives. Nil credentials read a public bucket without signing. Any other kind returns mounts.ErrInvalidArgument.

Constants and variables

const (
	GoogleIssuer     = "https://accounts.google.com"
	GoogleIssuerBare = "accounts.google.com"
	GoogleJWKS       = "https://www.googleapis.com/oauth2/v3/certs"
)

Google's issuer and signing keys for the OIDC tokens Pub/Sub sends. Google issues ID tokens with either issuer form, and its Pub/Sub docs say to accept both.

var ErrUnauthenticated = errors.New("gcs: Pub/Sub push not authenticated")

ErrUnauthenticated means a Pub/Sub push carried no bearer token, or one the PushVerifier refused. Answer 401 or 403, and Pub/Sub retries with backoff.

New

func New(store blobs.Store, opts ...Option) *bucket.Driver

New returns a driver for mounts.KindGCS. store keeps each Resolve's listing, as bucket.New describes.

NewClient

func NewClient(ctx context.Context, creds mounts.Credentials, opts ...Option) (*storage.Client, error)

NewClient returns a Cloud Storage client that sends creds' bearer token, built the way the mount driver builds its own, for other code in this module, such as gcsblobs. Nil creds sends no token, for a public bucket. AWS credentials return mounts.ErrInvalidArgument.

ParsePush

func ParsePush(r *http.Request, v PushVerifier) ([]mounts.Change, error)

ParsePush reads a Pub/Sub push carrying a GCS object notification, after v accepts its bearer token. It returns one Change for a finalized (created or overwritten) object, a deleted object, or changed metadata, whose Source names the object, such as "gs://designs/boards/jetson/README.md". Registry.Following then finds every mount whose prefix holds it. Ref and Version are empty, as in s3.ParseEvent. Other event types return no change and no error, so the app answers 200 and Pub/Sub doesn't retry them. A nil v returns mounts.ErrInvalidArgument, since an unauthenticated push endpoint lets anyone make the app re-resolve its mounts.

GoogleVerifier

type GoogleVerifier struct {
	// Audience is the audience the push subscription sets, usually the endpoint's URL. Required.
	Audience string

	// Email, when set, is the service account the subscription pushes as. A token for any other
	// account is refused. Leave it empty only when the audience alone is secret enough.
	Email string

	// Issuer, when set, is the one issuer a token must carry. Empty accepts either of Google's
	// forms, GoogleIssuer or GoogleIssuerBare. JWKSURL defaults to GoogleJWKS. A test points them
	// at a fake.
	Issuer  string
	JWKSURL string

	// HTTPClient fetches the keys. Nil means http.DefaultClient.
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

GoogleVerifier checks a Pub/Sub push token's signature against Google's keys, its issuer (either of Google's two forms), its audience and, when Email is set, the service account that signed it. Share one per process, since it caches Google's keys. It fetches them on first use, and again when a token names an unknown key, so a key rotation needs no restart.

GoogleVerifier.VerifyPush

func (g *GoogleVerifier) VerifyPush(ctx context.Context, token string) error

VerifyPush checks token as the type comment describes.

Option

type Option func(*options)

Option configures the driver.

WithEndpoint

func WithEndpoint(url string) Option

WithEndpoint sends JSON API requests to url, such as a test's fake at "http://127.0.0.1:4443/storage/v1/", in place of Google's.

WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the base HTTP client. The driver adds the bearer token on top of its transport.

WithLimits

func WithLimits(l mounts.Limits) Option

WithLimits caps a source's objects and bytes, as bucket.WithLimits does.

WithViews

func WithViews(dir string) Option

WithViews sets the folder where HostPath builds snapshot views, as bucket.WithViews does. With a store that can link, creating a snapshot mount then downloads all of its files.

PushVerifier

type PushVerifier interface {
	// VerifyPush returns nil when token is a valid token for this endpoint, and an error saying
	// which check failed otherwise.
	VerifyPush(ctx context.Context, token string) error
}

PushVerifier checks the OIDC token Pub/Sub sends with an authenticated push subscription. GoogleVerifier is the one to use. A test passes its own.

gormstore

import "github.com/panyam/goapplib/storage/backends/gorm"

Package gormstore keeps mount records and connection records in a database through GORM, so several servers can share them without a shared folder. It works with any database GORM supports, such as PostgreSQL, MySQL or SQLite.

It is a Go module of its own, github.com/panyam/goapplib/storage/backends/gorm, so an app that keeps its records in a folder never downloads GORM.

Constants and variables

const ConnectionTable = "goapplib_connections_v2"

ConnectionTable is the table connection records live in. GORM can't change a table's primary key, so keying records by owner and ID took a new table. Before goapplib 0.7.23 they were in OldConnectionTable, keyed by ID alone.

const OldConnectionTable = "goapplib_connections"

OldConnectionTable is where connection records were before goapplib 0.7.23. NewConnectionStore copies its rows into ConnectionTable once and leaves it in place, so an older server can still read it during a rollout. Drop it by hand once every server runs 0.7.23 or later.

ConnectionStore

type ConnectionStore struct {
	// contains filtered or unexported fields
}

ConnectionStore is a connections.Store over a GORM database.

NewConnectionStore

func NewConnectionStore(db *gorm.DB) (*ConnectionStore, error)

NewConnectionStore migrates ConnectionTable in db and returns a store over it. When ConnectionTable is empty and OldConnectionTable exists, it copies the old table's rows in one transaction first, so records saved before goapplib 0.7.23 read back as they were.

ConnectionStore.DeleteConnection

func (s *ConnectionStore) DeleteConnection(ctx context.Context, owner, id string) error

DeleteConnection removes owner's row with that ID. Deleting a missing row is not an error.

ConnectionStore.GetConnection

func (s *ConnectionStore) GetConnection(ctx context.Context, owner, id string) (connections.Connection, error)

GetConnection returns owner's record with that ID, or connections.ErrNotFound.

ConnectionStore.ListConnections

func (s *ConnectionStore) ListConnections(ctx context.Context, owner string) ([]connections.Connection, error)

ListConnections returns the connections owned by owner, in ID order. An empty owner lists the server-scoped ones.

ConnectionStore.PutConnection

func (s *ConnectionStore) PutConnection(ctx context.Context, c connections.Connection) error

PutConnection validates c, then inserts it or replaces the row with c.Owner and c.ID. An invalid record returns connections.ErrInvalid and writes nothing.

MountStore

type MountStore struct {
	// contains filtered or unexported fields
}

MountStore is a mounts.RecordStore over a GORM database. Several servers can share one database: a create is exclusive across them, and each sees the others' changes through Generation.

NewMountStore

func NewMountStore(db *gorm.DB) (*MountStore, error)

NewMountStore migrates the goapplib_mounts and goapplib_mount_generation tables in db and returns a store over them.

MountStore.CreateMount

func (s *MountStore) CreateMount(ctx context.Context, m mounts.Mount) error

CreateMount inserts m and bumps the generation counter in one transaction. The insert skips a name that exists, and a skipped insert returns mounts.ErrExists, so of two servers creating the same name, one wins. A bad name returns mounts.ErrInvalidArgument.

MountStore.DeleteMount

func (s *MountStore) DeleteMount(ctx context.Context, name string) error

DeleteMount removes the record named name, and bumps the generation counter in the same transaction when there was one. Deleting a missing record is not an error.

MountStore.Generation

func (s *MountStore) Generation(ctx context.Context) (string, error)

Generation returns the counter that every create and delete bumps, as a decimal string.

MountStore.GetMount

func (s *MountStore) GetMount(ctx context.Context, name string) (mounts.Mount, error)

GetMount returns the record named name, or mounts.ErrNotFound.

MountStore.ListMounts

func (s *MountStore) ListMounts(ctx context.Context) ([]mounts.Mount, error)

ListMounts returns every record, in name order.

gaestore

import "github.com/panyam/goapplib/storage/backends/gae"

Package gaestore keeps mount records and connection records in Google Cloud Datastore (or Firestore in Datastore mode), so several servers can share them without a shared folder. A namespace keeps one app's or one tenant's records apart from another's.

It is a Go module of its own, github.com/panyam/goapplib/storage/backends/gae, so an app that keeps its records in a folder never downloads the Datastore SDK.

ConnectionStore

type ConnectionStore struct {
	// contains filtered or unexported fields
}

ConnectionStore is a connections.Store over Datastore.

NewConnectionStore

func NewConnectionStore(client *datastore.Client, namespace string) *ConnectionStore

NewConnectionStore returns a store over the connection records in namespace. An empty namespace is Datastore's default one.

ConnectionStore.DeleteConnection

func (s *ConnectionStore) DeleteConnection(ctx context.Context, owner, id string) error

DeleteConnection removes owner's record with that ID, including one from before parents existed. Deleting a missing record is not an error.

ConnectionStore.GetConnection

func (s *ConnectionStore) GetConnection(ctx context.Context, owner, id string) (connections.Connection, error)

GetConnection returns owner's record with that ID, or connections.ErrNotFound. With no record under the owner's parent, it falls back to an entity from before parents existed.

ConnectionStore.ListConnections

func (s *ConnectionStore) ListConnections(ctx context.Context, owner string) ([]connections.Connection, error)

ListConnections returns the connections owned by owner, in ID order. An empty owner lists the server-scoped ones.

ConnectionStore.PutConnection

func (s *ConnectionStore) PutConnection(ctx context.Context, c connections.Connection) error

PutConnection validates c, then writes it, replacing owner's record with c.ID. An invalid record returns connections.ErrInvalid and writes nothing. A person's entity from before parents existed with the same ID moves under its owner's parent in the same transaction, so a server record can't overwrite it.

MountStore

type MountStore struct {
	// contains filtered or unexported fields
}

MountStore is a mounts.RecordStore over Datastore. Several servers can share one namespace: a create is exclusive across them, and each sees the others' changes through Generation.

NewMountStore

func NewMountStore(client *datastore.Client, namespace string) *MountStore

NewMountStore returns a store over the mount records in namespace. An empty namespace is Datastore's default one.

MountStore.CreateMount

func (s *MountStore) CreateMount(ctx context.Context, m mounts.Mount) error

CreateMount writes m and bumps the generation counter in one transaction. A record with m.Name returns mounts.ErrExists, so of two servers creating the same name, one wins. A bad name returns mounts.ErrInvalidArgument.

MountStore.DeleteMount

func (s *MountStore) DeleteMount(ctx context.Context, name string) error

DeleteMount removes the record named name, and bumps the generation counter in the same transaction when there was one. Deleting a missing record is not an error.

MountStore.Generation

func (s *MountStore) Generation(ctx context.Context) (string, error)

Generation returns the counter that every create and delete bumps, as a decimal string. It is "0" before the first write.

MountStore.GetMount

func (s *MountStore) GetMount(ctx context.Context, name string) (mounts.Mount, error)

GetMount returns the record named name, or mounts.ErrNotFound.

MountStore.ListMounts

func (s *MountStore) ListMounts(ctx context.Context) ([]mounts.Mount, error)

ListMounts returns every record, in name order.