Skip to content
go-libfossil Artifact [106477511d]
Login

Artifact [106477511d]

Artifact 106477511d38416ef8db487f47b622a517974d287d9de05e8dc6a88ab6d6e770:


package horizon

import (
	"errors"
	"fmt"
	"strings"

	"github.com/danmestas/go-libfossil/db"
	libfossil "github.com/danmestas/go-libfossil/internal/fsltype"
)

// ErrNameNotFound is returned when a horizon name resolves to no check-in.
var ErrNameNotFound = errors.New("horizon: name resolves to no check-in")

// NameTip is the name of the most recent check-in.
const NameTip = "tip"

// Resolved is the check-in a horizon name resolved to and how many steps
// back along primary parents were taken to reach it.
type Resolved struct {
	Hash  string
	Steps uint32
}

// ResolveName resolves a horizon name over q's check-ins as
// draft-fossil-horizon-00 §6.2.7 does: tip is the most recent check-in, a
// full hash names its check-in, and any other name, or a full hash naming no
// check-in, is the most recent check-in carrying an active sym-NAME tag,
// propagated or not. A tie on mtime goes to the lexicographically lowest
// full hash, never a local rid, so every origin resolves a name alike. From there it steps back up
// to depth times along primary parents, stopping early at a check-in with
// none, in one query bounded by the check-ins the repository holds.
func ResolveName(q db.Querier, name string, depth uint32) (Resolved, error) {
	if q == nil {
		panic("horizon.ResolveName: nil querier")
	}
	rid, err := namedCheckin(q, name)
	if err != nil {
		return Resolved{}, err
	}
	// One query walks back, at most depth steps and never more than there
	// are check-ins, so a corrupt cycle of primary parents ends too.
	var steps uint32
	err = q.QueryRow(`WITH RECURSIVE back(rid, n) AS (
			SELECT ?1, 0
			UNION ALL
			SELECT p.pid, back.n+1 FROM back
			JOIN plink p ON p.cid=back.rid AND p.isprim=1
			JOIN event e ON e.objid=p.pid AND e.type='ci'
			WHERE back.n < min(?2, (SELECT count(*) FROM event WHERE type='ci')))
		SELECT rid, n FROM back ORDER BY n DESC LIMIT 1`, rid, int64(depth)).Scan(&rid, &steps)
	if err != nil {
		return Resolved{}, fmt.Errorf("horizon: primary parents: %w", err)
	}
	if steps > depth {
		panic("horizon.ResolveName: walked past the depth")
	}
	var uuid string
	if err := q.QueryRow("SELECT uuid FROM blob WHERE rid=?", rid).Scan(&uuid); err != nil {
		return Resolved{}, fmt.Errorf("horizon: resolved check-in: %w", err)
	}
	return Resolved{Hash: uuid, Steps: steps}, nil
}

// namedCheckin is the check-in name names before any step back.
func namedCheckin(q db.Querier, name string) (libfossil.FslID, error) {
	if name == NameTip {
		return bestCheckin(q, `SELECT e.objid, b.uuid, CAST(e.mtime AS REAL)
			FROM event e JOIN blob b ON b.rid=e.objid
			WHERE e.type='ci' ORDER BY e.mtime DESC, b.uuid ASC`)
	}
	if isFullHash(name) {
		rid, err := bestCheckin(q, `SELECT e.objid, b.uuid, CAST(e.mtime AS REAL)
			FROM blob b JOIN event e ON e.objid=b.rid AND e.type='ci'
			WHERE b.uuid=?`, strings.ToLower(name))
		if !errors.Is(err, ErrNameNotFound) {
			return rid, err
		}
	}
	return bestCheckin(q, `SELECT e.objid, b.uuid, CAST(e.mtime AS REAL)
		FROM tagxref x JOIN tag t ON t.tagid=x.tagid
		JOIN event e ON e.objid=x.rid AND e.type='ci' JOIN blob b ON b.rid=e.objid
		WHERE t.tagname=? AND x.tagtype>0 ORDER BY e.mtime DESC, b.uuid ASC`, "sym-"+name)
}

