mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-11-11 11:57:57 +00:00
Observers publish to the broker with one shared MQTT login. Anyone who
has that login can publish under any observer's topic, and the ingestor
takes the observer id from the topic (`cmd/ingestor/main.go:1009`), so
the data in the analyzer DB is only as trustworthy as the shared
password. This PR gives each user a personal MQTT login, generated and
mailed by CoreScope, and lets the broker ask CoreScope whether a login
may connect and publish.
Closes #2319.
The feature is optional and off by default
(`userManagement.observerLogins.enabled`). It needs
`userManagement.enabled`. With it off, nothing changes.
## Changes in this PR
**Broker hooks.** `POST /api/mqtt-hook/emqx/authn` and `/authz`, for the
EMQX HTTP authenticator and authorizer.
- They check a shared secret header, `X-CoreScope-Hook-Secret`, in
constant time.
- A username CoreScope does not know gets `ignore`, so EMQX falls
through to its built-in database and existing users keep working.
- A personal login may only publish `meshcore/<iata>/<pubkey>/<type>`,
with a 64-hex pubkey that is unbound or bound to the same user.
- The first publish for an unbound pubkey binds that observer to the
user (first come wins), until the user owns 20 observers (admin
assignments count too).
- An admin can rebind any observer.
**Credentials.**
- Username `obs_` + 12 random `[a-z0-9]`, password 32 random
`[A-Za-z0-9]`, both from `crypto/rand`.
- The password is stored twice: SHA-256 for the auth check, and sealed
with AES-256-GCM (key from config or `CORESCOPE_OBSERVER_KEY`) so the
user can ask for the same credentials again.
- The UI and the API never show the password. It leaves the server only
in the mail.
**Mail.** One mail with four formats:
- the meshcoretomqtt TOML;
- the observer firmware CLI commands (Gessaman or Dutch-MeshCore, same
`mqttN` CLI), on slot 4: slots 1-2 (Gessaman, Let's Mesh US/EU) and 1-3
(Dutch-MeshCore, `MQTTDefaults.h:19-34`) hold default broker presets on
a fresh install, slot 4 is empty on both. `set mqtt4.server` gets the
bare host: the firmware picks the scheme from the port
(`MQTTBridge.cpp:2094-2145`), and builds before merge 32dd8ad
(2026-10-19) do not accept a scheme there (read from the source, not
tested on a device). A scheme is written only when the port would pick
the wrong one, for example TLS on 8884;
- the Home Assistant meshcore-ha broker form fields;
- the plain values.
Each block starts with a numbered title and one line on where it goes.
The account page can resend the mail, at most 3 times per 24 h.
**Account and admin UI.**
- The account page gets an "Observer MQTT login" section
(`#/account?section=observers`) with the username, the bound observers
and the resend button.
- The admin page gets an "Observer logins" tab
(`#/admin?tab=observer-logins`) that lists logins with revoke and
reissue, and every observer with its owner, "not migrated" or
"orphaned", with a reassign control.
**Notifications.** Creating a login adds `observer.offline.own` ("My
observers go offline") to the owner's notification events; mails go out
once the user has notifications switched on, and the user can untick it.
**Storage.** users.db schema v7 adds `mqtt_logins` and
`observer_bindings`. The server still writes only users.db through
`internal/users`, and the analyzer DB stays read-only.
**Docs.** `docs/observer-mqtt-logins.md` covers the EMQX setup (authn
and authz chains, the hook body templates, the closing `^obs_` deny rule
and why it is needed), how to enable it on a running EMQX through the
REST API step by step, with a check and a rollback per step, and how to
migrate observers off a shared login. `config.example.json` has the
block with placeholder values.
## Enabling it on an instance
Full steps in `docs/observer-mqtt-logins.md`. In short:
1. **CoreScope:** add `userManagement.observerLogins` to `config.json`
with `enabled: true`, a `hookSecret` (`openssl rand -hex 32`), an
`encryptionKey` (`openssl rand -base64 32`) and the `broker` host, port,
transport and TLS that observers should use. Restart. Keep the key safe:
without it, mails cannot be resent and logins must be reissued.
2. **EMQX, authorization:** add a file source with `{deny, {username,
{re, "^obs_"}}, all, ["#"]}.` and move it to the end, then add the HTTP
authorizer pointing at `/api/mqtt-hook/emqx/authz` (it lands at the
front).
3. **EMQX, authentication:** add the HTTP authenticator pointing at
`/api/mqtt-hook/emqx/authn` and move it to the front, before the
built-in database.
4. **Check:** the shared login still connects, an unknown `obs_` login
is refused, and `metrics.deny` on the authorizer stays 0 for existing
clients.
5. **Owners:** they request a login on their account page and paste the
block for their uploader. Each observer binds to them on its first
publish. An uploader that was refused before step 3 may need a restart.
6. **Later:** remove the shared login from the broker once enough
observers moved.
## Who can claim an observer
Any active account can request a login, and its first publish under an
unbound pubkey binds that observer, also when CoreScope already knew it
from the shared login (first come wins, a deliberate choice: owners
migrate without waiting for an admin). Observer pubkeys are public, and
registration cannot be closed, so with this feature on anyone with a
mail address can claim up to 20 unbound observers per account. Before,
publishing needed the shared password.
What limits it: each claim of a known observer mails the admins, an
admin can unbind or reassign it and revoke the login, and a bound
observer cannot be claimed by another login. The doc spells this out and
suggests assigning known observers to their owners before announcing the
feature. A stricter mode (admin approval of logins, or no auto-bind for
known observers) is not in this PR.
## Performance
`authorize()` runs for every publish that misses the EMQX authz cache.
It takes two short read locks, does map lookups and one topic split.
`BenchmarkAuthorizeBound` (2000 observers, 500 logins): 533.5 ns/op, 96
B/op, 2 allocs/op. The admin observers table renders once per load and
updates single rows after a change.
## Verification
- All 16 Go modules: `bash scripts/allmod.sh test ./...` green.
- Skipped `TestSaveGeoFilterPreservesFileMode` and
`TestWriteStatsAtomic_SymlinkAtDestIsReplaced`: both fail on Windows on
a clean master too.
- `sh test-all.sh` green.
- `tests/e2e/test-user-management-e2e.js` 36/36 locally. It covers:
request, mail, resend, revoke, reissue, reassign, no password in the
page or API body, and axe. The CI job for this suite gets the
`observerLogins` block with fake values in `deploy.yml`.
- Local EMQX 5.8.6 in Docker against a local CoreScope:
- a personal login connects and publishes, which binds the observer; a
second personal login is denied on that observer's topic, and subscribe
is denied;
- with CoreScope stopped, the built-in users still connect and publish,
and new personal-login connects are refused;
- the `^obs_` deny rule blocks an already-connected personal login while
CoreScope is down; without the rule, the same publish was delivered.
- Production: running on an EMQX 5.8.9 broker with about 50 clients
since 2026-10-25, set up through the REST API as in the doc. After the
hooks went in, the authorizer answered `ignore` for every existing login
(0 denies, 0 dropped messages), and 4 observers were bound to their
owners through personal logins on the same evening, with the shared
login still in use by the rest.
## Known behaviour
EMQX's HTTP client can mark the hook resource down for one health-check
interval (15 s measured) when CoreScope closes an idle keep-alive
connection just as a health check runs. During that window new
personal-login connects are refused and the uploader reconnects. I saw
it 3 times in about 25 minutes of runs with a forced 1-5 s idle timeout,
and could not trigger it on demand. EMQX 5.8.6 has no setting for it,
and 5.10.5 ships the same client code. The doc describes it and the
alarm to watch for.
## Not in this PR
- mosquitto (mosquitto-go-auth). EMQX only.
- A websocket path field: the mail does not carry one, the doc tells
operators to match the listener path.
- Disabling the shared login. That is an operator step after migration,
described in the doc.
- Tested on EMQX 5.8.6 (Docker) and 5.8.9 (production) only.
Note on cb9f4ff3: its message says the scheme problem was reported by an
operator. That report turned out to come from before the broker used the
hook, so it does not show this cause; the change rests on the firmware
source only.
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
474 lines
14 KiB
Go
474 lines
14 KiB
Go
package users
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Node notifications (docs/specs/2026-10-07-node-notifications-design.md):
|
|
// per-user preferences, the watch list, and the last state per (user, event,
|
|
// subject) that the server's evaluator compares against.
|
|
|
|
// Event types.
|
|
const (
|
|
NotifyNodeOffline = "node.offline"
|
|
NotifyNodeBattery = "node.battery"
|
|
NotifyNodeExternal = "node.external" // off by default; needs notifications.externalAlerts
|
|
NotifyForeignNew = "foreign.new" // admins only
|
|
NotifyObserverOffline = "observer.offline" // admins only
|
|
// NotifyObserverOfflineOwn: offline/online mails for the observers bound
|
|
// to the user's own MQTT login. Open to every role, off by default.
|
|
NotifyObserverOfflineOwn = "observer.offline.own"
|
|
)
|
|
|
|
// Subject states.
|
|
const (
|
|
NotifyGood = "good"
|
|
NotifyBad = "bad"
|
|
NotifyTold = "told" // foreign.new: the admin was told about this node
|
|
)
|
|
|
|
// NotifyMailPurpose labels notification mails in mail_log; the daily limits
|
|
// count it.
|
|
const NotifyMailPurpose = "notify"
|
|
|
|
var (
|
|
// NodeNotifyEvents are open to every user and chosen by default.
|
|
NodeNotifyEvents = []string{NotifyNodeOffline, NotifyNodeBattery}
|
|
// OptionalNodeNotifyEvents are open to every user (when the instance
|
|
// configures them) and off by default.
|
|
OptionalNodeNotifyEvents = []string{NotifyNodeExternal}
|
|
// OwnerNotifyEvents are open to every user and off by default.
|
|
OwnerNotifyEvents = []string{NotifyObserverOfflineOwn}
|
|
// AdminNotifyEvents are open to admins only and off by default.
|
|
AdminNotifyEvents = []string{NotifyForeignNew, NotifyObserverOffline}
|
|
)
|
|
|
|
// ErrWatchLimit: the user already watches the maximum number of nodes.
|
|
var ErrWatchLimit = errors.New("users: watch limit reached")
|
|
|
|
// IsAdminNotifyEvent reports whether only admins may choose e.
|
|
func IsAdminNotifyEvent(e string) bool { return e == NotifyForeignNew || e == NotifyObserverOffline }
|
|
|
|
// ValidNotifyEvent reports whether e is a known event type.
|
|
func ValidNotifyEvent(e string) bool {
|
|
return e == NotifyNodeOffline || e == NotifyNodeBattery || e == NotifyNodeExternal || e == NotifyObserverOfflineOwn || IsAdminNotifyEvent(e)
|
|
}
|
|
|
|
// NotifyPrefs is one user's notification preferences.
|
|
type NotifyPrefs struct {
|
|
UserID int64
|
|
Enabled bool
|
|
Events []string // chosen events, canonical order, no duplicates
|
|
UnsubToken string // random, only turns notifications off
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
// DefaultNotifyPrefs is what a user without a preferences row gets:
|
|
// notifications on, the node events chosen, no unsubscribe token yet.
|
|
// NotifyPrefsFor stores these values when it creates the row.
|
|
func DefaultNotifyPrefs(userID int64) NotifyPrefs {
|
|
return NotifyPrefs{UserID: userID, Enabled: true, Events: append([]string(nil), NodeNotifyEvents...)}
|
|
}
|
|
|
|
// Has reports whether the user chose event.
|
|
func (p NotifyPrefs) Has(event string) bool {
|
|
for _, e := range p.Events {
|
|
if e == event {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// NotifyWatch is one watched node of one user.
|
|
type NotifyWatch struct {
|
|
UserID int64
|
|
Pubkey string // lowercase hex
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
// NotifyKey identifies one evaluated subject of one user.
|
|
type NotifyKey struct {
|
|
UserID int64
|
|
Event string
|
|
Subject string // node pubkey, observer id, or "*" (foreign.new baseline)
|
|
}
|
|
|
|
// NotifyState is the last evaluated state of a NotifyKey.
|
|
type NotifyState struct {
|
|
NotifyKey
|
|
State string // NotifyGood, NotifyBad or NotifyTold
|
|
ChangedAt time.Time
|
|
}
|
|
|
|
// canonicalEvents keeps the known events of list in canonical order, once each.
|
|
func canonicalEvents(list []string) []string {
|
|
want := make(map[string]bool, len(list))
|
|
for _, e := range list {
|
|
want[e] = true
|
|
}
|
|
out := []string{}
|
|
for _, group := range [][]string{NodeNotifyEvents, OptionalNodeNotifyEvents, OwnerNotifyEvents, AdminNotifyEvents} {
|
|
for _, e := range group {
|
|
if want[e] {
|
|
out = append(out, e)
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func placeholders(n int) string { return strings.TrimSuffix(strings.Repeat("?,", n), ",") }
|
|
|
|
const prefsCols = `user_id, enabled, events, unsub_token, updated_at`
|
|
|
|
func scanPrefs(row rowScanner) (*NotifyPrefs, error) {
|
|
var p NotifyPrefs
|
|
var enabled int
|
|
var events string
|
|
var updated int64
|
|
if err := row.Scan(&p.UserID, &enabled, &events, &p.UnsubToken, &updated); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
p.Enabled = enabled != 0
|
|
p.Events = canonicalEvents(strings.Split(events, ","))
|
|
p.UpdatedAt = fromUnix(updated)
|
|
return &p, nil
|
|
}
|
|
|
|
func (s *Store) getPrefs(userID int64) (*NotifyPrefs, error) {
|
|
return scanPrefs(s.db.QueryRow(`SELECT `+prefsCols+` FROM notification_prefs WHERE user_id = ?`, userID))
|
|
}
|
|
|
|
// NotifyPrefsFor returns the user's preferences, creating the default row
|
|
// (on, node events, a new unsubscribe token) on first use.
|
|
func (s *Store) NotifyPrefsFor(userID int64) (NotifyPrefs, error) {
|
|
if p, err := s.getPrefs(userID); !errors.Is(err, ErrNotFound) {
|
|
if err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
return *p, nil
|
|
}
|
|
tok, _, err := NewToken()
|
|
if err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
d := DefaultNotifyPrefs(userID)
|
|
if _, err := s.db.Exec(`INSERT OR IGNORE INTO notification_prefs (user_id, enabled, events, unsub_token, updated_at)
|
|
VALUES (?, ?, ?, ?, ?)`, userID, d.Enabled, strings.Join(d.Events, ","), tok, unix(s.now())); err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
p, err := s.getPrefs(userID)
|
|
if err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
return *p, nil
|
|
}
|
|
|
|
// StoredNotifyPrefs returns the user's stored preferences, or nil when
|
|
// none were ever created. Unlike NotifyPrefsFor it never writes.
|
|
func (s *Store) StoredNotifyPrefs(userID int64) (*NotifyPrefs, error) {
|
|
p, err := s.getPrefs(userID)
|
|
if errors.Is(err, ErrNotFound) {
|
|
return nil, nil
|
|
}
|
|
return p, err
|
|
}
|
|
|
|
// SetNotifyPrefs stores enabled and events (unknown events dropped,
|
|
// canonical order) and deletes the state rows of events no longer chosen,
|
|
// so choosing an event again starts with a silent first evaluation. The
|
|
// caller checks which events the user may choose.
|
|
func (s *Store) SetNotifyPrefs(userID int64, enabled bool, events []string) (NotifyPrefs, error) {
|
|
if _, err := s.NotifyPrefsFor(userID); err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
ev := canonicalEvents(events)
|
|
en := 0
|
|
if enabled {
|
|
en = 1
|
|
}
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
defer tx.Rollback()
|
|
if _, err := tx.Exec(`UPDATE notification_prefs SET enabled = ?, events = ?, updated_at = ? WHERE user_id = ?`,
|
|
en, strings.Join(ev, ","), unix(s.now()), userID); err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
q := `DELETE FROM notification_state WHERE user_id = ?`
|
|
args := []any{userID}
|
|
if len(ev) > 0 {
|
|
q += ` AND event NOT IN (` + placeholders(len(ev)) + `)`
|
|
for _, e := range ev {
|
|
args = append(args, e)
|
|
}
|
|
}
|
|
if _, err := tx.Exec(q, args...); err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return NotifyPrefs{}, err
|
|
}
|
|
return s.NotifyPrefsFor(userID)
|
|
}
|
|
|
|
// DisableNotifyByToken turns notifications off for the user holding the
|
|
// unsubscribe token. wasEnabled reports whether they were on.
|
|
// ErrTokenInvalid for an empty or unknown token.
|
|
func (s *Store) DisableNotifyByToken(token string) (userID int64, wasEnabled bool, err error) {
|
|
if token == "" {
|
|
return 0, false, ErrTokenInvalid
|
|
}
|
|
var en int
|
|
err = s.db.QueryRow(`SELECT user_id, enabled FROM notification_prefs WHERE unsub_token = ?`, token).Scan(&userID, &en)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return 0, false, ErrTokenInvalid
|
|
}
|
|
if err != nil {
|
|
return 0, false, err
|
|
}
|
|
if en != 0 {
|
|
if _, err := s.db.Exec(`UPDATE notification_prefs SET enabled = 0, updated_at = ? WHERE user_id = ?`, unix(s.now()), userID); err != nil {
|
|
return 0, false, err
|
|
}
|
|
}
|
|
return userID, en != 0, nil
|
|
}
|
|
|
|
// AllNotifyPrefs returns every preferences row, by user id.
|
|
func (s *Store) AllNotifyPrefs() ([]NotifyPrefs, error) {
|
|
rows, err := s.db.Query(`SELECT ` + prefsCols + ` FROM notification_prefs ORDER BY user_id`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []NotifyPrefs
|
|
for rows.Next() {
|
|
p, err := scanPrefs(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *p)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// AddWatches adds pubkeys (lowercase hex, checked by the caller) to the
|
|
// user's watch list in one transaction, in order, while the list holds
|
|
// fewer than max entries (max <= 0: no limit). It reports how many were
|
|
// added, how many were already watched and how many the limit left out.
|
|
func (s *Store) AddWatches(userID int64, pubkeys []string, max int) (added, already, overLimit int, err error) {
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return 0, 0, 0, err
|
|
}
|
|
defer tx.Rollback()
|
|
have := map[string]bool{}
|
|
rows, err := tx.Query(`SELECT pubkey FROM notification_watches WHERE user_id = ?`, userID)
|
|
if err != nil {
|
|
return 0, 0, 0, err
|
|
}
|
|
for rows.Next() {
|
|
var pk string
|
|
if err := rows.Scan(&pk); err != nil {
|
|
rows.Close()
|
|
return 0, 0, 0, err
|
|
}
|
|
have[pk] = true
|
|
}
|
|
rows.Close()
|
|
if err := rows.Err(); err != nil {
|
|
return 0, 0, 0, err
|
|
}
|
|
now := unix(s.now())
|
|
for _, pk := range pubkeys {
|
|
switch {
|
|
case have[pk]:
|
|
already++
|
|
case max > 0 && len(have) >= max:
|
|
overLimit++
|
|
default:
|
|
if _, err := tx.Exec(`INSERT INTO notification_watches (user_id, pubkey, created_at) VALUES (?, ?, ?)`, userID, pk, now); err != nil {
|
|
return 0, 0, 0, err
|
|
}
|
|
have[pk] = true
|
|
added++
|
|
}
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return 0, 0, 0, err
|
|
}
|
|
return added, already, overLimit, nil
|
|
}
|
|
|
|
// AddWatch watches one node. Watching an already watched node is a no-op;
|
|
// ErrWatchLimit when the list is full.
|
|
func (s *Store) AddWatch(userID int64, pubkey string, max int) error {
|
|
_, _, over, err := s.AddWatches(userID, []string{pubkey}, max)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if over > 0 {
|
|
return ErrWatchLimit
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RemoveWatch stops watching a node and deletes its node.* state rows
|
|
// (node.external subjects are "<pubkey>/<key>"). Removing a node that is
|
|
// not watched is a no-op.
|
|
func (s *Store) RemoveWatch(userID int64, pubkey string) error {
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
if _, err := tx.Exec(`DELETE FROM notification_watches WHERE user_id = ? AND pubkey = ?`, userID, pubkey); err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.Exec(`DELETE FROM notification_state WHERE user_id = ? AND subject = ? AND event IN (?, ?)`,
|
|
userID, pubkey, NotifyNodeOffline, NotifyNodeBattery); err != nil {
|
|
return err
|
|
}
|
|
if _, err := tx.Exec(`DELETE FROM notification_state WHERE user_id = ? AND event = ? AND substr(subject, 1, ?) = ?`,
|
|
userID, NotifyNodeExternal, len(pubkey)+1, pubkey+"/"); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
func (s *Store) queryWatches(q string, args ...any) ([]NotifyWatch, error) {
|
|
rows, err := s.db.Query(q, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []NotifyWatch
|
|
for rows.Next() {
|
|
var w NotifyWatch
|
|
var created int64
|
|
if err := rows.Scan(&w.UserID, &w.Pubkey, &created); err != nil {
|
|
return nil, err
|
|
}
|
|
w.CreatedAt = fromUnix(created)
|
|
out = append(out, w)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// WatchesFor returns the user's watches, oldest first.
|
|
func (s *Store) WatchesFor(userID int64) ([]NotifyWatch, error) {
|
|
return s.queryWatches(`SELECT user_id, pubkey, created_at FROM notification_watches WHERE user_id = ? ORDER BY created_at, pubkey`, userID)
|
|
}
|
|
|
|
// AllWatches returns every watch, by user and pubkey.
|
|
func (s *Store) AllWatches() ([]NotifyWatch, error) {
|
|
return s.queryWatches(`SELECT user_id, pubkey, created_at FROM notification_watches ORDER BY user_id, pubkey`)
|
|
}
|
|
|
|
// AllNotifyStates returns every stored state.
|
|
func (s *Store) AllNotifyStates() ([]NotifyState, error) {
|
|
rows, err := s.db.Query(`SELECT user_id, event, subject, state, changed_at FROM notification_state`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var out []NotifyState
|
|
for rows.Next() {
|
|
var st NotifyState
|
|
var changed int64
|
|
if err := rows.Scan(&st.UserID, &st.Event, &st.Subject, &st.State, &changed); err != nil {
|
|
return nil, err
|
|
}
|
|
st.ChangedAt = fromUnix(changed)
|
|
out = append(out, st)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// WriteNotifyStates upserts the rows in one transaction. Rows of users
|
|
// deleted since the caller read them are skipped instead of failing the
|
|
// whole write on the foreign key.
|
|
func (s *Store) WriteNotifyStates(list []NotifyState) error {
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
stmt, err := tx.Prepare(`INSERT INTO notification_state (user_id, event, subject, state, changed_at)
|
|
SELECT ?, ?, ?, ?, ? WHERE EXISTS (SELECT 1 FROM users WHERE id = ?)
|
|
ON CONFLICT (user_id, event, subject) DO UPDATE SET state = excluded.state, changed_at = excluded.changed_at`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer stmt.Close()
|
|
for _, st := range list {
|
|
if _, err := stmt.Exec(st.UserID, st.Event, st.Subject, st.State, unix(st.ChangedAt), st.UserID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
// DeleteNotifyStates deletes the rows of keys in one transaction; keys
|
|
// without a row are ignored.
|
|
func (s *Store) DeleteNotifyStates(keys []NotifyKey) error {
|
|
if len(keys) == 0 {
|
|
return nil
|
|
}
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
stmt, err := tx.Prepare(`DELETE FROM notification_state WHERE user_id = ? AND event = ? AND subject = ?`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer stmt.Close()
|
|
for _, k := range keys {
|
|
if _, err := stmt.Exec(k.UserID, k.Event, k.Subject); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return tx.Commit()
|
|
}
|
|
|
|
// NotifyMailCounts counts notification mails sent at or after since: in
|
|
// total (deleted accounts included) and per existing user.
|
|
func (s *Store) NotifyMailCounts(since time.Time) (total int, perUser map[int64]int, err error) {
|
|
perUser = map[int64]int{}
|
|
rows, err := s.db.Query(`SELECT user_id, COUNT(*) FROM mail_log WHERE purpose = ? AND sent_at >= ? GROUP BY user_id`,
|
|
NotifyMailPurpose, unix(since))
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var uid sql.NullInt64
|
|
var n int
|
|
if err := rows.Scan(&uid, &n); err != nil {
|
|
return 0, nil, err
|
|
}
|
|
total += n
|
|
if uid.Valid {
|
|
perUser[uid.Int64] = n
|
|
}
|
|
}
|
|
return total, perUser, rows.Err()
|
|
}
|
|
|
|
// NotifyWatchStats counts watches and the users who have at least one.
|
|
func (s *Store) NotifyWatchStats() (watches, watchingUsers int, err error) {
|
|
err = s.db.QueryRow(`SELECT COUNT(*), COUNT(DISTINCT user_id) FROM notification_watches`).Scan(&watches, &watchingUsers)
|
|
return watches, watchingUsers, err
|
|
}
|