core

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: AGPL-3.0 Imports: 66 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Session = "session" // signed-in members only: account, workspace and billing
	Anyone  = "any"     // any member or API key of the tenant
)

Auth permissions that aren't a product's.

View Source
const (
	MaxDescription     = 500     // a library's description
	MaxName            = 100     // names of workspaces, people, keys, libraries
	MaxEmail           = 254     // email addresses
	MinPassword        = 12      // passwords, in bytes
	MaxPassword        = 72      // bcrypt reads no further
	MaxReference       = 255     // a video's reference (passthrough)
	MaxURL             = 2048    // webhook addresses, CDN addresses, paths
	MaxKeyIPs          = 50      // addresses on one API key
	MaxSearch          = 100     // a list search
	MaxCaptionBytes    = 1 << 20 // one caption file, WebVTT or SRT
	MaxCaptions        = 20      // caption tracks on one video
	MaxAllowedWebsites = 50      // websites a library's player may be shown on
	MaxVideoText       = 2000    // a video's description
	MaxTags            = 20      // tags on one video
	MaxTag             = 40      // one tag
	MaxMetadata        = 20      // key/value pairs on one video
	MaxMetaKey         = 40      // one metadata key
	MaxMetaValue       = 500     // one metadata value
	MaxChapters        = 100     // chapters in one video
)

Field rules the API enforces. GET /v1/meta publishes them, so the console checks forms against these same numbers. Text limits count characters (utf8.RuneCountInString), except passwords, which bcrypt reads in bytes.

View Source
const JobTimeout = 4 * time.Hour

JobTimeout bounds any one job, long enough for packaging a 12-hour video.

View Source
const RiverSchema = "river"

RiverSchema holds River's tables, apart from the application's own.

View Source
const SessionCookie = "ulka_session"

Variables

View Source
var (
	ErrUploadTooLarge     = APIError{Status: http.StatusRequestEntityTooLarge, Code: "upload_too_large"}
	ErrEncodeLimitReached = "encode_limit_reached" // a video's error code: the month's encoding minutes are used up
)
View Source
var (
	ErrInvalidOrigin = APIError{Status: http.StatusBadRequest, Code: "invalid_origin"}
	ErrOriginPrivate = APIError{Status: http.StatusBadRequest, Code: "origin_not_public"}
)
View Source
var (
	FailTimeout  = Sentence("The provider didn't answer in time.")
	FailUnusable = Sentence("The provider answered something we couldn't use.")
	FailAccess   = Sentence("The provider didn't accept our access.")
	FailUnreach  = Sentence("The provider couldn't be reached.")
	FailTheirs   = Sentence("The provider had a problem on its side.")
	FailOurs     = Sentence("Something on our side needs a look.")
)
View Source
var Countries = strings.Fields(`AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW`)

Countries are the ISO 3166-1 alpha-2 codes plus XK (Kosovo), as IP country databases use them; the console's lib/countries.ts holds the same list.

View Source
var DefaultLimits = Limits{MaxUploadBytes: 5 << 30, EncodeMinutesMonthly: 600}
View Source
var DummyHash = func() []byte {
	h, err := bcrypt.GenerateFromPassword([]byte("ulka-dummy-password"), bcrypt.DefaultCost)
	if err != nil {
		panic(err)
	}
	return h
}()

DummyHash is compared against when an email is unknown, so login takes the same time either way.

View Source
var (
	ErrForbidden = APIError{Status: http.StatusForbidden, Code: "forbidden"}
)
View Source
var ErrInvalidPage = APIError{Status: http.StatusBadRequest, Code: "invalid_page"}
View Source
var ErrTooManyAttempts = APIError{Status: http.StatusTooManyRequests, Code: "too_many_attempts"}

ErrTooManyAttempts is answered after 10 failed sign-ins for an address within 15 minutes.

View Source
var ExtraLimitDefaults = map[string]any{}

