apns2

package
v0.0.0-...-19e231a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 24, 2017 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// 400 The collapse identifier exceeds the maximum allowed size
	ReasonBadCollapseID = "BadCollapseId"

	// 400 The specified device token was bad. Verify that the request contains a
	// valid token and that the token matches the environment.
	ReasonBadDeviceToken = "BadDeviceToken"

	// 400 The apns-expiration value is bad.
	ReasonBadExpirationDate = "BadExpirationDate"

	// 400 The apns-id value is bad.
	ReasonBadMessageID = "BadMessageId"

	// 400 The apns-priority value is bad.
	ReasonBadPriority = "BadPriority"

	// 400 The apns-topic was invalid.
	ReasonBadTopic = "BadTopic"

	// 400 The device token does not match the specified topic.
	ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic"

	// 400 One or more headers were repeated.
	ReasonDuplicateHeaders = "DuplicateHeaders"

	// 400 Idle time out.
	ReasonIdleTimeout = "IdleTimeout"

	// 400 The device token is not specified in the request :path. Verify that the
	// :path header contains the device token.
	ReasonMissingDeviceToken = "MissingDeviceToken"

	// 400 The apns-topic header of the request was not specified and was
	// required. The apns-topic header is mandatory when the client is connected
	// using a certificate that supports multiple topics.
	ReasonMissingTopic = "MissingTopic"

	// 400 The message payload was empty.
	ReasonPayloadEmpty = "PayloadEmpty"

	// 400 Pushing to this topic is not allowed.
	ReasonTopicDisallowed = "TopicDisallowed"

	// 403 The certificate was bad.
	ReasonBadCertificate = "BadCertificate"

	// 403 The client certificate was for the wrong environment.
	ReasonBadCertificateEnvironment = "BadCertificateEnvironment"

	// 403 The provider token is stale and a new token should be generated.
	ReasonExpiredProviderToken = "ExpiredProviderToken"

	// 403 The specified action is not allowed.
	ReasonForbidden = "Forbidden"

	// 403 The provider token is not valid or the token signature could not be
	// verified.
	ReasonInvalidProviderToken = "InvalidProviderToken"

	// 403 No provider certificate was used to connect to APNs and Authorization
	// header was missing or no provider token was specified.
	ReasonMissingProviderToken = "MissingProviderToken"

	// 404 The request contained a bad :path value.
	ReasonBadPath = "BadPath"

	// 405 The specified :method was not POST.
	ReasonMethodNotAllowed = "MethodNotAllowed"

	// 410 The device token is inactive for the specified topic.
	ReasonUnregistered = "Unregistered"

	// 413 The message payload was too large. See Creating the Remote Notification
	// Payload in the Apple Local and Remote Notification Programming Guide for
	// details on maximum payload size.
	ReasonPayloadTooLarge = "PayloadTooLarge"

	// 429 The provider token is being updated too often.
	ReasonTooManyProviderTokenUpdates = "TooManyProviderTokenUpdates"

	// 429 Too many requests were made consecutively to the same device token.
	ReasonTooManyRequests = "TooManyRequests"

	// 500 An internal server error occurred.
	ReasonInternalServerError = "InternalServerError"

	// 503 The service is unavailable.
	ReasonServiceUnavailable = "ServiceUnavailable"

	// 503 The server is shutting down.
	ReasonShutdown = "Shutdown"
)

The possible Reason error codes returned from apns2. From table 8-6 in the Apple Local and Remote Notification Programming Guide.

View Source
const RequestRoot = "/3/device/"

APNS default root URL path.

View Source
const StatusAcccepted = http.StatusOK

StatusAcccepted is a 200 response.

Variables

View Source
var (
	ErrMissingAuth          = errors.New("apns2: authentication is not possible with no client certificate and no signer")
	ErrClientNotRunning     = errors.New("apns2: client processing pipeline not running")
	ErrClientAlreadyStarted = errors.New("apns2: client processing pipeline already started")
	ErrClientAlreadyClosed  = errors.New("apns2: client processing pipeline already closed")
	ErrPushInterrupted      = errors.New("apns2: push request interrupted")
	ErrCanceled             = errors.New("apns2: push request canceled")
)
View Source
var (
	ErrHTTPClientClosed = errors.New("HTTPClient: attempt to close already closed client")
	ErrNoConnectionPool = errors.New("HTTPClient: no connection pool")
)

