gateways

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 40 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gateways holds the Notification gateways of C-30: the Bridge Connections whose stored info declares the role gateway, and the contacts of people at them (C-30.FR-3). A person adds a contact from their own web session and confirms it with a code that the gateway delivers through sendNotification on the interactive path; the code is kept at rest as its HMAC with a Keyring sub-key, compared in constant time and only in the session that asked for it (ADR-0013), within the limits of gateway.contact_code and gateway.contact_code_requests on the business clock. An Admin sees and removes the contacts of any User, never sets one. A contact is personal data, not a Secret: it is stored in plain text, and masked wherever it would be logged. Deleting a User erases their contacts and codes (C-03.FR-13).

Index

Constants

View Source
const (
	AckNotVerified          = "not_verified"
	AckExpired              = "expired"
	AckUnknownCall          = "unknown_call"
	AckNotAccepted          = "not_accepted"
	AckNotificationMismatch = "notification_mismatch"
	AckStaleCall            = "stale_call"
	AckDisabled             = "disabled"
	AckDeleted              = "deleted"
)

The reasons of gateway_acknowledge_refused: action data that is not Muster's signature of a call, data signed with a key that left the Keyring, a call that is not one of the Connection that reported it, a call the gateway never accepted, an event whose notification_id is not the one the gateway accepted the call under, a call that ended more than AckWindow ago, and a person the call was for who is disabled or deleted.

View Source
const (
	CallWaiting      = "waiting"
	CallSending      = "sending"
	CallAccepted     = "accepted"
	CallNotDelivered = "not_delivered"
	CallDropped      = "dropped"
)

The states of a call.

View Source
const (
	// CodeLength, CodeTTL and MaxAttempts are gateway.contact_code: 6 digits, valid 10 minutes, at most 5 attempts.
	CodeLength  = 6
	CodeTTL     = 10 * time.Minute
	MaxAttempts = 5
	// RequestsPerUser, RequestsPerContact and CodesPerContact are gateway.contact_code_requests within RequestWindow:
	// the codes a User asks for, refused beyond it; the codes a User asks for to one contact text, refused beyond it;
	// and the codes one contact text receives whoever asks, beyond which a request is answered as sent and nothing is
	// sent, so that the answer never tells of other Users' requests.
	RequestsPerUser    = 5
	RequestsPerContact = 3
	CodesPerContact    = 10
	RequestWindow      = time.Hour
	// CodePruneAfter is how long after it expired a code is deleted, as account_link.request_prune_after is for the
	// Account link requests it is pruned with.
	CodePruneAfter = 24 * time.Hour
	// MaxContactLength is the longest contact, in characters, as the Bridge protocol takes it.
	MaxContactLength = 200
)

The settings gateway.contact_code and gateway.contact_code_requests (defaults.md, P-86).

View Source
const (
	ActionCreated   = "gateway_contact.created"
	ActionConfirmed = "gateway_contact.confirmed"
	ActionDeleted   = "gateway_contact.deleted"
	ResourceContact = "gateway_contact"
)

The Audit log actions and resource of C-30.FR-3.

View Source
const (
	ReasonReplaced    = "replaced"
	ReasonUserDeleted = "user_deleted"
)

The reasons of gateway_contact.deleted that its person or an Admin did not ask for.

View Source
const (
	ReasonWrongCode    = "wrong_code"
	ReasonOtherSession = "other_session"
	ReasonUsed         = "used"
	ReasonVoid         = "void"
	ReasonExpired      = "expired"
	ReasonNoCode       = "no_code"
)

The reasons of gateway_contact_code_rejected.

View Source
const (
	OutcomeOK       = "ok"
	OutcomeLimited  = "limited"
	OutcomeError    = "error"
	OutcomeWithheld = "withheld"
)

The outcomes of gateway_contact_code_sent besides the error classes of the Bridge protocol.

View Source
const (
	ClassTransient   = "transient"
	ClassRateLimited = "rate_limited"
	ClassGone        = "gone"
	ClassForbidden   = "forbidden"
	ClassInvalid     = "invalid"
)

The error classes of the Bridge protocol that a refusal of the gateway has.

View Source
const (
	CodeUnknownID          = "unknown_id"
	CodeInvalidFormat      = "invalid_format"
	CodeContactCodeInvalid = "contact_code_invalid"
)

The codes of the field errors.

View Source
const (
	SenderLease          = delivery.Lease
	SenderBatch          = delivery.Batch
	SenderTokenMargin    = delivery.TokenMargin
	SenderMaxWait        = delivery.MaxWait
	SenderMinWait        = delivery.MinWait
	SenderFailureBackoff = delivery.FailureBackoff
	SenderConcurrency    = 4
)

The defaults of the sender, as the delivery worker's (internal/delivery): the lease of a claimed call, renewed before its attempt; the calls one claim takes; the margin after the time a limiter token is due; the longest and the shortest wait between rounds; and the first wait after a failed round.

