-
Notifications
You must be signed in to change notification settings - Fork 567
/
repos.go
349 lines (320 loc) · 11 KB
/
repos.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package pfsdb
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/jackc/pgconn"
"github.com/jmoiron/sqlx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pachyderm/pachyderm/v2/src/internal/collection"
"github.com/pachyderm/pachyderm/v2/src/internal/dbutil"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
"github.com/pachyderm/pachyderm/v2/src/internal/pachsql"
"github.com/pachyderm/pachyderm/v2/src/internal/randutil"
"github.com/pachyderm/pachyderm/v2/src/internal/stream"
"github.com/pachyderm/pachyderm/v2/src/internal/watch/postgres"
"github.com/pachyderm/pachyderm/v2/src/pfs"
)
const (
// ReposChannelName is used to watch events for the repos table.
ReposChannelName = "pfs_repos"
getRepoAndBranches = `
SELECT
repo.id,
repo.name,
repo.type,
repo.description,
repo.project_id AS "project.id",
project.name AS "project.name",
array_agg(branch.name) AS "branches",
repo.created_at,
repo.updated_at
FROM pfs.repos repo
JOIN core.projects project ON repo.project_id = project.id
LEFT JOIN pfs.branches branch ON branch.repo_id = repo.id
`
noBranches = "{NULL}"
reposPageSize = 100
)
// RepoNotFoundError is returned by GetRepo() when a repo is not found in postgres.
type RepoNotFoundError struct {
Project string
Name string
Type string
ID RepoID
}
// Error satisfies the error interface.
func (err *RepoNotFoundError) Error() string {
return fmt.Sprintf("repo (id=%d, project=%s, name=%s, type=%s) not found", err.ID, err.Project, err.Name, err.Type)
}
func (err *RepoNotFoundError) GRPCStatus() *status.Status {
return status.New(codes.NotFound, err.Error())
}
func IsErrRepoNotFound(err error) bool {
return errors.As(err, &RepoNotFoundError{})
}
func IsDuplicateKeyErr(err error) bool {
targetErr := &pgconn.PgError{}
ok := errors.As(err, targetErr)
if !ok {
return false
}
return targetErr.Code == "23505" // duplicate key SQLSTATE
}
// RepoInfoWithID is an (id, repoInfo) tuple returned by the repo iterator.
type RepoInfoWithID struct {
ID RepoID
RepoInfo *pfs.RepoInfo
Revision int64
}
// this dropped global variable instantiation forces the compiler to check whether RepoIterator implements stream.Iterator.
var _ stream.Iterator[RepoInfoWithID] = &RepoIterator{}
// DeleteRepo deletes an entry in the pfs.repos table.
func DeleteRepo(ctx context.Context, tx *pachsql.Tx, repoProject, repoName, repoType string) error {
result, err := tx.ExecContext(ctx, "DELETE FROM pfs.repos "+
"WHERE project_id=(SELECT id FROM core.projects WHERE name=$1) AND name=$2 AND type=$3;", repoProject, repoName, repoType)
if err != nil {
return errors.Wrap(err, "delete repo")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err, "could not get affected rows")
}
if rowsAffected == 0 {
if _, err := GetProjectByName(ctx, tx, repoProject); err != nil {
if errors.As(err, new(*ProjectNotFoundError)) {
return errors.Join(err, &RepoNotFoundError{Project: repoProject, Name: repoName, Type: repoType})
}
return errors.Wrapf(err, "could not get project %v for delete repo", repoProject)
}
return &RepoNotFoundError{Project: repoProject, Name: repoName, Type: repoType}
}
return nil
}
func GetRepoID(ctx context.Context, tx *pachsql.Tx, repoProject, repoName, repoType string) (RepoID, error) {
row, err := getRepoByName(ctx, tx, repoProject, repoName, repoType)
if err != nil {
return 0, err
}
return row.ID, nil
}
// todo(fahad): rewrite branch related code during the branches migration.
// GetRepo retrieves an entry from the pfs.repos table by using the row id.
func GetRepo(ctx context.Context, tx *pachsql.Tx, id RepoID) (*pfs.RepoInfo, error) {
if id == 0 {
return nil, errors.New("invalid id: 0")
}
repo := &Repo{}
err := tx.GetContext(ctx, repo, fmt.Sprintf("%s WHERE repo.id=$1 GROUP BY repo.id, project.name, project.id;", getRepoAndBranches), id)
if err != nil {
if err == sql.ErrNoRows {
return nil, &RepoNotFoundError{ID: id}
}
return nil, errors.Wrap(err, "scanning repo row")
}
return repo.PbInfo()
}
// GetRepoByName retrieves an entry from the pfs.repos table by project, repo name, and type.
func GetRepoByName(ctx context.Context, tx *pachsql.Tx, repoProject, repoName, repoType string) (*pfs.RepoInfo, error) {
repo, err := getRepoByName(ctx, tx, repoProject, repoName, repoType)
if err != nil {
return nil, err
}
return repo.PbInfo()
}
func getRepoByName(ctx context.Context, tx *pachsql.Tx, repoProject, repoName, repoType string) (*Repo, error) {
if repoProject == "" {
repoProject = pfs.DefaultProjectName
}
repo := &Repo{}
if err := tx.GetContext(ctx, repo,
fmt.Sprintf("%s WHERE repo.project_id=(SELECT id from core.projects where name=$1) "+
"AND repo.name=$2 AND repo.type=$3 GROUP BY repo.id, project.name, project.id;", getRepoAndBranches),
repoProject, repoName, repoType,
); err != nil {
if err == sql.ErrNoRows {
if _, err := GetProjectByName(ctx, tx, repoProject); err != nil {
if errors.As(err, new(*ProjectNotFoundError)) {
return nil, errors.Join(err, &RepoNotFoundError{Project: repoProject, Name: repoName, Type: repoType})
}
return nil, errors.Wrapf(err, "could not get project for get repo", repoProject)
}
return nil, &RepoNotFoundError{Project: repoProject, Name: repoName, Type: repoType}
}
return nil, errors.Wrap(err, "scanning repo row")
}
return repo, nil
}
// UpsertRepo will attempt to insert a repo, and return its ID. If the repo already exists, it will update its description.
func UpsertRepo(ctx context.Context, tx *pachsql.Tx, repo *pfs.RepoInfo) (RepoID, error) {
if repo.Repo.Name == "" {
return 0, errors.Errorf("repo name is required: %+v", repo.Repo)
}
if repo.Repo.Type == "" {
return 0, errors.Errorf("repo type is required: %+v", repo.Repo)
}
if repo.Repo.Project == nil {
return 0, errors.Errorf("project is required: %+v", repo.Repo)
}
var repoID RepoID
if err := tx.QueryRowContext(ctx,
`
INSERT INTO pfs.repos (name, type, project_id, description)
VALUES ($1, $2, (SELECT id from core.projects where name=$3), $4)
ON CONFLICT (name, type, project_id) DO UPDATE SET description= EXCLUDED.description
RETURNING id
`,
repo.Repo.Name, repo.Repo.Type, repo.Repo.Project.Name, repo.Description,
).Scan(&repoID); err != nil {
return 0, errors.Wrap(err, "upsert repo")
}
return repoID, nil
}
type repoColumn string
const (
RepoColumnID = repoColumn("repo.id")
RepoColumnCreatedAt = repoColumn("repo.created_at")
RepoColumnUpdatedAt = repoColumn("repo.updated_at")
)
type OrderByRepoColumn OrderByColumn[repoColumn]
func NewRepoIterator(ctx context.Context, ext sqlx.ExtContext, startPage, pageSize uint64, filter *pfs.Repo, orderBys ...OrderByRepoColumn) (*RepoIterator, error) {
var conditions []string
var values []any
if filter != nil {
if filter.Project != nil && filter.Project.Name != "" {
conditions = append(conditions, "project.name = ?")
values = append(values, filter.Project.Name)
}
if filter.Name != "" {
conditions = append(conditions, "repo.name = ?")
values = append(values, filter.Name)
}
if filter.Type != "" {
conditions = append(conditions, "repo.type = ?")
values = append(values, filter.Type)
}
}
query := getRepoAndBranches
if len(conditions) > 0 {
query += fmt.Sprintf("\nWHERE %s", strings.Join(conditions, " AND "))
}
query += "\nGROUP BY repo.id, project.name, project.id"
var orderByGeneric []OrderByColumn[repoColumn]
if len(orderBys) == 0 {
orderByGeneric = []OrderByColumn[repoColumn]{{Column: RepoColumnID, Order: SortOrderAsc}}
} else {
for _, orderBy := range orderBys {
orderByGeneric = append(orderByGeneric, OrderByColumn[repoColumn](orderBy))
}
}
query += "\n" + OrderByQuery[repoColumn](orderByGeneric...)
query = ext.Rebind(query)
return &RepoIterator{
paginator: newPageIterator[Repo](ctx, query, values, startPage, pageSize),
ext: ext,
}, nil
}
func ForEachRepo(ctx context.Context, tx *pachsql.Tx, filter *pfs.Repo, cb func(repoWithID RepoInfoWithID) error, orderBys ...OrderByRepoColumn) error {
iter, err := NewRepoIterator(ctx, tx, 0, 100, filter, orderBys...)
if err != nil {
return errors.Wrap(err, "for each repo")
}
if err := stream.ForEach[RepoInfoWithID](ctx, iter, cb); err != nil {
return errors.Wrap(err, "for each repo")
}
return nil
}
func ListRepo(ctx context.Context, tx *pachsql.Tx, filter *pfs.Repo, orderBys ...OrderByRepoColumn) ([]RepoInfoWithID, error) {
var repos []RepoInfoWithID
if err := ForEachRepo(ctx, tx, filter, func(repoWithID RepoInfoWithID) error {
repos = append(repos, repoWithID)
return nil
}, orderBys...); err != nil {
return nil, errors.Wrap(err, "list repo")
}
return repos, nil
}
type RepoIterator struct {
paginator pageIterator[Repo]
ext sqlx.ExtContext
}
func (i *RepoIterator) Next(ctx context.Context, dst *RepoInfoWithID) error {
if dst == nil {
return errors.Errorf("dst RepoInfo cannot be nil")
}
repo, rev, err := i.paginator.next(ctx, i.ext)
if err != nil {
return err
}
repoInfo, err := repo.PbInfo()
if err != nil {
return err
}
dst.ID = repo.ID
dst.RepoInfo = repoInfo
dst.Revision = rev
return nil
}
// Helper functions for watching repos.
type repoUpsertHandler func(id RepoID, repoInfo *pfs.RepoInfo) error
type repoDeleteHandler func(id RepoID) error
func WatchRepos(ctx context.Context, db *pachsql.DB, listener collection.PostgresListener, onUpsert repoUpsertHandler, onDelete repoDeleteHandler) error {
watcher, err := postgres.NewWatcher(db, listener, randutil.UniqueString("watch-repos-"), ReposChannelName)
if err != nil {
return err
}
defer watcher.Close()
snapshot, err := NewRepoIterator(ctx, db, 0, reposPageSize, nil, OrderByRepoColumn{Column: RepoColumnID, Order: SortOrderAsc})
if err != nil {
return err
}
return watchRepos(ctx, db, snapshot, watcher.Watch(), onUpsert, onDelete)
}
func watchRepos(ctx context.Context, db *pachsql.DB, snapshot stream.Iterator[RepoInfoWithID], events <-chan *postgres.Event, onUpsert repoUpsertHandler, onDelete repoDeleteHandler) error {
// Handle snapshot.
if err := stream.ForEach[RepoInfoWithID](ctx, snapshot, func(r RepoInfoWithID) error {
return onUpsert(r.ID, r.RepoInfo)
}); err != nil {
return err
}
// Handle events.
for {
select {
case event, ok := <-events:
if !ok {
return errors.New("watch repos: events channel closed")
}
if event.Err != nil {
return event.Err
}
id := RepoID(event.Id)
switch event.Type {
case postgres.EventDelete:
if err := onDelete(id); err != nil {
return err
}
case postgres.EventInsert, postgres.EventUpdate:
var repoInfo *pfs.RepoInfo
if err := dbutil.WithTx(ctx, db, func(ctx context.Context, tx *pachsql.Tx) error {
var err error
repoInfo, err = GetRepo(ctx, tx, id)
if err != nil {
return err
}
return nil
}); err != nil {
return err
}
if err := onUpsert(id, repoInfo); err != nil {
return err
}
default:
return errors.Errorf("unknown event type: %v", event.Type)
}
case <-ctx.Done():
return errors.Wrap(ctx.Err(), "watch repos")
}
}
}