exponotifier

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 12 Imported by: 0

README

Reference

https://github.com/oliveroneill/exponent-server-sdk-golang/tree/master

Example

Basic usage

import (
    "context"
    "log"

    exponotifier "github.com/naonao2323/expo-notifier"
)

func main() {
    ctx := context.Background()

    notifier := exponotifier.NewNotifier()

    token, err := exponotifier.NewExponentPushToken("ExponentPushToken[xxxx]")
    if err != nil {
        log.Fatal(err)
    }

    err = notifier.Add(ctx, exponotifier.PushMessage{
        To:    token,
        Title: "Hello",
        Body:  "This is a notification",
    })
    if err != nil {
        log.Fatal(err)
    }

    notifier.Flush()
}

Buffer settings

import (
    "time"

    exponotifier "github.com/naonao2323/expo-notifier"
)

notifier := exponotifier.NewNotifier(
    exponotifier.WithBuffer(
        exponotifier.WithCountThreshold(50),
        exponotifier.WithDelayThreshold(2*time.Second),
        exponotifier.WithByteThreshold(512*1024), // 512KB
    ),
)

Documentation

Overview

Package exponotifier provides a client for sending Expo push notifications.

Index

Constants

View Source
const (
	DefaultDelayThreshold    = time.Second
	DefaultCountThreshold    = 10
	DefaultByteThreshold     = 1 << 20 // 1MB
	DefaultBufferedByteLimit = 1 << 30 // 1GB
	DefaultMinItemBytes      = 128
	DefaultWorkerLimit       = 1
)

Default threshold values used when BufferSetting fields are zero.

View Source
const (
	// DefaultHost is the default Expo push notification host.
	DefaultHost = "https://exp.host"
	// DefaultBaseAPIURL is the default base path for Expo API requests.
	DefaultBaseAPIURL = "/--/api/v2"
)
View Source
const (
	// SuccessStatus is the status value returned by Expo on a successful notification.
	SuccessStatus = "ok"
	// ErrorDeviceNotRegistered indicates the push token is no longer valid.
	ErrorDeviceNotRegistered = "DeviceNotRegistered"
	// ErrorMessageTooBig indicates the notification payload exceeded 4096 bytes.
	ErrorMessageTooBig = "MessageTooBig"
	// ErrorMessageRateExceeded indicates messages are being sent too frequently.
	ErrorMessageRateExceeded = "MessageRateExceeded"
)
View Source
const (
	// DefaultPriority is the standard delivery priority for push messages.
	DefaultPriority = "default"
	// NormalPriority is the normal delivery priority for push messages.
	NormalPriority = "normal"
	// HighPriority is the high delivery priority for push messages.
	HighPriority = "high"
)

Variables

View Source
var DefaultHTTPClient = http.DefaultClient

DefaultHTTPClient is the default HTTP client used for API requests.

View Source
var ErrMalformedToken = errors.New("token should start with ExponentPushToken")

ErrMalformedToken is returned when a push token does not start with "ExponentPushToken".

View Source
var ErrOversizedItem = errors.New("buffer: item size exceeds byte limit")

ErrOversizedItem is returned by Add when the item size exceeds BufferedByteLimit.

Functions

This section is empty.

Types

type Buffer

type Buffer struct {
	BufferSetting
	// contains filtered or unexported fields
}

Buffer batches PushMessages and dispatches them to a handler when count, byte, or delay thresholds are exceeded.

func NewBuffer

func NewBuffer(handler func([]PushMessage), setting BufferSetting) *Buffer

NewBuffer creates a Buffer that calls handler with each flushed batch.

func (*Buffer) Add

func (b *Buffer) Add(ctx context.Context, msg PushMessage, size int) error

Add enqueues msg. Blocks until byte capacity is available or ctx is done. Returns ErrOversizedItem if size exceeds ByteLimit, or ctx.Err() if cancelled.

func (*Buffer) Flush

func (b *Buffer) Flush()

Flush dispatches any buffered messages and waits for all handlers to return.

type BufferOption

type BufferOption func(*BufferSetting)

BufferOption is a functional option for configuring a BufferSetting.

func WithBufferedByteLimit

func WithBufferedByteLimit(n int) BufferOption

WithBufferedByteLimit sets the total byte capacity across buffered and in-flight messages.

func WithByteThreshold

func WithByteThreshold(n int) BufferOption

WithByteThreshold sets the per-bundle byte size that triggers an immediate flush.

func WithCountThreshold

func WithCountThreshold(n int) BufferOption

WithCountThreshold sets the number of messages that triggers an immediate flush.

func WithDelayThreshold

func WithDelayThreshold(d time.Duration) BufferOption

WithDelayThreshold sets the maximum time a message waits before being flushed.

func WithWorkerLimit

func WithWorkerLimit(n int) BufferOption

WithWorkerLimit sets the maximum number of concurrent batch handler goroutines.

type BufferSetting

type BufferSetting struct {
	DelayThreshold    time.Duration
	CountThreshold    int
	ByteThreshold     int // per-bundle soft trigger
	BufferedByteLimit int // total bytes allowed across ring + in-flight (semaphore capacity)
	WorkerLimit       int
}

