gunk-dev/the-valley

checkrequest.go

source6a7605f70901main's published tip history
2.7 KiB
1package change
2
3import (
4 "crypto/rand"
5 "encoding/hex"
6 "strings"
7)
8
9// A check request asks a host's check worker to build the checks a commit
10// requires, outside any change. It is a ref pointing straight at the
11// commit:
12//
13// refs/the-valley/check-requests/<principal>/<worktree>/<attempt>
14//
15// <principal> is the principal that filed it. <worktree> and <attempt> are
16// tokens the requesting client makes, each CheckRequestToken lowercase
17// hexadecimal digits: a client names the worktree it asks from with one,
18// and each request it files from there with the other, so a rerun of the
19// same commit is a new ref. The push hook admits the ref
20// (valleyhook/checkrequest.go), and the worker reads it (status/worker.go).
21
22// CheckRequestPrefix opens every check request's ref.
23const CheckRequestPrefix = "refs/the-valley/check-requests/"
24
25// CheckRequestToken is how many lowercase hexadecimal digits a check
26// request's worktree and attempt tokens each hold.
27const CheckRequestToken = 16
28
29// ParseCheckRequestRef splits a check request's ref into its principal,
30// worktree and attempt. It reports false for a ref that is not
31// refs/the-valley/check-requests/<principal>/<worktree>/<attempt> with a
32// principal's name as the principal, and CheckRequestToken lowercase
33// hexadecimal digits as each token.
34func ParseCheckRequestRef(ref string) (principal, worktree, attempt string, ok bool) {
35 rest, found := strings.CutPrefix(ref, CheckRequestPrefix)
36 if !found {
37 return "", "", "", false
38 }
39 parts := strings.Split(rest, "/")
40 if len(parts) != 3 || !ValidPrincipal(parts[0]) || !requestToken(parts[1]) || !requestToken(parts[2]) {
41 return "", "", "", false
42 }
43 return parts[0], parts[1], parts[2], true
44}
45
46// CheckRequestRef is the ref of the check request principal files from
47// the worktree token as the attempt token. It reports false when that ref
48// would not parse as a check request's (ParseCheckRequestRef).
49func CheckRequestRef(principal, worktree, attempt string) (string, bool) {
50 ref := CheckRequestPrefix + principal + "/" + worktree + "/" + attempt
51 _, _, _, ok := ParseCheckRequestRef(ref)
52 return ref, ok
53}
54
55// NewCheckRequestToken makes a worktree or an attempt token:
56// CheckRequestToken lowercase hexadecimal digits, at random.
57func NewCheckRequestToken() (string, error) {
58 b := make([]byte, CheckRequestToken/2)
59 if _, err := rand.Read(b); err != nil {
60 return "", err
61 }
62 return hex.EncodeToString(b), nil
63}
64
65// requestToken reports whether s is a check request's worktree or attempt
66// token.
67func requestToken(s string) bool {
68 if len(s) != CheckRequestToken {
69 return false
70 }
71 for _, c := range []byte(s) {
72 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
73 return false
74 }
75 }
76 return true
77}