mailbox

package
v0.2.37 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

Package mailbox emulates the altengine mailbox service: email addresses an app or an agent owns. Mail arrives through the same admission and ingest path the hosted service runs — from the /v1 inject endpoint, the console's compose form, a raw .eml upload, or the optional SMTP listener — and is stored, matched against the instance's routes, and handed to a function, a channel or a webhook. Nothing sent from here leaves the emulator.

Index

Constants

View Source
const (
	DefaultRetentionDays = 7
	MaxRetentionDays     = 90
	// InboundDailyCeiling is inbound messages per instance per UTC day; also the default. A
	// tenant may only lower it.
	InboundDailyCeiling = 5000

	MaxRoutes          = 20
	MaxActionsPerRoute = 3

	MaxWebhookURLLength = 2048
)
View Source
const (
	// MaxMessageBytes is the largest message accepted, total.
	MaxMessageBytes = 25 * 1024 * 1024
	// MaxAttachmentBytes is the largest single attachment stored. A bigger part is dropped and
	// listed as rejected; the message is kept.
	MaxAttachmentBytes = 10 * 1024 * 1024
	// MaxAttachments is attachments stored per message; past it they are listed as rejected.
	MaxAttachments = 100
)
View Source
const (
	// MaxRecipients is recipients per message, to and cc together.
	MaxRecipients = 50
	// MaxSendBodyBytes is the body cap per part on a send.
	MaxSendBodyBytes = 512 * 1024
	// MaxSendAttachments is attachments per sent message.
	MaxSendAttachments = 32
	// MaxSendMessageBytes is the whole sent message, encoded, attachments included.
	MaxSendMessageBytes = 5 * 1024 * 1024
	// MaxSendRequestBytes is the largest request carrying a send: the largest message base64'd
	// into JSON, with room for the rest.
	MaxSendRequestBytes = 8 * 1024 * 1024
)
View Source
const (
	// BodyMax is the inline body cap per part, in UTF-16 code units as hosted.
	BodyMax = 512 * 1024
	// MaxListLimit / defaultListLimit bound a listing.
	MaxListLimit = 100

	// MaxWaiters is long-polls parked at once per instance; past it a waiter is answered empty.
	MaxWaiters = 50
	// MaxWaitMS is the longest a long-poll is held.
	MaxWaitMS = 30_000
	// MaxDeliveryAttempts is attempts before a delivery is given up on.
	MaxDeliveryAttempts = 5
)
View Source
const (
	// FunctionTimeout is how long one function call is waited for.
	FunctionTimeout = 30 * time.Second
	// WebhookTimeout is how long a webhook receiver is waited for.
	WebhookTimeout = 10 * time.Second
	// FunctionBodyMax is the body handed to a function (and a webhook), per part.
	FunctionBodyMax = 256 * 1024

	SignatureHeader = "x-altengine-signature"
	TimestampHeader = "x-altengine-timestamp"
)
View Source
const DefaultDomain = "mail.localhost"

DefaultDomain is the emulator's mail domain when none is configured.

View Source
const DefaultLocal = "inbox"

DefaultLocal is the name a bare `<slug>@` address files under.

View Source
const MaxLocalPart = 64

MaxLocalPart is RFC 5321's limit on the whole local part — slug, dot and name together.

View Source
const OrgSendsPerDay = 100

OrgSendsPerDay is the emulator's org-wide send cap. Hosted, an org may send 10 a day without a payment method and 100 with one. The emulator has no billing, so it applies the HIGHER of the two — local is never stricter than any hosted org, and never allows more than every hosted org does. It counts in memory: a restart starts the day over.

View Source
const StatusNotDelivered = "sent (emulator: not delivered)"

StatusNotDelivered is a sent message's status when no local mailbox took it.

Variables

View Source
var ErrShortenNeedsFull = errors.New("shortening an expiry needs full access")

ErrShortenNeedsFull is SetExpiry refusing to move an expiry earlier for a caller that may not.

Functions

func ActionKey

func ActionKey(a Action) string

ActionKey is the stable key a delivery row is stored under: the whole action, options included, so a retry does what the first attempt did even after the routes are edited.

func AddressFor

func AddressFor(slug, local, domain string) string

AddressFor is the address for a name on an instance. The default name is the bare `<slug>@`.

func AddressPattern

func AddressPattern(slug, domain string) string