HTTP layer-related errors.

View Source
var CommsDefault = CommsSlow

CommsDefault is the set of communication settings that is used when you do not supply an explicit comms configuration where one is needed.

View Source
var CommsFast = CommsCfg{
	DialTimeout:          20 * time.Second,
	MinDialBackOff:       4 * time.Second,
	MaxDialBackOff:       10 * time.Minute,
	DialBackOffJitter:    10 * funit.Percent,
	RequestTimeout:       30 * time.Second,
	KeepAlive:            10 * time.Hour,
	MaxConcurrentStreams: 500,
}

CommsFast is a baseline set of communication settings for situations where long delays cannot be tolerated.

View Source
var CommsSlow = CommsCfg{
	DialTimeout:          40 * time.Second,
	MinDialBackOff:       10 * time.Second,
	MaxDialBackOff:       10 * time.Minute,
	DialBackOffJitter:    10 * funit.Percent,
	RequestTimeout:       60 * time.Second,
	KeepAlive:            10 * time.Hour,
	MaxConcurrentStreams: 500,
}

CommsSlow is a baseline set of communication settings accommodating wider range of network performance and APN service responsiveness scenarios.

View Source
var DefaultCallback chan<- *Result

DefaultCallback can be used instead of nil value to idicate that client's default callback channel should be used to communicate back the result of a push request.

View Source
var DefaultJWTSigningMethod = jwt.SigningMethodES256

DefaultJWTSigningMethod method for APN requests is ES256.

View Source
var DefaultTokenLifeSpan = 50 * time.Minute

DefaultTokenLifeSpan specifies the time duration for which provier tokens are considered to be valid. At present APN service stops honoring authentication tokens that are older than 1 hour. Initial global default value allows 10 minutes of safety margin. If changed, any provider token authenticators created thereafter will use the new value.

View Source
var Gateway = struct {
	Development string
	Production  string
}{
	Development: "https://api.development.push.apple.com",
	Production:  "https://api.push.apple.com",
}

Gateway holds APN service's Development & Production urls. These use default HTTPS port 443. According to Apple you can alternatively use port 2197 if needed.

View Source
var LogLevel = LogNotice

LogLevel is a runtime-wide setting that indicates which severity levels should be logged.

View Source
var MinBlockingProcConfig = ProcCfg{
	MinConns:                  1,
	MaxConns:                  1,
	MaxRate:                   1000 / funit.Second,
	MaxBandwidth:              10 * funit.Gigabit / funit.Second,
	Scale:                     scale.Constant,
	AllowHTTP2Incursion:       true,
	HTTP2MetricsRefreshPeriod: 500 * time.Millisecond,
}

MinBlockingProcConfig is a configuration with absolute mimimal processing settings. It only allows a single connection to APN service with no scaling. HTTP/2 layer metrics refresh is set to 500ms to allow proper handling of HTTP/2 streams concurrency without introducing any noticeable overhead.

View Source
var NoCallback chan *Result

NoCallback is used to indicate that results of push notification requests should be silently discarded.

View Source
var NoContext context.Context

NoContext can be used instead of nil value to indicate no cancellation context.

View Source
var UnlimitedProcConfig = ProcCfg{
	MinConns:                  1,
	MaxConns:                  ^uint32(0),
	MaxRate:                   10000000 / funit.Second,
	MaxBandwidth:              1 * funit.Terabit / funit.Second,
	Scale:                     scale.Exponential(2),
	AllowHTTP2Incursion:       true,
	HTTP2MetricsRefreshPeriod: 500 * time.Millisecond,
}

UnlimitedProcConfig is a configuration with virtually no limit on processing speed and unlimited base 2 exponential scaling.

Functions

This section is empty.

Types

type APS

type APS struct {
	Alert            interface{}
	Badge            interface{}
	Category         string
	ContentAvailable bool
	MutableContent   bool
	Sound            string
	ThreadID         string
	URLArgs          []string
}