ExtraLimitDefaults are the defaults of limits an application built on ulka-vms adds, by their JSON names.

View Source
var FieldRules = map[string]int{
	"name": MaxName, "email": MaxEmail, "password_min": MinPassword, "password_max": MaxPassword, "reference": MaxReference,
	"url": MaxURL, "key_ips": MaxKeyIPs, "search": MaxSearch, "description": MaxDescription, "caption_bytes": MaxCaptionBytes,
	"captions": MaxCaptions, "allowed_websites": MaxAllowedWebsites, "video_text": MaxVideoText, "tags": MaxTags, "tag": MaxTag,
	"metadata": MaxMetadata, "meta_key": MaxMetaKey, "meta_value": MaxMetaValue, "chapters": MaxChapters,
}

FieldRules is the rules /v1/meta publishes, by the names the console reads. An application built on ulka-vms adds its own at start.

View Source
var LookupIP = net.DefaultResolver.LookupNetIP

LookupIP resolves origin hostnames when they are saved; tests replace it.

View Source
var Messages = map[string]string{}/* 114 elements not displayed */

Messages says every code the API can report in words a person can act on: error codes, and why a video failed (its error_code). The API sends the message with each error and publishes the table at GET /v1/meta, so no client keeps its own copy. internal/app's tests fail when a code has no words here.

View Source
var Products = []string{"video", "webhooks"}

Products are what API key scopes grant, each at "read" or "write" (which includes read). AddProduct adds more.

View Source
var Roles = []string{"viewer", "member", "admin", "owner"}

Roles, least to most; each can do all the one before it can. Nobody may give a role above their own.

View Source
var RouteSeen func(pattern string)

Observe traces every request to h (otelhttp), named by mux's route pattern (never the raw path, which may hold tokens), and answers with X-Request-Id: the trace ID, to quote to support. A W3C traceparent continues its trace. RouteSeen, when set (the end-to-end suite), hears the mux pattern of every request, so the suite can tell which public routes it never reached.

View Source
var WebhookEvents = []WebhookEvent{
	{"asset.created", "A video was created"},
	{"upload.completed", "Its file finished uploading"},
	{"job.started", "Processing started"},
	{"asset.ready", "It can be played (720p and 360p)"},
	{"asset.complete", "Every quality is ready"},
	{"job.completed", "Processing finished"},
	{"asset.errored", "It couldn't be processed"},
	{"job.failed", "Processing failed"},
	{"upload.errored", "The upload didn't finish in time"},
	{"asset.download_ready", "Its MP4 download is ready"},
	{"asset.download_failed", "Its MP4 download couldn't be made"},
	{"asset.deleted", "It was deleted"},
}

