-
Notifications
You must be signed in to change notification settings - Fork 568
/
repos.go
435 lines (402 loc) · 13.8 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
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/pgjsontypes"
"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.metadata,
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
*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
}
func GetRepoInfoWithID(ctx context.Context, tx *pachsql.Tx, repoProject, repoName, repoType string) (*RepoInfoWithID, error) {
repo, err := getRepoByName(ctx, tx, repoProject, repoName, repoType)
if err != nil {
return nil, errors.Wrap(err, "get repo info with id")
}
repoInfo, err := repo.PbInfo()
if err != nil {
return nil, errors.Wrap(err, "get repo info with id")
}
return &RepoInfoWithID{
ID: repo.ID,
RepoInfo: repoInfo,
}, nil
}
// 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, metadata)
VALUES ($1, $2, (SELECT id from core.projects where name=$3), $4, $5)
ON CONFLICT (name, type, project_id) DO UPDATE SET description=EXCLUDED.description, metadata=EXCLUDED.metadata
RETURNING id
`,
repo.Repo.Name, repo.Repo.Type, repo.Repo.Project.Name, repo.Description, pgjsontypes.StringMap{Data: repo.Metadata},
).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")
RepoColumnName = repoColumn("repo.name")
RepoColumnProjectName = repoColumn("project.name")
)
type OrderByRepoColumn OrderByColumn[repoColumn]
type RepoFilter struct {
RepoTemplate *pfs.Repo
Projects []*pfs.Project
}
func NewRepoIterator(ctx context.Context, ext sqlx.ExtContext, startPage, pageSize, maxPages uint64, filter *RepoFilter, orderBys ...OrderByRepoColumn) (*RepoIterator, error) {
var conditions []string
var values []any
if filter != nil && filter.RepoTemplate != nil {
if filter.RepoTemplate.Project != nil && filter.RepoTemplate.Project.Name != "" {
conditions = append(conditions, "project.name = ?")
values = append(values, filter.RepoTemplate.Project.Name)
}
if filter.RepoTemplate.Name != "" {
conditions = append(conditions, "repo.name = ?")
values = append(values, filter.RepoTemplate.Name)
}
if filter.RepoTemplate.Type != "" {
conditions = append(conditions, "repo.type = ?")
values = append(values, filter.RepoTemplate.Type)
}
}
if filter != nil && len(filter.Projects) > 0 {
var projs []string
for _, p := range filter.Projects {
projs = append(projs, fmt.Sprintf("'%s'", p.Name))
}
cond := fmt.Sprintf("project.name IN (%s)", strings.Join(projs, ","))
conditions = append(conditions, cond)
}
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, maxPages),
ext: ext,
}, nil
}
func ForEachRepo(ctx context.Context, tx *pachsql.Tx, filter *RepoFilter, page *pfs.RepoPage, cb func(repoWithID RepoInfoWithID) error, orderBys ...OrderByRepoColumn) error {
var maxPages uint64
if page == nil {
page = &pfs.RepoPage{
PageIndex: 0,
PageSize: 100,
}
} else {
maxPages = 1
}
if len(orderBys) == 0 {
var err error
orderBys, err = makePageOrderBys(page.Order)
if err != nil {
return err
}
}
iter, err := NewRepoIterator(ctx, tx, uint64(page.PageIndex), uint64(page.PageSize), maxPages, 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 makePageOrderBys(ordering pfs.RepoPage_Ordering) ([]OrderByRepoColumn, error) {
if ordering == pfs.RepoPage_PROJECT_REPO {
return []OrderByRepoColumn{
{Column: RepoColumnProjectName, Order: SortOrderAsc},
{Column: RepoColumnName, Order: SortOrderAsc},
}, nil
}
return nil, errors.Errorf("cannot make page order bys for ordering %v", ordering)
}
func ListRepo(ctx context.Context, tx *pachsql.Tx, filter *RepoFilter, page *pfs.RepoPage, orderBys ...OrderByRepoColumn) ([]RepoInfoWithID, error) {
var repos []RepoInfoWithID
if err := ForEachRepo(ctx, tx, filter, page, 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, 0, 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")
}
}
}
func PickRepo(ctx context.Context, repoPicker *pfs.RepoPicker, tx *pachsql.Tx) (*RepoInfoWithID, error) {
if repoPicker == nil || repoPicker.Picker == nil {
return nil, errors.New("repo picker cannot be nil")
}
switch repoPicker.Picker.(type) {
case *pfs.RepoPicker_Name:
picker := repoPicker.GetName()
proj, err := PickProject(ctx, picker.Project, tx)
if err != nil {
return nil, errors.Wrap(err, "picking repo")
}
repo := &pfs.Repo{
Project: proj.ProjectInfo.Project,
Type: pfs.UserRepoType,
Name: picker.Name,
}
if picker.Type != "" {
repo.Type = picker.Type
}
repoInfoWithID, err := GetRepoInfoWithID(ctx, tx, repo.Project.Name, repo.Name, repo.Type)
if err != nil {
return nil, errors.Wrap(err, "picking repo")
}
return repoInfoWithID, nil
default:
return nil, errors.Errorf("repo picker is of an unknown type: %T", repoPicker.Picker)
}
}