type Alert

type Alert struct {
	Action       string   `json:"action,omitempty"`
	ActionLocKey string   `json:"action-loc-key,omitempty"`
	Body         string   `json:"body,omitempty"`
	LaunchImage  string   `json:"launch-image,omitempty"`
	LocArgs      []string `json:"loc-args,omitempty"`
	LocKey       string   `json:"loc-key,omitempty"`
	Title        string   `json:"title,omitempty"`
	Subtitle     string   `json:"subtitle,omitempty"`
	TitleLocArgs []string `json:"title-loc-args,omitempty"`
	TitleLocKey  string   `json:"title-loc-key,omitempty"`
}

type Client

type Client struct {

	// Id identifies client in log entries.
	Id string

	// Gateway is the APN service connection endpoint.
	// Apple publishes two public endpoints: production and development.
	// They are preconfigured in Gateway.Production and Gateway.Development.
	Gateway string

	// CommsCfg contains communication settings to be used by the client.
	// See CommsCfg type declaration for additional details.
	CommsCfg CommsCfg

	// ProcCfg contains autoscaling settings.
	// See ProcCfg type declaration for additional details.
	ProcCfg ProcCfg

	// Certificate, if not nil, is used in the client side configuration
	// of the TLS connections to APN servers.
	// This is one of the authentication methods supported by APN service.
	Certificate *tls.Certificate

	// RootCA, if not nil, can be used to specify an alternative root
	// certificate authority. This should only be needed in testing, or
	// if you system's root certificate authorities are not set up.
	RootCA *tls.Certificate

	// Signer, if not nil, is used to sign individual requests to APN service.
	Signer RequestSigner

	// Queue for submitting push requests.
	//
	// You can use it directly in your code, especially in select statements
	// when coordination with other channels is desired.
	// Alternatively client's Push method can be used.
	Queue <-chan *Request

	// Callback, if not nil, specifies the channel to which the outcome of
	// the push request executions should be delivered.
	// If Callback is nil and a request doesn't specify an alternative callback,
	// requests execution result is silently dropped.
	Callback chan<- *Result
	// contains filtered or unexported fields
}

Client provides the means for asynchronous communication with APN service. It is safe to use one client in concurrent goroutines and issue concurrent push requests.

As per APN service guidelines, you should keep a handle on this client so that you can keep your connections with APN servers open. Repeatedly opening and closing connections in rapid succession is treated by Apple as a denial-of-service attack.

func (*Client) HasSigner

func (c *Client) HasSigner() bool

HasSigner returns `true` if there is a non-default signer configured for signing push requests.

func (*Client) Kill

func (c *Client) Kill() error

Kill performs hard shutdown of the Client without waiting for the processing pipeline to unwind. Inflight requests are discarded.

func (*Client) Push

func (c *Client) Push(n *Notification, signer RequestSigner, ctx context.Context, callback chan<- *Result) error

Push asynchronously sends a Notification to the APN service. Context carries a deadline and a cancellation signal and allows you to close long running requests when the context timeout is exceeded. Context can be nil or NoContext if no cancellation functionality is desired.

If not nil, the supplied signer is asked to sign the request before submitting it to APN service. If the supplied signer is nil, but client's signer was configured at the initialization time, the client's signer will sign the request. NoSigner can be specified if the request must not be signed.

This method will block if downstream capacity is exceeded. For non-blocking behavior or to allow coordination with activity on other channels consider creating a Request instance and writing it to client's Queue directly.

func (*Client) Start

func (c *Client) Start(wg *sync.WaitGroup) error

Start starts Client processing pipeline. If the client has already been started, ErrClientAlreadyStarted error is returned.

func (*Client) Stop

func (c *Client) Stop() error

Stop performs soft shutdown of the Client. All inflight requests are given the chance to be executed.

type CommsCfg