BufferSetting holds throttle configuration for the Buffer.

type Client

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

Client handles raw HTTP communication with the Expo push API.

type DeviceNotRegisteredError

type DeviceNotRegisteredError struct{ PushResponseError }

DeviceNotRegisteredError is returned when the push token is invalid or unregistered.

type ErrorHandler

type ErrorHandler func(msgs []PushMessage, err error) RetryDecision

ErrorHandler is called when a batch send fails (network error, non-2xx status, API error) or when individual push responses indicate delivery failures. Return Retry to re-enqueue msgs into the buffer, or NoRetry to discard them.

type ExponentPushToken

type ExponentPushToken string

ExponentPushToken is a validated Expo push token.

func NewExponentPushToken

func NewExponentPushToken(token string) (ExponentPushToken, error)

NewExponentPushToken returns a validated ExponentPushToken or an error if the token is malformed.

type MessageRateExceededError

type MessageRateExceededError struct{ PushResponseError }

MessageRateExceededError is returned when messages are sent too frequently to a device.

type MessageTooBigError

type MessageTooBigError struct{ PushResponseError }

MessageTooBigError is returned when the notification payload exceeds the 4096-byte limit.

type Notifier

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

Notifier sends Expo push notifications via a buffer.

func NewNotifier

func NewNotifier(opts ...Option) *Notifier

NewNotifier creates a Notifier with the given options. A buffer is always initialized.

func (*Notifier) Add

func (n *Notifier) Add(ctx context.Context, msg PushMessage) error

Add enqueues msg into the buffer. Blocks until byte capacity is available or ctx is done.

func (*Notifier) Flush

func (n *Notifier) Flush()

Flush drains all buffered messages and waits for all batch sends to complete.

type Option

type Option func(*Notifier)

Option is a functional option for configuring a Notifier.

func WithAPIURL

func WithAPIURL(apiURL string) Option

WithAPIURL sets the base API URL path.

func WithAccessToken

func WithAccessToken(token string) Option

WithAccessToken sets the Expo access token for authenticated requests.

func WithBuffer

func WithBuffer(opts ...BufferOption) Option

WithBuffer enables batched sending with the given buffer options. Messages added via Add are accumulated and flushed as batch HTTP requests.

func WithErrorHandler

func WithErrorHandler(h ErrorHandler) Option

WithErrorHandler sets a callback invoked on send failures. Without this option, errors are silently dropped.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithHost

func WithHost(host string) Option

WithHost sets the Expo push notification host.

type PushMessage

type PushMessage struct {
	To         ExponentPushToken `json:"to"`
	Title      string            `json:"title,omitempty"`
	Body       string            `json:"body"`
	Data       map[string]string `json:"data,omitempty"`
	Sound      string            `json:"sound,omitempty"`
	TTLSeconds int               `json:"ttl,omitempty"`
	Expiration int64             `json:"expiration,omitempty"`
	Priority   string            `json:"priority,omitempty"`
	Badge      int               `json:"badge,omitempty"`
	ChannelID  string            `json:"channelId,omitempty"`
}

PushMessage describes a push notification request.

type PushResponse

type PushResponse struct {
	PushMessage PushMessage
	ID          string            `json:"id"`
	Status      string            `json:"status"`
	Message     string            `json:"message"`
	Details     map[string]string `json:"details"`
}

PushResponse holds the result of a single push notification request.

func (*PushResponse) ValidateResponse

func (r *PushResponse) ValidateResponse() error

ValidateResponse returns a typed error if the push response indicates a failure.

type PushResponseError

type PushResponseError struct {
	Response *PushResponse
}

PushResponseError is the base error type for push notification response failures.

func (*PushResponseError) Error

func (e *PushResponseError) Error() string

type PushServerError

type PushServerError struct {
	Message  string
	Response *http.Response
	Err      error
}

PushServerError is returned when the Expo push server returns an unexpected error response.

func (*PushServerError) As

func (e *PushServerError) As(target any) bool

As sets the target to this PushServerError if the target type matches.

func (*PushServerError) Error

func (e *PushServerError) Error() string

func (*PushServerError) Is

func (e *PushServerError) Is(target error) bool

Is reports whether the target is a PushServerError.

func (*PushServerError) Unwrap

func (e *PushServerError) Unwrap() error

type RequestError

type RequestError struct {
	Err error
}

RequestError is returned when the HTTP request to Expo fails due to a network or transport error.

func (*RequestError) Error

func (e *RequestError) Error() string

func (*RequestError) Unwrap

func (e *RequestError) Unwrap() error

type RetryDecision

type RetryDecision bool

RetryDecision is the return value of an ErrorHandler.

const (
	// Retry re-enqueues the failed messages into the buffer.
	Retry RetryDecision = true
	// NoRetry discards the failed messages.
	NoRetry RetryDecision = false
)

Directories

Path Synopsis
internal
ring
Package ring provides a fixed-capacity generic circular buffer.
Package ring provides a fixed-capacity generic circular buffer.
scheduler
Package scheduler provides a generic bounded worker pool that dispatches items from a Queue to a handler function.
Package scheduler provides a generic bounded worker pool that dispatches items from a Queue to a handler function.

Jump to

Keyboard shortcuts

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