Skip to content

Commit

Permalink
feat: delivery by category metric
Browse files Browse the repository at this point in the history
  • Loading branch information
martinramirez7 committed Jun 12, 2024
1 parent 764d40e commit bd86781
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 18 deletions.
55 changes: 39 additions & 16 deletions collect.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,23 @@ import (
type Collector struct {
logger log.Logger

blocks *prometheus.Desc
bounceDrops *prometheus.Desc
bounces *prometheus.Desc
clicks *prometheus.Desc
deferred *prometheus.Desc
delivered *prometheus.Desc
invalidEmails *prometheus.Desc
opens *prometheus.Desc
processed *prometheus.Desc
requests *prometheus.Desc
spamReportDrops *prometheus.Desc
spamReports *prometheus.Desc
uniqueClicks *prometheus.Desc
uniqueOpens *prometheus.Desc
unsubscribeDrops *prometheus.Desc
unsubscribes *prometheus.Desc
blocks *prometheus.Desc
bounceDrops *prometheus.Desc
bounces *prometheus.Desc
clicks *prometheus.Desc
deferred *prometheus.Desc
delivered *prometheus.Desc
invalidEmails *prometheus.Desc
opens *prometheus.Desc
processed *prometheus.Desc
requests *prometheus.Desc
spamReportDrops *prometheus.Desc
spamReports *prometheus.Desc
uniqueClicks *prometheus.Desc
uniqueOpens *prometheus.Desc
unsubscribeDrops *prometheus.Desc
unsubscribes *prometheus.Desc
category_delivered *prometheus.Desc
}

func collector(logger log.Logger) *Collector {
Expand Down Expand Up @@ -130,6 +131,12 @@ func collector(logger log.Logger) *Collector {
[]string{"user_name"},
nil,
),
category_delivered: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "delivered_by_category"),
"delivered_by_category",
[]string{"user_name", "category"},
nil,
),
}
}

Expand Down Expand Up @@ -253,4 +260,20 @@ func (c *Collector) Collect(ch chan<- prometheus.Metric) {
*sendGridUserName,
)
}

category_statistics, err := collectByCategory(today)

if err != nil {
level.Error(c.logger).Log(err)
return
}
for _, stats := range category_statistics.Stats {
ch <- prometheus.MustNewConstMetric(
c.category_delivered,
prometheus.CounterValue,
float64(stats.Metrics.Delivered),
*sendGridUserName,
stats.Category,
)
}
}
62 changes: 60 additions & 2 deletions sendgrid.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import (
"net/http"
"net/url"
"os"
"strconv"
"time"
)

const (
endpoint = "https://api.sendgrid.com/v3/stats"
endpoint = "https://api.sendgrid.com/v3/stats"
endpoint_categories = "https://api.sendgrid.com/v3/categories/stats/sums"
)

type Metrics struct {
Expand All @@ -34,7 +36,8 @@ type Metrics struct {
}

type Stat struct {
Metrics *Metrics `json:"metrics,omitempty"`
Metrics *Metrics `json:"metrics,omitempty"`
Category string `json:"name,omitempty"`
}

type Statistics struct {
Expand Down Expand Up @@ -92,3 +95,58 @@ func collectByDate(timeStart time.Time, timeEnd time.Time) ([]*Statistics, error
return nil, fmt.Errorf("status code = %d, response = %s", res.StatusCode, res.Body)
}
}

func collectByCategory(timeStart time.Time) (*Statistics, error) {
var limit int = 25
var offset int = 0
var stats *Statistics = &Statistics{}

for {
parsedURL, err := url.Parse(endpoint_categories)
if err != nil {
return nil, err
}
layout := "2006-01-02"
dateStart := timeStart.Format(layout)

query := url.Values{}
query.Set("start_date", dateStart)
query.Set("limit", strconv.Itoa(limit))
query.Set("offset", strconv.Itoa(offset))

parsedURL.RawQuery = query.Encode()

req, err := http.NewRequest(http.MethodGet, parsedURL.String(), nil)
if err != nil {
return nil, err
}

req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *sendGridAPIKey))

res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()

var pageStats *Statistics
var reader io.Reader = res.Body
reader = io.TeeReader(reader, os.Stdout)
switch res.StatusCode {
case http.StatusTooManyRequests:
return nil, fmt.Errorf("API rate limit exceeded")
case http.StatusOK:
if err := json.NewDecoder(reader).Decode(&pageStats); err != nil {
return nil, err
}
stats.Stats = append(stats.Stats, pageStats.Stats...)
default:
return nil, fmt.Errorf("status code = %d, response = %s", res.StatusCode, res.Body)
}
if len(pageStats.Stats) == 0 {
break
}
offset += limit
}
return stats, nil
}

0 comments on commit bd86781

Please sign in to comment.