SenderConcurrency is the sender's own: the calls a round attempts at once. Four keep the default limiter of a gateway's Connection (connection.bridge.limiter, 10 calls a second) busy while the gateway answers each call within 400 ms, where one call at a time would make one call per answer. A round holds at most four connections of the main pool at once: its claims and preparations run on its own goroutine, each holding one of the four slots, and each attempt holds at most one connection at a time — its preparation's transaction, then its record's, none while the gateway answers. Beside them, the probes of Broken gateways that a round starts at its end, up to ProbeConcurrency, which may run into the next round, hold one each for their short reads and transaction. Processing keeps to half of a pool of max(10, CPUs) (db.MinPoolConns): at the peak, with a gateway that answers at once and no gateway Broken, the sender and processing hold up to 9 of a pool of 10 and the others wait in the pool's queue; a gateway that takes longer to answer than a transaction takes leaves the sender's slots without a connection most of the time.

View Source
const AckWindow = keyring.CallKeyWindow

AckWindow is how long after a call ended — when the gateway accepted it — an acknowledgement of it is still acted on, by the business clock that ended_at is written by: bridge.event_max_age, the age at which the report of an acknowledgement is dropped, plus as long again for the call to ring or be retried by the gateway after it was accepted. It is keyring.CallKeyWindow, the time the Keyring keeps the key that signed the call's action data.

View Source
const BrokenProbeInterval = delivery.BrokenProbeInterval

BrokenProbeInterval is delivery.broken_probe_interval: how often a Broken gateway is probed through info.

View Source
const CallRetentionBatch = 5000

CallRetentionBatch is the most calls one delete of their retention removes.

View Source
const CallsChannel = "muster_gateway_calls"

CallsChannel is the LISTEN/NOTIFY channel that wakes the gateway senders of every replica when a Page is queued.

View Source
const CombineWindow = 60 * time.Second

CombineWindow is gateway.combine_window (P-87, provisional): the first call to a person through a gateway goes at once; the Pages that come due after it go together in the next call, no sooner than this after the previous call ended, accepted or Not delivered.

View Source
const MaxCallText = bridge.MaxNotificationText

MaxCallText is the longest text of a call: the bridge client cuts a notification's text there (api/bridge.yaml).

View Source
const ProbeConcurrency = 4

ProbeConcurrency is how many probes of Broken gateways one replica runs at once: a probe whose info hangs holds one of them, and never the calls of the sender or the other probes.

View Source
const ReconcileWindow = 2 * BrokenProbeInterval

ReconcileWindow is how far back the Leader's reconciliation looks for calls that failed without making their gateway Broken: twice delivery.broken_probe_interval, many runs of its Leader task, so that it never rescans the history of calls.

Variables

View Source
var (
	// ErrNotFound is a contact that does not exist or is not the User's.
	ErrNotFound = errors.New("no such gateway contact")
	// ErrUserNotFound is a User an Admin names that does not exist.
	ErrUserNotFound = errors.New("no such user")
)
View Source
var ErrNoPage = errors.New("no such user, notification gateway or alert group")

ErrNoPage is a Page that names no User, no Notification gateway or no Alert Group of the Organization, or a deleted one.

View Source
var ErrUnknownStop = errors.New("unknown stop check")

ErrUnknownStop is a Page with a StopCheck that this version does not know, or without the runs it names.

Functions

This section is empty.

Types

type AckQueries

type AckQueries interface {
	GetAcknowledgedCall(ctx context.Context, arg dbgen.GetAcknowledgedCallParams) (dbgen.GetAcknowledgedCallRow, error)
	ListCallGroups(ctx context.Context, arg dbgen.ListCallGroupsParams) ([]dbgen.ListCallGroupsRow, error)
}

AckQueries are the reads of the Acknowledge through a Notification gateway; *dbgen.Queries implements them.

func NewAckQueries

func NewAckQueries(d DBTX) AckQueries

NewAckQueries are the AckQueries over the main pool.

type Acknowledgements

type Acknowledgements struct {
	OrgID   int64
	Queries AckQueries
	// Commands run Acknowledge through the dispatcher, one Alert Group at a time, each in its own transaction.
	Commands Acknowledger
	// Roles are the Permissions of each Role, which the person the call was for acts with.
	Roles auth.Roles
	// Keys verify the action data: the Keyring.
	Keys buttons.Keys
	// Business dates the end of a call against AckWindow: the business clock, which ended_at is written by.
	Business clock.Clock
	Log      *logging.Logger
}

Acknowledgements handle the notification_acknowledged events of the Notification gateways of an Organization (C-30.FR-6, ADR-0013): they implement bridge.Acknowledgements, which internal/runtime wires into bridge.Events, and run inside the event's claim, so that an event is handled once per id (C-22.FR-11).

func (*Acknowledgements) Acknowledged

func (a *Acknowledgements) Acknowledged(ctx context.Context, c bridge.Conn, ev bridge.Event) (string, error)