AddressPattern is how every address of an instance looks, for showing a person.

func AttachmentKey

func AttachmentKey(messageID string, idx int) string

func BuildMessage

func BuildMessage(m OutMessage) []byte

BuildMessage renders a message as RFC 5322 bytes with CRLF line endings.

func ChannelPayload

func ChannelPayload(instanceName, ch string, m *Record, includeText bool) map[string]any

ChannelPayload is the channel message: envelope fields, no body unless asked, never an attachment URL — subscribers can be end users' browsers. Sized to fit the channel's message cap once framed as {channel, data, ts}.

func Clip

func Clip(s *string, max int) (*string, bool)

Clip truncates to at most max UTF-16 code units without splitting a surrogate pair — the unit the hosted service measures in.

func ClipBytes

func ClipBytes(s string, maxBytes int) (string, bool)

ClipBytes cuts s to at most maxBytes of UTF-8 without leaving half a character.

func DefaultConfigMap

func DefaultConfigMap() map[string]any

DefaultConfigMap is the registry's seed config for a new mailbox instance.

func GlobMatch

func GlobMatch(glob, value string) bool

GlobMatch: `*` any run, `?` one character, everything else literal, case-insensitive.

NOT a regex. A pattern is tenant input and a sender address is the internet's, and a glob compiled to a backtracking regex is a CPU-time denial of service on the inbound path. The two-pointer match is O(pattern × value) in the worst case and linear in practice.

func KeepUntil added in v0.2.34

func KeepUntil(days any, now int64) (int64, error)

KeepUntil is when one message should now expire: `days` (1–MaxRetentionDays) from now. Every surface that keeps a message longer or shorter goes through it, so none can keep one forever.

func MintLocal

func MintLocal() string

MintLocal is a name for a caller who did not choose one: `m` + 11 hex.

func NameFilter

func NameFilter(raw, slug, domain string) (string, error)

NameFilter reads a name filter from a caller: a bare name (`support`) or a full address on THIS instance. "" for an empty filter; an error for anything else, including an address on another instance.

func NewMessageID

func NewMessageID(now int64) string

NewMessageID is time-ordered and fixed-width: base36 milliseconds (9 chars) then random hex. Lexicographic order is creation order, so an id IS a keyset cursor.

func NormalizeDomain

func NormalizeDomain(d string) string

NormalizeDomain trims, lowercases and strips the leading/trailing dot of a configured domain.

func NormalizedConfigMap

func NormalizedConfigMap(raw map[string]any) map[string]any

NormalizedConfigMap is a config as the hosted service stores it after a write: every setting named with its value or default, the routes as validated. A save is followed by this, so get_instance_config reads back the same full shape it does hosted.

func RawKey

func RawKey(messageID string) string

RawKey / AttachmentKey name where a message's bytes are stored within its instance.

func ResolveAfter

func ResolveAfter(v string, now int64) string

ResolveAfter turns `now` into the current time's id prefix; anything else is an id as given.

func RetryAt

func RetryAt(attempts int, now int64) int64

RetryAt is when the next attempt is due after `attempts` failures, or 0 when there is none left.

func SenderVerified

func SenderVerified(headerValues []string, fromAddress, authservID string) bool

SenderVerified reports whether the From domain authenticated a message, from the Authentication-Results header the receiving server added: DMARC passed, or DKIM or SPF passed for a domain aligned with From. Only the TOPMOST header counts, and only when it names our own receiving server (authservID) — every header below it came with the message.

func SignWebhook

func SignWebhook(secret string, timestamp int64, body []byte) string

SignWebhook is the delivery signature: `v1=` + hex HMAC-SHA256, keyed with the whole secret, over "<timestamp>.<raw body>" — the scheme every altengine webhook uses.

func SlugOf

func SlugOf(instanceName string) string

SlugOf is an instance's slug locally: its name, when that is a valid slug, else "".

func SnippetOf

func SnippetOf(text, html *string) string

SnippetOf is a one-line preview: the text body, whitespace collapsed, bounded.

func SplitTarget

func SplitTarget(s string) (instance, name string)

SplitTarget splits `<instance>/<name>` at the FIRST slash: a channel name may contain slashes.

func UTCDay

func UTCDay(ms int64) string

UTCDay is the day a moment falls in, as the counter key.

func ValidSlug

func ValidSlug(s string) bool

