grain/server/db/mongo/purgeEvents.go

126 lines
3.5 KiB
Go
Raw Normal View History

2024-09-22 19:34:32 +00:00
package mongo
import (
"context"
"grain/config"
2024-09-22 19:34:32 +00:00
types "grain/config/types"
2024-11-09 16:08:48 +00:00
nostr "grain/server/types"
2024-11-13 02:37:43 +00:00
"grain/server/utils"
2024-09-22 19:34:32 +00:00
"log"
2024-11-13 02:37:43 +00:00
"strconv"
2024-09-22 19:34:32 +00:00
"time"
"go.mongodb.org/mongo-driver/bson"
2024-11-13 02:37:43 +00:00
"go.mongodb.org/mongo-driver/mongo"
2024-09-22 19:34:32 +00:00
)
// PurgeOldEvents removes old events based on the configuration and a list of whitelisted pubkeys.
2024-11-09 16:08:48 +00:00
func PurgeOldEvents(cfg *types.EventPurgeConfig) {
2024-09-22 19:34:32 +00:00
if !cfg.Enabled {
return
}
client := GetClient()
2024-11-16 15:42:35 +00:00
// Calculate the cutoff time
currentTime := time.Now().Unix()
cutoff := currentTime - int64(cfg.KeepIntervalHours*3600) // Convert hours to seconds
2024-11-13 02:37:43 +00:00
var collectionsToPurge []string
2024-11-16 15:42:35 +00:00
totalPurged := 0
totalKept := 0
2024-09-22 19:34:32 +00:00
2024-11-13 02:37:43 +00:00
// Determine collections to purge
if cfg.PurgeByKindEnabled {
for _, kind := range cfg.KindsToPurge {
collectionsToPurge = append(collectionsToPurge, "event-kind"+strconv.Itoa(kind))
}
} else {
collectionsToPurge = getAllEventCollections(client)
2024-09-22 19:34:32 +00:00
}
2024-11-13 02:37:43 +00:00
for _, collectionName := range collectionsToPurge {
collection := client.Database("grain").Collection(collectionName)
baseFilter := bson.M{"created_at": bson.M{"$lt": cutoff}}
2024-09-22 19:34:32 +00:00
2024-11-13 02:37:43 +00:00
cursor, err := collection.Find(context.TODO(), baseFilter)
if err != nil {
log.Printf("Error fetching old events for purging from %s: %v", collectionName, err)
2024-11-09 16:08:48 +00:00
continue
2024-09-22 19:34:32 +00:00
}
2024-11-13 02:37:43 +00:00
defer cursor.Close(context.TODO())
2024-09-22 19:34:32 +00:00
2024-11-13 02:37:43 +00:00
for cursor.Next(context.TODO()) {
var evt nostr.Event
if err := cursor.Decode(&evt); err != nil {
log.Printf("Error decoding event from %s: %v", collectionName, err)
2024-11-16 15:42:35 +00:00
totalKept++
continue
}
// Debug log to check created_at and cutoff
//log.Printf("Processing event ID: %s, pubkey: %s, created_at: %d, cutoff: %d", evt.ID, evt.PubKey, evt.CreatedAt, cutoff)
// If the event is not older than the cutoff, mark it as kept
if evt.CreatedAt >= cutoff {
totalKept++
2024-11-13 02:37:43 +00:00
continue
}
2024-11-16 15:42:35 +00:00
// Skip purging if the pubkey is whitelisted
if cfg.ExcludeWhitelisted && config.IsPubKeyWhitelisted(evt.PubKey, true) {
//log.Printf("Event ID: %s is kept because the pubkey is whitelisted.", evt.ID)
totalKept++
2024-11-13 02:37:43 +00:00
continue
}
2024-11-16 15:42:35 +00:00
// Check if purging by category is enabled and matches the event's category
2024-11-13 02:37:43 +00:00
category := utils.DetermineEventCategory(evt.Kind)
2024-11-16 15:42:35 +00:00
if purge, exists := cfg.PurgeByCategory[category]; !exists || !purge {
totalKept++
continue
}
// Proceed to delete the event
_, err = collection.DeleteOne(context.TODO(), bson.M{"id": evt.ID})
if err != nil {
log.Printf("Error purging event ID %s from %s: %v", evt.ID, collectionName, err)
totalKept++
} else {
totalPurged++
2024-11-13 02:37:43 +00:00
}
2024-11-09 16:08:48 +00:00
}
2024-11-13 02:37:43 +00:00
}
2024-11-16 15:42:35 +00:00
log.Printf("Purging completed: Total events purged = %d, Total events kept = %d", totalPurged, totalKept)
2024-11-13 02:37:43 +00:00
}
2024-11-09 16:08:48 +00:00
2024-11-13 02:37:43 +00:00
// getAllEventCollections returns a list of all event collections if purging all kinds.
func getAllEventCollections(client *mongo.Client) []string {
var collections []string
collectionNames, err := client.Database("grain").ListCollectionNames(context.TODO(), bson.M{})
if err != nil {
log.Printf("Error listing collection names: %v", err)
return collections
}
for _, name := range collectionNames {
if len(name) > 10 && name[:10] == "event-kind" {
collections = append(collections, name)
2024-09-22 19:34:32 +00:00
}
}
2024-11-13 02:37:43 +00:00
return collections
2024-09-22 19:34:32 +00:00
}
// ScheduleEventPurging runs the event purging at a configurable interval.
func ScheduleEventPurging(cfg *types.ServerConfig) {
2024-11-13 02:37:43 +00:00
purgeInterval := time.Duration(cfg.EventPurge.PurgeIntervalMinutes) * time.Minute
2024-09-22 19:34:32 +00:00
ticker := time.NewTicker(purgeInterval)
defer ticker.Stop()
for range ticker.C {
2024-11-09 16:08:48 +00:00
PurgeOldEvents(&cfg.EventPurge)
2024-11-16 15:42:35 +00:00
//log.Println("Scheduled purging completed.")
2024-09-22 19:34:32 +00:00
}
}