Sign in

Search issue titles and bodies, change requests and comments. Private repositories you cannot read are not included.

vole
Site
Clone

Read only, no credentials:

https://rodent.software/vole.git

Write over SSH with a registered key:

git clone ssh://git@rodent.software/vole.git

Self-hosted forge that lives in your Git repo.

Blame · forge/channel/channel.go

Line attribution on main · 247 line(s)

262e516e
Keenan Nemetz
19d ago
1 // Package channel stores release channels: server-side pointers from a stable
214e7ea6
Keenan Nemetz
17d ago
2 // name to one release, which stays frozen while the channel names it.
262e516e
Keenan Nemetz
19d ago
3 //
4 // A channel is consumed from the instance's public URL, not cloned, so the source
3047be84
Keenan Nemetz
17d ago
5 // of truth is the instance database rather than the repository's metadata branch.
6 // It lives beside the roster in instance.db, not in the derived index, because a
7 // channel move has no Git worktree to touch and an index rebuild must not be able
8 // to discard one. The target tag name and tag object are recorded; the web and
262e516e
Keenan Nemetz
19d ago
9 // the SSH verbs resolve the tag in the repository and report a dangling channel
10 // when it no longer matches.
11 package channel
12
13 import (
14 "database/sql"
15 "encoding/hex"
16 "errors"
17 "fmt"
3047be84
Keenan Nemetz
17d ago
18 "os"
262e516e
Keenan Nemetz
19d ago
19 "regexp"
20 "strings"
21 "time"
22
8f6548a6
Keenan Nemetz
3d ago
23 "rodent.software/vole/internal/sqlstore"
262e516e
Keenan Nemetz
19d ago
24 )
25
26 const (
27 // MaxNameLen bounds the URL segment.
28 MaxNameLen = 32
29 // MaxTagLen is generous for a tag name and still bounds a row.
30 MaxTagLen = 200
de72893e
Keenan Nemetz
17d ago
31 // MaxDescription bounds the prose shown on the releases page.
262e516e
Keenan Nemetz
19d ago
32 MaxDescription = 8 << 10
33 )
34
35 var nameRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
36
37 // Channel is one mutable alias for a release.
38 type Channel struct {
39 Name string
40 Release string
41 ReleaseObject string
42 UpdatedBy string
43 UpdatedAt time.Time
44 Description string
45 }
46
47 // ValidName checks the URL segment. Lowercase keeps the URL and the database key
48 // from differing by case.
49 func ValidName(name string) error {
50 switch {
51 case name == "":
52 return fmt.Errorf("a channel needs a name")
53 case len(name) > MaxNameLen:
54 return fmt.Errorf("channel name is %d bytes, limit %d", len(name), MaxNameLen)
55 case !nameRE.MatchString(name):
56 return fmt.Errorf("channel name %q must be lowercase letters, digits, and dashes, starting with a letter or digit", name)
57 }
58 return nil
59 }
60
61 func validObjectID(id string) error {
62 if len(id) != 40 && len(id) != 64 {
63 return fmt.Errorf("release_object %q is not a 40- or 64-character object id", id)
64 }
65 if _, err := hex.DecodeString(id); err != nil {
66 return fmt.Errorf("release_object %q is not hexadecimal", id)
67 }
68 return nil
69 }
70
71 func validate(ch *Channel) error {
72 switch {
73 case ValidName(ch.Name) != nil:
74 return ValidName(ch.Name)
75 case ch.Release == "":
76 return fmt.Errorf("a channel needs a release tag")
77 case len(ch.Release) > MaxTagLen:
78 return fmt.Errorf("release tag is %d bytes, limit %d", len(ch.Release), MaxTagLen)
79 case strings.ContainsAny(ch.Release, "\x00\n\r\t"):
80 return fmt.Errorf("release tag %q contains a control character", ch.Release)
81 }
82 if err := validObjectID(ch.ReleaseObject); err != nil {
83 return err
84 }
85 if strings.TrimSpace(ch.UpdatedBy) == "" {
86 return fmt.Errorf("updated_by is required")
87 }
88 if ch.UpdatedAt.IsZero() {
89 return fmt.Errorf("updated_at is required")
90 }
91 if len(ch.Description) > MaxDescription {
92 return fmt.Errorf("description is %d bytes, limit %d", len(ch.Description), MaxDescription)
93 }
94 return nil
95 }
96
3047be84
Keenan Nemetz
17d ago
97 // Store is the authoritative channel table. It lives in the instance database
98 // with the roster: a channel is source state, not a row an index rebuild may
262e516e
Keenan Nemetz
19d ago
99 // discard.
100 type Store struct{ db *sql.DB }
101
3047be84
Keenan Nemetz
17d ago
102 // Open opens the channel table in an existing instance database. The file is the
103 // one the roster, sessions and access rules already use, so nothing here may
104 // create it: a missing database is an instance that was never initialised.
262e516e
Keenan Nemetz
19d ago
105 func Open(path string) (*Store, error) {
3047be84
Keenan Nemetz
17d ago
106 if _, err := os.Stat(path); err != nil {
107 return nil, fmt.Errorf("channel: %s is missing; run vole admin init", path)
108 }
8f6548a6
Keenan Nemetz
3d ago
109 db, err := sqlstore.Open(path, sqlstore.Options{MaxConns: 4})
262e516e
Keenan Nemetz
19d ago
110 if err != nil {
111 return nil, err
112 }
113 s := &Store{db: db}
114 if _, err := db.Exec(`
115 CREATE TABLE IF NOT EXISTS release_channels (
116 repo_id TEXT NOT NULL,
117 name TEXT NOT NULL,
118 tag TEXT NOT NULL,
119 tag_object TEXT NOT NULL,
120 updated_by TEXT NOT NULL,
121 updated_at INTEGER NOT NULL,
122 description TEXT NOT NULL DEFAULT '',
123 PRIMARY KEY (repo_id, name)
124 );
125 CREATE INDEX IF NOT EXISTS release_channels_tag ON release_channels(repo_id, tag);
126 `); err != nil {
127 db.Close()
128 return nil, fmt.Errorf("channel: create schema: %w", err)
129 }
130 return s, nil
131 }
132
133 // Close releases the database.
8f6548a6
Keenan Nemetz
3d ago
134 // OpenReader opens the channel table for a caller that only reads. The push
135 // hook decides whether a release may change, and a push must not be the reason a
136 // schema is written.
137 func OpenReader(path string) (*Store, error) {
138 if _, err := os.Stat(path); err != nil {
139 return nil, fmt.Errorf("channel: %s is missing; run vole admin init", path)
140 }
141 d, err := sqlstore.Open(path, sqlstore.Options{MaxConns: 4, ReadOnly: true})
142 if err != nil {
143 return nil, err
144 }
145 return &Store{db: d}, nil
146 }
147
262e516e
Keenan Nemetz
19d ago
148 func (s *Store) Close() error {
149 if s == nil || s.db == nil {
150 return nil
151 }
152 return s.db.Close()
153 }
154
155 // Set creates or moves a channel. One row per (repository, name); a move replaces
156 // the target and metadata in one statement.
157 func (s *Store) Set(repoID string, ch Channel) error {
158 if err := validate(&ch); err != nil {
159 return err
160 }
161 _, err := s.db.Exec(`
162 INSERT INTO release_channels(repo_id, name, tag, tag_object, updated_by, updated_at, description)
163 VALUES (?,?,?,?,?,?,?)
164 ON CONFLICT(repo_id, name) DO UPDATE SET
165 tag=excluded.tag,
166 tag_object=excluded.tag_object,
167 updated_by=excluded.updated_by,
168 updated_at=excluded.updated_at,
169 description=excluded.description`,
170 repoID, ch.Name, ch.Release, ch.ReleaseObject, ch.UpdatedBy, ch.UpdatedAt.Unix(), ch.Description)
171 if err != nil {
172 return fmt.Errorf("channel: set %s: %w", ch.Name, err)
173 }
174 return nil
175 }
176
177 // Clear removes a channel. The bool reports whether a row existed.
178 func (s *Store) Clear(repoID, name string) (bool, error) {
179 if err := ValidName(name); err != nil {
180 return false, err
181 }
182 res, err := s.db.Exec(`DELETE FROM release_channels WHERE repo_id=? AND name=?`, repoID, name)
183 if err != nil {
184 return false, fmt.Errorf("channel: clear %s: %w", name, err)
185 }
186 n, err := res.RowsAffected()
187 return n > 0, err
188 }
189
190 // Get returns one channel.
191 func (s *Store) Get(repoID, name string) (Channel, bool, error) {
192 var ch Channel
193 var at int64
194 err := s.db.QueryRow(`
195 SELECT name, tag, tag_object, updated_by, updated_at, description
196 FROM release_channels WHERE repo_id=? AND name=?`, repoID, name).
197 Scan(&ch.Name, &ch.Release, &ch.ReleaseObject, &ch.UpdatedBy, &at, &ch.Description)
198 if errors.Is(err, sql.ErrNoRows) {
199 return Channel{}, false, nil
200 }
201 if err != nil {
202 return Channel{}, false, err
203 }
204 ch.UpdatedAt = time.Unix(at, 0).UTC()
205 return ch, true, nil
206 }
207
208 // List returns every channel for a repository, sorted by name.
209 func (s *Store) List(repoID string) ([]Channel, error) {
210 rows, err := s.db.Query(`
211 SELECT name, tag, tag_object, updated_by, updated_at, description
212 FROM release_channels WHERE repo_id=? ORDER BY name`, repoID)
213 if err != nil {
214 return nil, err
215 }
216 defer rows.Close()
217 var out []Channel
218 for rows.Next() {
219 var ch Channel
220 var at int64
221 if err := rows.Scan(&ch.Name, &ch.Release, &ch.ReleaseObject, &ch.UpdatedBy, &at, &ch.Description); err != nil {
222 return nil, err
223 }
224 ch.UpdatedAt = time.Unix(at, 0).UTC()
225 out = append(out, ch)
226 }
227 return out, rows.Err()
228 }
229
230 // ForTag returns the channel names that currently name a tag, sorted.
231 func (s *Store) ForTag(repoID, tag string) ([]string, error) {
232 rows, err := s.db.Query(
233 `SELECT name FROM release_channels WHERE repo_id=? AND tag=? ORDER BY name`, repoID, tag)
234 if err != nil {
235 return nil, err
236 }
237 defer rows.Close()
238 var out []string
239 for rows.Next() {
240 var name string
241 if err := rows.Scan(&name); err != nil {
242 return nil, err
243 }
244 out = append(out, name)
245 }
246 return out, rows.Err()
247 }