ValidSlug reports whether s can be the first part of an address.

func ValidateConfig

func ValidateConfig(cfg map[string]any) error

ValidateConfig is the strict check every config write runs (console PUT, MCP patch), with the hosted rules and messages: a value out of range is refused, never clamped.

func ValidateLocal

func ValidateLocal(raw any, slug string) (string, error)

ValidateLocal checks a name a caller chose through the API, for an instance whose slug is `slug` ("" skips the length check against it): no plus tag, and short enough that the whole local part fits RFC 5321's 64 characters.

func ValidateOutboundAddress

func ValidateOutboundAddress(raw any, field string) (string, error)

ValidateOutboundAddress is a bare `user@domain` check for addresses we SEND to: one `@`, no whitespace, nothing that could end a header or open another address, a dotted domain.

func ValidateWebhookURL

func ValidateWebhookURL(v any, what string) (string, error)

ValidateWebhookURL: an https URL with no credentials in it. Kept exactly as hosted — locally too, so a route that saves here saves there; point it at an https tunnel to reach a local receiver.

Types

type Action

type Action struct {
	Function    string `json:"function,omitempty"`
	Channel     string `json:"channel,omitempty"`
	IncludeText bool   `json:"includeText,omitempty"`
	Webhook     string `json:"webhook,omitempty"`
	// Queue is `<tasks-instance>/<queue>`: the message becomes a task there.
	Queue string `json:"queue,omitempty"`
}

Action is one thing a route does: exactly one of Function, Channel, Webhook or Queue is set.

func ParseActionKey

func ParseActionKey(key string) (Action, bool)

ParseActionKey is the action a delivery key names; ok=false for a key this version does not understand.

type AddressRecord

type AddressRecord struct {
	Local      string         `json:"local"`
	Label      *string        `json:"label"`
	Meta       map[string]any `json:"meta"`
	Registered bool           `json:"registered"`
	CreatedAt  int64          `json:"createdAt"`
	DisabledAt *int64         `json:"disabledAt"`
}

AddressRecord is an address that carries a setting.

type AddressValue

type AddressValue struct {
	Address string `json:"address"`
	Name    string `json:"name"`
}

AddressValue is one mailbox (address and display name).

type AdmitResult

type AdmitResult struct {
	OK     bool
	Code   int
	Reason string
}

AdmitResult is the answer to "is this message taken".

type Attachment

type Attachment struct {
	Idx         int     `json:"idx"`
	Filename    *string `json:"filename"`
	ContentType string  `json:"contentType"`
	Size        int64   `json:"size"`
	ContentID   *string `json:"contentId"`
	Disposition *string `json:"disposition"`
	Rejected    *string `json:"rejected"`
	Key         string  `json:"-"`
}

Attachment is one attachment's record. Key is where its bytes are stored, "" when they were not (a rejected part).

type Config

type Config struct {
	Settings Settings `json:"settings"`
	Routes   []Route  `json:"routes"`
}

Config is the parsed instance config.

func ParseConfig

func ParseConfig(raw map[string]any) Config

ParseConfig reads an instance's stored config tolerantly: anything missing or malformed is the default, and a route that no longer validates is dropped rather than half-applied.

type Delivery

type Delivery struct {
	Action   string `json:"action"`
	Status   string `json:"status"`
	Attempts int    `json:"attempts"`
	NextAt   *int64 `json:"nextAt"`
}

Delivery is what one route action did for one message.

type DeliveryResult

type DeliveryResult struct {
	MessageID string
	Action    string
	Status    string
	Attempts  int
	NextAt    int64 // 0 = none
}

DeliveryResult is what one attempt did.

type DueDelivery

type DueDelivery struct {
	MessageID string
	Action    string
	Attempts  int
}

DueDelivery is one pending delivery whose time has come.

type Handler

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

Handler serves the mailbox planes.

func NewHandler

func NewHandler(reg *control.Registry, a *auth.Store, svc *Service) *Handler

NewHandler builds the handler.

func (*Handler) Register

func (h *Handler) Register(mux *http.ServeMux)

Register mounts the data plane, the signed downloads and the console's routes.

type ListOptions

type ListOptions struct {
	Local     string
	Cursor    string // newest-first: older than this id
	After     string // oldest-first: newer than this id
	Limit     int
	Unread    bool
	Direction string
}

ListOptions select one page of messages.

type Local

