Documentation
¶
Overview ¶
Package support implements the instance support inbox: capture of inbound human messages our bots cannot parse, and replies back through the channel they arrived on (spec 2026-08-22-02).
Two invariants govern everything here:
- CAPTURE IS THE INVARIANT. If a human sent it and the system could not act on it, it is recorded. Nothing here may be allowed to change that.
- A CAPTURE FAILURE MUST NEVER BREAK THE CHANNEL IT CAME FROM. The webhook still returns its normal 2xx and the alerting path is untouched. Capture is best-effort *for the request* — but a failure is logged at WARN and counted in solidping_support_capture_total, never swallowed silently.
Index ¶
- Constants
- Variables
- type Inbound
- type Mailer
- type Options
- type ReadReceiptFunc
- type ReplyFunc
- type ReplyRoute
- type RouteFunc
- type Service
- func (s *Service) Capture(ctx context.Context, inbound *Inbound) (*models.SupportThread, *models.SupportMessage, error)
- func (s *Service) CaptureSafe(ctx context.Context, inbound *Inbound)
- func (s *Service) CloseLiveThread(ctx context.Context, channel, identity string) (bool, error)
- func (s *Service) DetachOrganization(ctx context.Context, orgUID string) (int64, error)
- func (s *Service) GetThread(ctx context.Context, uid string) (*models.SupportThread, error)
- func (s *Service) ListMessages(ctx context.Context, threadUID string, limit int) ([]*models.SupportMessage, error)
- func (s *Service) ListThreads(ctx context.Context, filter models.ListSupportThreadsFilter) ([]*models.SupportThread, error)
- func (s *Service) LiveThread(ctx context.Context, channel, identity string) (*models.SupportThread, error)
- func (s *Service) MarkRead(ctx context.Context, thread *models.SupportThread) error
- func (s *Service) PurgeClosedBefore(ctx context.Context, before time.Time, batch int) (int64, error)
- func (s *Service) RecordDelivery(ctx context.Context, channel, externalID, status string)
- func (s *Service) RegisterReadReceipt(channel string, fn ReadReceiptFunc)
- func (s *Service) RegisterReplier(channel string, fn ReplyFunc)
- func (s *Service) RegisterRoutedReplier(channel string, fn ReplyFunc, route RouteFunc)
- func (s *Service) Reply(ctx context.Context, threadUID, body, authorUID string) (*models.SupportMessage, error)
- func (s *Service) ReplyRouteFor(ctx context.Context, thread *models.SupportThread) ReplyRoute
- func (s *Service) ReplyRoutes(ctx context.Context, threads []*models.SupportThread) map[string]ReplyRoute
- func (s *Service) Resend(ctx context.Context, threadUID, messageUID string) (*models.SupportMessage, error)
- func (s *Service) ThreadURL(threadUID string) string
- func (s *Service) UpdateThread(ctx context.Context, uid string, status, subject *string) (*models.SupportThread, error)
Constants ¶
const ( // DefaultMessagesPerThreadPerHour caps how many messages one conversation // may add in an hour. DefaultMessagesPerThreadPerHour = 120 // DefaultThreadsPerIdentityPerDay caps how many times one identity may open // a brand-new thread in a day. Closing and re-opening is legitimate; doing // it fifty times is not. DefaultThreadsPerIdentityPerDay = 20 // DefaultMirrorFoldWindow is how long one thread's mirror notifications are // folded into the next mail. Someone texting a hundred times must not // produce a hundred emails. DefaultMirrorFoldWindow = 10 * time.Minute // DefaultMirrorsPerHour caps mirrors instance-wide. DefaultMirrorsPerHour = 60 )
Abuse ceilings. These endpoints are fed by publicly reachable phone numbers, so the tables are attacker-influenced and every one of these is a hard bound rather than a nicety.
Variables ¶
var ( // ErrThreadNotFound is returned when no live thread matches the uid. ErrThreadNotFound = errors.New("support thread not found") // ErrReplyWindowClosed is returned when the channel will not accept a // free-form reply right now. It is a REFUSAL WE MAKE, deliberately, rather // than a provider error surfaced after the fact. ErrReplyWindowClosed = errors.New("the reply window for this thread has closed") // ErrNoReplier is returned when no adapter is registered for the channel. ErrNoReplier = errors.New("this channel cannot be replied to from the support inbox") // ErrNoReplyRoute is returned when the channel HAS an adapter but this // particular thread cannot be routed back through it — a Slack workspace // with no stored connection, a Discord thread with no channel id, an org // with no SMS sender. // // It is the per-thread sibling of ErrNoReplier, and like it, it is a refusal // we make BEFORE touching the provider. Nothing is stored on this path: the // send was never attempted, so there is no attempt to record. ErrNoReplyRoute = errors.New("this thread cannot be routed back to its channel") // ErrMessageNotFound is returned when a resend names a message that is not // in the thread. ErrMessageNotFound = errors.New("support message not found in this thread") // ErrNotResendable is returned when a resend names a message that is not a // failed outbound reply. ErrNotResendable = errors.New("only an outbound reply whose delivery failed can be resent") // ErrEmptyReply is returned for a blank reply body. ErrEmptyReply = errors.New("reply body is empty") // ErrUnknownChannel is returned for an inbound message on a channel the // support inbox does not model. ErrUnknownChannel = errors.New("unknown support channel") // ErrNoIdentity is returned when an inbound message carries nothing to // thread the conversation on. ErrNoIdentity = errors.New("inbound message has no channel identity") // ErrTooManyThreads is returned when one identity has opened more new // threads today than the abuse ceiling allows. ErrTooManyThreads = errors.New("identity opened too many support threads today") // ErrInvalidStatus is returned for a status outside open/pending/closed. ErrInvalidStatus = errors.New("invalid support status") )
Errors returned by the service.
Functions ¶
This section is empty.
Types ¶
type Inbound ¶
type Inbound struct {
// Channel is one of the models.SupportChannel* values.
Channel string
// Identity threads the conversation: an E.164 number, a Telegram chat id, a
// Slack user id, a Discord user id.
Identity string
// ExternalID is the provider's message id. Meta and Twilio both retry on
// any non-2xx, so a replay is guaranteed, not an edge case — this is what
// makes capture idempotent.
ExternalID string
// Body is the message text. Non-text messages carry a placeholder here and
// the real kind in RawType.
Body string
// RawType is one of the models.SupportRawType* values.
RawType string
// SenderLabel is a human-readable name for the subject line, when the
// channel offers one.
SenderLabel string
// Context carries whatever the reply adapter needs that is not the identity
// (a Slack IM channel id, a Discord DM channel id, a WhatsApp phone id).
Context map[string]any
// At is the provider's timestamp; zero means "now".
At time.Time
}
Inbound is one captured message, in channel-neutral terms.
type Options ¶
type Options struct {
Mailer Mailer
Logger *slog.Logger
BaseURL string
ReplyTo string
Now func() time.Time
}
Options configures a Service.
type ReadReceiptFunc ¶
type ReadReceiptFunc func(ctx context.Context, thread *models.SupportThread, externalID string) error
ReadReceiptFunc notifies the channel that a human has read (or answered) the conversation carrying externalID — the newest inbound message on the thread that has one. Mirrors ReplyFunc's registration pattern for the same reason: internal/support is a leaf package and cannot import the channel integrations, so the adapter is registered from server.go instead (see registerSupportRepliers in server/internal/app/support_wiring.go).
type ReplyFunc ¶
ReplyFunc sends an outbound reply through the thread's originating channel and returns the provider message id.
Adapters are registered rather than imported so this package stays a leaf: the Slack and Discord integrations already depend on handlers, and importing them here would close an import cycle. server.go, which imports everything anyway, is where the wiring lives.
type ReplyRoute ¶
type ReplyRoute struct {
// CanReply is false when the adapter has no usable route for this thread.
CanReply bool
// Reason explains a false CanReply in operator-facing terms. Empty when
// CanReply is true.
Reason string
}
ReplyRoute is the PER-THREAD answer to "can we answer this person right now?".
It is deliberately not a bare bool: an operator staring at a disabled reply box needs to know whether the workspace was never installed, the thread lost its channel id, or the instance has no SMS at all — three very different things to go and fix.
type RouteFunc ¶
type RouteFunc func(ctx context.Context, thread *models.SupportThread) ReplyRoute
RouteFunc is the PRE-FLIGHT companion to a ReplyFunc: it answers, for one specific thread, whether the adapter could route a reply — without sending anything.
It is a separate function rather than a dry-run flag on ReplyFunc precisely because its type cannot send: it returns an answer and a reason, not a provider message id, so there is nowhere for an accidental send to put its result. A dry-run boolean would leave every adapter one missed branch away from posting a message to a customer while merely rendering a list.
It must NOT call the provider. It resolves local routing state — is there a stored connection, a channel id, an SMS sender — and nothing more: this runs once per thread on every inbox render, and a provider that is merely slow must never start reading as "cannot reply".
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the support inbox.
func NewService ¶
NewService builds the support inbox service.
func (*Service) Capture ¶
func (s *Service) Capture( ctx context.Context, inbound *Inbound, ) (*models.SupportThread, *models.SupportMessage, error)
Capture records an inbound message, creating or continuing a thread.
Returns the thread and the message. A duplicate (same channel + external id) returns the existing rows and no error — a webhook retry is a normal event, not a fault.
func (*Service) CaptureSafe ¶
CaptureSafe records an inbound message and NEVER returns an error or panics.
This is the entry point every webhook uses. It exists so a capture failure — a DB outage, a panic in a parser, an abuse ceiling — cannot turn into a non-2xx on a provider webhook, which would make the provider retry, which would eventually make the provider disable the subscription. Losing one message is bad; losing the channel is worse.
func (*Service) CloseLiveThread ¶
CloseLiveThread closes the live thread for a channel identity, when there is one. It reports whether a thread was closed.
This is the person leaving support mode themselves (Telegram's /done). It does not mark the thread read: an operator who has not seen the last messages must still find them unread in the inbox.
func (*Service) DetachOrganization ¶
DetachOrganization strips attribution from every thread pointing at a deleted organization.
The thread itself SURVIVES. Attribution is a hint about who we think wrote in, not ownership: deleting an org must not delete a stranger's support conversation, and it must not leave a dangling reference either.
func (*Service) ListMessages ¶
func (s *Service) ListMessages( ctx context.Context, threadUID string, limit int, ) ([]*models.SupportMessage, error)
ListMessages returns a thread's messages in chronological order.
func (*Service) ListThreads ¶
func (s *Service) ListThreads( ctx context.Context, filter models.ListSupportThreadsFilter, ) ([]*models.SupportThread, error)
ListThreads returns threads newest-activity-first.
func (*Service) LiveThread ¶
func (s *Service) LiveThread( ctx context.Context, channel, identity string, ) (*models.SupportThread, error)
LiveThread returns the live (not closed) thread for a channel identity, or nil when there is none.
Channels with an explicit support mode (Telegram's /support) use it as that mode's state: a person is "in support" exactly while a live thread exists, so closing the thread from the inbox ends the mode too, with nothing to keep in sync.
func (*Service) MarkRead ¶
MarkRead zeroes a thread's unread counter and, on the unread→read transition, fires the channel's registered read-receipt hook (see RegisterReadReceipt) best-effort.
thread must already be loaded by the caller (GetThread) — this reads only its UID, Channel and UnreadCount and takes it instead of a bare uid so a caller that renders the inbox on every open does not have to re-query just to know what to pass. thread.UnreadCount is set to 0 in place once the write lands, keeping the caller's copy consistent with what was persisted.
The check "was UnreadCount > 0 before this call" IS the idempotency gate: re-opening an already-read thread is a genuine no-op, not a second call to Meta's mark-as-read API.
func (*Service) PurgeClosedBefore ¶
func (s *Service) PurgeClosedBefore(ctx context.Context, before time.Time, batch int) (int64, error)
PurgeClosedBefore deletes closed threads last touched before `before`, and their messages by cascade. Returns how many threads went.
Message bodies are PERSONAL DATA — this is the retention half of the privacy obligation the feature carries, and DetachOrganization below is the erasure half.
func (*Service) RecordDelivery ¶
RecordDelivery updates the delivery status of an OUTBOUND support message from a provider callback.
This deliberately reuses the same callbacks that already drive incident_notifications rather than inventing a second delivery pipeline: the WhatsApp webhook and the Twilio status callback both arrive keyed on the provider message id, which is exactly what support_messages.external_id stores.
Best-effort and silent when nothing matches — the overwhelming majority of those callbacks are about an alert, not a support reply, so "no such message" is the normal case and must not be logged as a fault.
func (*Service) RegisterReadReceipt ¶
func (s *Service) RegisterReadReceipt(channel string, fn ReadReceiptFunc)
RegisterReadReceipt wires a channel's read-receipt notifier. A channel with none registered is a silent no-op: fireReadReceipt only ever calls a registered hook, never fabricates one. v1 registers WhatsApp only — a future WhatsApp command dispatcher calls whatsapp.Client.MarkRead directly instead of going through this hook, because its policy (mark read on receipt, not on operator read) is different.
func (*Service) RegisterReplier ¶
RegisterReplier wires an outbound adapter for one channel, with no per-thread pre-flight: registered means routable. Calling it twice for the same channel replaces the previous adapter.
Use it only where reachability is genuinely a property of the instance rather than of the thread — WhatsApp and Telegram, whose registration is already gated on their config being present.
func (*Service) RegisterRoutedReplier ¶
RegisterRoutedReplier wires an outbound adapter together with the pre-flight that decides, per thread, whether that adapter has a route.
This is the form every channel whose reachability varies by thread must use — Slack (is there a stored connection for THIS workspace?), Discord (does the thread carry a channel id?), SMS (does this org resolve to a sender?). Registering such a channel with RegisterReplier is the exact bug this distinction exists to prevent.
func (*Service) Reply ¶
func (s *Service) Reply( ctx context.Context, threadUID, body, authorUID string, ) (*models.SupportMessage, error)
Reply sends an outbound reply through the thread's channel and records it.
The window check happens HERE, before the send, so an expired WhatsApp thread produces our own explanatory refusal rather than a provider error the operator has to decode.
func (*Service) ReplyRouteFor ¶
func (s *Service) ReplyRouteFor(ctx context.Context, thread *models.SupportThread) ReplyRoute
ReplyRouteFor answers, for ONE thread, whether a reply can be routed.
This replaced a channel-level CanReply(channel) lookup, which asked a per-thread question of a boot-time map and therefore reported every Slack thread as answerable whether or not its workspace had ever been connected. The channel-level form is deliberately gone rather than deprecated: leaving it callable is leaving the bug callable.
func (*Service) ReplyRoutes ¶
func (s *Service) ReplyRoutes( ctx context.Context, threads []*models.SupportThread, ) map[string]ReplyRoute
ReplyRoutes answers the pre-flight for a whole listing, memoized on the inputs a route decision actually depends on.
Without the memo an inbox page is an N+1: the Slack pre-flight is a connection lookup, and a 500-thread listing from one busy workspace would run 500 identical ones. Threads sharing a channel, an attributed org and a channel context resolve identically by construction — that tuple is exactly what the registered RouteFuncs read.
func (*Service) Resend ¶
func (s *Service) Resend( ctx context.Context, threadUID, messageUID string, ) (*models.SupportMessage, error)
Resend re-attempts delivery of an outbound reply whose send failed, rewriting that message's delivery record in place.
This is the way out of the state the pre-flight cannot undo: replies stored before a route existed (or during a provider outage) are the operator's own words, visibly kept and permanently unsent. Resending re-runs the full pre-flight — window, then route — so a message queued against a workspace that has since been connected simply goes, and one that still has no route is refused with the current reason rather than failing again at the provider.
Only a FAILED OUTBOUND message qualifies. Resending a delivered reply would send a customer the same text twice, which is worse than the problem.
func (*Service) UpdateThread ¶
func (s *Service) UpdateThread( ctx context.Context, uid string, status, subject *string, ) (*models.SupportThread, error)
UpdateThread applies an operator's status/subject change.