type CommsCfg struct {

	// DialTimeout is the maximum amount of time a dial will wait for a connect
	// to complete.
	DialTimeout time.Duration

	// MinDialBackOff is the minimum amount of time by which dial attempts
	// should be delayed after encountering a refused connection.
	// Actual back-off time will grow exponentially until a connection attempt
	// is successful.
	MinDialBackOff time.Duration

	// MaxDialBackOff is the maximum amount of time by which dial attempts
	// should be delayed after encountering a refused connection.
	MaxDialBackOff time.Duration

	// DialBackOffJitter is used to calculate the ramdom amount to appy to each
	// back-off time calculation.
	DialBackOffJitter funit.Measure

	// RequestTimeout specifies a time limit for requests made by the
	// HTTPClient. The timeout includes connection time, any redirects,
	// and reading the response body.
	RequestTimeout time.Duration

	// KeepAlive specifies the keep-alive period for an active network
	// connection. If zero, keep-alives are not enabled.
	// Apple recommends not closing connections to APN service at all,
	// but a sinsibly long duration is acceptable.
	KeepAlive time.Duration

	// MaxConcurrentStreams is the maximum allowed number of concurrent streams
	// per HTTP/2 connection. If connection's MAX_CONCURRENT_STREAMS option
	// is invoked by the remote side with a lower value, the remote request
	// will be honored if possible.
	MaxConcurrentStreams uint32
}

CommsCfg is a set of parameters that govern communications with APN servers. Two baseline configuration sets are predefined by CommsFast and CommsSlow global variables. You may define your own sets as needed to address any specific requirements of your particular setup.

type HTTP2Stream

type HTTP2Stream struct {
	// contains filtered or unexported fields
}

HTTP2Stream is a token indicating a stream reservation in one of the HTTPClient's HTTP/2 connections.

func (*HTTP2Stream) Close

func (s *HTTP2Stream) Close()

Close releases an HTTP/2 stream reservation.

type HTTPClient

type HTTPClient struct {
	http.Client
	// contains filtered or unexported fields
}

HTTPClient wraps http.Client and augments it with HTTP/2 stream reservation facility.

Due to current limitations of Go http2 client implementation, only a single underlying http2.ClientConn is intended to be supported by the client. This means that correct communication behavior is limited to a single HTTP/2 server endpoint. Note, however, that no attempt is made to restrict the way in which the client is used, including handling of any encountered redirect responses.

func NewHTTPClient

func NewHTTPClient(gateway string, commsCfg CommsCfg, cCert *tls.Certificate, rootCA *tls.Certificate) (*HTTPClient, error)

NewHTTPClient creates a new HTTPClient for handling HTTP requests to a single specified gateway. TLS client certificate cCert and custom root certificate authority rootCA certificate are optional and can be nil.

func (*HTTPClient) Close

func (c *HTTPClient) Close() error

func (*HTTPClient) ReservedStream

func (c *HTTPClient) ReservedStream(cancel func(<-chan struct{}) error) (*HTTP2Stream, error)

ReservedStream returns a reserved HTTP2Stream in the client's HTTP/2 connection, or a non-nil error.

type Header struct {
	// The topic of the remote notification, which is typically the bundle ID
	// for your app. The certificate you create in your developer account
	// must include the capability for this topic.
	// If your certificate includes multiple topics, you must specify a value for this header.
	// If you omit this request header and your APNs certificate does not specify
	// multiple topics, the APNs server uses the certificate’s Subject as the default topic.
	// If you are using a provider token instead of a certificate, you must specify a value
	// for this request header. The topic you provide should be provisioned for the your team
	// named in your developer account.
	Topic string

	// CollapseID, if set, allows grouping of multiple notifications by apns2.
	// Multiple notifications with the same collapse identifier are displayed
	// to the user as a single notification.
	// The value of this field must not exceed 64 bytes.
	CollapseID string

	// Priority is the priority of the notification.
	// Specify ether apns2.PriorityHigh (10) or apns2.PriorityLow (5)
	// If you don't set this, the APNs server will set the priority to 10.
	Priority Priority

	// Expiration identifies the date when the notification is no longer valid
	// and can be discarded.
	// If this value is nonzero, APNs stores the notification
	// and tries to deliver it at least once, repeating the attempt as needed
	// if it is unable to deliver the notification the first time.
	// If the value is 0, APNs treats the notification as if it expires immediately
	// and does not store the notification or attempt to redeliver it.
	Expiration time.Time
	// contains filtered or unexported fields
}

