backup relay configuration added

This commit is contained in:
Chris kerr 2024-11-09 13:26:59 -05:00
parent 59d6caaf09
commit 8491827b06
3 changed files with 53 additions and 0 deletions

View File

@ -14,6 +14,10 @@ server:
max_connections: 100
max_subscriptions_per_client: 10
backup_relay:
enabled: false # Set to true to enable sending events to the backup relay
url: "wss://some-relay.com" # URL of the backup relay
event_time_constraints:
min_created_at: 1577836800 # January 1, 2020, as Unix timestamp
# min_created_at_string: now-5m # Custom value to indicate 5 minutes in the past

View File

@ -26,4 +26,8 @@ type ServerConfig struct {
Auth AuthConfig `yaml:"auth"`
EventPurge EventPurgeConfig `yaml:"event_purge"`
EventTimeConstraints EventTimeConstraints `yaml:"event_time_constraints"` // Added this field
BackupRelay struct {
Enabled bool `yaml:"enabled"`
URL string `yaml:"url"`
} `yaml:"backup_relay"`
}

View File

@ -6,6 +6,7 @@ import (
"fmt"
"grain/config"
"grain/server/db/mongo"
"log"
"time"
"grain/server/handlers/response"
@ -82,6 +83,50 @@ func HandleEvent(ws *websocket.Conn, message []interface{}) {
// Store the event in MongoDB or other storage
mongo.StoreMongoEvent(context.TODO(), evt, ws)
fmt.Println("Event processed:", evt.ID)
// Load the config and check for errors
cfg, err := config.LoadConfig("config.yml")
if err != nil {
log.Printf("Error loading configuration: %v", err)
return
}
// Send the event to the backup relay if configured
if cfg.BackupRelay.Enabled {
go func() {
err := sendToBackupRelay(cfg.BackupRelay.URL, evt)
if err != nil {
log.Printf("Failed to send event %s to backup relay: %v", evt.ID, err)
} else {
log.Printf("Event %s successfully sent to backup relay", evt.ID)
}
}()
}
}
func sendToBackupRelay(backupURL string, evt nostr.Event) error {
conn, err := websocket.Dial(backupURL, "", "http://localhost/")
if err != nil {
return fmt.Errorf("error connecting to backup relay %s: %w", backupURL, err)
}
defer conn.Close()
// Create the message to send
eventMessage := []interface{}{"EVENT", evt}
eventMessageBytes, err := json.Marshal(eventMessage)
if err != nil {
return fmt.Errorf("error marshaling event message: %w", err)
}
if _, err := conn.Write(eventMessageBytes); err != nil {
return fmt.Errorf("error sending event message to backup relay: %w", err)
}
// Log and return
log.Printf("Event %s sent to backup relay %s", evt.ID, backupURL)
time.Sleep(500 * time.Millisecond) // Optional: small delay to avoid rapid successive sends
return nil
}
// Validate event timestamps against the configured min and max values