SPB Git

Repository Public

ops_maintenance.go 25.9 KB 716 lines go

1package api23import (4	"bytes"5	"context"6	"fmt"7	"net/url"8	"sort"9	"strconv"10	"strings"11	"time"1213	"github.com/google/uuid"14	"github.com/jackc/pgx/v5"1516	"clustr.spboucher.ai/mcc/internal/audit"17	"clustr.spboucher.ai/mcc/internal/authz"18	"clustr.spboucher.ai/mcc/internal/events"19	"clustr.spboucher.ai/mcc/internal/httpx"20	"clustr.spboucher.ai/mcc/internal/ids"21	mt "clustr.spboucher.ai/mcc/internal/maintenance"22)2324// Maintenance calendar and notes.25//26// Note rules (as the contract states them):27//   - anyone with maintenance.write writes notes and may pin or unpin any note;28//   - only the AUTHOR can change the body of a note (edited_at records that it was edited);29//   - a note is deleted (soft delete, kept in the database) by its author, or by30//     anyone holding alerts.manage (administrators and owners by default).3132const maxCalendarSpan = 400 * 24 * time.Hour3334const windowSelect = `select ` + mt.Columns + `, (select display_name from users u where u.id=maintenance_windows.created_by) from maintenance_windows`3536func windowOut(w mt.Window, creator *string) MaintenanceWindow {37	return MaintenanceWindow{Id: w.ID, Title: w.Title, Description: w.Description, Category: MaintenanceCategory(w.Category), StartsAt: w.StartsAt, EndsAt: w.EndsAt,38		Timezone: w.Timezone, Recurrence: MaintenanceRecurrence(w.Recurrence), RecurrenceUntil: w.RecurrenceUntil, Scope: MaintenanceScope{NodeIds: w.NodeIDs},39		SetMaintenanceMode: w.SetMaintenanceMode, SilenceAlerts: w.SilenceAlerts, Status: MaintenanceStatus(w.Status), ActivatedOccurrence: w.ActivatedOccurrence,40		CreatedBy: w.CreatedBy, CreatedByDisplayName: creator, CreatedAt: w.CreatedAt, UpdatedAt: w.UpdatedAt}41}4243type rowQuerier interface {44	QueryRow(context.Context, string, ...any) pgx.Row45}4647func loadWindow(ctx context.Context, q rowQuerier, id uuid.UUID, lock string) (mt.Window, *string, error) {48	var creator *string49	w, err := mt.Scan(q.QueryRow(ctx, windowSelect+` where id=$1`+lock, id), &creator)50	return w, creator, notFound(err)51}5253// windowsIn loads the windows that can have an occurrence in [from, to).54func (h *opsHandlers) windowsIn(ctx context.Context, from, to time.Time, node *uuid.UUID, status *string, skip *uuid.UUID) ([]mt.Window, []*string, error) {55	var w where56	w.add("starts_at < ?", to)57	w.add("(recurrence <> 'none' and (recurrence_until is null or recurrence_until >= ?) or ends_at > ?)", from.Add(-mt.MaxDuration), from)58	if node != nil {59		w.add("scope->'node_ids' @> to_jsonb(?::text)", node.String())60	}61	if status != nil {62		w.add("status = ?", *status)63	}64	if skip != nil {65		w.add("id <> ?", *skip)66	}67	rows, err := h.Pool.Query(ctx, windowSelect+w.sql()+" order by starts_at, id limit 5000", w.args...)68	if err != nil {69		return nil, nil, err70	}71	defer rows.Close()72	var ws []mt.Window73	var creators []*string74	for rows.Next() {75		var c *string76		win, err := mt.Scan(rows, &c)77		if err != nil {78			return nil, nil, err79		}80		ws, creators = append(ws, win), append(creators, c)81	}82	return ws, creators, rows.Err()83}8485func calendarRange(from, to *time.Time, defFrom, defTo time.Duration) (time.Time, time.Time, error) {86	now := nowUTC()87	f, t := now.Add(defFrom), now.Add(defTo)88	if from != nil {89		f = *from90		if to == nil {91			t = f.Add(defTo - defFrom)92		}93	}94	if to != nil {95		t = *to96	}97	if !t.After(f) || t.Sub(f) > maxCalendarSpan+31*24*time.Hour {98		return f, t, httpx.Validation("The range must be positive and at most 400 days.")99	}100	return f, t, nil101}102103func (h *opsHandlers) ListMaintenanceWindows(ctx context.Context, req ListMaintenanceWindowsRequestObject) (ListMaintenanceWindowsResponseObject, error) {104	from, to, err := calendarRange(req.Params.From, req.Params.To, 0, 30*24*time.Hour)105	if err != nil {106		return nil, err107	}108	if to.Sub(from) > maxCalendarSpan {109		return nil, httpx.Validation("The range must be at most 400 days.")110	}111	var status *string112	if req.Params.Status != nil {113		status = ptr(string(*req.Params.Status))114	}115	ws, creators, err := h.windowsIn(ctx, from, to, req.Params.NodeId, status, nil)116	if err != nil {117		return nil, err118	}119	out := MaintenanceOccurrenceList{Items: []MaintenanceOccurrence{}}120	winIDs := make([]uuid.UUID, 0, len(ws))121	for i, w := range ws {122		occs, trunc, err := mt.Expand(w, from, to, mt.MaxOccurrences)123		if err != nil {124			continue // a window that cannot be expanded (should not exist: validated on write) is not listed125		}126		out.Truncated = out.Truncated || trunc127		wo := windowOut(w, creators[i])128		for _, o := range occs {129			item := MaintenanceOccurrence{Window: wo, OccurrenceStart: o.Start, OccurrenceEnd: o.End}130			if w.Status == mt.StatusInProgress && w.ActivatedOccurrence != nil && w.ActivatedOccurrence.Equal(o.Start) {131				item.Active = ptr(true)132			}133			out.Items = append(out.Items, item)134		}135		if len(occs) > 0 {136			winIDs = append(winIDs, w.ID)137		}138	}139	sort.SliceStable(out.Items, func(i, j int) bool { return out.Items[i].OccurrenceStart.Before(out.Items[j].OccurrenceStart) })140	if len(out.Items) > mt.MaxOccurrences {141		out.Items, out.Truncated = out.Items[:mt.MaxOccurrences], true142	}143	// Note counts: per occurrence for recurring windows, per window otherwise.144	if len(winIDs) > 0 {145		rows, err := h.Pool.Query(ctx, `select window_id, occurrence, count(*) from maintenance_notes where window_id = any($1) and deleted_at is null group by 1,2`, winIDs)146		if err != nil {147			return nil, err148		}149		defer rows.Close()150		perOcc, perWin := map[string]int{}, map[uuid.UUID]int{}151		for rows.Next() {152			var id uuid.UUID153			var occ *time.Time154			var n int155			if err := rows.Scan(&id, &occ, &n); err != nil {156				return nil, err157			}158			perWin[id] += n159			if occ != nil {160				perOcc[id.String()+occ.UTC().Format(time.RFC3339)] += n161			}162		}163		if err := rows.Err(); err != nil {164			return nil, err165		}166		for i := range out.Items {167			it := &out.Items[i]168			if it.Window.Recurrence == MaintenanceRecurrence(mt.RecurrenceNone) {169				it.NoteCount = perWin[it.Window.Id]170			} else {171				it.NoteCount = perOcc[it.Window.Id.String()+it.OccurrenceStart.UTC().Format(time.RFC3339)]172			}173		}174	}175	return ListMaintenanceWindows200JSONResponse{Body: out}, nil176}177178func (h *opsHandlers) GetMaintenanceWindow(ctx context.Context, req GetMaintenanceWindowRequestObject) (GetMaintenanceWindowResponseObject, error) {179	w, c, err := loadWindow(ctx, h.Pool, req.Id, "")180	if err != nil {181		return nil, err182	}183	return GetMaintenanceWindow200JSONResponse{Body: windowOut(w, c)}, nil184}185186// checkWindow validates a window and its nodes, and returns overlap warnings.187func (h *opsHandlers) checkWindow(ctx context.Context, w mt.Window) ([]string, error) {188	if err := mt.Validate(w); err != nil {189		return nil, httpx.Validation("Invalid window: " + err.Error() + ".")190	}191	if len(w.Description) > 8000 || len(w.NodeIDs) > 200 {192		return nil, httpx.Validation("description or scope is too large.")193	}194	alias := map[uuid.UUID]string{}195	if len(w.NodeIDs) > 0 {196		rows, err := h.Pool.Query(ctx, `select id, alias::text from nodes where id = any($1) and retired_at is null`, w.NodeIDs)197		if err != nil {198			return nil, err199		}200		defer rows.Close()201		for rows.Next() {202			var id uuid.UUID203			var a string204			if err := rows.Scan(&id, &a); err != nil {205				return nil, err206			}207			alias[id] = a208		}209		if err := rows.Err(); err != nil {210			return nil, err211		}212		seen := map[uuid.UUID]bool{}213		for _, n := range w.NodeIDs {214			if alias[n] == "" || seen[n] {215				return nil, httpx.ErrNotFound.With("node_id", n.String())216			}217			seen[n] = true218		}219	}220	// Overlaps with other live windows on the same node: reported, never refused.221	from := w.StartsAt222	if now := nowUTC(); now.After(from) {223		from = now.Add(-mt.MaxDuration)224	}225	to := from.Add(maxCalendarSpan)226	others, _, err := h.windowsIn(ctx, from, to, nil, nil, &w.ID)227	if err != nil {228		return nil, err229	}230	var warnings []string231	for _, o := range others {232		if o.Status == mt.StatusCancelled || o.Status == mt.StatusCompleted || len(warnings) >= 20 {233			continue234		}235		var shared []string236		for _, n := range o.NodeIDs {237			if a, ok := alias[n]; ok {238				shared = append(shared, a)239			}240		}241		if len(shared) == 0 {242			continue243		}244		if hit, at := mt.Overlaps(w, o, from, to); hit {245			sort.Strings(shared)246			warnings = append(warnings, fmt.Sprintf("Overlaps %q on %s from %s.", o.Title, strings.Join(shared, ", "), at.UTC().Format(time.RFC3339)))247		}248	}249	return warnings, nil250}251252func scopeJSON(nodes []uuid.UUID) map[string]any {253	if nodes == nil {254		nodes = []uuid.UUID{}255	}256	return map[string]any{"node_ids": nodes}257}258259func (h *opsHandlers) CreateMaintenanceWindow(ctx context.Context, req CreateMaintenanceWindowRequestObject) (CreateMaintenanceWindowResponseObject, error) {260	if req.Body == nil {261		return nil, httpx.Validation("Body required.")262	}263	b := req.Body264	me := h.userID(ctx)265	now := nowUTC()266	w := mt.Window{ID: ids.New(), Title: strings.TrimSpace(b.Title), Description: deref(b.Description), Category: mt.CategoryPlanned, StartsAt: b.StartsAt.UTC(),267		EndsAt: b.EndsAt.UTC(), Timezone: "America/Toronto", Recurrence: mt.RecurrenceNone, RecurrenceUntil: b.RecurrenceUntil, NodeIDs: b.Scope.NodeIds,268		SetMaintenanceMode: b.SetMaintenanceMode == nil || *b.SetMaintenanceMode, SilenceAlerts: b.SilenceAlerts == nil || *b.SilenceAlerts,269		Status: mt.StatusScheduled, CreatedBy: &me, CreatedAt: now, UpdatedAt: now}270	if b.Category != nil {271		w.Category = string(*b.Category)272	}273	if b.Timezone != nil {274		w.Timezone = *b.Timezone275	}276	if b.Recurrence != nil {277		w.Recurrence = string(*b.Recurrence)278	}279	warnings, err := h.checkWindow(ctx, w)280	if err != nil {281		return nil, err282	}283	err = pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {284		if _, err := tx.Exec(ctx, `insert into maintenance_windows(id, title, description, category, starts_at, ends_at, timezone, recurrence, recurrence_until, scope,285				set_maintenance_mode, silence_alerts, created_by, created_at, updated_at) values ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$14)`,286			w.ID, w.Title, w.Description, w.Category, w.StartsAt, w.EndsAt, w.Timezone, w.Recurrence, w.RecurrenceUntil, scopeJSON(w.NodeIDs),287			w.SetMaintenanceMode, w.SilenceAlerts, me, now); err != nil {288			return err289		}290		if err := mt.Changed(ctx, tx, "window_created", w, nil); err != nil {291			return err292		}293		return h.audit(ctx, tx, "maintenance.window.create", "maintenance_window", w.ID.String(), audit.Success, "", map[string]any{"title": w.Title,294			"starts_at": w.StartsAt, "ends_at": w.EndsAt, "recurrence": w.Recurrence, "nodes": len(w.NodeIDs), "overlaps": len(warnings)})295	})296	if err != nil {297		return nil, err298	}299	w, c, err := loadWindow(ctx, h.Pool, w.ID, "")300	if err != nil {301		return nil, err302	}303	out := windowOut(w, c)304	if len(warnings) > 0 {305		out.Warnings = &warnings306	}307	return CreateMaintenanceWindow201JSONResponse{Body: out}, nil308}309310func (h *opsHandlers) UpdateMaintenanceWindow(ctx context.Context, req UpdateMaintenanceWindowRequestObject) (UpdateMaintenanceWindowResponseObject, error) {311	if req.Body == nil {312		return nil, httpx.Validation("Body required.")313	}314	b := req.Body315	var out MaintenanceWindow316	err := pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {317		w, _, err := loadWindow(ctx, tx, req.Id, " for update")318		if err != nil {319			return err320		}321		if w.Status == mt.StatusCompleted || w.Status == mt.StatusCancelled {322			return httpx.Conflict("conflict", "A completed or cancelled window cannot be modified.")323		}324		reschedule := b.StartsAt != nil || b.EndsAt != nil || b.Timezone != nil || b.Recurrence != nil || b.RecurrenceUntil != nil || b.Scope != nil ||325			b.SetMaintenanceMode != nil || b.SilenceAlerts != nil326		if reschedule && w.Status == mt.StatusInProgress {327			// What the running occurrence applied must stay undoable: finish it first.328			return httpx.Conflict("conflict", "An occurrence is in progress: complete or cancel it before changing the schedule, the scope or the effects.")329		}330		if b.Title != nil {331			w.Title = strings.TrimSpace(*b.Title)332		}333		if b.Description != nil {334			w.Description = *b.Description335		}336		if b.Category != nil {337			w.Category = string(*b.Category)338		}339		if b.StartsAt != nil {340			w.StartsAt = b.StartsAt.UTC()341		}342		if b.EndsAt != nil {343			w.EndsAt = b.EndsAt.UTC()344		}345		if b.Timezone != nil {346			w.Timezone = *b.Timezone347		}348		if b.Recurrence != nil {349			w.Recurrence = string(*b.Recurrence)350			if w.Recurrence == mt.RecurrenceNone {351				w.RecurrenceUntil = nil352			}353		}354		if b.RecurrenceUntil != nil {355			w.RecurrenceUntil = b.RecurrenceUntil356		}357		if b.Scope != nil {358			w.NodeIDs = b.Scope.NodeIds359		}360		if b.SetMaintenanceMode != nil {361			w.SetMaintenanceMode = *b.SetMaintenanceMode362		}363		if b.SilenceAlerts != nil {364			w.SilenceAlerts = *b.SilenceAlerts365		}366		warnings, err := h.checkWindow(ctx, w)367		if err != nil {368			return err369		}370		now := nowUTC()371		// A rescheduled window starts afresh: the "occurrence already completed" marker no longer applies.372		if _, err := tx.Exec(ctx, `update maintenance_windows set title=$2, description=$3, category=$4, starts_at=$5, ends_at=$6, timezone=$7, recurrence=$8,373				recurrence_until=$9, scope=$10, set_maintenance_mode=$11, silence_alerts=$12, updated_at=$13,374				completed_occurrence = case when $14 then null else completed_occurrence end where id=$1`,375			w.ID, w.Title, w.Description, w.Category, w.StartsAt, w.EndsAt, w.Timezone, w.Recurrence, w.RecurrenceUntil, scopeJSON(w.NodeIDs),376			w.SetMaintenanceMode, w.SilenceAlerts, now, reschedule); err != nil {377			return err378		}379		if err := mt.Changed(ctx, tx, "window_updated", w, nil); err != nil {380			return err381		}382		if err := h.audit(ctx, tx, "maintenance.window.update", "maintenance_window", w.ID.String(), audit.Success, "", map[string]any{"title": w.Title,383			"rescheduled": reschedule, "starts_at": w.StartsAt, "ends_at": w.EndsAt, "nodes": len(w.NodeIDs)}); err != nil {384			return err385		}386		nw, c, err := loadWindow(ctx, tx, w.ID, "")387		out = windowOut(nw, c)388		if len(warnings) > 0 {389			out.Warnings = &warnings390		}391		return err392	})393	if err != nil {394		return nil, err395	}396	return UpdateMaintenanceWindow200JSONResponse{Body: out}, nil397}398399func (h *opsHandlers) CancelMaintenanceWindow(ctx context.Context, req CancelMaintenanceWindowRequestObject) (CancelMaintenanceWindowResponseObject, error) {400	err := pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {401		w, _, err := loadWindow(ctx, tx, req.Id, " for update")402		if err != nil {403			return err404		}405		if w.Status == mt.StatusCompleted || w.Status == mt.StatusCancelled {406			return httpx.Conflict("conflict", "The window is already completed or cancelled.")407		}408		// Deactivate also handles a window that is not active (nothing to undo).409		if err := mt.Deactivate(ctx, tx, w, mt.StatusCancelled, nil, nowUTC()); err != nil {410			return err411		}412		if err := mt.Changed(ctx, tx, "window_cancelled", w, w.ActivatedOccurrence); err != nil {413			return err414		}415		return h.audit(ctx, tx, "maintenance.window.cancel", "maintenance_window", w.ID.String(), audit.Success, "", map[string]any{"title": w.Title, "was_in_progress": w.Status == mt.StatusInProgress})416	})417	if err != nil {418		return nil, err419	}420	return CancelMaintenanceWindow204Response{}, nil421}422423func (h *opsHandlers) CompleteMaintenanceWindow(ctx context.Context, req CompleteMaintenanceWindowRequestObject) (CompleteMaintenanceWindowResponseObject, error) {424	note := ""425	if req.Body != nil && req.Body.Note != nil {426		note = strings.TrimSpace(*req.Body.Note)427		if note == "" || len(note) > 20000 {428			return nil, httpx.Validation("note must be 1 to 20000 characters.")429		}430	}431	var out MaintenanceWindow432	err := pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {433		w, _, err := loadWindow(ctx, tx, req.Id, " for update")434		if err != nil {435			return err436		}437		now := nowUTC()438		var occ time.Time439		switch {440		case w.Status == mt.StatusInProgress && w.ActivatedOccurrence != nil:441			occ = *w.ActivatedOccurrence442		case w.Status == mt.StatusScheduled:443			// Due but not yet applied by the scheduler: mark it done so it is never applied.444			o, ok := mt.OccurrenceAt(w, now)445			if !ok || w.CompletedOccurrence != nil && w.CompletedOccurrence.Equal(o.Start) {446				return httpx.Conflict("conflict", "No occurrence of this window is in progress.")447			}448			occ = o.Start449		default:450			return httpx.Conflict("conflict", "The window is already completed or cancelled.")451		}452		if err := mt.Deactivate(ctx, tx, w, mt.StatusAfter(w, occ), &occ, now); err != nil {453			return err454		}455		if note != "" {456			if _, err := tx.Exec(ctx, `insert into maintenance_notes(id, window_id, occurrence, author_id, body, created_at) values ($1,$2,$3,$4,$5,$6)`,457				ids.New(), w.ID, occ, h.userID(ctx), note, now); err != nil {458				return err459			}460		}461		if err := mt.Changed(ctx, tx, "window_completed", w, &occ); err != nil {462			return err463		}464		if err := h.audit(ctx, tx, "maintenance.window.complete", "maintenance_window", w.ID.String(), audit.Success, "", map[string]any{"title": w.Title, "occurrence": occ, "note": note != ""}); err != nil {465			return err466		}467		nw, c, err := loadWindow(ctx, tx, w.ID, "")468		out = windowOut(nw, c)469		return err470	})471	if err != nil {472		return nil, err473	}474	return CompleteMaintenanceWindow200JSONResponse{Body: out}, nil475}476477// ── Notes ──────────────────────────────────────────────────────────────────478479const noteSelect = `select m.id, m.window_id, m.node_id, n.alias::text, m.occurrence, m.author_id, u.display_name, m.body, m.pinned, m.created_at, m.edited_at480	from maintenance_notes m join users u on u.id=m.author_id left join nodes n on n.id=m.node_id`481482func scanNote(r pgx.Row) (MaintenanceNote, error) {483	var n MaintenanceNote484	err := r.Scan(&n.Id, &n.WindowId, &n.NodeId, &n.NodeAlias, &n.Occurrence, &n.AuthorId, &n.AuthorDisplayName, &n.Body, &n.Pinned, &n.CreatedAt, &n.EditedAt)485	return n, err486}487488func noteChanged(ctx context.Context, tx pgx.Tx, change string, n MaintenanceNote) error {489	p := map[string]any{"change": change, "note_id": n.Id}490	if n.WindowId != nil {491		p["window_id"] = *n.WindowId492	}493	if n.NodeId != nil {494		p["node_ids"] = []uuid.UUID{*n.NodeId}495	}496	if n.Occurrence != nil {497		p["occurrence"] = *n.Occurrence498	}499	return events.Publish(ctx, tx, "maintenance.changed", p)500}501502func (h *opsHandlers) ListMaintenanceNotes(ctx context.Context, req ListMaintenanceNotesRequestObject) (ListMaintenanceNotesResponseObject, error) {503	p := req.Params504	var w where505	w.add("m.deleted_at is null")506	if p.WindowId != nil {507		w.add("m.window_id = ?", *p.WindowId)508	}509	if p.NodeId != nil {510		w.add("m.node_id = ?", *p.NodeId)511	}512	if p.Occurrence != nil {513		w.add("m.occurrence = ?", *p.Occurrence)514	}515	if p.Q != nil && strings.TrimSpace(*p.Q) != "" {516		q := strings.TrimSpace(*p.Q)517		if len(q) > 120 {518			return nil, httpx.Validation("q is too long.")519		}520		// Case-insensitive substring; the text is a bound parameter and its wildcards are escaped.521		w.add(`m.body ilike '%' || ? || '%' escape '\'`, escapeLike(q))522	}523	if p.Cursor != nil && *p.Cursor != "" {524		// Cursor = "<pinned 0|1>.<id of the last item>" following the (pinned desc, id desc) order.525		pin, idText, ok := strings.Cut(*p.Cursor, ".")526		id, err := uuid.Parse(idText)527		pv, perr := strconv.Atoi(pin)528		if !ok || err != nil || perr != nil || pv < 0 || pv > 1 {529			return nil, httpx.Validation("Invalid cursor.")530		}531		w.add("(m.pinned::int, m.id) < (?::int, ?::uuid)", pv, id)532	}533	limit := pageLimit(p.Limit)534	rows, err := h.Pool.Query(ctx, noteSelect+w.sql()+" order by m.pinned desc, m.id desc limit "+w.arg(limit+1), w.args...)535	if err != nil {536		return nil, err537	}538	items, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (MaintenanceNote, error) { return scanNote(r) })539	if err != nil {540		return nil, err541	}542	out := MaintenanceNoteList{Items: items}543	if len(items) > limit {544		out.Items = items[:limit]545		last := items[limit-1]546		pin := 0547		if last.Pinned {548			pin = 1549		}550		out.NextCursor = ptr(fmt.Sprintf("%d.%s", pin, last.Id))551	}552	if out.Items == nil {553		out.Items = []MaintenanceNote{}554	}555	return ListMaintenanceNotes200JSONResponse{Body: out}, nil556}557558func (h *opsHandlers) CreateMaintenanceNote(ctx context.Context, req CreateMaintenanceNoteRequestObject) (CreateMaintenanceNoteResponseObject, error) {559	if req.Body == nil {560		return nil, httpx.Validation("Body required.")561	}562	b := req.Body563	body := strings.TrimSpace(b.Body)564	switch {565	case body == "" || len(body) > 20000:566		return nil, httpx.Validation("body must be 1 to 20000 characters.")567	case b.WindowId == nil && b.NodeId == nil:568		return nil, httpx.Validation("At least one of window_id and node_id is required.")569	case b.Occurrence != nil && b.WindowId == nil:570		return nil, httpx.Validation("occurrence requires window_id.")571	}572	if b.NodeId != nil {573		var one int574		if err := h.Pool.QueryRow(ctx, `select 1 from nodes where id=$1`, *b.NodeId).Scan(&one); err != nil {575			return nil, notFound(err)576		}577	}578	if b.WindowId != nil {579		w, _, err := loadWindow(ctx, h.Pool, *b.WindowId, "")580		if err != nil {581			return nil, err582		}583		if b.Occurrence != nil {584			if _, ok := mt.OccurrenceStarting(w, *b.Occurrence); !ok {585				return nil, httpx.Validation("occurrence is not the start of an occurrence of this window.")586			}587		}588	}589	id := ids.New()590	var out MaintenanceNote591	err := pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {592		if _, err := tx.Exec(ctx, `insert into maintenance_notes(id, window_id, node_id, occurrence, author_id, body, pinned, created_at) values ($1,$2,$3,$4,$5,$6,$7,$8)`,593			id, b.WindowId, b.NodeId, b.Occurrence, h.userID(ctx), body, deref(b.Pinned), nowUTC()); err != nil {594			return err595		}596		var err error597		if out, err = scanNote(tx.QueryRow(ctx, noteSelect+` where m.id=$1`, id)); err != nil {598			return err599		}600		if err := noteChanged(ctx, tx, "note_created", out); err != nil {601			return err602		}603		// The note text itself stays out of the audit log (it is content, and may be long).604		return h.audit(ctx, tx, "maintenance.note.create", "maintenance_note", id.String(), audit.Success, "", map[string]any{"window_id": b.WindowId, "node_id": b.NodeId, "pinned": out.Pinned, "length": len(body)})605	})606	if err != nil {607		return nil, err608	}609	return CreateMaintenanceNote201JSONResponse{Body: out}, nil610}611612func (h *opsHandlers) UpdateMaintenanceNote(ctx context.Context, req UpdateMaintenanceNoteRequestObject) (UpdateMaintenanceNoteResponseObject, error) {613	if req.Body == nil || (req.Body.Body == nil && req.Body.Pinned == nil) {614		return nil, httpx.Validation("Nothing to change.")615	}616	b := req.Body617	me := h.userID(ctx)618	var out MaintenanceNote619	var forbidden bool620	err := pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {621		n, err := scanNote(tx.QueryRow(ctx, noteSelect+` where m.id=$1 and m.deleted_at is null for update of m`, req.Id))622		if err != nil {623			return notFound(err)624		}625		now := nowUTC()626		if b.Body != nil {627			body := strings.TrimSpace(*b.Body)628			if body == "" || len(body) > 20000 {629				return httpx.Validation("body must be 1 to 20000 characters.")630			}631			if n.AuthorId != me {632				forbidden = true633				return httpx.ErrForbidden.With("reason", "Only the author can edit the text of a note.")634			}635			if body != n.Body {636				if _, err := tx.Exec(ctx, `update maintenance_notes set body=$2, edited_at=$3 where id=$1`, req.Id, body, now); err != nil {637					return err638				}639			}640		}641		if b.Pinned != nil {642			if _, err := tx.Exec(ctx, `update maintenance_notes set pinned=$2 where id=$1`, req.Id, *b.Pinned); err != nil {643				return err644			}645		}646		if out, err = scanNote(tx.QueryRow(ctx, noteSelect+` where m.id=$1`, req.Id)); err != nil {647			return err648		}649		if err := noteChanged(ctx, tx, "note_updated", out); err != nil {650			return err651		}652		return h.audit(ctx, tx, "maintenance.note.update", "maintenance_note", req.Id.String(), audit.Success, "", map[string]any{"body_changed": b.Body != nil, "pinned": b.Pinned})653	})654	if forbidden {655		h.audit(ctx, h.Pool, "maintenance.note.update", "maintenance_note", req.Id.String(), audit.Denied, "not the author", nil)656	}657	if err != nil {658		return nil, err659	}660	return UpdateMaintenanceNote200JSONResponse{Body: out}, nil661}662663func (h *opsHandlers) DeleteMaintenanceNote(ctx context.Context, req DeleteMaintenanceNoteRequestObject) (DeleteMaintenanceNoteResponseObject, error) {664	me := h.userID(ctx)665	n, err := scanNote(h.Pool.QueryRow(ctx, noteSelect+` where m.id=$1 and m.deleted_at is null`, req.Id))666	if err != nil {667		return nil, notFound(err)668	}669	if n.AuthorId != me {670		// Someone else's note: alerts.manage (administrators and owners by default). The refusal is audited by authorize.671		if err := h.authorize(ctx, authz.AlertsManage, authz.Resource{Kind: "maintenance_note", ID: req.Id.String()}); err != nil {672			return nil, err673		}674	}675	err = pgx.BeginFunc(ctx, h.Pool, func(tx pgx.Tx) error {676		tag, err := tx.Exec(ctx, `update maintenance_notes set deleted_at=$2 where id=$1 and deleted_at is null`, req.Id, nowUTC())677		if err != nil {678			return err679		}680		if tag.RowsAffected() == 0 {681			return httpx.ErrNotFound682		}683		if err := noteChanged(ctx, tx, "note_deleted", n); err != nil {684			return err685		}686		return h.audit(ctx, tx, "maintenance.note.delete", "maintenance_note", req.Id.String(), audit.Success, "", map[string]any{"own_note": n.AuthorId == me})687	})688	if err != nil {689		return nil, err690	}691	return DeleteMaintenanceNote204Response{}, nil692}693694// ── iCalendar ──────────────────────────────────────────────────────────────695696func (h *opsHandlers) ExportMaintenanceCalendar(ctx context.Context, req ExportMaintenanceCalendarRequestObject) (ExportMaintenanceCalendarResponseObject, error) {697	from, to, err := calendarRange(req.Params.From, req.Params.To, -30*24*time.Hour, maxCalendarSpan)698	if err != nil {699		return nil, err700	}701	ws, _, err := h.windowsIn(ctx, from, to, req.Params.NodeId, nil, nil)702	if err != nil {703		return nil, err704	}705	domain := "mcc.invalid"706	if u, err := url.Parse(h.Cfg.PublicOrigin); err == nil && u.Hostname() != "" {707		domain = u.Hostname()708	}709	var buf bytes.Buffer710	if err := mt.WriteICS(&buf, ws, from, to, nowUTC(), domain); err != nil {711		return nil, err712	}713	return ExportMaintenanceCalendar200TextcalendarResponse{Body: &buf, ContentLength: int64(buf.Len()),714		Headers: ExportMaintenanceCalendar200ResponseHeaders{ContentDisposition: ptr(`attachment; filename="mcc-maintenance.ics"`)}}, nil715}716
Files main
Menu

Theme