diff --git a/blog.go b/blog.go index 7a9e62b..fdc8ddc 100644 --- a/blog.go +++ b/blog.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "log" "net/http" @@ -25,7 +26,7 @@ const ( ) func latestBlogsHandle(w http.ResponseWriter, r *http.Request) { - latest, err := blogApp.LatestBlogs(0) + latest, err := blogApp.LatestBlogs(r.Context(), 0) if err != nil { if err == backend.ErrNotFound { w.WriteHeader(404) @@ -39,13 +40,13 @@ func latestBlogsHandle(w http.ResponseWriter, r *http.Request) { } var out string for _, b := range latest { - out += blogElement(b) + out += blogElement(r.Context(), b) } sendContent(w, r, out, "", "") } func blogHandle(w http.ResponseWriter, r *http.Request, blog string) { - bl, err := blogApp.Blog(blog) + bl, err := blogApp.Blog(r.Context(), blog) if err != nil { if err == backend.ErrNotFound { w.WriteHeader(404) @@ -57,15 +58,15 @@ func blogHandle(w http.ResponseWriter, r *http.Request, blog string) { sendContent(w, r, "Error getting page", "", "") return } - sendContent(w, r, blogElement(bl), bl.Title, bl.Favicon) + sendContent(w, r, blogElement(r.Context(), bl), bl.Title, bl.Favicon) } -func blogElement(b *blog.Blog) (out string) { +func blogElement(ctx context.Context, b *blog.Blog) (out string) { if b.StaticPage { return b.Blog } out = fmt.Sprintf(blogTitle, b.ID, b.ID, b.Title) - auth, err := blogApp.GetAuthor(b) + auth, err := blogApp.GetAuthor(ctx, b) if err == nil { out += fmt.Sprintf(blogAuthor, auth.Name) } else { diff --git a/internal/backend/app.go b/internal/backend/app.go index be31929..0f085ae 100644 --- a/internal/backend/app.go +++ b/internal/backend/app.go @@ -1,6 +1,9 @@ package backend -import "net/http" +import ( + "context" + "net/http" +) // An application interface. Both LogTable and CrashTable are optional, if they return nil then requests will be forbidden. type App interface { @@ -18,7 +21,7 @@ type CallbackApp interface { // Allows for an App to filter crashes before they get added to the DB, such as making sure the crash is from the correct version. type CrashFilterApp interface { App - AddCrash(IndividualCrash) bool + ShouldAddCrash(context.Context, IndividualCrash) bool } // Allows an app more flexibility by directly interfacing with the backend's mux diff --git a/internal/backend/count.go b/internal/backend/count.go index 1c77f08..31dd8cd 100644 --- a/internal/backend/count.go +++ b/internal/backend/count.go @@ -1,6 +1,7 @@ package backend import ( + "context" "encoding/json" "log" "net/http" @@ -53,15 +54,15 @@ func (b *Backend) countLog(w http.ResponseWriter, r *http.Request) { } curDate := getDate(time.Now()) if req.ID == "" { - err = addToCountTable(w, count, req.Platform, curDate) + err = addToCountTable(r.Context(), w, count, req.Platform, curDate) if err != nil { log.Println("error adding to count table:", err) } return } - l, err := count.Get(req.ID) + l, err := count.Get(r.Context(), req.ID) if err == ErrNotFound { - err = addToCountTable(w, count, req.Platform, curDate) + err = addToCountTable(r.Context(), w, count, req.Platform, curDate) if err != nil { log.Println("error adding to count table:", err) } @@ -72,7 +73,7 @@ func (b *Backend) countLog(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) return } - err = count.PartUpdate(req.ID, map[string]any{"date": curDate}) + err = count.PartUpdate(r.Context(), req.ID, map[string]any{"date": curDate}) if err != nil { log.Println("error updating count log:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -82,14 +83,14 @@ func (b *Backend) countLog(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(map[string]string{"id": req.ID}) } -func addToCountTable(w http.ResponseWriter, c CountTable, platform string, curDate int) error { +func addToCountTable(ctx context.Context, w http.ResponseWriter, c CountTable, platform string, curDate int) error { id, err := uuid.NewV7() if err != nil { log.Println("error generating new log UUID:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") return err } - err = c.Insert(CountLog{ + err = c.Insert(ctx, CountLog{ ID: id.String(), Platform: platform, Date: curDate, @@ -127,7 +128,7 @@ func (b *Backend) getCount(w http.ResponseWriter, r *http.Request) { ReturnError(w, http.StatusBadRequest, "badRequest", "Trying to get user count on app that doesn't have a count table") return } - out, err := count.Count(r.URL.Query().Get("platform")) + out, err := count.Count(r.Context(), r.URL.Query().Get("platform")) if err != nil { log.Println("error getting count:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") diff --git a/internal/backend/crash.go b/internal/backend/crash.go index e4df220..d6073f9 100644 --- a/internal/backend/crash.go +++ b/internal/backend/crash.go @@ -1,6 +1,7 @@ package backend import ( + "context" "encoding/json" "log" "net/http" @@ -49,7 +50,7 @@ func (b *Backend) reportCrash(w http.ResponseWriter, r *http.Request) { return } if filter, ok := ap.(CrashFilterApp); ok { - if !filter.AddCrash(crash) { + if !filter.ShouldAddCrash(r.Context(), crash) { return } } @@ -59,8 +60,8 @@ func (b *Backend) reportCrash(w http.ResponseWriter, r *http.Request) { ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server misconfigured") return } - if !tab.IsArchived(crash) { - err = tab.InsertCrash(crash) + if !tab.IsArchived(r.Context(), crash) { + err = tab.InsertCrash(r.Context(), crash) if err != nil { log.Println("crash insertion error:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -83,7 +84,7 @@ func (b *Backend) deleteCrash(w http.ResponseWriter, r *http.Request) { ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request") return } - b.actualCrashDelete(w, b.GetApp(hdr.Key), crashID) + b.actualCrashDelete(r.Context(), w, b.GetApp(hdr.Key), crashID) } func (b *Backend) managementDeleteCrash(w http.ResponseWriter, r *http.Request) { @@ -105,16 +106,16 @@ func (b *Backend) managementDeleteCrash(w http.ResponseWriter, r *http.Request) ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request") return } - b.actualCrashDelete(w, ap, crashID) + b.actualCrashDelete(r.Context(), w, ap, crashID) } -func (b *Backend) actualCrashDelete(w http.ResponseWriter, ap App, crashID string) { +func (b *Backend) actualCrashDelete(ctx context.Context, w http.ResponseWriter, ap App, crashID string) { crash := ap.CrashTable() if crash == nil { ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server Misconfigured") return } - err := crash.Remove(crashID) + err := crash.Remove(ctx, crashID) if err != nil && err != ErrNotFound { log.Println("error when deleting crash:", err) } @@ -135,7 +136,7 @@ func (b *Backend) archiveCrash(w http.ResponseWriter, r *http.Request) { ReturnError(w, http.StatusBadRequest, "invalidBody", "Bad request") return } - b.actualCrashArchive(w, b.GetApp(hdr.Key), toArchive) + b.actualCrashArchive(r.Context(), w, b.GetApp(hdr.Key), toArchive) } func (b *Backend) managementArchiveCrash(w http.ResponseWriter, r *http.Request) { @@ -159,22 +160,22 @@ func (b *Backend) managementArchiveCrash(w http.ResponseWriter, r *http.Request) ReturnError(w, http.StatusBadRequest, "invalidBody", "Bad request") return } - b.actualCrashArchive(w, ap, toArchive) + b.actualCrashArchive(r.Context(), w, ap, toArchive) } -func (b *Backend) actualCrashArchive(w http.ResponseWriter, ap App, toArchive ArchivedCrash) { +func (b *Backend) actualCrashArchive(ctx context.Context, w http.ResponseWriter, ap App, toArchive ArchivedCrash) { crash := ap.CrashTable() if crash == nil { ReturnError(w, http.StatusInternalServerError, "misconfigured", "Server Misconfigured") return } - err := crash.Archive(toArchive) + err := crash.Archive(ctx, toArchive) if err != nil { log.Println("error archive crash:", err) return } first, _, _ := strings.Cut(toArchive.Stack, "\n") - crashes, err := crash.Find(map[string]any{"error": toArchive.Error, "firstLine": first}) + crashes, err := crash.Find(ctx, map[string]any{"error": toArchive.Error, "firstLine": first}) if err == ErrNotFound { return } else if err != nil { @@ -194,12 +195,12 @@ func (b *Backend) actualCrashArchive(w http.ResponseWriter, ap App, toArchive Ar } } if len(c.Individual) == 0 { - err = crash.Remove(c.ID) + err = crash.Remove(ctx, c.ID) if err != nil { log.Println("error removing empty crash report:", err) } } else if len(c.Individual) < ogLen { - err = crash.PartUpdate(c.ID, map[string]any{"individual": c.Individual}) + err = crash.PartUpdate(ctx, c.ID, map[string]any{"individual": c.Individual}) if err != nil { log.Println("error updating individual crash reports:", err) } diff --git a/internal/backend/darkstorm.go b/internal/backend/darkstorm.go index 4aef5c4..0c3cc5a 100644 --- a/internal/backend/darkstorm.go +++ b/internal/backend/darkstorm.go @@ -1,6 +1,7 @@ package backend import ( + "context" "crypto/ed25519" "embed" "encoding/json" @@ -83,7 +84,7 @@ func (b *Backend) cleanupLoop() { if tab == nil { continue } - err = tab.RemoveOldLogs(old) + err = tab.RemoveOldLogs(context.Background(), old) if err != nil { log.Printf("error removing old logs for %v: %v\n", a.AppID(), err) } diff --git a/internal/backend/db.go b/internal/backend/db.go index 83b228c..ab85765 100644 --- a/internal/backend/db.go +++ b/internal/backend/db.go @@ -1,6 +1,9 @@ package backend -import "errors" +import ( + "context" + "errors" +) var ( ErrNotFound = errors.New("no matches found in table") @@ -11,28 +14,28 @@ type IDStruct interface { } type Table[T IDStruct] interface { - Get(ID string) (data *T, err error) - Find(values map[string]any) ([]T, error) - Insert(data T) error - Remove(ID string) error - FullUpdate(ID string, data T) error - PartUpdate(ID string, update map[string]any) error + Get(ctx context.Context, ID string) (data *T, err error) + Find(ctx context.Context, values map[string]any) ([]T, error) + Insert(ctx context.Context, data T) error + Remove(ctx context.Context, ID string) error + FullUpdate(ctx context.Context, ID string, data T) error + PartUpdate(ctx context.Context, ID string, update map[string]any) error } type CountTable interface { Table[CountLog] // Remove all Log items that have a CountLog.Date value less then the given value. - RemoveOldLogs(date int) error + RemoveOldLogs(ctx context.Context, date int) error // Get count. If platform is an empty string or "all", the full count should be given - Count(platform string) (int, error) + Count(ctx context.Context, platform string) (int, error) } type CrashTable interface { Table[CrashReport] // Move a crash type to archive. Crashes that match the archived crash will be automatically removed from the CrashTable. - Archive(ArchivedCrash) error - IsArchived(IndividualCrash) bool + Archive(context.Context, ArchivedCrash) error + IsArchived(context.Context, IndividualCrash) bool // Add the IndividualCrash report to the crash table. If a CrashReport exists that matches, then it gets added to CrashReport.Individual. // If an IndividualCrash exists that is a perfect match, Count is incremented instead of adding it to the array. - InsertCrash(IndividualCrash) error + InsertCrash(context.Context, IndividualCrash) error } diff --git a/internal/backend/db/mongo.go b/internal/backend/db/mongo.go index efa5f74..a72689b 100644 --- a/internal/backend/db/mongo.go +++ b/internal/backend/db/mongo.go @@ -18,8 +18,8 @@ func NewMongoTable[T backend.IDStruct](col *mongo.Collection) *MongoTable[T] { } } -func (m *MongoTable[T]) Get(ID string) (data *T, err error) { - res := m.col.FindOne(context.Background(), bson.M{"_id": ID}) +func (m *MongoTable[T]) Get(ctx context.Context, ID string) (data *T, err error) { + res := m.col.FindOne(ctx, bson.M{"_id": ID}) if res.Err() == mongo.ErrNoDocuments { return nil, backend.ErrNotFound } else if res.Err() != nil { @@ -30,58 +30,58 @@ func (m *MongoTable[T]) Get(ID string) (data *T, err error) { return &out, err } -func (m *MongoTable[T]) Find(values map[string]any) ([]T, error) { - res, err := m.col.Find(context.Background(), values) +func (m *MongoTable[T]) Find(ctx context.Context, values map[string]any) ([]T, error) { + res, err := m.col.Find(ctx, values) if err == mongo.ErrNoDocuments { return nil, backend.ErrNotFound } else if err != nil { return nil, err } var out []T - err = res.All(context.Background(), &out) + err = res.All(ctx, &out) return out, err } -func (m *MongoTable[T]) Insert(data T) error { - _, err := m.col.InsertOne(context.Background(), data) +func (m *MongoTable[T]) Insert(ctx context.Context, data T) error { + _, err := m.col.InsertOne(ctx, data) return err } -func (m *MongoTable[T]) Remove(ID string) error { - res := m.col.FindOneAndDelete(context.Background(), bson.M{"_id": ID}) +func (m *MongoTable[T]) Remove(ctx context.Context, ID string) error { + res := m.col.FindOneAndDelete(ctx, bson.M{"_id": ID}) return res.Err() } -func (m *MongoTable[T]) FullUpdate(ID string, data T) error { - res := m.col.FindOneAndReplace(context.Background(), bson.M{"_id": ID}, data) +func (m *MongoTable[T]) FullUpdate(ctx context.Context, ID string, data T) error { + res := m.col.FindOneAndReplace(ctx, bson.M{"_id": ID}, data) if res.Err() == mongo.ErrNoDocuments { return backend.ErrNotFound } return res.Err() } -func (m *MongoTable[T]) PartUpdate(ID string, update map[string]any) error { - res := m.col.FindOneAndUpdate(context.Background(), bson.M{"_id": ID}, bson.M{"$set": update}) +func (m *MongoTable[T]) PartUpdate(ctx context.Context, ID string, update map[string]any) error { + res := m.col.FindOneAndUpdate(ctx, bson.M{"_id": ID}, bson.M{"$set": update}) if res.Err() == mongo.ErrNoDocuments { return backend.ErrNotFound } return res.Err() } -func (m *MongoTable[CountLog]) RemoveOldLogs(date int) error { - _, err := m.col.DeleteMany(context.Background(), bson.M{"date": bson.M{"$lt": date}}) +func (m *MongoTable[CountLog]) RemoveOldLogs(ctx context.Context, date int) error { + _, err := m.col.DeleteMany(ctx, bson.M{"date": bson.M{"$lt": date}}) if err == mongo.ErrNoDocuments { return nil } return err } -func (m *MongoTable[CountLog]) Count(platform string) (int, error) { +func (m *MongoTable[CountLog]) Count(ctx context.Context, platform string) (int, error) { var filter bson.M if platform == "" || platform == "all" { filter = bson.M{} } else { filter = bson.M{"platform": platform} } - out, err := m.col.CountDocuments(context.Background(), filter) + out, err := m.col.CountDocuments(ctx, filter) return int(out), err } diff --git a/internal/backend/db/mongo_crash.go b/internal/backend/db/mongo_crash.go index 46e8b8c..7f48e7a 100644 --- a/internal/backend/db/mongo_crash.go +++ b/internal/backend/db/mongo_crash.go @@ -22,24 +22,24 @@ func NewMongoCrashTable(crashCol *mongo.Collection, archiveCol *mongo.Collection } } -func (m *MongoCrashTable) Archive(toArchive backend.ArchivedCrash) error { +func (m *MongoCrashTable) Archive(ctx context.Context, toArchive backend.ArchivedCrash) error { if toArchive.Platform == "" { toArchive.Platform = "all" } - _, err := m.archiveCol.InsertOne(context.Background(), toArchive) + _, err := m.archiveCol.InsertOne(ctx, toArchive) return err } -func (m *MongoCrashTable) IsArchived(ind backend.IndividualCrash) bool { - res := m.archiveCol.FindOne(context.Background(), +func (m *MongoCrashTable) IsArchived(ctx context.Context, ind backend.IndividualCrash) bool { + res := m.archiveCol.FindOne(ctx, bson.M{"error": ind.Error, "stack": ind.Stack, "platform": bson.M{"$in": []string{ind.Platform, "all"}}}, ) return res.Err() == nil } -func (m *MongoCrashTable) InsertCrash(ind backend.IndividualCrash) error { +func (m *MongoCrashTable) InsertCrash(ctx context.Context, ind backend.IndividualCrash) error { first, _, _ := strings.Cut(ind.Stack, "\n") - res, err := m.col.UpdateOne(context.Background(), + res, err := m.col.UpdateOne(ctx, bson.M{"error": ind.Error, "firstLine": first, //filter main report "individual": bson.M{"$elemMatch": bson.M{"stack": ind.Stack, "platform": ind.Platform}}}, //filter individual bson.M{"$inc": bson.M{"individual.$.count": 1}}, //increment count @@ -49,7 +49,7 @@ func (m *MongoCrashTable) InsertCrash(ind backend.IndividualCrash) error { } if err == mongo.ErrNoDocuments || res.MatchedCount == 0 { ind.Count = 1 - res, err = m.col.UpdateMany(context.Background(), + res, err = m.col.UpdateMany(ctx, bson.M{"error": ind.Error, "firstLine": first}, //filter bson.M{"$push": bson.M{"individual": ind}}, //Add new individual report ) @@ -63,7 +63,7 @@ func (m *MongoCrashTable) InsertCrash(ind backend.IndividualCrash) error { return err } ind.Count = 1 - _, err = m.col.InsertOne(context.Background(), + _, err = m.col.InsertOne(ctx, backend.CrashReport{ ID: id.String(), Error: ind.Error, diff --git a/internal/backend/header.go b/internal/backend/header.go index 755d7a2..331d410 100644 --- a/internal/backend/header.go +++ b/internal/backend/header.go @@ -45,7 +45,7 @@ func (b *Backend) ParseHeader(r *http.Request) (*ParsedHeader, error) { token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") if key != "" { - apiKey, err := b.keyTable.Get(key) + apiKey, err := b.keyTable.Get(r.Context(), key) if err == ErrNotFound { return nil, ErrApiKeyUnauthorized } else if err != nil { @@ -73,7 +73,7 @@ func (b *Backend) ParseHeader(r *http.Request) (*ParsedHeader, error) { } else if err != nil { return out, errors.Join(ErrTokenUnauthorized, err) } - usr, err := b.userTable.Get(sub) + usr, err := b.userTable.Get(r.Context(), sub) if err == jwt.ErrInvalidKey { return out, ErrTokenUnauthorized } else if err != nil { diff --git a/internal/backend/user.go b/internal/backend/user.go index ddfc6f5..ea39a58 100644 --- a/internal/backend/user.go +++ b/internal/backend/user.go @@ -139,7 +139,7 @@ func (b *Backend) createUser(w http.ResponseWriter, r *http.Request) { // TODO: filter offensive words/phrases b.userMutex.Lock() defer b.userMutex.Unlock() - matchUsername, err := b.userTable.Find(map[string]any{"username": req.Username}) + matchUsername, err := b.userTable.Find(r.Context(), map[string]any{"username": req.Username}) if err != nil && !errors.Is(err, ErrNotFound) { log.Println("error when checking for username collisions:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -148,7 +148,7 @@ func (b *Backend) createUser(w http.ResponseWriter, r *http.Request) { ReturnError(w, http.StatusUnauthorized, "taken", "Username or email already used") return } - matchEmail, err := b.userTable.Find(map[string]any{"email": req.Email}) + matchEmail, err := b.userTable.Find(r.Context(), map[string]any{"email": req.Email}) if err != nil && !errors.Is(err, ErrNotFound) { log.Println("error when checking for email collisions:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -163,7 +163,7 @@ func (b *Backend) createUser(w http.ResponseWriter, r *http.Request) { ReturnError(w, http.StatusInternalServerError, "internal", "Server error") return } - err = b.userTable.Insert(u) + err = b.userTable.Insert(r.Context(), u) if err != nil { log.Println("error inserting new user:", err) ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -196,7 +196,7 @@ func (b *Backend) deleteUser(w http.ResponseWriter, r *http.Request) { } b.userMutex.Lock() defer b.userMutex.Unlock() - err = b.userTable.Remove(userID) + err = b.userTable.Remove(r.Context(), userID) if err != nil && err != ErrNotFound { log.Println("error deleting user:", err) } @@ -231,7 +231,7 @@ func (b *Backend) login(w http.ResponseWriter, r *http.Request) { b.userMutex.RLock() defer b.userMutex.RUnlock() var ret loginReturn - users, err := b.userTable.Find(map[string]any{"username": req.Username}) + users, err := b.userTable.Find(r.Context(), map[string]any{"username": req.Username}) if errors.Is(err, ErrNotFound) || len(users) != 1 { ret.Error = "invalid" w.WriteHeader(http.StatusUnauthorized) @@ -269,7 +269,7 @@ func (b *Backend) login(w http.ResponseWriter, r *http.Request) { upd["timeout"] = timeout ret.Timeout = timeout - time.Now().Unix() } - b.userTable.PartUpdate(u.ID, upd) + b.userTable.PartUpdate(r.Context(), u.ID, upd) w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(ret) } diff --git a/internal/blog/author.go b/internal/blog/author.go index 66133c5..da47f5f 100644 --- a/internal/blog/author.go +++ b/internal/blog/author.go @@ -20,8 +20,8 @@ type Author struct { PicURL string `json:"picurl" bson:"picurl"` } -func (b *BlogApp) AboutMe() (*Author, error) { - res := b.authCol.FindOne(context.Background(), bson.M{"_id": "caleb_gardner"}) +func (b *BlogApp) AboutMe(ctx context.Context) (*Author, error) { + res := b.authCol.FindOne(ctx, bson.M{"_id": "caleb_gardner"}) if res.Err() != nil { log.Println("error getting about me:", res.Err()) if res.Err() == mongo.ErrNoDocuments { @@ -39,7 +39,7 @@ func (b *BlogApp) AboutMe() (*Author, error) { } func (b *BlogApp) reqAuthorInfo(w http.ResponseWriter, r *http.Request) { - res := b.authCol.FindOne(context.Background(), r.PathValue("authorID")) + res := b.authCol.FindOne(r.Context(), r.PathValue("authorID")) if res.Err() == mongo.ErrNoDocuments { backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found") return @@ -85,7 +85,7 @@ func (b *BlogApp) addAuthorInfo(w http.ResponseWriter, r *http.Request) { if i != 1 { newID += strconv.Itoa(i) } - collisionCheck := b.authCol.FindOne(context.Background(), bson.M{"name": newAuth.Name}) + collisionCheck := b.authCol.FindOne(r.Context(), bson.M{"name": newAuth.Name}) if collisionCheck.Err() == mongo.ErrNoDocuments { newAuth.ID = newID break @@ -95,7 +95,7 @@ func (b *BlogApp) addAuthorInfo(w http.ResponseWriter, r *http.Request) { return } } - _, err = b.authCol.InsertOne(context.Background(), newAuth) + _, err = b.authCol.InsertOne(r.Context(), newAuth) if err != nil { log.Println("error inserting new author:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error") @@ -136,7 +136,7 @@ func (b *BlogApp) updateAuthorInfo(w http.ResponseWriter, r *http.Request) { if rawUpd["picurl"] != "" { actlUpd["picurl"] = rawUpd["picurl"] } - res, err := b.authCol.UpdateByID(context.Background(), r.PathValue("authorID"), actlUpd) + res, err := b.authCol.UpdateByID(r.Context(), r.PathValue("authorID"), actlUpd) if err != nil { if err == mongo.ErrNoDocuments { backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found") diff --git a/internal/blog/blog.go b/internal/blog/blog.go index 47cf5e5..8cddc1a 100644 --- a/internal/blog/blog.go +++ b/internal/blog/blog.go @@ -33,8 +33,8 @@ func (b *BlogApp) ConvertBlog(blog *Blog) { } } -func (b *BlogApp) GetAuthor(blog *Blog) (*Author, error) { - res := b.authCol.FindOne(context.Background(), bson.M{"_id": blog.Author}) +func (b *BlogApp) GetAuthor(ctx context.Context, blog *Blog) (*Author, error) { + res := b.authCol.FindOne(ctx, bson.M{"_id": blog.Author}) if res.Err() != nil { if res.Err() == mongo.ErrNoDocuments { return nil, backend.ErrNotFound @@ -46,14 +46,14 @@ func (b *BlogApp) GetAuthor(blog *Blog) (*Author, error) { return &author, err } -func (b *BlogApp) Blog(ID string) (*Blog, error) { +func (b *BlogApp) Blog(ctx context.Context, ID string) (*Blog, error) { b.cacheMutex.RLock() blog, has := b.blogCache[ID] b.cacheMutex.RUnlock() if has { return &blog, nil } - res := b.blogCol.FindOne(context.Background(), bson.M{"_id": ID, "draft": false}) + res := b.blogCol.FindOne(ctx, bson.M{"_id": ID, "draft": false}) if res.Err() != nil { if res.Err() == mongo.ErrNoDocuments { return nil, backend.ErrNotFound @@ -85,7 +85,7 @@ func (b *BlogApp) reqBlog(w http.ResponseWriter, r *http.Request) { backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Must provide a blogID") return } - blog, err := b.Blog(blogID) + blog, err := b.Blog(r.Context(), blogID) if err != nil { if err == backend.ErrNotFound { backend.ReturnError(w, http.StatusNotFound, "notFound", "Not blog found with the given ID") @@ -130,7 +130,7 @@ func (b *BlogApp) createBlog(w http.ResponseWriter, r *http.Request) { newBlog.CreateTime = tim newBlog.UpdateTime = tim newBlog.Author = hdr.User.Username - _, err = b.blogCol.InsertOne(context.Background(), newBlog) + _, err = b.blogCol.InsertOne(r.Context(), newBlog) if err != nil { log.Println("error when inserting new blog:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error") @@ -177,7 +177,7 @@ func (b *BlogApp) updateBlog(w http.ResponseWriter, r *http.Request) { reqUpd["blog"] = blog } reqUpd["updateTime"] = time.Now().Unix() - res, err := b.blogCol.UpdateByID(context.Background(), r.PathValue("blogID"), reqUpd) + res, err := b.blogCol.UpdateByID(r.Context(), r.PathValue("blogID"), reqUpd) if err != nil { if err == mongo.ErrNoDocuments { backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found") @@ -193,8 +193,8 @@ func (b *BlogApp) updateBlog(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) } -func (b *BlogApp) LatestBlogs(page int64) ([]*Blog, error) { - res, err := b.blogCol.Find(context.Background(), bson.M{"staticPage": false, "draft": false}, options.Find(). +func (b *BlogApp) LatestBlogs(ctx context.Context, page int64) ([]*Blog, error) { + res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find(). SetSort(bson.M{"createTime": -1}). SetLimit(5). SetSkip(page*5)) @@ -205,7 +205,7 @@ func (b *BlogApp) LatestBlogs(page int64) ([]*Blog, error) { return nil, err } var out []*Blog - err = res.All(context.Background(), &out) + err = res.All(ctx, &out) if err != nil { return nil, err } @@ -225,7 +225,7 @@ func (b *BlogApp) reqLatestBlogs(w http.ResponseWriter, r *http.Request) { page = 0 } } - blogs, err := b.LatestBlogs(int64(page)) + blogs, err := b.LatestBlogs(r.Context(), int64(page)) if err != nil && err != backend.ErrNotFound { log.Println("error getting latest blogs:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error") @@ -245,8 +245,8 @@ type BlogListResult struct { CreateTime int `json:"createTime" bson:"createTime"` } -func (b *BlogApp) BlogList(page int64) ([]BlogListResult, error) { - res, err := b.blogCol.Find(context.Background(), bson.M{}, options.Find(). +func (b *BlogApp) BlogList(ctx context.Context, page int64) ([]BlogListResult, error) { + res, err := b.blogCol.Find(ctx, bson.M{}, options.Find(). SetProjection(bson.M{"_id": 1, "createTime": 1}). SetSort(bson.M{"createTime": 1}). SetLimit(50). @@ -258,7 +258,7 @@ func (b *BlogApp) BlogList(page int64) ([]BlogListResult, error) { return nil, err } var out []BlogListResult - err = res.All(context.Background(), &out) + err = res.All(ctx, &out) if err != nil { return nil, err } @@ -275,7 +275,7 @@ func (b *BlogApp) reqBlogList(w http.ResponseWriter, r *http.Request) { page = 0 } } - blogList, err := b.BlogList(int64(page)) + blogList, err := b.BlogList(r.Context(), int64(page)) if err != nil && err != backend.ErrNotFound { log.Println("error getting blog list:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error") diff --git a/internal/blog/portfolio.go b/internal/blog/portfolio.go index 807f6f1..b9aca36 100644 --- a/internal/blog/portfolio.go +++ b/internal/blog/portfolio.go @@ -22,22 +22,22 @@ type PortfolioProject struct { } `json:"language" bson:"language"` } -func (b *BlogApp) Projects(languageFilter string) ([]PortfolioProject, error) { +func (b *BlogApp) Projects(ctx context.Context, languageFilter string) ([]PortfolioProject, error) { filter := bson.M{} if languageFilter != "" { filter["language.language"] = languageFilter } - res, err := b.portfolioCol.Find(context.Background(), filter, options.Find().SetSort(bson.M{"order": 1})) + res, err := b.portfolioCol.Find(ctx, filter, options.Find().SetSort(bson.M{"order": 1})) if err != nil { return nil, err } var out []PortfolioProject - err = res.All(context.Background(), &out) + err = res.All(ctx, &out) return out, err } func (b *BlogApp) reqPortfolio(w http.ResponseWriter, r *http.Request) { - folio, err := b.Projects(r.URL.Query().Get("lang")) + folio, err := b.Projects(r.Context(), r.URL.Query().Get("lang")) if err != nil { backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error") return diff --git a/internal/cdr/backend.go b/internal/cdr/backend.go index 0ff7990..1100674 100644 --- a/internal/cdr/backend.go +++ b/internal/cdr/backend.go @@ -49,9 +49,9 @@ func (b *CDRBackend) AddBackend(back *backend.Backend) { b.back = back } -func (s CDRBackend) AddCrash(cr backend.IndividualCrash) bool { - res := s.db.Collection("versions").FindOne(context.Background(), bson.M{"version": cr.Version}) - return res.Err() != mongo.ErrNoDocuments +func (s CDRBackend) ShouldAddCrash(ctx context.Context, cr backend.IndividualCrash) bool { + res := s.db.Collection("versions").FindOne(ctx, bson.M{"version": cr.Version}) + return res.Err() == nil } func (b CDRBackend) Extension(mux *http.ServeMux) { diff --git a/internal/cdr/die.go b/internal/cdr/die.go index 3c55570..6e62cc7 100644 --- a/internal/cdr/die.go +++ b/internal/cdr/die.go @@ -1,7 +1,6 @@ package cdr import ( - "context" "encoding/json" "io" "log" @@ -56,7 +55,7 @@ func (b CDRBackend) UploadDie(w http.ResponseWriter, r *http.Request) { if toUpload.Die["uuid"] != nil { delete(toUpload.Die, "uuid") } - _, err = b.db.Collection("dice").InsertOne(context.Background(), toUpload) + _, err = b.db.Collection("dice").InsertOne(r.Context(), toUpload) if err != nil { backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error") log.Println("error inserting die:", err) @@ -67,7 +66,7 @@ func (b CDRBackend) UploadDie(w http.ResponseWriter, r *http.Request) { } func (b CDRBackend) GetDie(w http.ResponseWriter, r *http.Request) { - res := b.db.Collection("dice").FindOne(context.Background(), bson.M{"_id": r.PathValue("dieID")}) + res := b.db.Collection("dice").FindOne(r.Context(), bson.M{"_id": r.PathValue("dieID")}) if res.Err() == mongo.ErrNoDocuments { backend.ReturnError(w, 404, "not found", "Die with the given id is not found") return diff --git a/internal/swassistant/main.go b/internal/swassistant/main.go index 4de7646..1c8377a 100644 --- a/internal/swassistant/main.go +++ b/internal/swassistant/main.go @@ -49,8 +49,8 @@ func (s *SWBackend) AddBackend(b *backend.Backend) { s.back = b } -func (s *SWBackend) AddCrash(cr backend.IndividualCrash) bool { - res := s.db.Collection("versions").FindOne(context.Background(), bson.M{"version": cr.Version}) +func (s *SWBackend) ShouldAddCrash(ctx context.Context, cr backend.IndividualCrash) bool { + res := s.db.Collection("versions").FindOne(ctx, bson.M{"version": cr.Version}) return res.Err() != mongo.ErrNoDocuments } diff --git a/internal/swassistant/profile.go b/internal/swassistant/profile.go index d97eaf8..4270eb8 100644 --- a/internal/swassistant/profile.go +++ b/internal/swassistant/profile.go @@ -1,7 +1,6 @@ package swassistant import ( - "context" "encoding/json" "io" "log" @@ -61,7 +60,7 @@ func (s *SWBackend) UploadProfile(w http.ResponseWriter, r *http.Request) { Type: profType, Profile: prof, } - _, err = s.db.Collection("profiles").InsertOne(context.Background(), toUpload) + _, err = s.db.Collection("profiles").InsertOne(r.Context(), toUpload) if err != nil { backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error") log.Println("error inserting profile:", err) @@ -72,7 +71,7 @@ func (s *SWBackend) UploadProfile(w http.ResponseWriter, r *http.Request) { } func (s *SWBackend) GetProfile(w http.ResponseWriter, r *http.Request) { - res := s.db.Collection("profiles").FindOne(context.Background(), bson.M{"_id": r.PathValue("profileID")}) + res := s.db.Collection("profiles").FindOne(r.Context(), bson.M{"_id": r.PathValue("profileID")}) if res.Err() == mongo.ErrNoDocuments { backend.ReturnError(w, 404, "not found", "Profile not found") return diff --git a/internal/swassistant/room.go b/internal/swassistant/room.go index dd0ced1..81c8ec3 100644 --- a/internal/swassistant/room.go +++ b/internal/swassistant/room.go @@ -1,7 +1,6 @@ package swassistant import ( - "context" "encoding/json" "log" "net/http" @@ -30,7 +29,8 @@ func (s *SWBackend) ListRooms(w http.ResponseWriter, r *http.Request) { backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application not authorized") return } - res, err := s.db.Collection("rooms").Find(context.Background(), bson.M{"users": hdr.User.Username}, options.Find().SetProjection(bson.M{"_id": 1, "name": 1, "owner": 1})) + res, err := s.db.Collection("rooms").Find(r.Context(), bson.M{"users": hdr.User.Username}, + options.Find().SetProjection(bson.M{"_id": 1, "name": 1, "owner": 1})) if err != nil && err != mongo.ErrNoDocuments { log.Println("error getting room list:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -42,7 +42,7 @@ func (s *SWBackend) ListRooms(w http.ResponseWriter, r *http.Request) { Owner string `json:"owner" bson:"owner"` }, 0) if err == nil { - err = res.All(context.Background(), &out) + err = res.All(r.Context(), &out) if err != nil { log.Println("error decoding room list:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -74,7 +74,7 @@ func (s *SWBackend) NewRoom(w http.ResponseWriter, r *http.Request) { Users: []string{}, Profiles: []string{}, } - _, err = s.db.Collection("rooms").InsertOne(context.Background(), newRoom) + _, err = s.db.Collection("rooms").InsertOne(r.Context(), newRoom) if err != nil { log.Println("error creating room:", err) backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error") @@ -93,7 +93,7 @@ func (s *SWBackend) GetRoom(w http.ResponseWriter, r *http.Request) { return } roomID := r.PathValue("roomID") - res := s.db.Collection("rooms").FindOne(context.TODO(), bson.M{"_id": roomID}) + res := s.db.Collection("rooms").FindOne(r.Context(), bson.M{"_id": roomID}) if res.Err() == mongo.ErrNoDocuments { backend.ReturnError(w, http.StatusNotFound, "not found", "Room not found") return diff --git a/portfolio.go b/portfolio.go index ff26845..b46c83e 100644 --- a/portfolio.go +++ b/portfolio.go @@ -20,7 +20,7 @@ const ( func portfolioRequest(w http.ResponseWriter, r *http.Request) { selectedLang := r.URL.Query().Get("lang") - proj, err := blogApp.Projects(selectedLang) + proj, err := blogApp.Projects(r.Context(), selectedLang) if err != nil { log.Println("error getting portfolio projects:", err) w.WriteHeader(http.StatusInternalServerError) @@ -28,7 +28,7 @@ func portfolioRequest(w http.ResponseWriter, r *http.Request) { return } aboutMe := "