Skip to content

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
vtopc committed Sep 17, 2024
1 parent 73d6a29 commit c3d2e09
Show file tree
Hide file tree
Showing 4 changed files with 214 additions and 0 deletions.
56 changes: 56 additions & 0 deletions analytics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package mailgun

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"

"github.com/pkg/errors"
)

// ListMetrics returns account metrics.
// Must be /v1 API.
// https://documentation.mailgun.com/docs/mailgun/api-reference/openapi-final/tag/Metrics/
func (c *Client) ListMetrics(ctx context.Context, opts MetricsOptions) (*MetricsResponse, error) {

Check failure on line 17 in analytics.go

View workflow job for this annotation

GitHub Actions / test (1.22.x, ubuntu-latest)

undefined: Client
url := fmt.Sprintf("%s", metricsEndpoint)
mRequest, err := json.Marshal(opts)
if err != nil {
return nil, errors.Wrap(err, "while marshalling analytics metrics request")
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(mRequest))
if err != nil {
return nil, errors.Wrap(err, "while creating analytics metrics request")
}

resp, err := c.httpClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "while making analytics metrics request")
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, errors.Errorf("POST on '%s' returned %s", url, string(body))
}

var ret MetricsResponse
if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil {
return nil, errors.Wrap(err, "while decoding analytics metrics 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",
},
},
},
}

0 comments on commit c3d2e09

Please sign in to comment.