type Local struct {
	Local string
	Tag   string // "" = none
}

Local is a name with its optional plus tag.

func ParseLocal

func ParseLocal(raw string) (Local, bool)

ParseLocal splits `name+tag` and normalizes. ok is false when the name is not one we accept. A tag that is not printable is dropped rather than refused: it is only a hint the sender added.

type MatchInput

type MatchInput struct {
	Local           string
	From            string
	Subject         string
	AttachmentCount int
}

MatchInput is what route matching reads off a message.

type NewMessage

type NewMessage struct {
	ID          string
	Direction   string
	Local       string
	PlusTag     string
	From        AddressValue
	To, Cc      []AddressValue
	ReplyTo     []AddressValue
	Subject     string
	Text, HTML  *string
	MessageID   string
	InReplyTo   string
	References  string
	AuthResults string
	Verified    bool
	Status      string
	RawKey      string
	Size        int64
	StoredBytes int64
	Attachments []Attachment
	ReceivedAt  int64
	ExpiresAt   int64
}

NewMessage is what the inbound and send paths hand over to be stored.

type Options

type Options struct {
	// Domain is the mail domain every address is on. Default DefaultDomain.
	Domain string
	// Base is this emulator's own origin (http://127.0.0.1:9191), for URLs minted outside a
	// request: the attachment links in a function or webhook payload.
	Base string
	// Loopback, when true (the default), delivers a send to an address on a local mailbox into
	// that mailbox — what the hosted service does too, by real mail.
	Loopback *bool
}

Options configures the mailbox service.

type OutAttachment

type OutAttachment struct {
	Filename    string
	ContentType string
	Content     []byte
	// ContentID, when set, makes the part inline, referenced from the HTML as cid:<ContentID>.
	ContentID string
}

OutAttachment is a file to put in a built message.

type OutMessage

type OutMessage struct {
	From        AddressValue
	To, Cc      []AddressValue
	Subject     string
	Text, HTML  string
	MessageID   string
	InReplyTo   string
	References  string
	Date        time.Time
	Attachments []OutAttachment
	// Headers are extra header lines written first, verbatim (no CR or LF in them).
	Headers [][2]string
}

OutMessage is everything BuildMessage writes.

type ParsedAttachment

type ParsedAttachment struct {
	Filename    string
	MimeType    string
	Content     []byte
	ContentID   string
	Disposition string
}

ParsedAttachment is one attachment as found in a message.

type ParsedEmail

type ParsedEmail struct {
	From, To, Cc, ReplyTo []AddressValue
	Subject               string
	Text, HTML            *string
	MessageID             string
	InReplyTo             string
	References            string
	AuthResults           []string // every Authentication-Results value, top first
	Attachments           []ParsedAttachment
}

ParsedEmail is what ingest reads out of a raw message.

func ParseEmail

func ParseEmail(raw []byte) *ParsedEmail

ParseEmail parses a raw RFC 5322 message.

type PublicMessage

type PublicMessage struct {
	Summary
	Text          *string            `json:"text"`
	HTML          *string            `json:"html"`
	TextTruncated bool               `json:"textTruncated"`
	HTMLTruncated bool               `json:"htmlTruncated"`
	References    *string            `json:"references"`
	AuthResults   *string            `json:"authResults"`
	Deliveries    []Delivery         `json:"deliveries"`
	HasRaw        bool               `json:"hasRaw"`
	Attachments   []publicAttachment `json:"attachments"`
}

PublicMessage is a message as the API returns it: no storage keys.

func Public

func Public(m *Record) PublicMessage

Public strips a record to its API shape.

type QueueSink added in v0.2.35

type QueueSink interface {
	EnqueueMail(ref, messageID string, payload, summary []byte) (status, why string, permanent bool)
}

QueueSink is the tasks service as a route sees it: hand a message to `<tasks-instance>/<queue>`. payload is what a function would receive; summary is what is sent instead when payload is too large for a task. A narrow interface, so the mailbox does not depend on the tasks service.

type Recipient

type Recipient struct {
	Slug  string
	Local string
	Tag   string
}

Recipient is an envelope recipient resolved to the instance slug and name it addresses.

func ParseRecipient

func ParseRecipient(address, domain string) (Recipient, bool)

ParseRecipient resolves an address to the instance and name it addresses, or ok=false when it is not a mailbox address on this mail domain.

type Record

