Skip to content

Commit

Permalink
Optionally purge cloudflare cache on update
Browse files Browse the repository at this point in the history
  • Loading branch information
Fizzadar committed Oct 30, 2023
1 parent cb22e0e commit 9df1462
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
3 changes: 3 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ type Config struct {
ListenAddress string `yaml:"listen_address"`
PublicURL string `yaml:"public_url"`

CloudflareZoneID string `yaml:"cloudflare_zone_id"`
CloudflareToken string `yaml:"cloudflare_token"`

Feeds map[string]*FeedConfig `yaml:"feeds"`
feedsByRoomID map[id.RoomID]*FeedConfig

Expand Down
44 changes: 44 additions & 0 deletions update.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package main
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"net/http"
"time"

"github.com/rs/zerolog"
Expand Down Expand Up @@ -32,6 +34,10 @@ func (fs *FeedServ) HandleFeedEvent(_ mautrix.EventSource, evt *event.Event) {
feed.pushEvent(log, evt)

fs.regenerateFeed(feed, log)

if err := fs.purgeCloudflareCache(feed); err != nil {
log.Error().Err(err).Msg("Failed to purge Cloudflare cache")
}
}

func (feed *FeedConfig) pushEvent(log zerolog.Logger, evt *event.Event) {
Expand Down Expand Up @@ -97,3 +103,41 @@ func (fs *FeedServ) regenerateFeed(feed *FeedConfig, log zerolog.Logger) {
Dur("duration", time.Since(start)).
Msg("Feed updated successfully")
}

var cloudflareClient = &http.Client{Timeout: time.Second * 10}

type cloudflarePurgeRequest struct {
Files []string `json:"files"`
}

func (fs *FeedServ) purgeCloudflareCache(feed *FeedConfig) error {
if fs.Config.CloudflareToken == "" {
return nil
}

data := cloudflarePurgeRequest{[]string{
fs.Config.PublicURL + "/" + feed.id,
fs.Config.PublicURL + "/" + feed.id + ".json",
fs.Config.PublicURL + "/" + feed.id + ".rss",
fs.Config.PublicURL + "/" + feed.id + ".atom",
}}
body, err := json.Marshal(data)
if err != nil {
return err
}

url := "https://api.cloudflare.com/client/v4/zones/" + fs.Config.CloudflareZoneID + "/purge_cache"
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+fs.Config.CloudflareToken)

resp, err := cloudflareClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()

return nil
}

0 comments on commit 9df1462

Please sign in to comment.