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
- Variables
- type AckQueries
- type Acknowledgements
- type Acknowledger
- type Broken
- func (b *Broken) Break(ctx context.Context, g brokenGateway, cause, reason string) error
- func (b *Broken) Deleted(ctx context.Context, tx DBTX, connectionID int64) error
- func (b *Broken) EndBroken(ctx context.Context, connectionID int64) error
- func (b *Broken) Export(ctx context.Context) error
- func (b *Broken) Next(ctx context.Context) (time.Duration, bool, error)
- func (b *Broken) Probe(ctx context.Context) error
- func (b *Broken) Reconcile(ctx context.Context) error
- func (b *Broken) Renamed(ctx context.Context, tx DBTX, publicID, name string) error
- func (b *Broken) Wait()
- type BrokenQueries
- type BrokenStore
- type CallPruner
- type CallQueries
- type CallStore
- type CallTarget
- type Calls
- func (c *Calls) DevPage(ctx context.Context, store CallStore, userPublicID, gatewayPublicID string, ...) error
- func (c *Calls) Page(ctx context.Context, tx DBTX, p PageCall) (func(context.Context), error)
- func (c *Calls) Queue(ctx context.Context, tx DBTX, p PageCall) (int64, func(context.Context), error)
- func (c *Calls) Target(ctx context.Context, tx DBTX, gatewayID int64, gatewayPublicID string, ...) (CallTarget, error)
- type CodeKeys
- type Config
- type ConnectionLimiter
- type Contact
- type DBTX
- type FieldError
- type Gateway
- type Limiter
- type PageCall
- type PageRecorder
- type Path
- type Pool
- type Prober
- type Pruner
- type Queries
- type RateLimitedError
- type RefusedError
- type Requester
- type Sender
- type Service
- func (s *Service) Confirm(ctx context.Context, r Requester, contactPublicID, code string) (Contact, error)
- func (s *Service) ConfirmedContact(ctx context.Context, userID, gatewayID int64) (contact string, ok bool, err error)
- func (s *Service) Create(ctx context.Context, r Requester, connectionPublicID, contact string) (Contact, error)
- func (s *Service) Delete(ctx context.Context, r Requester, contactPublicID string) error
- func (s *Service) DeleteOfUser(ctx context.Context, r Requester, userPublicID, contactPublicID string) error
- func (s *Service) Gateways(ctx context.Context) ([]Gateway, error)
- func (s *Service) List(ctx context.Context, userID int64) ([]Contact, error)
- func (s *Service) ListOfUser(ctx context.Context, userPublicID string) ([]Contact, error)
- func (s *Service) RemoveUserContacts(ctx context.Context, tx usersdb.DBTX, userID int64, actor audit.Actor, ...) (func(context.Context), error)
- func (s *Service) SendCode(ctx context.Context, r Requester, contactPublicID string) (Contact, error)
- type StopCheck
- type Store
Constants ¶
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.
const ( CallWaiting = "waiting" CallSending = "sending" CallAccepted = "accepted" CallNotDelivered = "not_delivered" CallDropped = "dropped" )
The states of a call.
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).
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.
const ( ReasonReplaced = "replaced" ReasonUserDeleted = "user_deleted" )
The reasons of gateway_contact.deleted that its person or an Admin did not ask for.
const ( ReasonWrongCode = "wrong_code" ReasonOtherSession = "other_session" ReasonUsed = "used" ReasonVoid = "void" ReasonExpired = "expired" ReasonNoCode = "no_code" )
The reasons of gateway_contact_code_rejected.
const ( OutcomeOK = "ok" OutcomeLimited = "limited" OutcomeError = "error" OutcomeWithheld = "withheld" )
The outcomes of gateway_contact_code_sent besides the error classes of the Bridge protocol.
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.
const ( CodeUnknownID = "unknown_id" CodeInvalidFormat = "invalid_format" CodeContactCodeInvalid = "contact_code_invalid" )
The codes of the field errors.
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.
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.
const BrokenProbeInterval = delivery.BrokenProbeInterval
BrokenProbeInterval is delivery.broken_probe_interval: how often a Broken gateway is probed through info.
const CallRetentionBatch = 5000
CallRetentionBatch is the most calls one delete of their retention removes.
const CallsChannel = "muster_gateway_calls"
CallsChannel is the LISTEN/NOTIFY channel that wakes the gateway senders of every replica when a Page is queued.
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.
const MaxCallText = bridge.MaxNotificationText
MaxCallText is the longest text of a call: the bridge client cuts a notification's text there (api/bridge.yaml).
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.
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 ¶
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") )
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
type BrokenQueries ¶
type BrokenQueries interface {
BreakGateway(ctx context.Context, arg dbgen.BreakGatewayParams) (dbgen.BreakGatewayRow, error)
UpdateGatewayBrokenReason(ctx context.Context, arg dbgen.UpdateGatewayBrokenReasonParams) (int64, error)
EndGatewayBroken(ctx context.Context, arg dbgen.EndGatewayBrokenParams) (dbgen.EndGatewayBrokenRow, error)
ClaimGatewayProbes(ctx context.Context, arg dbgen.ClaimGatewayProbesParams) ([]dbgen.ClaimGatewayProbesRow,
error)
FailGatewayProbe(ctx context.Context, arg dbgen.FailGatewayProbeParams) (int64, error)
NextGatewayProbe(ctx context.Context, arg dbgen.NextGatewayProbeParams) (dbgen.NextGatewayProbeRow, error)
ListGatewayHealth(ctx context.Context, orgID int64) ([]dbgen.ListGatewayHealthRow, error)
ListUnmarkedFailures(ctx context.Context, arg dbgen.ListUnmarkedFailuresParams) ([]dbgen.ListUnmarkedFailuresRow,
error)
LockGatewayState(ctx context.Context, arg dbgen.LockGatewayStateParams) error
GetGatewayState(ctx context.Context, arg dbgen.GetGatewayStateParams) (dbgen.GetGatewayStateRow, error)
Notify(ctx context.Context, h db.Hint) error
internalalerts.Store
}
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 ¶
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 ¶
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 ¶
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 ¶
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.
type FieldError ¶
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 ¶
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 Prober ¶
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.
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 ¶
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 ¶
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.
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 (*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 ¶
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 ¶
Gateways lists the Notification gateways of the Organization by name (C-30.FR-1, FR-9).
func (*Service) ListOfUser ¶
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.