Header is a container for the routing information. How a header is constructed and utilized is not constrained, but the intent is to never modify it once created and assigned. The same header can then be used for routing of any number of notifications.

type JWT

type JWT struct {
	IssuedAt  time.Time
	ExpiresAt time.Time
	JwtToken  *jwt.Token
	AsHeader  string
}

JWT is an implementation of provider token in the form of Javascript Web Token, that can be written to HTTP authorization header. It is intended to remain immutable once created, and is safe to use in concurrent goroutines.

type JWTSigner

type JWTSigner struct {
	// A 10-character key identifier, obtained from Apple developer account.
	KeyID string

	// A 10-character Team ID, obtained from Apple developer account.
	TeamID string

	// Private key for signing generated tokens.
	SigningKey *ecdsa.PrivateKey

	// Method to use for signing generated tokens.
	SigningMethod *jwt.SigningMethodECDSA

	// The duration for which generated tokens are considered valid by apns2.
	// This is currently required to not exceed one hour.
	TokenLifeSpan time.Duration
	// contains filtered or unexported fields
}

Provider token-based signer that uses JSON Web Tokens to sign individual requests to APN service. It is safe to use in concurrent goroutines.

func (*JWTSigner) GetToken

func (s *JWTSigner) GetToken() (*JWT, error)

GetToken returns provider authentication token that is guaranteed to be valid at the time of the call.

func (*JWTSigner) SignRequest

func (s *JWTSigner) SignRequest(r *http.Request) error

SignRequest adds Authorization header to the supplied request. The header is an encrypted JSON Web Token containing signer's credentials. The token is guaranteed to be valid at the time of the call.

type Logger

type Logger interface {
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Fatalln(v ...interface{})
	Flags() int
	Output(calldepth int, s string) error
	Panic(v ...interface{})
	Panicf(format string, v ...interface{})
	Panicln(v ...interface{})
	Prefix() string
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
	SetFlags(flag int)
	SetOutput(w io.Writer)
	SetPrefix(prefix string)
}

Logger interface is extracted from log.Logger to aid in configuring custom loggers for use in this package.

var Log Logger = log.New(os.Stderr, "apns2: ", log.LstdFlags)

Log is a runtime-wide logger used by this package. You are allowed to set it to a different facility as needed.

type Notification

type Notification struct {
	// ApnsID is a canonical UUID that identifies the notification.
	// If there is an error sending the notification, APNs uses this value
	// to identify the notification in its response.
	// The canonical form is 32 lowercase hexadecimal digits,
	// displayed in five groups separated by hyphens in the form 8-4-4-4-12.
	// An example ApnsID is as follows: 123e4567-e89b-12d3-a456-42665544000
	// If omitted, a new ApnsID is created by APNs and returned in the response.
	ApnsID string

	// Recipient is the device token of the notification target.
	Recipient string

	// Header is a reference to a structure containing routing information.
	Header *Header

	// Payload is the notification data that is passed to the recipient.
	// Payload can be of any type that can be marshalled into a valid
	// JSON dictionary, a string representation of such dictionaty or
	// a slice of bytes of JSON encoding of such dictionary.
	Payload interface{}
}

Notification holds the data that is to be pushed to the recipient as well as any routing information required to deliver it. Routing headers and the notification payload are meant to remain immutable and are intended to be shared accross multiple notifications if needed. This is usefull when the same message needs to be deliverd to many recipients.

type Payload

type Payload struct {
	APS *APS
	Raw map[string]interface{}
	// contains filtered or unexported fields
}

Payload is the container for the actual data to be delivered to the notification recipient. How a payload is utilized is not constrained, but the intent is to never modify it once created and assigned. The same payload can then be sent to any number of recipients.

func (*Payload) MarshalJSON

func (p *Payload) MarshalJSON() ([]byte, error)

type Priority

type Priority int

Priority is the priority of the notification. Allowable values are defined by APNs and are listed below.

