package pipeline import ( "context" "database/sql" "fmt" "git.a-wan.net/alan/pipelines/internal/protocol" ) // notificationSettingPrefix namespaces the global notification choices inside // server_settings; each key stores "true" or "false". A missing row means the // default from protocol.DefaultNotificationSettings. const notificationSettingPrefix = "notify." type settingsQuerier interface { QueryContext(context.Context, string, ...any) (*sql.Rows, error) } // readNotificationSettings reads the stored choices through q, which may be the // database or an open transaction (run-transition enqueue reads inside its tx). func readNotificationSettings(ctx context.Context, q settingsQuerier) (protocol.NotificationSettings, error) { settings := protocol.DefaultNotificationSettings() rows, err := q.QueryContext(ctx, `SELECT key,value FROM server_settings WHERE key LIKE 'notify.%'`) if err != nil { return settings, err } defer rows.Close() for rows.Next() { var key, value string if err := rows.Scan(&key, &value); err != nil { return settings, err } if field := settings.Field(key[len(notificationSettingPrefix):]); field != nil { *field = value == "true" } } return settings, rows.Err() } // NotificationSettings returns the operator's global notification choices. func (s *Store) NotificationSettings(ctx context.Context) (protocol.NotificationSettings, error) { return readNotificationSettings(ctx, s.db) } // UpdateNotificationSettings applies a validated partial update atomically and // returns the stored result. Unknown keys and non-boolean values are refused // before anything is written. func (s *Store) UpdateNotificationSettings(ctx context.Context, update map[string]any) (protocol.NotificationSettings, error) { values, err := protocol.ValidateNotificationSettingsUpdate(update) if err != nil { return protocol.NotificationSettings{}, err } tx, err := s.db.BeginTx(ctx, nil) if err != nil { return protocol.NotificationSettings{}, err } defer tx.Rollback() for key, value := range values { if _, err := tx.ExecContext(ctx, `INSERT INTO server_settings(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, notificationSettingPrefix+key, fmt.Sprint(value)); err != nil { return protocol.NotificationSettings{}, err } } settings, err := readNotificationSettings(ctx, tx) if err != nil { return protocol.NotificationSettings{}, err } return settings, tx.Commit() }