Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions CLAUDE.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ The fields of the settings pages. The UI shows these descriptions in the hints (

## Projects

A project is one service (backend, frontend, worker) with its own DSN. Deleting a project stops its DSN at once and deletes its data. Only admins delete projects.
A project is one service (backend, frontend, worker) with its own DSN. Deleting a project stops its DSN at once; its data is deleted in the background. Only admins delete projects.

| Field | |
|---|---|
Expand Down
24 changes: 10 additions & 14 deletions internal/api/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"net/url"
"reflect"
Expand Down Expand Up @@ -408,38 +409,33 @@ func duplicateError(duplicate services.Duplicate, what string) error {
const hiddenDuplicate = "Another connection already sends there."

// problemsError reports the field errors of a form as one InputError
// ("name: ...; levels: ..."), nil when there are none. fields renames form
// fields to the tool's input names.
func problemsError(problems map[string]string, fields map[string]string) error {
// ("name: ...; levels: ..."), nil when there are none.
func problemsError(problems map[string]string) error {
if len(problems) == 0 {
return nil
}

var lines []string

named := make(map[string]string, len(problems))
lines := make([]string, 0, len(problems))

for field, problem := range problems {
name := cmp.Or(fields[field], field)
named[name] = problem
lines = append(lines, name+": "+problem)
lines = append(lines, field+": "+problem)
}

slices.Sort(lines)

return InputError{message: strings.Join(lines, "; "), fields: named}
return InputError{message: strings.Join(lines, "; "), fields: maps.Clone(problems)}
}

// formError is the error of a form: a services.Refusal with its status
// (403 or 409) and its fields renamed, err as it is otherwise.
func formError(err error, fields map[string]string) error {
// (403 or 409) and its fields, err as it is otherwise.
func formError(err error) error {
var refusal services.Refusal

if !errors.As(err, &refusal) {
return err
}

input, _ := problemsError(refusal.Problems, fields).(InputError)
input, _ := problemsError(refusal.Problems).(InputError)
input.status = refusalStatus(refusal.Kind)

return input
Expand Down Expand Up @@ -500,7 +496,7 @@ func OutcomeOf(err error) Outcome {
outcome.Status, outcome.RetryAfter, outcome.Hidden = cmp.Or(input.status, http.StatusBadRequest), input.retryAfter, input.hidden
outcome.Body = ErrorBody{Error: input.message, Fields: input.fields, Duplicate: input.duplicate}
case errors.As(err, &refusal):
return OutcomeOf(formError(refusal, nil))
return OutcomeOf(formError(refusal))
case errors.As(err, &reason):
outcome.Status, outcome.Body.Error = refusalStatus(reason.Kind), reason.Text
case errors.Is(err, ErrNotFound):
Expand Down
59 changes: 13 additions & 46 deletions internal/api/manage.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package api
import (
"context"
"errors"
"net/url"
"strconv"
"time"

"github.com/devforth/exceptic/internal/platform/config"
Expand Down Expand Up @@ -213,7 +211,7 @@ func (handler *handlers) updateAccountName(ctx context.Context, call Call, input
return userOutput{}, err
}

if err := problemsError(problems, nil); err != nil {
if err := problemsError(problems); err != nil {
return userOutput{}, err
}

Expand Down Expand Up @@ -366,11 +364,10 @@ type projectDefaults struct {
}

func (handler *handlers) getProjectDefaults(ctx context.Context, call Call, _ noInput) (projectDefaults, error) {
defaults := handler.services.Projects.FormValues(store.Project{})
storage, err := handler.services.Projects.Storage(ctx, call.Access(), []int{})

return projectDefaults{
ShownColor: handler.services.Projects.Color(store.Project{}), LogLevels: defaults["log_level"], DiskShare: store.Project{}.Share(),
ShownColor: handler.services.Projects.Color(store.Project{}), LogLevels: handler.services.Projects.RecordedLogLevels(config.Project{}), DiskShare: store.Project{}.Share(),
AllowedOrigins: []string{}, LimitBytes: storage.LimitBytes, Limit: storage.Limit, Used: storage.Used,
}, err
}
Expand Down Expand Up @@ -465,42 +462,24 @@ type projectFields struct {

var projectChoices = map[string][]string{"log_levels": config.LogLevels}

// apply writes the given fields over the form.
func (fields projectFields) apply(form url.Values) {
if fields.Color != nil {
form.Set("color", *fields.Color)
}

if fields.LogLevels != nil {
form["log_level"] = *fields.LogLevels
}

if fields.DiskShare != nil {
form.Set("disk_share", strconv.Itoa(*fields.DiskShare))
}

if fields.AllowedOrigins != nil {
// An empty list still sends the field, so it clears them.
form["allowed_origin"] = append([]string{""}, *fields.AllowedOrigins...)
}
// change is the services' change of these fields and name.
func (fields projectFields) change(name *string) services.ProjectChange {
return services.ProjectChange{Name: name, Color: fields.Color, LogLevels: fields.LogLevels, DiskShare: fields.DiskShare, AllowedOrigins: fields.AllowedOrigins}
}

// projectFormFields names the form's fields as the tools do.
var projectFormFields = map[string]string{"log_level": "log_levels", "allowed_origin": "allowed_origins"}

type createProjectInput struct {
Name string `json:"name" jsonschema:"Lowercase letters, digits, '-' and '_', starting with a letter or digit, not digits only (that reads as an ID): backend, frontend, worker."`
projectFields
}

func (handler *handlers) saveProject(ctx context.Context, call Call, form url.Values, project store.Project) (projectSettings, error) {
saved, problems, err := handler.services.Projects.Save(ctx, call.Viewer, form, project)
func (handler *handlers) saveProject(ctx context.Context, call Call, change services.ProjectChange, project store.Project) (projectSettings, error) {
saved, problems, err := handler.services.Projects.Save(ctx, call.Viewer, change, project)

if err != nil {
return projectSettings{}, formError(err, projectFormFields)
return projectSettings{}, formError(err)
}

if err := problemsError(problems, projectFormFields); err != nil {
if err := problemsError(problems); err != nil {
return projectSettings{}, err
}

Expand All @@ -522,11 +501,7 @@ func (handler *handlers) saveProject(ctx context.Context, call Call, form url.Va
}

func (handler *handlers) createProject(ctx context.Context, call Call, input createProjectInput) (projectSettings, error) {
form := handler.services.Projects.FormValues(store.Project{})
form.Set("name", input.Name)
input.apply(form)

return handler.saveProject(ctx, call, form, store.Project{})
return handler.saveProject(ctx, call, input.change(&input.Name), store.Project{})
}

type updateProjectInput struct {
Expand All @@ -542,15 +517,7 @@ func (handler *handlers) updateProject(ctx context.Context, call Call, input upd
return projectSettings{}, err
}

form := handler.services.Projects.FormValues(project)

if input.Name != nil {
form.Set("name", *input.Name)
}

input.apply(form)

return handler.saveProject(ctx, call, form, project)
return handler.saveProject(ctx, call, input.change(input.Name), project)
}

func (handler *handlers) deleteProject(ctx context.Context, call Call, input projectInput) (doneOutput, error) {
Expand Down Expand Up @@ -649,7 +616,7 @@ func (handler *handlers) createUser(ctx context.Context, call Call, input create
return passwordOutput{}, err
}

if err := problemsError(problems, nil); err != nil {
if err := problemsError(problems); err != nil {
return passwordOutput{}, err
}

Expand Down Expand Up @@ -709,7 +676,7 @@ func (handler *handlers) updateUser(ctx context.Context, call Call, input update
return userOutput{}, err
}

if err := problemsError(problems, nil); err != nil {
if err := problemsError(problems); err != nil {
return userOutput{}, err
}

Expand Down
104 changes: 32 additions & 72 deletions internal/api/notifications.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"time"

Expand Down Expand Up @@ -409,86 +408,47 @@ func (chat chatFields) replaced() []string {
return nil
}

// set writes the filled chat fields over the form.
func (chat chatFields) set(form url.Values) {
for name, value := range map[string]string{
"bot_token": chat.BotToken, "chat_id": chat.ChatID, "webhook_url": chat.WebhookURL,
"slack_bot_token": chat.SlackBotToken, "slack_channel": chat.SlackChannel,
} {
if value != "" {
form.Set(name, value)
}
}
}

// setCheckbox: a checkbox of the form as given; nil keeps it.
func setCheckbox(form url.Values, name string, value *bool) {
switch {
case value == nil:
case *value:
form.Set(name, "on")
default:
form.Del(name)
// tokens are the services' chat tokens of these fields.
func (chat chatFields) tokens() services.ChatTokens {
return services.ChatTokens{
BotToken: chat.BotToken, ChatID: chat.ChatID, WebhookURL: chat.WebhookURL, SlackBotToken: chat.SlackBotToken, SlackChannel: chat.SlackChannel,
}
}

// applyConnection writes the given fields over the form (projects:
// connectionPatch is the services' change of the given fields (projects:
// projectsField's refusals).
func (handler *handlers) applyConnection(call Call, form url.Values, fields connectionFields, chat chatFields) error {
if fields.Name != nil {
form.Set("name", *fields.Name)
func (handler *handlers) connectionPatch(call Call, fields connectionFields, chat chatFields) (services.ConnectionChange, error) {
change := services.ConnectionChange{
Name: fields.Name, AllProjects: fields.AllProjects, Levels: fields.Levels, Active: fields.Active, IncludeIssueLink: fields.IncludeIssueLink, Chat: chat.tokens(),
}

if fields.Projects != nil {
ids, err := handler.projectsField(call, "projects", *fields.Projects)

if err != nil {
return err
return change, err
}

form.Del("project")

for _, id := range ids {
form.Add("project", strconv.Itoa(id))
}
}

switch {
case fields.AllProjects != nil:
setCheckbox(form, "all_projects", fields.AllProjects)
case fields.Projects != nil:
all := len(*fields.Projects) == 0
setCheckbox(form, "all_projects", &all)
change.ProjectIDs = &ids
}

if fields.Levels != nil {
form["level"] = *fields.Levels
}

setCheckbox(form, "active", fields.Active)
setCheckbox(form, "include_issue_link", fields.IncludeIssueLink)
chat.set(form)

return nil
return change, nil
}

// connectionFormFields names the form's fields as the tools do.
var connectionFormFields = map[string]string{"address": "email"}

// saveConnection saves the form over connection (none: a new one); replaced
// names the secrets the form replaces, for the audit log.
func (handler *handlers) saveConnection(ctx context.Context, call Call, form url.Values, connection store.Connection, replaced []string) (connectionOutput, error) {
saved, err := handler.services.Connections.Save(ctx, call.Access(), form, connection)
// saveConnection saves change over connection (none: a new one); replaced
// names the secrets it replaces, for the audit log.
func (handler *handlers) saveConnection(ctx context.Context, call Call, change services.ConnectionChange, connection store.Connection, replaced []string) (connectionOutput, error) {
saved, err := handler.services.Connections.Save(ctx, call.Access(), change, connection)

if err != nil {
return connectionOutput{}, formError(err, connectionFormFields)
return connectionOutput{}, formError(err)
}

if saved.Duplicate != nil {
return connectionOutput{}, duplicateError(*saved.Duplicate, "sends there")
}

if err := problemsError(saved.Problems, connectionFormFields); err != nil {
if err := problemsError(saved.Problems); err != nil {
return connectionOutput{}, err
}

Expand Down Expand Up @@ -518,9 +478,7 @@ type createConnectionInput struct {
}

func (handler *handlers) createConnection(ctx context.Context, call Call, input createConnectionInput) (connectionOutput, error) {
// A new connection starts as in the UI (store.NewConnection).
form := handler.services.Connections.FormValues(handler.services.Connections.New(input.Type, call.Access()))
form.Set("type", input.Type)
destinationID := ""

if input.Type == config.ChannelEmail {
destination, ok, err := handler.services.Verification.FindDestination(ctx, input.Email)
Expand All @@ -533,14 +491,19 @@ func (handler *handlers) createConnection(ctx context.Context, call Call, input
return connectionOutput{}, unconfirmed("email", "confirm "+strconv.Quote(input.Email)+" first with start_email_verification and confirm_email")
}

form.Set("destination_id", destination.ID)
destinationID = destination.ID
}

if err := handler.applyConnection(call, form, input.connectionFields, input.chatFields); err != nil {
// A new connection starts from Connections.New, as in the UI.
change, err := handler.connectionPatch(call, input.connectionFields, input.chatFields)

if err != nil {
return connectionOutput{}, err
}

return handler.saveConnection(ctx, call, form, store.Connection{}, nil)
change.Type, change.DestinationID = input.Type, destinationID

return handler.saveConnection(ctx, call, change, store.Connection{}, nil)
}

type connectionInput struct {
Expand All @@ -560,13 +523,13 @@ func (handler *handlers) updateConnection(ctx context.Context, call Call, input
return connectionOutput{}, err
}

form := handler.services.Connections.FormValues(connection)
change, err := handler.connectionPatch(call, input.connectionFields, input.chatFields)

if err := handler.applyConnection(call, form, input.connectionFields, input.chatFields); err != nil {
if err != nil {
return connectionOutput{}, err
}

return handler.saveConnection(ctx, call, form, connection, input.replaced())
return handler.saveConnection(ctx, call, change, connection, input.replaced())
}

type setConnectionActiveInput struct {
Expand Down Expand Up @@ -632,11 +595,8 @@ func (handler *handlers) testChat(ctx context.Context, call Call, input testChat
existing, channelType = connection, connection.Type
}

form := url.Values{"name": {input.Name}}
setCheckbox(form, "include_issue_link", &input.IncludeIssueLink)
input.set(form)

result := handler.services.Connections.TestChat(ctx, form, channelType, existing)
settings := services.ChatSettings{Type: channelType, Name: input.Name, IncludeIssueLink: input.IncludeIssueLink, Chat: input.tokens()}
result := handler.services.Connections.TestChat(ctx, settings, existing)

return chatTestOutput{Sent: result.Sent, Message: result.Message}, nil
}
Expand Down Expand Up @@ -664,7 +624,7 @@ func (handler *handlers) sendTestMessage(ctx context.Context, call Call, input c

// unconfirmed refuses at field what an unconfirmed address may not do (409).
func unconfirmed(field, problem string) error {
input, _ := problemsError(map[string]string{field: problem}, nil).(InputError)
input, _ := problemsError(map[string]string{field: problem}).(InputError)
input.status = http.StatusConflict

return input
Expand Down
Loading
Loading