type nameCandidate struct {
	rid  libfossil.FslID
	uuid string
}

// bestCheckin picks the highest-mtime candidate of query (ordered by mtime DESC,
// uuid ASC). When several check-ins tie on mtime, any candidate that another
// tied candidate descends from through any parent (merge parents included) is
// dropped before the lowest full hash decides (§6.2.7).
func bestCheckin(q db.Querier, query string, args ...any) (libfossil.FslID, error) {
	rows, err := q.Query(query, args...)
	if err != nil {
		return 0, fmt.Errorf("horizon: resolve name: %w", err)
	}
	defer rows.Close()
	var tied []nameCandidate
	var topTime float64
	for rows.Next() {
		var rid libfossil.FslID
		var uuid string
		var mtime float64
		if err := rows.Scan(&rid, &uuid, &mtime); err != nil {
			return 0, fmt.Errorf("horizon: resolve name: %w", err)
		}
		if len(tied) == 0 {
			topTime = mtime
		} else if mtime != topTime {
			break
		}
		tied = append(tied, nameCandidate{rid: rid, uuid: uuid})
	}
	if err := rows.Err(); err != nil {
		return 0, fmt.Errorf("horizon: resolve name: %w", err)
	}
	if len(tied) == 0 {
		return 0, ErrNameNotFound
	}
	if len(tied) == 1 {
		return tied[0].rid, nil
	}
	return resolveTie(q, tied)
}

// resolveTie drops every candidate in tied that is an ancestor (via any plink
// parent, primary or merge) of another candidate in tied, then returns the
// surviving candidate with the lexicographically lowest full hash (§6.2.7).
func resolveTie(q db.Querier, tied []nameCandidate) (libfossil.FslID, error) {
	if len(tied) < 2 {
		panic("horizon.resolveTie: need at least two candidates")
	}
	candSet := make(map[libfossil.FslID]bool, len(tied))
	for _, c := range tied {
		candSet[c.rid] = true
	}
	ancestors, err := tiedAncestors(q, tied, candSet)
	if err != nil {
		return 0, err
	}
	for _, c := range tied {
		if !ancestors[c.rid] {
			return c.rid, nil
		}
	}
	// Cyclic plink data could mark every candidate; fall back to lowest hash.
	return tied[0].rid, nil
}

func tiedAncestors(
	q db.Querier, tied []nameCandidate, candSet map[libfossil.FslID]bool,
) (map[libfossil.FslID]bool, error) {
	dropped := map[libfossil.FslID]bool{}
	for _, start := range tied {
		seen := map[libfossil.FslID]bool{start.rid: true}
		queue := []libfossil.FslID{start.rid}
		for len(queue) > 0 && len(seen) <= heldSetNodes {
			cur := queue[0]
			queue = queue[1:]
			parents, err := plinkParents(q, cur)
			if err != nil {
				return nil, err
			}
			for _, pid := range parents {
				if candSet[pid] && pid != start.rid {
					dropped[pid] = true
				}
				if !seen[pid] {
					seen[pid] = true
					queue = append(queue, pid)
				}
			}
		}
	}
	return dropped, nil
}

func plinkParents(q db.Querier, cid libfossil.FslID) ([]libfossil.FslID, error) {
	rows, err := q.Query("SELECT pid FROM plink WHERE cid=?", cid)
	if err != nil {
		return nil, fmt.Errorf("horizon: tie parents: %w", err)
	}
	defer rows.Close()
	var out []libfossil.FslID
	for rows.Next() {
		var pid libfossil.FslID
		if err := rows.Scan(&pid); err != nil {
			return nil, fmt.Errorf("horizon: tie parents: %w", err)
		}
		out = append(out, pid)
	}
	return out, rows.Err()
}

// isFullHash reports a 40 or 64 digit hex string, of either case.
func isFullHash(s string) bool {
	if len(s) != 40 && len(s) != 64 {
		return false
	}
	for i := 0; i < len(s); i++ {
		c := s[i]
		if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F') {
			return false
		}
	}
	return true
}