Acknowledged runs the Acknowledge of the event ev of the Connection c and returns its answer, in the profile language of the person the call was for (C-12.FR-3), which bridge.Events makes with answerEvent on the interactive path. The action data is verified with the key it names and must name a call of this Connection and this Organization (buttons.SubjectCall); the actor is the User the call was for, never the contact (ADR-0013). For each Alert Group of the call — those it carried from its first attempt, also one whose chain stopped meanwhile — the dispatcher runs Acknowledge with the Transport gateway, whose precondition refuses an Alert Group that someone owns or that is resolved (groups.acknowledge); a person without the Permission is refused by the dispatcher, as for a press (C-18.FR-8). Data that does not verify, a call of another Connection, an event about another notification than the one the gateway accepted the call under, a call never accepted or that ended more than AckWindow ago (bound), and a disabled or deleted person run nothing, are logged as gateway_acknowledge_refused and answered so. An error — a read that failed, or a Command that failed otherwise than by its refusal — fails the event, so that it comes again.

type Acknowledger

type Acknowledger interface {
	Acknowledge(ctx context.Context, c groups.Caller, publicID string) (groups.Result, error)
}

Acknowledger is the Command a call acknowledges with; *groups.Service implements it.

type Broken

type Broken struct {
	OrgID int64
	Store BrokenStore
	// Lease names this replica in the lease of a probe and carries the clocks: broken_since and the probes on the
	// business clock, the lease on the real clock.
	Lease db.Lease
	// Prober probes a Broken gateway through info: *connections.Service.
	Prober Prober
	// RunbookBase is MUSTER_RUNBOOK_BASE_URL, the base of the runbook_url of MusterNotificationGatewayBroken.
	RunbookBase string
	Log         *logging.Logger
	// contains filtered or unexported fields
}

Broken keeps the Broken state of the Notification gateways of the Organization OrgID.

func (*Broken) Break

func (b *Broken) Break(ctx context.Context, g brokenGateway, cause, reason string) error

Break makes the gateway g Broken with cause and reason, the masked error it answered, in a transaction of its own: MusterNotificationGatewayBroken, the Connection's hint and gateway_broken once committed. A gateway that is Broken already stays so with reason as its reason, and its Connection's hint is sent; a deleted Connection changes nothing.

func (*Broken) Deleted

func (b *Broken) Deleted(ctx context.Context, tx DBTX, connectionID int64) error

Deleted ends the Broken state of the deleted Connection connectionID in the transaction tx of its deletion, which locked its row: MusterNotificationGatewayBroken resolves, and nothing is logged.

func (*Broken) EndBroken

func (b *Broken) EndBroken(ctx context.Context, connectionID int64) error

EndBroken ends the Broken state of the gateway connectionID after a successful check of its Connection (C-30.FR-8), in a transaction of its own, logged once committed. A gateway that is not Broken changes nothing.

func (*Broken) Export

func (b *Broken) Export(ctx context.Context) error

Export sets muster_notification_gateway_broken to 1 for each Broken gateway of the Organization that is not deleted and 0 for the Notification gateways in order, as part of the Leader task delivery_queue; the series of a gateway that was deleted or is no Notification gateway any more is removed. Running it twice sets the same values.

func (*Broken) Next

func (b *Broken) Next(ctx context.Context) (time.Duration, bool, error)

Next is how long until the next probe of a Broken gateway can be claimed, false for none. While every slot probes, a due probe cannot be claimed before one is freed, which wakes the sender, so only the end of a live lease counts.

func (*Broken) Probe

func (b *Broken) Probe(ctx context.Context) error

Probe starts the probes of the Broken gateways that are due, each claimed, and so leased, just before it runs, in a goroutine of its own, at most ProbeConcurrency at once, and returns without waiting for them: a probe whose info hangs delays neither the calls of the sender nor the other probes. A failed claim is the round's error; a probe whose outcome could not be recorded is logged as gateway_probe_failed, and the gateway is probed again after delivery.broken_probe_interval.

func (*Broken) Reconcile

func (b *Broken) Reconcile(ctx context.Context) error

Reconcile brings the Broken state of the Notification gateways of the Organization in line with their calls and their Internal alerts, as part of the Leader task delivery_queue; running it twice changes nothing more. A gateway that is not Broken whose call failed in a way that breaks a gateway — a Fatal outcome that reached it, or a used budget — within ReconcileWindow and after its last Broken state ended is made Broken: the replica that ended the call stopped before it did so. An open MusterNotificationGatewayBroken of a Connection that is not Broken, or is deleted or gone, is resolved, as one that a down migration left behind; the Connection's row is locked first, so that a Break or an end of the state at the same moment is either before or after it.

func (*Broken) Renamed

func (b *Broken) Renamed(ctx context.Context, tx DBTX, publicID, name string) error

Renamed raises an open MusterNotificationGatewayBroken of the Connection publicID again with its new name, in the transaction tx of the rename, as the same firing.

func (*Broken) Wait

func (b *Broken) Wait()

Wait waits until the probes that Probe started have ended.

type BrokenQueries

BrokenQueries are the queries of Broken gateways, with the writes of Internal alerts and the hint of a Connection, in one transaction or alone.

type BrokenStore

type BrokenStore interface {
	BrokenQueries
	InBrokenTx(ctx context.Context, f func(q BrokenQueries) error) error
	Over(tx DBTX) BrokenQueries
}

