package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strconv"
"strings"
"time"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ops"
)
// RefusalBlockingOpen is the accept gate's code for "this landing still
// has blocking comments nobody settled". Its fields are count, and open:
// a JSON array of {hash, file, line} for each, file and line empty for a
// remark on the whole diff. Landing over them takes a branch owner or a
// repository admin saying why, with overrideBlocking set: the reason that passes red or
// stale checks does not pass these. Auto-land never overrides, and waits.
const RefusalBlockingOpen = "blocking_open"
// RefusalNotBlocking is landing.comment's code for a resolve or reopen
// aimed at a post that is not a blocking comment of this landing. Its
// field is post, what the caller named.
const RefusalNotBlocking = "not_blocking"
// RefusalBlockingUnchanged is landing.comment's code for a resolve of a
// comment already resolved, or a reopen of one already open. Its field is
// state, what the comment is now: "open" or "resolved".
const RefusalBlockingUnchanged = "blocking_unchanged"
// blockingOpenPhrase is in every blocking_open sentence, for a caller
// that holds the sentence and not the refusal (a stack walk's Reason).
const blockingOpenPhrase = "open blocking comment"
// isBlockingOpen says err is the accept gate's blocking_open refusal.
func isBlockingOpen(err error) bool {
var ref *ops.Refusal
return errors.As(err, &ref) && ref.Code == RefusalBlockingOpen
}
// maySettleBlock is THE rule for who may resolve or reopen a blocking
// comment: its author, the landing's author, or anyone who holds what
// accept holds. A write asks it of the caller's request and a read of
// the person who wrote each marker, both through this one function, so
// what the API lets a person do and what history is believed to have
// done cannot drift apart. capsOf says what an account holds: a write
// reads it through the request's token ceiling, a read as the account is
// now. Without a capability plane nobody holds anything here: only the
// two authors settle.
//
// actor must be an account the forge itself established. An unnamed or
// anonymous one matches nobody, and a name taken from an artifact is
// never an actor (see blockingProvenance).
func (d Deps) maySettleBlock(actor, blockAuthor, landingAuthor string, capsOf func(account string) CapSet) bool {
if actor == "" || actor == "anonymous" {
return false
}
if actor == blockAuthor || actor == landingAuthor {
return true
}
return d.CapsFor != nil && capsOf(actor).HasAny("i")
}
// blockingProvenance is who carried an artifact to this forge and when,
// as the forge recorded it: the pusher's login for a sync, the signed-in
// account for a post written through the API. The user an artifact
// claims in its U card is whatever its clone said, so a settlement never
// trusts it; an artifact with no record settles nothing.
func (d Deps) blockingProvenance(repoName string) index.Provenance {
return func(hash string) (string, time.Time, bool) {
if d.Carriers == nil {
return "", time.Time{}, false
}
who, at := d.Carriers.CarrierOf(repoName, hash)
return who, at, who != ""
}
}
// postAuthor is the account the forge recorded as writing a post's first
// version, and the name that version claims only when it recorded none.
func (d Deps) postAuthor(repoName string, first index.ForumPost) string {
if who, _, ok := d.blockingProvenance(repoName)(first.Hash); ok {
return who
}
return first.User
}
// recordWriter notes the account that wrote a post through the API, so
// a marker in it can be traced to someone. The first carrier stays.
func (d Deps) recordWriter(ctx context.Context, repoName, hash string) {
d.recordWriterAs(repoName, ops.User(ctx), hash)
}
// recordWriterAs is recordWriter for a post written on someone's behalf:
// a held post a moderator approves was written by its author.
func (d Deps) recordWriterAs(repoName, account, hash string) {
if d.Carriers == nil || hash == "" || account == "" {
return
}
if err := d.Carriers.RecordCarriers(repoName, account, []string{hash}); err != nil {
log.Printf("landing: record %s's post %.12s: %v", account, hash, err)
}
}
// blockingOf is a landing thread's blocking comments, all and open,
// judged by what each settler holds NOW and by who actually wrote each
// marker, so a reply a stranger synced in settles nothing.
func (d Deps) blockingOf(repoName string, l index.LandingSummary, chains [][]index.ForumPost) (all, open []index.BlockingNote) {
all, open, _ = d.blockingThread(repoName, l, chains)
return all, open
}
// blockingThread is blockingOf and the resolves and reopens it counted.
func (d Deps) blockingThread(repoName string, l index.LandingSummary, chains [][]index.ForumPost) (all, open []index.BlockingNote, settles []index.Settle) {
capsNow := func(account string) CapSet { return d.CapsFor(account, repoName) }
return index.BlockingThread(chains, d.blockingProvenance(repoName),
func(actor, blockAuthor string) bool {
return d.maySettleBlock(actor, blockAuthor, l.Author, capsNow)
})
}
// blockingFor reads a landing's thread and derives its blocking comments.
func (d Deps) blockingFor(repoName string, repo *Repo, l index.LandingSummary) (all, open []index.BlockingNote, chains [][]index.ForumPost, err error) {
chains, found, err := repo.Index.ForumThreadChains(l.ID)
if err != nil || !found {
return nil, nil, nil, err
}
all, open = d.blockingOf(repoName, l, chains)
return all, open, chains, nil
}
// blockingGate is the accept gate for one landing: the refusal naming
// what is open, or nil. A thread that cannot be read refuses rather than
// passes: a gate that fails open is not one.
func (d Deps) blockingGate(repoName string, repo *Repo, l index.LandingSummary) error {
_, open, _, err := d.blockingFor(repoName, repo, l)
if err != nil {
return err
}
if len(open) == 0 {
return nil
}
return blockingOpenRefusal(open)
}
type blockingRef struct {
Hash string `json:"hash"`
File string `json:"file"`
Line int `json:"line"`
}
func blockingOpenRefusal(open []index.BlockingNote) *ops.Refusal {
refs := make([]blockingRef, len(open))
names := make([]string, len(open))
for i, n := range open {
refs[i] = blockingRef{Hash: n.Hash, File: n.File, Line: n.Line}
names[i] = short(n.Hash)
}
list, _ := json.Marshal(refs)
return &ops.Refusal{
Code: RefusalBlockingOpen,
Message: fmt.Sprintf("%d %s(s) on this landing: %s; resolve each (a reply starting \"resolved: <hash>\"), "+
"or a branch owner or repository admin may accept over them with overrideBlocking and a stated reason",
len(open), blockingOpenPhrase, strings.Join(names, ", ")),
Fields: map[string]string{"count": strconv.Itoa(len(open)), "open": string(list)},
Class: ops.ErrForbidden,
}
}
// blockingOverrideNote is the record's line for an accept over open
// blocking comments, written before the merge as the checks' is.
func blockingOverrideNote(open []index.BlockingNote, reason string) string {
names := make([]string, len(open))
for i, n := range open {
names[i] = short(n.Hash)
}
return "Accepting over " + blockingOpenPhrase + "(s) (" + strings.Join(names, ", ") + "): " + reason
}
// blockingMarkup turns a comment's typed fields into the post that
// carries them: it rewrites in.Message and, for a resolve or reopen,
// aims in.To at the blocking comment. The marker lives in the post body
// and nowhere else, so a stock Fossil clone sees exactly what quarry
// derived its state from.
func (d Deps) blockingMarkup(ctx context.Context, in *landingSayIn, repo *Repo, l index.LandingSummary) error {
asked := 0
for _, on := range []bool{in.Blocking, in.Resolves != "", in.Reopens != ""} {
if on {
asked++
}
}
if asked == 0 {
return nil
}
if asked > 1 {
return fmt.Errorf("a comment is blocking, resolves one or reopens one, not several of those: %w", ops.ErrInvalid)
}
if in.Blocking {
if strings.TrimSpace(index.BlockingText(in.Message)) == "" {
return fmt.Errorf("a blocking comment needs something said: %w", ops.ErrInvalid)
}
in.Message = index.AsBlocking(in.Message)
return nil
}
kind, ref := index.MarkResolved, in.Resolves
if in.Reopens != "" {
kind, ref = index.MarkReopened, in.Reopens
}
if in.File != "" || in.Line != 0 {
return fmt.Errorf("a %s is a reply to a blocking comment, not a line note: %w", kind, ops.ErrInvalid)
}
ref = strings.ToLower(strings.TrimSpace(ref))
if m := index.ParseMarker(string(kind) + ": " + ref); m.Kind != kind {
return fmt.Errorf("%s names a blocking comment by its hash, at least %d characters: %w", kind, index.MinMarkerHash, ops.ErrInvalid)
}
all, open, chains, err := d.blockingFor(in.Repo, repo, l)
if err != nil {
return err
}
chain, found, ambiguous := index.ChainOf(chains, ref)
if ambiguous {
return fmt.Errorf("%q names more than one post in this record: %w", ref, ops.ErrInvalid)
}
// A resolve is what lets a landing through, so who may write one is
// decided first, from the post named when there is one, and a
// stranger learns nothing about the thread from which refusal they
// get. A reopen lets nothing through: whoever may comment may reopen,
// as the read side counts it (index.Blocking).
if kind == index.MarkResolved {
blockAuthor := ""
if found {
blockAuthor = d.postAuthor(in.Repo, chain[0])
}
capsNow := func(account string) CapSet { return d.capsFor(ctx, account, in.Repo) }
if !d.maySettleBlock(ops.User(ctx), blockAuthor, l.Author, capsNow) {
return fmt.Errorf("a blocking comment may be resolved by its author, the landing's author, or someone who may accept it: %w",
ops.ErrForbidden)
}
}
if !found {
return fmt.Errorf("no post %q in this record: %w", ref, ops.ErrInvalid)
}
var blocker *index.BlockingNote
for i := range all {
if all[i].Hash == chain[len(chain)-1].Hash {
blocker = &all[i]
}
}
if blocker == nil {
return &ops.Refusal{Code: RefusalNotBlocking, Fields: map[string]string{"post": ref},
Message: fmt.Sprintf("%s is not a blocking comment of this landing", short(ref))}
}
isOpen := false
for _, o := range open {
isOpen = isOpen || o.Hash == blocker.Hash
}
// A resolve changes an open comment and a reopen a resolved one;
// anything else would write a reply that says nothing happened.
if isOpen != (kind == index.MarkResolved) {
state := "resolved"
if isOpen {
state = "open"
}
return &ops.Refusal{Code: RefusalBlockingUnchanged, Fields: map[string]string{"state": state},
Message: fmt.Sprintf("%s is already %s", short(blocker.Hash), state)}
}
in.Message = index.FormatMarker(kind, blocker.Hash, in.Message)
if in.To == "" {
in.To = blocker.Hash
}
return nil
}
// markBlocking lays the thread's blocking state over one post of
// landing.get, so a page draws a comment as a blocker, a resolved blocker
// or a settle without reading markers itself. It sets Blocking (and, for
// the caller, MaySettle) on a blocking comment and Settle on a reply the
// derivation counted as a resolve or reopen, returning that reply's words
// (the counted version's, which a later edit by someone who may not settle
// does not change). A resolve nobody who may settle wrote is left a plain
// remark, because the derivation ignores it too and a page that called it
// a resolve would contradict the gate.
func (d Deps) markBlocking(ctx context.Context, repoName string, l index.LandingSummary, all []index.BlockingNote, settles []index.Settle, lp *landingPost, p index.ForumPost) {
if lp.Transition != "" || lp.Retarget != "" || lp.Updated != "" {
return // an event's text is machine text, never a marker
}
capsNow := func(account string) CapSet { return d.capsFor(ctx, account, repoName) }
for i := range all {
for _, h := range all[i].Chain {
if h != p.Hash {
continue
}
lp.Blocking = "open"
if all[i].ResolvedBy != "" {
lp.Blocking, lp.ResolvedBy, lp.ResolvedAt = "resolved", all[i].ResolvedBy, all[i].ResolvedAt
} else {
lp.MaySettle = d.maySettleBlock(ops.User(ctx), all[i].User, l.Author, capsNow)
}
return
}
}
for _, st := range settles {
for _, h := range st.Chain {
if h == p.Hash {
lp.Settle, lp.Settles = string(st.Kind), st.Target
lp.SettleBy, lp.SettleUnverified, lp.SettleAt = st.By, st.Unverified, st.Date
return
}
}
}
}