Repository Public
1package api23import (4 "context"5 "errors"6 "fmt"7 "strings"8 "time"910 "github.com/google/uuid"11 "github.com/jackc/pgx/v5"1213 "clustr.spboucher.ai/mcc/internal/audit"14 "clustr.spboucher.ai/mcc/internal/httpx"15)1617// Helpers shared by the operations handlers (ops_*.go).1819func nowUTC() time.Time { return time.Now().UTC().Truncate(time.Microsecond) }2021func pageLimit(l *int) int {22 if l == nil {23 return 5024 }25 if *l < 1 {26 return 127 }28 if *l > 200 {29 return 20030 }31 return *l32}3334// where builds a parameterized WHERE clause; values never enter the SQL text.35type where struct {36 conds []string37 args []any38}3940// add appends a condition; every "?" in cond is replaced by the next placeholder.41func (w *where) add(cond string, vals ...any) {42 for _, v := range vals {43 w.args = append(w.args, v)44 cond = strings.Replace(cond, "?", fmt.Sprintf("$%d", len(w.args)), 1)45 }46 w.conds = append(w.conds, cond)47}4849func (w *where) sql() string {50 if len(w.conds) == 0 {51 return ""52 }53 return " where " + strings.Join(w.conds, " and ")54}5556// arg registers a value and returns its placeholder.57func (w *where) arg(v any) string {58 w.args = append(w.args, v)59 return fmt.Sprintf("$%d", len(w.args))60}6162// uuidCursor parses a cursor that is the id of the last item of the previous page (ids are time-ordered UUIDv7).63func uuidCursor(c *string) (*uuid.UUID, error) {64 if c == nil || *c == "" {65 return nil, nil66 }67 id, err := uuid.Parse(*c)68 if err != nil {69 return nil, httpx.Validation("Invalid cursor.")70 }71 return &id, nil72}7374func notFound(err error) error {75 if errors.Is(err, pgx.ErrNoRows) {76 return httpx.ErrNotFound77 }78 return err79}8081func deref[T any](p *T) (v T) {82 if p != nil {83 v = *p84 }85 return v86}8788func nonEmpty(s string) *string {89 if s == "" {90 return nil91 }92 return &s93}9495// refused audits a refused request (anything but a plain 403, which authorize96// already recorded) and returns the error unchanged.97func (c *core) refused(ctx context.Context, action, targetKind, targetID string, params map[string]any, err error) error {98 var he *httpx.Error99 if !errors.As(err, &he) || he.Code == "forbidden" || he.Status >= 500 && he.Code != "orchestrator_frozen" {100 return err101 }102 outcome := audit.Denied103 if he.Code == "validation_failed" || he.Code == "not_found" {104 outcome = audit.Failure105 }106 c.audit(ctx, c.Pool, action, targetKind, targetID, outcome, he.Code, params)107 return err108}109110func (c *core) userID(ctx context.Context) uuid.UUID { return principalFrom(ctx).Session.User.ID }111112// escapeLike makes user text literal inside a LIKE pattern.113func escapeLike(s string) string {114 return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)115}116