BrokenStore runs the queries of Broken gateways over the main pool, alone or in a short transaction, and over the transaction of a caller.

func NewBrokenStore

func NewBrokenStore(p Pool) BrokenStore

NewBrokenStore is the BrokenStore over the main pool.

type CallPruner

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

CallPruner deletes the calls whose Alert Groups were all deleted, for the alert_group_retention Leader task.

func NewCallPruner

func NewCallPruner(d DBTX) CallPruner

NewCallPruner returns the CallPruner over d.

func (CallPruner) Calls

func (p CallPruner) Calls(ctx context.Context, orgID int64, now time.Time) (int64, error)

Calls deletes the calls of the Organization that ended at or before now — accepted, Not delivered or dropped — and are about no Alert Group any more, the retention of Alert Groups having deleted every one of theirs with their items (retention.alert_group_summaries), in batches of at most CallRetentionBatch until a batch comes back short; their texts, which named those Alert Groups, were cleared when they ended. It runs after the Alert Group retention, in its Leader task; running it twice deletes nothing more.

type CallQueries

type CallQueries interface {
	GetPage(ctx context.Context, arg dbgen.GetPageParams) (dbgen.GetPageRow, error)
	GetPageGroupID(ctx context.Context, arg dbgen.GetPageGroupIDParams) (int64, error)
	GetGateway(ctx context.Context, arg dbgen.GetGatewayParams) (dbgen.GetGatewayRow, error)
	GetGatewayByID(ctx context.Context, arg dbgen.GetGatewayByIDParams) (dbgen.GetGatewayByIDRow, error)
	ListCallableUsers(ctx context.Context, arg dbgen.ListCallableUsersParams) ([]int64, error)
	GetUserByPublicID(ctx context.Context, arg dbgen.GetUserByPublicIDParams) (dbgen.GetUserByPublicIDRow, error)
	LockCallPerson(ctx context.Context, arg dbgen.LockCallPersonParams) error
	PreviousCall(ctx context.Context, arg dbgen.PreviousCallParams) (dbgen.PreviousCallRow, error)
	LockWaitingCall(ctx context.Context, arg dbgen.LockWaitingCallParams) (dbgen.LockWaitingCallRow, error)
	InsertWaitingCall(ctx context.Context, arg dbgen.InsertWaitingCallParams) (int64, error)
	MarkCallCritical(ctx context.Context, arg dbgen.MarkCallCriticalParams) error
	AddCallItem(ctx context.Context, arg dbgen.AddCallItemParams) error
	NotifyCalls(ctx context.Context, channel string) error
	ClaimDueCalls(ctx context.Context, arg dbgen.ClaimDueCallsParams) ([]dbgen.ClaimDueCallsRow, error)
	GetLeasedCall(ctx context.Context, arg dbgen.GetLeasedCallParams) (dbgen.GetLeasedCallRow, error)
	ListCallGroups(ctx context.Context, arg dbgen.ListCallGroupsParams) ([]dbgen.ListCallGroupsRow, error)
	DropCallItems(ctx context.Context, arg dbgen.DropCallItemsParams) error
	CallContact(ctx context.Context, arg dbgen.CallContactParams) (dbgen.CallContactRow, error)
	StartCall(ctx context.Context, arg dbgen.StartCallParams) (int64, error)
	RenewCallLease(ctx context.Context, arg dbgen.RenewCallLeaseParams) (int64, error)
	RescheduleCall(ctx context.Context, arg dbgen.RescheduleCallParams) (int64, error)
	UnstartCall(ctx context.Context, arg dbgen.UnstartCallParams) (int64, error)
	RecordCallRetry(ctx context.Context, arg dbgen.RecordCallRetryParams) (int64, error)
	EndCall(ctx context.Context, arg dbgen.EndCallParams) (bool, error)
	ReleaseWaitingCall(ctx context.Context, arg dbgen.ReleaseWaitingCallParams) error
	NextCallWork(ctx context.Context, arg dbgen.NextCallWorkParams) (dbgen.NextCallWorkRow, error)
}

CallQueries are the queries of the calls; *dbgen.Queries implements them.

type CallStore

type CallStore interface {
	CallQueries
	InCallTx(ctx context.Context, f func(tx DBTX, q CallQueries) error) error
}

CallStore runs the queries of the calls over the main pool, alone or in short transactions that also hand out the transaction itself, which the dispatcher and the limiter write through.

func NewCallStore

func NewCallStore(p Pool) CallStore

NewCallStore is the CallStore over the main pool.

type CallTarget

type CallTarget struct {
	Gateway  groups.PageGateway
	Live     bool
	Callable []int64
}

CallTarget is what a Page through a Notification gateway may call (C-32.FR-14, C-31.FR-3): the gateway, Live while it is not deleted and still declares the role gateway, and the people among those asked who have a confirmed contact there, in id order.

type Calls

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

Calls queues the calls of an Organization: Page, in the transaction of its caller.

func NewCalls