type Record struct {
	Summary
	Text          *string      `json:"text"`
	HTML          *string      `json:"html"`
	TextTruncated bool         `json:"textTruncated"`
	HTMLTruncated bool         `json:"htmlTruncated"`
	References    *string      `json:"references"`
	AuthResults   *string      `json:"authResults"`
	RawKey        string       `json:"-"`
	Attachments   []Attachment `json:"attachments"`
	Deliveries    []Delivery   `json:"deliveries"`
}

Record is a full message.

type Rejection

type Rejection struct{ SMTP string }

Rejection is a refusal as the sender sees it: an SMTP reply line.

func (*Rejection) Error

func (r *Rejection) Error() string

type Route

type Route struct {
	Match RouteMatch `json:"match"`
	Do    []Action   `json:"do"`
}

Route is one entry of the ordered trigger list.

func MatchRoute

func MatchRoute(routes []Route, m MatchInput) *Route

MatchRoute returns the first route whose every given field matches, or nil.

func ValidateRoutes

func ValidateRoutes(input any) ([]Route, error)

ValidateRoutes is the strict check of the route list, also reused by the tolerant read.

type RouteMatch

type RouteMatch struct {
	To            string `json:"to,omitempty"`
	From          string `json:"from,omitempty"`
	Subject       string `json:"subject,omitempty"`
	HasAttachment *bool  `json:"hasAttachment,omitempty"`
}

RouteMatch: every given field must hold. Globs are case-insensitive, `*` and `?`.

type SMTPServer

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

SMTPServer is the listener.

func (*SMTPServer) Addr

func (m *SMTPServer) Addr() net.Addr

Addr is the bound address.

func (*SMTPServer) Close

func (m *SMTPServer) Close() error

Close stops accepting and waits for sessions in flight.

func (*SMTPServer) Serve

func (m *SMTPServer) Serve()

Serve accepts connections until Close.

type Service

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

Service is the mailbox service: the store, the inbound path, triggers and sending.

func NewService

func NewService(reg *control.Registry, store *Store, mux http.Handler, hub *channel.Hub, o Options) *Service

NewService builds the service. mux is the emulator's router, used to call functions in process; hub is the channel hub routes publish into.

func (*Service) AdmitAddress

func (s *Service) AdmitAddress(to string, rawSize int64) (*control.Instance, Recipient, error)

AdmitAddress is everything that can refuse a message for a full address before its body is read. rawSize may be 0 when it is not yet known (SMTP without SIZE); the caller then checks the size after reading.

func (*Service) Deliver

func (s *Service) Deliver(to, envelopeFrom string, raw []byte, authenticated bool) (*Record, error)

Deliver is the whole inbound path for a full address: admit, then ingest.

func (*Service) DeliverLocal

func (s *Service) DeliverLocal(inst *control.Instance, to, envelopeFrom string, raw []byte, authenticated bool) (*Record, error)

DeliverLocal delivers to a bare `name[+tag]` (or a full address on this instance) of a known instance — what inject and the console do, with or without a valid slug.

func (*Service) Domain

func (s *Service) Domain() string

Domain is the mail domain.

func (*Service) Drop

func (s *Service) Drop(instanceID string)

Drop is the instance-delete hook: every message, file and key the instance holds.

func (*Service) FunctionPayload

func (s *Service) FunctionPayload(inst *control.Instance, m *Record) map[string]any

FunctionPayload is the function (and webhook) request body: the summary, the bodies (bounded), and attachments with short-lived download URLs.

func (*Service) Ingest

func (s *Service) Ingest(inst *control.Instance, to Local, envelopeFrom string, raw []byte, authenticated bool) (*Record, error)

Ingest parses, stores and dispatches one message that has already been admitted.

func (*Service) Keep added in v0.2.34

func (s *Service) Keep(inst *control.Instance, id string, days any, canShorten bool) (*Summary, error)

Keep is the one per-message expiry change: /v1, MCP, the function binding and the console. Extending needs `write`; moving the expiry EARLIER is a deferred delete, so only a caller that could delete (canShorten: `full`, or the console) may.

func (*Service) ListenSMTP

func (s *Service) ListenSMTP(addr string, authenticated bool) (*SMTPServer, error)

ListenSMTP binds addr. authenticated says whether mail received this way counts as coming from an authenticated sender (see authStamp) — what lets reply mode be tested end to end.