const (
	// PriorityLow instructs APNs to send the push message at a time
	// that takes into account power considerations for the device.
	// Notifications with this priority might be grouped and delivered
	//in bursts. They are throttled, and in some cases are not delivered.
	PriorityLow Priority = 5

	// PriorityHigh instructs APNs to send the push message immediately.
	// Notifications with this priority must trigger an alert, sound,
	// or badge on the target device.
	// It is an error to use this priority for a push notification
	// that contains only the content-available key.
	PriorityHigh = 10
)

type ProcCfg

type ProcCfg struct {

	// MaxRetries is the maximum number of times a failed notification push
	// should be reattempted. This only applies to "retriable" failures.
	MaxRetries uint32

	// RetryEval is the function that is called when a push attempt fails
	// and retry eligibility needs to be determined.
	RetryEval func(*Response, error) bool

	// MinConns is minimum number of concurrent connections to APN servers
	// that should be kept open.
	MinConns uint32

	// MaxConns is maximum allowed number of concurrent connections
	// to APN service.
	MaxConns uint32

	// MaxRate is the throughput cap specified in notifications per second.
	// It is not strictly enforced as would be the case with a true rate
	// limiter. Instead it only prevents additional scaling from taking place
	// once the specified rate is reached.
	MaxRate funit.Measure

	// MaxBandwidth is the throughput cap specified in bits per second.
	// It is not strictly enforced as would be the case with a true rate
	// limiter. Instead it only prevents additional scaling from taking place
	// once the specified rate is reached.
	MaxBandwidth funit.Measure

	// Scale specifies the manner of scaling up and winding down.
	// Three scaling modes come prefefined: Incremental, Exponential and Constant.
	// See below for more detail.
	Scale scale.Scale

	// MinSustain is the minimum duration of time over which the processing
	// has to experience blocking before a scale-up attemp is made. It is also
	// the minimum amount of time over which non-blocking processing has to
	// take place before a wind-down attemp is made.
	MinSustain time.Duration

	// PollInterval is the time between performance metrics sampling attempts.
	PollInterval time.Duration

	// SettlePeriod is the amount of time given to the processing for it to
	// settle down at the new rate after successful scaling up or
	// winding down attempt. Sustained performance analysis is ignored during
	// this time and no new scaling attempt is made.
	SettlePeriod time.Duration

	// AllowHTTP2Incursion controls whether it is OK to perform reflection-based
	// probing of HTTP/2 layer. When enabled, scaler may access certain private
	// properties in x/net/http2 package if needed for more precise performance
	// analysis.
	AllowHTTP2Incursion bool

	// UsePreciseHTTP2Metrics, if set to true, instructs the scaler to query
	// HTTP/2 layer parameters on every call that requires the data.
	// Set this to false if you wish to eliminate any additional overhead that
	// this may introduce.
	UsePreciseHTTP2Metrics bool

	// HTTP2MetricsRefreshPeriod, if set to a positive value, controls
	// the frequency of "imprecise" metrics updates. Under this approach any
	// relevant fields that are private to x/net/http2 packaged are only
	// queried periodically.
	// This reduces the overhead of any required reflection calls, but it also
	// introduces the risk of potentially relying on some stale metrics.
	// In most realistic situations, however, this can be easily tolerated
	// given frequent enough refresh period.
	//
	// HTTP2MetricsRefreshPeriod value is ignored and periodic updates
	// are turned off if UsePreciseHTTP2Metrics is set to true.
	// Setting HTTP2MetricsRefreshPeriod to 0 or negative value disables
	// metrics refresh even if UsePreciseMetrics is false.
	HTTP2MetricsRefreshPeriod time.Duration
}

ProcCfg is a set of parameters that govern request processing flow including automatic scaling of the processing pipeline.

type Request

type Request struct {

	// Notification is the notification to push to APN service
	Notification *Notification

	// Signer, if not nil, is used to sign the request before submitting it
	// to APN service. If Signer is nil, but client's signer was configured
	// at the initialization time, the client's signer will sign the request.
	Signer RequestSigner

	// Context carries a deadline and a cancellation signal and allows you
	// to close long running requests when the context timeout is exceeded.
	// Context can be nil, for backwards compatibility.
	Context context.Context

	// Callback, if not nil, specifies the channel to which the outcome of
	// the push execution should be delivered. If Callback is nil and client's
	// Callback was configured at the initialization time, the result
	// will be delivered to client's Callback.
	Callback chan<- *Result
	// contains filtered or unexported fields
}