func NewCalls(orgID int64, business clock.Clock, log *logging.Logger) *Calls

NewCalls is the queue of calls of the Organization orgID, dated on the business clock.

func (*Calls) DevPage

func (c *Calls) DevPage(ctx context.Context, store CallStore, userPublicID, gatewayPublicID string,
	groupPublicIDs []string) error

DevPage queues, under muster dev, a call of the Notification gateway gatewayPublicID to the User userPublicID about each of the Alert Groups groupPublicIDs, as a Notification rule's call would, with StopNotFiring, in one transaction of store (POST /_dev/gateway-calls). An id that names nothing is an error that wraps ErrNoPage, and nothing is queued.

func (*Calls) Page

func (c *Calls) Page(ctx context.Context, tx DBTX, p PageCall) (func(context.Context), error)

Page queues the Page p in the transaction tx of its caller (C-30.FR-4): it joins the call to the person through the gateway that waits for its first attempt, or creates one, due at once when the person had no call through the gateway or the last one ended CombineWindow ago or longer, due CombineWindow after the last one ended otherwise, and not due while the last one is still being sent, until it ends; the call becomes critical once a critical Alert Group joins it, and stays critical even when that Alert Group is dropped from it before its first attempt: it is claimed early, and its preparation then finds what is left. tx must be READ COMMITTED, PostgreSQL's default: the waiting call and the previous call are read after the person's lock, and must show what its last holder committed. It takes the person's lock first (calls.go, Lock order) and wakes the senders once tx commits, and returns what to log once tx committed.

func (*Calls) Queue

func (c *Calls) Queue(ctx context.Context, tx DBTX, p PageCall) (int64, func(context.Context), error)

Queue is Page, which also returns the internal id of the call the Page joined or created: the Alert Group's item keeps the Page p.Page and the stop check of p, its run and its rule run — those of the latest Page when the call is about the Alert Group already, as when its chain started over and Paged again.

func (*Calls) Target

func (c *Calls) Target(ctx context.Context, tx DBTX, gatewayID int64, gatewayPublicID string, users []int64) (
	CallTarget, error)

Target reads, in the transaction tx of its caller, the Notification gateway gatewayID — or, when it is 0, the one whose public_id is gatewayPublicID, as a Notification rule names it — and those of users who have a confirmed contact there.

type CodeKeys

type CodeKeys interface {
	Sign(p keyring.Purpose, msg []byte) (mac []byte, keyID string, err error)
	Verify(p keyring.Purpose, keyID string, msg, mac []byte) (bool, error)
	KeyIDs() []string
}

CodeKeys sign the codes of contacts and check them with every key they hold; *keyring.Keyring implements them.

type Config

type Config struct {
	OrgID int64
	Store Store
	// Keys sign the codes as they are stored: the Keyring.
	Keys  CodeKeys
	Audit *audit.Writer
	// Business is the business clock: the times of contacts and codes, the expiry of a code and the request limits.
	Business clock.Clock
	Log      *logging.Logger
	// Gateway sends the notification with a code, through Path, the interactive path.
	Gateway delivery.Gateway
	Path    Path
	// Random is where codes come from; nil is crypto/rand.
	Random io.Reader
}

Config is what the Service needs.

type ConnectionLimiter

type ConnectionLimiter struct{}

ConnectionLimiter is the limiter of delivery: the token buckets of rate_limit_buckets, shared by every replica.

func (ConnectionLimiter) ConnectionToken

func (ConnectionLimiter) ConnectionToken(ctx context.Context, d DBTX, orgID, connection int64, now time.Time) (bool,
	time.Time, error)

ConnectionToken takes a token of the Connection connection (delivery.ConnectionToken).

func (ConnectionLimiter) HoldConnection

func (ConnectionLimiter) HoldConnection(ctx context.Context, d DBTX, orgID, connection int64, until time.Time) error

HoldConnection holds the bucket of the Connection connection until until (delivery.HoldConnection).

type Contact

type Contact struct {
	PublicID           string
	ConnectionPublicID string
	ConnectionName     string
	Contact            string
	ConfirmedAt        *time.Time
	Replaces           *string
	CreatedAt          time.Time
}

Contact is a contact at a Notification gateway as the API shows it. ConfirmedAt is nil while it is unconfirmed; Replaces is the confirmed contact of the same person and gateway that it replaces once confirmed.

func (Contact) Confirmed

func (c Contact) Confirmed() bool

Confirmed reports whether the contact is confirmed, and so called.

type DBTX

type DBTX = dbgen.DBTX

DBTX is the pool or transaction the queries run in.

type FieldError

type FieldError struct {
	Pointer           string
	Code              string
	Detail            string
	AttemptsRemaining *int
}

FieldError is a request field that is not valid; Detail never repeats the contact or the code. AttemptsRemaining is set on contact_code_invalid: the codes the contact still takes, 0 once it takes none.

func (*FieldError) Error

func (e *FieldError) Error() string

type Gateway

type Gateway struct {
	ID       int64
	PublicID string
	Name     string
}

Gateway is a Notification gateway: a Bridge Connection, not deleted, whose stored info declares the role gateway.

