repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/image.go
registry/app/store/database/image.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "sort" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" gitness_store "github.com/harness/gitness/store" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/pkg/errors" ) type ImageDao struct { db *sqlx.DB } func NewImageDao(db *sqlx.DB) store.ImageRepository { return &ImageDao{ db: db, } } type imageDB struct { ID int64 `db:"image_id"` UUID string `db:"image_uuid"` Name string `db:"image_name"` ArtifactType *artifact.ArtifactType `db:"image_type"` RegistryID int64 `db:"image_registry_id"` Labels sql.NullString `db:"image_labels"` Enabled bool `db:"image_enabled"` CreatedAt int64 `db:"image_created_at"` UpdatedAt int64 `db:"image_updated_at"` CreatedBy int64 `db:"image_created_by"` UpdatedBy int64 `db:"image_updated_by"` } type imageLabelDB struct { Labels sql.NullString `db:"labels"` } func (i ImageDao) GetByUUID(ctx context.Context, uuid string) (*types.Image, error) { stmt := databaseg.Builder. Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(imageDB{}), ",")). From("images"). Where("image_uuid = ?", uuid) db := dbtx.GetAccessor(ctx, i.db) dst := new(imageDB) sql, args, err := stmt.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find image by uuid") } return i.mapToImage(ctx, dst) } func (i ImageDao) Get(ctx context.Context, id int64) (*types.Image, error) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(imageDB{}), ",")). From("images"). Where("image_id = ?", id) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) dst := new(imageDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get image") } return i.mapToImage(ctx, dst) } func (i ImageDao) DeleteByImageNameAndRegID(ctx context.Context, regID int64, image string) (err error) { stmt := databaseg.Builder.Delete("images"). Where("image_name = ? AND image_registry_id = ?", image, regID) sql, args, err := stmt.ToSql() if err != nil { return errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) _, err = db.ExecContext(ctx, sql, args...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed") } return nil } func (i ImageDao) DeleteByImageNameIfNoLinkedArtifacts( ctx context.Context, regID int64, image string, ) error { stmt := databaseg.Builder.Delete("images"). Where("image_name = ? AND image_registry_id = ?", image, regID). Where("NOT EXISTS ( SELECT 1 FROM artifacts WHERE artifacts.artifact_image_id = images.image_id )") sql, args, err := stmt.ToSql() if err != nil { return errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) _, err = db.ExecContext(ctx, sql, args...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed") } return nil } func (i ImageDao) GetByName(ctx context.Context, registryID int64, name string) (*types.Image, error) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(imageDB{}), ",")). From("images"). Where("image_registry_id = ? AND image_name = ? AND image_type IS NULL", registryID, name) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) dst := new(imageDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get image") } return i.mapToImage(ctx, dst) } func (i ImageDao) GetByNameAndType( ctx context.Context, registryID int64, name string, artifactType *artifact.ArtifactType, ) (*types.Image, error) { if artifactType == nil || *artifactType == "" { return i.GetByName(ctx, registryID, name) } q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(imageDB{}), ",")). From("images"). Where("image_registry_id = ? AND image_name = ?", registryID, name). Where("image_type = ?", *artifactType) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) dst := new(imageDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get image") } return i.mapToImage(ctx, dst) } func (i ImageDao) CreateOrUpdate(ctx context.Context, image *types.Image) error { if commons.IsEmpty(image.Name) { return errors.New("package/image name is empty") } var conflictCondition string if image.ArtifactType == nil { conflictCondition = ` ON CONFLICT (image_registry_id, image_name) WHERE image_type IS NULL ` } else { conflictCondition = ` ON CONFLICT (image_registry_id, image_name, image_type) WHERE image_type IS NOT NULL ` } var sqlQuery = ` INSERT INTO images ( image_registry_id ,image_name ,image_type ,image_enabled ,image_created_at ,image_updated_at ,image_created_by ,image_updated_by ,image_uuid ) VALUES ( :image_registry_id ,:image_name ,:image_type ,:image_enabled ,:image_created_at ,:image_updated_at ,:image_created_by ,:image_updated_by ,:image_uuid ) ` + conflictCondition + ` DO UPDATE SET image_enabled = :image_enabled RETURNING image_id` db := dbtx.GetAccessor(ctx, i.db) query, arg, err := db.BindNamed(sqlQuery, i.mapToInternalImage(ctx, image)) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind image object") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&image.ID); err != nil && !errors.Is(err, sql.ErrNoRows) { return databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return nil } func (i ImageDao) GetLabelsByParentIDAndRepo( ctx context.Context, parentID int64, repo string, limit int, offset int, search string, ) (labels []string, err error) { q := databaseg.Builder.Select("a.image_labels as labels"). From("images a"). Join("registries r ON r.registry_id = a.image_registry_id"). Where("r.registry_parent_id = ? AND r.registry_name = ?", parentID, repo) if search != "" { q = q.Where("a.image_labels LIKE ?", "%"+search+"%") } q = q.OrderBy("a.image_labels ASC"). Limit(util.SafeIntToUInt64(limit)).Offset(util.SafeIntToUInt64(offset)) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } dst := []*imageLabelDB{} db := dbtx.GetAccessor(ctx, i.db) if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact labels") } return i.mapToImageLabels(dst), nil } func (i ImageDao) CountLabelsByParentIDAndRepo( ctx context.Context, parentID int64, repo, search string, ) (count int64, err error) { q := databaseg.Builder.Select("a.image_labels as labels"). From("images a"). Join("registries r ON r.registry_id = a.image_registry_id"). Where("r.registry_parent_id = ? AND r.registry_name = ?", parentID, repo) if search != "" { q = q.Where("a.image_labels LIKE ?", "%"+search+"%") } sql, args, err := q.ToSql() if err != nil { return -1, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) dst := []*imageLabelDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return -1, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact labels") } return int64(len(dst)), nil } func (i ImageDao) GetByRepoAndName( ctx context.Context, parentID int64, repo string, name string, ) (*types.Image, error) { q := databaseg.Builder.Select("a.image_id, a.image_name, "+ " a.image_registry_id, a.image_labels, a.image_created_at, "+ " a.image_updated_at, a.image_created_by, a.image_updated_by"). From("images a"). Join(" registries r ON r.registry_id = a.image_registry_id"). Where("r.registry_parent_id = ? AND r.registry_name = ? AND a.image_name = ?", parentID, repo, name) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, i.db) dst := new(imageDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact") } return i.mapToImage(ctx, dst) } func (i ImageDao) Update(ctx context.Context, image *types.Image) (err error) { var sqlQuery = " UPDATE images SET " + util.GetSetDBKeys(imageDB{}, "image_id", "image_uuid") + " WHERE image_id = :image_id " dbImage := i.mapToInternalImage(ctx, image) // update Version (used for optimistic locking) and Updated time dbImage.UpdatedAt = time.Now().UnixMilli() db := dbtx.GetAccessor(ctx, i.db) query, arg, err := db.BindNamed(sqlQuery, dbImage) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind images object") } result, err := db.ExecContext(ctx, query, arg...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to update images") } count, err := result.RowsAffected() if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows") } if count == 0 { return gitness_store.ErrVersionConflict } return nil } func (i ImageDao) UpdateStatus(ctx context.Context, image *types.Image) (err error) { q := databaseg.Builder.Update("images"). Set("image_enabled", image.Enabled). Set("image_updated_at", time.Now().UnixMilli()). Where("image_registry_id = ? AND image_name = ?", image.RegistryID, image.Name) sql, args, err := q.ToSql() if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind images object") } result, err := i.db.ExecContext(ctx, sql, args...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to update images") } count, err := result.RowsAffected() if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to get number of updated rows") } if count == 0 { return gitness_store.ErrVersionConflict } return nil } func (i ImageDao) DuplicateImage(ctx context.Context, sourceImage *types.Image, targetRegistryID int64) ( *types.Image, error, ) { targetImage := &types.Image{ Name: sourceImage.Name, ArtifactType: sourceImage.ArtifactType, RegistryID: targetRegistryID, Enabled: sourceImage.Enabled, } err := i.CreateOrUpdate(ctx, targetImage) if err != nil { return nil, errors.Wrap(err, "Failed to duplicate image") } return targetImage, nil } func (i ImageDao) mapToInternalImage(ctx context.Context, in *types.Image) *imageDB { session, _ := request.AuthSessionFrom(ctx) if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } in.UpdatedAt = time.Now() in.UpdatedBy = session.Principal.ID if in.UUID == "" { in.UUID = uuid.NewString() } sort.Strings(in.Labels) return &imageDB{ ID: in.ID, UUID: in.UUID, Name: in.Name, ArtifactType: in.ArtifactType, RegistryID: in.RegistryID, Labels: util.GetEmptySQLString(util.ArrToString(in.Labels)), Enabled: in.Enabled, CreatedAt: in.CreatedAt.UnixMilli(), UpdatedAt: in.UpdatedAt.UnixMilli(), CreatedBy: in.CreatedBy, UpdatedBy: in.UpdatedBy, } } func (i ImageDao) mapToImage(_ context.Context, dst *imageDB) (*types.Image, error) { createdBy := dst.CreatedBy updatedBy := dst.UpdatedBy return &types.Image{ ID: dst.ID, UUID: dst.UUID, Name: dst.Name, ArtifactType: dst.ArtifactType, RegistryID: dst.RegistryID, Labels: util.StringToArr(dst.Labels.String), Enabled: dst.Enabled, CreatedAt: time.UnixMilli(dst.CreatedAt), UpdatedAt: time.UnixMilli(dst.UpdatedAt), CreatedBy: createdBy, UpdatedBy: updatedBy, }, nil } func (i ImageDao) mapToImageLabels(dst []*imageLabelDB) []string { elements := make(map[string]bool) res := []string{} for _, labels := range dst { elements, res = i.mapToImageLabel(elements, res, labels) } return res } func (i ImageDao) mapToImageLabel( elements map[string]bool, res []string, dst *imageLabelDB, ) (map[string]bool, []string) { if dst == nil { return elements, res } labels := util.StringToArr(dst.Labels.String) for _, label := range labels { if !elements[label] { elements[label] = true res = append(res, label) } } return elements, res }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/download_stat.go
registry/app/store/database/download_stat.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "fmt" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" sq "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) type DownloadStatDao struct { db *sqlx.DB } func NewDownloadStatDao(db *sqlx.DB) store.DownloadStatRepository { return &DownloadStatDao{ db: db, } } type downloadStatDB struct { ID int64 `db:"download_stat_id"` ArtifactID int64 `db:"download_stat_artifact_id"` Timestamp int64 `db:"download_stat_timestamp"` CreatedAt int64 `db:"download_stat_created_at"` UpdatedAt int64 `db:"download_stat_updated_at"` CreatedBy int64 `db:"download_stat_created_by"` UpdatedBy int64 `db:"download_stat_updated_by"` } func (d DownloadStatDao) Create(ctx context.Context, downloadStat *types.DownloadStat) error { const sqlQuery = ` INSERT INTO download_stats ( download_stat_artifact_id ,download_stat_timestamp ,download_stat_created_at ,download_stat_updated_at ,download_stat_created_by ,download_stat_updated_by ) VALUES ( :download_stat_artifact_id ,:download_stat_timestamp ,:download_stat_created_at ,:download_stat_updated_at ,:download_stat_created_by ,:download_stat_updated_by ) RETURNING download_stat_id` db := dbtx.GetAccessor(ctx, d.db) query, arg, err := db.BindNamed(sqlQuery, d.mapToInternalDownloadStat(ctx, downloadStat)) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind download stat object") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&downloadStat.ID); err != nil && !errors.Is(err, sql.ErrNoRows) { return databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return nil } func (d DownloadStatDao) CreateByRegistryIDImageAndArtifactName( ctx context.Context, regID int64, image string, version string, ) error { selectQuery := databaseg.Builder. Select( "a.artifact_id", "?", "?", "?", "?", "?", ). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Where("a.artifact_version = ? AND i.image_registry_id = ? AND i.image_name = ?"). Limit(1) insertQuery := databaseg.Builder. Insert("download_stats"). Columns( "download_stat_artifact_id", "download_stat_timestamp", "download_stat_created_at", "download_stat_updated_at", "download_stat_created_by", "download_stat_updated_by", ). Select(selectQuery) // Convert query to SQL string and args sqlStr, _, err := insertQuery.ToSql() if err != nil { return fmt.Errorf("failed to generate SQL: %w", err) } session, _ := request.AuthSessionFrom(ctx) user := session.Principal.ID db := dbtx.GetAccessor(ctx, d.db) // Execute the query with parameters _, err = db.ExecContext(ctx, sqlStr, time.Now().UnixMilli(), time.Now().UnixMilli(), time.Now().UnixMilli(), user, user, version, regID, image) if err != nil { return fmt.Errorf("failed to insert download stat: %w", err) } return nil } func (d DownloadStatDao) GetTotalDownloadsForImage(ctx context.Context, imageID int64) (int64, error) { q := databaseg.Builder.Select(`count(*)`). From("artifacts art").Where("art.artifact_image_id = ?", imageID). Join("download_stats ds ON ds.download_stat_artifact_id = art.artifact_id") sql, args, err := q.ToSql() if err != nil { return 0, errors.Wrap(err, "Failed to convert query to sql") } // Log the final sql query finalQuery := util.FormatQuery(sql, args) log.Ctx(ctx).Debug().Str("sql", finalQuery).Msg("Executing GetTotalDownloadsForImage query") // Execute query db := dbtx.GetAccessor(ctx, d.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (d DownloadStatDao) GetTotalDownloadsForArtifactID(ctx context.Context, artifactID int64) (int64, error) { q := databaseg.Builder.Select(`count(*)`). From("download_stats ds").Where("ds.download_stat_artifact_id = ?", artifactID) sql, args, err := q.ToSql() if err != nil { return 0, errors.Wrap(err, "Failed to convert query to sql") } // Log the final sql query finalQuery := util.FormatQuery(sql, args) log.Ctx(ctx).Debug().Str("sql", finalQuery).Msg("Executing GetTotalDownloadsForArtifact query") // Execute query db := dbtx.GetAccessor(ctx, d.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (d DownloadStatDao) GetTotalDownloadsForManifests( ctx context.Context, artifactVersions []string, imageID int64, ) (map[string]int64, error) { q := databaseg.Builder.Select(`art.artifact_version, count(*) as count`). From("artifacts art"). Join("download_stats ds ON ds.download_stat_artifact_id = art.artifact_id").Where(sq.And{ sq.Eq{"artifact_image_id": imageID}, sq.Eq{"artifact_version": artifactVersions}, }, "art").GroupBy("art.artifact_version") sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } // Log the final sql query finalQuery := util.FormatQuery(sql, args) log.Ctx(ctx).Debug().Str("sql", finalQuery).Msg("Executing GetTotalDownloadsForManifests query") // Execute query db := dbtx.GetAccessor(ctx, d.db) dst := []*versionsCountDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing query") } // Convert the slice to a map result := make(map[string]int64) for _, v := range dst { result[v.Version] = v.Count } return result, nil } func (d DownloadStatDao) mapToInternalDownloadStat( ctx context.Context, in *types.DownloadStat, ) *downloadStatDB { session, _ := request.AuthSessionFrom(ctx) if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } in.UpdatedAt = time.Now() return &downloadStatDB{ ID: in.ID, ArtifactID: in.ArtifactID, Timestamp: time.Now().UnixMilli(), CreatedAt: in.CreatedAt.UnixMilli(), UpdatedAt: in.UpdatedAt.UnixMilli(), CreatedBy: in.CreatedBy, UpdatedBy: session.Principal.ID, } } type versionsCountDB struct { Version string `db:"artifact_version"` Count int64 `db:"count"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/task_event_store.go
registry/app/store/database/task_event_store.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "fmt" "time" "github.com/harness/gitness/registry/app/store" databaseg "github.com/harness/gitness/store/database" "github.com/google/uuid" "github.com/jmoiron/sqlx" ) type taskEventStore struct { db *sqlx.DB } // NewTaskEventStore returns a new TaskEventRepository implementation. func NewTaskEventStore(db *sqlx.DB) store.TaskEventRepository { return &taskEventStore{ db: db, } } // LogTaskEvent logs an event in the task_events table. func (s *taskEventStore) LogTaskEvent(ctx context.Context, key string, event string, payload []byte) error { now := time.Now().UnixMilli() stmt := databaseg.Builder. Insert("registry_task_events"). Columns("registry_task_event_id", "registry_task_event_key", "registry_task_event_event", "registry_task_event_payload", "registry_task_event_created_at"). Values(uuid.NewString(), key, event, payload, now) query, args, err := stmt.ToSql() if err != nil { return fmt.Errorf("failed to build insert event query: %w", err) } _, err = s.db.ExecContext(ctx, query, args...) if err != nil { return fmt.Errorf("failed to log task event '%s' for task %s: %w", event, key, err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/bandwidth_stat.go
registry/app/store/database/bandwidth_stat.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "errors" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/types" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" ) type BandwidthStatDao struct { db *sqlx.DB } func NewBandwidthStatDao(db *sqlx.DB) store.BandwidthStatRepository { return &BandwidthStatDao{ db: db, } } type bandwidthStatDB struct { ID int64 `db:"bandwidth_stat_id"` ImageID int64 `db:"bandwidth_stat_image_id"` Timestamp int64 `db:"bandwidth_stat_timestamp"` Type types.BandwidthType `db:"bandwidth_stat_type"` Bytes int64 `db:"bandwidth_stat_bytes"` CreatedAt int64 `db:"bandwidth_stat_created_at"` UpdatedAt int64 `db:"bandwidth_stat_updated_at"` CreatedBy int64 `db:"bandwidth_stat_created_by"` UpdatedBy int64 `db:"bandwidth_stat_updated_by"` } func (b BandwidthStatDao) Create(ctx context.Context, bandwidthStat *types.BandwidthStat) error { const sqlQuery = ` INSERT INTO bandwidth_stats ( bandwidth_stat_image_id ,bandwidth_stat_timestamp ,bandwidth_stat_type ,bandwidth_stat_bytes ,bandwidth_stat_created_at ,bandwidth_stat_updated_at ,bandwidth_stat_created_by ,bandwidth_stat_updated_by ) VALUES ( :bandwidth_stat_image_id ,:bandwidth_stat_timestamp ,:bandwidth_stat_type ,:bandwidth_stat_bytes ,:bandwidth_stat_created_at ,:bandwidth_stat_updated_at ,:bandwidth_stat_created_by ,:bandwidth_stat_updated_by ) RETURNING bandwidth_stat_id` db := dbtx.GetAccessor(ctx, b.db) query, arg, err := db.BindNamed(sqlQuery, b.mapToInternalBandwidthStat(ctx, bandwidthStat)) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind bandwidth stat object") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&bandwidthStat.ID); err != nil && !errors.Is(err, sql.ErrNoRows) { return databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return nil } func (b BandwidthStatDao) mapToInternalBandwidthStat(ctx context.Context, in *types.BandwidthStat) *bandwidthStatDB { session, _ := request.AuthSessionFrom(ctx) if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } in.UpdatedAt = time.Now() return &bandwidthStatDB{ ID: in.ID, ImageID: in.ImageID, Timestamp: time.Now().UnixMilli(), Type: in.Type, Bytes: in.Bytes, CreatedAt: in.CreatedAt.UnixMilli(), UpdatedAt: in.UpdatedAt.UnixMilli(), CreatedBy: in.CreatedBy, UpdatedBy: session.Principal.ID, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/tag.go
registry/app/store/database/tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "encoding/json" "fmt" "sort" "strings" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" store2 "github.com/harness/gitness/store" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" sq "github.com/Masterminds/squirrel" "github.com/jmoiron/sqlx" "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) const ( // OrderDesc is the normalized string to be used for sorting results in descending order. OrderDesc types.SortOrder = "desc" lessThan string = "<" greaterThan string = ">" labelSeparatorStart string = "%^_" labelSeparatorEnd string = "^_%" downloadCount string = "download_count" imageName string = "image_name" name string = "name" postgresStringAgg string = "string_agg" sqliteGroupConcat string = "group_concat" ) type tagDao struct { db *sqlx.DB } func NewTagDao(db *sqlx.DB) store.TagRepository { return &tagDao{ db: db, } } // tagDB holds the record of a tag in DB. type tagDB struct { ID int64 `db:"tag_id"` Name string `db:"tag_name"` ImageName string `db:"tag_image_name"` RegistryID int64 `db:"tag_registry_id"` ManifestID int64 `db:"tag_manifest_id"` CreatedAt int64 `db:"tag_created_at"` UpdatedAt int64 `db:"tag_updated_at"` CreatedBy sql.NullInt64 `db:"tag_created_by"` UpdatedBy sql.NullInt64 `db:"tag_updated_by"` } type artifactMetadataDB struct { ID int64 `db:"artifact_id"` UUID string `db:"uuid"` Name string `db:"name"` RegistryUUID string `db:"registry_uuid"` RepoName string `db:"repo_name"` DownloadCount int64 `db:"download_count"` PackageType artifact.PackageType `db:"package_type"` Labels sql.NullString `db:"labels"` LatestVersion string `db:"latest_version"` CreatedAt int64 `db:"created_at"` ModifiedAt int64 `db:"modified_at"` Tag *string `db:"tag"` Version string `db:"version"` Metadata *json.RawMessage `db:"metadata"` IsQuarantined bool `db:"is_quarantined"` QuarantineReason *string `db:"quarantine_reason"` ArtifactType *artifact.ArtifactType `db:"artifact_type"` Tags *string `db:"tags"` } type tagMetadataDB struct { Name string `db:"name"` Size string `db:"size"` PackageType artifact.PackageType `db:"package_type"` DigestCount int `db:"digest_count"` ModifiedAt int64 `db:"modified_at"` SchemaVersion int `db:"manifest_schema_version"` NonConformant bool `db:"manifest_non_conformant"` Payload []byte `db:"manifest_payload"` MediaType string `db:"mt_media_type"` Digest []byte `db:"manifest_digest"` DownloadCount int64 `db:"download_count"` } type ociVersionMetadataDB struct { Size string `db:"size"` PackageType artifact.PackageType `db:"package_type"` DigestCount int `db:"digest_count"` ModifiedAt int64 `db:"modified_at"` SchemaVersion int `db:"manifest_schema_version"` NonConformant bool `db:"manifest_non_conformant"` Payload []byte `db:"manifest_payload"` MediaType string `db:"mt_media_type"` Digest []byte `db:"manifest_digest"` DownloadCount int64 `db:"download_count"` Tags *string `db:"tags"` } type tagDetailDB struct { ID int64 `db:"id"` Name string `db:"name"` ImageName string `db:"image_name"` CreatedAt int64 `db:"created_at"` UpdatedAt int64 `db:"updated_at"` Size string `db:"size"` DownloadCount int64 `db:"download_count"` } type tagInfoDB struct { Name string `db:"name"` Digest []byte `db:"manifest_digest"` } func (t tagDao) CreateOrUpdate(ctx context.Context, tag *types.Tag) error { const sqlQuery = ` INSERT INTO tags ( tag_name ,tag_image_name ,tag_registry_id ,tag_manifest_id ,tag_created_at ,tag_updated_at ,tag_created_by ,tag_updated_by ) VALUES ( :tag_name ,:tag_image_name ,:tag_registry_id ,:tag_manifest_id ,:tag_created_at ,:tag_updated_at ,:tag_created_by ,:tag_updated_by ) ON CONFLICT (tag_registry_id, tag_name, tag_image_name) DO UPDATE SET tag_manifest_id = :tag_manifest_id, tag_updated_at = :tag_updated_at WHERE tags.tag_manifest_id <> :tag_manifest_id RETURNING tag_id, tag_created_at, tag_updated_at` db := dbtx.GetAccessor(ctx, t.db) tagDB := t.mapToInternalTag(ctx, tag) query, arg, err := db.BindNamed(sqlQuery, tagDB) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind repo object") } if err = db.QueryRowContext(ctx, query, arg...).Scan( &tagDB.ID, &tagDB.CreatedAt, &tagDB.UpdatedAt, ); err != nil { err := databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") if !errors.Is(err, store2.ErrResourceNotFound) { return err } } return nil } // LockTagByNameForUpdate locks a tag by name within a repository using SELECT FOR UPDATE. // It returns a boolean indicating whether the tag exists and was successfully locked. func (t tagDao) LockTagByNameForUpdate( ctx context.Context, repoID int64, name string, ) (bool, error) { // Since tag_registry_id is not unique in the DB schema, we use LIMIT 1 to ensure that // only one record is locked and processed. stmt := databaseg.Builder.Select("1"). From("tags"). Where("tag_registry_id = ? AND tag_name = ?", repoID, name). Limit(1). Suffix("FOR UPDATE") sqlQuery, args, err := stmt.ToSql() if err != nil { return false, fmt.Errorf("failed to convert select for update query to SQL: %w", err) } db := dbtx.GetAccessor(ctx, t.db) var exists int err = db.QueryRowContext(ctx, sqlQuery, args...).Scan(&exists) if err != nil { if errors.Is(err, sql.ErrNoRows) { return false, nil // Tag does not exist } return false, databaseg.ProcessSQLErrorf(ctx, err, "the select for update query failed") } return true, nil } // DeleteTagByName deletes a tag by name within a repository. A boolean is returned to denote whether the tag was // deleted or not. This avoids the need for a separate preceding `SELECT` to find if it exists. func (t tagDao) DeleteTagByName( ctx context.Context, repoID int64, name string, ) (bool, error) { stmt := databaseg.Builder.Delete("tags"). Where("tag_registry_id = ? AND tag_name = ?", repoID, name) sql, args, err := stmt.ToSql() if err != nil { return false, fmt.Errorf("failed to convert purge tag query to sql: %w", err) } db := dbtx.GetAccessor(ctx, t.db) result, err := db.ExecContext(ctx, sql, args...) if err != nil { return false, databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed") } count, _ := result.RowsAffected() return count == 1, nil } // DeleteTagByName deletes a tag by name within a repository. // // A boolean is returned to denote whether the tag was // // deleted or not. This avoids the need for a separate preceding // // `SELECT` to find if it exists. func (t tagDao) DeleteTagByManifestID( ctx context.Context, repoID int64, manifestID int64, ) (bool, error) { stmt := databaseg.Builder.Delete("tags"). Where("tag_registry_id = ? AND tag_manifest_id = ?", repoID, manifestID) sql, args, err := stmt.ToSql() if err != nil { return false, fmt.Errorf("failed to convert purge tag query to sql: %w", err) } db := dbtx.GetAccessor(ctx, t.db) result, err := db.ExecContext(ctx, sql, args...) if err != nil { return false, databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed") } count, _ := result.RowsAffected() return count > 0, nil } // TagsPaginated finds up to `filters.MaxEntries` tags of a given // repository with name lexicographically after `filters.LastEntry`. // This is used exclusively for the GET /v2/<name>/tags/list API route, // where pagination is done with a marker (`filters.LastEntry`). // Even if there is no tag with a name of `filters.LastEntry`, // the returned tags will always be those with a path lexicographically after // `filters.LastEntry`. Finally, tags are lexicographically sorted. // These constraints exists to preserve the existing API behaviour // (when doing a filesystem walk based pagination). func (t tagDao) TagsPaginated( ctx context.Context, repoID int64, image string, filters types.FilterParams, ) ([]*types.Tag, error) { stmt := databaseg.Builder. Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(tagDB{}), ",")). From("tags"). Where( "tag_registry_id = ? AND tag_image_name = ? AND tag_name > ?", repoID, image, filters.LastEntry, ). OrderBy("tag_name").Limit(uint64(filters.MaxEntries)) //nolint:gosec db := dbtx.GetAccessor(ctx, t.db) dst := []*tagDB{} sql, args, err := stmt.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find tag") } return t.mapToTagList(ctx, dst) } func (t tagDao) HasTagsAfterName( ctx context.Context, repoID int64, filters types.FilterParams, ) (bool, error) { stmt := databaseg.Builder. Select("COUNT(*)"). From("tags"). Where( "tag_registry_id = ? AND tag_name LIKE ? ", repoID, sqlPartialMatch(filters.Name), ) comparison := greaterThan if filters.SortOrder == OrderDesc { comparison = lessThan } if filters.OrderBy != "published_at" { stmt = stmt.Where("tag_name "+comparison+" ?", filters.LastEntry) } else { stmt = stmt.Where( "AND (GREATEST(tag_created_at, tag_updated_at), tag_name) "+comparison+" (? ?)", filters.PublishedAt, filters.LastEntry, ) } stmt = stmt.OrderBy("tag_name").GroupBy("tag_name").Limit(uint64(filters.MaxEntries)) //nolint:gosec db := dbtx.GetAccessor(ctx, t.db) var count int64 sqlQuery, args, err := stmt.ToSql() if err != nil { return false, errors.Wrap(err, "Failed to convert query to sqlQuery") } if err = db.QueryRowContext(ctx, sqlQuery, args...).Scan(&count); err != nil && !errors.Is(err, sql.ErrNoRows) { return false, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find tag") } return count == 1, nil } // sqlPartialMatch builds a string that can be passed as value // // for a SQL `LIKE` expression. Besides surrounding the // // input value with `%` wildcard characters for a partial match, // // this function also escapes the `_` and `%` // // metacharacters supported in Postgres `LIKE` expressions. // See https://www.postgresql.org/docs/current/ // functions-matching.html#FUNCTIONS-LIKE for more details. func sqlPartialMatch(value string) string { value = strings.ReplaceAll(value, "_", `\_`) value = strings.ReplaceAll(value, "%", `\%`) return fmt.Sprintf("%%%s%%", value) } func (t tagDao) GetAllArtifactsByParentID( ctx context.Context, parentID int64, registryIDs *[]string, sortByField string, sortByOrder string, limit int, offset int, search string, latestVersion bool, packageTypes []string, ) (*[]types.ArtifactMetadata, error) { q1 := t.GetAllArtifactOnParentIDQueryForNonOCI(parentID, latestVersion, registryIDs, packageTypes, search, false) q2 := t.GetAllArtifactsQueryByParentIDForOCI(parentID, latestVersion, registryIDs, packageTypes, search) q1SQL, q1Args, err := q1.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } q2SQL, _, err := q2.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } // Combine q1 and q2 with UNION ALL finalQuery := fmt.Sprintf(` SELECT repo_name, name, package_type, version, modified_at, labels, download_count, is_quarantined, quarantine_reason, artifact_type, registry_uuid, uuid FROM (%s UNION ALL %s) AS combined `, q1SQL, q2SQL) // Combine query arguments finalArgs := q1Args // Apply sorting based on provided field sortField := "modified_at" switch sortByField { case downloadCount: sortField = "download_count" case imageName: sortField = "name" } finalQuery = fmt.Sprintf("%s ORDER BY %s %s", finalQuery, sortField, sortByOrder) // Add pagination (LIMIT and OFFSET) **after** the WHERE and ORDER BY clauses finalQuery = fmt.Sprintf("%s LIMIT %d OFFSET %d", finalQuery, limit, offset) db := dbtx.GetAccessor(ctx, t.db) dst := []*artifactMetadataDB{} if err = db.SelectContext(ctx, &dst, finalQuery, finalArgs...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing custom list query") } return t.mapToArtifactMetadataList(dst) } func (t tagDao) GetAllArtifactsQueryByParentIDForOCI( parentID int64, latestVersion bool, registryIDs *[]string, packageTypes []string, search string, ) sq.SelectBuilder { // TODO: update query to return correct artifact uuid q2 := databaseg.Builder.Select( `r.registry_name as repo_name, r.registry_uuid as registry_uuid, t.tag_image_name as name, r.registry_package_type as package_type, t.tag_name as version, i.image_uuid as uuid, t.tag_updated_at as modified_at, i.image_labels as labels, COALESCE(t2.download_count,0) as download_count, false as is_quarantined, '' as quarantine_reason, i.image_type as artifact_type `, ). From("tags t"). Join("registries r ON t.tag_registry_id = r.registry_id"). Where("r.registry_parent_id = ?", parentID). Join( "images i ON i.image_registry_id = t.tag_registry_id AND"+ " i.image_name = t.tag_image_name", ). LeftJoin( `( SELECT i.image_name, SUM(COALESCE(t1.download_count, 0)) as download_count FROM ( SELECT a.artifact_image_id, COUNT(d.download_stat_id) as download_count FROM artifacts a JOIN download_stats d ON d.download_stat_artifact_id = a.artifact_id GROUP BY a.artifact_image_id ) as t1 JOIN images i ON i.image_id = t1.artifact_image_id JOIN registries r ON r.registry_id = i.image_registry_id WHERE r.registry_parent_id = ? GROUP BY i.image_name) as t2 ON t.tag_image_name = t2.image_name`, parentID, ) if latestVersion { q2 = q2.Join( `(SELECT t.tag_id as id, ROW_NUMBER() OVER (PARTITION BY t.tag_registry_id, t.tag_image_name ORDER BY t.tag_updated_at DESC) AS rank FROM tags t JOIN registries r ON t.tag_registry_id = r.registry_id WHERE r.registry_parent_id = ? ) AS a ON t.tag_id = a.id`, parentID, // nolint:goconst ). Where("a.rank = 1") } if len(*registryIDs) > 0 { q2 = q2.Where(sq.Eq{"r.registry_name": registryIDs}) } if len(packageTypes) > 0 { q2 = q2.Where(sq.Eq{"r.registry_package_type": packageTypes}) } if search != "" { q2 = q2.Where("t.tag_image_name LIKE ?", sqlPartialMatch(search)) } return q2 } func (t tagDao) GetAllArtifactsByParentIDUntagged( ctx context.Context, parentID int64, registryIDs *[]string, sortByField string, sortByOrder string, limit int, offset int, search string, packageTypes []string, ) (*[]types.ArtifactMetadata, error) { // Query 1: Get core artifact data with pagination coreQuery := t.getCoreArtifactsQuery( parentID, registryIDs, packageTypes, search, sortByField, sortByOrder, limit, offset) coreSQL, coreArgs, err := coreQuery.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert core query to sql") } db := dbtx.GetAccessor(ctx, t.db) coreResults := []*artifactMetadataDB{} if err = db.SelectContext(ctx, &coreResults, coreSQL, coreArgs...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing core artifacts query") } if len(coreResults) == 0 { return &[]types.ArtifactMetadata{}, nil } // Extract artifact IDs for enrichment query artifactIDs := make([]int64, len(coreResults)) for i, result := range coreResults { artifactIDs[i] = result.ID } // Query 2: Get download counts and tags only for returned artifacts enrichmentData, err := t.getArtifactEnrichmentData(ctx, artifactIDs) if err != nil { return nil, errors.Wrap(err, "Failed to get enrichment data") } // Merge the data for _, result := range coreResults { if enrichment, exists := enrichmentData[result.ID]; exists { result.DownloadCount = enrichment.DownloadCount if enrichment.Tags != "" { result.Tags = &enrichment.Tags } } } return t.mapToArtifactMetadataList(coreResults) } // getCoreArtifactsQuery returns core artifact data with pagination (no download counts or tags). func (t tagDao) getCoreArtifactsQuery( parentID int64, registryIDs *[]string, packageTypes []string, search string, sortByField string, sortByOrder string, limit int, offset int, ) sq.SelectBuilder { query := databaseg.Builder.Select( `ar.artifact_id, ar.artifact_uuid as uuid, r.registry_uuid as registry_uuid, r.registry_name as repo_name, i.image_name as name, r.registry_package_type as package_type, ar.artifact_version as version, ar.artifact_updated_at as modified_at, i.image_type as artifact_type`, ). From("artifacts ar"). Join("images i ON i.image_id = ar.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). Where("r.registry_parent_id = ?", parentID) // Apply filters if len(*registryIDs) > 0 { query = query.Where(sq.Eq{"r.registry_name": registryIDs}) } if len(packageTypes) > 0 { query = query.Where(sq.Eq{"r.registry_package_type": packageTypes}) } if search != "" { query = query.Where("i.image_name LIKE ?", sqlPartialMatch(search)) } // Apply sorting and pagination sortField := "ar.artifact_updated_at" if sortByField == imageName { sortField = "i.image_name" } return query.OrderBy(fmt.Sprintf("%s %s", sortField, sortByOrder)). Limit(uint64(limit)). // nolint:gosec Offset(uint64(offset)) // nolint:gosec } type enrichmentData struct { DownloadCount int64 Tags string } func (t tagDao) getArtifactEnrichmentData(ctx context.Context, artifactIDs []int64) (map[int64]enrichmentData, error) { if len(artifactIDs) == 0 { return make(map[int64]enrichmentData), nil } db := dbtx.GetAccessor(ctx, t.db) driver := db.DriverName() // Pick aggregation function and decode function depending on database var tagAggExpr, decodeFunction string if driver == "postgres" { tagAggExpr = "STRING_AGG(t.tag_name, ',')" decodeFunction = "decode(ar.artifact_version, 'hex')" } else { tagAggExpr = "GROUP_CONCAT(t.tag_name, ',')" decodeFunction = "unhex(ar.artifact_version)" } // Build placeholders for the 3 IN clauses var placeholders1, placeholders2, placeholders3, placeholders4 string args := make([]interface{}, 0, len(artifactIDs)*4) const placeholderSeparator = ", ?" // nolint:nestif if driver == "postgres" { // PostgreSQL: sequential parameter numbering across entire query paramIndex := 1 // First IN clause (main WHERE) for i := range artifactIDs { if i > 0 { placeholders1 += fmt.Sprintf(", $%d", paramIndex) } else { placeholders1 += fmt.Sprintf("$%d", paramIndex) } paramIndex++ } // Second IN clause (download_counts) for i := range artifactIDs { if i > 0 { placeholders2 += fmt.Sprintf(", $%d", paramIndex) } else { placeholders2 += fmt.Sprintf("$%d", paramIndex) } paramIndex++ } // Third IN clause (tag_lists) for i := range artifactIDs { if i > 0 { placeholders3 += fmt.Sprintf(", $%d", paramIndex) } else { placeholders3 += fmt.Sprintf("$%d", paramIndex) } paramIndex++ } // Fourth IN clause (main WHERE) for i := range artifactIDs { if i > 0 { placeholders4 += fmt.Sprintf(", $%d", paramIndex) } else { placeholders4 += fmt.Sprintf("$%d", paramIndex) } paramIndex++ } } else { // SQLite: ? placeholders can be reused for i := range artifactIDs { if i > 0 { placeholders1 += placeholderSeparator placeholders2 += placeholderSeparator placeholders3 += placeholderSeparator placeholders4 += placeholderSeparator } else { placeholders1 += "?" placeholders2 += "?" placeholders3 += "?" placeholders4 += "?" } } } // Arguments: artifactIDs repeated 4 times for the 4 IN clauses for range 4 { for _, id := range artifactIDs { args = append(args, id) } } query := fmt.Sprintf(` WITH oci_artifacts AS ( SELECT a.artifact_image_id, a.artifact_id, a.artifact_version FROM artifacts a join images i ON a.artifact_image_id = i.image_id join registries r ON r.registry_id = i.image_registry_id where r.registry_package_type IN ('DOCKER','HELM') and artifact_id IN (%s) ), download_counts AS ( SELECT ds.download_stat_artifact_id AS artifact_id, COUNT(ds.download_stat_id) AS download_count FROM download_stats ds WHERE ds.download_stat_artifact_id IN (%s) GROUP BY ds.download_stat_artifact_id ), tag_lists AS ( SELECT ar.artifact_id, %s AS tags FROM oci_artifacts ar JOIN images i ON i.image_id = ar.artifact_image_id JOIN manifests m ON m.manifest_registry_id = i.image_registry_id AND m.manifest_image_name = i.image_name AND m.manifest_digest = %s JOIN tags t ON t.tag_manifest_id = m.manifest_id WHERE ar.artifact_id IN (%s) GROUP BY ar.artifact_id ) SELECT ar.artifact_id, COALESCE(dc.download_count, 0) AS download_count, COALESCE(tl.tags, '') AS tags FROM artifacts ar LEFT JOIN download_counts dc ON dc.artifact_id = ar.artifact_id LEFT JOIN tag_lists tl ON tl.artifact_id = ar.artifact_id WHERE ar.artifact_id IN (%s); `, placeholders1, placeholders2, tagAggExpr, decodeFunction, placeholders3, placeholders4) type enrichmentRow struct { ArtifactID int64 `db:"artifact_id"` DownloadCount int64 `db:"download_count"` Tags string `db:"tags"` } var rows []enrichmentRow if err := db.SelectContext(ctx, &rows, query, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing enrichment query") } result := make(map[int64]enrichmentData, len(rows)) for _, row := range rows { result[row.ArtifactID] = enrichmentData{ DownloadCount: row.DownloadCount, Tags: row.Tags, } } return result, nil } func (t tagDao) GetAllArtifactOnParentIDQueryForNonOCI( parentID int64, latestVersion bool, registryIDs *[]string, packageTypes []string, search string, queryTags bool, ) sq.SelectBuilder { suffix := " " if queryTags { suffix = ", NULL AS tags " } q1 := databaseg.Builder.Select( `r.registry_name as repo_name, r.registry_uuid as registry_uuid, i.image_name as name, r.registry_package_type as package_type, ar.artifact_version as version, ar.artifact_uuid as uuid, ar.artifact_updated_at as modified_at, i.image_labels as labels, COALESCE(t2.download_count, 0) as download_count, (qp.quarantined_path_id IS NOT NULL) AS is_quarantined, qp.quarantined_path_reason as quarantine_reason, i.image_type as artifact_type`+suffix, ). From("artifacts ar"). Join("images i ON i.image_id = ar.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). Where("r.registry_parent_id = ? AND r.registry_package_type NOT IN ('DOCKER', 'HELM')", parentID). LeftJoin("quarantined_paths qp ON ((qp.quarantined_path_artifact_id = ar.artifact_id "+ "OR qp.quarantined_path_artifact_id IS NULL) "+ "AND qp.quarantined_path_image_id = i.image_id) AND qp.quarantined_path_registry_id = r.registry_id"). LeftJoin( `( SELECT a.artifact_version, SUM(COALESCE(t1.download_count, 0)) as download_count FROM ( SELECT a.artifact_id, COUNT(d.download_stat_id) as download_count FROM artifacts a JOIN download_stats d ON d.download_stat_artifact_id = a.artifact_id GROUP BY a.artifact_id ) as t1 JOIN artifacts a ON a.artifact_id = t1.artifact_id JOIN images i ON i.image_id = a.artifact_image_id JOIN registries r ON r.registry_id = i.image_registry_id WHERE r.registry_parent_id = ? GROUP BY a.artifact_version) as t2 ON ar.artifact_version = t2.artifact_version`, parentID, ) if latestVersion { q1 = q1.Join( `(SELECT ar.artifact_id as id, ROW_NUMBER() OVER (PARTITION BY ar.artifact_image_id ORDER BY ar.artifact_updated_at DESC) AS rank FROM artifacts ar JOIN images i ON i.image_id = ar.artifact_image_id JOIN registries r ON i.image_registry_id = r.registry_id WHERE r.registry_parent_id = ? ) AS a ON ar.artifact_id = a.id`, parentID, // nolint:goconst ). Where("a.rank = 1") } if len(*registryIDs) > 0 { q1 = q1.Where(sq.Eq{"r.registry_name": registryIDs}) } if len(packageTypes) > 0 { q1 = q1.Where(sq.Eq{"r.registry_package_type": packageTypes}) } if search != "" { q1 = q1.Where("i.image_name LIKE ?", sqlPartialMatch(search)) } return q1 } func (t tagDao) CountAllOCIArtifactsByParentID( ctx context.Context, parentID int64, registryIDs *[]string, search string, latestVersion bool, packageTypes []string, ) (int64, error) { // nolint:goconst q := databaseg.Builder.Select("COUNT(*)"). From("tags t"). Join("registries r ON t.tag_registry_id = r.registry_id"). // nolint:goconst Where("r.registry_parent_id = ?", parentID). Join( "images ar ON ar.image_registry_id = t.tag_registry_id" + " AND ar.image_name = t.tag_image_name", ) if latestVersion { q = q.Join( `(SELECT t.tag_id as id, ROW_NUMBER() OVER (PARTITION BY t.tag_registry_id, t.tag_image_name ORDER BY t.tag_updated_at DESC) AS rank FROM tags t JOIN registries r ON t.tag_registry_id = r.registry_id WHERE r.registry_parent_id = ? ) AS a ON t.tag_id = a.id`, parentID, // nolint:goconst ).Where("a.rank = 1") } if len(*registryIDs) > 0 { q = q.Where(sq.Eq{"r.registry_name": registryIDs}) } if search != "" { q = q.Where("image_name LIKE ?", sqlPartialMatch(search)) } if len(packageTypes) > 0 { q = q.Where(sq.Eq{"registry_package_type": packageTypes}) } sql, args, err := q.ToSql() if err != nil { return -1, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, t.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (t tagDao) CountAllArtifactsByParentID( ctx context.Context, parentID int64, registryIDs *[]string, search string, latestVersion bool, packageTypes []string, untaggedImagesEnabled bool, ) (int64, error) { if untaggedImagesEnabled { // Use the new unified count function for all artifacts return t.CountAllArtifactsByParentIDUntagged(ctx, parentID, registryIDs, search, latestVersion, packageTypes) } q := databaseg.Builder.Select("COUNT(*)"). From("artifacts ar"). Join("images i ON i.image_id = ar.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). Where("r.registry_parent_id = ? AND r.registry_package_type NOT IN ('DOCKER', 'HELM')", parentID) if latestVersion { q = q.Join( `(SELECT ar.artifact_id as id, ROW_NUMBER() OVER (PARTITION BY ar.artifact_image_id ORDER BY ar.artifact_updated_at DESC) AS rank FROM artifacts ar JOIN images i ON i.image_id = ar.artifact_image_id JOIN registries r ON i.image_registry_id = r.registry_id WHERE r.registry_parent_id = ? ) AS a ON ar.artifact_id = a.id`, parentID, ).Where("a.rank = 1") } if len(*registryIDs) > 0 { q = q.Where(sq.Eq{"r.registry_name": registryIDs}) } if search != "" { q = q.Where("image_name LIKE ?", sqlPartialMatch(search)) } if len(packageTypes) > 0 { q = q.Where(sq.Eq{"registry_package_type": packageTypes}) } sql, args, err := q.ToSql() if err != nil { return -1, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, t.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } var ociCount int64 ociCount, err = t.CountAllOCIArtifactsByParentID(ctx, parentID, registryIDs, search, latestVersion, packageTypes) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count + ociCount, nil } func (t tagDao) CountAllArtifactsByParentIDUntagged( ctx context.Context, parentID int64, registryIDs *[]string, search string, _ bool, packageTypes []string, ) (int64, error) { query := databaseg.Builder.Select("COUNT(*)"). From("artifacts ar"). Join("images i ON i.image_id = ar.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). Where("r.registry_parent_id = ?", parentID) // Apply filters if len(*registryIDs) > 0 { query = query.Where(sq.Eq{"r.registry_name": registryIDs}) } if len(packageTypes) > 0 { query = query.Where(sq.Eq{"r.registry_package_type": packageTypes}) } if search != "" { query = query.Where("i.image_name LIKE ?", sqlPartialMatch(search)) } querySQL, queryArgs, err := query.ToSql() if err != nil { return 0, errors.Wrap(err, "Failed to convert count query to sql") } db := dbtx.GetAccessor(ctx, t.db) var count int64 if err := db.GetContext(ctx, &count, querySQL, queryArgs...); err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (t tagDao) GetTagDetail( ctx context.Context, repoID int64, imageName string, name string, ) (*types.TagDetail, error) { // Define subquery for download counts downloadCountSubquery := ` SELECT a.artifact_image_id, COUNT(d.download_stat_id) AS download_count, i.image_name, i.image_registry_id FROM artifacts a JOIN download_stats d ON d.download_stat_artifact_id = a.artifact_id JOIN images i ON i.image_id = a.artifact_image_id GROUP BY a.artifact_image_id, i.image_name, i.image_registry_id ` // Build main query q := databaseg.Builder. Select(` t.tag_id AS id, t.tag_name AS name, t.tag_image_name AS image_name, t.tag_created_at AS created_at, t.tag_updated_at AS updated_at, m.manifest_total_size AS size, COALESCE(dc.download_count, 0) AS download_count `). From("tags AS t"). Join("manifests AS m ON m.manifest_id = t.tag_manifest_id"). LeftJoin(fmt.Sprintf("(%s) AS dc ON t.tag_image_name = dc.image_name "+ "AND t.tag_registry_id = dc.image_registry_id", downloadCountSubquery)). Where( "t.tag_registry_id = ? AND t.tag_image_name = ? AND t.tag_name = ?", repoID, imageName, name, ) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, t.db) dst := new(tagDetailDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get tag detail") } return t.mapToTagDetail(ctx, dst) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
true
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/mediatype.go
registry/app/store/database/mediatype.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "time" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" errors2 "github.com/pkg/errors" ) type mediaTypesDao struct { db *sqlx.DB } type mediaTypeDB struct { ID int64 `db:"mt_id"` MediaType string `db:"mt_media_type"` CreatedAt int64 `db:"mt_created_at"` IsRunnable bool `db:"is_runnable"` } func NewMediaTypesDao(db *sqlx.DB) store.MediaTypesRepository { return &mediaTypesDao{ db: db, } } func (mt mediaTypesDao) MediaTypeExists(ctx context.Context, mediaType string) (bool, error) { stmt := database.Builder.Select("EXISTS (SELECT 1 FROM media_types WHERE mt_media_type = ?)") sql, args, err := stmt.ToSql() if err != nil { return false, errors2.Wrap(err, "Failed to convert query to sql") } args = append(args, mediaType) var exists bool db := dbtx.GetAccessor(ctx, mt.db) if err = db.GetContext(ctx, &exists, sql, args...); err != nil { return false, database.ProcessSQLErrorf(ctx, err, "Failed to check if media type exists") } return exists, nil } func (mt mediaTypesDao) GetMediaTypeByID( ctx context.Context, id int64, ) (*types.MediaType, error) { stmt := database.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(mediaTypeDB{}), ",")). From("media_types"). Where("mt_id = ?", id) sql, args, err := stmt.ToSql() if err != nil { return nil, errors2.Wrap(err, "Failed to convert query to sql") } dst := new(mediaTypeDB) db := dbtx.GetAccessor(ctx, mt.db) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find media type") } return mt.mapToMediaType(dst), nil } func (mt mediaTypesDao) mapToMediaType(dst *mediaTypeDB) *types.MediaType { return &types.MediaType{ ID: dst.ID, MediaType: dst.MediaType, CreatedAt: time.UnixMilli(dst.CreatedAt), IsRunnable: dst.IsRunnable, } } func (mt mediaTypesDao) MapMediaType(ctx context.Context, mediaType string) (int64, error) { stmt := database.Builder.Select("mt_id"). From("media_types"). Where("mt_media_type = ?", mediaType) db := dbtx.GetAccessor(ctx, mt.db) var id int64 sql, args, err := stmt.ToSql() if err != nil { return 0, errors2.Wrap(err, "Failed to convert query to sql") } if err = db.GetContext(ctx, &id, sql, args...); err != nil { return 0, database.ProcessSQLErrorf(ctx, err, "Failed to find repo") } return id, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/cleanup_policy.go
registry/app/store/database/cleanup_policy.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/common/lib/errors" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/types" "github.com/harness/gitness/registry/types/enum" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" "github.com/rs/zerolog/log" ) type CleanupPolicyDao struct { db *sqlx.DB tx dbtx.Transactor } type CleanupPolicyDB struct { ID int64 `db:"cp_id"` RegistryID int64 `db:"cp_registry_id"` Name string `db:"cp_name"` ExpiryTimeInMs int64 `db:"cp_expiry_time_ms"` CreatedAt int64 `db:"cp_created_at"` UpdatedAt int64 `db:"cp_updated_at"` CreatedBy int64 `db:"cp_created_by"` UpdatedBy int64 `db:"cp_updated_by"` } type CleanupPolicyPrefixMappingDB struct { PrefixID int64 `db:"cpp_id"` CleanupPolicyID int64 `db:"cpp_cleanup_policy_id"` Prefix string `db:"cpp_prefix"` PrefixType enum.PrefixType `db:"cpp_prefix_type"` } type CleanupPolicyJoinMapping struct { CleanupPolicyDB CleanupPolicyPrefixMappingDB } func NewCleanupPolicyDao(db *sqlx.DB, tx dbtx.Transactor) store.CleanupPolicyRepository { return &CleanupPolicyDao{ db: db, tx: tx, } } func (c CleanupPolicyDao) GetIDsByRegistryID(ctx context.Context, id int64) (ids []int64, err error) { stmt := databaseg.Builder.Select("cp_id").From("cleanup_policies"). Where("cp_registry_id = ?", id) db := dbtx.GetAccessor(ctx, c.db) var res []int64 query, args, err := stmt.ToSql() if err != nil { return nil, err } if err = db.SelectContext(ctx, &res, query, args...); err != nil { if !errors.Is(err, sql.ErrNoRows) { return nil, databaseg.ProcessSQLErrorf( ctx, err, "failed to get cleanup policy ids by registry id %d", id, ) } } return res, nil } func (c CleanupPolicyDao) GetByRegistryID( ctx context.Context, id int64, ) (cleanupPolicies *[]types.CleanupPolicy, err error) { stmt := databaseg.Builder.Select( "cp_id", "cp_registry_id", "cp_name", "cp_expiry_time_ms", "cp_created_at", "cp_updated_at", "cp_created_by", "cp_updated_by", "cpp_id", "cpp_cleanup_policy_id", "cpp_prefix", "cpp_prefix_type", ). From("cleanup_policies"). Join("cleanup_policy_prefix_mappings ON cp_id = cpp_cleanup_policy_id"). Where("cp_registry_id = ?", id) db := dbtx.GetAccessor(ctx, c.db) query, args, err := stmt.ToSql() if err != nil { return nil, err } rows, err := db.QueryxContext(ctx, query, args...) if err != nil { if !errors.Is(err, sql.ErrNoRows) { return nil, databaseg.ProcessSQLErrorf( ctx, err, "failed to get cleanup policy ids by registry id %d", id, ) } } defer func(rows *sqlx.Rows) { err := rows.Close() if err != nil { log.Ctx(ctx).Error().Msgf("failed to close rows: %v", err) } }(rows) return c.mapToCleanupPolicies(ctx, rows) } func (c CleanupPolicyDao) Create(ctx context.Context, cleanupPolicy *types.CleanupPolicy) (id int64, err error) { const sqlQuery = ` INSERT INTO cleanup_policies ( cp_registry_id ,cp_name ,cp_expiry_time_ms ,cp_created_at ,cp_updated_at ,cp_created_by ,cp_updated_by ) values ( :cp_registry_id ,:cp_name ,:cp_expiry_time_ms ,:cp_created_at ,:cp_updated_at ,:cp_created_by ,:cp_updated_by ) RETURNING cp_id` db := dbtx.GetAccessor(ctx, c.db) // insert repo first so we get id query, arg, err := db.BindNamed(sqlQuery, c.mapToInternalCleanupPolicy(ctx, cleanupPolicy)) if err != nil { return 0, databaseg.ProcessSQLErrorf( ctx, err, "Failed to bind cleanup policy object", ) } if err = db.QueryRowContext(ctx, query, arg...).Scan(&cleanupPolicy.ID); err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return cleanupPolicy.ID, nil } func (c CleanupPolicyDao) createPrefixMapping( ctx context.Context, mapping CleanupPolicyPrefixMappingDB, ) (id int64, err error) { const sqlQuery = ` INSERT INTO cleanup_policy_prefix_mappings ( cpp_cleanup_policy_id ,cpp_prefix ,cpp_prefix_type ) values ( :cpp_cleanup_policy_id ,:cpp_prefix ,:cpp_prefix_type ) RETURNING cpp_id` db := dbtx.GetAccessor(ctx, c.db) // insert repo first so we get id query, arg, err := db.BindNamed(sqlQuery, mapping) if err != nil { return 0, databaseg.ProcessSQLErrorf( ctx, err, "Failed to bind cleanup policy object", ) } if err = db.QueryRowContext(ctx, query, arg...).Scan(&mapping.PrefixID); err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return mapping.PrefixID, nil } // Delete deletes a cleanup policy by id // It doesn't cleanup the prefix mapping as they are removed by the database cascade. func (c CleanupPolicyDao) Delete(ctx context.Context, id int64) (err error) { stmt := databaseg.Builder.Delete("cleanup_policies").Where("cp_id = ?", id) query, args, err := stmt.ToSql() if err != nil { return err } db := dbtx.GetAccessor(ctx, c.db) _, err = db.ExecContext(ctx, query, args...) if err != nil { return databaseg.ProcessSQLErrorf( ctx, err, "failed to delete cleanup policy %d", id, ) } return nil } func (c CleanupPolicyDao) deleteCleanupPolicies(ctx context.Context, ids []int64) error { query, args, err := sqlx.In("DELETE FROM cleanup_policies WHERE cp_id IN (?)", ids) if err != nil { return err } query = c.db.Rebind(query) db := dbtx.GetAccessor(ctx, c.db) _, err = db.ExecContext(ctx, query, args...) if err != nil { return databaseg.ProcessSQLErrorf( ctx, err, "failed to delete cleanup policies %v", ids, ) } return nil } func (c CleanupPolicyDao) ModifyCleanupPolicies( ctx context.Context, cleanupPolicies *[]types.CleanupPolicy, ids []int64, ) error { err := c.tx.WithTx( ctx, func(ctx context.Context) error { if len(ids) > 0 { err := c.deleteCleanupPolicies(ctx, ids) if err != nil { return err } } if !commons.IsEmpty(cleanupPolicies) { for _, cp := range *cleanupPolicies { cpCopy := cp // Create a copy of cp to avoid implicit memory aliasing id, err := c.Create(ctx, &cpCopy) if err != nil { return err } cp.ID = id err2 := c.createPrefixMappingsInternal(ctx, cp) if err2 != nil { return err2 } } } return nil }, ) return err } func (c CleanupPolicyDao) createPrefixMappingsInternal( ctx context.Context, cp types.CleanupPolicy, ) error { mappings := c.mapToInternalCleanupPolicyMapping(&cp) for _, m := range *mappings { _, err := c.createPrefixMapping(ctx, m) if err != nil { return err } } return nil } func (c CleanupPolicyDao) mapToInternalCleanupPolicyMapping( cp *types.CleanupPolicy, ) *[]CleanupPolicyPrefixMappingDB { result := make([]CleanupPolicyPrefixMappingDB, 0) if !commons.IsEmpty(cp.PackagePrefix) { for _, prefix := range cp.PackagePrefix { result = append( result, CleanupPolicyPrefixMappingDB{ CleanupPolicyID: cp.ID, Prefix: prefix, PrefixType: enum.PrefixTypePackage, }, ) } } if !commons.IsEmpty(cp.VersionPrefix) { for _, prefix := range cp.VersionPrefix { result = append( result, CleanupPolicyPrefixMappingDB{ CleanupPolicyID: cp.ID, Prefix: prefix, PrefixType: enum.PrefixTypeVersion, }, ) } } return &result } func (c CleanupPolicyDao) mapToInternalCleanupPolicy( ctx context.Context, cp *types.CleanupPolicy, ) *CleanupPolicyDB { if cp.CreatedAt.IsZero() { cp.CreatedAt = time.Now() } cp.UpdatedAt = time.Now() session, _ := request.AuthSessionFrom(ctx) if cp.CreatedBy == 0 { cp.CreatedBy = session.Principal.ID } cp.UpdatedBy = session.Principal.ID return &CleanupPolicyDB{ ID: cp.ID, RegistryID: cp.RegistryID, Name: cp.Name, ExpiryTimeInMs: cp.ExpiryTime, CreatedAt: cp.CreatedAt.UnixMilli(), UpdatedAt: cp.UpdatedAt.UnixMilli(), CreatedBy: cp.CreatedBy, UpdatedBy: cp.UpdatedBy, } } func (c CleanupPolicyDao) mapToCleanupPolicies( _ context.Context, rows *sqlx.Rows, ) (*[]types.CleanupPolicy, error) { cleanupPolicies := make(map[int64]*types.CleanupPolicy) for rows.Next() { var cp CleanupPolicyJoinMapping if err := rows.StructScan(&cp); err != nil { return nil, errors.Wrap(err, "failed to scan cleanup policy") } if _, exists := cleanupPolicies[cp.ID]; !exists { cleanupPolicies[cp.ID] = &types.CleanupPolicy{ ID: cp.ID, RegistryID: cp.RegistryID, Name: cp.Name, ExpiryTime: cp.ExpiryTimeInMs, CreatedAt: time.UnixMilli(cp.CreatedAt), UpdatedAt: time.UnixMilli(cp.UpdatedAt), PackagePrefix: make([]string, 0), VersionPrefix: make([]string, 0), } } if cp.PrefixType == enum.PrefixTypePackage { cleanupPolicies[cp.ID].PackagePrefix = append(cleanupPolicies[cp.ID].PackagePrefix, cp.Prefix) } if cp.PrefixType == enum.PrefixTypeVersion { cleanupPolicies[cp.ID].VersionPrefix = append(cleanupPolicies[cp.ID].VersionPrefix, cp.Prefix) } } var result []types.CleanupPolicy for _, cp := range cleanupPolicies { result = append(result, *cp) } return &result, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/task.go
registry/app/store/database/task.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "encoding/json" "fmt" "time" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" ) var _ store.TaskRepository = (*taskStore)(nil) func NewTaskStore(db *sqlx.DB, tx dbtx.Transactor) store.TaskRepository { return &taskStore{ db: db, tx: tx, } } type taskStore struct { db *sqlx.DB tx dbtx.Transactor } // Find returns a task by its key. func (s *taskStore) Find(ctx context.Context, key string) (*types.Task, error) { stmt := databaseg.Builder. Select("registry_task_key", "registry_task_kind", "registry_task_payload", "registry_task_status", "registry_task_run_again", "registry_task_updated_at"). From("registry_tasks"). Where("registry_task_key = ?", key) query, args, err := stmt.ToSql() if err != nil { return nil, fmt.Errorf("failed to build query: %w", err) } taskDB := &TaskDB{} if err := s.db.GetContext(ctx, taskDB, query, args...); err != nil { return nil, fmt.Errorf("failed to find task with key %s: %w", key, err) } return taskDB.ToTask(), nil } func (s *taskStore) UpsertTask(ctx context.Context, task *types.Task) error { now := time.Now().UnixMilli() stmt := databaseg.Builder. Insert("registry_tasks"). Columns("registry_task_key", "registry_task_kind", "registry_task_payload", "registry_task_updated_at"). Values(task.Key, task.Kind, task.Payload, now). Suffix("ON CONFLICT (registry_task_key) DO UPDATE " + "SET registry_task_updated_at = EXCLUDED.registry_task_updated_at") query, args, err := stmt.ToSql() if err != nil { return fmt.Errorf("failed to build upsert query: %w", err) } _, err = s.db.ExecContext(ctx, query, args...) if err != nil { return fmt.Errorf("failed to upsert task with key %s: %w", task.Key, err) } return nil } func (s *taskStore) UpdateStatus(ctx context.Context, taskKey string, status types.TaskStatus) error { now := time.Now().UnixMilli() stmt := databaseg.Builder. Update("registry_tasks"). Set("registry_task_status", status). Set("registry_task_updated_at", now). Where("registry_task_key = ?", taskKey) query, args, err := stmt.ToSql() if err != nil { return fmt.Errorf("failed to build update status query: %w", err) } _, err = s.db.ExecContext(ctx, query, args...) return err } func (s *taskStore) SetRunAgain(ctx context.Context, taskKey string, runAgain bool) error { stmt := databaseg.Builder. Update("registry_tasks"). Set("registry_task_run_again", runAgain). Where("registry_task_key = ?", taskKey) query, args, err := stmt.ToSql() if err != nil { return fmt.Errorf("failed to build set run_again query: %w", err) } _, err = s.db.ExecContext(ctx, query, args...) return err } func (s *taskStore) LockForUpdate(ctx context.Context, task *types.Task) (types.TaskStatus, error) { stmt := databaseg.Builder. Select("registry_task_status"). From("registry_tasks"). Where("registry_task_key = ?", task.Key) if s.db.DriverName() != SQLITE3 { stmt = stmt.Suffix("FOR UPDATE") } query, args, err := stmt.ToSql() if err != nil { return "", fmt.Errorf("failed to build lock for update query: %w", err) } var result string err = s.db.QueryRowContext(ctx, query, args...).Scan(&result) if err != nil { return "", fmt.Errorf("failed to lock task with key %s: %w", task.Key, err) } return types.TaskStatus(result), nil } // CompleteTask updates the task status, output data and returns if it should run again. func (s *taskStore) CompleteTask( ctx context.Context, key string, status types.TaskStatus, ) (bool, error) { now := time.Now().UnixMilli() stmt := databaseg.Builder. Update("registry_tasks"). Set("registry_task_status", status). Set("registry_task_updated_at", now) stmt = stmt.Where("registry_task_key = ?", key). Suffix("RETURNING registry_task_run_again") query, args, err := stmt.ToSql() if err != nil { return false, fmt.Errorf("failed to build complete task query: %w", err) } var runAgain bool err = s.db.QueryRowContext(ctx, query, args...).Scan(&runAgain) if err != nil { return runAgain, fmt.Errorf("failed to complete task %s with status %s: %w", key, status, err) } return runAgain, nil } // ListPendingTasks lists tasks with pending status. func (s *taskStore) ListPendingTasks(ctx context.Context, limit int) ([]*types.Task, error) { stmt := databaseg.Builder. Select("registry_task_key", "registry_task_kind", "registry_task_payload", "registry_task_status", "registry_task_run_again", "registry_task_updated_at"). From("registry_tasks"). Where("registry_task_status = ?", string(types.TaskStatusPending)). OrderBy("registry_task_updated_at"). Limit(util.SafeIntToUInt64(limit)) query, args, err := stmt.ToSql() if err != nil { return nil, fmt.Errorf("failed to build list pending tasks query: %w", err) } var tasksDB []*TaskDB err = s.db.SelectContext(ctx, &tasksDB, query, args...) if err != nil { return nil, fmt.Errorf("failed to list pending tasks with limit %d: %w", limit, err) } tasks := make([]*types.Task, len(tasksDB)) for i, taskDB := range tasksDB { tasks[i] = taskDB.ToTask() } return tasks, nil } // TaskDB represents a database entity for task processing. type TaskDB struct { Key string `db:"registry_task_key"` Kind string `db:"registry_task_kind"` Payload json.RawMessage `db:"registry_task_payload"` Status string `db:"registry_task_status"` RunAgain bool `db:"registry_task_run_again"` UpdatedAt int64 `db:"registry_task_updated_at"` } // ToTask converts a database task entity to a DTO. func (t *TaskDB) ToTask() *types.Task { return &types.Task{ Key: t.Key, Kind: types.TaskKind(t.Kind), Payload: t.Payload, Status: types.TaskStatus(t.Status), RunAgain: t.RunAgain, UpdatedAt: time.UnixMilli(t.UpdatedAt), } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/layer.go
registry/app/store/database/layer.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "errors" "fmt" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" store2 "github.com/harness/gitness/store" "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" ) type layersDao struct { db *sqlx.DB mtRepository store.MediaTypesRepository } func NewLayersDao(db *sqlx.DB, mtRepository store.MediaTypesRepository) store.LayerRepository { return &layersDao{ db: db, mtRepository: mtRepository, } } type layersDB struct { ID int64 `db:"layer_id"` RegistryID int64 `db:"layer_registry_id"` ManifestID int64 `db:"layer_manifest_id"` MediaTypeID int64 `db:"layer_media_type_id"` BlobID int64 `db:"layer_blob_id"` Size int64 `db:"layer_size"` CreatedAt int64 `db:"layer_created_at"` UpdatedAt int64 `db:"layer_updated_at"` CreatedBy int64 `db:"layer_created_by"` UpdatedBy int64 `db:"layer_updated_by"` } func (l layersDao) AssociateLayerBlob( ctx context.Context, m *types.Manifest, b *types.Blob, ) error { const sqlQuery = ` INSERT INTO layers ( layer_registry_id ,layer_manifest_id ,layer_media_type_id ,layer_blob_id ,layer_size ,layer_created_at ,layer_updated_at ,layer_created_by ,layer_updated_by ) VALUES ( :layer_registry_id ,:layer_manifest_id ,:layer_media_type_id ,:layer_blob_id ,:layer_size ,:layer_created_at ,:layer_updated_at ,:layer_created_by ,:layer_updated_by ) ON CONFLICT (layer_registry_id, layer_manifest_id, layer_blob_id) DO UPDATE SET layer_registry_id = EXCLUDED.layer_registry_id RETURNING layer_id` mediaTypeID, err := l.mtRepository.MapMediaType(ctx, b.MediaType) if err != nil { return err } layer := &types.Layer{ RegistryID: m.RegistryID, ManifestID: m.ID, MediaTypeID: mediaTypeID, BlobID: b.ID, Size: b.Size, } db := dbtx.GetAccessor(ctx, l.db) query, arg, err := db.BindNamed(sqlQuery, l.mapToInternalLayer(ctx, layer)) if err != nil { return database.ProcessSQLErrorf(ctx, err, "Bind query failed") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&layer.ID); err != nil { err = database.ProcessSQLErrorf(ctx, err, "QueryRowContext failed") if errors.Is(err, store2.ErrDuplicate) { return nil } if errors.Is(err, store2.ErrForeignKeyViolation) { return util.ErrRefManifestNotFound } return fmt.Errorf("failed to associate layer blob: %w", err) } return nil } func (l layersDao) GetAllLayersByManifestID( ctx context.Context, manifestID int64, ) (*[]types.Layer, error) { stmt := database.Builder. Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(layersDB{}), ",")). From("layers"). Where("layer_manifest_id = ?", manifestID) toSQL, args, err := stmt.ToSql() if err != nil { return nil, fmt.Errorf("failed to convert layers query to sql: %w", err) } dst := []layersDB{} db := dbtx.GetAccessor(ctx, l.db) if err = db.SelectContext(ctx, &dst, toSQL, args...); err != nil { err := database.ProcessSQLErrorf(ctx, err, "Failed to find layers") return nil, err } layers := make([]types.Layer, len(dst)) for i := range dst { layer := l.mapToLayer(&dst[i]) layers[i] = *layer } return &layers, nil } func (l layersDao) mapToLayer(dst *layersDB) *types.Layer { return &types.Layer{ ID: dst.ID, RegistryID: dst.RegistryID, ManifestID: dst.ManifestID, MediaTypeID: dst.MediaTypeID, BlobID: dst.BlobID, Size: dst.Size, CreatedAt: time.UnixMilli(dst.CreatedAt), UpdatedAt: time.UnixMilli(dst.UpdatedAt), CreatedBy: dst.CreatedBy, UpdatedBy: dst.UpdatedBy, } } func (l layersDao) mapToInternalLayer(ctx context.Context, in *types.Layer) *layersDB { if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } in.UpdatedAt = time.Now() session, _ := request.AuthSessionFrom(ctx) if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } in.UpdatedBy = session.Principal.ID return &layersDB{ ID: in.ID, RegistryID: in.RegistryID, ManifestID: in.ManifestID, MediaTypeID: in.MediaTypeID, BlobID: in.BlobID, Size: in.Size, CreatedAt: in.CreatedAt.Unix(), UpdatedAt: in.UpdatedAt.Unix(), CreatedBy: in.CreatedBy, UpdatedBy: in.UpdatedBy, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/quarantine_artifact.go
registry/app/store/database/quarantine_artifact.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/pkg/errors" ) type QuarantineArtifactDao struct { db *sqlx.DB } func NewQuarantineArtifactDao(db *sqlx.DB) *QuarantineArtifactDao { return &QuarantineArtifactDao{ db: db, } } type QuarantineArtifactDB struct { ID string `db:"quarantined_path_id"` NodeID *string `db:"quarantined_path_node_id"` Reason string `db:"quarantined_path_reason"` RegistryID int64 `db:"quarantined_path_registry_id"` ImageID *int64 `db:"quarantined_path_image_id"` ArtifactID *int64 `db:"quarantined_path_artifact_id"` CreatedAt int64 `db:"quarantined_path_created_at"` CreatedBy int64 `db:"quarantined_path_created_by"` } func (q QuarantineArtifactDao) GetByFilePath(ctx context.Context, filePath string, registryID int64, artifact string, version string, artifactType *artifact.ArtifactType) ([]*types.QuarantineArtifact, error) { // First, get all quarantine artifacts for this registry stmtBuilder := databaseg.Builder. Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(QuarantineArtifactDB{}), ",")). From("quarantined_paths"). LeftJoin("artifacts as ar ON quarantined_path_artifact_id = ar.artifact_id"). LeftJoin("images as i ON quarantined_path_image_id = i.image_id"). LeftJoin("nodes as nd ON quarantined_path_node_id = nd.node_id"). Where("quarantined_path_registry_id = ? AND i.image_name = ?", registryID, artifact) // Add artifact type condition if provided if artifactType != nil { stmtBuilder = stmtBuilder.Where("i.image_type = ?", string(*artifactType)) } // Add version condition with proper parentheses for correct operator precedence stmtBuilder = stmtBuilder.Where( "(quarantined_path_artifact_id IS NULL OR "+ "ar.artifact_version = ?)", version) // Add filepath condition with proper parentheses for correct operator precedence stmtBuilder = stmtBuilder.Where( "(quarantined_path_node_id IS NULL OR "+ "nd.node_path = ?)", filePath) db := dbtx.GetAccessor(ctx, q.db) dst := []*QuarantineArtifactDB{} sqlQuery, args, err := stmtBuilder.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } if err := db.SelectContext(ctx, &dst, sqlQuery, args...); err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find quarantine artifacts with the provided criteria") } return q.mapToQuarantineArtifactList(ctx, dst) } func (q QuarantineArtifactDao) Create(ctx context.Context, artifact *types.QuarantineArtifact) error { const sqlQuery = ` INSERT INTO quarantined_paths ( quarantined_path_id, quarantined_path_node_id, quarantined_path_reason, quarantined_path_registry_id, quarantined_path_artifact_id, quarantined_path_image_id, quarantined_path_created_at, quarantined_path_created_by ) VALUES ( :quarantined_path_id, :quarantined_path_node_id, :quarantined_path_reason, :quarantined_path_registry_id, :quarantined_path_artifact_id, :quarantined_path_image_id, :quarantined_path_created_at, :quarantined_path_created_by ) ON CONFLICT (quarantined_path_node_id, quarantined_path_registry_id, quarantined_path_artifact_id, quarantined_path_image_id) DO NOTHING RETURNING quarantined_path_id` db := dbtx.GetAccessor(ctx, q.db) query, arg, err := db.BindNamed(sqlQuery, q.mapToInternalQuarantineArtifact(ctx, artifact)) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind quarantine artifact object") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&artifact.ID); err != nil && !errors.Is(err, sql.ErrNoRows) { return databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return nil } func (q QuarantineArtifactDao) mapToQuarantineArtifact(_ context.Context, dst *QuarantineArtifactDB) *types.QuarantineArtifact { var artifactID, imageID int64 var nodeID *string if dst.ArtifactID != nil { artifactID = *dst.ArtifactID } if dst.ImageID != nil { imageID = *dst.ImageID } if dst.NodeID != nil { nodeID = dst.NodeID } return &types.QuarantineArtifact{ ID: dst.ID, NodeID: nodeID, Reason: dst.Reason, RegistryID: dst.RegistryID, ArtifactID: artifactID, ImageID: imageID, CreatedAt: time.Unix(dst.CreatedAt, 0), CreatedBy: dst.CreatedBy, } } func (q QuarantineArtifactDao) mapToQuarantineArtifactList(ctx context.Context, dsts []*QuarantineArtifactDB) ([]*types.QuarantineArtifact, error) { result := make([]*types.QuarantineArtifact, 0, len(dsts)) for _, dst := range dsts { item := q.mapToQuarantineArtifact(ctx, dst) result = append(result, item) } return result, nil } func (q QuarantineArtifactDao) mapToInternalQuarantineArtifact(ctx context.Context, in *types.QuarantineArtifact) *QuarantineArtifactDB { session, _ := request.AuthSessionFrom(ctx) if in.ID == "" { in.ID = uuid.New().String() } if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } if in.CreatedBy == 0 && session != nil { in.CreatedBy = session.Principal.ID } var artifactIDPtr *int64 if in.ArtifactID != 0 { artifactID := in.ArtifactID artifactIDPtr = &artifactID } var imageIDPtr *int64 if in.ImageID != 0 { imageID := in.ImageID imageIDPtr = &imageID } return &QuarantineArtifactDB{ ID: in.ID, NodeID: in.NodeID, Reason: in.Reason, RegistryID: in.RegistryID, ArtifactID: artifactIDPtr, ImageID: imageIDPtr, CreatedAt: in.CreatedAt.Unix(), CreatedBy: in.CreatedBy, } } func (q QuarantineArtifactDao) DeleteByRegistryIDArtifactAndFilePath(ctx context.Context, registryID int64, artifactID *int64, imageID int64, nodeID *string) error { // Build the delete query stmtBuilder := databaseg.Builder. Delete("quarantined_paths"). Where("quarantined_path_registry_id = ?"+ " AND quarantined_path_image_id = ?", registryID, imageID) if artifactID != nil { stmtBuilder = stmtBuilder.Where("quarantined_path_artifact_id = ?", *artifactID) } if nodeID != nil { stmtBuilder = stmtBuilder.Where("quarantined_path_node_id = ?", *nodeID) } // Execute the query db := dbtx.GetAccessor(ctx, q.db) sql, args, err := stmtBuilder.ToSql() if err != nil { return errors.Wrap(err, "Failed to convert delete query to SQL") } _, err = db.ExecContext(ctx, sql, args...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Failed to delete quarantine artifact with the provided criteria") } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/manifest_reference.go
registry/app/store/database/manifest_reference.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "errors" "fmt" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" store2 "github.com/harness/gitness/store" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" ) type manifestReferenceDao struct { db *sqlx.DB } func NewManifestReferenceDao(db *sqlx.DB) store.ManifestReferenceRepository { return &manifestReferenceDao{ db: db, } } type manifestReferenceDB struct { ID int64 `db:"manifest_ref_id"` RegistryID int64 `db:"manifest_ref_registry_id"` ParentID int64 `db:"manifest_ref_parent_id"` ChildID int64 `db:"manifest_ref_child_id"` CreatedAt int64 `db:"manifest_ref_created_at"` UpdatedAt int64 `db:"manifest_ref_updated_at"` CreatedBy int64 `db:"manifest_ref_created_by"` UpdatedBy int64 `db:"manifest_ref_updated_by"` } func (dao manifestReferenceDao) AssociateManifest( ctx context.Context, ml *types.Manifest, m *types.Manifest, ) error { if ml.ID == m.ID { return fmt.Errorf("cannot associate a manifest with itself") } const sqlQuery = ` INSERT INTO manifest_references ( manifest_ref_registry_id ,manifest_ref_parent_id ,manifest_ref_child_id ,manifest_ref_created_at ,manifest_ref_updated_at ,manifest_ref_created_by ,manifest_ref_updated_by ) VALUES ( :manifest_ref_registry_id ,:manifest_ref_parent_id ,:manifest_ref_child_id ,:manifest_ref_created_at ,:manifest_ref_updated_at ,:manifest_ref_created_by ,:manifest_ref_updated_by ) ON CONFLICT (manifest_ref_registry_id, manifest_ref_parent_id, manifest_ref_child_id) DO NOTHING RETURNING manifest_ref_id` manifestRef := &types.ManifestReference{ RegistryID: ml.RegistryID, ParentID: ml.ID, ChildID: m.ID, } db := dbtx.GetAccessor(ctx, dao.db) query, arg, err := db.BindNamed(sqlQuery, mapToInternalManifestReference(ctx, manifestRef)) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "Bind query failed") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&manifestRef.ID); err != nil { err = databaseg.ProcessSQLErrorf(ctx, err, "QueryRowContext failed") if errors.Is(err, store2.ErrResourceNotFound) { return nil } if errors.Is(err, store2.ErrForeignKeyViolation) { return util.ErrRefManifestNotFound } return fmt.Errorf("inserting manifest reference: %w", err) } return nil } func (dao manifestReferenceDao) DissociateManifest( _ context.Context, _ *types.Manifest, _ *types.Manifest, ) error { // TODO implement me panic("implement me") } func mapToInternalManifestReference(ctx context.Context, in *types.ManifestReference) *manifestReferenceDB { if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } in.UpdatedAt = time.Now() session, _ := request.AuthSessionFrom(ctx) if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } in.UpdatedBy = session.Principal.ID return &manifestReferenceDB{ ID: in.ID, RegistryID: in.RegistryID, ParentID: in.ParentID, ChildID: in.ChildID, CreatedAt: in.CreatedAt.UnixMilli(), UpdatedAt: in.UpdatedAt.UnixMilli(), CreatedBy: in.CreatedBy, UpdatedBy: in.UpdatedBy, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/blob.go
registry/app/store/database/blob.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "fmt" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" "github.com/jmoiron/sqlx" "github.com/opencontainers/go-digest" errors2 "github.com/pkg/errors" ) type blobDao struct { db *sqlx.DB //FIXME: Arvind: Move this to controller layer later mtRepository store.MediaTypesRepository } func NewBlobDao(db *sqlx.DB, mtRepository store.MediaTypesRepository) store.BlobRepository { return &blobDao{ db: db, mtRepository: mtRepository, } } var ( PrimaryQuery = database.Builder.Select("blobs.blob_id as blob_id", "blob_media_type_id", "mt_media_type", "blob_digest", "blob_size", "blob_created_at", "blob_root_parent_id"). From("blobs"). Join("media_types ON mt_id = blobs.blob_media_type_id") ) type blobDB struct { ID int64 `db:"blob_id"` RootParentID int64 `db:"blob_root_parent_id"` Digest []byte `db:"blob_digest"` MediaTypeID int64 `db:"blob_media_type_id"` Size int64 `db:"blob_size"` CreatedAt int64 `db:"blob_created_at"` CreatedBy int64 `db:"blob_created_by"` } type blobMetadataDB struct { blobDB MediaType string `db:"mt_media_type"` } func (bd blobDao) FindByDigestAndRootParentID(ctx context.Context, d digest.Digest, rootParentID int64) (*types.Blob, error) { dgst, err := types.NewDigest(d) if err != nil { return nil, err } digestBytes, err := util.GetHexDecodedBytes(string(dgst)) if err != nil { return nil, err } stmt := PrimaryQuery. Where("blob_root_parent_id = ?", rootParentID). Where("blob_digest = ?", digestBytes) db := dbtx.GetAccessor(ctx, bd.db) dst := new(blobMetadataDB) sql, args, err := stmt.ToSql() if err != nil { return nil, errors2.Wrap(err, "Failed to convert query to sql") } if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find blob") } return bd.mapToBlob(dst) } func (bd blobDao) TotalSizeByRootParentID(ctx context.Context, rootID int64) (int64, error) { q := database.Builder.Select("COALESCE(SUM(blob_size), 0) AS size"). From("blobs"). Where("blob_root_parent_id = ?", rootID) db := dbtx.GetAccessor(ctx, bd.db) var size int64 sqlQuery, args, err := q.ToSql() if err != nil { return 0, errors2.Wrap(err, "Failed to convert query to sql") } if err = db.QueryRowContext(ctx, sqlQuery, args...).Scan(&size); err != nil && !errors2.Is(err, sql.ErrNoRows) { return 0, database.ProcessSQLErrorf(ctx, err, "Failed to find total blob size for root parent with id %d", rootID) } return size, nil } func (bd blobDao) FindByID(ctx context.Context, id int64) (*types.Blob, error) { stmt := PrimaryQuery. Where("blob_id = ?", id) db := dbtx.GetAccessor(ctx, bd.db) dst := new(blobMetadataDB) sql, args, err := stmt.ToSql() if err != nil { return nil, errors2.Wrap(err, "Failed to convert query to sql") } if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find blob") } return bd.mapToBlob(dst) } func (bd blobDao) FindByDigestAndRepoID(ctx context.Context, d digest.Digest, repoID int64, imageName string) (*types.Blob, error) { dgst, err := types.NewDigest(d) if err != nil { return nil, err } digestBytes, err := util.GetHexDecodedBytes(string(dgst)) if err != nil { return nil, err } stmt := PrimaryQuery. Join("registry_blobs ON rblob_blob_id = blobs.blob_id"). Where("rblob_registry_id = ?", repoID). Where("rblob_image_name = ?", imageName). Where("blob_digest = ?", digestBytes) db := dbtx.GetAccessor(ctx, bd.db) dst := new(blobMetadataDB) sql, args, err := stmt.ToSql() if err != nil { return nil, errors2.Wrap(err, "Failed to convert query to sql") } if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Failed to find blob") } return bd.mapToBlob(dst) } func (bd blobDao) CreateOrFind(ctx context.Context, b *types.Blob) (*types.Blob, bool, error) { sqlQuery := `INSERT INTO blobs ( blob_digest, blob_root_parent_id, blob_media_type_id, blob_size, blob_created_at, blob_created_by ) VALUES ( :blob_digest, :blob_root_parent_id, :blob_media_type_id, :blob_size, :blob_created_at, :blob_created_by ) ON CONFLICT ( blob_digest, blob_root_parent_id ) DO NOTHING RETURNING blob_id` mediaTypeID, err := bd.mtRepository.MapMediaType(ctx, b.MediaType) if err != nil { return nil, false, err } b.MediaTypeID = mediaTypeID db := dbtx.GetAccessor(ctx, bd.db) blob, err := mapToInternalBlob(ctx, b) if err != nil { return nil, false, err } query, arg, err := db.BindNamed(sqlQuery, blob) if err != nil { return nil, false, database.ProcessSQLErrorf(ctx, err, "Failed to bind repo object") } var created bool if err = db.QueryRowContext(ctx, query, arg...).Scan(&b.ID); err != nil { if errors2.Is(err, sql.ErrNoRows) { created = false } else { return nil, false, database.ProcessSQLErrorf(ctx, err, "Insert query failed") } } else { created = true } blob2, err := bd.FindByDigestAndRootParentID(ctx, b.Digest, b.RootParentID) return blob2, created, err } func (bd blobDao) DeleteByID(ctx context.Context, id int64) error { stmt := database.Builder.Delete("blobs"). Where("blob_id = ?", id) sql, args, err := stmt.ToSql() if err != nil { return fmt.Errorf("failed to convert purge blob query to sql: %w", err) } db := dbtx.GetAccessor(ctx, bd.db) _, err = db.ExecContext(ctx, sql, args...) if err != nil { return database.ProcessSQLErrorf(ctx, err, "the delete query failed") } return nil } func (bd blobDao) ExistsBlob(ctx context.Context, repoID int64, d digest.Digest, image string) (bool, error) { stmt := database.Builder.Select("EXISTS (SELECT 1 FROM registry_blobs " + "JOIN blobs as b ON rblob_blob_id = b.blob_id " + "WHERE rblob_registry_id = ? AND " + "rblob_image_name = ? AND " + "b.blob_digest = ?)") sql, args, err := stmt.ToSql() if err != nil { return false, fmt.Errorf("failed to convert exists blob query to sql: %w", err) } var exists bool db := dbtx.GetAccessor(ctx, bd.db) newDigest, err := types.NewDigest(d) if err != nil { return false, err } bytes, err := util.GetHexDecodedBytes(string(newDigest)) if err != nil { return false, err } args = append(args, repoID, image, bytes) if err = db.GetContext(ctx, &exists, sql, args...); err != nil { return false, database.ProcessSQLErrorf(ctx, err, "Failed to check exists blob") } return exists, nil } func mapToInternalBlob(ctx context.Context, in *types.Blob) (*blobDB, error) { session, _ := request.AuthSessionFrom(ctx) if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } in.CreatedBy = -1 newDigest, err := types.NewDigest(in.Digest) if err != nil { return nil, err } digestBytes, err := util.GetHexDecodedBytes(string(newDigest)) if err != nil { return nil, err } return &blobDB{ ID: in.ID, RootParentID: in.RootParentID, MediaTypeID: in.MediaTypeID, Digest: digestBytes, Size: in.Size, CreatedAt: in.CreatedAt.UnixMilli(), CreatedBy: in.CreatedBy, }, nil } func (bd blobDao) mapToBlob(dst *blobMetadataDB) (*types.Blob, error) { createdBy := int64(-1) dig := types.Digest(util.GetHexEncodedString(dst.Digest)) parsedDigest, err := dig.Parse() if err != nil { return nil, err } return &types.Blob{ ID: dst.ID, RootParentID: dst.RootParentID, MediaTypeID: dst.MediaTypeID, MediaType: dst.MediaType, Digest: parsedDigest, Size: dst.Size, CreatedAt: time.UnixMilli(dst.CreatedAt), CreatedBy: createdBy, }, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/artifact.go
registry/app/store/database/artifact.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "database/sql" "encoding/json" "fmt" "sort" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/database/util" "github.com/harness/gitness/registry/types" gitness_store "github.com/harness/gitness/store" databaseg "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" sq "github.com/Masterminds/squirrel" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/pkg/errors" "github.com/rs/zerolog/log" ) type ArtifactDao struct { db *sqlx.DB } func NewArtifactDao(db *sqlx.DB) store.ArtifactRepository { return &ArtifactDao{ db: db, } } type artifactDB struct { ID int64 `db:"artifact_id"` UUID string `db:"artifact_uuid"` Version string `db:"artifact_version"` ImageID int64 `db:"artifact_image_id"` Metadata *json.RawMessage `db:"artifact_metadata"` CreatedAt int64 `db:"artifact_created_at"` UpdatedAt int64 `db:"artifact_updated_at"` CreatedBy int64 `db:"artifact_created_by"` UpdatedBy int64 `db:"artifact_updated_by"` } func (a ArtifactDao) GetByUUID(ctx context.Context, uuid string) (*types.Artifact, error) { stmt := databaseg.Builder. Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(artifactDB{}), ",")). From("artifacts"). Where("artifact_uuid = ?", uuid) db := dbtx.GetAccessor(ctx, a.db) dst := new(artifactDB) sql, args, err := stmt.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to find artifact by uuid") } return a.mapToArtifact(ctx, dst) } func (a ArtifactDao) Get(ctx context.Context, id int64) (*types.Artifact, error) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(artifactDB{}), ",")). From("artifacts"). Where("artifact_id = ?", id) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := new(artifactDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact") } return a.mapToArtifact(ctx, dst) } func (a ArtifactDao) GetByName(ctx context.Context, imageID int64, version string) (*types.Artifact, error) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(artifactDB{}), ",")). From("artifacts"). Where("artifact_image_id = ? AND artifact_version = ?", imageID, version) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := new(artifactDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact") } return a.mapToArtifact(ctx, dst) } func (a ArtifactDao) GetByRegistryImageAndVersion( ctx context.Context, registryID int64, image string, version string, ) (*types.Artifact, error) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(artifactDB{}), ",")). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Where("i.image_registry_id = ?", registryID). Where("i.image_name = ?", image). Where("a.artifact_version = ?", version) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := new(artifactDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact") } return a.mapToArtifact(ctx, dst) } func (a ArtifactDao) GetByRegistryIDAndImage(ctx context.Context, registryID int64, image string) ( *[]types.Artifact, error, ) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(artifactDB{}), ",")). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Where("i.image_registry_id = ? AND i.image_name = ?", registryID, image). OrderBy("a.artifact_created_at DESC") sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := []artifactDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifacts") } artifacts := make([]types.Artifact, len(dst)) for i := range dst { d := dst[i] art, err := a.mapToArtifact(ctx, &d) if err != nil { return nil, errors.Wrap(err, "Failed to map artifact") } artifacts[i] = *art } return &artifacts, nil } func (a ArtifactDao) GetLatestByImageID(ctx context.Context, imageID int64) (*types.Artifact, error) { q := databaseg.Builder.Select(util.ArrToStringByDelimiter(util.GetDBTagsFromStruct(artifactDB{}), ",")). From("artifacts"). Where("artifact_image_id = ?", imageID).OrderBy("artifact_updated_at DESC").Limit(1) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := new(artifactDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact") } return a.mapToArtifact(ctx, dst) } func (a ArtifactDao) CreateOrUpdate(ctx context.Context, artifact *types.Artifact) (int64, error) { if commons.IsEmpty(artifact.Version) { return 0, errors.New("version is empty") } const sqlQuery = ` INSERT INTO artifacts ( artifact_image_id ,artifact_version ,artifact_created_at ,artifact_metadata ,artifact_updated_at ,artifact_created_by ,artifact_updated_by ,artifact_uuid ) VALUES ( :artifact_image_id ,:artifact_version ,:artifact_created_at ,:artifact_metadata ,:artifact_updated_at ,:artifact_created_by ,:artifact_updated_by ,:artifact_uuid ) ON CONFLICT (artifact_image_id, artifact_version) DO UPDATE SET artifact_metadata = :artifact_metadata RETURNING artifact_id` db := dbtx.GetAccessor(ctx, a.db) query, arg, err := db.BindNamed(sqlQuery, a.mapToInternalArtifact(ctx, artifact)) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed to bind artifact object") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&artifact.ID); err != nil && !errors.Is(err, sql.ErrNoRows) { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Insert query failed") } return artifact.ID, nil } func (a ArtifactDao) Count(ctx context.Context) (int64, error) { stmt := databaseg.Builder.Select("COUNT(*)"). From("artifacts") sql, args, err := stmt.ToSql() if err != nil { return 0, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (a ArtifactDao) DuplicateArtifact( ctx context.Context, sourceArtifact *types.Artifact, targetImageID int64, ) (*types.Artifact, error) { targetArtifact := &types.Artifact{ ImageID: targetImageID, Version: sourceArtifact.Version, Metadata: sourceArtifact.Metadata, } _, err := a.CreateOrUpdate(ctx, targetArtifact) if err != nil { return nil, errors.Wrap(err, "Failed to duplicate artifact") } return targetArtifact, nil } func (a ArtifactDao) DeleteByImageNameAndRegistryID(ctx context.Context, regID int64, image string) (err error) { var delStmt sq.DeleteBuilder switch a.db.DriverName() { case SQLITE3: delStmt = databaseg.Builder.Delete("artifacts"). Where("artifact_id IN (SELECT a.artifact_id FROM artifacts a JOIN images i ON i.image_id = a.artifact_image_id"+ " WHERE i.image_name = ? AND i.image_registry_id = ?)", image, regID) default: delStmt = databaseg.Builder.Delete("artifacts a USING images i"). Where("a.artifact_image_id = i.image_id"). Where("i.image_name = ? AND i.image_registry_id = ?", image, regID) } db := dbtx.GetAccessor(ctx, a.db) delQuery, delArgs, err := delStmt.ToSql() if err != nil { return fmt.Errorf("failed to convert delete query to sql: %w", err) } _, err = db.ExecContext(ctx, delQuery, delArgs...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed") } return nil } func (a ArtifactDao) DeleteByVersionAndImageName( ctx context.Context, image string, version string, regID int64, ) (err error) { var delStmt sq.DeleteBuilder switch a.db.DriverName() { case SQLITE3: delStmt = databaseg.Builder.Delete("artifacts"). Where("artifact_id IN (SELECT a.artifact_id FROM artifacts a JOIN images i ON i.image_id = a.artifact_image_id"+ " WHERE a.artifact_version = ? AND i.image_name = ? AND i.image_registry_id = ?)", version, image, regID) default: delStmt = databaseg.Builder.Delete("artifacts a USING images i"). Where("a.artifact_image_id = i.image_id"). Where("a.artifact_version = ? AND i.image_name = ? AND i.image_registry_id = ?", version, image, regID) } sql, args, err := delStmt.ToSql() if err != nil { return errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) _, err = db.ExecContext(ctx, sql, args...) if err != nil { return databaseg.ProcessSQLErrorf(ctx, err, "the delete query failed") } return nil } func (a ArtifactDao) mapToInternalArtifact(ctx context.Context, in *types.Artifact) *artifactDB { session, _ := request.AuthSessionFrom(ctx) if in.CreatedAt.IsZero() { in.CreatedAt = time.Now() } if in.CreatedBy == 0 { in.CreatedBy = session.Principal.ID } var metadata = json.RawMessage("null") if in.Metadata != nil { metadata = in.Metadata } in.UpdatedAt = time.Now() in.UpdatedBy = session.Principal.ID if in.UUID == "" { in.UUID = uuid.NewString() } return &artifactDB{ ID: in.ID, UUID: in.UUID, Version: in.Version, ImageID: in.ImageID, Metadata: &metadata, CreatedAt: in.CreatedAt.UnixMilli(), UpdatedAt: in.UpdatedAt.UnixMilli(), CreatedBy: in.CreatedBy, UpdatedBy: in.UpdatedBy, } } func (a ArtifactDao) mapToArtifact(_ context.Context, dst *artifactDB) (*types.Artifact, error) { createdBy := dst.CreatedBy updatedBy := dst.UpdatedBy var metadata json.RawMessage if dst.Metadata != nil { metadata = *dst.Metadata } return &types.Artifact{ ID: dst.ID, UUID: dst.UUID, Version: dst.Version, ImageID: dst.ImageID, Metadata: metadata, CreatedAt: time.UnixMilli(dst.CreatedAt), UpdatedAt: time.UnixMilli(dst.UpdatedAt), CreatedBy: createdBy, UpdatedBy: updatedBy, }, nil } func (a ArtifactDao) SearchLatestByName( ctx context.Context, regID int64, name string, limit int, offset int, ) (*[]types.Artifact, error) { subQuery := ` SELECT artifact_image_id, MAX(artifact_created_at) AS max_created_at FROM artifacts GROUP BY artifact_image_id` q := databaseg.Builder. Select("a.artifact_metadata,"+ "a.artifact_created_at"). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Join(fmt.Sprintf(`(%s) latest ON a.artifact_image_id = latest.artifact_image_id AND a.artifact_created_at = latest.max_created_at `, subQuery)). Where("i.image_name LIKE ? AND i.image_registry_id = ?", "%"+name+"%", regID). Limit(util.SafeIntToUInt64(limit)). Offset(util.SafeIntToUInt64(offset)) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to build SQL for latest artifact metadata with pagination") } db := dbtx.GetAccessor(ctx, a.db) var metadataList []*artifactDB if err := db.SelectContext(ctx, &metadataList, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact metadata") } artifactList, err := a.mapArtifactToArtifactMetadataList(ctx, metadataList) if err != nil { return nil, errors.Wrap(err, "Failed to map artifact metadata") } return artifactList, nil } func (a ArtifactDao) CountLatestByName( ctx context.Context, regID int64, name string, ) (int64, error) { subQuery := ` SELECT artifact_image_id, MAX(artifact_created_at) AS max_created_at FROM artifacts GROUP BY artifact_image_id` // Main count query q := databaseg.Builder. Select("COUNT(*)"). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Join(fmt.Sprintf(`(%s) latest ON a.artifact_image_id = latest.artifact_image_id AND a.artifact_created_at = latest.max_created_at `, subQuery)). Where("i.image_name LIKE ? AND i.image_registry_id = ?", "%"+name+"%", regID) sql, args, err := q.ToSql() if err != nil { return 0, errors.Wrap(err, "Failed to build count SQL") } db := dbtx.GetAccessor(ctx, a.db) var count int64 if err := db.GetContext(ctx, &count, sql, args...); err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed to count artifact metadata") } return count, nil } func (a ArtifactDao) SearchByImageName( ctx context.Context, regID int64, name string, limit int, offset int, ) (*[]types.ArtifactMetadata, error) { q := databaseg.Builder.Select( `i.image_name as name, a.artifact_id as artifact_id, a.artifact_version as version, a.artifact_metadata as metadata`, ). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Where("i.image_registry_id = ?", regID) if name != "" { q = q.Where("i.image_name LIKE ?", sqlPartialMatch(name)) } q = q.OrderBy("i.image_name ASC, a.artifact_version ASC"). Limit(util.SafeIntToUInt64(limit)). Offset(util.SafeIntToUInt64(offset)) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to build SQL for"+ " artifact metadata with pagination") } db := dbtx.GetAccessor(ctx, a.db) var dst []*artifactMetadataDB if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get artifact metadata") } return a.mapToArtifactMetadataList(dst) } func (a ArtifactDao) CountByImageName( ctx context.Context, regID int64, name string, ) (int64, error) { q := databaseg.Builder. Select("COUNT(*)"). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Where("i.image_registry_id = ?", regID) if name != "" { q = q.Where("i.image_name LIKE ?", sqlPartialMatch(name)) } sql, args, err := q.ToSql() if err != nil { return 0, errors.Wrap(err, "Failed to build count SQL") } db := dbtx.GetAccessor(ctx, a.db) var count int64 if err := db.GetContext(ctx, &count, sql, args...); err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed to count artifact metadata") } return count, nil } func (a ArtifactDao) GetAllArtifactsByParentID( ctx context.Context, parentID int64, registryIDs *[]string, sortByField string, sortByOrder string, limit int, offset int, search string, latestVersion bool, packageTypes []string, ) (*[]types.ArtifactMetadata, error) { q := databaseg.Builder.Select( `r.registry_name as repo_name, i.image_name as name, r.registry_package_type as package_type, a.artifact_version as version, a.artifact_updated_at as modified_at, i.image_labels as labels, a.artifact_metadata as metadata, COALESCE(t2.download_count,0) as download_count `, ). From("artifacts a"). Join("images i ON a.artifact_image_id = i.image_id"). Join("registries r ON r.registry_id = i.image_registry_id"). Where("r.registry_parent_id = ?", parentID). LeftJoin( `( SELECT i.image_name, SUM(COALESCE(t1.download_count, 0)) as download_count FROM ( SELECT a.artifact_image_id, COUNT(d.download_stat_id) as download_count FROM artifacts a JOIN download_stats d ON d.download_stat_artifact_id = a.artifact_id GROUP BY a.artifact_image_id ) as t1 JOIN images i ON i.image_id = t1.artifact_image_id JOIN registries r ON r.registry_id = i.image_registry_id WHERE r.registry_parent_id = ? GROUP BY i.image_name) as t2 ON i.image_name = t2.image_name`, parentID, ) if latestVersion { q = q.Join( `(SELECT t.artifact_id as id, ROW_NUMBER() OVER (PARTITION BY t.artifact_image_id ORDER BY t.artifact_updated_at DESC) AS rank FROM artifacts t JOIN images i ON t.artifact_image_id = i.image_id JOIN registries r ON i.image_registry_id = r.registry_id WHERE r.registry_parent_id = ? ) AS a1 ON a.artifact_id = a1.id`, parentID, // nolint:goconst ). Where("a1.rank = 1") } if len(*registryIDs) > 0 { q = q.Where(sq.Eq{"r.registry_name": registryIDs}) } if len(packageTypes) > 0 { q = q.Where(sq.Eq{"r.registry_package_type": packageTypes}) } if search != "" { q = q.Where("i.image_name LIKE ?", sqlPartialMatch(search)) } sortField := "i." + sortByField if sortByField == downloadCount { sortField = downloadCount } q = q.OrderBy(sortField + " " + sortByOrder).Limit(util.SafeIntToUInt64(limit)).Offset(util.SafeIntToUInt64(offset)) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := []*artifactMetadataDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing custom list query") } return a.mapToArtifactMetadataList(dst) } func (a ArtifactDao) CountAllArtifactsByParentID( ctx context.Context, parentID int64, registryIDs *[]string, search string, latestVersion bool, packageTypes []string, ) (int64, error) { // nolint:goconst q := databaseg.Builder.Select("COUNT(*)"). From("artifacts a"). Join("images i ON i.image_id = a.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). // nolint:goconst Where("r.registry_parent_id = ?", parentID) if latestVersion { q = q.Join( `(SELECT t.artifact_id as id, ROW_NUMBER() OVER (PARTITION BY t.artifact_image_id ORDER BY t.artifact_updated_at DESC) AS rank FROM artifacts t JOIN images i ON t.artifact_image_id = i.image_id JOIN registries r ON i.image_registry_id = r.registry_id WHERE r.registry_parent_id = ? ) AS a1 ON a.artifact_id = a1.id`, parentID, // nolint:goconst ). Where("a1.rank = 1") } if len(*registryIDs) > 0 { q = q.Where(sq.Eq{"r.registry_name": registryIDs}) } if search != "" { q = q.Where("image_name LIKE ?", sqlPartialMatch(search)) } if len(packageTypes) > 0 { q = q.Where(sq.Eq{"registry_package_type": packageTypes}) } sql, args, err := q.ToSql() if err != nil { return -1, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (a ArtifactDao) GetArtifactsByRepo( ctx context.Context, parentID int64, repoKey string, sortByField string, sortByOrder string, limit int, offset int, search string, labels []string, artifactType *artifact.ArtifactType, ) (*[]types.ArtifactMetadata, error) { q := databaseg.Builder.Select( `r.registry_name as repo_name, i.image_name as name, i.image_uuid as uuid, r.registry_uuid as registry_uuid, r.registry_package_type as package_type, a.artifact_version as latest_version, a.artifact_updated_at as modified_at, i.image_labels as labels, i.image_type as artifact_type, COALESCE(t2.download_count, 0) as download_count`, ). From("artifacts a"). Join( `(SELECT a.artifact_id as id, ROW_NUMBER() OVER (PARTITION BY a.artifact_image_id ORDER BY a.artifact_updated_at DESC) AS rank FROM artifacts a JOIN images i ON i.image_id = a.artifact_image_id JOIN registries r ON i.image_registry_id = r.registry_id WHERE r.registry_parent_id = ? AND r.registry_name = ? ) AS a1 ON a.artifact_id = a1.id`, parentID, repoKey, // nolint:goconst ). Join("images i ON i.image_id = a.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). LeftJoin( `( SELECT i.image_name, SUM(COALESCE(t1.download_count, 0)) as download_count FROM ( SELECT a.artifact_image_id, COUNT(d.download_stat_id) as download_count FROM artifacts a JOIN download_stats d ON d.download_stat_artifact_id = a.artifact_id GROUP BY a.artifact_image_id ) as t1 JOIN images i ON i.image_id = t1.artifact_image_id JOIN registries r ON r.registry_id = i.image_registry_id WHERE r.registry_parent_id = ? AND r.registry_name = ? GROUP BY i.image_name) as t2 ON i.image_name = t2.image_name`, parentID, repoKey, ). Where("a1.rank = 1 ") if search != "" { q = q.Where("i.image_name LIKE ?", sqlPartialMatch(search)) } if artifactType != nil && *artifactType != "" { q = q.Where("i.image_type = ?", *artifactType) } if len(labels) > 0 { sort.Strings(labels) labelsVal := util.GetEmptySQLString(util.ArrToString(labels)) labelsVal.String = labelSeparatorStart + labelsVal.String + labelSeparatorEnd q = q.Where("'^_' || i.image_labels || '^_' LIKE ?", labelsVal) } // nolint:goconst sortField := "image_" + sortByField switch sortByField { case downloadCount: sortField = downloadCount case imageName: sortField = name } q = q.OrderBy(sortField + " " + sortByOrder).Limit(util.SafeIntToUInt64(limit)).Offset(util.SafeIntToUInt64(offset)) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := []*artifactMetadataDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing custom list query") } return a.mapToArtifactMetadataList(dst) } // nolint:goconst func (a ArtifactDao) CountArtifactsByRepo( ctx context.Context, parentID int64, repoKey, search string, labels []string, artifactType *artifact.ArtifactType, ) (int64, error) { q := databaseg.Builder.Select("COUNT(*)"). From("artifacts a"). Join( "images i ON i.image_id = a.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). Where("r.registry_parent_id = ? AND r.registry_name = ?", parentID, repoKey) if search != "" { q = q.Where("i.image_name LIKE ?", sqlPartialMatch(search)) } if artifactType != nil && *artifactType != "" { q = q.Where("i.image_type = ?", *artifactType) } if len(labels) > 0 { sort.Strings(labels) labelsVal := util.GetEmptySQLString(util.ArrToString(labels)) labelsVal.String = labelSeparatorStart + labelsVal.String + labelSeparatorEnd q = q.Where("'^_' || i.image_labels || '^_' LIKE ?", labelsVal) } sql, args, err := q.ToSql() if err != nil { return -1, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) var count int64 err = db.QueryRowContext(ctx, sql, args...).Scan(&count) if err != nil { return 0, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing count query") } return count, nil } func (a ArtifactDao) GetLatestArtifactMetadata( ctx context.Context, parentID int64, repoKey string, imageName string, ) (*types.ArtifactMetadata, error) { // Precomputed download count subquery downloadCountSubquery := ` SELECT i.image_name, i.image_registry_id, SUM(COALESCE(dc.download_count, 0)) AS download_count FROM images i LEFT JOIN ( SELECT a.artifact_image_id, COUNT(d.download_stat_id) AS download_count FROM artifacts a JOIN download_stats d ON d.download_stat_artifact_id = a.artifact_id GROUP BY a.artifact_image_id ) AS dc ON i.image_id = dc.artifact_image_id GROUP BY i.image_name, i.image_registry_id ` var q sq.SelectBuilder if a.db.DriverName() == SQLITE3 { q = databaseg.Builder.Select( `r.registry_name AS repo_name, r.registry_package_type AS package_type, i.image_name AS name, a.artifact_version AS latest_version, a.artifact_created_at AS created_at, a.artifact_updated_at AS modified_at, i.image_labels AS labels, COALESCE(dc_subquery.download_count, 0) AS download_count`, ). From("artifacts a"). Join("images i ON i.image_id = a.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). // nolint:goconst LeftJoin(fmt.Sprintf("(%s) AS dc_subquery ON dc_subquery.image_name = i.image_name "+ "AND dc_subquery.image_registry_id = r.registry_id", downloadCountSubquery)). Where( "r.registry_parent_id = ? AND r.registry_name = ? AND i.image_name = ?", parentID, repoKey, imageName, ). OrderBy("a.artifact_updated_at DESC").Limit(1) } else { q = databaseg.Builder.Select( `r.registry_name AS repo_name, r.registry_package_type AS package_type, i.image_name AS name, a.artifact_version AS latest_version, a.artifact_created_at AS created_at, a.artifact_updated_at AS modified_at, i.image_labels AS labels, COALESCE(t2.download_count, 0) AS download_count`, ). From("artifacts a"). Join("images i ON i.image_id = a.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). // nolint:goconst LeftJoin(fmt.Sprintf("LATERAL (%s) AS t2 ON i.image_name = t2.image_name", downloadCountSubquery)). Where( "r.registry_parent_id = ? AND r.registry_name = ? AND i.image_name = ?", parentID, repoKey, imageName, ). OrderBy("a.artifact_updated_at DESC").Limit(1) } sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } // Log the final sql query finalQuery := util.FormatQuery(sql, args) log.Ctx(ctx).Debug().Str("sql", finalQuery).Msg("Executing GetLatestTagMetadata query") // Execute query db := dbtx.GetAccessor(ctx, a.db) dst := new(artifactMetadataDB) if err = db.GetContext(ctx, dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to get tag detail") } return a.mapToArtifactMetadata(dst) } func (a ArtifactDao) mapArtifactToArtifactMetadataList( ctx context.Context, dst []*artifactDB, ) (*[]types.Artifact, error) { artifacts := make([]types.Artifact, 0, len(dst)) for _, d := range dst { artifact, err := a.mapToArtifact(ctx, d) if err != nil { return nil, err } artifacts = append(artifacts, *artifact) } return &artifacts, nil } func (a ArtifactDao) mapToArtifactMetadataList( dst []*artifactMetadataDB, ) (*[]types.ArtifactMetadata, error) { artifacts := make([]types.ArtifactMetadata, 0, len(dst)) for _, d := range dst { artifact, err := a.mapToArtifactMetadata(d) if err != nil { return nil, err } artifacts = append(artifacts, *artifact) } return &artifacts, nil } func (a ArtifactDao) GetAllVersionsByRepoAndImage( ctx context.Context, regID int64, image string, sortByField string, sortByOrder string, limit int, offset int, search string, artifactType *artifact.ArtifactType, ) (*[]types.NonOCIArtifactMetadata, error) { // Build the main query q := databaseg.Builder. Select(` a.artifact_id as id, a.artifact_uuid as uuid, a.artifact_version AS name, a.artifact_metadata ->> 'size' AS size, a.artifact_metadata ->> 'file_count' AS file_count, a.artifact_updated_at AS modified_at, (qp.quarantined_path_id IS NOT NULL) AS is_quarantined, qp.quarantined_path_reason as quarantine_reason, i.image_type as artifact_type`, ) if a.db.DriverName() == SQLITE3 { q = databaseg.Builder.Select(` a.artifact_id as id, a.artifact_uuid as uuid, a.artifact_version AS name, json_extract(a.artifact_metadata, '$.size') AS size, json_extract(a.artifact_metadata, '$.file_count') AS file_count, a.artifact_updated_at AS modified_at, (qp.quarantined_path_id IS NOT NULL) AS is_quarantined, qp.quarantined_path_reason as quarantine_reason, i.image_type as artifact_type`, ) } q = q.From("artifacts a"). Join("images i ON i.image_id = a.artifact_image_id"). LeftJoin("quarantined_paths qp ON ((qp.quarantined_path_artifact_id = a.artifact_id "+ "OR qp.quarantined_path_artifact_id IS NULL) "+ "AND qp.quarantined_path_image_id = i.image_id) AND qp.quarantined_path_registry_id = ?", regID). Where( " i.image_registry_id = ? AND i.image_name = ?", regID, image, ) if artifactType != nil && *artifactType != "" { q = q.Where("i.image_type = ?", *artifactType) } if search != "" { q = q.Where("artifact_version LIKE ?", sqlPartialMatch(search)) } // nolint:goconst sortField := "artifact_" + sortByField if sortByField == name || sortByField == downloadCount { sortField = name } q = q.OrderBy(sortField + " " + sortByOrder).Limit(util.SafeIntToUInt64(limit)).Offset(util.SafeIntToUInt64(offset)) sql, args, err := q.ToSql() if err != nil { return nil, errors.Wrap(err, "Failed to convert query to sql") } db := dbtx.GetAccessor(ctx, a.db) dst := []*nonOCIArtifactMetadataDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed executing custom list query") } artifactIDs := make([]any, 0, len(dst)) for _, art := range dst { artifactIDs = append(artifactIDs, art.ID) } err = a.fetchDownloadStatsForArtifacts(ctx, artifactIDs, dst, sortByField == downloadCount, sortByOrder) if err != nil { return nil, databaseg.ProcessSQLErrorf(ctx, err, "Failed to fetch the download count for artifacts") } return a.mapToNonOCIMetadataList(dst) } func (a ArtifactDao) fetchDownloadStatsForArtifacts( ctx context.Context, artifactIDs []any, dst []*nonOCIArtifactMetadataDB, sortByDownloadCount bool, sortOrder string, ) error { if len(artifactIDs) == 0 { return nil } query, args, err := databaseg.Builder. Select("download_stat_artifact_id", "COUNT(*) AS download_count"). From("download_stats"). Where(sq.Eq{"download_stat_artifact_id": artifactIDs}). GroupBy("download_stat_artifact_id"). ToSql() if err != nil { return errors.Wrap(err, "building download stats query") } results := []downloadCountResult{} if err := a.db.SelectContext(ctx, &results, query, args...); err != nil { return errors.Wrap(err, "executing download stats query") } // Map artifact ID -> count countMap := make(map[string]int64, len(results)) for _, r := range results { countMap[r.ArtifactID] = r.DownloadCount } // Update download counts in dst for _, artifact := range dst { if count, ok := countMap[artifact.ID]; ok { artifact.DownloadCount = count } else { artifact.DownloadCount = 0 } } if sortByDownloadCount { sort.Slice(dst, func(i, j int) bool { if sortOrder == "DESC" { return dst[i].DownloadCount > dst[j].DownloadCount } return dst[i].DownloadCount < dst[j].DownloadCount }) } return nil } func (a ArtifactDao) CountAllVersionsByRepoAndImage( ctx context.Context, parentID int64, repoKey string, image string, search string, artifactType *artifact.ArtifactType, ) (int64, error) { stmt := databaseg.Builder.Select("COUNT(*)"). From("artifacts a"). Join("images i ON i.image_id = a.artifact_image_id"). Join("registries r ON i.image_registry_id = r.registry_id"). Where( "r.registry_parent_id = ? AND r.registry_name = ? "+ "AND i.image_name = ?", parentID, repoKey, image, ) if artifactType != nil && *artifactType != "" { stmt = stmt.Where("i.image_type = ?", *artifactType) } if search != "" { stmt = stmt.Where("artifact_version LIKE ?", sqlPartialMatch(search)) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
true
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/webhookexecution.go
registry/app/store/database/webhookexecution.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package database import ( "context" "fmt" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database" "github.com/harness/gitness/store/database/dbtx" gitnesstypes "github.com/harness/gitness/types" "github.com/harness/gitness/types/enum" "github.com/guregu/null" "github.com/jmoiron/sqlx" ) type WebhookExecutionDao struct { db *sqlx.DB } const ( webhookExecutionColumns = ` registry_webhook_execution_id ,registry_webhook_execution_retrigger_of ,registry_webhook_execution_retriggerable ,registry_webhook_execution_webhook_id ,registry_webhook_execution_trigger_type ,registry_webhook_execution_trigger_id ,registry_webhook_execution_result ,registry_webhook_execution_created ,registry_webhook_execution_duration ,registry_webhook_execution_error ,registry_webhook_execution_request_url ,registry_webhook_execution_request_headers ,registry_webhook_execution_request_body ,registry_webhook_execution_response_status_code ,registry_webhook_execution_response_status ,registry_webhook_execution_response_headers ,registry_webhook_execution_response_body` webhookExecutionSelectBase = ` SELECT` + webhookExecutionColumns + ` FROM registry_webhook_executions` ) func (w WebhookExecutionDao) Find(ctx context.Context, id int64) (*gitnesstypes.WebhookExecutionCore, error) { const sqlQuery = webhookExecutionSelectBase + ` WHERE registry_webhook_execution_id = $1` db := dbtx.GetAccessor(ctx, w.db) dst := &webhookExecutionDB{} if err := db.GetContext(ctx, dst, sqlQuery, id); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Select query failed") } return mapToWebhookExecution(dst), nil } func (w WebhookExecutionDao) Create(ctx context.Context, webhookExecution *gitnesstypes.WebhookExecutionCore) error { const sqlQuery = ` INSERT INTO registry_webhook_executions ( registry_webhook_execution_retrigger_of ,registry_webhook_execution_retriggerable ,registry_webhook_execution_webhook_id ,registry_webhook_execution_trigger_type ,registry_webhook_execution_trigger_id ,registry_webhook_execution_result ,registry_webhook_execution_created ,registry_webhook_execution_duration ,registry_webhook_execution_error ,registry_webhook_execution_request_url ,registry_webhook_execution_request_headers ,registry_webhook_execution_request_body ,registry_webhook_execution_response_status_code ,registry_webhook_execution_response_status ,registry_webhook_execution_response_headers ,registry_webhook_execution_response_body ) values ( :registry_webhook_execution_retrigger_of ,:registry_webhook_execution_retriggerable ,:registry_webhook_execution_webhook_id ,:registry_webhook_execution_trigger_type ,:registry_webhook_execution_trigger_id ,:registry_webhook_execution_result ,:registry_webhook_execution_created ,:registry_webhook_execution_duration ,:registry_webhook_execution_error ,:registry_webhook_execution_request_url ,:registry_webhook_execution_request_headers ,:registry_webhook_execution_request_body ,:registry_webhook_execution_response_status_code ,:registry_webhook_execution_response_status ,:registry_webhook_execution_response_headers ,:registry_webhook_execution_response_body ) RETURNING registry_webhook_execution_id` db := dbtx.GetAccessor(ctx, w.db) dbwebhookExecution := mapToWebhookExecutionDB(webhookExecution) query, arg, err := db.BindNamed(sqlQuery, dbwebhookExecution) if err != nil { return database.ProcessSQLErrorf(ctx, err, "Failed to registry bind webhook object") } if err = db.QueryRowContext(ctx, query, arg...).Scan(&dbwebhookExecution.ID); err != nil { return database.ProcessSQLErrorf(ctx, err, "Insert query failed") } return nil } func (w WebhookExecutionDao) ListForWebhook( ctx context.Context, webhookID int64, limit int, page int, size int, ) ([]*gitnesstypes.WebhookExecutionCore, error) { stmt := database.Builder. Select(webhookExecutionColumns). From("registry_webhook_executions"). Where("registry_webhook_execution_webhook_id = ?", webhookID) stmt = stmt.Limit(database.Limit(limit)) stmt = stmt.Offset(database.Offset(page, size)) // fixed ordering by desc id (new ones first) - add customized ordering if deemed necessary. stmt = stmt.OrderBy("registry_webhook_execution_id DESC") sql, args, err := stmt.ToSql() if err != nil { return nil, fmt.Errorf("failed to convert query to sql: %w", err) } db := dbtx.GetAccessor(ctx, w.db) dst := []*webhookExecutionDB{} if err = db.SelectContext(ctx, &dst, sql, args...); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Select query failed") } return mapToWebhookExecutions(dst), nil } func (w WebhookExecutionDao) CountForWebhook(ctx context.Context, webhookID int64) (int64, error) { stmt := database.Builder. Select("COUNT(*)"). From("registry_webhook_executions"). Where("registry_webhook_execution_webhook_id = ?", webhookID) sql, args, err := stmt.ToSql() if err != nil { return 0, fmt.Errorf("failed to convert query to sql: %w", err) } db := dbtx.GetAccessor(ctx, w.db) var count int64 if err = db.GetContext(ctx, &count, sql, args...); err != nil { return 0, database.ProcessSQLErrorf(ctx, err, "Count query failed") } return count, nil } func (w WebhookExecutionDao) ListForTrigger( ctx context.Context, triggerID string, ) ([]*gitnesstypes.WebhookExecutionCore, error) { const sqlQuery = webhookExecutionSelectBase + ` WHERE registry_webhook_execution_trigger_id = $1` db := dbtx.GetAccessor(ctx, w.db) dst := []*webhookExecutionDB{} if err := db.SelectContext(ctx, &dst, sqlQuery, triggerID); err != nil { return nil, database.ProcessSQLErrorf(ctx, err, "Select query failed") } return mapToWebhookExecutions(dst), nil } func NewWebhookExecutionDao(db *sqlx.DB) store.WebhooksExecutionRepository { return &WebhookExecutionDao{ db: db, } } type webhookExecutionDB struct { ID int64 `db:"registry_webhook_execution_id"` RetriggerOf null.Int `db:"registry_webhook_execution_retrigger_of"` Retriggerable bool `db:"registry_webhook_execution_retriggerable"` WebhookID int64 `db:"registry_webhook_execution_webhook_id"` TriggerType enum.WebhookTrigger `db:"registry_webhook_execution_trigger_type"` TriggerID string `db:"registry_webhook_execution_trigger_id"` Result enum.WebhookExecutionResult `db:"registry_webhook_execution_result"` Created int64 `db:"registry_webhook_execution_created"` Duration int64 `db:"registry_webhook_execution_duration"` Error string `db:"registry_webhook_execution_error"` RequestURL string `db:"registry_webhook_execution_request_url"` RequestHeaders string `db:"registry_webhook_execution_request_headers"` RequestBody string `db:"registry_webhook_execution_request_body"` ResponseStatusCode int `db:"registry_webhook_execution_response_status_code"` ResponseStatus string `db:"registry_webhook_execution_response_status"` ResponseHeaders string `db:"registry_webhook_execution_response_headers"` ResponseBody string `db:"registry_webhook_execution_response_body"` } func mapToWebhookExecution(webhookExecutionDB *webhookExecutionDB) *gitnesstypes.WebhookExecutionCore { webhookExecution := &gitnesstypes.WebhookExecutionCore{ ID: webhookExecutionDB.ID, RetriggerOf: webhookExecutionDB.RetriggerOf.Ptr(), Retriggerable: webhookExecutionDB.Retriggerable, WebhookID: webhookExecutionDB.WebhookID, TriggerType: webhookExecutionDB.TriggerType, TriggerID: webhookExecutionDB.TriggerID, Result: webhookExecutionDB.Result, Created: webhookExecutionDB.Created, Duration: webhookExecutionDB.Duration, Error: webhookExecutionDB.Error, Request: gitnesstypes.WebhookExecutionRequest{ URL: webhookExecutionDB.RequestURL, Headers: webhookExecutionDB.RequestHeaders, Body: webhookExecutionDB.RequestBody, }, Response: gitnesstypes.WebhookExecutionResponse{ StatusCode: webhookExecutionDB.ResponseStatusCode, Status: webhookExecutionDB.ResponseStatus, Headers: webhookExecutionDB.ResponseHeaders, Body: webhookExecutionDB.ResponseBody, }, } return webhookExecution } func mapToWebhookExecutionDB(webhookExecution *gitnesstypes.WebhookExecutionCore) *webhookExecutionDB { webhookExecutionDD := &webhookExecutionDB{ ID: webhookExecution.ID, RetriggerOf: null.IntFromPtr(webhookExecution.RetriggerOf), Retriggerable: webhookExecution.Retriggerable, WebhookID: webhookExecution.WebhookID, TriggerType: webhookExecution.TriggerType, TriggerID: webhookExecution.TriggerID, Result: webhookExecution.Result, Created: webhookExecution.Created, Duration: webhookExecution.Duration, Error: webhookExecution.Error, RequestURL: webhookExecution.Request.URL, RequestHeaders: webhookExecution.Request.Headers, RequestBody: webhookExecution.Request.Body, ResponseStatusCode: webhookExecution.Response.StatusCode, ResponseStatus: webhookExecution.Response.Status, ResponseHeaders: webhookExecution.Response.Headers, ResponseBody: webhookExecution.Response.Body, } return webhookExecutionDD } func mapToWebhookExecutions(executions []*webhookExecutionDB) []*gitnesstypes.WebhookExecutionCore { m := make([]*gitnesstypes.WebhookExecutionCore, len(executions)) for i, hook := range executions { m[i] = mapToWebhookExecution(hook) } return m }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/util/errors.go
registry/app/store/database/util/errors.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package util import ( "errors" "fmt" ) var ( // ErrNotFound is returned when a row is not found on the metadata database. ErrNotFound = errors.New("not found") // ErrManifestNotFound is returned when a manifest is not found on the metadata database. ErrManifestNotFound = fmt.Errorf("manifest %w", ErrNotFound) // ErrRefManifestNotFound is returned when a manifest referenced by a list/index is not found on the metadata database. ErrRefManifestNotFound = fmt.Errorf("referenced %w", ErrManifestNotFound) // ErrManifestReferencedInList is returned when attempting to delete a manifest referenced in at least one list. ErrManifestReferencedInList = errors.New("manifest referenced by manifest list") ) // UnknownMediaTypeError is returned when attempting to save a manifest containing references with unknown media types. type UnknownMediaTypeError struct { // MediaType is the offending media type MediaType string } // Error implements error. func (err UnknownMediaTypeError) Error() string { return fmt.Sprintf("unknown media type: %s", err.MediaType) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/util/utils.go
registry/app/store/database/util/utils.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package util import ( "database/sql" "fmt" "strings" "github.com/harness/gitness/registry/utils" ) func GetEmptySQLString(str string) sql.NullString { if utils.IsEmpty(str) { return sql.NullString{String: str, Valid: false} } return sql.NullString{String: str, Valid: true} } func GetEmptySQLInt64(i int64) sql.NullInt64 { if i == 0 { return sql.NullInt64{Int64: i, Valid: false} } return sql.NullInt64{Int64: i, Valid: true} } func ConstructQuery(query string, args []any) string { var builder strings.Builder argIndex := 0 for i := 0; i < len(query); i++ { if query[i] == '?' && argIndex < len(args) { arg := args[argIndex] argIndex++ // Convert the argument to a SQL-safe string var argStr string switch v := arg.(type) { case string: argStr = fmt.Sprintf("'%s'", strings.ReplaceAll(v, "'", "''")) // Escape single quotes in strings case int, int64, float64: argStr = fmt.Sprintf("%v", v) case bool: argStr = fmt.Sprintf("%t", v) default: argStr = fmt.Sprintf("'%v'", v) } builder.WriteString(argStr) } else { builder.WriteByte(query[i]) } } return builder.String() } // FormatQuery is a helper function to interpolate parameters into the query. func FormatQuery(query string, params []any) string { for i, param := range params { placeholder := fmt.Sprintf("$%d", i+1) var value string switch v := param.(type) { case string: value = fmt.Sprintf("'%s'", strings.ReplaceAll(v, "'", "''")) case []string: quotedValues := make([]string, len(v)) for i, s := range v { quotedValues[i] = fmt.Sprintf("'%s'", strings.ReplaceAll(s, "'", "''")) } value = fmt.Sprintf("ARRAY[%s]", strings.Join(quotedValues, ", ")) default: value = fmt.Sprintf("%v", v) } query = strings.Replace(query, placeholder, value, 1) } return query } func SafeIntToUInt64(i int) uint64 { if i < 0 { return 0 } return uint64(i) } func MinInt(a, b int) int { if a < b { return a } return b }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/store/database/util/mapper.go
registry/app/store/database/util/mapper.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package util import ( "encoding/hex" "reflect" "strconv" "strings" "github.com/harness/gitness/registry/utils" ) const ID = "" const separator = "^_" func StringToArr(s string) []string { return StringToArrByDelimiter(s, separator) } func ArrToString(arr []string) string { return ArrToStringByDelimiter(arr, separator) } func Int64ArrToString(arr []int64) string { return Int64ArrToStringByDelimiter(arr, separator) } func StringToInt64Arr(s string) []int64 { return StringToInt64ArrByDelimiter(s, separator) } func StringToArrByDelimiter(s string, delimiter string) []string { var arr []string if utils.IsEmpty(s) { return arr } return strings.Split(s, delimiter) } func ArrToStringByDelimiter(arr []string, delimiter string) string { return strings.Join(arr, delimiter) } func Int64ArrToStringByDelimiter(arr []int64, delimiter string) string { var s []string for _, i := range arr { s = append(s, strconv.FormatInt(i, 10)) } return strings.Join(s, delimiter) } func StringToInt64ArrByDelimiter(s string, delimiter string) []int64 { var arr []int64 if utils.IsEmpty(s) { return arr } for i := range strings.SplitSeq(s, delimiter) { j, _ := strconv.ParseInt(i, 10, 64) arr = append(arr, j) } return arr } func GetSetDBKeys(s any, ignoreKeys ...string) string { keys := GetDBTagsFromStruct(s) filteredKeys := make([]string, 0) keysLoop: for _, key := range keys { for _, ignoreKey := range ignoreKeys { if key == ignoreKey { continue keysLoop } } filteredKeys = append(filteredKeys, key+" = :"+key) } return strings.Join(filteredKeys, ", ") } func GetDBTagsFromStruct(s any) []string { var tags []string rt := reflect.TypeOf(s) for i := 0; i < rt.NumField(); i++ { field := rt.Field(i) dbTag := field.Tag.Get("db") if dbTag != "" { tags = append(tags, dbTag) } } return tags } func GetHexDecodedBytes(s string) ([]byte, error) { return hex.DecodeString(s) } func GetHexEncodedString(b []byte) string { return hex.EncodeToString(b) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/utils/rpm/helper.go
registry/app/utils/rpm/helper.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm //nolint:gosec import ( "fmt" "io" "reflect" "strings" rpmmetadata "github.com/harness/gitness/registry/app/metadata/rpm" rpmtypes "github.com/harness/gitness/registry/app/utils/rpm/types" "github.com/harness/gitness/registry/validation" "github.com/sassoftware/go-rpmutils" ) const ( sIFMT = 0xf000 sIFDIR = 0x4000 sIXUSR = 0x40 sIXGRP = 0x8 sIXOTH = 0x1 RepoDataPrefix = "repodata/" ) func ParsePackage(r io.Reader) (*rpmtypes.Package, error) { rpm, err := rpmutils.ReadRpm(r) if err != nil { return nil, err } nevra, err := rpm.Header.GetNEVRA() if err != nil { return nil, err } isSourceRpm := false if rpm.Header != nil { if headerValue := reflect.ValueOf(rpm.Header).Elem(); headerValue.Kind() == reflect.Struct { isSourceField := headerValue.FieldByName("isSource") if isSourceField.IsValid() && isSourceField.Kind() == reflect.Bool { isSourceRpm = isSourceField.Bool() } } } if isSourceRpm { nevra.Arch = "src" } version := fmt.Sprintf("%s-%s", nevra.Version, nevra.Release) p := &rpmtypes.Package{ Name: nevra.Name, Version: version, VersionMetadata: &rpmmetadata.VersionMetadata{ Summary: getString(rpm.Header, rpmutils.SUMMARY), Description: getString(rpm.Header, rpmutils.DESCRIPTION), License: getString(rpm.Header, rpmutils.LICENSE), ProjectURL: getString(rpm.Header, rpmutils.URL), }, FileMetadata: &rpmmetadata.FileMetadata{ Architecture: nevra.Arch, Epoch: nevra.Epoch, Version: nevra.Version, Release: nevra.Release, Vendor: getString(rpm.Header, rpmutils.VENDOR), Group: getString(rpm.Header, rpmutils.GROUP), Packager: getString(rpm.Header, rpmutils.PACKAGER), SourceRpm: getString(rpm.Header, rpmutils.SOURCERPM), BuildHost: getString(rpm.Header, rpmutils.BUILDHOST), BuildTime: getUInt64(rpm.Header, rpmutils.BUILDTIME), FileTime: getUInt64(rpm.Header, rpmutils.FILEMTIMES), InstalledSize: getUInt64(rpm.Header, rpmutils.SIZE), ArchiveSize: getUInt64(rpm.Header, rpmutils.SIG_PAYLOADSIZE), Provides: getEntries(rpm.Header, rpmutils.PROVIDENAME, rpmutils.PROVIDEVERSION, rpmutils.PROVIDEFLAGS), Requires: getEntries(rpm.Header, rpmutils.REQUIRENAME, rpmutils.REQUIREVERSION, rpmutils.REQUIREFLAGS), Conflicts: getEntries(rpm.Header, rpmutils.CONFLICTNAME, rpmutils.CONFLICTVERSION, rpmutils.CONFLICTFLAGS), Obsoletes: getEntries(rpm.Header, rpmutils.OBSOLETENAME, rpmutils.OBSOLETEVERSION, rpmutils.OBSOLETEFLAGS), Files: getFiles(rpm.Header), Changelogs: getChangelogs(rpm.Header), }, } if !validation.IsValidURL(p.VersionMetadata.ProjectURL) { p.VersionMetadata.ProjectURL = "" } return p, nil } func getString(h *rpmutils.RpmHeader, tag int) string { values, err := h.GetStrings(tag) if err != nil || len(values) < 1 { return "" } return values[0] } func getUInt64(h *rpmutils.RpmHeader, tag int) uint64 { values, err := h.GetUint64s(tag) if err != nil || len(values) < 1 { return 0 } return values[0] } // nolint: gocritic func getEntries(h *rpmutils.RpmHeader, namesTag, versionsTag, flagsTag int) []*rpmmetadata.Entry { names, err := h.GetStrings(namesTag) if err != nil || len(names) == 0 { return nil } flags, err := h.GetUint64s(flagsTag) if err != nil || len(flags) == 0 { return nil } versions, err := h.GetStrings(versionsTag) if err != nil || len(versions) == 0 { return nil } if len(names) != len(flags) || len(names) != len(versions) { return nil } entries := make([]*rpmmetadata.Entry, 0, len(names)) for i := range names { e := &rpmmetadata.Entry{ Name: names[i], } flags := flags[i] if (flags&rpmutils.RPMSENSE_GREATER) != 0 && (flags&rpmutils.RPMSENSE_EQUAL) != 0 { e.Flags = "GE" } else if (flags&rpmutils.RPMSENSE_LESS) != 0 && (flags&rpmutils.RPMSENSE_EQUAL) != 0 { e.Flags = "LE" } else if (flags & rpmutils.RPMSENSE_GREATER) != 0 { e.Flags = "GT" } else if (flags & rpmutils.RPMSENSE_LESS) != 0 { e.Flags = "LT" } else if (flags & rpmutils.RPMSENSE_EQUAL) != 0 { e.Flags = "EQ" } version := versions[i] if version != "" { parts := strings.Split(version, "-") versionParts := strings.Split(parts[0], ":") if len(versionParts) == 2 { e.Version = versionParts[1] e.Epoch = versionParts[0] } else { e.Version = versionParts[0] e.Epoch = "0" } if len(parts) > 1 { e.Release = parts[1] } } entries = append(entries, e) } return entries } func getFiles(h *rpmutils.RpmHeader) []*rpmmetadata.File { baseNames, _ := h.GetStrings(rpmutils.BASENAMES) dirNames, _ := h.GetStrings(rpmutils.DIRNAMES) dirIndexes, _ := h.GetUint32s(rpmutils.DIRINDEXES) fileFlags, _ := h.GetUint32s(rpmutils.FILEFLAGS) fileModes, _ := h.GetUint32s(rpmutils.FILEMODES) files := make([]*rpmmetadata.File, 0, len(baseNames)) for i := range baseNames { if len(dirIndexes) <= i { continue } dirIndex := dirIndexes[i] if len(dirNames) <= int(dirIndex) { continue } var fileType string var isExecutable bool if i < len(fileFlags) && (fileFlags[i]&rpmutils.RPMFILE_GHOST) != 0 { fileType = "ghost" } else if i < len(fileModes) { if (fileModes[i] & sIFMT) == sIFDIR { fileType = "dir" } else { mode := fileModes[i] & ^uint32(sIFMT) isExecutable = (mode&sIXUSR) != 0 || (mode&sIXGRP) != 0 || (mode&sIXOTH) != 0 } } files = append(files, &rpmmetadata.File{ Path: dirNames[dirIndex] + baseNames[i], Type: fileType, IsExecutable: isExecutable, }) } return files } func getChangelogs(h *rpmutils.RpmHeader) []*rpmmetadata.Changelog { texts, err := h.GetStrings(rpmutils.CHANGELOGTEXT) if err != nil || len(texts) == 0 { return nil } authors, err := h.GetStrings(rpmutils.CHANGELOGNAME) if err != nil || len(authors) == 0 { return nil } times, err := h.GetUint32s(rpmutils.CHANGELOGTIME) if err != nil || len(times) == 0 { return nil } if len(texts) != len(authors) || len(texts) != len(times) { return nil } changelogs := make([]*rpmmetadata.Changelog, 0, len(texts)) for i := range texts { changelogs = append(changelogs, &rpmmetadata.Changelog{ Author: authors[i], Date: int64(times[i]), Text: texts[i], }) } return changelogs }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/utils/rpm/types/types.go
registry/app/utils/rpm/types/types.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package types //nolint:gosec import ( "bytes" "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding" "encoding/xml" "errors" "hash" "io" "math" "os" rpmmetadata "github.com/harness/gitness/registry/app/metadata/rpm" ) const ( sizeMD5 = 92 sizeSHA1 = 96 sizeSHA256 = 108 sizeSHA512 = 204 size = sizeMD5 + sizeSHA1 + sizeSHA256 + sizeSHA512 DefaultMemorySize = 32 * 1024 * 1024 ) var ( ErrInvalidMemorySize = errors.New("memory size must be greater 0 and lower math.MaxInt32") ErrWriteAfterRead = errors.New("write is unsupported after a read operation") ) type PrimaryVersion struct { Epoch string `xml:"epoch,attr"` Version string `xml:"ver,attr"` Release string `xml:"rel,attr"` } type PrimaryChecksum struct { Checksum string `xml:",chardata"` //nolint: tagliatelle Type string `xml:"type,attr"` Pkgid string `xml:"pkgid,attr"` } type PrimaryTimes struct { File uint64 `xml:"file,attr"` Build uint64 `xml:"build,attr"` } type PrimarySizes struct { Package int64 `xml:"package,attr"` Installed uint64 `xml:"installed,attr"` Archive uint64 `xml:"archive,attr"` } type PrimaryLocation struct { Href string `xml:"href,attr"` } type PrimaryEntryList struct { Entries []*rpmmetadata.Entry `xml:"entry"` } // MarshalXML implements custom XML marshaling for primaryEntryList to add rpm prefix. func (l PrimaryEntryList) MarshalXML(e *xml.Encoder, start xml.StartElement) error { return e.EncodeElement(struct { Entries []*rpmmetadata.Entry `xml:"rpm:entry"` }{ Entries: l.Entries, }, start) } type PrimaryFormat struct { License string `xml:"license"` Vendor string `xml:"vendor"` Group string `xml:"group"` Buildhost string `xml:"buildhost"` Sourcerpm string `xml:"sourcerpm"` Provides PrimaryEntryList `xml:"provides"` Requires PrimaryEntryList `xml:"requires"` Conflicts PrimaryEntryList `xml:"conflicts"` Obsoletes PrimaryEntryList `xml:"obsoletes"` Files []*rpmmetadata.File `xml:"file"` } // MarshalXML implements custom XML marshaling for primaryFormat to add rpm prefix. func (f PrimaryFormat) MarshalXML(e *xml.Encoder, start xml.StartElement) error { return e.EncodeElement(struct { License string `xml:"rpm:license"` Vendor string `xml:"rpm:vendor"` Group string `xml:"rpm:group"` Buildhost string `xml:"rpm:buildhost"` Sourcerpm string `xml:"rpm:sourcerpm"` Provides PrimaryEntryList `xml:"rpm:provides"` Requires PrimaryEntryList `xml:"rpm:requires"` Conflicts PrimaryEntryList `xml:"rpm:conflicts"` Obsoletes PrimaryEntryList `xml:"rpm:obsoletes"` Files []*rpmmetadata.File `xml:"file"` }{ License: f.License, Vendor: f.Vendor, Group: f.Group, Buildhost: f.Buildhost, Sourcerpm: f.Sourcerpm, Provides: f.Provides, Requires: f.Requires, Conflicts: f.Conflicts, Obsoletes: f.Obsoletes, Files: f.Files, }, start) } type PrimaryPackage struct { XMLName xml.Name `xml:"package"` Type string `xml:"type,attr"` Name string `xml:"name"` Architecture string `xml:"arch"` Version PrimaryVersion `xml:"version"` Checksum PrimaryChecksum `xml:"checksum"` Summary string `xml:"summary"` Description string `xml:"description"` Packager string `xml:"packager"` URL string `xml:"url"` Time PrimaryTimes `xml:"time"` Size PrimarySizes `xml:"size"` Location PrimaryLocation `xml:"location"` Format PrimaryFormat `xml:"format"` } type OtherVersion struct { Epoch string `xml:"epoch,attr"` Version string `xml:"ver,attr"` Release string `xml:"rel,attr"` } type OtherPackage struct { Pkgid string `xml:"pkgid,attr"` Name string `xml:"name,attr"` Architecture string `xml:"arch,attr"` Version OtherVersion `xml:"version"` Changelogs []*rpmmetadata.Changelog `xml:"changelog"` } type FileListVersion struct { Epoch string `xml:"epoch,attr"` Version string `xml:"ver,attr"` Release string `xml:"rel,attr"` } type FileListPackage struct { Pkgid string `xml:"pkgid,attr"` Name string `xml:"name,attr"` Architecture string `xml:"arch,attr"` Version FileListVersion `xml:"version"` Files []*rpmmetadata.File `xml:"file"` } type Repomd struct { XMLName xml.Name `xml:"repomd"` Xmlns string `xml:"xmlns,attr"` XmlnsRpm string `xml:"xmlns:rpm,attr"` Data []*RepoData `xml:"data"` } type RepoChecksum struct { Value string `xml:",chardata"` //nolint: tagliatelle Type string `xml:"type,attr"` } type RepoLocation struct { Href string `xml:"href,attr"` } type RepoData struct { Type string `xml:"type,attr"` Checksum RepoChecksum `xml:"checksum"` OpenChecksum RepoChecksum `xml:"open-checksum"` //nolint: tagliatelle Location RepoLocation `xml:"location"` Timestamp int64 `xml:"timestamp"` Size int64 `xml:"size"` OpenSize int64 `xml:"open-size"` //nolint: tagliatelle } type PackageInfo struct { Name string Sha256 string Size int64 VersionMetadata *rpmmetadata.VersionMetadata FileMetadata *rpmmetadata.FileMetadata } type Package struct { Name string Version string VersionMetadata *rpmmetadata.VersionMetadata FileMetadata *rpmmetadata.FileMetadata } type readAtSeeker interface { io.ReadSeeker io.ReaderAt } type FileBackedBuffer struct { maxMemorySize int64 size int64 buffer bytes.Buffer file *os.File reader readAtSeeker } func NewFileBackedBuffer(maxMemorySize int) (*FileBackedBuffer, error) { if maxMemorySize < 0 || maxMemorySize > math.MaxInt32 { return nil, ErrInvalidMemorySize } return &FileBackedBuffer{ maxMemorySize: int64(maxMemorySize), }, nil } //nolint:nestif func (b *FileBackedBuffer) Write(p []byte) (int, error) { if b.reader != nil { return 0, ErrWriteAfterRead } var n int var err error if b.file != nil { n, err = b.file.Write(p) } else { if b.size+int64(len(p)) > b.maxMemorySize { b.file, err = os.CreateTemp("", "gitness-buffer-") if err != nil { return 0, err } _, err = io.Copy(b.file, &b.buffer) if err != nil { return 0, err } return b.Write(p) } n, err = b.buffer.Write(p) } if err != nil { return n, err } b.size += int64(n) return n, nil } func (b *FileBackedBuffer) Size() int64 { return b.size } func (b *FileBackedBuffer) switchToReader() error { if b.reader != nil { return nil } if b.file != nil { if _, err := b.file.Seek(0, io.SeekStart); err != nil { return err } b.reader = b.file } else { b.reader = bytes.NewReader(b.buffer.Bytes()) } return nil } func (b *FileBackedBuffer) Read(p []byte) (int, error) { if err := b.switchToReader(); err != nil { return 0, err } return b.reader.Read(p) } func (b *FileBackedBuffer) ReadAt(p []byte, off int64) (int, error) { if err := b.switchToReader(); err != nil { return 0, err } return b.reader.ReadAt(p, off) } func (b *FileBackedBuffer) Seek(offset int64, whence int) (int64, error) { if err := b.switchToReader(); err != nil { return 0, err } return b.reader.Seek(offset, whence) } func (b *FileBackedBuffer) Close() error { if b.file != nil { err := b.file.Close() os.Remove(b.file.Name()) b.file = nil return err } return nil } type HashedBuffer struct { *FileBackedBuffer hash *MultiHasher combinedWriter io.Writer } func NewHashedBufferWithSize(maxMemorySize int) (*HashedBuffer, error) { b, err := NewFileBackedBuffer(maxMemorySize) if err != nil { return nil, err } hash := NewMultiHasher() combinedWriter := io.MultiWriter(b, hash) return &HashedBuffer{ b, hash, combinedWriter, }, nil } func CreateHashedBufferFromReader(r io.Reader) (*HashedBuffer, error) { return CreateHashedBufferFromReaderWithSize(r, DefaultMemorySize) } func CreateHashedBufferFromReaderWithSize(r io.Reader, maxMemorySize int) (*HashedBuffer, error) { b, err := NewHashedBufferWithSize(maxMemorySize) if err != nil { return nil, err } _, err = io.Copy(b, r) if err != nil { return nil, err } return b, nil } func (b *HashedBuffer) Write(p []byte) (int, error) { return b.combinedWriter.Write(p) } func (b *HashedBuffer) Sums() (hashMD5, hashSHA1, hashSHA256, hashSHA512 []byte) { return b.hash.Sums() } type MultiHasher struct { md5 hash.Hash sha1 hash.Hash sha256 hash.Hash sha512 hash.Hash combinedWriter io.Writer } //nolint:gosec func NewMultiHasher() *MultiHasher { md5 := md5.New() sha1 := sha1.New() sha256 := sha256.New() sha512 := sha512.New() combinedWriter := io.MultiWriter(md5, sha1, sha256, sha512) return &MultiHasher{ md5, sha1, sha256, sha512, combinedWriter, } } // nolint:errcheck func (h *MultiHasher) MarshalBinary() ([]byte, error) { md5Bytes, err := h.md5.(encoding.BinaryMarshaler).MarshalBinary() if err != nil { return nil, err } sha1Bytes, err := h.sha1.(encoding.BinaryMarshaler).MarshalBinary() if err != nil { return nil, err } sha256Bytes, err := h.sha256.(encoding.BinaryMarshaler).MarshalBinary() if err != nil { return nil, err } sha512Bytes, err := h.sha512.(encoding.BinaryMarshaler).MarshalBinary() if err != nil { return nil, err } b := make([]byte, 0, size) b = append(b, md5Bytes...) b = append(b, sha1Bytes...) b = append(b, sha256Bytes...) b = append(b, sha512Bytes...) return b, nil } func (h *MultiHasher) Write(p []byte) (int, error) { return h.combinedWriter.Write(p) } func (h *MultiHasher) Sums() (hashMD5, hashSHA1, hashSHA256, hashSHA512 []byte) { hashMD5 = h.md5.Sum(nil) hashSHA1 = h.sha1.Sum(nil) hashSHA256 = h.sha256.Sum(nil) hashSHA512 = h.sha512.Sum(nil) return hashMD5, hashSHA1, hashSHA256, hashSHA512 }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/utils/gopackage/wire.go
registry/app/utils/gopackage/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/registry/app/pkg/filemanager" refcache2 "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/google/wire" ) func LocalRegistryHelperProvider( fileManager filemanager.FileManager, artifactDao store.ArtifactRepository, spaceFinder refcache.SpaceFinder, registryFinder refcache2.RegistryFinder, ) RegistryHelper { return NewRegistryHelper(fileManager, artifactDao, spaceFinder, registryFinder) } var WireSet = wire.NewSet(LocalRegistryHelperProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/utils/gopackage/helper.go
registry/app/utils/gopackage/helper.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "path/filepath" "strings" "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/registry/app/api/openapi/contracts/artifact" apiutils "github.com/harness/gitness/registry/app/api/utils" gopackagemetadata "github.com/harness/gitness/registry/app/metadata/gopackage" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/gopackage/utils" refcache2 "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/types" gitnessstore "github.com/harness/gitness/store" ) type RegistryHelper interface { UpdatePackageIndex( ctx context.Context, principalID int64, rootParentID int64, registryID int64, image string, ) error UpdatePackageMetadata( ctx context.Context, rootParentID int64, registryID int64, image string, version string, ) error } type registryHelper struct { fileManager filemanager.FileManager artifactDao store.ArtifactRepository spaceFinder refcache.SpaceFinder registryFinder refcache2.RegistryFinder } func NewRegistryHelper( fileManager filemanager.FileManager, artifactDao store.ArtifactRepository, spaceFinder refcache.SpaceFinder, registryFinder refcache2.RegistryFinder, ) RegistryHelper { return &registryHelper{ fileManager: fileManager, artifactDao: artifactDao, spaceFinder: spaceFinder, registryFinder: registryFinder, } } func (h *registryHelper) UpdatePackageIndex( ctx context.Context, principalID int64, rootParentID int64, registryID int64, image string, ) error { rootSpace, err := h.spaceFinder.FindByID(ctx, rootParentID) if err != nil { return fmt.Errorf("failed to find root space by ID: %w", err) } versionList, err := h.regeneratePackageIndex(ctx, registryID, image) if err != nil { return fmt.Errorf("failed to regenerate package index: %w", err) } return h.uploadIndexMetadata( ctx, principalID, rootSpace.Identifier, rootParentID, registryID, image, versionList, ) } func (h *registryHelper) regeneratePackageIndex( ctx context.Context, registryID int64, image string, ) ([]string, error) { lastArtifactID := int64(0) artifactBatchLimit := 50 versionList := []string{} for { artifacts, err := h.artifactDao.GetArtifactsByRepoAndImageBatch( ctx, registryID, image, artifactBatchLimit, lastArtifactID, ) if err != nil && errors.Is(err, gitnessstore.ErrResourceNotFound) { break } if err != nil { return nil, fmt.Errorf("failed to get artifacts: %w", err) } for _, a := range *artifacts { versionList = append(versionList, a.Version) if a.ID > lastArtifactID { lastArtifactID = a.ID } } if len(*artifacts) < artifactBatchLimit { break } } return versionList, nil } func (h *registryHelper) uploadIndexMetadata( ctx context.Context, principalID int64, rootIdentifier string, rootParentID int64, registryID int64, image string, versionList []string, ) error { fileName := image filePath := utils.GetIndexFilePath(image) _, err := h.fileManager.UploadFile( ctx, filePath, registryID, rootParentID, rootIdentifier, nil, io.NopCloser(strings.NewReader(strings.Join(versionList, "\n"))), fileName, principalID, ) if err != nil { return fmt.Errorf("failed to upload package index metadata: %w", err) } return nil } func (h *registryHelper) UpdatePackageMetadata( ctx context.Context, rootParentID int64, registryID int64, image string, version string, ) error { rootSpace, err := h.spaceFinder.FindByID(ctx, rootParentID) if err != nil { return fmt.Errorf("failed to find root space by ID: %w", err) } registry, err := h.registryFinder.FindByID(ctx, registryID) if err != nil { return fmt.Errorf("failed to find registry by ID: %w", err) } artifact, err := h.artifactDao.GetByRegistryImageAndVersion(ctx, registryID, image, version) if err != nil { return fmt.Errorf("failed to get artifact by registry, image and version: %w", err) } var metadata gopackagemetadata.VersionMetadataDB // convert artifact metadata to version metadata using json err = json.Unmarshal(artifact.Metadata, &metadata) if err != nil { return fmt.Errorf("failed to convert artifact metadata to version metadata: %w", err) } // regenerate package metadata err = h.regeneratePackageMetadata( ctx, rootSpace.Identifier, registry, image, version, &metadata.VersionMetadata, ) if err != nil { return fmt.Errorf("failed to regenerate package metadata: %w", err) } // convert version metadata to artifact metadata using json rawMetadata, err := json.Marshal(metadata) if err != nil { return fmt.Errorf("failed to marshal metadata: %w", err) } // update artifact err = h.artifactDao.UpdateArtifactMetadata(ctx, rawMetadata, artifact.ID) if err != nil { return fmt.Errorf("failed to create or update artifact: %w", err) } return nil } func (h *registryHelper) regeneratePackageMetadata( ctx context.Context, rootIdentifier string, registry *types.Registry, image string, version string, metadata *gopackagemetadata.VersionMetadata, ) error { path, err := apiutils.GetFilePath(artifact.PackageTypeGO, image, version) if err != nil { return fmt.Errorf("failed to get file path: %w", err) } metadata.Name = image metadata.Version = version err = h.updatePackageMetadataFromInfoFile( ctx, path, rootIdentifier, registry, version, metadata, ) if err != nil { return fmt.Errorf("failed to update package metadata from info file: %w", err) } err = h.updatePackageMetadataFromModFile( ctx, path, rootIdentifier, registry, version, metadata, ) if err != nil { return fmt.Errorf("failed to update package metadata from mod file: %w", err) } err = h.updatePackageMetadataFromZipFile( ctx, path, rootIdentifier, registry, version, metadata, ) if err != nil { return fmt.Errorf("failed to update package metadata from zip file: %w", err) } return nil } func (h *registryHelper) updatePackageMetadataFromInfoFile( ctx context.Context, path string, rootIdentifier string, registry *types.Registry, version string, metadata *gopackagemetadata.VersionMetadata, ) error { infoFileName := version + ".info" infoFilePath := filepath.Join(path, infoFileName) reader, _, _, err := h.fileManager.DownloadFile( ctx, infoFilePath, registry.ID, registry.Name, rootIdentifier, false, ) if err != nil { return fmt.Errorf("failed to download package metadata: %w", err) } infoBytes := &bytes.Buffer{} if _, err := io.Copy(infoBytes, reader); err != nil { return fmt.Errorf("error reading 'info': %w", err) } reader.Close() infometadata, err := utils.GetPackageMetadataFromInfoFile(infoBytes) if err != nil { return fmt.Errorf("failed to get package metadata from info file: %w", err) } metadata.Time = infometadata.Time metadata.Origin = infometadata.Origin return nil } func (h *registryHelper) updatePackageMetadataFromModFile( ctx context.Context, path string, rootIdentifier string, registry *types.Registry, version string, metadata *gopackagemetadata.VersionMetadata, ) error { modFileName := version + ".mod" modFilePath := filepath.Join(path, modFileName) reader, _, _, err := h.fileManager.DownloadFile( ctx, modFilePath, registry.ID, registry.Name, rootIdentifier, false, ) if err != nil { return fmt.Errorf("failed to download package metadata: %w", err) } modBytes := &bytes.Buffer{} if _, err := io.Copy(modBytes, reader); err != nil { return fmt.Errorf("error reading 'mod': %w", err) } reader.Close() err = utils.UpdateMetadataFromModFile(modBytes, metadata) if err != nil { return fmt.Errorf("failed to update metadata from mod file: %w", err) } return nil } func (h *registryHelper) updatePackageMetadataFromZipFile( ctx context.Context, path string, rootIdentifier string, registry *types.Registry, version string, metadata *gopackagemetadata.VersionMetadata, ) error { zipFileName := version + ".zip" zipFilePath := filepath.Join(path, zipFileName) reader, _, _, err := h.fileManager.DownloadFile( ctx, zipFilePath, registry.ID, registry.Name, rootIdentifier, false, ) if err != nil { return fmt.Errorf("failed to download package metadata: %w", err) } defer reader.Close() err = utils.UpdateMetadataFromZipFile(reader, metadata) if err != nil { return fmt.Errorf("failed to update metadata from zip file: %w", err) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/utils/cargo/wire.go
registry/app/utils/cargo/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "github.com/harness/gitness/app/services/refcache" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/store" "github.com/google/wire" ) func LocalRegistryHelperProvider( fileManager filemanager.FileManager, artifactDao store.ArtifactRepository, spaceFinder refcache.SpaceFinder, ) RegistryHelper { return NewRegistryHelper(fileManager, artifactDao, spaceFinder) } var WireSet = wire.NewSet(LocalRegistryHelperProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/utils/cargo/helper.go
registry/app/utils/cargo/helper.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "encoding/json" "fmt" "io" "strings" "github.com/harness/gitness/app/services/refcache" cargometadata "github.com/harness/gitness/registry/app/metadata/cargo" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/store" ) type RegistryHelper interface { GetIndexFilePathFromImageName(imageName string) string UpdatePackageIndex( ctx context.Context, principalID int64, rootParentID int64, registryID int64, image string, ) error } type registryHelper struct { fileManager filemanager.FileManager artifactDao store.ArtifactRepository spaceFinder refcache.SpaceFinder } func NewRegistryHelper( fileManager filemanager.FileManager, artifactDao store.ArtifactRepository, spaceFinder refcache.SpaceFinder, ) RegistryHelper { return &registryHelper{ fileManager: fileManager, artifactDao: artifactDao, spaceFinder: spaceFinder, } } func (h *registryHelper) GetIndexFilePathFromImageName(imageName string) string { length := len(imageName) switch length { case 0: return imageName case 1: return fmt.Sprintf("/index/1/%s", imageName) case 2: return fmt.Sprintf("/index/2/%s", imageName) case 3: return fmt.Sprintf("/index/3/%c/%s", imageName[0], imageName) default: return fmt.Sprintf("/index/%s/%s/%s", imageName[0:2], imageName[2:4], imageName) } } func (h *registryHelper) UpdatePackageIndex( ctx context.Context, principalID int64, rootParentID int64, registryID int64, image string, ) error { rootSpace, err := h.spaceFinder.FindByID(ctx, rootParentID) if err != nil { return fmt.Errorf("failed to find root space by ID: %w", err) } indexMetadataList, err := h.regeneratePackageIndex(ctx, registryID, image) if err != nil { return fmt.Errorf("failed to regenerate package index: %w", err) } return h.uploadIndexMetadata( ctx, principalID, rootSpace.Identifier, rootParentID, registryID, image, indexMetadataList, ) } func (h *registryHelper) regeneratePackageIndex( ctx context.Context, registryID int64, image string, ) ([]*cargometadata.IndexMetadata, error) { lastArtifactID := int64(0) artifactBatchLimit := 50 versionMetadataList := []*cargometadata.IndexMetadata{} for { artifacts, err := h.artifactDao.GetArtifactsByRepoAndImageBatch( ctx, registryID, image, artifactBatchLimit, lastArtifactID, ) if err != nil { return nil, fmt.Errorf("failed to get artifacts: %w", err) } for _, a := range *artifacts { metadata := cargometadata.VersionMetadataDB{} err := json.Unmarshal(a.Metadata, &metadata) if err != nil { return nil, fmt.Errorf("failed to unmarshal metadata for artifact %s: %w", a.Name, err) } deps := h.mapVersionDependenciesToIndexDependencies(metadata.Dependencies) features := metadata.Features // If there are no features, we initialize it to an empty map if features == nil { features = make(map[string][]string) } if len(metadata.GetFiles()) > 0 { versionMetadataList = append(versionMetadataList, &cargometadata.IndexMetadata{ Name: a.Name, Version: a.Version, Checksum: metadata.GetFiles()[0].Sha256, Dependencies: deps, Features: features, Yanked: metadata.Yanked, }) } if a.ID > lastArtifactID { lastArtifactID = a.ID } } if len(*artifacts) < artifactBatchLimit { break } } return versionMetadataList, nil } func (h *registryHelper) uploadIndexMetadata( ctx context.Context, principalID int64, rootIdentifier string, rootParentID int64, registryID int64, image string, indexMetadataList []*cargometadata.IndexMetadata, ) error { fileName := image filePath := h.GetIndexFilePathFromImageName(image) metadataList := []string{} for _, metadata := range indexMetadataList { metadataJSON, err := json.Marshal(metadata) if err != nil { return fmt.Errorf("failed to marshal metadata: %w", err) } metadataList = append(metadataList, string(metadataJSON)) } _, err := h.fileManager.UploadFile( ctx, filePath, registryID, rootParentID, rootIdentifier, nil, io.NopCloser(strings.NewReader(strings.Join(metadataList, "\n"))), fileName, principalID, ) if err != nil { return fmt.Errorf("failed to upload package index metadata: %w", err) } return nil } func (h *registryHelper) mapVersionDependenciesToIndexDependencies( dependencies []cargometadata.VersionDependency, ) []cargometadata.IndexDependency { // If there are no dependencies, we initialize it to an empty slice if dependencies == nil { return []cargometadata.IndexDependency{} } deps := make([]cargometadata.IndexDependency, len(dependencies)) for i, dep := range dependencies { deps[i] = cargometadata.IndexDependency{ VersionRequired: dep.VersionRequired, Dependency: cargometadata.Dependency{ Name: dep.Name, Features: dep.Features, IsOptional: dep.IsOptional, DefaultFeatures: dep.DefaultFeatures, Target: dep.Target, Kind: dep.Kind, Registry: dep.Registry, ExplicitNameInToml: dep.ExplicitNameInToml, }, } } return deps }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/wire.go
registry/app/api/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package api import ( "context" usercontroller "github.com/harness/gitness/app/api/controller/user" "github.com/harness/gitness/app/auth/authn" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" corestore "github.com/harness/gitness/app/store" urlprovider "github.com/harness/gitness/app/url" cargo2 "github.com/harness/gitness/registry/app/api/controller/pkg/cargo" generic3 "github.com/harness/gitness/registry/app/api/controller/pkg/generic" gopackage2 "github.com/harness/gitness/registry/app/api/controller/pkg/gopackage" "github.com/harness/gitness/registry/app/api/controller/pkg/huggingface" "github.com/harness/gitness/registry/app/api/controller/pkg/npm" nuget2 "github.com/harness/gitness/registry/app/api/controller/pkg/nuget" python2 "github.com/harness/gitness/registry/app/api/controller/pkg/python" rpm2 "github.com/harness/gitness/registry/app/api/controller/pkg/rpm" "github.com/harness/gitness/registry/app/api/handler/cargo" "github.com/harness/gitness/registry/app/api/handler/generic" "github.com/harness/gitness/registry/app/api/handler/gopackage" hf2 "github.com/harness/gitness/registry/app/api/handler/huggingface" mavenhandler "github.com/harness/gitness/registry/app/api/handler/maven" npm2 "github.com/harness/gitness/registry/app/api/handler/npm" nugethandler "github.com/harness/gitness/registry/app/api/handler/nuget" ocihandler "github.com/harness/gitness/registry/app/api/handler/oci" "github.com/harness/gitness/registry/app/api/handler/packages" pypi2 "github.com/harness/gitness/registry/app/api/handler/python" "github.com/harness/gitness/registry/app/api/handler/rpm" "github.com/harness/gitness/registry/app/api/interfaces" "github.com/harness/gitness/registry/app/api/router" storagedriver "github.com/harness/gitness/registry/app/driver" "github.com/harness/gitness/registry/app/driver/factory" "github.com/harness/gitness/registry/app/driver/filesystem" "github.com/harness/gitness/registry/app/driver/s3-aws" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" cargoregistry "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/docker" "github.com/harness/gitness/registry/app/pkg/filemanager" generic2 "github.com/harness/gitness/registry/app/pkg/generic" gopackageregistry "github.com/harness/gitness/registry/app/pkg/gopackage" hf3 "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/maven" npm22 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/quarantine" rpmregistry "github.com/harness/gitness/registry/app/pkg/rpm" publicaccess2 "github.com/harness/gitness/registry/app/services/publicaccess" refcache2 "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/app/store/cache" "github.com/harness/gitness/registry/app/store/database" "github.com/harness/gitness/registry/config" "github.com/harness/gitness/registry/gc" "github.com/harness/gitness/types" "github.com/google/wire" "github.com/rs/zerolog/log" ) type RegistryApp struct { Config *types.Config AppRouter router.AppRouter } func BlobStorageProvider(ctx context.Context, c *types.Config) (storagedriver.StorageDriver, error) { var d storagedriver.StorageDriver var err error if c.Registry.Storage.StorageType == "filesystem" { filesystem.Register(ctx) d, err = factory.Create(ctx, "filesystem", config.GetFilesystemParams(c)) if err != nil { log.Fatal().Stack().Err(err).Msgf("") panic(err) } } else { s3.Register(ctx) d, err = factory.Create(ctx, "s3aws", config.GetS3StorageParameters(c)) if err != nil { log.Error().Stack().Err(err).Msg("failed to init s3 Blob storage ") panic(err) } } return d, err } func NewHandlerProvider( controller *docker.Controller, spaceFinder refcache.SpaceFinder, spaceStore corestore.SpaceStore, tokenStore corestore.TokenStore, userCtrl *usercontroller.Controller, authenticator authn.Authenticator, urlProvider urlprovider.Provider, authorizer authz.Authorizer, config *types.Config, registryFinder refcache2.RegistryFinder, publicAccessService publicaccess2.CacheService, ) *ocihandler.Handler { return ocihandler.NewHandler( controller, spaceFinder, spaceStore, tokenStore, userCtrl, authenticator, urlProvider, authorizer, config.Registry.HTTP.RelativeURL, registryFinder, publicAccessService, config.Auth.AnonymousUserSecret, ) } func NewMavenHandlerProvider( controller *maven.Controller, spaceStore corestore.SpaceStore, tokenStore corestore.TokenStore, userCtrl *usercontroller.Controller, authenticator authn.Authenticator, authorizer authz.Authorizer, spaceFinder refcache.SpaceFinder, publicAccessService publicaccess2.CacheService, ) *mavenhandler.Handler { return mavenhandler.NewHandler( controller, spaceStore, tokenStore, userCtrl, authenticator, authorizer, spaceFinder, publicAccessService, ) } func NewPackageHandlerProvider( registryDao store.RegistryRepository, downloadStatDao store.DownloadStatRepository, bandwidthStatDao store.BandwidthStatRepository, spaceStore corestore.SpaceStore, tokenStore corestore.TokenStore, userCtrl *usercontroller.Controller, authenticator authn.Authenticator, urlProvider urlprovider.Provider, authorizer authz.Authorizer, spaceFinder refcache.SpaceFinder, regFinder refcache2.RegistryFinder, fileManager filemanager.FileManager, quarantineFinder quarantine.Finder, packageWrapper interfaces.PackageWrapper, ) packages.Handler { return packages.NewHandler( registryDao, downloadStatDao, bandwidthStatDao, spaceStore, tokenStore, userCtrl, authenticator, urlProvider, authorizer, spaceFinder, regFinder, fileManager, quarantineFinder, packageWrapper, ) } func NewPythonHandlerProvider( controller python2.Controller, packageHandler packages.Handler, ) pypi2.Handler { return pypi2.NewHandler(controller, packageHandler) } func NewNugetHandlerProvider( controller nuget2.Controller, packageHandler packages.Handler, ) nugethandler.Handler { return nugethandler.NewHandler(controller, packageHandler) } func NewNPMHandlerProvider( controller npm.Controller, packageHandler packages.Handler, ) npm2.Handler { return npm2.NewHandler(controller, packageHandler) } func NewRpmHandlerProvider( controller rpm2.Controller, packageHandler packages.Handler, ) rpm.Handler { return rpm.NewHandler(controller, packageHandler) } func NewGenericHandlerProvider( spaceStore corestore.SpaceStore, controller *generic3.Controller, tokenStore corestore.TokenStore, userCtrl *usercontroller.Controller, authenticator authn.Authenticator, urlProvider urlprovider.Provider, authorizer authz.Authorizer, packageHandler packages.Handler, spaceFinder refcache.SpaceFinder, registryFinder refcache2.RegistryFinder, ) *generic.Handler { return generic.NewGenericArtifactHandler( spaceStore, controller, tokenStore, userCtrl, authenticator, urlProvider, authorizer, packageHandler, spaceFinder, registryFinder, ) } func NewCargoHandlerProvider( controller cargo2.Controller, packageHandler packages.Handler, ) cargo.Handler { return cargo.NewHandler(controller, packageHandler) } func NewGoPackageHandlerProvider( controller gopackage2.Controller, packageHandler packages.Handler, ) gopackage.Handler { return gopackage.NewHandler(controller, packageHandler) } var WireSet = wire.NewSet( BlobStorageProvider, NewHandlerProvider, NewMavenHandlerProvider, NewGenericHandlerProvider, NewPackageHandlerProvider, NewPythonHandlerProvider, NewNugetHandlerProvider, NewNPMHandlerProvider, NewRpmHandlerProvider, NewCargoHandlerProvider, NewGoPackageHandlerProvider, database.WireSet, cache.WireSet, refcache2.WireSet, pkg.WireSet, docker.OpenSourceWireSet, filemanager.WireSet, quarantine.WireSet, maven.WireSet, nuget.WireSet, python.WireSet, generic2.WireSet, npm22.WireSet, router.WireSet, gc.WireSet, generic3.WireSet, python2.ControllerSet, nuget2.ControllerSet, npm.ControllerSet, base.WireSet, rpm2.ControllerSet, rpmregistry.WireSet, cargo2.ControllerSet, cargoregistry.WireSet, gopackage2.ControllerSet, gopackageregistry.WireSet, huggingface.WireSet, hf2.WireSet, hf3.WireSet, publicaccess2.WireSet, ) func Wire(_ *types.Config) (RegistryApp, error) { wire.Build(WireSet, wire.Struct(new(RegistryApp), "*")) return RegistryApp{}, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/python/wire.go
registry/app/api/controller/pkg/python/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package python import ( urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func ControllerProvider( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local python.LocalRegistry, proxy python.Proxy, quarantineFinder quarantine.Finder, ) Controller { return NewController(proxyStore, registryDao, imageDao, artifactDao, fileManager, tx, urlProvider, local, proxy, quarantineFinder) } var ControllerSet = wire.NewSet(ControllerProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/python/response.go
registry/app/api/controller/pkg/python/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package python import ( "io" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" pythontype "github.com/harness/gitness/registry/app/pkg/types/python" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*GetMetadataResponse)(nil) var _ response.Response = (*GetArtifactResponse)(nil) var _ response.Response = (*PutArtifactResponse)(nil) type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type GetMetadataResponse struct { BaseResponse PackageMetadata pythontype.PackageMetadata } type GetArtifactResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type PutArtifactResponse struct { BaseResponse Sha256 string }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/python/metadata.go
registry/app/api/controller/pkg/python/metadata.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package python import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/response" pythontype "github.com/harness/gitness/registry/app/pkg/types/python" registrytypes "github.com/harness/gitness/registry/types" ) // Metadata represents the metadata of a Python package. func (c *controller) GetPackageMetadata(ctx context.Context, info pythontype.ArtifactInfo) *GetMetadataResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) pythonRegistry, ok := a.(python.Registry) if !ok { return &GetMetadataResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected python.Registry"), nil, }, pythontype.PackageMetadata{}, } } metadata, err := pythonRegistry.GetPackageMetadata(ctx, info) return &GetMetadataResponse{ BaseResponse{ err, nil, }, metadata, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) metadataResponse, ok := result.(*GetMetadataResponse) if !ok { return &GetMetadataResponse{ BaseResponse{ err, nil, }, pythontype.PackageMetadata{}, } } return metadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/python/controller.go
registry/app/api/controller/pkg/python/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package python import ( "context" "mime/multipart" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/quarantine" pythontype "github.com/harness/gitness/registry/app/pkg/types/python" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) type Controller interface { GetPackageMetadata(ctx context.Context, info pythontype.ArtifactInfo) *GetMetadataResponse UploadPackageFile( ctx context.Context, info pythontype.ArtifactInfo, file multipart.File, fileHeader *multipart.FileHeader, ) *PutArtifactResponse DownloadPackageFile(ctx context.Context, info pythontype.ArtifactInfo) *GetArtifactResponse } // Controller handles Python package operations. type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider // TODO: Cleanup and initiate at other place local python.LocalRegistry proxy python.Proxy quarantineFinder quarantine.Finder } // NewController creates a new Python controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local python.LocalRegistry, proxy python.Proxy, quarantineFinder quarantine.Finder, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, imageDao: imageDao, artifactDao: artifactDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, proxy: proxy, quarantineFinder: quarantineFinder, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/python/upload_package.go
registry/app/api/controller/pkg/python/upload_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package python import ( "context" "fmt" "mime/multipart" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/response" pythontype "github.com/harness/gitness/registry/app/pkg/types/python" registrytypes "github.com/harness/gitness/registry/types" ) // UploadPackageFile FIXME: Extract this upload function for all types of packageTypes // uploads the package file to the storage. func (c *controller) UploadPackageFile( ctx context.Context, info pythontype.ArtifactInfo, file multipart.File, fileHeader *multipart.FileHeader, ) *PutArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID info.Registry = registry pythonRegistry, ok := a.(python.Registry) if !ok { return &PutArtifactResponse{ BaseResponse{ Error: fmt.Errorf("invalid registry type: expected python.Registry"), ResponseHeaders: nil, }, "", } } headers, sha256, err := pythonRegistry.UploadPackageFile(ctx, info, file, fileHeader.Filename) return &PutArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: headers, }, sha256, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) putResponse, ok := result.(*PutArtifactResponse) if !ok { return &PutArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: nil, }, "", } } return putResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/python/download.go
registry/app/api/controller/pkg/python/download.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package python import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/python" "github.com/harness/gitness/registry/app/pkg/response" pythontype "github.com/harness/gitness/registry/app/pkg/types/python" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackageFile( ctx context.Context, info pythontype.ArtifactInfo, ) *GetArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) pythonRegistry, ok := a.(python.Registry) if !ok { return &GetArtifactResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected python.Registry"), nil, }, "", nil, nil, } } headers, fileReader, readCloser, redirectURL, err := pythonRegistry.DownloadPackageFile(ctx, info) return &GetArtifactResponse{ BaseResponse{ err, headers, }, redirectURL, fileReader, readCloser, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, true) if err != nil { return &GetArtifactResponse{ BaseResponse{ err, nil, }, "", nil, nil, } } getResponse, ok := result.(*GetArtifactResponse) if !ok { return &GetArtifactResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected GetArtifactResponse"), nil, }, "", nil, nil, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/generic/wire.go
registry/app/api/controller/pkg/generic/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package generic import ( "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" gitnessstore "github.com/harness/gitness/app/store" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/generic" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func DBStoreProvider( imageDao store.ImageRepository, artifactDao store.ArtifactRepository, bandwidthStatDao store.BandwidthStatRepository, downloadStatDao store.DownloadStatRepository, registryDao store.RegistryRepository, ) *DBStore { return NewDBStore(registryDao, imageDao, artifactDao, bandwidthStatDao, downloadStatDao) } func ControllerProvider( spaceStore gitnessstore.SpaceStore, authorizer authz.Authorizer, fileManager filemanager.FileManager, dBStore *DBStore, tx dbtx.Transactor, spaceFinder refcache.SpaceFinder, local generic.LocalRegistry, proxy generic.Proxy, quarantineFinder quarantine.Finder, ) *Controller { return NewController(spaceStore, authorizer, fileManager, dBStore, tx, spaceFinder, local, proxy, quarantineFinder) } var DBStoreSet = wire.NewSet(DBStoreProvider) var ControllerSet = wire.NewSet(ControllerProvider) var WireSet = wire.NewSet(ControllerSet, DBStoreSet)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/generic/response.go
registry/app/api/controller/pkg/generic/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package generic import ( "io" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*HeadArtifactResponse)(nil) var _ response.Response = (*GetArtifactResponse)(nil) var _ response.Response = (*PutArtifactResponse)(nil) var _ response.Response = (*DeleteArtifactResponse)(nil) type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type HeadArtifactResponse struct { BaseResponse } type GetArtifactResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type PutArtifactResponse struct { BaseResponse Sha256 string } type DeleteArtifactResponse struct { BaseResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/generic/v2.go
registry/app/api/controller/pkg/generic/v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package generic import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" generic2 "github.com/harness/gitness/registry/app/pkg/generic" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/generic" registrytypes "github.com/harness/gitness/registry/types" ) func (c Controller) DownloadFile( ctx context.Context, info generic.ArtifactInfo, filePath string, ) *GetArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) genericRegistry, ok := a.(generic2.Registry) if !ok { return &GetArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid registry type: expected generic.Registry, got %T", a), }, } } headers, fileReader, readCloser, redirectURL, err := genericRegistry.DownloadFile(ctx, info, filePath) return &GetArtifactResponse{ BaseResponse: BaseResponse{ Error: err, ResponseHeaders: headers, }, RedirectURL: redirectURL, Body: fileReader, ReadCloser: readCloser, } } result, err := base.ProxyWrapper(ctx, c.DBStore.RegistryDao, c.quarantineFinder, f, info, true) if err != nil { return &GetArtifactResponse{ BaseResponse: BaseResponse{ Error: err, }, } } getResponse, ok := result.(*GetArtifactResponse) if !ok { return &GetArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected GetArtifactResponse, got %T", result), }, } } return getResponse } func (c Controller) HeadFile( ctx context.Context, info generic.ArtifactInfo, filePath string, ) *HeadArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) genericRegistry, ok := a.(generic2.Registry) if !ok { return &HeadArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid registry type: expected generic.Registry, got %T", a), }, } } headers, err := genericRegistry.HeadFile(ctx, info, filePath) return &HeadArtifactResponse{ BaseResponse: BaseResponse{ Error: err, ResponseHeaders: headers, }, } } result, err := base.ProxyWrapper(ctx, c.DBStore.RegistryDao, c.quarantineFinder, f, info, false) if err != nil { return &HeadArtifactResponse{ BaseResponse: BaseResponse{ Error: err, }, } } headResponse, ok := result.(*HeadArtifactResponse) if !ok { return &HeadArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected HeadArtifactResponse, got %T", result), }, } } return headResponse } func (c Controller) DeleteFile(ctx context.Context, info generic.ArtifactInfo) *DeleteArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) genericRegistry, ok := a.(generic2.Registry) if !ok { return &DeleteArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid registry type: expected generic.Registry, got %T", a), }, } } headers, err := genericRegistry.DeleteFile(ctx, info) return &DeleteArtifactResponse{ BaseResponse: BaseResponse{ Error: err, ResponseHeaders: headers, }, } } result, err := base.NoProxyWrapper(ctx, c.DBStore.RegistryDao, f, info) if err != nil { return &DeleteArtifactResponse{ BaseResponse: BaseResponse{ Error: err, }, } } deleteArtifactResponse, ok := result.(*DeleteArtifactResponse) if !ok { return &DeleteArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected DeleteArtifactResponse, got %T", result), }, } } return deleteArtifactResponse } func (c Controller) PutFile( ctx context.Context, info generic.ArtifactInfo, reader io.ReadCloser, contentType string, ) *PutArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) genericRegistry, ok := a.(generic2.Registry) if !ok { return &PutArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid registry type: expected generic.Registry, got %T", a), }, } } headers, sha256, err := genericRegistry.PutFile(ctx, info, reader, contentType) return &PutArtifactResponse{ BaseResponse: BaseResponse{ Error: err, ResponseHeaders: headers, }, Sha256: sha256, } } result, err := base.NoProxyWrapper(ctx, c.DBStore.RegistryDao, f, info) if err != nil { return &PutArtifactResponse{ BaseResponse: BaseResponse{ Error: err, }, } } putArtifactResponse, ok := result.(*PutArtifactResponse) if !ok { return &PutArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected PutArtifactResponse, got %T", result), }, } } return putArtifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/generic/utils.go
registry/app/api/controller/pkg/generic/utils.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package generic import ( "errors" "fmt" "regexp" ) const ( duplicateFileError = "file: [%s] with Artifact: [%s], Version: [%s] and registry: [%s] already exist" filenameRegex = `^[a-zA-Z0-9][a-zA-Z0-9._~@,/-]*[a-zA-Z0-9]$` regNameFormat = "registry : [%s]" ) // ErrDuplicateFile is returned when a file already exists in the registry. var ErrDuplicateFile = errors.New("duplicate file error") func validateFileName(filename string) error { filenameRe := regexp.MustCompile(filenameRegex) if !filenameRe.MatchString(filename) { return fmt.Errorf("invalid filename: %s", filename) } return nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/generic/controller.go
registry/app/api/controller/pkg/generic/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package generic import ( "context" "encoding/json" "errors" "fmt" "io" "mime/multipart" "net/http" "path" "strings" "time" "github.com/harness/gitness/app/api/request" "github.com/harness/gitness/app/auth/authz" "github.com/harness/gitness/app/services/refcache" corestore "github.com/harness/gitness/app/store" "github.com/harness/gitness/registry/app/dist_temp/errcode" "github.com/harness/gitness/registry/app/metadata" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/generic" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/storage" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/registry/types" "github.com/harness/gitness/store/database/dbtx" "github.com/harness/gitness/types/enum" ) type Controller struct { SpaceStore corestore.SpaceStore Authorizer authz.Authorizer DBStore *DBStore fileManager filemanager.FileManager tx dbtx.Transactor spaceFinder refcache.SpaceFinder local generic.LocalRegistry proxy generic.Proxy quarantineFinder quarantine.Finder } type DBStore struct { RegistryDao store.RegistryRepository ImageDao store.ImageRepository ArtifactDao store.ArtifactRepository TagDao store.TagRepository BandwidthStatDao store.BandwidthStatRepository DownloadStatDao store.DownloadStatRepository } func NewController( spaceStore corestore.SpaceStore, authorizer authz.Authorizer, fileManager filemanager.FileManager, dBStore *DBStore, tx dbtx.Transactor, spaceFinder refcache.SpaceFinder, local generic.LocalRegistry, proxy generic.Proxy, quarantineFinder quarantine.Finder, ) *Controller { return &Controller{ SpaceStore: spaceStore, Authorizer: authorizer, fileManager: fileManager, DBStore: dBStore, tx: tx, spaceFinder: spaceFinder, local: local, proxy: proxy, quarantineFinder: quarantineFinder, } } func NewDBStore( registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, bandwidthStatDao store.BandwidthStatRepository, downloadStatDao store.DownloadStatRepository, ) *DBStore { return &DBStore{ RegistryDao: registryDao, ImageDao: imageDao, ArtifactDao: artifactDao, BandwidthStatDao: bandwidthStatDao, DownloadStatDao: downloadStatDao, } } func (c Controller) UploadArtifact( ctx context.Context, info pkg.GenericArtifactInfo, //nolint:staticcheck r *http.Request, ) (*commons.ResponseHeaders, string, errcode.Error) { responseHeaders := &commons.ResponseHeaders{ Headers: make(map[string]string), Code: 0, } err := pkg.GetRegistryCheckAccess(ctx, c.Authorizer, c.spaceFinder, info.ParentID, *info.ArtifactInfo, enum.PermissionArtifactsUpload) if err != nil { return nil, "", errcode.ErrCodeDenied.WithDetail(err) } reader, err := r.MultipartReader() if err != nil { return nil, "", errcode.ErrCodeUnknown.WithDetail(err) } fileInfo, err := c.UploadFile(ctx, reader, &info) if errors.Is(err, ErrDuplicateFile) { return nil, "", errcode.ErrCodeInvalidRequest.WithDetail(err) } if err != nil { return responseHeaders, "", errcode.ErrCodeUnknown.WithDetail(err) } err = c.tx.WithTx( ctx, func(ctx context.Context) error { image := &types.Image{ Name: info.Image, RegistryID: info.RegistryID, Enabled: true, } err := c.DBStore.ImageDao.CreateOrUpdate(ctx, image) if err != nil { return fmt.Errorf("failed to create image for artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } dbArtifact, err := c.DBStore.ArtifactDao.GetByName(ctx, image.ID, info.Version) if err != nil && !strings.Contains(err.Error(), "resource not found") { return fmt.Errorf("failed to fetch artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } metadata := &metadata.GenericMetadata{ Description: info.Description, } err2 := c.updateMetadata(dbArtifact, metadata, info, fileInfo) if err2 != nil { return fmt.Errorf("failed to update metadata for artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } metadataJSON, err := json.Marshal(metadata) if err != nil { return fmt.Errorf("failed to parse metadata for artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } _, err = c.DBStore.ArtifactDao.CreateOrUpdate(ctx, &types.Artifact{ ImageID: image.ID, Version: info.Version, Metadata: metadataJSON, }) if err != nil { return fmt.Errorf("failed to create artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } return nil }) if err != nil { return responseHeaders, "", errcode.ErrCodeUnknown.WithDetail(err) } responseHeaders.Code = http.StatusCreated return responseHeaders, fileInfo.Sha256, errcode.Error{} } func (c Controller) updateMetadata( dbArtifact *types.Artifact, metadataInput *metadata.GenericMetadata, info pkg.GenericArtifactInfo, fileInfo types.FileInfo, //nolint:staticcheck ) error { var files []metadata.File if dbArtifact != nil { err := json.Unmarshal(dbArtifact.Metadata, metadataInput) if err != nil { return fmt.Errorf("failed to get metadata for artifact : [%s] with registry : [%s]", info.Image, info.RegIdentifier) } fileExist := false files = metadataInput.Files for _, file := range files { if file.Filename == fileInfo.Filename { fileExist = true } } if !fileExist { files = append(files, metadata.File{ Size: fileInfo.Size, Filename: fileInfo.Filename, CreatedAt: time.Now().UnixMilli(), }) metadataInput.Files = files metadataInput.FileCount++ metadataInput.Size += fileInfo.Size } } else { files = append(files, metadata.File{ Size: fileInfo.Size, Filename: fileInfo.Filename, CreatedAt: time.Now().UnixMilli(), }) metadataInput.Files = files metadataInput.FileCount++ metadataInput.Size += fileInfo.Size } return nil } func (c Controller) PullArtifact(ctx context.Context, info pkg.GenericArtifactInfo) ( //nolint:staticcheck *commons.ResponseHeaders, *storage.FileReader, string, errcode.Error, ) { responseHeaders := &commons.ResponseHeaders{ Headers: make(map[string]string), Code: 0, } err := pkg.GetRegistryCheckAccess(ctx, c.Authorizer, c.spaceFinder, info.ParentID, *info.ArtifactInfo, enum.PermissionArtifactsDownload) if err != nil { return nil, nil, "", errcode.ErrCodeDenied.WithDetail(err) } path := "/" + info.Image + "/" + info.Version + "/" + info.FileName fileReader, _, redirectURL, err := c.fileManager.DownloadFile(ctx, path, info.RegistryID, info.RegIdentifier, info.RootIdentifier, true) if err != nil { return responseHeaders, nil, "", errcode.ErrCodeRootNotFound.WithDetail(err) } responseHeaders.Code = http.StatusOK return responseHeaders, fileReader, redirectURL, errcode.Error{} } func (c Controller) CheckIfFileAlreadyExist(ctx context.Context, info pkg.GenericArtifactInfo) error { //nolint:staticcheck image, err := c.DBStore.ImageDao.GetByName(ctx, info.RegistryID, info.Image) if err != nil && !strings.Contains(err.Error(), "resource not found") { return fmt.Errorf("failed to fetch the image for artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } if image == nil { return nil } dbArtifact, err := c.DBStore.ArtifactDao.GetByName(ctx, image.ID, info.Version) if err != nil && !strings.Contains(err.Error(), "resource not found") { return fmt.Errorf("failed to fetch artifact : [%s] with "+ regNameFormat, info.Image, info.RegIdentifier) } if dbArtifact == nil { return nil } metadata := &metadata.GenericMetadata{} err = json.Unmarshal(dbArtifact.Metadata, metadata) if err == nil { for _, file := range metadata.Files { if file.Filename == info.FileName { return fmt.Errorf("%w: %s", ErrDuplicateFile, fmt.Sprintf(duplicateFileError, info.FileName, info.Image, info.Version, info.RegIdentifier)) } } } return nil } func (c Controller) ParseAndUploadToTmp( ctx context.Context, reader *multipart.Reader, info pkg.GenericArtifactInfo, fileToFind string, //nolint:staticcheck formKeys []string, ) (types.FileInfo, string, map[string]string, error) { formValues := make(map[string]string) var fileInfo types.FileInfo var filename string // Track which keys we still need to find keysToFind := make(map[string]bool) for _, key := range formKeys { keysToFind[key] = true } for { part, err := reader.NextPart() if errors.Is(err, io.EOF) { break } if err != nil { return types.FileInfo{}, "", formValues, err } formName := part.FormName() // Check if this is the file part we're looking for if formName == fileToFind { fileInfo, filename, err = c.fileManager.UploadTempFile(ctx, info.RootIdentifier, nil, "", part) if err != nil { return types.FileInfo{}, "", formValues, err } continue } // Check if this is one of the form values we're looking for if _, ok := keysToFind[formName]; !ok { // Not a key we're looking for part.Close() continue } // Read the form value (these are typically small) var valueBytes []byte buffer := make([]byte, 1024) for { n, err := part.Read(buffer) if n > 0 { valueBytes = append(valueBytes, buffer[:n]...) } if errors.Is(err, io.EOF) { break } if err != nil { return types.FileInfo{}, "", formValues, fmt.Errorf("error reading form value: %w", err) } } formValues[formName] = string(valueBytes) delete(keysToFind, formName) part.Close() // If we've found all form keys and the file (if needed), we can stop if len(keysToFind) == 0 { break } } // If fileToFind was provided but not found, return an error if fileToFind != "" && filename == "" { return types.FileInfo{}, "", formValues, fmt.Errorf("file part with key '%s' not found", fileToFind) } return fileInfo, filename, formValues, nil } func (c Controller) UploadFile( ctx context.Context, reader *multipart.Reader, info *pkg.GenericArtifactInfo, //nolint:staticcheck ) (types.FileInfo, error) { fileInfo, tmpFileName, formValues, err := c.ParseAndUploadToTmp(ctx, reader, *info, "file", []string{"filename", "description"}) if err != nil { return types.FileInfo{}, fmt.Errorf("failed to Parse/upload "+ "the generic artifact file to temp location: [%s] with error: [%w] ", tmpFileName, err) } if err := validateFileName(formValues["filename"]); err != nil { return types.FileInfo{}, fmt.Errorf("invalid file name for generic artifact file: [%s]", formValues["filename"]) } info.FileName = formValues["filename"] info.Description = formValues["description"] fileInfo.Filename = info.FileName err = c.CheckIfFileAlreadyExist(ctx, *info) if err != nil { return types.FileInfo{}, fmt.Errorf("file already exist: [%w] ", err) } session, _ := request.AuthSessionFrom(ctx) filePath := path.Join(info.Image, info.Version, fileInfo.Filename) err = c.fileManager.MoveTempFile(ctx, filePath, info.RegistryID, info.RootParentID, info.RootIdentifier, fileInfo, tmpFileName, session.Principal.ID) if err != nil { return types.FileInfo{}, err } return fileInfo, err }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/pre_upload.go
registry/app/api/controller/pkg/huggingface/pre_upload.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) PreUpload(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *PreUploadResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &PreUploadResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, preUploadResponse, err := hfRegistry.PreUpload(ctx, info, body) return &PreUploadResponse{ BaseResponse{ err, headers, }, preUploadResponse, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &PreUploadResponse{ BaseResponse{ err, nil, }, nil, } } preUploadResponse, ok := result.(*PreUploadResponse) if !ok { return &PreUploadResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected PreUploadResponse"), nil, }, nil, } } return preUploadResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/lfs_upload.go
registry/app/api/controller/pkg/huggingface/lfs_upload.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) LfsUpload(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *LfsUploadResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID hfRegistry, ok := a.(huggingface.Registry) if !ok { return &LfsUploadResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, lfsUploadResponse, err := hfRegistry.LfsUpload(ctx, info, body) return &LfsUploadResponse{ BaseResponse{ err, headers, }, lfsUploadResponse, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &LfsUploadResponse{ BaseResponse{ err, nil, }, nil, } } lfsUploadResponse, ok := result.(*LfsUploadResponse) if !ok { return &LfsUploadResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected LfsUploadResponse"), nil, }, nil, } } return lfsUploadResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/wire.go
registry/app/api/controller/pkg/huggingface/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) // WireSet provides a wire set for the huggingface package. var WireSet = wire.NewSet( ProvideController, ) // ProvideController provides a huggingface controller. func ProvideController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local huggingface.LocalRegistry, quarantineFinder quarantine.Finder, ) Controller { return NewController( proxyStore, registryDao, imageDao, artifactDao, fileManager, tx, urlProvider, local, quarantineFinder, ) }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/commit_revision.go
registry/app/api/controller/pkg/huggingface/commit_revision.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) // CommitEntry represents a single line in the commits input. // Make sure these structs are defined within this package or imported correctly. // If they are already defined in types.go or similar in this package, remove these definitions. func (c *controller) CommitRevision( ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser, ) *CommitRevisionResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID hfRegistry, ok := a.(huggingface.Registry) if !ok { return &CommitRevisionResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, commitRevisionResponse, err := hfRegistry.CommitRevision(ctx, info, body) return &CommitRevisionResponse{ BaseResponse{ err, headers, }, commitRevisionResponse, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &CommitRevisionResponse{ BaseResponse{ err, nil, }, nil, } } commitRevisionResponse, ok := result.(*CommitRevisionResponse) if !ok { return &CommitRevisionResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected CommitRevisionResponse"), nil, }, nil, } } return commitRevisionResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/response.go
registry/app/api/controller/pkg/huggingface/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" huggingfacetype "github.com/harness/gitness/registry/app/pkg/types/huggingface" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*ValidateYamlResponse)(nil) var _ response.Response = (*PreUploadResponse)(nil) var _ response.Response = (*RevisionInfoResponse)(nil) var _ response.Response = (*LfsInfoResponse)(nil) var _ response.Response = (*LfsVerifyResponse)(nil) var _ response.Response = (*LfsUploadResponse)(nil) var _ response.Response = (*HeadFileResponse)(nil) var _ response.Response = (*DownloadFileResponse)(nil) // Response is the base response interface. type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type ValidateYamlResponse struct { BaseResponse Response *huggingfacetype.ValidateYamlResponse } type PreUploadResponse struct { BaseResponse Response *huggingfacetype.PreUploadResponse } // RevisionInfoResponse represents a response for revision info. type RevisionInfoResponse struct { BaseResponse Response *huggingfacetype.RevisionInfoResponse } type LfsInfoResponse struct { BaseResponse Response *huggingfacetype.LfsInfoResponse } type LfsUploadResponse struct { BaseResponse Response *huggingfacetype.LfsUploadResponse } type LfsVerifyResponse struct { BaseResponse Response *huggingfacetype.LfsVerifyResponse } type CommitRevisionResponse struct { BaseResponse Response *huggingfacetype.CommitRevisionResponse } type HeadFileResponse struct { BaseResponse } type DownloadFileResponse struct { BaseResponse RedirectURL string Body *storage.FileReader }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/validate_yaml.go
registry/app/api/controller/pkg/huggingface/validate_yaml.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) ValidateYaml( ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser, ) *ValidateYamlResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &ValidateYamlResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, validateYamlResponse, err := hfRegistry.ValidateYaml(ctx, info, body) return &ValidateYamlResponse{ BaseResponse{ err, headers, }, validateYamlResponse, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &ValidateYamlResponse{ BaseResponse{ err, nil, }, nil, } } validateYamlResponse, ok := result.(*ValidateYamlResponse) if !ok { return &ValidateYamlResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected ValidateYamlResponse"), nil, }, nil, } } return validateYamlResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/revision_info.go
registry/app/api/controller/pkg/huggingface/revision_info.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) RevisionInfo( ctx context.Context, info hftype.ArtifactInfo, queryParams map[string][]string, ) *RevisionInfoResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &RevisionInfoResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, revisionInfoResponse, err := hfRegistry.RevisionInfo(ctx, info, queryParams) return &RevisionInfoResponse{ BaseResponse{ err, headers, }, revisionInfoResponse, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &RevisionInfoResponse{ BaseResponse{ err, nil, }, nil, } } revisionInfoResponse, ok := result.(*RevisionInfoResponse) if !ok { return &RevisionInfoResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected RevisionInfoResponse"), nil, }, nil, } } return revisionInfoResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/download_file.go
registry/app/api/controller/pkg/huggingface/download_file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadFile( ctx context.Context, info hftype.ArtifactInfo, fileName string, ) *DownloadFileResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &DownloadFileResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, "", nil, } } headers, body, redirectURL, err := hfRegistry.DownloadFile(ctx, info, fileName) return &DownloadFileResponse{ BaseResponse{ err, headers, }, redirectURL, body, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, true) if err != nil { return &DownloadFileResponse{ BaseResponse{ err, nil, }, "", nil, } } downloadFileResponse, ok := result.(*DownloadFileResponse) if !ok { return &DownloadFileResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected DownloadFileResponse"), nil, }, "", nil, } } return downloadFileResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/controller.go
registry/app/api/controller/pkg/huggingface/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "io" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/quarantine" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) // Controller defines the interface for Huggingface package operations. type Controller interface { ValidateYaml(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *ValidateYamlResponse PreUpload(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *PreUploadResponse RevisionInfo(ctx context.Context, info hftype.ArtifactInfo, queryParams map[string][]string) *RevisionInfoResponse LfsInfo(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser, token string) *LfsInfoResponse LfsVerify(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *LfsVerifyResponse CommitRevision(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *CommitRevisionResponse LfsUpload(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *LfsUploadResponse HeadFile(ctx context.Context, info hftype.ArtifactInfo, fileName string) *HeadFileResponse DownloadFile(ctx context.Context, info hftype.ArtifactInfo, fileName string) *DownloadFileResponse } // controller implements the Controller interface. type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider local huggingface.LocalRegistry quarantineFinder quarantine.Finder } // NewController creates a new Huggingface controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local huggingface.LocalRegistry, quarantineFinder quarantine.Finder, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, imageDao: imageDao, artifactDao: artifactDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, quarantineFinder: quarantineFinder, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/head_file.go
registry/app/api/controller/pkg/huggingface/head_file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) HeadFile( ctx context.Context, info hftype.ArtifactInfo, fileName string, ) *HeadFileResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &HeadFileResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, } } headers, err := hfRegistry.HeadFile(ctx, info, fileName) return &HeadFileResponse{ BaseResponse{ err, headers, }, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &HeadFileResponse{ BaseResponse{ err, nil, }, } } headFileResponse, ok := result.(*HeadFileResponse) if !ok { return &HeadFileResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected HeadFileResponse"), nil, }, } } return headFileResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/lfs_verify.go
registry/app/api/controller/pkg/huggingface/lfs_verify.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) LfsVerify(ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser) *LfsVerifyResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &LfsVerifyResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, lfsVerifyResponse, err := hfRegistry.LfsVerify(ctx, info, body) return &LfsVerifyResponse{ BaseResponse{ err, headers, }, lfsVerifyResponse, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &LfsVerifyResponse{ BaseResponse{ err, nil, }, nil, } } lfsVerifyResponse, ok := result.(*LfsVerifyResponse) if !ok { return &LfsVerifyResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected LfsVerifyResponse"), nil, }, nil, } } return lfsVerifyResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/huggingface/lfs_info.go
registry/app/api/controller/pkg/huggingface/lfs_info.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package huggingface import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/huggingface" "github.com/harness/gitness/registry/app/pkg/response" hftype "github.com/harness/gitness/registry/app/pkg/types/huggingface" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) LfsInfo( ctx context.Context, info hftype.ArtifactInfo, body io.ReadCloser, token string, ) *LfsInfoResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) hfRegistry, ok := a.(huggingface.Registry) if !ok { return &LfsInfoResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected huggingface.Registry"), nil, }, nil, } } headers, lfsInfoResponse, err := hfRegistry.LfsInfo(ctx, info, body, token) return &LfsInfoResponse{ BaseResponse{ err, headers, }, lfsInfoResponse, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &LfsInfoResponse{ BaseResponse{ err, nil, }, nil, } } lfsInfoResponse, ok := result.(*LfsInfoResponse) if !ok { return &LfsInfoResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected LfsInfoResponse"), nil, }, nil, } } return lfsInfoResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/rpm/wire.go
registry/app/api/controller/pkg/rpm/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm import ( urlprovider "github.com/harness/gitness/app/url" registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/rpm" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func ControllerProvider( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local rpm.LocalRegistry, proxy rpm.Proxy, postProcessingReporter *registrypostprocessingevents.Reporter, ) Controller { return NewController( proxyStore, registryDao, imageDao, artifactDao, fileManager, tx, urlProvider, local, proxy, proxyStore, postProcessingReporter, ) } var ControllerSet = wire.NewSet(ControllerProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/rpm/response.go
registry/app/api/controller/pkg/rpm/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm import ( "io" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*GetRepoDataResponse)(nil) var _ response.Response = (*GetArtifactResponse)(nil) var _ response.Response = (*PutArtifactResponse)(nil) type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type GetRepoDataResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type GetArtifactResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type PutArtifactResponse struct { BaseResponse Sha256 string }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/rpm/metadata.go
registry/app/api/controller/pkg/rpm/metadata.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/rpm" rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm" ) // GetRepoData represents the metadata of a RPM package. func (c *controller) GetRepoData(ctx context.Context, info rpmtype.ArtifactInfo, fileName string) *GetRepoDataResponse { a := base.GetArtifactRegistry(info.Registry) rpmRegistry, ok := a.(rpm.Registry) if !ok { return &GetRepoDataResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected rpm.Registry"), nil, }, "", nil, nil, } } responseHeaders, fileReader, _, redirectURL, err := rpmRegistry.GetRepoData(ctx, info, fileName) return &GetRepoDataResponse{ BaseResponse{ err, responseHeaders, }, redirectURL, fileReader, nil, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/rpm/controller.go
registry/app/api/controller/pkg/rpm/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm import ( "context" "mime/multipart" urlprovider "github.com/harness/gitness/app/url" registrypostprocessingevents "github.com/harness/gitness/registry/app/events/asyncprocessing" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/rpm" rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) type Controller interface { UploadPackageFile( ctx context.Context, info rpmtype.ArtifactInfo, file multipart.Part, fileName string, ) *PutArtifactResponse DownloadPackageFile( ctx context.Context, info rpmtype.ArtifactInfo, ) *GetArtifactResponse GetRepoData( ctx context.Context, info rpmtype.ArtifactInfo, fileName string, ) *GetRepoDataResponse } // Controller handles RPM package operations. type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider local rpm.LocalRegistry proxy rpm.Proxy upstreamProxyStore store.UpstreamProxyConfigRepository postProcessingReporter *registrypostprocessingevents.Reporter } // NewController creates a new RPM controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local rpm.LocalRegistry, proxy rpm.Proxy, upstreamProxyStore store.UpstreamProxyConfigRepository, postProcessingReporter *registrypostprocessingevents.Reporter, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, imageDao: imageDao, artifactDao: artifactDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, proxy: proxy, upstreamProxyStore: upstreamProxyStore, postProcessingReporter: postProcessingReporter, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/rpm/upload_package.go
registry/app/api/controller/pkg/rpm/upload_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm import ( "context" "fmt" "mime/multipart" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/rpm" rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm" registrytypes "github.com/harness/gitness/registry/types" ) // UploadPackageFile uploads the package file to the storage. func (c *controller) UploadPackageFile( ctx context.Context, info rpmtype.ArtifactInfo, file multipart.Part, fileName string, ) *PutArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID rpmRegistry, ok := a.(rpm.Registry) if !ok { return &PutArtifactResponse{ BaseResponse{ Error: fmt.Errorf("invalid registry type: expected rpm.Registry"), ResponseHeaders: nil, }, "", } } headers, sha256, err := rpmRegistry.UploadPackageFile(ctx, info, &file, fileName) return &PutArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: headers, }, sha256, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) rs, ok := result.(*PutArtifactResponse) if !ok { return &PutArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: nil, }, "", } } return rs }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/rpm/download.go
registry/app/api/controller/pkg/rpm/download.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rpm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/rpm" rpmtype "github.com/harness/gitness/registry/app/pkg/types/rpm" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackageFile( ctx context.Context, info rpmtype.ArtifactInfo, ) *GetArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID info.Registry = registry rpmRegistry, ok := a.(rpm.Registry) if !ok { return &GetArtifactResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected rpm.Registry"), nil, }, "", nil, nil, } } headers, fileReader, readCloser, redirectURL, err := rpmRegistry.DownloadPackageFile(ctx, info) return &GetArtifactResponse{ BaseResponse{ err, headers, }, redirectURL, fileReader, readCloser, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &GetArtifactResponse{ BaseResponse{ err, nil, }, "", nil, nil, } } getResponse, ok := result.(*GetArtifactResponse) if !ok { return &GetArtifactResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected GetArtifactResponse"), nil, }, "", nil, nil, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/wire.go
registry/app/api/controller/pkg/gopackage/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func ControllerProvider( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, registryFinder refcache.RegistryFinder, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local gopackage.LocalRegistry, proxy gopackage.Proxy, quarantineFinder quarantine.Finder, ) Controller { return NewController( proxyStore, registryDao, registryFinder, imageDao, artifactDao, fileManager, tx, urlProvider, local, proxy, quarantineFinder, ) } var ControllerSet = wire.NewSet(ControllerProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/response.go
registry/app/api/controller/pkg/gopackage/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "io" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*DownloadFileResponse)(nil) type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type DownloadFileResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type UploadFileResponse struct { BaseResponse `json:"-"` Status string `json:"status,omitempty"` Image string `json:"image,omitempty"` Version string `json:"version,omitempty"` } type RegeneratePackageIndexResponse struct { BaseResponse `json:"-"` Ok bool `json:"ok,omitempty"` } type RegeneratePackageMetadataResponse struct { BaseResponse `json:"-"` Ok bool `json:"ok,omitempty"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/regenerate_pacakge_metadata.go
registry/app/api/controller/pkg/gopackage/regenerate_pacakge_metadata.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/response" gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) RegeneratePackageMetadata( ctx context.Context, info *gopackagetype.ArtifactInfo, ) *RegeneratePackageMetadataResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) goRegistry, ok := a.(gopackage.Registry) if !ok { return c.getRegeneratePackageMetadataErrorResponse( fmt.Errorf("invalid registry type: expected go.Registry"), nil, ) } headers, err := goRegistry.RegeneratePackageMetadata(ctx, *info) return c.getRegeneratePackageMetadataErrorResponse( err, headers, ) } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return c.getRegeneratePackageMetadataErrorResponse( err, nil, ) } putResponse, ok := result.(*RegeneratePackageMetadataResponse) if !ok { return c.getRegeneratePackageMetadataErrorResponse( fmt.Errorf("invalid response type: expected RegeneratePackageMetadataResponse"), nil, ) } putResponse.Ok = true return putResponse } func (c *controller) getRegeneratePackageMetadataErrorResponse( err error, headers *commons.ResponseHeaders, ) *RegeneratePackageMetadataResponse { return &RegeneratePackageMetadataResponse{ BaseResponse: BaseResponse{ err, headers, }, Ok: false, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/download_package_file.go
registry/app/api/controller/pkg/gopackage/download_package_file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/response" gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackageFile( ctx context.Context, info *gopackagetype.ArtifactInfo, ) *DownloadFileResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) gopackageRegistry, ok := a.(gopackage.Registry) if !ok { return c.getDownloadPackageFileErrorResponse( fmt.Errorf("invalid registry type: expected gopackage.Registry"), nil, ) } headers, fileReader, readCloser, redirectURL, err := gopackageRegistry.DownloadPackageFile( ctx, *info, ) return &DownloadFileResponse{ BaseResponse: BaseResponse{ err, headers, }, RedirectURL: redirectURL, Body: fileReader, ReadCloser: readCloser, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, true) if err != nil { return c.getDownloadPackageFileErrorResponse( err, nil, ) } getResponse, ok := result.(*DownloadFileResponse) if !ok { return c.getDownloadPackageFileErrorResponse( fmt.Errorf("invalid response type: expected DownloadFileResponse"), nil, ) } return getResponse } func (c *controller) getDownloadPackageFileErrorResponse( err error, headers *commons.ResponseHeaders, ) *DownloadFileResponse { return &DownloadFileResponse{ BaseResponse: BaseResponse{ err, headers, }, RedirectURL: "", Body: nil, ReadCloser: nil, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/regenerate_pacakge_index.go
registry/app/api/controller/pkg/gopackage/regenerate_pacakge_index.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/response" gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) RegeneratePackageIndex( ctx context.Context, info *gopackagetype.ArtifactInfo, ) *RegeneratePackageIndexResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) goRegistry, ok := a.(gopackage.Registry) if !ok { return c.getRegeneratePackageIndexErrorResponse( fmt.Errorf("invalid registry type: expected go.Registry"), nil, ) } headers, err := goRegistry.RegeneratePackageIndex(ctx, *info) return c.getRegeneratePackageIndexErrorResponse( err, headers, ) } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return c.getRegeneratePackageIndexErrorResponse( err, nil, ) } putResponse, ok := result.(*RegeneratePackageIndexResponse) if !ok { return c.getRegeneratePackageIndexErrorResponse( fmt.Errorf("invalid response type: expected RegeneratePackageIndexResponse"), nil, ) } putResponse.Ok = true return putResponse } func (c *controller) getRegeneratePackageIndexErrorResponse( err error, headers *commons.ResponseHeaders, ) *RegeneratePackageIndexResponse { return &RegeneratePackageIndexResponse{ BaseResponse: BaseResponse{ err, headers, }, Ok: false, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/controller.go
registry/app/api/controller/pkg/gopackage/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "context" "io" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/quarantine" gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage" "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) type Controller interface { UploadPackage( ctx context.Context, info *gopackagetype.ArtifactInfo, mod io.ReadCloser, zip io.ReadCloser, ) *UploadFileResponse DownloadPackageFile( ctx context.Context, info *gopackagetype.ArtifactInfo, ) *DownloadFileResponse RegeneratePackageIndex( ctx context.Context, info *gopackagetype.ArtifactInfo, ) *RegeneratePackageIndexResponse RegeneratePackageMetadata( ctx context.Context, info *gopackagetype.ArtifactInfo, ) *RegeneratePackageMetadataResponse } type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository registryFinder refcache.RegistryFinder imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider local gopackage.LocalRegistry proxy gopackage.Proxy quarantineFinder quarantine.Finder } // NewController creates a new Go Package controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, registryFinder refcache.RegistryFinder, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local gopackage.LocalRegistry, proxy gopackage.Proxy, quarantineFinder quarantine.Finder, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, registryFinder: registryFinder, imageDao: imageDao, artifactDao: artifactDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, proxy: proxy, quarantineFinder: quarantineFinder, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/gopackage/upload_package.go
registry/app/api/controller/pkg/gopackage/upload_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gopackage import ( "context" "fmt" "io" "net/http" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/gopackage" "github.com/harness/gitness/registry/app/pkg/response" gopackagetype "github.com/harness/gitness/registry/app/pkg/types/gopackage" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) UploadPackage( ctx context.Context, info *gopackagetype.ArtifactInfo, mod io.ReadCloser, zip io.ReadCloser, ) *UploadFileResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID gopackageRegistry, ok := a.(gopackage.Registry) if !ok { return c.getUploadPackageFileErrorResponse( fmt.Errorf("invalid registry type: expected gopackage.Registry"), nil, ) } headers, err := gopackageRegistry.UploadPackage(ctx, *info, mod, zip) return c.getUploadPackageFileErrorResponse( err, headers, ) } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return c.getUploadPackageFileErrorResponse( err, nil, ) } putResponse, ok := result.(*UploadFileResponse) if !ok { return c.getUploadPackageFileErrorResponse( fmt.Errorf("invalid response type: expected BaseResponse"), nil, ) } putResponse.ResponseHeaders.Code = http.StatusOK putResponse.Status = "success" putResponse.Image = info.Image putResponse.Version = info.Version return putResponse } func (c *controller) getUploadPackageFileErrorResponse( err error, headers *commons.ResponseHeaders, ) *UploadFileResponse { return &UploadFileResponse{ BaseResponse: BaseResponse{ err, headers, }, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/get_package_version_metadata_v2.go
registry/app/api/controller/pkg/nuget/get_package_version_metadata_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) GetPackageVersionMetadataV2( ctx context.Context, info nugettype.ArtifactInfo, ) *GetPackageVersionMetadataV2Response { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetPackageVersionMetadataV2Response{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } packageMetadata, err := nugetRegistry.GetPackageVersionMetadataV2(ctx, info) return &GetPackageVersionMetadataV2Response{ BaseResponse{ err, nil, }, packageMetadata, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &GetPackageVersionMetadataV2Response{ BaseResponse{ err, nil, }, nil, } } packageMetadataResponse, ok := result.(*GetPackageVersionMetadataV2Response) if !ok { return &GetPackageVersionMetadataV2Response{ BaseResponse{ fmt.Errorf("invalid response type: expected GetPackageVersionMetadataV2Response"), nil, }, nil, } } return packageMetadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/wire.go
registry/app/api/controller/pkg/nuget/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func ControllerProvider( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local nuget.LocalRegistry, proxy nuget.Proxy, quarantineFinder quarantine.Finder, ) Controller { return NewController(proxyStore, registryDao, imageDao, artifactDao, fileManager, tx, urlProvider, local, proxy, quarantineFinder) } var ControllerSet = wire.NewSet(ControllerProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/get_package_version_metadata.go
registry/app/api/controller/pkg/nuget/get_package_version_metadata.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) GetPackageVersionMetadata( ctx context.Context, info nugettype.ArtifactInfo, ) *GetPackageVersionMetadataResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetPackageVersionMetadataResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } packageVersionMetadata, err := nugetRegistry.GetPackageVersionMetadata(ctx, info) return &GetPackageVersionMetadataResponse{ BaseResponse{ err, nil, }, packageVersionMetadata, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &GetPackageVersionMetadataResponse{ BaseResponse{ err, nil, }, nil, } } packageVersionMetadataResponse, ok := result.(*GetPackageVersionMetadataResponse) if !ok { return &GetPackageVersionMetadataResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected GetPackageMetadataResponse"), nil, }, nil, } } return packageVersionMetadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/search_count_v2.go
registry/app/api/controller/pkg/nuget/search_count_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) CountPackageV2( ctx context.Context, info nugettype.ArtifactInfo, searchTerm string, ) *EntityCountResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &EntityCountResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, 0, } } count, err := nugetRegistry.CountPackageV2(ctx, info, searchTerm) return &EntityCountResponse{ BaseResponse{ err, nil, }, count, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &EntityCountResponse{ BaseResponse{ err, nil, }, 0, } } countResponse, ok := result.(*EntityCountResponse) if !ok { return &EntityCountResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected ListPackageVersionV2Response"), nil, }, 0, } } return countResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/list_package_version_v2.go
registry/app/api/controller/pkg/nuget/list_package_version_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) ListPackageVersionV2( ctx context.Context, info nugettype.ArtifactInfo, ) *ListPackageVersionV2Response { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &ListPackageVersionV2Response{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } feedResponse, err := nugetRegistry.ListPackageVersionV2(ctx, info) return &ListPackageVersionV2Response{ BaseResponse{ err, nil, }, feedResponse, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &ListPackageVersionV2Response{ BaseResponse{ err, nil, }, nil, } } listPackageVersionResponse, ok := result.(*ListPackageVersionV2Response) if !ok { return &ListPackageVersionV2Response{ BaseResponse{ fmt.Errorf("invalid response type: expected ListPackageVersionV2Response"), nil, }, nil, } } return listPackageVersionResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/response.go
registry/app/api/controller/pkg/nuget/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "io" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/nuget" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*GetServiceEndpointResponse)(nil) var _ response.Response = (*GetArtifactResponse)(nil) var _ response.Response = (*PutArtifactResponse)(nil) type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type GetServiceEndpointResponse struct { BaseResponse ServiceEndpoint *nuget.ServiceEndpoint } type GetServiceEndpointV2Response struct { BaseResponse ServiceEndpoint *nuget.ServiceEndpointV2 } type GetServiceMetadataV2Response struct { BaseResponse ServiceMetadata *nuget.ServiceMetadataV2 } type GetArtifactResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type PutArtifactResponse struct { BaseResponse } type DeleteArtifactResponse struct { BaseResponse } type ListPackageVersionResponse struct { BaseResponse PackageVersion *nuget.PackageVersion } type ListPackageVersionV2Response struct { BaseResponse FeedResponse *nuget.FeedResponse } type SearchPackageV2Response struct { BaseResponse FeedResponse *nuget.FeedResponse } type SearchPackageResponse struct { BaseResponse SearchResponse *nuget.SearchResultResponse } type EntityCountResponse struct { BaseResponse Count int64 } type GetPackageMetadataResponse struct { BaseResponse RegistrationResponse nuget.RegistrationResponse } type GetPackageVersionMetadataV2Response struct { BaseResponse FeedEntryResponse *nuget.FeedEntryResponse } type RegistrationResponse interface { isRegistrationResponse() // marker method } type GetPackageVersionMetadataResponse struct { BaseResponse RegistrationLeafResponse *nuget.RegistrationLeafResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/package_version_count_v2.go
registry/app/api/controller/pkg/nuget/package_version_count_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) CountPackageVersionV2( ctx context.Context, info nugettype.ArtifactInfo, ) *EntityCountResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &EntityCountResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, 0, } } count, err := nugetRegistry.CountPackageVersionV2(ctx, info) return &EntityCountResponse{ BaseResponse{ err, nil, }, count, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &EntityCountResponse{ BaseResponse{ err, nil, }, 0, } } countPackageVersionResponse, ok := result.(*EntityCountResponse) if !ok { return &EntityCountResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected ListPackageVersionV2Response"), nil, }, 0, } } return countPackageVersionResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/service_endpoint.go
registry/app/api/controller/pkg/nuget/service_endpoint.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) GetServiceEndpoint( ctx context.Context, info nugettype.ArtifactInfo, ) *GetServiceEndpointResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetServiceEndpointResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } serviceEndpoint := nugetRegistry.GetServiceEndpoint(ctx, info) return &GetServiceEndpointResponse{ BaseResponse{ nil, nil, }, serviceEndpoint, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &GetServiceEndpointResponse{ BaseResponse{ err, nil, }, nil, } } serviceEndpointResponse, ok := result.(*GetServiceEndpointResponse) if !ok { return &GetServiceEndpointResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected GetServiceEndpointResponse"), nil, }, nil, } } return serviceEndpointResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/service_metadata_v2.go
registry/app/api/controller/pkg/nuget/service_metadata_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) GetServiceMetadataV2( ctx context.Context, info nugettype.ArtifactInfo, ) *GetServiceMetadataV2Response { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetServiceMetadataV2Response{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } serviceMetadata := nugetRegistry.GetServiceMetadataV2(ctx, info) return &GetServiceMetadataV2Response{ BaseResponse{ nil, nil, }, serviceMetadata, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &GetServiceMetadataV2Response{ BaseResponse{ err, nil, }, nil, } } serviceMetadataResponse, ok := result.(*GetServiceMetadataV2Response) if !ok { return &GetServiceMetadataV2Response{ BaseResponse{ fmt.Errorf("invalid response type: expected GetServiceMetadataV2Response"), nil, }, nil, } } return serviceMetadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/search.go
registry/app/api/controller/pkg/nuget/search.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) SearchPackage( ctx context.Context, info nugettype.ArtifactInfo, searchTerm string, limit, offset int, ) *SearchPackageResponse { f := func(registry registrytypes.Registry, a pkg.Artifact, l, o int) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &SearchPackageResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } feedResponse, err := nugetRegistry.SearchPackage(ctx, info, searchTerm, l, o) return &SearchPackageResponse{ BaseResponse{ err, nil, }, feedResponse, } } aggregatedResults, totalCount, err := base.SearchPackagesProxyWrapper(ctx, c.registryDao, f, extractResponseData, info, limit, offset) if err != nil { return &SearchPackageResponse{ BaseResponse{ err, nil, }, nil, } } // Create response using the aggregated results searchResults := make([]*nugettype.SearchResult, 0, len(aggregatedResults)) for _, result := range aggregatedResults { if searchResult, ok := result.(*nugettype.SearchResult); ok { searchResults = append(searchResults, searchResult) } } searchResultResponse := &nugettype.SearchResultResponse{ TotalHits: totalCount, Data: searchResults, } return &SearchPackageResponse{ BaseResponse: BaseResponse{ Error: nil, ResponseHeaders: nil, }, SearchResponse: searchResultResponse, } } func extractResponseData(searchResponse response.Response) ([]any, int64) { var nativeResults []any var totalHits int64 if searchResp, ok := searchResponse.(*SearchPackageResponse); ok && searchResp.SearchResponse != nil { totalHits = searchResp.SearchResponse.TotalHits for _, result := range searchResp.SearchResponse.Data { nativeResults = append(nativeResults, result) } } return nativeResults, totalHits }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/delete_package.go
registry/app/api/controller/pkg/nuget/delete_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DeletePackage( ctx context.Context, info nugettype.ArtifactInfo, ) *DeleteArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &DeleteArtifactResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, } } headers, err := nugetRegistry.DeletePackage(ctx, info) return &DeleteArtifactResponse{ BaseResponse{ err, headers, }, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &DeleteArtifactResponse{ BaseResponse{ err, nil, }, } } getResponse, ok := result.(*DeleteArtifactResponse) if !ok { return &DeleteArtifactResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected DeleteArtifactResponse"), nil, }, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/list_package_version.go
registry/app/api/controller/pkg/nuget/list_package_version.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) ListPackageVersion( ctx context.Context, info nugettype.ArtifactInfo, ) *ListPackageVersionResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &ListPackageVersionResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } packageVersions, err := nugetRegistry.ListPackageVersion(ctx, info) return &ListPackageVersionResponse{ BaseResponse{ err, nil, }, packageVersions, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &ListPackageVersionResponse{ BaseResponse{ err, nil, }, nil, } } listPackageVersionResponse, ok := result.(*ListPackageVersionResponse) if !ok { return &ListPackageVersionResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected ListPackageVersionResponse"), nil, }, nil, } } return listPackageVersionResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/service_endpoint_v2.go
registry/app/api/controller/pkg/nuget/service_endpoint_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) GetServiceEndpointV2( ctx context.Context, info nugettype.ArtifactInfo, ) *GetServiceEndpointV2Response { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetServiceEndpointV2Response{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } serviceEndpoint := nugetRegistry.GetServiceEndpointV2(ctx, info) return &GetServiceEndpointV2Response{ BaseResponse{ nil, nil, }, serviceEndpoint, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &GetServiceEndpointV2Response{ BaseResponse{ err, nil, }, nil, } } serviceEndpointResponse, ok := result.(*GetServiceEndpointV2Response) if !ok { return &GetServiceEndpointV2Response{ BaseResponse{ fmt.Errorf("invalid response type: expected GetServiceEndpointV2Response"), nil, }, nil, } } return serviceEndpointResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/controller.go
registry/app/api/controller/pkg/nuget/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "io" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/quarantine" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) type Controller interface { UploadPackage( ctx context.Context, info nugettype.ArtifactInfo, fileReader io.ReadCloser, fileBundleType nuget.FileBundleType, ) *PutArtifactResponse DownloadPackage(ctx context.Context, info nugettype.ArtifactInfo) *GetArtifactResponse DeletePackage(ctx context.Context, info nugettype.ArtifactInfo) *DeleteArtifactResponse GetServiceEndpoint( ctx context.Context, info nugettype.ArtifactInfo, ) *GetServiceEndpointResponse GetServiceEndpointV2( ctx context.Context, info nugettype.ArtifactInfo, ) *GetServiceEndpointV2Response ListPackageVersion(ctx context.Context, info nugettype.ArtifactInfo) *ListPackageVersionResponse ListPackageVersionV2(ctx context.Context, info nugettype.ArtifactInfo) *ListPackageVersionV2Response GetPackageMetadata(ctx context.Context, info nugettype.ArtifactInfo) *GetPackageMetadataResponse GetPackageVersionMetadataV2(ctx context.Context, info nugettype.ArtifactInfo) *GetPackageVersionMetadataV2Response GetPackageVersionMetadata(ctx context.Context, info nugettype.ArtifactInfo) *GetPackageVersionMetadataResponse CountPackageVersionV2(ctx context.Context, info nugettype.ArtifactInfo) *EntityCountResponse SearchPackage( ctx context.Context, info nugettype.ArtifactInfo, searchTerm string, limit, offset int, ) *SearchPackageResponse SearchPackageV2( ctx context.Context, info nugettype.ArtifactInfo, searchTerm string, limit, offset int, ) *SearchPackageV2Response CountPackageV2(ctx context.Context, info nugettype.ArtifactInfo, searchTerm string) *EntityCountResponse GetServiceMetadataV2(ctx context.Context, info nugettype.ArtifactInfo) *GetServiceMetadataV2Response } // Controller handles Python package operations. type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider local nuget.LocalRegistry proxy nuget.Proxy quarantineFinder quarantine.Finder } // NewController creates a new Python controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local nuget.LocalRegistry, proxy nuget.Proxy, quarantineFinder quarantine.Finder, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, imageDao: imageDao, artifactDao: artifactDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, proxy: proxy, quarantineFinder: quarantineFinder, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/get_package_metadata.go
registry/app/api/controller/pkg/nuget/get_package_metadata.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) GetPackageMetadata( ctx context.Context, info nugettype.ArtifactInfo, ) *GetPackageMetadataResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetPackageMetadataResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } packageMetadata, err := nugetRegistry.GetPackageMetadata(ctx, info) return &GetPackageMetadataResponse{ BaseResponse{ err, nil, }, packageMetadata, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return &GetPackageMetadataResponse{ BaseResponse{ err, nil, }, nil, } } packageMetadataResponse, ok := result.(*GetPackageMetadataResponse) if !ok { return &GetPackageMetadataResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected GetPackageMetadataResponse"), nil, }, nil, } } return packageMetadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/upload_package.go
registry/app/api/controller/pkg/nuget/upload_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) UploadPackage( ctx context.Context, info nugettype.ArtifactInfo, fileReader io.ReadCloser, fileBundleType nuget.FileBundleType, ) *PutArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID nugetRegistry, ok := a.(nuget.Registry) if !ok { return &PutArtifactResponse{ BaseResponse{ Error: fmt.Errorf("invalid registry type: expected nuget.Registry"), ResponseHeaders: nil, }, } } headers, _, err := nugetRegistry.UploadPackage(ctx, info, fileReader, fileBundleType) return &PutArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: headers, }, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &PutArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: nil, }, } } uploadResponse, ok := result.(*PutArtifactResponse) if !ok { return &PutArtifactResponse{ BaseResponse{ Error: fmt.Errorf("invalid response type: expected PutArtifactResponse"), ResponseHeaders: nil, }, } } return uploadResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/search_v2.go
registry/app/api/controller/pkg/nuget/search_v2.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "encoding/xml" "fmt" "net/url" "strconv" "time" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) SearchPackageV2( ctx context.Context, info nugettype.ArtifactInfo, searchTerm string, limit, offset int, ) *SearchPackageV2Response { f := func(registry registrytypes.Registry, a pkg.Artifact, l, o int) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &SearchPackageV2Response{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, nil, } } feedResponse, err := nugetRegistry.SearchPackageV2(ctx, info, searchTerm, l, o) return &SearchPackageV2Response{ BaseResponse{ err, nil, }, feedResponse, } } aggregatedResults, totalCount, err := base.SearchPackagesProxyWrapper(ctx, c.registryDao, f, extractResponseDataV2, info, limit, offset) if err != nil { return &SearchPackageV2Response{ BaseResponse{ err, nil, }, nil, } } // Create response using the aggregated results feedEntries := make([]*nugettype.FeedEntryResponse, 0, len(aggregatedResults)) for _, result := range aggregatedResults { if entry, ok := result.(*nugettype.FeedEntryResponse); ok { feedEntries = append(feedEntries, entry) } } // Get the base URL for proper XML namespace fields baseURL := c.urlProvider.PackageURL(ctx, info.RootIdentifier+"/"+info.RegIdentifier, "nuget") links := []nugettype.FeedEntryLink{ {Rel: "self", Href: xml.CharData(baseURL)}, } nextURL := "" if len(feedEntries) == limit { u, _ := url.Parse(baseURL) u = u.JoinPath("Search()") q := u.Query() q.Add("$skip", strconv.Itoa(limit+offset)) q.Add("$top", strconv.Itoa(limit)) if searchTerm != "" { q.Add("searchTerm", searchTerm) } u.RawQuery = q.Encode() nextURL = u.String() } if nextURL != "" { links = append(links, nugettype.FeedEntryLink{ Rel: "next", Href: xml.CharData(nextURL), }) } // Create FeedResponse with proper XML namespace fields feedResponse := &nugettype.FeedResponse{ Xmlns: nuget.XMLNamespaceAtom, Base: baseURL, XmlnsD: nuget.XMLNamespaceDataServices, XmlnsM: nuget.XMLNamespaceDataServicesMetadata, ID: nuget.XMLNamespaceDataContract, Updated: time.Now(), Links: links, Count: totalCount, Entries: feedEntries, } return &SearchPackageV2Response{ BaseResponse: BaseResponse{ Error: nil, ResponseHeaders: nil, }, FeedResponse: feedResponse, } } func extractResponseDataV2(searchResponse response.Response) ([]any, int64) { var nativeResults []any var totalHits int64 // Handle v2 response if searchV2Resp, ok := searchResponse.(*SearchPackageV2Response); ok && searchV2Resp.FeedResponse != nil { totalHits = searchV2Resp.FeedResponse.Count for _, entry := range searchV2Resp.FeedResponse.Entries { nativeResults = append(nativeResults, entry) } } return nativeResults, totalHits }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/nuget/download_package.go
registry/app/api/controller/pkg/nuget/download_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package nuget import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/nuget" "github.com/harness/gitness/registry/app/pkg/response" nugettype "github.com/harness/gitness/registry/app/pkg/types/nuget" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackage( ctx context.Context, info nugettype.ArtifactInfo, ) *GetArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) nugetRegistry, ok := a.(nuget.Registry) if !ok { return &GetArtifactResponse{ BaseResponse{ fmt.Errorf("invalid registry type: expected nuget.Registry"), nil, }, "", nil, nil, } } headers, fileReader, redirectURL, readCloser, err := nugetRegistry.DownloadPackage(ctx, info) return &GetArtifactResponse{ BaseResponse{ err, headers, }, redirectURL, fileReader, readCloser, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, true) if err != nil { return &GetArtifactResponse{ BaseResponse{ err, nil, }, "", nil, nil, } } getResponse, ok := result.(*GetArtifactResponse) if !ok { return &GetArtifactResponse{ BaseResponse{ fmt.Errorf("invalid response type: expected GetArtifactResponse"), nil, }, "", nil, nil, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/list_tag.go
registry/app/api/controller/pkg/npm/list_tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" commons2 "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) func (c *controller) ListTags( ctx context.Context, info *npm.ArtifactInfo, ) *ListTagResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID info.Registry = registry info.ParentID = registry.ParentID npmRegistry, ok := a.(npm2.Registry) if !ok { return &ListTagResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } tags, err := npmRegistry.ListTags(ctx, *info) if !commons2.IsEmpty(err) { return &ListTagResponse{ BaseResponse: BaseResponse{Error: err}, } } return &ListTagResponse{ Tags: tags, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if !commons2.IsEmpty(err) { return &ListTagResponse{ BaseResponse: BaseResponse{Error: err}, } } artifactResponse, ok := result.(*ListTagResponse) if !ok { return &ListTagResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected ListTagResponse")}, } } return artifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/wire.go
registry/app/api/controller/pkg/npm/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func ControllerProvider( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, downloadStatsDao store.DownloadStatRepository, urlProvider urlprovider.Provider, local npm2.LocalRegistry, proxy npm2.Proxy, quarantineFinder quarantine.Finder, ) Controller { return NewController(proxyStore, registryDao, imageDao, artifactDao, fileManager, downloadStatsDao, tx, urlProvider, local, proxy, quarantineFinder) } var ControllerSet = wire.NewSet(ControllerProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/response.go
registry/app/api/controller/pkg/npm/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "io" npm2 "github.com/harness/gitness/registry/app/metadata/npm" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/storage" ) type GetMetadataResponse struct { BaseResponse PackageMetadata npm2.PackageMetadata } func (r *GetMetadataResponse) GetError() error { return r.Error } type ListTagResponse struct { Tags map[string]string BaseResponse } func (r *ListTagResponse) GetError() error { return r.Error } type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } type GetArtifactResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } func (r *GetArtifactResponse) GetError() error { return r.Error } type PutArtifactResponse struct { Sha256 string BaseResponse } func (r *PutArtifactResponse) GetError() error { return r.Error } type HeadMetadataResponse struct { BaseResponse Exists bool } func (r *HeadMetadataResponse) GetError() error { return r.Error } type DeleteEntityResponse struct { Error error } func (r *DeleteEntityResponse) GetError() error { return r.Error } type SearchArtifactResponse struct { BaseResponse Artifacts *npm2.PackageSearch } func (r *SearchArtifactResponse) GetError() error { return r.Error }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/metadata.go
registry/app/api/controller/pkg/npm/metadata.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) // GetPackageMetadata fetches the metadata of a package with the given artifact info. // // This is a proxy function to Registry.PutFile, which is used to fetch the metadata // of a package. The function is used by the API handler. // // The function takes a context and an artifact info as parameters and returns a GetPackageMetadata // containing the metadata of the package. If an error occurs during the operation, the // function returns an error as well. func (c *controller) GetPackageMetadata( ctx context.Context, info *npm.ArtifactInfo, ) *GetMetadataResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) npmRegistry, ok := a.(npm2.Registry) if !ok { return &GetMetadataResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } metadata, err := npmRegistry.GetPackageMetadata(ctx, *info) return &GetMetadataResponse{ BaseResponse: BaseResponse{Error: err}, PackageMetadata: metadata, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if !commons.IsEmpty(err) { return &GetMetadataResponse{ BaseResponse: BaseResponse{Error: err}, } } metadataResponse, ok := result.(*GetMetadataResponse) if !ok { return &GetMetadataResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected GetMetadataResponse, got %T", result), }, } } return metadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/search_package.go
registry/app/api/controller/pkg/npm/search_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) func (c *controller) SearchPackage( ctx context.Context, info *npm.ArtifactInfo, limit int, offset int, ) *SearchArtifactResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID info.ParentID = registry.ParentID info.Registry = registry npmRegistry, ok := a.(npm2.Registry) if !ok { return &GetMetadataResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } artifacts, err := npmRegistry.SearchPackage(ctx, *info, limit, offset) return &SearchArtifactResponse{ BaseResponse: BaseResponse{Error: err}, Artifacts: artifacts, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if !commons.IsEmpty(err) { return &SearchArtifactResponse{ BaseResponse: BaseResponse{Error: err}, } } metadataResponse, ok := result.(*SearchArtifactResponse) if !ok { return &SearchArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected GetMetadataResponse, got %T", result)}, } } return metadataResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/add_tag.go
registry/app/api/controller/pkg/npm/add_tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // nolint:goheader package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) func (c *controller) AddTag( ctx context.Context, info *npm.ArtifactInfo, ) *ListTagResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID npmRegistry, ok := a.(npm2.Registry) if !ok { return &ListTagResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } tags, err := npmRegistry.AddTag(ctx, *info) if err != nil { return &ListTagResponse{ BaseResponse: BaseResponse{Error: err}, } } return &ListTagResponse{ Tags: tags, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &ListTagResponse{ BaseResponse: BaseResponse{Error: err}, } } artifactResponse, ok := result.(*ListTagResponse) if !ok { return &ListTagResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected ListTagResponse")}, } } return artifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/delete_package.go
registry/app/api/controller/pkg/npm/delete_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) func (c *controller) DeletePackage( ctx context.Context, info *npm.ArtifactInfo, ) *DeleteEntityResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID npmRegistry, ok := a.(npm2.Registry) if !ok { return &DeleteEntityResponse{ Error: fmt.Errorf("invalid registry type: expected npm.Registry"), } } err := npmRegistry.DeletePackage(ctx, *info) if err != nil { return &DeleteEntityResponse{Error: err} } return &DeleteEntityResponse{} } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &DeleteEntityResponse{Error: err} } artifactResponse, ok := result.(*DeleteEntityResponse) if !ok { return &DeleteEntityResponse{ Error: fmt.Errorf("invalid response type: expected DeleteEntityResponse"), } } return artifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/delete_version.go
registry/app/api/controller/pkg/npm/delete_version.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) func (c *controller) DeleteVersion( ctx context.Context, info *npm.ArtifactInfo, ) *DeleteEntityResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID npmRegistry, ok := a.(npm2.Registry) if !ok { return &DeleteEntityResponse{ Error: fmt.Errorf("invalid registry type: expected npm.Registry"), } } err := npmRegistry.DeleteVersion(ctx, *info) if err != nil { return &DeleteEntityResponse{Error: err} } return &DeleteEntityResponse{} } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &DeleteEntityResponse{Error: err} } artifactResponse, ok := result.(*DeleteEntityResponse) if !ok { return &DeleteEntityResponse{ Error: fmt.Errorf("invalid response type: expected DeleteEntityResponse"), } } return artifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/download_file.go
registry/app/api/controller/pkg/npm/download_file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" commons2 "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackageFileByName( ctx context.Context, info *npm.ArtifactInfo, ) *GetArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) npmRegistry, ok := a.(npm2.Registry) if !ok { return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } headers, fileReader, readCloser, redirectURL, errs := npmRegistry.DownloadPackageFile(ctx, *info) return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: errs, ResponseHeaders: headers}, RedirectURL: redirectURL, Body: fileReader, ReadCloser: readCloser, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, true) if commons2.IsEmpty(err) { return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: err}, } } getResponse, ok := result.(*GetArtifactResponse) if !ok { return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected GetArtifactResponse")}, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/controller.go
registry/app/api/controller/pkg/npm/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "io" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/filemanager" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) // Controller handles PyPI package operations. type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider downloadStat store.DownloadStatRepository local npm2.LocalRegistry proxy npm2.Proxy quarantineFinder quarantine.Finder } type Controller interface { UploadPackageFile( ctx context.Context, info *npm.ArtifactInfo, file io.ReadCloser, ) *PutArtifactResponse DownloadPackageFile( ctx context.Context, info *npm.ArtifactInfo, ) *GetArtifactResponse GetPackageMetadata(ctx context.Context, info *npm.ArtifactInfo) *GetMetadataResponse HeadPackageFileByName(ctx context.Context, info *npm.ArtifactInfo) *HeadMetadataResponse ListTags( ctx context.Context, info *npm.ArtifactInfo, ) *ListTagResponse AddTag( ctx context.Context, info *npm.ArtifactInfo, ) *ListTagResponse DeleteTag( ctx context.Context, info *npm.ArtifactInfo, ) *ListTagResponse DeleteVersion( ctx context.Context, info *npm.ArtifactInfo, ) *DeleteEntityResponse DeletePackage( ctx context.Context, info *npm.ArtifactInfo, ) *DeleteEntityResponse SearchPackage( ctx context.Context, info *npm.ArtifactInfo, limit int, offset int, ) *SearchArtifactResponse } // NewController creates a new PyPI controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, downloadStatsDao store.DownloadStatRepository, tx dbtx.Transactor, urlProvider urlprovider.Provider, local npm2.LocalRegistry, proxy npm2.Proxy, quarantineFinder quarantine.Finder, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, imageDao: imageDao, artifactDao: artifactDao, downloadStat: downloadStatsDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, proxy: proxy, quarantineFinder: quarantineFinder, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/upload.go
registry/app/api/controller/pkg/npm/upload.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "io" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) // UploadPackageFile FIXME: Extract this upload function for all types of packageTypes // uploads the package file to the storage. func (c *controller) UploadPackageFile( ctx context.Context, info *npm.ArtifactInfo, file io.ReadCloser, ) *PutArtifactResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID npmRegistry, ok := a.(npm2.Registry) if !ok { return &PutArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } headers, sha256, err := npmRegistry.UploadPackageFile(ctx, *info, file) if !commons.IsEmpty(err) { return &PutArtifactResponse{ BaseResponse: BaseResponse{Error: err}, } } return &PutArtifactResponse{ BaseResponse: BaseResponse{ResponseHeaders: headers}, Sha256: sha256} } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if !commons.IsEmpty(err) { return &PutArtifactResponse{ BaseResponse: BaseResponse{Error: err}, } } artifactResponse, ok := result.(*PutArtifactResponse) if !ok { return &PutArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected PutArtifactResponse")}, } } return artifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/head_file.go
registry/app/api/controller/pkg/npm/head_file.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" commons2 "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) HeadPackageFileByName( ctx context.Context, info *npm.ArtifactInfo, ) *HeadMetadataResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) npmRegistry, ok := a.(npm2.Registry) if !ok { return &HeadMetadataResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid Registry type: expected npm.Registry")}, } } exist, err := npmRegistry.HeadPackageMetadata(ctx, *info) if !commons2.IsEmpty(err) { return &HeadMetadataResponse{ BaseResponse: BaseResponse{Error: err}, } } return &HeadMetadataResponse{ Exists: exist} } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if !commons2.IsEmpty(err) { return &HeadMetadataResponse{ BaseResponse: BaseResponse{Error: err}, } } getResponse, ok := result.(*HeadMetadataResponse) if !ok { return &HeadMetadataResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected GetArtifactResponse")}, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/delete_tag.go
registry/app/api/controller/pkg/npm/delete_tag.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" "github.com/harness/gitness/registry/types" ) func (c *controller) DeleteTag( ctx context.Context, info *npm.ArtifactInfo, ) *ListTagResponse { f := func(registry types.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID npmRegistry, ok := a.(npm2.Registry) if !ok { return &ListTagResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } tags, err := npmRegistry.DeleteTag(ctx, *info) if err != nil { return &ListTagResponse{ BaseResponse: BaseResponse{Error: err}, } } return &ListTagResponse{ Tags: tags, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &ListTagResponse{ BaseResponse: BaseResponse{Error: err}, } } artifactResponse, ok := result.(*ListTagResponse) if !ok { return &ListTagResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected ListTagResponse")}, } } return artifactResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/npm/download.go
registry/app/api/controller/pkg/npm/download.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package npm import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" commons2 "github.com/harness/gitness/registry/app/pkg/commons" npm2 "github.com/harness/gitness/registry/app/pkg/npm" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/pkg/types/npm" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackageFile( ctx context.Context, info *npm.ArtifactInfo, ) *GetArtifactResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) npmRegistry, ok := a.(npm2.Registry) if !ok { return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid registry type: expected npm.Registry")}, } } headers, fileReader, readCloser, redirectURL, err := npmRegistry.DownloadPackageFile(ctx, *info) return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: err, ResponseHeaders: headers}, RedirectURL: redirectURL, Body: fileReader, ReadCloser: readCloser, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, true) if !commons2.IsEmpty(err) { return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: err}, } } getResponse, ok := result.(*GetArtifactResponse) if !ok { return &GetArtifactResponse{ BaseResponse: BaseResponse{Error: fmt.Errorf("invalid response type: expected GetArtifactResponse")}, } } return getResponse }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/wire.go
registry/app/api/controller/pkg/cargo/wire.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( refcache2 "github.com/harness/gitness/app/services/refcache" urlprovider "github.com/harness/gitness/app/url" "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/quarantine" "github.com/harness/gitness/registry/app/services/publicaccess" "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" "github.com/google/wire" ) func ControllerProvider( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, registryFinder refcache.RegistryFinder, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local cargo.LocalRegistry, proxy cargo.Proxy, publicAccessService publicaccess.CacheService, spaceFinder refcache2.SpaceFinder, quarantineFinder quarantine.Finder, ) Controller { return NewController( proxyStore, registryDao, registryFinder, imageDao, artifactDao, fileManager, tx, urlProvider, local, proxy, publicAccessService, spaceFinder, quarantineFinder, ) } var ControllerSet = wire.NewSet(ControllerProvider)
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/response.go
registry/app/api/controller/pkg/cargo/response.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "io" "github.com/harness/gitness/registry/app/metadata/cargo" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" "github.com/harness/gitness/registry/app/storage" ) var _ response.Response = (*GetRegistryConfigResponse)(nil) var _ response.Response = (*UploadArtifactResponse)(nil) type BaseResponse struct { Error error ResponseHeaders *commons.ResponseHeaders } func (r BaseResponse) GetError() error { return r.Error } type GetRegistryConfigResponse struct { BaseResponse Config *cargo.RegistryConfig } type UploadArtifactWarnings struct { InvalidCategories []string `json:"invalid_categories,omitempty"` InvalidBadges []string `json:"invalid_badges,omitempty"` Other []string `json:"other,omitempty"` } type UploadArtifactResponse struct { BaseResponse `json:"-"` Warnings *UploadArtifactWarnings `json:"warnings,omitempty"` } type DownloadFileResponse struct { BaseResponse RedirectURL string Body *storage.FileReader ReadCloser io.ReadCloser } type GetPackageIndexResponse struct { DownloadFileResponse } type GetPackageResponse struct { DownloadFileResponse } type UpdateYankResponse struct { BaseResponse `json:"-"` Ok bool `json:"ok"` } type RegeneratePackageIndexResponse struct { BaseResponse `json:"-"` Ok bool `json:"ok"` } type SearchPackageResponse struct { BaseResponse `json:"-"` Crates []SearchPackageResponseCrate `json:"crates"` Metadata SearchPackageResponseMetadata `json:"meta"` } type SearchPackageResponseCrate struct { Name string `json:"name"` MaxVersion string `json:"max_version"` Description string `json:"description"` } type SearchPackageResponseMetadata struct { Total int64 `json:"total"` }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/search_package.go
registry/app/api/controller/pkg/cargo/search_package.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "encoding/json" "fmt" "net/http" cargometadata "github.com/harness/gitness/registry/app/metadata/cargo" "github.com/harness/gitness/registry/app/pkg/commons" cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo" "github.com/harness/gitness/registry/types" "github.com/rs/zerolog/log" ) var ( DefaultPageSize = 10 MaxPageSize = 100 DefaultSortByField = "image_created_at" DefaultSortByOrder = "ASC" ) func (c *controller) SearchPackage( ctx context.Context, info *cargotype.ArtifactInfo, requestParams *cargotype.SearchPackageRequestParams, ) (*SearchPackageResponse, error) { responseHeaders := &commons.ResponseHeaders{ Headers: make(map[string]string), Code: 0, } requestInfo := c.getSearchPackageRequestInfo(requestParams) registry, err := c.registryFinder.FindByRootParentID(ctx, info.ParentID, info.RegIdentifier) if err != nil { return nil, fmt.Errorf("failed to get registry %s: %w", info.RegIdentifier, err) } registryList := make([]string, 0) registryList = append(registryList, registry.Name) if len(registry.UpstreamProxies) > 0 { repoKeys, err := c.registryDao.FetchUpstreamProxyKeys(ctx, registry.UpstreamProxies) if err != nil { return nil, fmt.Errorf("failed to get upstream proxies repokeys %s: %w", info.RegIdentifier, err) } registryList = append(registryList, repoKeys...) } artifacts, err := c.artifactDao.GetAllArtifactsByParentID( ctx, info.ParentID, &registryList, requestInfo.SortField, requestInfo.SortOrder, requestInfo.Limit, requestInfo.Offset, requestInfo.SearchTerm, true, []string{}, ) if err != nil { return nil, fmt.Errorf("failed to get artifacts %s: %w", info.RegIdentifier, err) } count, err := c.artifactDao.CountAllArtifactsByParentID( ctx, info.ParentID, &registryList, requestInfo.SearchTerm, true, []string{}, ) if err != nil { return nil, fmt.Errorf("failed to get artifacts count %s: %w", info.RegIdentifier, err) } crates := make([]SearchPackageResponseCrate, 0) if artifacts != nil { for _, artifact := range *artifacts { crates = append(crates, *c.mapArtifactToSearchPackageCrate(ctx, artifact)) } } responseHeaders.Code = http.StatusOK return &SearchPackageResponse{ BaseResponse: BaseResponse{ ResponseHeaders: responseHeaders, }, Crates: crates, Metadata: SearchPackageResponseMetadata{ Total: count, }, }, nil } func (c *controller) getSearchPackageRequestInfo( params *cargotype.SearchPackageRequestParams, ) *cargotype.SearchPackageRequestInfo { var requestInfo cargotype.SearchPackageRequestInfo if params == nil { return &requestInfo } if params.SearchTerm != nil { requestInfo.SearchTerm = *params.SearchTerm } if params.Size != nil { requestInfo.Limit = int(*params.Size) } else { requestInfo.Limit = DefaultPageSize } requestInfo.Limit = min(requestInfo.Limit, MaxPageSize) requestInfo.Offset = int(0) requestInfo.SortField = DefaultSortByField requestInfo.SortOrder = DefaultSortByOrder return &requestInfo } func (c *controller) mapArtifactToSearchPackageCrate( ctx context.Context, artifact types.ArtifactMetadata, ) *SearchPackageResponseCrate { metadata := cargometadata.VersionMetadataDB{} err := json.Unmarshal(artifact.Metadata, &metadata) if err != nil { log.Error().Ctx(ctx).Msg( fmt.Sprintf( "Failed to unmarshal metadata for package %s version %s: %s", artifact.Name, artifact.Version, err.Error(), ), ) } return &SearchPackageResponseCrate{ Name: artifact.Name, MaxVersion: artifact.Version, Description: metadata.Description, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/registry_config.go
registry/app/api/controller/pkg/cargo/registry_config.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "fmt" "net/http" "net/url" "path" "strings" "github.com/harness/gitness/registry/app/api/controller/metadata" "github.com/harness/gitness/registry/app/metadata/cargo" "github.com/harness/gitness/registry/app/pkg/commons" cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo" gitnessenum "github.com/harness/gitness/types/enum" "github.com/rs/zerolog/log" ) func (c *controller) GetRegistryConfig( ctx context.Context, info *cargotype.ArtifactInfo, ) (*GetRegistryConfigResponse, error) { responseHeaders := &commons.ResponseHeaders{ Headers: make(map[string]string), Code: 0, } registryRef := metadata.GetRegistryRef(info.RootIdentifier, info.RegIdentifier) apiURL := c.urlProvider.PackageURL(ctx, registryRef, "cargo") downloadURL := c.getDownloadURL(apiURL) space, err := c.spaceFinder.FindByID(ctx, info.ParentID) if err != nil { log.Ctx(ctx).Error().Stack().Str("middleware", "OciCheckAuth").Err(err).Msgf("error while fetching the space with ID: %d err: %v", info.ParentID, err) responseHeaders.Code = http.StatusInternalServerError return &GetRegistryConfigResponse{ BaseResponse: BaseResponse{ ResponseHeaders: responseHeaders, }, }, fmt.Errorf("failed to get space: %w", err) } publicAccessSupported, err := c.publicAccessService. Get(ctx, gitnessenum.PublicResourceTypeRegistry, space.Path+"/"+info.RegIdentifier) if err != nil { responseHeaders.Code = http.StatusInternalServerError return &GetRegistryConfigResponse{ BaseResponse: BaseResponse{ ResponseHeaders: responseHeaders, }, }, fmt.Errorf("failed to check public access: %w", err) } responseHeaders.Code = http.StatusOK return &GetRegistryConfigResponse{ BaseResponse: BaseResponse{ ResponseHeaders: responseHeaders, }, Config: &cargo.RegistryConfig{ DownloadURL: downloadURL, APIURL: apiURL, AuthRequired: !publicAccessSupported, }, }, nil } func (c *controller) getDownloadURL(apiURL string) string { base, _ := url.Parse(apiURL) segments := []string{base.Path} segments = append(segments, "api") segments = append(segments, "v1") segments = append(segments, "crates") base.Path = path.Join(segments...) return strings.TrimRight(base.String(), "/") }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/update_yank.go
registry/app/api/controller/pkg/cargo/update_yank.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/response" cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) UpdateYank( ctx context.Context, info *cargotype.ArtifactInfo, yank bool, ) (*UpdateYankResponse, error) { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID cargoRegistry, ok := a.(cargo.Registry) if !ok { return &UpdateYankResponse{ BaseResponse{ Error: fmt.Errorf("invalid registry type: expected cargo.Registry"), ResponseHeaders: nil, }, false, } } headers, err := cargoRegistry.UpdateYank(ctx, *info, yank) return &UpdateYankResponse{ BaseResponse{ Error: err, ResponseHeaders: headers, }, false, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &UpdateYankResponse{ BaseResponse{ Error: err, ResponseHeaders: nil, }, false, }, err } putResponse, ok := result.(*UpdateYankResponse) if !ok { return &UpdateYankResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected UpdateYankResponse"), ResponseHeaders: nil, }, Ok: false, }, fmt.Errorf("invalid response type: expected UpdateYankResponse") } putResponse.Ok = true return putResponse, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/download_package_index.go
registry/app/api/controller/pkg/cargo/download_package_index.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "fmt" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/commons" "github.com/harness/gitness/registry/app/pkg/response" cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) DownloadPackageIndex( ctx context.Context, info *cargotype.ArtifactInfo, filePath string, ) *GetPackageIndexResponse { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.UpdateRegistryInfo(registry) cargoRegistry, ok := a.(cargo.Registry) if !ok { return c.getDownloadPackageIndexErrorResponse( fmt.Errorf("invalid registry type: expected cargo.Registry"), nil, ) } headers, fileReader, readCloser, redirectURL, err := cargoRegistry.DownloadPackageIndex( ctx, *info, filePath, ) return &GetPackageIndexResponse{ DownloadFileResponse{ BaseResponse: BaseResponse{ Error: err, ResponseHeaders: headers, }, RedirectURL: redirectURL, Body: fileReader, ReadCloser: readCloser, }, } } result, err := base.ProxyWrapper(ctx, c.registryDao, c.quarantineFinder, f, info, false) if err != nil { return c.getDownloadPackageIndexErrorResponse( err, nil, ) } getResponse, ok := result.(*GetPackageIndexResponse) if !ok { return c.getDownloadPackageIndexErrorResponse( fmt.Errorf("invalid response type: expected GetPackageIndexResponse"), nil, ) } return getResponse } func (c *controller) getDownloadPackageIndexErrorResponse( err error, headers *commons.ResponseHeaders, ) *GetPackageIndexResponse { return &GetPackageIndexResponse{ DownloadFileResponse{ BaseResponse: BaseResponse{ Error: err, ResponseHeaders: headers, }, RedirectURL: "", Body: nil, ReadCloser: nil, }, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/controller.go
registry/app/api/controller/pkg/cargo/controller.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "io" "github.com/harness/gitness/app/services/publicaccess" refcache2 "github.com/harness/gitness/app/services/refcache" urlprovider "github.com/harness/gitness/app/url" cargometadata "github.com/harness/gitness/registry/app/metadata/cargo" "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/filemanager" "github.com/harness/gitness/registry/app/pkg/quarantine" cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo" "github.com/harness/gitness/registry/app/services/refcache" "github.com/harness/gitness/registry/app/store" "github.com/harness/gitness/store/database/dbtx" ) type Controller interface { GetRegistryConfig(ctx context.Context, info *cargotype.ArtifactInfo) (*GetRegistryConfigResponse, error) SearchPackage( ctx context.Context, info *cargotype.ArtifactInfo, requestInfo *cargotype.SearchPackageRequestParams, ) (*SearchPackageResponse, error) DownloadPackageIndex( ctx context.Context, info *cargotype.ArtifactInfo, filePath string, ) *GetPackageIndexResponse RegeneratePackageIndex( ctx context.Context, info *cargotype.ArtifactInfo, ) (*RegeneratePackageIndexResponse, error) DownloadPackage( ctx context.Context, info *cargotype.ArtifactInfo, ) *GetPackageResponse UploadPackage( ctx context.Context, info *cargotype.ArtifactInfo, metadata *cargometadata.VersionMetadata, fileReader io.ReadCloser, ) (*UploadArtifactResponse, error) UpdateYank(ctx context.Context, info *cargotype.ArtifactInfo, yank bool) (*UpdateYankResponse, error) } // Controller handles Cargo package operations. type controller struct { fileManager filemanager.FileManager proxyStore store.UpstreamProxyConfigRepository tx dbtx.Transactor registryDao store.RegistryRepository registryFinder refcache.RegistryFinder imageDao store.ImageRepository artifactDao store.ArtifactRepository urlProvider urlprovider.Provider local cargo.LocalRegistry proxy cargo.Proxy publicAccessService publicaccess.Service spaceFinder refcache2.SpaceFinder quarantineFinder quarantine.Finder } // NewController creates a new Cargo controller. func NewController( proxyStore store.UpstreamProxyConfigRepository, registryDao store.RegistryRepository, registryFinder refcache.RegistryFinder, imageDao store.ImageRepository, artifactDao store.ArtifactRepository, fileManager filemanager.FileManager, tx dbtx.Transactor, urlProvider urlprovider.Provider, local cargo.LocalRegistry, proxy cargo.Proxy, publicAccessService publicaccess.Service, spaceFinder refcache2.SpaceFinder, quarantineFinder quarantine.Finder, ) Controller { return &controller{ proxyStore: proxyStore, registryDao: registryDao, registryFinder: registryFinder, imageDao: imageDao, artifactDao: artifactDao, fileManager: fileManager, tx: tx, urlProvider: urlProvider, local: local, proxy: proxy, publicAccessService: publicAccessService, spaceFinder: spaceFinder, quarantineFinder: quarantineFinder, } }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false
harness/harness
https://github.com/harness/harness/blob/a087eef054a8fc8317f4fda02d3c7ee599b71fec/registry/app/api/controller/pkg/cargo/upload.go
registry/app/api/controller/pkg/cargo/upload.go
// Copyright 2023 Harness, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cargo import ( "context" "fmt" "io" cargometadata "github.com/harness/gitness/registry/app/metadata/cargo" "github.com/harness/gitness/registry/app/pkg" "github.com/harness/gitness/registry/app/pkg/base" "github.com/harness/gitness/registry/app/pkg/cargo" "github.com/harness/gitness/registry/app/pkg/response" cargotype "github.com/harness/gitness/registry/app/pkg/types/cargo" registrytypes "github.com/harness/gitness/registry/types" ) func (c *controller) UploadPackage( ctx context.Context, info *cargotype.ArtifactInfo, metadata *cargometadata.VersionMetadata, fileReader io.ReadCloser, ) (*UploadArtifactResponse, error) { f := func(registry registrytypes.Registry, a pkg.Artifact) response.Response { info.RegIdentifier = registry.Name info.RegistryID = registry.ID cargoRegistry, ok := a.(cargo.Registry) if !ok { return &UploadArtifactResponse{ BaseResponse{ Error: fmt.Errorf("invalid registry type: expected cargo.Registry"), ResponseHeaders: nil, }, nil, } } headers, err := cargoRegistry.UploadPackage(ctx, *info, metadata, fileReader) return &UploadArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: headers, }, nil, } } result, err := base.NoProxyWrapper(ctx, c.registryDao, f, info) if err != nil { return &UploadArtifactResponse{ BaseResponse{ Error: err, ResponseHeaders: nil, }, nil, }, err } putResponse, ok := result.(*UploadArtifactResponse) if !ok { return &UploadArtifactResponse{ BaseResponse: BaseResponse{ Error: fmt.Errorf("invalid response type: expected UploadArtifactResponse"), ResponseHeaders: nil, }, Warnings: nil, }, fmt.Errorf("invalid response type: expected UploadArtifactResponse") } return putResponse, nil }
go
Apache-2.0
a087eef054a8fc8317f4fda02d3c7ee599b71fec
2026-01-07T08:36:08.091982Z
false