func (*Service) Loopback

func (s *Service) Loopback() bool

Loopback reports and sets whether sends to local addresses are delivered locally.

func (*Service) PutAddress

func (s *Service) PutAddress(inst *control.Instance, localRaw any, labelRaw any, metaRaw any) (*AddressRecord, error)

PutAddress is the one registration rule: /v1, MCP and the console call it.

func (*Service) Replay

func (s *Service) Replay(inst *control.Instance, id string) (*Record, error)

Replay re-runs a stored message through the instance's CURRENT routes: the deliveries are replaced with what the routes pick now and attempted at once. Returns the message as it stands afterwards.

func (*Service) Run

func (s *Service) Run(ctx context.Context)

Run drives Tick every few seconds until ctx is done.

func (*Service) Send

func (s *Service) Send(inst *control.Instance, input map[string]any) (*Summary, error)

Send sends one message from inst. Every surface — /v1, MCP, the function binding and the console — calls this, so the limits have one implementation. `input` is the JSON body: from, fromName, to, cc, subject, text, html, attachments, replyToMessageId.

func (*Service) SetLoopback

func (s *Service) SetLoopback(v bool)

func (*Service) Store

func (s *Service) Store() *Store

Store is the underlying store.

func (*Service) Tick

func (s *Service) Tick()

Tick is one pass of the background loop: expire what has passed its time and re-drive deliveries that are due.

func (*Service) Wait

func (s *Service) Wait()

Wait blocks until background deliveries started so far have finished (tests).

func (*Service) WithQueues added in v0.2.35

func (s *Service) WithQueues(q QueueSink) *Service

WithQueues lets routes hand mail to a task queue.

type Settings

type Settings struct {
	RateLimit       *int64 `json:"rateLimit"`
	Region          string `json:"region"`
	AcceptMode      string `json:"acceptMode"` // any | registered
	InboundDailyCap int64  `json:"inboundDailyCap"`
	RetentionDays   int64  `json:"retentionDays"`
	SendMode        string `json:"sendMode"`     // off | reply | any
	DailySendCap    *int64 `json:"dailySendCap"` // nil = only the org's cap
	KeepRaw         bool   `json:"keepRaw"`
}

Settings are the instance's scalars.

func DefaultSettings

func DefaultSettings() Settings

DefaultSettings is what a new instance starts with.

type Store

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

Store is every mailbox instance's data.

func NewStore

func NewStore(dir string) *Store

NewStore opens the store. dir "" keeps everything in memory.

func (*Store) Admit

func (s *Store) Admit(instanceID, local string, now int64, acceptMode string, cap int64) (AdmitResult, error)

Admit decides, before the body is read, whether a message for `local` is taken — and if so counts it against today's inbound cap. Counting here rather than at store is what makes the cap a bound under concurrent deliveries.

func (*Store) Bytes

func (s *Store) Bytes(instanceID, key string) ([]byte, bool)

Bytes reads one object's bytes.

func (*Store) DisableAddress

func (s *Store) DisableAddress(instanceID, local string, now int64) (*AddressRecord, error)

DisableAddress refuses inbound mail to an address and stops it sending; its messages stay.

func (*Store) Drop

func (s *Store) Drop(instanceID string)

Drop removes an instance entirely: its database, its bytes, its waiters.

func (*Store) DueDeliveries

func (s *Store) DueDeliveries(instanceID string, now int64, limit int) ([]DueDelivery, error)

DueDeliveries are pending deliveries at or past their time.

func (*Store) Expire

func (s *Store) Expire(instanceID string, now int64) (int, error)

Expire removes what has passed its expiry, and prunes old day counters.

func (*Store) Get

func (s *Store) Get(instanceID, id string) (*Record, error)

Get returns one full message, or nil.

func (*Store) GetAddress

func (s *Store) GetAddress(instanceID, local string) (*AddressRecord, error)

GetAddress returns an address's row, or nil.

func (*Store) HasWrittenToUs

func (s *Store) HasWrittenToUs(instanceID, sender string) (bool, error)

HasWrittenToUs: has `sender` written to this instance in AUTHENTICATED mail — reply mode's test.

func (*Store) List

func (s *Store) List(instanceID string, o ListOptions) ([]Summary, *string, error)

List returns one page. Newest first with Cursor; oldest first with After (what a poller wants).

func (*Store) ListAddresses

