Build out the admin panel

- Overview: users, organizations, workspaces, spaces, pages, files and
  storage (org admins see their organization), plus pages open right now,
  the search index size, and version, uptime and database health.
- Users: invite people by email (with resend, revoke and a copyable link
  when mail fails) and send a password-reset email.
- Authentication: sign-up on or off, the email-domain allow-list, and
  sign-in links by email.
- Branding: instance name, accent colour and logo. The web app shows them
  on the sign-in pages and applies the accent colour everywhere.
- Email and Storage: SMTP and S3 settings with test buttons.
- Maintenance: create, download and delete database backups, and a view
  of the background jobs with their last run, duration and errors.

On the server, a small jobs registry records each search-indexing pass,
and "search.rebuild" replaces the separate reindex endpoint. A new
instance package serves the dashboard numbers, health and backups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 17:34:48 +01:00
1 parent 92cd81fd96
commit ffc6cc4fbc
31 files changed
+2326 -134

No files matched your search

+92
View File
@@ -4,9 +4,29 @@
package api
import (
"time"
openapi_types "github.com/oapi-codegen/runtime/types"
)
// Defines values for AdminStatsScope.
const (
AdminStatsScopeInstance AdminStatsScope = "instance"
AdminStatsScopeOrganization AdminStatsScope = "organization"
)
// Valid indicates whether the value is a known member of the AdminStatsScope enum.
func (e AdminStatsScope) Valid() bool {
switch e {
case AdminStatsScopeInstance:
return true
case AdminStatsScopeOrganization:
return true
default:
return false
}
}
// Defines values for InviteStatus.
const (
Added InviteStatus = "added"
@@ -214,6 +234,49 @@ func (e ExportPageParamsFormat) Valid() bool {
}
}
// AdminHealth defines model for AdminHealth.
type AdminHealth struct {
Database struct {
Error *string `json:"error,omitempty"`
LatencyMs int `json:"latencyMs"`
Ok bool `json:"ok"`
} `json:"database"`
GoVersion string `json:"goVersion"`
Goroutines int `json:"goroutines"`
MemoryMb int `json:"memoryMb"`
Started time.Time `json:"started"`
UptimeSeconds int `json:"uptimeSeconds"`
Version string `json:"version"`
}
// AdminStats defines model for AdminStats.
type AdminStats struct {
Attachments int `json:"attachments"`
// Editors People connected to those pages (instance scope only)
Editors int `json:"editors"`
// Indexed Pages in the search index (instance scope only)
Indexed int `json:"indexed"`
Organizations int `json:"organizations"`
// Pages Pages outside the trash
Pages int `json:"pages"`
// Rooms Pages open for editing now (instance scope only)
Rooms int `json:"rooms"`
Scope AdminStatsScope `json:"scope"`
Spaces int `json:"spaces"`
// StorageBytes Total size of attachments
StorageBytes int `json:"storageBytes"`
Users int `json:"users"`
Workspaces int `json:"workspaces"`
}
// AdminStatsScope defines model for AdminStats.Scope.
type AdminStatsScope string
// Attachment defines model for Attachment.
type Attachment struct {
Created string `json:"created"`
@@ -246,6 +309,13 @@ type AuthSettings struct {
MagicLink bool `json:"magicLink"`
}
// Backup defines model for Backup.
type Backup struct {
Key string `json:"key"`
Modified string `json:"modified"`
Size int `json:"size"`
}
// BrandingSettings defines model for BrandingSettings.
type BrandingSettings struct {
AccentColor string `json:"accentColor"`
@@ -391,6 +461,28 @@ type InviteInfo struct {
WorkspaceName string `json:"workspaceName"`
}
// Job defines model for Job.
type Job struct {
Description string `json:"description"`
// Every How often it runs on its own (Go duration); empty when only on demand
Every string `json:"every"`
Failures int `json:"failures"`
LastDurationMs int `json:"lastDurationMs"`
LastError string `json:"lastError"`
// LastStarted RFC 3339; empty before the first run
LastStarted string `json:"lastStarted"`
Name string `json:"name"`
// Runnable Can be started by hand
Runnable bool `json:"runnable"`
Running bool `json:"running"`
// Runs Runs since the server started
Runs int `json:"runs"`
}
// LoginRequest defines model for LoginRequest.
type LoginRequest struct {
Email openapi_types.Email `json:"email"`
+23
View File
@@ -73,6 +73,29 @@ func (h *Hub) Close(ctx context.Context) error {
}
}
// Stats counts the open pages and their connected editors.
type Stats struct {
Rooms int `json:"rooms"`
Peers int `json:"peers"`
}
// Stats reports what is open right now (for the admin dashboard).
func (h *Hub) Stats() Stats {
h.mu.Lock()
rooms := make([]*room, 0, len(h.rooms))
for _, r := range h.rooms {
rooms = append(rooms, r)
}
h.mu.Unlock()
st := Stats{Rooms: len(rooms)}
for _, r := range rooms {
r.mu.Lock()
st.Peers += len(r.sessions)
r.mu.Unlock()
}
return st
}
// Peer is the sending side of one connection. Send must not block; it returns
// false when the peer cannot keep up and is being disconnected.
type Peer interface {
+74
View File
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"io"
"mime"
"net/http"
"docwell/server/internal/access"
"docwell/server/internal/instance"
"docwell/server/internal/jobs"
)
// InstanceService is the admin panel's view of the server (instance.Service).
type InstanceService interface {
Stats(ctx context.Context, c access.Caller) (instance.Stats, error)
Health(ctx context.Context, c access.Caller) (instance.Health, error)
Jobs(c access.Caller) ([]jobs.Job, error)
RunJob(c access.Caller, name string) error
ListBackups(ctx context.Context, c access.Caller) ([]instance.Backup, error)
CreateBackup(ctx context.Context, c access.Caller) error
DeleteBackup(ctx context.Context, c access.Caller, key string) error
OpenBackup(ctx context.Context, c access.Caller, key string) (*http.Response, error)
}
func (a *api) adminRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/admin/stats", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
st, err := a.instance.Stats(r.Context(), caller(r))
a.respond(w, st, err)
}))
mux.HandleFunc("GET /api/v1/admin/health", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
h, err := a.instance.Health(r.Context(), caller(r))
a.respond(w, h, err)
}))
mux.HandleFunc("GET /api/v1/admin/jobs", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
list, err := a.instance.Jobs(caller(r))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/admin/jobs/{name}/run", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
if err := a.instance.RunJob(caller(r), r.PathValue("name")); err != nil {
a.writeError(w, err)
return
}
w.WriteHeader(http.StatusAccepted)
}))
mux.HandleFunc("GET /api/v1/admin/backups", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
list, err := a.instance.ListBackups(r.Context(), caller(r))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/admin/backups", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.instance.CreateBackup(r.Context(), caller(r)))
}))
mux.HandleFunc("DELETE /api/v1/admin/backups/{key}", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.instance.DeleteBackup(r.Context(), caller(r), r.PathValue("key")))
}))
mux.HandleFunc("GET /api/v1/admin/backups/{key}", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
resp, err := a.instance.OpenBackup(r.Context(), caller(r), r.PathValue("key"))
if err != nil {
a.writeError(w, err)
return
}
defer resp.Body.Close()
h := w.Header()
h.Set("Content-Type", "application/zip")
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": r.PathValue("key")}))
if n := resp.Header.Get("Content-Length"); n != "" {
h.Set("Content-Length", n)
}
_, _ = io.Copy(w, resp.Body)
}))
}
+2 -1
View File
@@ -42,7 +42,7 @@ type api struct {
dir DirectoryService
settings SettingsService
files *auth.FileTokens
index SearchIndex
instance InstanceService
collab CollabHub
log *slog.Logger
}
@@ -152,6 +152,7 @@ func (a *api) routes(mux *routeMux) {
a.transferRoutes(mux)
a.shareRoutes(mux)
a.commentRoutes(mux)
a.adminRoutes(mux)
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
+3 -3
View File
@@ -28,8 +28,8 @@ type Deps struct {
Settings SettingsService
// FileTokens signs the ?token= of file links; nil allows only bearer tokens.
FileTokens *auth.FileTokens
// Search is the full-text index (admin reindex); nil disables it.
Search SearchIndex
// Instance serves the admin dashboard, health, jobs and backups.
Instance InstanceService
// MaxUpload caps one attachment in bytes.
MaxUpload int64
// Collab serves /collab; nil disables live editing.
@@ -60,7 +60,7 @@ func NewRouter(d Deps) http.Handler {
func newMux(d Deps) *routeMux {
mux := &routeMux{ServeMux: http.NewServeMux()}
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, index: d.Search, collab: d.Collab, log: d.Log}
a := &api{auth: d.Auth, dir: d.Directory, settings: d.Settings, files: d.FileTokens, instance: d.Instance, collab: d.Collab, log: d.Log}
a.routes(mux)
a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
a.collabRoute(mux, d.CORSOrigins)
-23
View File
@@ -16,12 +16,6 @@ type SearchService interface {
Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (directory.SearchResult, error)
}
// SearchIndex is the index maintenance the admin panel can trigger.
type SearchIndex interface {
Rebuild(ctx context.Context) error
Count() (uint64, error)
}
func (a *api) searchRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/workspaces/{id}/search", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
@@ -29,21 +23,4 @@ func (a *api) searchRoutes(mux *routeMux) {
res, err := a.dir.Search(r.Context(), caller(r), r.PathValue("id"), q.Get("q"), min(max(limit, 0), 50))
a.respond(w, res, err)
}))
mux.HandleFunc("POST /api/v1/admin/search/reindex", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
if err := access.ManageInstance(caller(r)); err != nil {
a.writeError(w, err)
return
}
if a.index == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "unavailable"})
return
}
// Rebuilding can take a while; it runs on after the response.
go func() {
if err := a.index.Rebuild(context.WithoutCancel(r.Context())); err != nil {
a.log.Error("search: rebuild failed", "err", err)
}
}()
w.WriteHeader(http.StatusAccepted)
}))
}
+250
View File
@@ -0,0 +1,250 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package instance serves the admin panel's view of the whole server: the
// dashboard numbers, system health, background jobs and database backups.
package instance
import (
"context"
"errors"
"fmt"
"net/http"
"regexp"
"runtime"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/collab"
"docwell/server/internal/jobs"
"docwell/server/internal/store/pocketbase"
)
// Live is what the collaboration hub reports.
type Live interface{ Stats() collab.Stats }
// Indexed is what the search index reports.
type Indexed interface{ Count() (uint64, error) }
type Service struct {
pb *pocketbase.Client
version string
started time.Time
live Live
index Indexed
jobs *jobs.Registry
}
func New(pb *pocketbase.Client, version string, live Live, index Indexed, reg *jobs.Registry) *Service {
return &Service{pb: pb, version: version, started: time.Now(), live: live, index: index, jobs: reg}
}
// Stats are the dashboard numbers; an org admin sees their organization's.
type Stats struct {
// Scope is "instance" for superadmins, "organization" for org admins.
Scope string `json:"scope"`
Users int `json:"users"`
Organizations int `json:"organizations"`
Workspaces int `json:"workspaces"`
Spaces int `json:"spaces"`
Pages int `json:"pages"`
Attachments int `json:"attachments"`
StorageBytes int64 `json:"storageBytes"`
// Rooms and Editors are pages open right now and the people in them
// (instance-wide only).
Rooms int `json:"rooms"`
Editors int `json:"editors"`
// Indexed is the number of pages in the search index (instance-wide only).
Indexed int `json:"indexed"`
}
func (s *Service) count(ctx context.Context, collection, filter string) (int, error) {
res, err := pocketbase.List[struct{}](ctx, s.pb, collection, pocketbase.ListOptions{PerPage: 1, Filter: filter, Fields: "id"})
return res.TotalItems, err
}
// Stats counts what c manages.
func (s *Service) Stats(ctx context.Context, c access.Caller) (Stats, error) {
all, org, err := access.UserScope(c)
if err != nil {
return Stats{}, err
}
st := Stats{Scope: "instance"}
f := map[string]string{"users": "", "organizations": "", "workspaces": "", "spaces": "", "pages": "deleted_at = ''", "attachments": ""}
if !all {
st.Scope = "organization"
if org == "" {
return st, nil
}
f = map[string]string{
"users": fmt.Sprintf("organization = '%s'", org),
"organizations": fmt.Sprintf("id = '%s'", org),
"workspaces": fmt.Sprintf("organization = '%s'", org),
"spaces": fmt.Sprintf("workspace.organization = '%s'", org),
"pages": fmt.Sprintf("deleted_at = '' && workspace.organization = '%s'", org),
"attachments": fmt.Sprintf("workspace.organization = '%s'", org),
}
}
for name, dst := range map[string]*int{
"users": &st.Users, "organizations": &st.Organizations, "workspaces": &st.Workspaces,
"spaces": &st.Spaces, "pages": &st.Pages, "attachments": &st.Attachments,
} {
if *dst, err = s.count(ctx, name, f[name]); err != nil {
return Stats{}, err
}
}
// Storage is the sum of attachment sizes; PocketBase has no aggregate
// query over REST, so it pages through the size column.
for page := 1; ; page++ {
res, err := pocketbase.List[struct {
Size int64 `json:"size"`
}](ctx, s.pb, "attachments", pocketbase.ListOptions{Page: page, PerPage: 1000, Fields: "size", Filter: f["attachments"]})
if err != nil {
return Stats{}, err
}
for _, a := range res.Items {
st.StorageBytes += a.Size
}
if page >= res.TotalPages || len(res.Items) == 0 {
break
}
}
if all {
if s.live != nil {
live := s.live.Stats()
st.Rooms, st.Editors = live.Rooms, live.Peers
}
if s.index != nil {
if n, err := s.index.Count(); err == nil {
st.Indexed = int(min(n, 1<<31-1))
}
}
}
return st, nil
}
// Health describes the running server (superadmin).
type Health struct {
Version string `json:"version"`
GoVersion string `json:"goVersion"`
Started string `json:"started"`
UptimeSec int64 `json:"uptimeSeconds"`
Database struct {
OK bool `json:"ok"`
LatencyMs int64 `json:"latencyMs"`
Error string `json:"error,omitempty"`
} `json:"database"`
Goroutines int `json:"goroutines"`
MemoryMB uint64 `json:"memoryMb"`
}
func (s *Service) Health(ctx context.Context, c access.Caller) (Health, error) {
if err := access.ManageInstance(c); err != nil {
return Health{}, err
}
h := Health{
Version: s.version, GoVersion: runtime.Version(), Started: s.started.UTC().Format(time.RFC3339),
UptimeSec: int64(time.Since(s.started).Seconds()), Goroutines: runtime.NumGoroutine(),
}
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
h.MemoryMB = mem.Sys >> 20
start := time.Now()
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
err := s.pb.Health(ctx)
h.Database.LatencyMs = time.Since(start).Milliseconds()
h.Database.OK = err == nil
if err != nil {
h.Database.Error = err.Error()
}
return h, nil
}
// Jobs lists the background jobs (superadmin).
func (s *Service) Jobs(c access.Caller) ([]jobs.Job, error) {
if err := access.ManageInstance(c); err != nil {
return nil, err
}
return s.jobs.List(), nil
}
// RunJob starts a job by hand (superadmin).
func (s *Service) RunJob(c access.Caller, name string) error {
if err := access.ManageInstance(c); err != nil {
return err
}
switch err := s.jobs.Run(name); {
case errors.Is(err, jobs.ErrUnknown):
return apperr.NotFound("no job can be started with that name")
case errors.Is(err, jobs.ErrBusy):
return apperr.Conflict("the job is already running")
default:
return err
}
}
// ---- Backups ---------------------------------------------------------------
// Backup is one PocketBase backup archive (the whole database and its files).
type Backup struct {
Key string `json:"key"`
Size int64 `json:"size"`
Modified string `json:"modified"`
}
var backupKey = regexp.MustCompile(`^[a-z0-9_.-]{1,150}\.zip$`)
func backupError(err error) error {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) {
switch pbErr.Status {
case http.StatusNotFound:
return apperr.NotFound("backup not found")
case http.StatusBadRequest:
return apperr.Invalid(pbErr.Message)
}
}
return err
}
func (s *Service) ListBackups(ctx context.Context, c access.Caller) ([]Backup, error) {
if err := access.ManageInstance(c); err != nil {
return nil, err
}
out := []Backup{}
err := s.pb.Do(ctx, http.MethodGet, "/api/backups", nil, &out)
return out, backupError(err)
}
// CreateBackup asks PocketBase to write a new archive. It can take a while
// on large instances; PocketBase answers when the archive is complete.
func (s *Service) CreateBackup(ctx context.Context, c access.Caller) error {
if err := access.ManageInstance(c); err != nil {
return err
}
name := "docwell-" + time.Now().UTC().Format("20060102-150405") + ".zip"
return backupError(s.pb.Do(ctx, http.MethodPost, "/api/backups", map[string]string{"name": name}, nil))
}
func (s *Service) DeleteBackup(ctx context.Context, c access.Caller, key string) error {
if err := access.ManageInstance(c); err != nil {
return err
}
if !backupKey.MatchString(key) {
return apperr.NotFound("backup not found")
}
return backupError(s.pb.Do(ctx, http.MethodDelete, "/api/backups/"+key, nil, nil))
}
// OpenBackup streams an archive; the caller closes the body.
func (s *Service) OpenBackup(ctx context.Context, c access.Caller, key string) (*http.Response, error) {
if err := access.ManageInstance(c); err != nil {
return nil, err
}
if !backupKey.MatchString(key) {
return nil, apperr.NotFound("backup not found")
}
resp, err := s.pb.OpenBackup(ctx, key)
return resp, backupError(err)
}
+120
View File
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package jobs tracks docwell-server's background work (search indexing and
// the like) so the admin panel can show when each job last ran, how long it
// took and whether it failed, and run some of them on demand.
package jobs
import (
"context"
"errors"
"sort"
"sync"
"time"
)
// ErrUnknown is returned for a job name that was never registered.
var ErrUnknown = errors.New("unknown job")
// ErrBusy is returned when a job is asked to run while it is running.
var ErrBusy = errors.New("job is already running")
// Job is one kind of background work, as the admin panel shows it.
type Job struct {
Name string `json:"name"`
Description string `json:"description"`
// Every is how often it runs on its own ("" = only on demand).
Every string `json:"every"`
Runnable bool `json:"runnable"`
Running bool `json:"running"`
Runs int `json:"runs"`
Failures int `json:"failures"`
LastStarted string `json:"lastStarted"`
LastDuration int64 `json:"lastDurationMs"`
LastError string `json:"lastError"`
}
type entry struct {
Job
run func(ctx context.Context) error
}
type Registry struct {
mu sync.Mutex
jobs map[string]*entry
now func() time.Time
}
func New() *Registry {
return &Registry{jobs: map[string]*entry{}, now: time.Now}
}
// Register declares a job. run, when not nil, lets admins start it by hand.
func (r *Registry) Register(name, description string, every time.Duration, run func(ctx context.Context) error) {
r.mu.Lock()
defer r.mu.Unlock()
e := &entry{Job: Job{Name: name, Description: description, Runnable: run != nil}, run: run}
if every > 0 {
e.Every = every.String()
}
r.jobs[name] = e
}
// Track runs fn as one run of job name and records the outcome. Unknown
// names are registered on the fly, so callers never lose a report.
func (r *Registry) Track(name string, fn func() error) error {
r.mu.Lock()
e, ok := r.jobs[name]
if !ok {
e = &entry{Job: Job{Name: name}}
r.jobs[name] = e
}
start := r.now()
e.Running = true
r.mu.Unlock()
err := fn()
r.mu.Lock()
defer r.mu.Unlock()
e.Running = false
e.Runs++
e.LastStarted = start.UTC().Format(time.RFC3339)
e.LastDuration = r.now().Sub(start).Milliseconds()
e.LastError = ""
if err != nil {
e.Failures++
e.LastError = err.Error()
}
return err
}
// List returns every job, by name.
func (r *Registry) List() []Job {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]Job, 0, len(r.jobs))
for _, e := range r.jobs {
out = append(out, e.Job)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// Run starts a runnable job in the background.
func (r *Registry) Run(name string) error {
r.mu.Lock()
e, ok := r.jobs[name]
switch {
case !ok || e.run == nil:
r.mu.Unlock()
return ErrUnknown
case e.Running:
r.mu.Unlock()
return ErrBusy
}
run := e.run
r.mu.Unlock()
go func() { _ = r.Track(name, func() error { return run(context.Background()) }) }()
return nil
}
+51
View File
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package jobs
import (
"context"
"errors"
"testing"
"time"
)
func TestTrackAndRun(t *testing.T) {
r := New()
ran := make(chan struct{})
release := make(chan struct{})
r.Register("index", "Indexes pages", 3*time.Second, func(context.Context) error {
close(ran)
<-release
return nil
})
if err := r.Track("index", func() error { return errors.New("boom") }); err == nil {
t.Fatal("Track must return fn's error")
}
j := r.List()[0]
if j.Runs != 1 || j.Failures != 1 || j.LastError != "boom" || j.Every != "3s" || !j.Runnable {
t.Errorf("after a failure: %+v", j)
}
if err := r.Run("index"); err != nil {
t.Fatal(err)
}
<-ran
if err := r.Run("index"); !errors.Is(err, ErrBusy) {
t.Errorf("second run while busy = %v", err)
}
close(release)
for i := 0; i < 100 && r.List()[0].Running; i++ {
time.Sleep(5 * time.Millisecond)
}
if j := r.List()[0]; j.Running || j.Runs != 2 || j.LastError != "" {
t.Errorf("after a good run: %+v", j)
}
if err := r.Run("nope"); !errors.Is(err, ErrUnknown) {
t.Errorf("unknown = %v", err)
}
_ = r.Track("adhoc", func() error { return nil })
if len(r.List()) != 2 {
t.Error("unregistered jobs are tracked too")
}
}
+14 -3
View File
@@ -58,7 +58,18 @@ type Index struct {
pb *pocketbase.Client
log *slog.Logger
mu sync.Mutex // serializes indexing passes
mu sync.Mutex // serializes indexing passes
track func(name string, fn func() error) error
}
// Track reports each indexing pass to fn (the admin panel's job list).
func (x *Index) Track(fn func(name string, run func() error) error) { x.track = fn }
func (x *Index) tracked(name string, fn func() error) error {
if x.track == nil {
return fn()
}
return x.track(name, fn)
}
const checkpointKey = "checkpoint"
@@ -136,11 +147,11 @@ func (x *Index) Run(ctx context.Context, interval, sweepEvery time.Duration) {
defer tick.Stop()
lastSweep := time.Time{}
for {
if err := x.CatchUp(ctx); err != nil && ctx.Err() == nil {
if err := x.tracked("search.index", func() error { return x.CatchUp(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: indexing failed", "err", err)
}
if time.Since(lastSweep) >= sweepEvery {
if err := x.Sweep(ctx); err != nil && ctx.Err() == nil {
if err := x.tracked("search.sweep", func() error { return x.Sweep(ctx) }); err != nil && ctx.Err() == nil {
x.log.Warn("search: sweep failed", "err", err)
}
lastSweep = time.Now()
@@ -323,6 +323,34 @@ func (c *Client) OpenFile(ctx context.Context, collection, recordID, filename st
return resp, nil
}
// OpenBackup streams a PocketBase backup archive. The caller closes the body.
func (c *Client) OpenBackup(ctx context.Context, key string) (*http.Response, error) {
token, err := c.authToken(ctx)
if err != nil {
return nil, err
}
var ft struct {
Token string `json:"token"`
}
if err := c.send(ctx, http.MethodPost, "/api/files/token", token, nil, &ft); err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
c.baseURL+"/api/backups/"+url.PathEscape(key)+"?token="+url.QueryEscape(ft.Token), nil)
if err != nil {
return nil, err
}
resp, err := (&http.Client{}).Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
defer resp.Body.Close()
return nil, &Error{Status: resp.StatusCode, Message: "backup download failed"}
}
return resp, nil
}
// raw sends a request with a non-JSON body and returns the response for a
// 2xx status; errors are decoded like send's.
func (c *Client) raw(ctx context.Context, method, path, token string, body io.Reader, contentType string) (*http.Response, error) {