|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "net/url" |
| 9 | + "os" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + "unicode/utf8" |
| 14 | + |
| 15 | + "github.com/flashcatcloud/go-flashduty" |
| 16 | + "github.com/spf13/cobra" |
| 17 | +) |
| 18 | + |
| 19 | +const maxPostMortemContentIdempotencyKeyRunes = 128 |
| 20 | + |
| 21 | +func newIncidentPostMortemContentResetCmd() *cobra.Command { |
| 22 | + var ( |
| 23 | + markdownFile string |
| 24 | + expectedRevision int64 |
| 25 | + idempotencyKey string |
| 26 | + ) |
| 27 | + |
| 28 | + cmd := &cobra.Command{ |
| 29 | + Use: "post-mortem-content-reset <post-mortem-id>", |
| 30 | + Short: "Reset post-mortem Markdown content", |
| 31 | + Long: curatedLong( |
| 32 | + "Replace the collaborative Markdown body of a drafting post-mortem report in one shot.\n\n"+ |
| 33 | + "Read Markdown from --markdown-file (or \"-\" for stdin). The entire file is sent as-is; leading and trailing content is preserved. Empty Markdown is rejected.\n\n"+ |
| 34 | + "--expected-revision guards against overwriting a concurrent edit: the reset only succeeds when the document's current revision equals it, and 0 is valid (first write / empty document). Negative values are rejected. When omitted, the CLI first fetches the report's current revision via the post-mortem info endpoint and uses that; pass it explicitly for strict concurrency control, when the caller already holds a revision and must fail on any intervening write.\n\n"+ |
| 35 | + "--idempotency-key is required, must be non-empty, and at most 128 Unicode characters.", |
| 36 | + "Incidents", |
| 37 | + "PostMortemWriteResetContent", |
| 38 | + ), |
| 39 | + Args: requireExactArg("post-mortem-id"), |
| 40 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 41 | + return runCommand(cmd, args, func(ctx *RunContext) error { |
| 42 | + markdown, err := readPostMortemMarkdownFile(markdownFile) |
| 43 | + if err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + if err := validatePostMortemContentResetFlags(idempotencyKey); err != nil { |
| 47 | + return err |
| 48 | + } |
| 49 | + |
| 50 | + revision := expectedRevision |
| 51 | + if cmd.Flags().Changed("expected-revision") { |
| 52 | + if revision < 0 { |
| 53 | + return fmt.Errorf("--expected-revision must be >= 0") |
| 54 | + } |
| 55 | + } else { |
| 56 | + revision, err = currentPostMortemRevisionFn(ctx, ctx.Args[0]) |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + out, _, err := ctx.Client.Incidents.PostMortemWriteResetContent(cmdContext(ctx.Cmd), &flashduty.ResetPostMortemContentRequest{ |
| 63 | + PostMortemID: ctx.Args[0], |
| 64 | + Markdown: markdown, |
| 65 | + ExpectedRevision: flashduty.Int64(revision), |
| 66 | + IdempotencyKey: idempotencyKey, |
| 67 | + }) |
| 68 | + if err != nil { |
| 69 | + return err |
| 70 | + } |
| 71 | + |
| 72 | + human := fmt.Sprintf( |
| 73 | + "Reset post-mortem content for %s: generation %d→%d, revision %d→%d", |
| 74 | + out.PostMortemID, |
| 75 | + out.PreviousGeneration, |
| 76 | + out.Generation, |
| 77 | + out.PreviousRevision, |
| 78 | + out.Revision, |
| 79 | + ) |
| 80 | + return ctx.WriteResultJSON(out, human) |
| 81 | + }) |
| 82 | + }, |
| 83 | + } |
| 84 | + |
| 85 | + cmd.Flags().StringVar(&markdownFile, "markdown-file", "", "Path to Markdown content, or \"-\" to read stdin (required)") |
| 86 | + cmd.Flags().Int64Var(&expectedRevision, "expected-revision", 0, "Expected document revision; 0 is valid (optional: when omitted, the current revision is fetched via post-mortem info first)") |
| 87 | + cmd.Flags().StringVar(&idempotencyKey, "idempotency-key", "", "Idempotency key for safe retries; max 128 Unicode characters (required)") |
| 88 | + _ = cmd.MarkFlagRequired("markdown-file") |
| 89 | + _ = cmd.MarkFlagRequired("idempotency-key") |
| 90 | + |
| 91 | + return cmd |
| 92 | +} |
| 93 | + |
| 94 | +func validatePostMortemContentResetFlags(idempotencyKey string) error { |
| 95 | + if idempotencyKey == "" { |
| 96 | + return fmt.Errorf("--idempotency-key must not be empty") |
| 97 | + } |
| 98 | + if utf8.RuneCountInString(idempotencyKey) > maxPostMortemContentIdempotencyKeyRunes { |
| 99 | + return fmt.Errorf("--idempotency-key must be at most %d Unicode characters", maxPostMortemContentIdempotencyKeyRunes) |
| 100 | + } |
| 101 | + return nil |
| 102 | +} |
| 103 | + |
| 104 | +// currentPostMortemRevisionFn resolves the current collaboration revision of a |
| 105 | +// post-mortem report. It is a package variable so tests can stub it. |
| 106 | +var currentPostMortemRevisionFn = fetchCurrentPostMortemRevision |
| 107 | + |
| 108 | +// fetchCurrentPostMortemRevision GETs /incident/post-mortem/info and reads |
| 109 | +// data.meta.revision. go-flashduty v0.5.11's typed PostMortemMeta does not |
| 110 | +// expose the revision field yet (the server returns it), so this request goes |
| 111 | +// out directly, reusing the SDK client's base URL and the same credential |
| 112 | +// resolution as defaultNewClient — including broker mode, where the sentinel |
| 113 | +// app_key is overwritten by the broker as the request egresses. |
| 114 | +// |
| 115 | +// TODO: switch to ctx.Client.Incidents.PostMortemInfo once go-flashduty |
| 116 | +// exposes meta.revision on PostMortemMeta. |
| 117 | +func fetchCurrentPostMortemRevision(ctx *RunContext, postMortemID string) (int64, error) { |
| 118 | + cfg, err := loadResolvedConfig() |
| 119 | + if err != nil { |
| 120 | + return 0, err |
| 121 | + } |
| 122 | + |
| 123 | + appKey := cfg.AppKey |
| 124 | + hc := &http.Client{Timeout: 30 * time.Second} |
| 125 | + if fdStr := os.Getenv("FLASHDUTY_CRED_FD"); fdStr != "" { |
| 126 | + fd, perr := strconv.Atoi(fdStr) |
| 127 | + // fds 0/1/2 are stdio; see defaultNewClient. |
| 128 | + if perr != nil || fd < 3 { |
| 129 | + return 0, fmt.Errorf("invalid FLASHDUTY_CRED_FD=%q", fdStr) |
| 130 | + } |
| 131 | + bc := newBrokerHTTPClient(fd) |
| 132 | + if bc == nil { |
| 133 | + return 0, errBrokerUnsupported |
| 134 | + } |
| 135 | + hc = bc |
| 136 | + appKey = "broker-sentinel" |
| 137 | + } else if appKey == "" { |
| 138 | + return 0, fmt.Errorf("no app key configured. Run 'flashduty login' or set FLASHDUTY_APP_KEY") |
| 139 | + } |
| 140 | + |
| 141 | + rel, err := url.Parse("incident/post-mortem/info") |
| 142 | + if err != nil { |
| 143 | + return 0, fmt.Errorf("failed to build post-mortem info URL: %w", err) |
| 144 | + } |
| 145 | + u := ctx.Client.BaseURL.ResolveReference(rel) |
| 146 | + q := u.Query() |
| 147 | + q.Set("post_mortem_id", postMortemID) |
| 148 | + q.Set("app_key", appKey) |
| 149 | + u.RawQuery = q.Encode() |
| 150 | + |
| 151 | + req, err := http.NewRequestWithContext(cmdContext(ctx.Cmd), http.MethodGet, u.String(), nil) |
| 152 | + if err != nil { |
| 153 | + return 0, fmt.Errorf("failed to build post-mortem info request: %w", err) |
| 154 | + } |
| 155 | + req.Header.Set("Accept", "application/json") |
| 156 | + |
| 157 | + resp, err := hc.Do(req) |
| 158 | + if err != nil { |
| 159 | + return 0, fmt.Errorf("failed to fetch post-mortem info for %s: %w", postMortemID, err) |
| 160 | + } |
| 161 | + defer func() { _ = resp.Body.Close() }() |
| 162 | + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) |
| 163 | + if err != nil { |
| 164 | + return 0, fmt.Errorf("failed to read post-mortem info response: %w", err) |
| 165 | + } |
| 166 | + |
| 167 | + var env struct { |
| 168 | + Error *struct { |
| 169 | + Code string `json:"code"` |
| 170 | + Message string `json:"message"` |
| 171 | + } `json:"error"` |
| 172 | + Data struct { |
| 173 | + Meta struct { |
| 174 | + Revision *int64 `json:"revision"` |
| 175 | + } `json:"meta"` |
| 176 | + } `json:"data"` |
| 177 | + } |
| 178 | + if err := json.Unmarshal(body, &env); err != nil { |
| 179 | + return 0, fmt.Errorf("failed to decode post-mortem info response: %w", err) |
| 180 | + } |
| 181 | + if resp.StatusCode != http.StatusOK || (env.Error != nil && env.Error.Code != "" && env.Error.Code != "OK") { |
| 182 | + msg := http.StatusText(resp.StatusCode) |
| 183 | + if env.Error != nil && env.Error.Message != "" { |
| 184 | + msg = env.Error.Message |
| 185 | + } |
| 186 | + return 0, fmt.Errorf("failed to fetch post-mortem info for %s: %s", postMortemID, msg) |
| 187 | + } |
| 188 | + if env.Data.Meta.Revision == nil { |
| 189 | + return 0, fmt.Errorf("post-mortem info for %s did not report a revision; pass --expected-revision explicitly", postMortemID) |
| 190 | + } |
| 191 | + return *env.Data.Meta.Revision, nil |
| 192 | +} |
| 193 | + |
| 194 | +// readPostMortemMarkdownFile loads Markdown bytes without trimming. Path "-" |
| 195 | +// reads the injectable stdinReader so tests never touch the real stdin and |
| 196 | +// absent flags never block on an empty pipe. |
| 197 | +func readPostMortemMarkdownFile(path string) (string, error) { |
| 198 | + path = strings.TrimSpace(path) |
| 199 | + if path == "" { |
| 200 | + return "", fmt.Errorf("--markdown-file is required") |
| 201 | + } |
| 202 | + |
| 203 | + var ( |
| 204 | + b []byte |
| 205 | + err error |
| 206 | + ) |
| 207 | + if path == "-" { |
| 208 | + b, err = io.ReadAll(stdinReader) |
| 209 | + if err != nil { |
| 210 | + return "", fmt.Errorf("failed to read markdown from stdin: %w", err) |
| 211 | + } |
| 212 | + } else { |
| 213 | + b, err = os.ReadFile(path) |
| 214 | + if err != nil { |
| 215 | + return "", fmt.Errorf("failed to read markdown file: %w", err) |
| 216 | + } |
| 217 | + } |
| 218 | + if len(b) == 0 { |
| 219 | + return "", fmt.Errorf("markdown content must not be empty") |
| 220 | + } |
| 221 | + return string(b), nil |
| 222 | +} |
0 commit comments