type Limiter

type Limiter interface {
	ConnectionToken(ctx context.Context, db DBTX, orgID, connection int64, now time.Time) (bool, time.Time, error)
	HoldConnection(ctx context.Context, db DBTX, orgID, connection int64, until time.Time) error
}

Limiter takes the tokens of the limiter of a gateway's Connection, through the transaction db of the call's preparation, and holds it after a RetryAfter (C-11.FR-3, connection.bridge.limiter); delivery's functions implement it.

type PageCall

type PageCall struct {
	UserID       int64
	GatewayID    int64
	AlertGroupID int64
	Stop         StopCheck
	Run          int64
	RuleRun      int64
	Page         int64
}

PageCall is a Page through a Notification gateway: the User called, the gateway's Connection and the Alert Group it is about, by internal id, the StopCheck of the chain or the rule that Paged with the run of the chain and the rule run it names, and the pages row of the Page, 0 for the hook of muster dev.

type PageRecorder

type PageRecorder interface {
	SettleCall(ctx context.Context, tx groups.DBTX, o groups.CallOutcome) (func(context.Context), error)
}

PageRecorder records how a call ended for the Pages that joined it and its Alert Groups through the dispatcher, in the transaction tx of the end of the call (PageReached, PageNotDelivered): an Assignee for an accepted call, page_not_delivered for one Not delivered (C-32.FR-12, C-30.FR-7); *groups.Service implements it.

type Path

type Path interface {
	Do(ctx context.Context, s delivery.Subject, op delivery.Op) (delivery.Outcome, error)
}

Path is the interactive path of delivery (C-11.FR-2); *delivery.Interactive implements it.

type Pool

type Pool interface {
	DBTX
	db.Beginner
}

Pool is the main pool: the queries, and the transactions of a change.

type Prober

type Prober interface {
	ProbeGateway(ctx context.Context, connectionID int64) delivery.Outcome
}

Prober probes the Bridge Connection connectionID of a Broken gateway through info, read afresh in the delivery client class; *connections.Service implements it.

type Pruner

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

Pruner deletes the codes that expired CodePruneAfter ago, for the short_lived_pruning Leader task.

func NewPruner

func NewPruner(d DBTX) Pruner

NewPruner returns the Pruner over d.

func (Pruner) Codes

func (p Pruner) Codes(ctx context.Context, orgID int64, now time.Time, limit int32) (int64, error)

Codes deletes at most limit codes of the Organization that expired CodePruneAfter before now, used and void ones included.

type Queries

type Queries interface {
	ListGateways(ctx context.Context, orgID int64) ([]dbgen.ListGatewaysRow, error)
	GetGateway(ctx context.Context, arg dbgen.GetGatewayParams) (dbgen.GetGatewayRow, error)
	ConfirmedContact(ctx context.Context, arg dbgen.ConfirmedContactParams) (string, error)
	LockContactUser(ctx context.Context, arg dbgen.LockContactUserParams) (dbgen.LockContactUserRow, error)
	GetUserByPublicID(ctx context.Context, arg dbgen.GetUserByPublicIDParams) (dbgen.GetUserByPublicIDRow, error)
	LockContactText(ctx context.Context, arg dbgen.LockContactTextParams) error
	CountUserCodes(ctx context.Context, arg dbgen.CountUserCodesParams) (dbgen.CountUserCodesRow, error)
	CountUserContactCodes(ctx context.Context, arg dbgen.CountUserContactCodesParams) (
		dbgen.CountUserContactCodesRow, error)
	CountContactCodes(ctx context.Context, arg dbgen.CountContactCodesParams) (dbgen.CountContactCodesRow, error)
	ListContactsOfUser(ctx context.Context, arg dbgen.ListContactsOfUserParams) ([]dbgen.ListContactsOfUserRow, error)
	LockContactOfUser(ctx context.Context, arg dbgen.LockContactOfUserParams) (dbgen.LockContactOfUserRow, error)
	InsertContact(ctx context.Context, arg dbgen.InsertContactParams) (int64, error)
	DeleteContact(ctx context.Context, arg dbgen.DeleteContactParams) (int64, error)
	DeleteUnconfirmedContacts(ctx context.Context, arg dbgen.DeleteUnconfirmedContactsParams) (
		[]dbgen.DeleteUnconfirmedContactsRow, error)
	DeleteReplacedContacts(ctx context.Context, arg dbgen.DeleteReplacedContactsParams) (
		[]dbgen.DeleteReplacedContactsRow, error)
	ConfirmContact(ctx context.Context, arg dbgen.ConfirmContactParams) error
	DeleteUserContacts(ctx context.Context, arg dbgen.DeleteUserContactsParams) ([]dbgen.DeleteUserContactsRow, error)
	DeleteUserCodes(ctx context.Context, arg dbgen.DeleteUserCodesParams) (int64, error)
	MarkCodeSent(ctx context.Context, arg dbgen.MarkCodeSentParams) error
	VoidEarlierCodes(ctx context.Context, arg dbgen.VoidEarlierCodesParams) (int64, error)
	InsertCode(ctx context.Context, arg dbgen.InsertCodeParams) (int64, error)
	VoidCode(ctx context.Context, arg dbgen.VoidCodeParams) error
	DeleteCode(ctx context.Context, arg dbgen.DeleteCodeParams) error
	LockNewestCode(ctx context.Context, arg dbgen.LockNewestCodeParams) (dbgen.LockNewestCodeRow, error)
	RecordWrongCode(ctx context.Context, arg dbgen.RecordWrongCodeParams) (int64, error)
	UseCode(ctx context.Context, arg dbgen.UseCodeParams) (int64, error)
	audit.Store
}

