Remove db.DefaultContext in routers/ and cmd/ (#26076)

Now, the only remaining usages of `models.db.DefaultContext` are in
  - `modules`
  - `models`
  - `services`
This commit is contained in:
delvh 2023-07-24 05:47:27 +02:00 committed by GitHub
parent 24c3bb95ac
commit f3d41c61eb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 127 additions and 134 deletions

View file

@ -5,6 +5,7 @@
package cmd package cmd
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"net/url" "net/url"
@ -373,7 +374,7 @@ func runRepoSyncReleases(_ *cli.Context) error {
continue continue
} }
oldnum, err := getReleaseCount(repo.ID) oldnum, err := getReleaseCount(ctx, repo.ID)
if err != nil { if err != nil {
log.Warn(" GetReleaseCountByRepoID: %v", err) log.Warn(" GetReleaseCountByRepoID: %v", err)
} }
@ -385,7 +386,7 @@ func runRepoSyncReleases(_ *cli.Context) error {
continue continue
} }
count, err = getReleaseCount(repo.ID) count, err = getReleaseCount(ctx, repo.ID)
if err != nil { if err != nil {
log.Warn(" GetReleaseCountByRepoID: %v", err) log.Warn(" GetReleaseCountByRepoID: %v", err)
gitRepo.Close() gitRepo.Close()
@ -401,9 +402,9 @@ func runRepoSyncReleases(_ *cli.Context) error {
return nil return nil
} }
func getReleaseCount(id int64) (int64, error) { func getReleaseCount(ctx context.Context, id int64) (int64, error) {
return repo_model.GetReleaseCountByRepoID( return repo_model.GetReleaseCountByRepoID(
db.DefaultContext, ctx,
id, id,
repo_model.FindReleasesOptions{ repo_model.FindReleasesOptions{
IncludeTags: true, IncludeTags: true,

View file

@ -114,7 +114,7 @@ func SearchPackages(ctx *context.Context) {
// EnumeratePackages lists all package names // EnumeratePackages lists all package names
// https://packagist.org/apidoc#list-packages // https://packagist.org/apidoc#list-packages
func EnumeratePackages(ctx *context.Context) { func EnumeratePackages(ctx *context.Context) {
ps, err := packages_model.GetPackagesByType(db.DefaultContext, ctx.Package.Owner.ID, packages_model.TypeComposer) ps, err := packages_model.GetPackagesByType(ctx, ctx.Package.Owner.ID, packages_model.TypeComposer)
if err != nil { if err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return

View file

@ -4,6 +4,7 @@
package conan package conan
import ( import (
std_ctx "context"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
@ -602,18 +603,16 @@ func DeletePackageV2(ctx *context.Context) {
} }
func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeReference, ignoreRecipeRevision bool, pref *conan_module.PackageReference, ignorePackageRevision bool) error { func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeReference, ignoreRecipeRevision bool, pref *conan_module.PackageReference, ignorePackageRevision bool) error {
ctx, committer, err := db.TxContext(db.DefaultContext) var pd *packages_model.PackageDescriptor
if err != nil { versionDeleted := false
return err
}
defer committer.Close()
err := db.WithTx(apictx, func(ctx std_ctx.Context) error {
pv, err := packages_model.GetVersionByNameAndVersion(ctx, apictx.Package.Owner.ID, packages_model.TypeConan, rref.Name, rref.Version) pv, err := packages_model.GetVersionByNameAndVersion(ctx, apictx.Package.Owner.ID, packages_model.TypeConan, rref.Name, rref.Version)
if err != nil { if err != nil {
return err return err
} }
pd, err := packages_model.GetPackageDescriptor(ctx, pv) pd, err = packages_model.GetPackageDescriptor(ctx, pv)
if err != nil { if err != nil {
return err return err
} }
@ -648,8 +647,6 @@ func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeRef
return err return err
} }
} }
versionDeleted := false
has, err := packages_model.HasVersionFileReferences(ctx, pv.ID) has, err := packages_model.HasVersionFileReferences(ctx, pv.ID)
if err != nil { if err != nil {
return err return err
@ -657,12 +654,11 @@ func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeRef
if !has { if !has {
versionDeleted = true versionDeleted = true
if err := packages_service.DeletePackageVersionAndReferences(ctx, pv); err != nil { return packages_service.DeletePackageVersionAndReferences(ctx, pv)
return err
} }
} return nil
})
if err := committer.Commit(); err != nil { if err != nil {
return err return err
} }

View file

@ -26,19 +26,19 @@ var uploadVersionMutex sync.Mutex
// saveAsPackageBlob creates a package blob from an upload // saveAsPackageBlob creates a package blob from an upload
// The uploaded blob gets stored in a special upload version to link them to the package/image // The uploaded blob gets stored in a special upload version to link them to the package/image
func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pci *packages_service.PackageCreationInfo) (*packages_model.PackageBlob, error) { func saveAsPackageBlob(ctx context.Context, hsr packages_module.HashedSizeReader, pci *packages_service.PackageCreationInfo) (*packages_model.PackageBlob, error) {
pb := packages_service.NewPackageBlob(hsr) pb := packages_service.NewPackageBlob(hsr)
exists := false exists := false
contentStore := packages_module.NewContentStore() contentStore := packages_module.NewContentStore()
uploadVersion, err := getOrCreateUploadVersion(&pci.PackageInfo) uploadVersion, err := getOrCreateUploadVersion(ctx, &pci.PackageInfo)
if err != nil { if err != nil {
return nil, err return nil, err
} }
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.WithTx(ctx, func(ctx context.Context) error {
if err := packages_service.CheckSizeQuotaExceeded(ctx, pci.Creator, pci.Owner, packages_model.TypeContainer, hsr.Size()); err != nil { if err := packages_service.CheckSizeQuotaExceeded(ctx, pci.Creator, pci.Owner, packages_model.TypeContainer, hsr.Size()); err != nil {
return err return err
} }
@ -79,24 +79,24 @@ func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pci *packages_servi
} }
// mountBlob mounts the specific blob to a different package // mountBlob mounts the specific blob to a different package
func mountBlob(pi *packages_service.PackageInfo, pb *packages_model.PackageBlob) error { func mountBlob(ctx context.Context, pi *packages_service.PackageInfo, pb *packages_model.PackageBlob) error {
uploadVersion, err := getOrCreateUploadVersion(pi) uploadVersion, err := getOrCreateUploadVersion(ctx, pi)
if err != nil { if err != nil {
return err return err
} }
return db.WithTx(db.DefaultContext, func(ctx context.Context) error { return db.WithTx(ctx, func(ctx context.Context) error {
return createFileForBlob(ctx, uploadVersion, pb) return createFileForBlob(ctx, uploadVersion, pb)
}) })
} }
func getOrCreateUploadVersion(pi *packages_service.PackageInfo) (*packages_model.PackageVersion, error) { func getOrCreateUploadVersion(ctx context.Context, pi *packages_service.PackageInfo) (*packages_model.PackageVersion, error) {
var uploadVersion *packages_model.PackageVersion var uploadVersion *packages_model.PackageVersion
// FIXME: Replace usage of mutex with database transaction // FIXME: Replace usage of mutex with database transaction
// https://github.com/go-gitea/gitea/pull/21862 // https://github.com/go-gitea/gitea/pull/21862
uploadVersionMutex.Lock() uploadVersionMutex.Lock()
err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { err := db.WithTx(ctx, func(ctx context.Context) error {
created := true created := true
p := &packages_model.Package{ p := &packages_model.Package{
OwnerID: pi.Owner.ID, OwnerID: pi.Owner.ID,
@ -172,8 +172,8 @@ func createFileForBlob(ctx context.Context, pv *packages_model.PackageVersion, p
return nil return nil
} }
func deleteBlob(ownerID int64, image, digest string) error { func deleteBlob(ctx context.Context, ownerID int64, image, digest string) error {
return db.WithTx(db.DefaultContext, func(ctx context.Context) error { return db.WithTx(ctx, func(ctx context.Context) error {
pfds, err := container_model.GetContainerBlobs(ctx, &container_model.BlobSearchOptions{ pfds, err := container_model.GetContainerBlobs(ctx, &container_model.BlobSearchOptions{
OwnerID: ownerID, OwnerID: ownerID,
Image: image, Image: image,

View file

@ -210,7 +210,7 @@ func InitiateUploadBlob(ctx *context.Context) {
} }
if accessible { if accessible {
if err := mountBlob(&packages_service.PackageInfo{Owner: ctx.Package.Owner, Name: image}, blob.Blob); err != nil { if err := mountBlob(ctx, &packages_service.PackageInfo{Owner: ctx.Package.Owner, Name: image}, blob.Blob); err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
} }
@ -239,7 +239,7 @@ func InitiateUploadBlob(ctx *context.Context) {
return return
} }
if _, err := saveAsPackageBlob( if _, err := saveAsPackageBlob(ctx,
buf, buf,
&packages_service.PackageCreationInfo{ &packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{ PackageInfo: packages_service.PackageInfo{
@ -384,7 +384,7 @@ func EndUploadBlob(ctx *context.Context) {
return return
} }
if _, err := saveAsPackageBlob( if _, err := saveAsPackageBlob(ctx,
uploader, uploader,
&packages_service.PackageCreationInfo{ &packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{ PackageInfo: packages_service.PackageInfo{
@ -502,7 +502,7 @@ func DeleteBlob(ctx *context.Context) {
return return
} }
if err := deleteBlob(ctx.Package.Owner.ID, ctx.Params("image"), d); err != nil { if err := deleteBlob(ctx, ctx.Package.Owner.ID, ctx.Params("image"), d); err != nil {
apiError(ctx, http.StatusInternalServerError, err) apiError(ctx, http.StatusInternalServerError, err)
return return
} }
@ -543,7 +543,7 @@ func UploadManifest(ctx *context.Context) {
return return
} }
digest, err := processManifest(mci, buf) digest, err := processManifest(ctx, mci, buf)
if err != nil { if err != nil {
var namedError *namedError var namedError *namedError
if errors.As(err, &namedError) { if errors.As(err, &namedError) {

View file

@ -50,7 +50,7 @@ type manifestCreationInfo struct {
Properties map[string]string Properties map[string]string
} }
func processManifest(mci *manifestCreationInfo, buf *packages_module.HashedBuffer) (string, error) { func processManifest(ctx context.Context, mci *manifestCreationInfo, buf *packages_module.HashedBuffer) (string, error) {
var index oci.Index var index oci.Index
if err := json.NewDecoder(buf).Decode(&index); err != nil { if err := json.NewDecoder(buf).Decode(&index); err != nil {
return "", err return "", err
@ -72,14 +72,14 @@ func processManifest(mci *manifestCreationInfo, buf *packages_module.HashedBuffe
} }
if isImageManifestMediaType(mci.MediaType) { if isImageManifestMediaType(mci.MediaType) {
return processImageManifest(mci, buf) return processImageManifest(ctx, mci, buf)
} else if isImageIndexMediaType(mci.MediaType) { } else if isImageIndexMediaType(mci.MediaType) {
return processImageManifestIndex(mci, buf) return processImageManifestIndex(ctx, mci, buf)
} }
return "", errManifestInvalid return "", errManifestInvalid
} }
func processImageManifest(mci *manifestCreationInfo, buf *packages_module.HashedBuffer) (string, error) { func processImageManifest(ctx context.Context, mci *manifestCreationInfo, buf *packages_module.HashedBuffer) (string, error) {
manifestDigest := "" manifestDigest := ""
err := func() error { err := func() error {
@ -92,7 +92,7 @@ func processImageManifest(mci *manifestCreationInfo, buf *packages_module.Hashed
return err return err
} }
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -181,7 +181,7 @@ func processImageManifest(mci *manifestCreationInfo, buf *packages_module.Hashed
return err return err
} }
if err := notifyPackageCreate(mci.Creator, pv); err != nil { if err := notifyPackageCreate(ctx, mci.Creator, pv); err != nil {
return err return err
} }
@ -196,7 +196,7 @@ func processImageManifest(mci *manifestCreationInfo, buf *packages_module.Hashed
return manifestDigest, nil return manifestDigest, nil
} }
func processImageManifestIndex(mci *manifestCreationInfo, buf *packages_module.HashedBuffer) (string, error) { func processImageManifestIndex(ctx context.Context, mci *manifestCreationInfo, buf *packages_module.HashedBuffer) (string, error) {
manifestDigest := "" manifestDigest := ""
err := func() error { err := func() error {
@ -209,7 +209,7 @@ func processImageManifestIndex(mci *manifestCreationInfo, buf *packages_module.H
return err return err
} }
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(ctx)
if err != nil { if err != nil {
return err return err
} }
@ -285,7 +285,7 @@ func processImageManifestIndex(mci *manifestCreationInfo, buf *packages_module.H
return err return err
} }
if err := notifyPackageCreate(mci.Creator, pv); err != nil { if err := notifyPackageCreate(ctx, mci.Creator, pv); err != nil {
return err return err
} }
@ -300,13 +300,13 @@ func processImageManifestIndex(mci *manifestCreationInfo, buf *packages_module.H
return manifestDigest, nil return manifestDigest, nil
} }
func notifyPackageCreate(doer *user_model.User, pv *packages_model.PackageVersion) error { func notifyPackageCreate(ctx context.Context, doer *user_model.User, pv *packages_model.PackageVersion) error {
pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) pd, err := packages_model.GetPackageDescriptor(ctx, pv)
if err != nil { if err != nil {
return err return err
} }
notification.NotifyPackageCreate(db.DefaultContext, doer, pd) notification.NotifyPackageCreate(ctx, doer, pd)
return nil return nil
} }

View file

@ -5,6 +5,7 @@ package npm
import ( import (
"bytes" "bytes"
std_ctx "context"
"errors" "errors"
"fmt" "fmt"
"io" "io"
@ -222,7 +223,7 @@ func UploadPackage(ctx *context.Context) {
} }
for _, tag := range npmPackage.DistTags { for _, tag := range npmPackage.DistTags {
if err := setPackageTag(tag, pv, false); err != nil { if err := setPackageTag(ctx, tag, pv, false); err != nil {
if err == errInvalidTagName { if err == errInvalidTagName {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return
@ -345,7 +346,7 @@ func AddPackageTag(ctx *context.Context) {
return return
} }
if err := setPackageTag(ctx.Params("tag"), pv, false); err != nil { if err := setPackageTag(ctx, ctx.Params("tag"), pv, false); err != nil {
if err == errInvalidTagName { if err == errInvalidTagName {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return
@ -366,7 +367,7 @@ func DeletePackageTag(ctx *context.Context) {
} }
if len(pvs) != 0 { if len(pvs) != 0 {
if err := setPackageTag(ctx.Params("tag"), pvs[0], true); err != nil { if err := setPackageTag(ctx, ctx.Params("tag"), pvs[0], true); err != nil {
if err == errInvalidTagName { if err == errInvalidTagName {
apiError(ctx, http.StatusBadRequest, err) apiError(ctx, http.StatusBadRequest, err)
return return
@ -377,7 +378,7 @@ func DeletePackageTag(ctx *context.Context) {
} }
} }
func setPackageTag(tag string, pv *packages_model.PackageVersion, deleteOnly bool) error { func setPackageTag(ctx std_ctx.Context, tag string, pv *packages_model.PackageVersion, deleteOnly bool) error {
if tag == "" { if tag == "" {
return errInvalidTagName return errInvalidTagName
} }
@ -386,12 +387,7 @@ func setPackageTag(tag string, pv *packages_model.PackageVersion, deleteOnly boo
return errInvalidTagName return errInvalidTagName
} }
ctx, committer, err := db.TxContext(db.DefaultContext) return db.WithTx(ctx, func(ctx std_ctx.Context) error {
if err != nil {
return err
}
defer committer.Close()
pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{ pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{
PackageID: pv.PackageID, PackageID: pv.PackageID,
Properties: map[string]string{ Properties: map[string]string{
@ -425,8 +421,8 @@ func setPackageTag(tag string, pv *packages_model.PackageVersion, deleteOnly boo
return err return err
} }
} }
return nil
return committer.Commit() })
} }
func PackageSearch(ctx *context.Context) { func PackageSearch(ctx *context.Context) {

View file

@ -8,7 +8,6 @@ import (
"net/http" "net/http"
asymkey_model "code.gitea.io/gitea/models/asymkey" asymkey_model "code.gitea.io/gitea/models/asymkey"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/perm"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
@ -31,7 +30,7 @@ func appendPrivateInformation(ctx std_ctx.Context, apiKey *api.PublicKey, key *a
if defaultUser.ID == key.OwnerID { if defaultUser.ID == key.OwnerID {
apiKey.Owner = convert.ToUser(ctx, defaultUser, defaultUser) apiKey.Owner = convert.ToUser(ctx, defaultUser, defaultUser)
} else { } else {
user, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) user, err := user_model.GetUserByID(ctx, key.OwnerID)
if err != nil { if err != nil {
return apiKey, err return apiKey, err
} }

View file

@ -85,7 +85,7 @@ func Packages(ctx *context.Context) {
// DeletePackageVersion deletes a package version // DeletePackageVersion deletes a package version
func DeletePackageVersion(ctx *context.Context) { func DeletePackageVersion(ctx *context.Context) {
pv, err := packages_model.GetVersionByID(db.DefaultContext, ctx.FormInt64("id")) pv, err := packages_model.GetVersionByID(ctx, ctx.FormInt64("id"))
if err != nil { if err != nil {
ctx.ServerError("GetRepositoryByID", err) ctx.ServerError("GetRepositoryByID", err)
return return

View file

@ -4,6 +4,7 @@
package healthcheck package healthcheck
import ( import (
"context"
"net/http" "net/http"
"os" "os"
"time" "time"
@ -72,7 +73,7 @@ func Check(w http.ResponseWriter, r *http.Request) {
statuses := make([]status, 0) statuses := make([]status, 0)
if setting.InstallLock { if setting.InstallLock {
statuses = append(statuses, checkDatabase(rsp.Checks)) statuses = append(statuses, checkDatabase(r.Context(), rsp.Checks))
statuses = append(statuses, checkCache(rsp.Checks)) statuses = append(statuses, checkCache(rsp.Checks))
} }
for _, s := range statuses { for _, s := range statuses {
@ -89,9 +90,9 @@ func Check(w http.ResponseWriter, r *http.Request) {
} }
// database checks gitea database status // database checks gitea database status
func checkDatabase(checks checks) status { func checkDatabase(ctx context.Context, checks checks) status {
st := componentStatus{} st := componentStatus{}
if err := db.GetEngine(db.DefaultContext).Ping(); err != nil { if err := db.GetEngine(ctx).Ping(); err != nil {
st.Status = fail st.Status = fail
st.Time = getCheckTime() st.Time = getCheckTime()
log.Error("database ping failed with error: %v", err) log.Error("database ping failed with error: %v", err)

View file

@ -198,7 +198,7 @@ type fileInfo struct {
st typesniffer.SniffedType st typesniffer.SniffedType
} }
func getFileReader(repoID int64, blob *git.Blob) ([]byte, io.ReadCloser, *fileInfo, error) { func getFileReader(ctx gocontext.Context, repoID int64, blob *git.Blob) ([]byte, io.ReadCloser, *fileInfo, error) {
dataRc, err := blob.DataAsync() dataRc, err := blob.DataAsync()
if err != nil { if err != nil {
return nil, nil, nil, err return nil, nil, nil, err
@ -221,7 +221,7 @@ func getFileReader(repoID int64, blob *git.Blob) ([]byte, io.ReadCloser, *fileIn
return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil
} }
meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repoID, pointer.Oid) meta, err := git_model.GetLFSMetaObjectByOid(ctx, repoID, pointer.Oid)
if err != nil && err != git_model.ErrLFSObjectNotExist { // fallback to plain file if err != nil && err != git_model.ErrLFSObjectNotExist { // fallback to plain file
return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil
} }
@ -265,7 +265,7 @@ func renderReadmeFile(ctx *context.Context, subfolder string, readmeFile *git.Tr
ctx.Data["ReadmeExist"] = true ctx.Data["ReadmeExist"] = true
ctx.Data["FileIsSymlink"] = readmeFile.IsLink() ctx.Data["FileIsSymlink"] = readmeFile.IsLink()
buf, dataRc, fInfo, err := getFileReader(ctx.Repo.Repository.ID, target.Blob()) buf, dataRc, fInfo, err := getFileReader(ctx, ctx.Repo.Repository.ID, target.Blob())
if err != nil { if err != nil {
ctx.ServerError("getFileReader", err) ctx.ServerError("getFileReader", err)
return return
@ -328,7 +328,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st
ctx.Data["IsViewFile"] = true ctx.Data["IsViewFile"] = true
ctx.Data["HideRepoInfo"] = true ctx.Data["HideRepoInfo"] = true
blob := entry.Blob() blob := entry.Blob()
buf, dataRc, fInfo, err := getFileReader(ctx.Repo.Repository.ID, blob) buf, dataRc, fInfo, err := getFileReader(ctx, ctx.Repo.Repository.ID, blob)
if err != nil { if err != nil {
ctx.ServerError("getFileReader", err) ctx.ServerError("getFileReader", err)
return return