Request holds all necessary information needed to submit a notification to APN service. Requests can be directly submitted to Client's Queue.

func (*Request) HasSigner

func (r *Request) HasSigner() bool

HasSigner returns true if the request has a custom signer supplied or if no signing should be performed for this request.

type RequestError

type RequestError struct {
	// contains filtered or unexported fields
}

RequestError indicates a request-level error. This helps distinguishing errors that are only scoped to a single request from those related to wider scope, such as transport layer errors.

type RequestSigner

type RequestSigner interface {

	// SignRequest gives the signer a chance to sign the request.
	// Any headers and the request body is guaranteed to have been
	// set up at this point.
	SignRequest(r *http.Request) error
}

RequestSigner must be implemented by all APN service request signers. Provider token signing allows authenticating with APN service on per request basis, if needed.

var DefaultSigner RequestSigner

DefaultSigner can be used instead of nil value where a RequestSigner is required to indicate that a push request should be signed with client's default signer.

var NoSigner RequestSigner

NoSigner can be used where a RequestSigner is required when a push request need not be signed.

type Response

type Response struct {

	// The ApnsID value from the Notification. If you didn't set an ApnsID in the
	// Notification, this will be a new unique UUID which has been created by apns2.
	ApnsID string

	// StatusCode is the HTTP status code returned by apns2.
	// A 200 value indicates that the notification was successfully sent.
	// For a list of other possible status codes, see table 6-4 in the Apple Local
	// and Remote Notification Programming Guide.
	StatusCode int

	// RejectionReason is the APNs error string indicating the reason
	// for the push failure (if any). The error code is specified as a string.
	// For a list of possible values, see the Reason constants above.
	// If the notification was accepted, this value will be "".
	RejectionReason string `json:"reason"`

	// If the value of StatusCode is 410, this is the last time at which APNs
	// confirmed that the device token was no longer valid for the topic.
	// TODO Make Response.UnsubscribedAt a time.Time and handle unmarshalling better
	UnsubscribedAt Time `json:"timestamp"`
}

Response represents a result from the APN service indicating whether a notification was accepted or rejected and (if applicable) any accompanying data.

func (*Response) IsAccepted

func (c *Response) IsAccepted() bool

IsAccepted returns whether or not the notification was accepted by APN service. This is the same as checking if the StatusCode == 200.

type Result

type Result struct {

	// Notification is the original notification.
	Notification *Notification

	// Signer is the one-off signer that was supplied in the push request.
	Signer RequestSigner

	// Context is the cancellation context instance passed to the original
	// push request.
	Context context.Context

	// Response represents a result from the APN service. If a push operation
	// fails prior to communicating with APN servers, Response will be nil and
	// Err field will have a non-nil value.
	Response *Response

	// Err, if not nil, is an error encontered while attempting a push.
	// Note that nil Err does not necessarily indicate a successful attempt.
	// You must also examine Response for additional status details.
	Err error
}

Result represents the outcome of an asynchronous push operation. The original notification is included along with any optional agruments supplied to the push request.

func (*Result) IsAccepted

func (r *Result) IsAccepted() bool

IsAccepted returns whether or not the notification was accepted by APN service.

type Severity

type Severity int

Severity represents a log entry severity.

const (
	LogError Severity = iota
	LogWarn
	LogNotice
	LogInfo
)

func LogTrace

func LogTrace(traceLevel uint) Severity

LogTrace returns a Severity value corresponding to the spcified trace level.

func (Severity) Bound

func (t Severity) Bound() Severity

Bounds returns a severity value that is clamped between LogError and LogInfo + 1, latter being indicative of trace level logging.

func (Severity) String

func (t Severity) String() string

String returns name associated with given Severity value.

type Time

type Time struct {
	time.Time
}

Time represents a device uninstall time

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON converts an epoch date in milliseconds into a Time struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL