Files
Docwell/Server/internal/store/pocketbase/client.go
T
tajniak81andClaude Opus 5.5 ffc6cc4fbc 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>
2026-10-31 17:34:48 +01:00

383 lines
10 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
// Package pocketbase is a minimal typed client for the PocketBase REST API,
// authenticated as a superuser. It is the only way docwell-server reaches the
// database service.
package pocketbase
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"sync"
"time"
)
type Client struct {
baseURL string
email string
password string
http *http.Client
mu sync.Mutex
token string
}
func New(baseURL, email, password string) *Client {
return &Client{
baseURL: baseURL,
email: email,
password: password,
http: &http.Client{Timeout: 30 * time.Second},
}
}
// Error is a non-2xx response from PocketBase.
type Error struct {
Status int `json:"status"`
Message string `json:"message"`
Data map[string]FieldError `json:"data"`
// MFAID is set on a 401 when the first auth factor passed and MFA is required.
MFAID string `json:"mfaId"`
}
// FieldError is a per-field validation error in Error.Data.
type FieldError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (e *Error) Error() string {
return fmt.Sprintf("pocketbase: %d %s", e.Status, e.Message)
}
// IsNotFound reports whether err is a PocketBase 404.
func IsNotFound(err error) bool {
var pbErr *Error
return errors.As(err, &pbErr) && pbErr.Status == http.StatusNotFound
}
// Health checks that PocketBase is up. It does not require authentication.
func (c *Client) Health(ctx context.Context) error {
return c.send(ctx, http.MethodGet, "/api/health", "", nil, nil)
}
// ListResult is one page of records.
type ListResult[T any] struct {
Page int `json:"page"`
PerPage int `json:"perPage"`
TotalItems int `json:"totalItems"`
TotalPages int `json:"totalPages"`
Items []T `json:"items"`
}
// ListOptions maps to PocketBase list query parameters.
type ListOptions struct {
Page int
PerPage int
Filter string
Sort string
// Expand lists relations to inline, e.g. "organization" or "user,workspace".
Expand string
// Fields limits the returned fields, e.g. "id,title" (skips large columns).
Fields string
}
func (o ListOptions) values() url.Values {
v := url.Values{}
if o.Page > 0 {
v.Set("page", fmt.Sprint(o.Page))
}
if o.PerPage > 0 {
v.Set("perPage", fmt.Sprint(o.PerPage))
}
if o.Filter != "" {
v.Set("filter", o.Filter)
}
if o.Sort != "" {
v.Set("sort", o.Sort)
}
if o.Expand != "" {
v.Set("expand", o.Expand)
}
if o.Fields != "" {
v.Set("fields", o.Fields)
}
return v
}
// List fetches a page of records from a collection.
func List[T any](ctx context.Context, c *Client, collection string, opts ListOptions) (ListResult[T], error) {
var out ListResult[T]
path := "/api/collections/" + url.PathEscape(collection) + "/records"
if q := opts.values().Encode(); q != "" {
path += "?" + q
}
err := c.Do(ctx, http.MethodGet, path, nil, &out)
return out, err
}
// Get fetches one record by id.
func Get[T any](ctx context.Context, c *Client, collection, id string) (T, error) {
return GetExpand[T](ctx, c, collection, id, "")
}
// GetExpand fetches one record by id with relations inlined.
func GetExpand[T any](ctx context.Context, c *Client, collection, id, expand string) (T, error) {
var out T
path := recordPath(collection, id)
if expand != "" {
path += "?expand=" + url.QueryEscape(expand)
}
err := c.Do(ctx, http.MethodGet, path, nil, &out)
return out, err
}
// Create inserts a record and returns the stored version.
func Create[T any](ctx context.Context, c *Client, collection string, body any) (T, error) {
var out T
err := c.Do(ctx, http.MethodPost, "/api/collections/"+url.PathEscape(collection)+"/records", body, &out)
return out, err
}
// Update patches a record and returns the stored version.
func Update[T any](ctx context.Context, c *Client, collection, id string, body any) (T, error) {
var out T
err := c.Do(ctx, http.MethodPatch, recordPath(collection, id), body, &out)
return out, err
}
// Delete removes a record.
func (c *Client) Delete(ctx context.Context, collection, id string) error {
return c.Do(ctx, http.MethodDelete, recordPath(collection, id), nil, nil)
}
func recordPath(collection, id string) string {
return "/api/collections/" + url.PathEscape(collection) + "/records/" + url.PathEscape(id)
}
// Do sends a JSON request as the superuser. On a 401 it re-authenticates once
// and retries.
func (c *Client) Do(ctx context.Context, method, path string, body, out any) error {
token, err := c.authToken(ctx)
if err != nil {
return err
}
err = c.send(ctx, method, path, token, body, out)
var pbErr *Error
if errors.As(err, &pbErr) && pbErr.Status == http.StatusUnauthorized {
c.mu.Lock()
if c.token == token {
c.token = ""
}
c.mu.Unlock()
if token, err = c.authToken(ctx); err != nil {
return err
}
err = c.send(ctx, method, path, token, body, out)
}
return err
}
// DoAs sends a JSON request on behalf of an end user: token is the user's
// auth token, or "" for an anonymous call (login, password reset, ...).
func (c *Client) DoAs(ctx context.Context, method, path, token string, body, out any) error {
return c.send(ctx, method, path, token, body, out)
}
func (c *Client) send(ctx context.Context, method, path, token string, body, out any) error {
var reader io.Reader
if body != nil {
buf, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(buf)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
if err != nil {
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", token)
}
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
pbErr := &Error{Status: resp.StatusCode}
_ = json.NewDecoder(resp.Body).Decode(pbErr)
pbErr.Status = resp.StatusCode
return pbErr
}
if out == nil || resp.StatusCode == http.StatusNoContent {
return nil
}
return json.NewDecoder(resp.Body).Decode(out)
}
func (c *Client) authToken(ctx context.Context) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.token != "" {
return c.token, nil
}
var res struct {
Token string `json:"token"`
}
err := c.send(ctx, http.MethodPost, "/api/collections/_superusers/auth-with-password", "",
map[string]string{"identity": c.email, "password": c.password}, &res)
if err != nil {
return "", fmt.Errorf("pocketbase superuser auth: %w", err)
}
c.token = res.Token
return c.token, nil
}
// CreateWithFile inserts a record with one file field, streaming the file to
// PocketBase as multipart form data. fields are the other (text) fields.
func CreateWithFile[T any](ctx context.Context, c *Client, collection string, fields map[string]string, fileField, filename string, file io.Reader) (T, error) {
var out T
pr, pw := io.Pipe()
mw := multipart.NewWriter(pw)
go func() {
err := func() error {
for k, v := range fields {
if err := mw.WriteField(k, v); err != nil {
return err
}
}
part, err := mw.CreateFormFile(fileField, filename)
if err != nil {
return err
}
if _, err := io.Copy(part, file); err != nil {
return err
}
return mw.Close()
}()
pw.CloseWithError(err)
}()
token, err := c.authToken(ctx)
if err != nil {
pr.Close()
return out, err
}
resp, err := c.raw(ctx, http.MethodPost, "/api/collections/"+url.PathEscape(collection)+"/records", token, pr, mw.FormDataContentType())
if err != nil {
return out, err
}
defer resp.Body.Close()
return out, json.NewDecoder(resp.Body).Decode(&out)
}
// OpenFile streams a protected file of a record. The caller closes the body.
func (c *Client) OpenFile(ctx context.Context, collection, recordID, filename string, header http.Header) (*http.Response, error) {
token, err := c.authToken(ctx)
if err != nil {
return nil, err
}
var ft struct {
Token string `json:"token"`
}
// File tokens are short-lived; asking for one per download keeps this simple.
if err := c.send(ctx, http.MethodPost, "/api/files/token", token, nil, &ft); err != nil {
return nil, err
}
path := "/api/files/" + url.PathEscape(collection) + "/" + url.PathEscape(recordID) + "/" + url.PathEscape(filename) +
"?token=" + url.QueryEscape(ft.Token)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
if err != nil {
return nil, err
}
for _, h := range []string{"Range", "If-None-Match", "If-Modified-Since"} {
if v := header.Get(h); v != "" {
req.Header.Set(h, v)
}
}
// Downloads may take longer than the JSON client's timeout.
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: "file download failed"}
}
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) {
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
req.Header.Set("Authorization", token)
resp, err := (&http.Client{}).Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= 300 {
defer resp.Body.Close()
pbErr := &Error{Status: resp.StatusCode}
_ = json.NewDecoder(resp.Body).Decode(pbErr)
pbErr.Status = resp.StatusCode
if resp.StatusCode == http.StatusUnauthorized {
c.mu.Lock()
if c.token == token {
c.token = ""
}
c.mu.Unlock()
}
return nil, pbErr
}
return resp, nil
}