Queries are the queries of the package, with the insert of the Audit log.

type RateLimitedError

type RateLimitedError struct {
	RetryAfter time.Duration
}

RateLimitedError refuses a code request beyond gateway.contact_code_requests until RetryAfter passed.

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

func (*RateLimitedError) Seconds

func (e *RateLimitedError) Seconds() int

Seconds is the wait in whole seconds, rounded up, at least 1, for Retry-After.

type RefusedError

type RefusedError struct {
	Class string
}

RefusedError is a notification with a code that the gateway refused: Class is how, as the Bridge protocol classifies it. It never carries the gateway's answer, which may repeat the contact and the code.

func (*RefusedError) Error

func (e *RefusedError) Error() string

type Requester

type Requester struct {
	UserID       int64
	UserPublicID string
	SessionID    int64
	Actor        audit.Actor
	Transport    audit.Transport
	Address      netip.Addr
}

Requester is who asks through the API: the User whose own contacts change, with the web session a code is tied to, or the Admin who removes a contact; the actor, the Transport and the client address of the Audit log entry.

type Sender

type Sender struct {
	OrgID int64
	Store CallStore
	// Lease names this replica in lease_owner and carries the clocks: due times, the combine window and the limiter
	// on the business clock, leases on the real clock.
	Lease db.Lease
	// Gateway sends the notifications: *bridge.Adapter.
	Gateway delivery.Gateway
	// Limiter is the limiter of the gateways' Connections; nil is ConnectionLimiter.
	Limiter Limiter
	// Keys sign the action data of calls with the button-signature key: the Keyring.
	Keys  buttons.Keys
	Pages PageRecorder
	// Broken keeps the Broken state of the gateways (broken.go): a Fatal answer or a used budget makes a gateway
	// Broken, and each round probes the Broken gateways that are due; nil leaves the state alone.
	Broken *Broken
	Log    *logging.Logger
	// Random is uniform in [0, 1) and jitters delivery.transient_backoff; nil is math/rand/v2.
	Random func() float64
	// MaxWait bounds the wait between rounds, Batch the calls one claim takes, and Concurrency the calls a round
	// attempts at once; zero is the default.
	MaxWait     time.Duration
	Batch       int32
	Concurrency int
	// Wait waits for d or until a wake arrives; nil waits on the real clock.
	Wait func(ctx context.Context, d time.Duration, wake <-chan struct{})
	// contains filtered or unexported fields
}

Sender is the gateway sender of one replica for the Organization OrgID.

func (*Sender) Round

func (s *Sender) Round(ctx context.Context) (time.Duration, error)

Round attempts every due call, Batch at a time and up to Concurrency at once (attemptDue), then probes the Broken gateways that are due, and returns how long until the next call or probe can be claimed, at most MaxWait. A call that fails is logged and attempted again once its lease runs out; the round goes on. It returns once every attempt it started has ended, also when ctx ends.

func (*Sender) Run

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

Run sends calls until ctx ends: a round, then a wait until the next call can be claimed, between SenderMinWait and MaxWait, or until woken; after a failed round, such as one without the database, a backoff, as the delivery worker does.

func (*Sender) Wake

func (s *Sender) Wake()

Wake makes the sender run a round at once: a Page was queued, the development clock moved, or the LISTEN is back.

type Service

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

Service holds the Notification gateways of an Organization and the contacts of people at them.

func New

func New(cfg Config) *Service

New returns the Service of cfg.

func (*Service) Confirm

func (s *Service) Confirm(ctx context.Context, r Requester, contactPublicID, code string) (Contact, error)

Confirm confirms the contact contactPublicID of the requesting User with code (C-30.FR-3, AC-2). Under the lock of the User and of the contact's newest code: a code that is used or void, whose web session ended, that expired, or that the contact lacks, and a wrong code or one asked for in another web session — both of which count an attempt, the one that reaches gateway.contact_code's limit voiding the code — are a FieldError contact_code_invalid at /code, never saying which, with the attempts left, logged as gateway_contact_code_rejected. A right code from the session that asked for it is used, compared in constant time, and confirms the contact: the User's earlier confirmed contact at the gateway is deleted, recorded as gateway_contact.deleted with the reason replaced, and the confirmation is recorded as gateway_contact.confirmed, in one transaction. A contact that is already confirmed stays as it is. A contact of another User is ErrNotFound. It calls no gateway.

func (*Service) ConfirmedContact