WebhookEvents is every event an endpoint can receive or choose. Published at GET /v1/meta; a new core.Emit type goes here too (TestWebhookEventsMatchSpec keeps it and api/openapi.json's webhooks in step). An application built on ulka-vms appends its own at start.

Functions

func AddGauge

func AddGauge(name string, fn func(context.Context) (float64, error))

AddGauge reports fn's value as the metric ulka.<name> once a minute (for example, jobs waiting). It may be called before or after StartObserving: the global meter hands registrations on to the provider once it's set.

func AddProduct

func AddProduct(name string)

AddProduct adds a product an application built on ulka-vms serves, granted like video: viewers read, members and admins write. Call it at start, before serving.

func BeginShutdown

func BeginShutdown()

BeginShutdown closes Closing; the API calls it before it stops accepting requests.

func CDNURL

func CDNURL(raw string) (string, bool)

CDNURL is a customer's own CDN address as delivery uses it, "https://<host>" with nothing after; false otherwise.

func CheckMigrated

func CheckMigrated(ctx context.Context, pool *pgxpool.Pool, sets ...Migrations) error

CheckMigrated refuses to run against a database that is missing migrations this binary knows about, which would otherwise fail later, one query at a time.

func CheckOrigin

func CheckOrigin(ctx context.Context, raw string) error

CheckOrigin accepts an http(s) URL with no path, query or credentials, whose host is, or resolves only to, public addresses: we fetch from it for customers, and must never be pointed at our own network. ponytail: checked when saved; DNS can change later, so fetchers also refuse private addresses at connect time.

func CheckPublicHost

func CheckPublicHost(ctx context.Context, host string) error

CheckPublicHost accepts a public IP address, or a hostname that resolves only to public addresses.

func ClickHouseInsert

func ClickHouseInsert(ctx context.Context, base, table string, rows io.Reader) error

ClickHouseInsert appends JSONEachRow lines to table. Callers send small batches often, so the server gathers them into larger parts (async insert), and the call returns once they are written.

func ClickHouseQuery

func ClickHouseQuery(ctx context.Context, base, sql string, params map[string]string, each func([]byte) error) error

ClickHouseQuery runs one query over ClickHouse's HTTP interface and hands each JSONEachRow line to each.

func ClientIP

func ClientIP(r *http.Request, trusted []netip.Prefix) netip.Addr

ClientIP is the caller's address: the peer, or when the peer is a trusted proxy, the last address in X-Forwarded-For that isn't one (earlier entries are whatever the client claimed).

func Closing

func Closing() <-chan struct{}

Closing is closed when the process starts shutting down, so a long wait (a Live Server's poll) ends at once instead of holding the restart up for its whole length.

func Connect

func Connect(ctx context.Context, dsn string) (*pgxpool.Pool, error)

Connect opens a pool and refuses a role that would skip row-level security.

func Decode

func Decode(w http.ResponseWriter, r *http.Request, v any) bool

Decode requires a JSON content type, which also keeps cross-site form posts out.

func DeliveryRow

func DeliveryRow(r *http.Request, trusted []netip.Prefix, uri string, status int, sent int64, took time.Duration) map[string]any

DeliveryRow is one response in origin_access_logs, where video delivery is metered: the origin's segments and the API's downloads. uri is /s/<workspace>/<video>/…, from which ClickHouse takes the workspace.

func DrainLogs

func DrainLogs(ctx context.Context)

DrainLogs waits, after BeginShutdown, until every log has sent what it held, or ctx ends.

func Emit

func Emit(ctx context.Context, rc *river.Client[pgx.Tx], q TenantTx, typ string, data any) error

Emit queues the event inside the caller's transaction, so it exists exactly when its change commits. The webhooks module sends it on to each of the tenant's endpoints.

func HasStatus

func HasStatus(err error, status int) bool

HasStatus reports whether err is a provider answer with that status.

func Hash

func Hash(s string) []byte

func InScope

func InScope(ctx context.Context, pool *pgxpool.Pool, p Principal, fn func(TenantTx) error) error

InScope sets app.tenant_id and app.user_id from p; either may be unset.

func InTenant

func InTenant(ctx context.Context, pool *pgxpool.Pool, tenantID pgtype.UUID, fn func(TenantTx) error) error

InTenant runs fn in a transaction scoped by RLS to one tenant.

func InternalError

func InternalError(w http.ResponseWriter, r *http.Request, err error)

func IsWebhookEvent

func IsWebhookEvent(t string) bool

IsWebhookEvent reports whether t is one of WebhookEvents.

func LogFailure

func LogFailure(ctx context.Context, err error, what string, args ...any) string

LogFailure writes err to the log with its context (key, value pairs) and returns the sentence to store or send.

func LogMail

func LogMail(ctx context.Context, to, subject, body string) error

LogMail only logs the email: MAIL_PROVIDER=log, for development.

func Message

func Message(code string) string

Message is code's words; a code without any is a bug, logged, and answered with the generic words.

func Migrate

func Migrate(ctx context.Context, dsn string, sets ...Migrations) error

Migrate brings River's tables up to date, then applies every unapplied file of each set in turn, all in one transaction.

func Observe

func Observe(mux *http.ServeMux, h http.Handler) http.Handler

func Open

func Open(key, sealed []byte) ([]byte, error)

func Paged

func Paged[T any](rows []T, c Cursor, key func(T) (time.Time, string)) map[string]any

Paged is a cursor list response: {data, next_cursor}, next_cursor empty on the last page. rows were fetched with Fetch(); key gives a row's position.

func PagedTotal

func PagedTotal[T any](rows []T, c Cursor, key func(T) (time.Time, string), total int64) map[string]any

PagedTotal is Paged plus how many rows match the whole request (its filters, not the cursor), for "1-10 of 57".

func ParsePrefix

func ParsePrefix(s string) (netip.Prefix, error)

ParsePrefix reads an address ("203.0.113.9") or a range ("203.0.113.0/24").

func Plain

func Plain(s string) string

Plain returns s when it is one of the registered sentences (or empty), and FailOurs for anything else.

func PlainFailure

func PlainFailure(err error) string

PlainFailure picks the sentence for err by its type: never by its text.

func PublicClient

func PublicClient(timeout time.Duration) *http.Client

PublicClient only connects to public addresses, checked on the resolved IP at connect time so DNS cannot sneak past it, and never follows redirects.

func PublicIP

func PublicIP(a netip.Addr) bool

PublicIP reports whether a is reachable on the public internet, so we never fetch from our own network for a customer.

func ReadAllLimits

func ReadAllLimits(ctx context.Context, q TenantTx, dst *map[string]any) error

ReadAllLimits fills dst with every limit by its JSON name: ulka-vms's and the application's, each unset one at its default. /v1/limits shows them.

func ReadLimits

func ReadLimits(ctx context.Context, q TenantTx, dst any) error

ReadLimits fills dst, already holding the defaults, with q's tenant's stored overrides. An application built on ulka-vms keeps its own limits in the same overrides under its own names.

func RecordUsage

func RecordUsage(ctx context.Context, q TenantTx, meter, key string, at time.Time, region, quantity string) error

RecordUsage writes one usage record in the caller's transaction; recording the same (meter, key) again replaces its quantity, so re-runs never double count. quantity is a decimal string.

func ReleaseLocked

func ReleaseLocked(conn *pgxpool.Conn, unlock string, args ...any)

ReleaseLocked runs unlock and returns conn to the pool. If unlock fails the connection is closed instead: a session-level advisory lock would otherwise stay held on a pooled connection, blocking that work for good.

func RemoveTemp

func RemoveTemp(dir string)

RemoveTemp deletes a temporary directory, logging a failure: leftovers would fill the disk unnoticed.

func RespondError

func RespondError(w http.ResponseWriter, r *http.Request, err error)

func RoleCan

func RoleCan(role, perm string) bool

RoleCan reports whether a role grants perm, as in "video:read" or "members:write".

func RoleRank

func RoleRank(role string) int

RoleRank orders roles; -1 for an unknown one.

func Seal

func Seal(key, plaintext []byte) ([]byte, error)

Seal encrypts secrets we must store and later use (like a customer's TLS private key) with AES-256-GCM. key is 32 bytes; the nonce is prepended to the ciphertext.

func Sentence

func Sentence(s string) string

Sentence registers a plain sentence a feature may store or send, and returns it.

func StartObserving

func StartObserving(ctx context.Context, service string, pool *pgxpool.Pool) (func(context.Context) error, error)

StartObserving sets up OpenTelemetry for this process ("api" or "worker"; service.name ulka-api or ulka-worker) and returns what flushes and stops it on shutdown. slog keeps printing to stderr and also sends each line as an OTel log carrying the trace it happened in.

func StorageProblem added in v0.1.2

func StorageProblem(err error) string

StorageProblem says in plain words why Check failed.

func TraceID

func TraceID(ctx context.Context) string

TraceID is the trace ctx belongs to, "" outside one.

func ValidCountry

func ValidCountry(c string) bool

ValidCountry reports whether c (upper case) is a country code a rule can name: a typo (UK, ZZ) would otherwise make a rule that silently matches no one.

func ValidHostname

func ValidHostname(s string) bool

ValidHostname reports whether s is a lowercase DNS name with at least two labels.

func ValidScopes

func ValidScopes(scopes []string) bool

ValidScopes reports whether scopes name known products at most once each, at "read" or "write".

func WriteError

func WriteError(w http.ResponseWriter, status int, code string)

WriteError answers with a stable code for programs and its words for people (see Messages).

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON answers with v. Unless the handler said otherwise, nothing may store it: API answers are per caller, and a CDN in front of the API (image delivery) must never keep one.

Types

type APIError

type APIError struct {
	Status int
	Code   string
}

APIError is an error with a stable code; RespondError writes it, a missing row as not_found, anything else as internal.

func (APIError) Error

func (e APIError) Error() string

type Acting

type Acting struct {
	AdminID   pgtype.UUID `json:"-"`
	AdminName string      `json:"admin_name"`
	Until     time.Time   `json:"until"`
	AdminURL  string      `json:"admin_url,omitempty"` // where to go back to, set when the person's profile is read
}

Acting is the Ulka admin behind a session, and when it ends.

type ClickHouseLog

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

ClickHouseLog appends rows to one ClickHouse table in batches, off the request path: a write per request would queue every request behind one row. Rows are usage (image transforms, downloads), so the log is drained when the process stops (DrainLogs); a crash still loses up to a second of rows. ponytail: memory only; a disk spool closes the crash gap when these rows are invoiced.

func NewClickHouseLog

func NewClickHouseLog(url, table string) *ClickHouseLog

func (*ClickHouseLog) Add

func (l *ClickHouseLog) Add(row any)

Add never blocks: with ClickHouse unreachable long enough to fill the buffer, rows are dropped and logged.

type Cursor

type Cursor struct {
	Q     string
	Limit int32
	At    pgtype.Timestamptz // the last row seen; not Valid on the first page
	ID    string
}

Cursor is a list request paged by position rather than count (?q=&limit=&cursor=): newest first by (created_at, id), continuing after the row the cursor names. Pages stay right while rows are added.

func ParseCursor

func ParseCursor(r *http.Request) (Cursor, error)

ParseCursor reads a cursor list request; limit is 1 to 100 (25 when absent).

func (Cursor) AfterUUID

func (c Cursor) AfterUUID() (pgtype.UUID, error)

AfterUUID is the cursor's row id for lists keyed by uuid; not Valid on the first page, invalid_page if malformed.

func (Cursor) Fetch

func (c Cursor) Fetch() int32

Fetch is how many rows to ask for: one more than a page, to know whether another follows.

func (Cursor) Like

func (c Cursor) Like() string

Like is the search as an ILIKE pattern matching anywhere, with % and _ in it taken literally.

type Deps

type Deps struct {
	Pool           *pgxpool.Pool
	River          *river.Client[pgx.Tx]
	SealKey        []byte // SEAL_KEY: seals secrets at rest (core.Seal); 32 bytes
	Store          Storage
	PublicURL      string         // where this API and the customer console are reached
	AdminURL       string         // where Ulka admin is reached (its own host)
	OriginURL      string         // where segments are
	PlayerURL      string         // where viewers watch and stream (the player host)
	DocsURL        string         // where the guides and the API reference are read (the docs host)
	PlayerDemo     string         // the video the player host's home shows, as library/video; empty for none
	SignupOpen     bool           // SIGNUP=open: anyone may create a workspace; closed, only invites bring people in
	TrustedProxies []netip.Prefix // proxies whose X-Forwarded-For is believed
	Geo            *Geo           // visitors' countries, for libraries' country rules; nil finds none
	Keys           KeyStore       // a key service; nil keeps keys sealed in the database
	// OnActing records a change made by an Ulka admin using the console as a person (the ops module sets it).
	OnActing func(ctx context.Context, p Principal, method, path string, status int)
}

Deps is what every module's handlers and workers share. River is an insert-only client in the API.

func (*Deps) Auth

func (d *Deps) Auth(perm string, next HandlerFunc) http.HandlerFunc

func (*Deps) Authenticate

func (d *Deps) Authenticate(r *http.Request) (Principal, error)

Authenticate returns an empty principal, not an error, when credentials are absent or wrong.

func (*Deps) WithPathID

func (d *Deps) WithPathID(r *http.Request, p Principal, fn func(TenantTx, pgtype.UUID) error) error

WithPathID runs fn in the caller's tenant with the {id} path value; a malformed id is not_found.

type Event

type Event struct {
	ID        string    `json:"id"`
	Type      string    `json:"type"`
	CreatedAt time.Time `json:"created_at"`
	Data      any       `json:"data"`
}

type EventArgs

type EventArgs struct {
	TenantID pgtype.UUID     `json:"tenant_id"`
	Body     json.RawMessage `json:"body"`
}

EventArgs is one event for a tenant, waiting to be fanned out to its webhook endpoints.

func (EventArgs) InsertOpts

func (EventArgs) InsertOpts() river.InsertOpts

func (EventArgs) Kind

func (EventArgs) Kind() string

type Geo

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

Geo finds a visitor's country in a self-hosted IP database (GEOIP_DB: DB-IP's free country file, or MaxMind's).

func OpenGeo

func OpenGeo(path string) (*Geo, error)

func (*Geo) Country

func (g *Geo) Country(addr netip.Addr) string

Country is the address's two-letter country code, or "" when it is unknown (a private address, or no database).

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request, Principal)

type JobMiddleware

type JobMiddleware struct{ river.MiddlewareDefaults }

JobMiddleware traces every job run as the root of its own trace, named by kind, with its workspace when the arguments carry one. A snoozed job isn't a failure; it's marked ulka.job.snoozed.

func (JobMiddleware) Work

func (JobMiddleware) Work(ctx context.Context, job *rivertype.JobRow, doInner func(context.Context) error) error

type KeyStore

type KeyStore interface {
	// Create returns the video's key, made on first call; asking again returns the same one.
	Create(ctx context.Context, contentID string) (key, iv []byte, err error)
	Get(ctx context.Context, contentID string) (key, iv []byte, err error)
	// Delete forgets a video's key; one already gone is not an error.
	Delete(ctx context.Context, contentID string) error
	// PlayerURL is where a player fetches the video's key, valid until exp.
	PlayerURL(contentID string, exp time.Time) string
}

KeyStore holds videos' encryption keys outside ulka-vms, in a key service that hands them to players. Without one (Deps.Keys nil) each video's key is sealed in the database and served by the player host.

type Limits

type Limits struct {
	MaxUploadBytes       int64 `json:"max_upload_bytes"`
	EncodeMinutesMonthly int   `json:"encode_minutes_monthly"`
}

Limits is what one workspace may use. New workspaces get DefaultLimits; admins change them per workspace.

func LimitsFor

func LimitsFor(ctx context.Context, q TenantTx) (Limits, error)

LimitsFor reads q's tenant's limits, each unset one at its default.

type Mailer

type Mailer func(ctx context.Context, to, subject, body string) error

Mailer delivers one plain-text email.

var SendMail Mailer = LogMail

SendMail is how Ulka sends email; the ulka command sets it at boot from MAIL_PROVIDER.

func ResendMailer

func ResendMailer(key, from string) Mailer

ResendMailer sends through Resend's API with an API key.

func SMTPMailer

func SMTPMailer(u *url.URL, from string) (Mailer, error)

SMTPMailer sends through an SMTP server: smtp://user:pass@host:587 (STARTTLS, required unless the host is local) or smtps://user:pass@host:465 (TLS from the start).

func WithFallback

func WithFallback(primary, backup Mailer) Mailer

WithFallback sends through primary and, when that fails, through backup, so a provider outage doesn't stop password resets and invitations. When both fail the error names both.

type Migrations

type Migrations struct {
	Prefix string
	FS     fs.FS
}

Migrations is one set of schema files, applied in name order. Each file's version is Prefix plus its name, so an application built on ulka-vms keeps its own files apart from ulka-vms's.

type Notice

type Notice struct {
	ID       string         `json:"id"` // stable across requests: kind plus what it's about
	Kind     string         `json:"kind"`
	Severity string         `json:"severity"` // danger, warning or info
	Subject  string         `json:"subject,omitempty"`
	Name     string         `json:"name,omitempty"`
	At       time.Time      `json:"at"` // when it happened, or when it will
	Data     map[string]any `json:"data,omitempty"`
}

Notice is one thing to look at. Kind is a stable code the console words; the API decides the severity.

type PlainError

type PlainError struct {
	Sentence string
	Cause    error
}

PlainError carries the sentence to show beside the cause to log, for a feature that knows better than the type does.

func (*PlainError) Error

func (e *PlainError) Error() string

func (*PlainError) Unwrap

func (e *PlainError) Unwrap() error

type Principal

type Principal struct {
	TenantID, UserID pgtype.UUID
	Role             string
	Scopes           []string
	Acting           *Acting // set when an Ulka admin is using the console as this person
}

Principal is who is calling: a member of a tenant with a role, or an API key (no UserID) with scopes.

func (Principal) Can

func (p Principal) Can(perm string) bool

Can reports whether p may use a product at a level: by role for a member, by scope for an API key.

func (Principal) Permissions

func (p Principal) Permissions() []string

Permissions lists everything p may do, each at its highest level, for the console to show only what works.

type SignInGuard

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

SignInGuard refuses an address that has failed too often, and records each outcome. key namespaces the address ("user:" or "admin:"); unknown addresses count too, so the limit reveals nothing about accounts.

func NewSignInGuard

func NewSignInGuard(pool *pgxpool.Pool, kind, email string) SignInGuard

func (SignInGuard) Blocked

func (g SignInGuard) Blocked(ctx context.Context) (bool, error)

func (SignInGuard) Record

func (g SignInGuard) Record(ctx context.Context, ok bool) error

type StatusError

type StatusError struct {
	Status int
	Msg    string
}

StatusError is a provider's HTTP answer that wasn't a success. Its text is for logs only.

func (*StatusError) Error

func (e *StatusError) Error() string

type Storage

type Storage struct {
	S3     *s3.Client
	Bucket string
}

func (Storage) Check

func (st Storage) Check(ctx context.Context) error

Check writes, reads back and deletes a small file, proving the bucket exists and the key may do all three.

func (Storage) DeletePrefix

func (st Storage) DeletePrefix(ctx context.Context, prefix string) error

DeletePrefix removes every object under prefix, and aborts unfinished multipart uploads there too.

func (Storage) GetFile

func (st Storage) GetFile(ctx context.Context, key, path string) error

func (Storage) PresignGet

func (st Storage) PresignGet(ctx context.Context, key string) (string, error)

func (Storage) PutFile

func (st Storage) PutFile(ctx context.Context, key, path string) error

func (Storage) ReadObject

func (st Storage) ReadObject(ctx context.Context, key string) ([]byte, error)

type TenantTx

type TenantTx struct {
	*db.Queries
	pgx.Tx
	TenantID pgtype.UUID
	UserID   pgtype.UUID
}

TenantTx is a transaction scoped by RLS to one tenant and, when UserID is set, to that user's own rows.

type WebhookEvent

type WebhookEvent struct {
	Type  string `json:"type"`
	Words string `json:"words"`
}

WebhookEvent is one kind of event ulka-vms sends to webhook endpoints, with its words for people.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL