Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DE-1315 Add support for metrics API #328

Draft
wants to merge 15 commits into
base: master
Choose a base branch
from
Draft
61 changes: 61 additions & 0 deletions analytics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package mailgun

import (
"context"
"strings"

"github.com/pkg/errors"
)

// ListMetrics returns domain/account metrics.
//
// NOTE: Only for v1 API. To use the /v1 version define MG_URL in the environment variable
// as `https://api.mailgun.net/v1` or set `mg.SetAPIBase("https://api.mailgun.net/v1")`
//
// https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Metrics/
func (mg *MailgunImpl) ListMetrics(ctx context.Context, opts MetricsOptions) (*MetricsResponse, error) {
if !strings.HasSuffix(mg.APIBase(), "/v1") {
return nil, errors.New("only v1 API is supported")
}

domain := mg.Domain()
if domain != "" {
domainFilter := MetricsFilterPredicate{
Attribute: "domain",
Comparator: "=",
LabeledValues: []MetricsLabeledValue{{Label: domain, Value: domain}},
}

opts.Filter.BoolGroupAnd = append(opts.Filter.BoolGroupAnd, domainFilter)
}

req := newHTTPRequest(generatePublicApiUrl(mg, metricsEndpoint))
req.setClient(mg.Client())
req.setBasicAuth(basicAuthUser, mg.APIKey())

payload := newJSONEncodedPayload(opts)

resp, err := makePostRequest(ctx, req, payload)
if err != nil {
return nil, errors.Errorf("POST %s failed: %s", metricsEndpoint, err)
}

var ret MetricsResponse
err = resp.parseFromJSON(&ret)
if err != nil {
return nil, errors.Wrap(err, "decoding response")
}

return &ret, nil
}

type MetricsPagination struct {
// Colon-separated value indicating column name and sort direction e.g. 'domain:asc'.
Sort string `json:"sort"`
// The number of items to skip over when satisfying the request. To get the first page of data set skip to zero. Then increment the skip by the limit for subsequent calls.
Skip int64 `json:"skip"`
// The maximum number of items returned in the response.
Limit int64 `json:"limit"`
// The total number of items in the query result set.
Total int64 `json:"total"`
}
40 changes: 40 additions & 0 deletions analytics_request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package mailgun

type MetricsOptions struct {
// A start date (default: 7 days before current time).
Start RFC2822Time `json:"start"`
// An end date (default: current time).
End RFC2822Time `json:"end"`
// A resolution in the format of 'day' 'hour' 'month'. Default is day.
Resolution Resolution `json:"resolution,omitempty"`
// A duration in the format of '1d' '2h' '2m'.
// If duration is provided then it is calculated from the end date and overwrites the start date.
Duration string `json:"duration,omitempty"`
// Attributes of the metric data such as 'time' 'domain' 'ip' 'ip_pool' 'recipient_domain' 'tag' 'country' 'subaccount'.
Dimensions []string `json:"dimensions,omitempty"`
// Name of the metrics to receive the stats for such as 'accepted_count' 'delivered_count' 'accepted_rate'.
Metrics []string `json:"metrics,omitempty"`
// Filters to apply to the query.
Filter MetricsFilterPredicateGroup `json:"filter,omitempty"`
// Include stats from all subaccounts.
IncludeSubaccounts bool `json:"include_subaccounts,omitempty"`
// Include top-level aggregate metrics.
IncludeAggregates bool `json:"include_aggregates,omitempty"`
// Attributes used for pagination and sorting.
Pagination MetricsPagination `json:"pagination,omitempty"`
}

type MetricsLabeledValue struct {
Label string `json:"label"`
Value string `json:"value"`
}

type MetricsFilterPredicate struct {
Attribute string `json:"attribute"`
Comparator string `json:"comparator"`
LabeledValues []MetricsLabeledValue `json:"values,omitempty"`
}

type MetricsFilterPredicateGroup struct {
BoolGroupAnd []MetricsFilterPredicate `json:"AND,omitempty"`
}
95 changes: 95 additions & 0 deletions analytics_response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package mailgun

type MetricsResponse struct {
Start string `json:"start"`
End string `json:"end"`
Resolution Resolution `json:"resolution"`
Duration string `json:"duration"`
Dimensions []string `json:"dimensions"`
Pagination MetricsPagination `json:"pagination"`
Items []MetricsItem `json:"items"`
Aggregates MetricsAggregates `json:"aggregates"`
}

type MetricsItem struct {
Dimensions []MetricsDimension `json:"dimensions"`
Metrics Metrics `json:"metrics"`
}

type MetricsAggregates struct {
Metrics Metrics `json:"metrics"`
}

type Metrics struct {
AcceptedIncomingCount *uint64 `json:"accepted_incoming_count"`
AcceptedOutgoingCount *uint64 `json:"accepted_outgoing_count"`
AcceptedCount *uint64 `json:"accepted_count"`
DeliveredSMTPCount *uint64 `json:"delivered_smtp_count"`
DeliveredHTTPCount *uint64 `json:"delivered_http_count"`
DeliveredOptimizedCount *uint64 `json:"delivered_optimized_count"`
DeliveredCount *uint64 `json:"delivered_count"`
StoredCount *uint64 `json:"stored_count"`
ProcessedCount *uint64 `json:"processed_count"`
SentCount *uint64 `json:"sent_count"`
OpenedCount *uint64 `json:"opened_count"`
ClickedCount *uint64 `json:"clicked_count"`
UniqueOpenedCount *uint64 `json:"unique_opened_count"`
UniqueClickedCount *uint64 `json:"unique_clicked_count"`
UnsubscribedCount *uint64 `json:"unsubscribed_count"`
ComplainedCount *uint64 `json:"complained_count"`
FailedCount *uint64 `json:"failed_count"`
TemporaryFailedCount *uint64 `json:"temporary_failed_count"`
PermanentFailedCount *uint64 `json:"permanent_failed_count"`
ESPBlockCount *uint64 `json:"esp_block_count"`
WebhookCount *uint64 `json:"webhook_count"`
PermanentFailedOptimizedCount *uint64 `json:"permanent_failed_optimized_count"`
PermanentFailedOldCount *uint64 `json:"permanent_failed_old_count"`
BouncedCount *uint64 `json:"bounced_count"`
HardBouncesCount *uint64 `json:"hard_bounces_count"`
SoftBouncesCount *uint64 `json:"soft_bounces_count"`
DelayedBounceCount *uint64 `json:"delayed_bounce_count"`
SuppressedBouncesCount *uint64 `json:"suppressed_bounces_count"`
SuppressedUnsubscribedCount *uint64 `json:"suppressed_unsubscribed_count"`
SuppressedComplaintsCount *uint64 `json:"suppressed_complaints_count"`
DeliveredFirstAttemptCount *uint64 `json:"delivered_first_attempt_count"`
DelayedFirstAttemptCount *uint64 `json:"delayed_first_attempt_count"`
DeliveredSubsequentCount *uint64 `json:"delivered_subsequent_count"`
DeliveredTwoPlusAttemptsCount *uint64 `json:"delivered_two_plus_attempts_count"`

DeliveredRate string `json:"delivered_rate"`
OpenedRate string `json:"opened_rate"`
ClickedRate string `json:"clicked_rate"`
UniqueOpenedRate string `json:"unique_opened_rate"`
UniqueClickedRate string `json:"unique_clicked_rate"`
UnsubscribedRate string `json:"unsubscribed_rate"`
ComplainedRate string `json:"complained_rate"`
BounceRate string `json:"bounce_rate"`
FailRate string `json:"fail_rate"`
PermanentFailRate string `json:"permanent_fail_rate"`
TemporaryFailRate string `json:"temporary_fail_rate"`
DelayedRate string `json:"delayed_rate"`

// usage metrics
EmailValidationCount *uint64 `json:"email_validation_count"`
EmailValidationPublicCount *uint64 `json:"email_validation_public_count"`
EmailValidationValidCount *uint64 `json:"email_validation_valid_count"`
EmailValidationSingleCount *uint64 `json:"email_validation_single_count"`
EmailValidationBulkCount *uint64 `json:"email_validation_bulk_count"`
EmailValidationListCount *uint64 `json:"email_validation_list_count"`
EmailValidationMailgunCount *uint64 `json:"email_validation_mailgun_count"`
EmailValidationMailjetCount *uint64 `json:"email_validation_mailjet_count"`
EmailPreviewCount *uint64 `json:"email_preview_count"`
EmailPreviewFailedCount *uint64 `json:"email_preview_failed_count"`
LinkValidationCount *uint64 `json:"link_validation_count"`
LinkValidationFailedCount *uint64 `json:"link_validation_failed_count"`
SeedTestCount *uint64 `json:"seed_test_count"`
}

type MetricsDimension struct {
// The dimension
Dimension string `json:"dimension"`
// The dimension value
Value string `json:"value"`
// The dimension value in displayable form
DisplayValue string `json:"display_value"`
}
23 changes: 23 additions & 0 deletions analytics_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package mailgun

var mockAcceptedIncomingCount uint64 = 10

var expectedResponse = MetricsResponse{
Start: "Mon, 15 Apr 2024 00:00:00 +0000",
Dimensions: []string{"time"},
Items: []MetricsItem{
{
Dimensions: []MetricsDimension{
{
Dimension: "time",
Value: "Mon, 15 Apr 2024 00:00:00 +0000",
DisplayValue: "Mon, 15 Apr 2024 00:00:00 +0000",
},
},
Metrics: Metrics{
AcceptedIncomingCount: &mockAcceptedIncomingCount,
ClickedRate: "0.8300",
},
},
},
}
5 changes: 1 addition & 4 deletions mailgun.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ const (
mimeMessagesEndpoint = "messages.mime"
bouncesEndpoint = "bounces"
statsTotalEndpoint = "stats/total"
metricsEndpoint = "analytics/metrics"
domainsEndpoint = "domains"
tagsEndpoint = "tags"
eventsEndpoint = "events"
Expand Down Expand Up @@ -425,10 +426,6 @@ func generatePublicApiUrl(m Mailgun, endpoint string) string {
return fmt.Sprintf("%s/%s", m.APIBase(), endpoint)
}

func generateSubaccountsApiUrl(m Mailgun) string {
return fmt.Sprintf("%s/%s/%s", m.APIBase(), accountsEndpoint, subaccountsEndpoint)
}

// generateParameterizedUrl works as generateApiUrl, but supports query parameters.
func generateParameterizedUrl(m Mailgun, endpoint string, payload payload) (string, error) {
paramBuffer, err := payload.getPayloadBuffer()
Expand Down
11 changes: 11 additions & 0 deletions reporting.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package mailgun

// common things for stats and metrics

type Resolution string

const (
ResolutionHour = Resolution("hour")
ResolutionDay = Resolution("day")
ResolutionMonth = Resolution("month")
)
17 changes: 4 additions & 13 deletions stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,6 @@ type statsTotalResponse struct {
Stats []Stats `json:"stats"`
}

// Used by GetStats() to specify the resolution stats are for
type Resolution string

// Indicate which resolution a stat response for request is for
const (
ResolutionHour = Resolution("hour")
ResolutionDay = Resolution("day")
ResolutionMonth = Resolution("month")
)

// Options for GetStats()
type GetStatOptions struct {
Resolution Resolution
Expand All @@ -85,7 +75,8 @@ type GetStatOptions struct {
End time.Time
}

// GetStats returns total stats for a given domain for the specified time period
// GetStats returns total stats for a given domain for the specified time period.
// Deprecated: Use ListMetrics instead.
func (mg *MailgunImpl) GetStats(ctx context.Context, events []string, opts *GetStatOptions) ([]Stats, error) {
r := newHTTPRequest(generateApiUrl(mg, statsTotalEndpoint))

Expand Down Expand Up @@ -115,7 +106,7 @@ func (mg *MailgunImpl) GetStats(ctx context.Context, events []string, opts *GetS
err := getResponseFromJSON(ctx, r, &res)
if err != nil {
return nil, err
} else {
return res.Stats, nil
}

return res.Stats, nil
}
5 changes: 5 additions & 0 deletions subaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package mailgun

import (
"context"
"fmt"
"strconv"
)

Expand Down Expand Up @@ -244,3 +245,7 @@ func (mg *MailgunImpl) DisableSubaccount(ctx context.Context, subaccountId strin
err := postResponseFromJSON(ctx, r, nil, &resp)
return resp, err
}

func generateSubaccountsApiUrl(m Mailgun) string {
return fmt.Sprintf("%s/%s/%s", m.APIBase(), accountsEndpoint, subaccountsEndpoint)
}
Loading