func (s *Service) ConfirmedContact(ctx context.Context, userID, gatewayID int64) (contact string, ok bool, err error)

ConfirmedContact is the confirmed contact of the User userID at the Notification gateway gatewayID, the one a call goes to; ok is false without one, or when the gateway is deleted or no longer a Notification gateway. An unconfirmed contact is never called (C-30.FR-3).

func (*Service) Create

func (s *Service) Create(ctx context.Context, r Requester, connectionPublicID, contact string) (Contact, error)

Create adds an unconfirmed contact of the requesting User at the Notification gateway connectionPublicID and sends it a code (C-30.FR-3). The contact is trimmed and must be 1 to MaxContactLength characters without control characters (FieldError invalid_format at /contact); a Connection that is not a Notification gateway is a FieldError unknown_id at /connection_id. In one transaction, under the lock of the User: the limits of gateway.contact_code_requests (RateLimitedError), the replacement of the User's earlier unconfirmed contact at the gateway, recorded as gateway_contact.deleted with the reason replaced, the contact, recorded as gateway_contact.created, and its code. Then the code goes out as SendCode sends it, or is withheld as SendCode withholds it; a failure there leaves the contact, unconfirmed, and is returned as SendCode returns it.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, r Requester, contactPublicID string) error

Delete removes the contact contactPublicID of the requesting User, from the web session.

func (*Service) DeleteOfUser

func (s *Service) DeleteOfUser(ctx context.Context, r Requester, userPublicID, contactPublicID string) error

DeleteOfUser removes the contact contactPublicID of the User userPublicID, for an Admin (C-18.FR-6 revised).

func (*Service) Gateways

func (s *Service) Gateways(ctx context.Context) ([]Gateway, error)

Gateways lists the Notification gateways of the Organization by name (C-30.FR-1, FR-9).

func (*Service) List

func (s *Service) List(ctx context.Context, userID int64) ([]Contact, error)

List lists the contacts of the User userID, by gateway and creation.

func (*Service) ListOfUser

func (s *Service) ListOfUser(ctx context.Context, userPublicID string) ([]Contact, error)

ListOfUser lists the contacts of the User userPublicID, for an Admin; an unknown User is ErrUserNotFound, and a deleted one has none.

func (*Service) RemoveUserContacts

func (s *Service) RemoveUserContacts(ctx context.Context, tx usersdb.DBTX, userID int64, actor audit.Actor,
	t audit.Transport, addr netip.Addr) (func(context.Context), error)

RemoveUserContacts deletes the contacts and codes of the User userID in the transaction tx of their deletion (C-03.FR-13 revised for L2), each contact recorded as gateway_contact.deleted with the reason user_deleted by actor. It returns nothing to run after the commit: nothing is logged.

func (*Service) SendCode

func (s *Service) SendCode(ctx context.Context, r Requester, contactPublicID string) (Contact, error)

SendCode sends a new code of gateway.contact_code for the contact contactPublicID of the requesting User through its gateway (C-30.FR-3): in one transaction, under the lock of the User, the limits of gateway.contact_code_requests (RateLimitedError), the earlier codes of the contact voided and the new one stored, its SHA-256 only, tied to the requesting web session; then, on the interactive path, sendNotification with the key of the code, the text "Your Muster code: …" in the User's language and no action, the code masked in the Request log. No limiter token within the budget is a *delivery.LimitedError and deletes the code, which was never sent; a refusal of the gateway is a *RefusedError and any other failure an error, both of which void the code, which still counts. A request beyond the codes the contact text receives across Users is answered as if its code were sent: a code that no one knows is stored and marked sent in the transaction, voiding the earlier ones, nothing is sent, and gateway_contact_code_sent says withheld. A contact of another User is ErrNotFound; one whose gateway is no longer a Notification gateway a FieldError unknown_id.

type StopCheck

type StopCheck string

StopCheck says when the chain or the rule that Paged has stopped on an Alert Group (C-30.FR-4): the sender drops such an Alert Group from a call before its first attempt, and ends the retries of a call once every one of its Alert Groups stopped. It is a name rather than a function, as any replica sends the call: the item of the Alert Group keeps the run and the rule run it names, and the sender reads them (ListCallGroups). Every stop check includes StopNotFiring.

const (
	StopNotFiring StopCheck = "not_firing"
	StopChainRun  StopCheck = "chain_run"
	StopRuleRun   StopCheck = "rule_run"
)

The stop checks: the Alert Group is no longer firing — acknowledged, snoozed or resolved —, for the hook of muster dev; or also the run of the chain of a call step stopped or is of an earlier start of its chains, as after a start-over (StopChainRun, PageCall.Run); or also the rule run of a call action stopped (StopRuleRun, PageCall.Run and PageCall.RuleRun). A run that ran out has not stopped: a call step that is the last step of its chain still calls.

type Store

type Store interface {
	Queries
	InTx(ctx context.Context, f func(Queries) error) error
}

Store runs the queries alone or in one transaction.

func NewStore

func NewStore(p Pool) Store

NewStore is the Store over the main pool.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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