// Code generated by sqlc. DO NOT EDIT. // versions: // sqlc v1.31.1 // source: alerts_send.sql package db import ( "context" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgtype" ) const beginAlertPass = `-- name: BeginAlertPass :exec INSERT INTO alert_passes (pass_id) VALUES ($1) ON CONFLICT DO NOTHING ` func (q *Queries) BeginAlertPass(ctx context.Context, passID uuid.UUID) error { _, err := q.db.Exec(ctx, beginAlertPass, passID) return err } const bumpAlertEmailAttempts = `-- name: BumpAlertEmailAttempts :exec UPDATE alert_outbox SET email_attempts = email_attempts + 1, email_next_attempt_at = GREATEST($1::timestamptz + interval '1 minute' * power(2, email_attempts), $2::timestamptz), email_done_at = CASE WHEN email_attempts + 1 >= $3::int THEN $1 ELSE email_done_at END WHERE id = ANY($4::bigint[]) AND email_done_at IS NULL ` type BumpAlertEmailAttemptsParams struct { At pgtype.Timestamptz `json:"at"` HoldUntil pgtype.Timestamptz `json:"hold_until"` MaxAttempts int32 `json:"max_attempts"` Ids []int64 `json:"ids"` } // Counts a failed mail and holds it back for a minute, doubling with each earlier failure; the last allowed failure // ends the channel. func (q *Queries) BumpAlertEmailAttempts(ctx context.Context, arg BumpAlertEmailAttemptsParams) error { _, err := q.db.Exec(ctx, bumpAlertEmailAttempts, arg.At, arg.HoldUntil, arg.MaxAttempts, arg.Ids, ) return err } const bumpAlertPushAttempts = `-- name: BumpAlertPushAttempts :exec UPDATE alert_outbox SET push_attempts = push_attempts + 1, push_next_attempt_at = GREATEST($1::timestamptz + interval '1 minute' * power(2, push_attempts), $2::timestamptz), push_done_at = CASE WHEN push_attempts + 1 >= $3::int THEN $1 ELSE push_done_at END WHERE id = ANY($4::bigint[]) AND push_done_at IS NULL ` type BumpAlertPushAttemptsParams struct { At pgtype.Timestamptz `json:"at"` HoldUntil pgtype.Timestamptz `json:"hold_until"` MaxAttempts int32 `json:"max_attempts"` Ids []int64 `json:"ids"` } // As for mail, or held until hold_until when the push server asked for longer. func (q *Queries) BumpAlertPushAttempts(ctx context.Context, arg BumpAlertPushAttemptsParams) error { _, err := q.db.Exec(ctx, bumpAlertPushAttempts, arg.At, arg.HoldUntil, arg.MaxAttempts, arg.Ids, ) return err } const deleteDevicesByToken = `-- name: DeleteDevicesByToken :exec DELETE FROM user_devices WHERE push_token = $1 ` func (q *Queries) DeleteDevicesByToken(ctx context.Context, pushToken string) error { _, err := q.db.Exec(ctx, deleteDevicesByToken, pushToken) return err } const deleteExhaustedAlerts = `-- name: DeleteExhaustedAlerts :execrows DELETE FROM alert_outbox WHERE id = ANY($1::bigint[]) AND delivered_at IS NULL AND email_done_at IS NOT NULL AND push_done_at IS NOT NULL AND (email_attempts >= $2::int OR push_attempts >= $2::int) ` type DeleteExhaustedAlertsParams struct { Ids []int64 `json:"ids"` MaxAttempts int32 `json:"max_attempts"` } // A finished notice that ran out of attempts on a channel is dropped. func (q *Queries) DeleteExhaustedAlerts(ctx context.Context, arg DeleteExhaustedAlertsParams) (int64, error) { result, err := q.db.Exec(ctx, deleteExhaustedAlerts, arg.Ids, arg.MaxAttempts) if err != nil { return 0, err } return result.RowsAffected(), nil } const deleteOldAlertPasses = `-- name: DeleteOldAlertPasses :exec DELETE FROM alert_passes WHERE started_at < $1 ` func (q *Queries) DeleteOldAlertPasses(ctx context.Context, startedAt pgtype.Timestamptz) error { _, err := q.db.Exec(ctx, deleteOldAlertPasses, startedAt) return err } const deliveredAlertDevices = `-- name: DeliveredAlertDevices :many SELECT outbox_id, session_id FROM alert_outbox_devices WHERE outbox_id = ANY($1::bigint[]) ` type DeliveredAlertDevicesRow struct { OutboxID int64 `json:"outbox_id"` SessionID uuid.UUID `json:"session_id"` } func (q *Queries) DeliveredAlertDevices(ctx context.Context, ids []int64) ([]DeliveredAlertDevicesRow, error) { rows, err := q.db.Query(ctx, deliveredAlertDevices, ids) if err != nil { return nil, err } defer rows.Close() items := []DeliveredAlertDevicesRow{} for rows.Next() { var i DeliveredAlertDevicesRow if err := rows.Scan(&i.OutboxID, &i.SessionID); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const expireAlertOutbox = `-- name: ExpireAlertOutbox :execrows DELETE FROM alert_outbox WHERE (delivered_at IS NULL AND created_at < $1) OR (delivered_at IS NOT NULL AND delivered_at < $2) ` type ExpireAlertOutboxParams struct { UndeliveredBefore pgtype.Timestamptz `json:"undelivered_before"` DeliveredBefore pgtype.Timestamptz `json:"delivered_before"` } // Drops what was not delivered within its window, and what was delivered long ago. func (q *Queries) ExpireAlertOutbox(ctx context.Context, arg ExpireAlertOutboxParams) (int64, error) { result, err := q.db.Exec(ctx, expireAlertOutbox, arg.UndeliveredBefore, arg.DeliveredBefore) if err != nil { return 0, err } return result.RowsAffected(), nil } const finishAlertPass = `-- name: FinishAlertPass :exec UPDATE alert_passes SET finished_at = now() WHERE pass_id = $1 ` func (q *Queries) FinishAlertPass(ctx context.Context, passID uuid.UUID) error { _, err := q.db.Exec(ctx, finishAlertPass, passID) return err } const holdAlertPush = `-- name: HoldAlertPush :exec UPDATE alert_outbox SET push_next_attempt_at = $1::timestamptz WHERE id = ANY($2::bigint[]) AND push_done_at IS NULL ` type HoldAlertPushParams struct { HoldUntil pgtype.Timestamptz `json:"hold_until"` Ids []int64 `json:"ids"` } // A rate-limited push waits until hold_until; no attempt is counted. func (q *Queries) HoldAlertPush(ctx context.Context, arg HoldAlertPushParams) error { _, err := q.db.Exec(ctx, holdAlertPush, arg.HoldUntil, arg.Ids) return err } const liveUserDevices = `-- name: LiveUserDevices :many SELECT d.session_id, d.user_id, d.platform, d.push_token, d.payload_key FROM user_devices d JOIN user_sessions s ON s.id = d.session_id WHERE d.user_id = ANY($1::uuid[]) AND s.ended_at IS NULL AND s.expires_at > now() AND (s.hard_expires_at IS NULL OR s.hard_expires_at > now()) ` type LiveUserDevicesRow struct { SessionID uuid.UUID `json:"session_id"` UserID uuid.UUID `json:"user_id"` Platform string `json:"platform"` PushToken string `json:"push_token"` PayloadKey []byte `json:"payload_key"` } func (q *Queries) LiveUserDevices(ctx context.Context, userIds []uuid.UUID) ([]LiveUserDevicesRow, error) { rows, err := q.db.Query(ctx, liveUserDevices, userIds) if err != nil { return nil, err } defer rows.Close() items := []LiveUserDevicesRow{} for rows.Next() { var i LiveUserDevicesRow if err := rows.Scan( &i.SessionID, &i.UserID, &i.Platform, &i.PushToken, &i.PayloadKey, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil } const markAlertDeviceDelivered = `-- name: MarkAlertDeviceDelivered :exec INSERT INTO alert_outbox_devices (outbox_id, session_id, delivered_at) VALUES ($1, $2, $3) ON CONFLICT (outbox_id, session_id) DO NOTHING ` type MarkAlertDeviceDeliveredParams struct { OutboxID int64 `json:"outbox_id"` SessionID uuid.UUID `json:"session_id"` DeliveredAt pgtype.Timestamptz `json:"delivered_at"` } func (q *Queries) MarkAlertDeviceDelivered(ctx context.Context, arg MarkAlertDeviceDeliveredParams) error { _, err := q.db.Exec(ctx, markAlertDeviceDelivered, arg.OutboxID, arg.SessionID, arg.DeliveredAt) return err } const markAlertsDelivered = `-- name: MarkAlertsDelivered :exec UPDATE alert_outbox SET delivered_at = $1 WHERE id = ANY($2::bigint[]) AND delivered_at IS NULL AND email_done_at IS NOT NULL AND push_done_at IS NOT NULL ` type MarkAlertsDeliveredParams struct { At pgtype.Timestamptz `json:"at"` Ids []int64 `json:"ids"` } // A notice is delivered once both channels are done. func (q *Queries) MarkAlertsDelivered(ctx context.Context, arg MarkAlertsDeliveredParams) error { _, err := q.db.Exec(ctx, markAlertsDelivered, arg.At, arg.Ids) return err } const markAlertsEmailDone = `-- name: MarkAlertsEmailDone :exec UPDATE alert_outbox SET email_done_at = COALESCE(email_done_at, $1), email_sent_at = CASE WHEN $2::boolean THEN COALESCE(email_sent_at, $1) ELSE email_sent_at END WHERE id = ANY($3::bigint[]) ` type MarkAlertsEmailDoneParams struct { At pgtype.Timestamptz `json:"at"` Sent bool `json:"sent"` Ids []int64 `json:"ids"` } // The mail went out (sent_at set) or none was needed. func (q *Queries) MarkAlertsEmailDone(ctx context.Context, arg MarkAlertsEmailDoneParams) error { _, err := q.db.Exec(ctx, markAlertsEmailDone, arg.At, arg.Sent, arg.Ids) return err } const markAlertsPushDone = `-- name: MarkAlertsPushDone :exec UPDATE alert_outbox SET push_done_at = COALESCE(push_done_at, $1) WHERE id = ANY($2::bigint[]) ` type MarkAlertsPushDoneParams struct { At pgtype.Timestamptz `json:"at"` Ids []int64 `json:"ids"` } func (q *Queries) MarkAlertsPushDone(ctx context.Context, arg MarkAlertsPushDoneParams) error { _, err := q.db.Exec(ctx, markAlertsPushDone, arg.At, arg.Ids) return err } const pendingAlerts = `-- name: PendingAlerts :many WITH p AS ( SELECT o.id, o.user_id, o.pass_id, o.target_kind, o.target_public_key, o.name, o.alert_kind, o.value, o.detail, o.push_attempts, u.email, (u.email_verified_at IS NOT NULL)::boolean AS email_verified, u.alert_email, u.alert_push, (o.email_done_at IS NULL AND (o.email_next_attempt_at IS NULL OR o.email_next_attempt_at <= $2))::boolean AS email_due, (o.push_done_at IS NULL AND (o.push_next_attempt_at IS NULL OR o.push_next_attempt_at <= $2))::boolean AS push_due, COALESCE(CASE WHEN o.target_kind = 'observer' THEN ob.id ELSE n.id END, '00000000-0000-0000-0000-000000000000'::uuid)::uuid AS target_id FROM alert_outbox o JOIN users u ON u.id = o.user_id AND u.disabled_at IS NULL LEFT JOIN nodes n ON o.target_kind = 'node' AND n.public_key = o.target_public_key LEFT JOIN observers ob ON o.target_kind = 'observer' AND ob.public_key = o.target_public_key LEFT JOIN alert_passes ap ON ap.pass_id = o.pass_id WHERE (ap.pass_id IS NULL OR ap.finished_at IS NOT NULL OR ap.started_at < $3) AND o.delivered_at IS NULL AND o.created_at >= $4 AND ((o.email_done_at IS NULL AND (o.email_next_attempt_at IS NULL OR o.email_next_attempt_at <= $2)) OR (o.push_done_at IS NULL AND (o.push_next_attempt_at IS NULL OR o.push_next_attempt_at <= $2))) ), g AS ( SELECT user_id, pass_id, count(*) AS n, sum(count(*)) OVER (ORDER BY user_id, pass_id) AS running FROM p GROUP BY user_id, pass_id ) SELECT p.id, p.user_id, p.pass_id, p.target_kind, p.target_public_key, p.name, p.alert_kind, p.value, p.detail, p.push_attempts, p.email, p.email_verified, p.alert_email, p.alert_push, p.email_due, p.push_due, p.target_id FROM p JOIN g ON g.user_id = p.user_id AND g.pass_id = p.pass_id WHERE g.running <= $1::bigint OR g.running = g.n ORDER BY p.user_id, p.pass_id, p.id ` type PendingAlertsParams struct { RowLimit int64 `json:"row_limit"` Now pgtype.Timestamptz `json:"now"` PassTimeoutBefore pgtype.Timestamptz `json:"pass_timeout_before"` NotBefore pgtype.Timestamptz `json:"not_before"` } type PendingAlertsRow struct { ID int64 `json:"id"` UserID uuid.UUID `json:"user_id"` PassID uuid.UUID `json:"pass_id"` TargetKind string `json:"target_kind"` TargetPublicKey []byte `json:"target_public_key"` Name string `json:"name"` AlertKind string `json:"alert_kind"` Value *int64 `json:"value"` Detail string `json:"detail"` PushAttempts int16 `json:"push_attempts"` Email string `json:"email"` EmailVerified bool `json:"email_verified"` AlertEmail bool `json:"alert_email"` AlertPush bool `json:"alert_push"` EmailDue bool `json:"email_due"` PushDue bool `json:"push_due"` TargetID uuid.UUID `json:"target_id"` } // Notices of a finished pass (or one that started before pass_timeout_before and never finished) only, with a channel // that is not done and is due, and whole user and pass groups only, so one pass's notices for a user stay in one mail: // groups are taken in order while the running total stays within row_limit, and the first group is taken whatever // its size. email_due and push_due say which channels to try. func (q *Queries) PendingAlerts(ctx context.Context, arg PendingAlertsParams) ([]PendingAlertsRow, error) { rows, err := q.db.Query(ctx, pendingAlerts, arg.RowLimit, arg.Now, arg.PassTimeoutBefore, arg.NotBefore, ) if err != nil { return nil, err } defer rows.Close() items := []PendingAlertsRow{} for rows.Next() { var i PendingAlertsRow if err := rows.Scan( &i.ID, &i.UserID, &i.PassID, &i.TargetKind, &i.TargetPublicKey, &i.Name, &i.AlertKind, &i.Value, &i.Detail, &i.PushAttempts, &i.Email, &i.EmailVerified, &i.AlertEmail, &i.AlertPush, &i.EmailDue, &i.PushDue, &i.TargetID, ); err != nil { return nil, err } items = append(items, i) } if err := rows.Err(); err != nil { return nil, err } return items, nil }