func (s *Store) ListAddresses(instanceID, cursor string, limit int) ([]*AddressRecord, *string, error)

ListAddresses pages the addresses that carry a setting, in name order.

func (*Store) MarkRead

func (s *Store) MarkRead(instanceID, id string, now int64) (bool, error)

MarkRead marks a message read (once) and reports whether it exists.

func (*Store) PrepareSend

func (s *Store) PrepareSend(instanceID, local string, recipients []string, requireReplied bool, cap *int64, now int64) error

PrepareSend checks, in one place, that the From address is not disabled, that in reply mode every recipient has written to us in authenticated mail, and that the instance's own daily cap (when it has one) has room — in which case one slot is taken.

func (*Store) PutAddress

func (s *Store) PutAddress(instanceID, local string, label *string, meta map[string]any, now int64) (*AddressRecord, error)

PutAddress registers (or labels) an address. Idempotent, keeps the original creation time, and re-enables a disabled address.

func (*Store) PutBytes

func (s *Store) PutBytes(instanceID, key string, b []byte) error

PutBytes stores one object's bytes.

func (*Store) RecordDeliveries

func (s *Store) RecordDeliveries(instanceID string, results []DeliveryResult) error

RecordDeliveries writes attempt results back.

func (*Store) Remove

func (s *Store) Remove(instanceID string, ids []string) (int, error)

Remove deletes messages: bytes first, then rows. Returns how many were removed.

func (*Store) ResetDeliveries

func (s *Store) ResetDeliveries(instanceID, messageID string, actions []string, now int64) error

ResetDeliveries replaces a message's deliveries with `actions`, all pending and untried — a replay through the current routes.

func (*Store) ReturnSend

func (s *Store) ReturnSend(instanceID string, now int64)

ReturnSend gives back a send slot taken for a send that then failed.

func (*Store) RotateWebhookSecret

func (s *Store) RotateWebhookSecret(instanceID string) (string, error)

RotateWebhookSecret replaces the key; the next delivery is signed with the new one.

func (*Store) SetExpiry added in v0.2.34

func (s *Store) SetExpiry(instanceID, id string, expiresAt int64, allowShorten bool) (*Summary, error)

SetExpiry moves one message's expiry. The caller bounds expiresAt (KeepUntil). Unless allowShorten, an expiresAt earlier than the current one is refused with ErrShortenNeedsFull and nothing changes — the check and the write are one statement. nil when there is no such message.

func (*Store) Stats

func (s *Store) Stats(instanceID string) (messages int64, storedBytes int64, err error)

Stats is the instance's message count and stored bytes.

func (*Store) StoreMessage

func (s *Store) StoreMessage(instanceID string, m NewMessage, deliveries []string) (Summary, error)

StoreMessage stores a message (inbound or sent), its attachments and the deliveries its route chose, then wakes any long-poll it satisfies.

func (*Store) WaitFor

func (s *Store) WaitFor(ctx context.Context, instanceID, local, after string, limit int, timeout time.Duration) ([]Summary, error)

WaitFor returns inbound messages after `after` (for `local`, when given), waiting up to timeout for the first one when there is none yet. Empty on timeout.

func (*Store) WebhookSecret

func (s *Store) WebhookSecret(instanceID string) (string, error)

WebhookSecret is the instance's webhook signing key, minted on first use.

type Summary

type Summary struct {
	ID              string         `json:"id"`
	Direction       string         `json:"direction"`
	Local           string         `json:"local"`
	PlusTag         *string        `json:"plusTag"`
	From            AddressValue   `json:"from"`
	To              []AddressValue `json:"to"`
	Cc              []AddressValue `json:"cc"`
	ReplyTo         []AddressValue `json:"replyTo"`
	Subject         string         `json:"subject"`
	Snippet         string         `json:"snippet"`
	MessageID       *string        `json:"messageId"`
	InReplyTo       *string        `json:"inReplyTo"`
	Verified        bool           `json:"verified"`
	Status          string         `json:"status"`
	Size            int64          `json:"size"`
	AttachmentCount int            `json:"attachmentCount"`
	ReceivedAt      int64          `json:"receivedAt"`
	ReadAt          *int64         `json:"readAt"`
	ExpiresAt       int64          `json:"expiresAt"`
}

Summary is a message as every list returns it: everything but the bodies.

Jump to

Keyboard shortcuts

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