| 1 | // SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | |
| 3 | // Package issues owns the issue + comment + label + milestone domain |
| 4 | // logic. Web handlers call into this package; the package owns |
| 5 | // transactions, cross-reference parsing, and event emission. |
| 6 | // |
| 7 | // PR-specific behavior lives in the future internal/pulls/ package |
| 8 | // (S22) — but PRs reuse the `issues` and `issue_comments` tables, so |
| 9 | // the queries here are kind-discriminated to keep the surface clean. |
| 10 | package issues |
| 11 | |
| 12 | import ( |
| 13 | "context" |
| 14 | "errors" |
| 15 | "fmt" |
| 16 | "log/slog" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "time" |
| 20 | |
| 21 | "github.com/jackc/pgx/v5" |
| 22 | "github.com/jackc/pgx/v5/pgtype" |
| 23 | "github.com/jackc/pgx/v5/pgxpool" |
| 24 | |
| 25 | "github.com/tenseleyFlow/shithub/internal/auth/audit" |
| 26 | "github.com/tenseleyFlow/shithub/internal/auth/throttle" |
| 27 | issuesdb "github.com/tenseleyFlow/shithub/internal/issues/sqlc" |
| 28 | mdrender "github.com/tenseleyFlow/shithub/internal/markdown" |
| 29 | ) |
| 30 | |
| 31 | // Deps wires this package against the rest of the runtime. Pool is |
| 32 | // required; Limiter governs the comment-create rate limit; Logger is |
| 33 | // optional (falls back to discarding when nil). |
| 34 | type Deps struct { |
| 35 | Pool *pgxpool.Pool |
| 36 | Limiter *throttle.Limiter |
| 37 | Logger *slog.Logger |
| 38 | // Audit is optional; when non-nil, state-changing orchestrator |
| 39 | // calls (SetState, SetLock, AddComment) record an audit row. The |
| 40 | // repo lifecycle package writes audit rows directly via deps.Audit; |
| 41 | // this field ensures issues/PR mutations are equally traceable |
| 42 | // (S00-S25 audit, M). |
| 43 | Audit *audit.Recorder |
| 44 | } |
| 45 | |
| 46 | // Errors returned by the orchestrator. Handlers map these to status |
| 47 | // codes + friendly user-facing messages. |
| 48 | var ( |
| 49 | ErrEmptyTitle = errors.New("issues: title is required") |
| 50 | ErrTitleTooLong = errors.New("issues: title too long (max 256)") |
| 51 | ErrBodyTooLong = errors.New("issues: body too long") |
| 52 | ErrEmptyComment = errors.New("issues: comment body is required") |
| 53 | ErrCommentTooLong = errors.New("issues: comment too long") |
| 54 | ErrIssueLocked = errors.New("issues: issue is locked") |
| 55 | ErrCommentRateLimit = errors.New("issues: comment rate limit exceeded") |
| 56 | ErrLabelExists = errors.New("issues: label name already taken on this repo") |
| 57 | ErrLabelInvalidColor = errors.New("issues: label color must be 6 hex chars") |
| 58 | ErrMilestoneExists = errors.New("issues: milestone title already taken on this repo") |
| 59 | ErrIssueNotFound = errors.New("issues: issue not found") |
| 60 | ) |
| 61 | |
| 62 | // CreateParams describes a new-issue request. |
| 63 | type CreateParams struct { |
| 64 | RepoID int64 |
| 65 | AuthorUserID int64 // 0 means anonymous (unsupported in S21; handler enforces) |
| 66 | Title string |
| 67 | Body string |
| 68 | // Kind defaults to "issue"; PR creation in S22 passes "pr". |
| 69 | Kind string |
| 70 | } |
| 71 | |
| 72 | // Create validates inputs, allocates a per-repo number atomically, |
| 73 | // inserts the row, renders the body's markdown, and returns the |
| 74 | // fresh issue. Default labels live with repo create; per-issue |
| 75 | // label/assignee/milestone application is a separate call. |
| 76 | // |
| 77 | // Cross-reference indexing fires asynchronously inside the same tx |
| 78 | // via insertReferencesFromBody — refs to other issues create |
| 79 | // `issue_references` rows + a `referenced` event on the target. |
| 80 | func Create(ctx context.Context, deps Deps, p CreateParams) (issuesdb.Issue, error) { |
| 81 | title := strings.TrimSpace(p.Title) |
| 82 | if title == "" { |
| 83 | return issuesdb.Issue{}, ErrEmptyTitle |
| 84 | } |
| 85 | if len(title) > 256 { |
| 86 | return issuesdb.Issue{}, ErrTitleTooLong |
| 87 | } |
| 88 | if len(p.Body) > 65535 { |
| 89 | return issuesdb.Issue{}, ErrBodyTooLong |
| 90 | } |
| 91 | kind := p.Kind |
| 92 | if kind == "" { |
| 93 | kind = "issue" |
| 94 | } |
| 95 | |
| 96 | tx, err := deps.Pool.Begin(ctx) |
| 97 | if err != nil { |
| 98 | return issuesdb.Issue{}, fmt.Errorf("begin: %w", err) |
| 99 | } |
| 100 | committed := false |
| 101 | defer func() { |
| 102 | if !committed { |
| 103 | _ = tx.Rollback(ctx) |
| 104 | } |
| 105 | }() |
| 106 | |
| 107 | q := issuesdb.New() |
| 108 | if err := q.EnsureRepoIssueCounter(ctx, tx, p.RepoID); err != nil { |
| 109 | return issuesdb.Issue{}, fmt.Errorf("counter init: %w", err) |
| 110 | } |
| 111 | num, err := q.AllocateIssueNumber(ctx, tx, p.RepoID) |
| 112 | if err != nil { |
| 113 | return issuesdb.Issue{}, fmt.Errorf("allocate number: %w", err) |
| 114 | } |
| 115 | |
| 116 | row, err := q.CreateIssue(ctx, tx, issuesdb.CreateIssueParams{ |
| 117 | RepoID: p.RepoID, |
| 118 | Number: num, |
| 119 | Kind: issuesdb.IssueKind(kind), |
| 120 | Title: title, |
| 121 | Body: p.Body, |
| 122 | AuthorUserID: pgtype.Int8{Int64: p.AuthorUserID, Valid: p.AuthorUserID != 0}, |
| 123 | }) |
| 124 | if err != nil { |
| 125 | return issuesdb.Issue{}, fmt.Errorf("insert: %w", err) |
| 126 | } |
| 127 | |
| 128 | // Render markdown for the cached body html. |
| 129 | html, mentions := renderBody(ctx, deps, p.Body) |
| 130 | row.BodyHtmlCached = pgtype.Text{String: html, Valid: html != ""} |
| 131 | |
| 132 | if err := q.UpdateIssueTitleBody(ctx, tx, issuesdb.UpdateIssueTitleBodyParams{ |
| 133 | ID: row.ID, Title: row.Title, Body: row.Body, |
| 134 | BodyHtmlCached: pgtype.Text{String: html, Valid: html != ""}, |
| 135 | }); err != nil { |
| 136 | return issuesdb.Issue{}, fmt.Errorf("update html: %w", err) |
| 137 | } |
| 138 | |
| 139 | if err := insertReferencesFromBody(ctx, tx, deps, row, p.Body, "issue_body", row.ID); err != nil { |
| 140 | return issuesdb.Issue{}, fmt.Errorf("refs: %w", err) |
| 141 | } |
| 142 | |
| 143 | // Emit the domain event in the same tx as the issue row so a |
| 144 | // rollback drops both. Mention resolution happens *after* commit |
| 145 | // to avoid holding the row lock through user-id lookups; the |
| 146 | // fan-out worker reads payload.mentions to drive @-ping |
| 147 | // recipients. |
| 148 | mentionIDs := mentionUserIDs(ctx, deps.Pool, mentions) |
| 149 | repoVis, _ := repoVisibilityPublic(ctx, tx, p.RepoID) |
| 150 | eventKind := "issue_created" |
| 151 | if kind == "pr" { |
| 152 | eventKind = "pr_opened" |
| 153 | } |
| 154 | if err := emitIssueEventTx(ctx, tx, eventKind, row, p.AuthorUserID, repoVis, mentionIDs); err != nil { |
| 155 | return issuesdb.Issue{}, fmt.Errorf("emit event: %w", err) |
| 156 | } |
| 157 | |
| 158 | if err := tx.Commit(ctx); err != nil { |
| 159 | return issuesdb.Issue{}, fmt.Errorf("commit: %w", err) |
| 160 | } |
| 161 | committed = true |
| 162 | return row, nil |
| 163 | } |
| 164 | |
| 165 | // CommentCreateParams is the input for AddComment. |
| 166 | type CommentCreateParams struct { |
| 167 | IssueID int64 |
| 168 | AuthorUserID int64 |
| 169 | Body string |
| 170 | // IsCollab signals that the actor's policy.Can role is at least |
| 171 | // triage. Used to bypass the locked-issue gate. |
| 172 | IsCollab bool |
| 173 | } |
| 174 | |
| 175 | // AddComment validates, applies the rate limit, inserts the comment, |
| 176 | // and indexes references. Returns the fresh comment. |
| 177 | func AddComment(ctx context.Context, deps Deps, p CommentCreateParams) (issuesdb.IssueComment, error) { |
| 178 | body := strings.TrimSpace(p.Body) |
| 179 | if body == "" { |
| 180 | return issuesdb.IssueComment{}, ErrEmptyComment |
| 181 | } |
| 182 | if len(body) > 65535 { |
| 183 | return issuesdb.IssueComment{}, ErrCommentTooLong |
| 184 | } |
| 185 | if deps.Limiter != nil && p.AuthorUserID != 0 { |
| 186 | if err := deps.Limiter.Hit(ctx, deps.Pool, throttle.Limit{ |
| 187 | Scope: "issue_comment", |
| 188 | Identifier: fmt.Sprintf("user:%d", p.AuthorUserID), |
| 189 | Max: 20, |
| 190 | Window: time.Hour, |
| 191 | }); err != nil { |
| 192 | return issuesdb.IssueComment{}, ErrCommentRateLimit |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | q := issuesdb.New() |
| 197 | issue, err := q.GetIssueByID(ctx, deps.Pool, p.IssueID) |
| 198 | if err != nil { |
| 199 | if errors.Is(err, pgx.ErrNoRows) { |
| 200 | return issuesdb.IssueComment{}, ErrIssueNotFound |
| 201 | } |
| 202 | return issuesdb.IssueComment{}, err |
| 203 | } |
| 204 | if issue.Locked && !p.IsCollab { |
| 205 | return issuesdb.IssueComment{}, ErrIssueLocked |
| 206 | } |
| 207 | |
| 208 | html, mentions := renderBody(ctx, deps, body) |
| 209 | |
| 210 | tx, err := deps.Pool.Begin(ctx) |
| 211 | if err != nil { |
| 212 | return issuesdb.IssueComment{}, err |
| 213 | } |
| 214 | committed := false |
| 215 | defer func() { |
| 216 | if !committed { |
| 217 | _ = tx.Rollback(ctx) |
| 218 | } |
| 219 | }() |
| 220 | |
| 221 | c, err := q.CreateIssueComment(ctx, tx, issuesdb.CreateIssueCommentParams{ |
| 222 | IssueID: p.IssueID, |
| 223 | AuthorUserID: pgtype.Int8{Int64: p.AuthorUserID, Valid: p.AuthorUserID != 0}, |
| 224 | Body: body, |
| 225 | BodyHtmlCached: pgtype.Text{String: html, Valid: html != ""}, |
| 226 | }) |
| 227 | if err != nil { |
| 228 | return issuesdb.IssueComment{}, err |
| 229 | } |
| 230 | |
| 231 | if err := insertReferencesFromBody(ctx, tx, deps, issue, body, "comment_body", c.ID); err != nil { |
| 232 | return issuesdb.IssueComment{}, err |
| 233 | } |
| 234 | |
| 235 | mentionIDs := mentionUserIDs(ctx, deps.Pool, mentions) |
| 236 | repoVis, _ := repoVisibilityPublic(ctx, tx, issue.RepoID) |
| 237 | commentKind := "issue_comment_created" |
| 238 | if issue.Kind == issuesdb.IssueKindPr { |
| 239 | commentKind = "pr_comment_created" |
| 240 | } |
| 241 | if err := emitCommentEventTx(ctx, tx, commentKind, issue, c.ID, p.AuthorUserID, repoVis, mentionIDs); err != nil { |
| 242 | return issuesdb.IssueComment{}, fmt.Errorf("emit event: %w", err) |
| 243 | } |
| 244 | |
| 245 | if err := tx.Commit(ctx); err != nil { |
| 246 | return issuesdb.IssueComment{}, err |
| 247 | } |
| 248 | committed = true |
| 249 | if deps.Audit != nil { |
| 250 | _ = deps.Audit.Record(ctx, deps.Pool, p.AuthorUserID, |
| 251 | audit.ActionIssueCommentCreated, audit.TargetIssue, p.IssueID, |
| 252 | map[string]any{"comment_id": c.ID}) |
| 253 | } |
| 254 | return c, nil |
| 255 | } |
| 256 | |
| 257 | // EditParams describes a title/body update applied to an existing |
| 258 | // issue. Both fields are optional pointers: nil means "leave as-is". |
| 259 | type EditParams struct { |
| 260 | IssueID int64 |
| 261 | Title *string |
| 262 | Body *string |
| 263 | } |
| 264 | |
| 265 | // Edit updates an issue's title and/or body, re-rendering the cached |
| 266 | // markdown body and re-indexing cross-references. Pure plumbing: the |
| 267 | // caller is responsible for the policy check before invoking. |
| 268 | func Edit(ctx context.Context, deps Deps, p EditParams) (issuesdb.Issue, error) { |
| 269 | q := issuesdb.New() |
| 270 | tx, err := deps.Pool.Begin(ctx) |
| 271 | if err != nil { |
| 272 | return issuesdb.Issue{}, fmt.Errorf("begin: %w", err) |
| 273 | } |
| 274 | committed := false |
| 275 | defer func() { |
| 276 | if !committed { |
| 277 | _ = tx.Rollback(ctx) |
| 278 | } |
| 279 | }() |
| 280 | cur, err := q.GetIssueByID(ctx, tx, p.IssueID) |
| 281 | if err != nil { |
| 282 | return issuesdb.Issue{}, err |
| 283 | } |
| 284 | title := cur.Title |
| 285 | if p.Title != nil { |
| 286 | title = strings.TrimSpace(*p.Title) |
| 287 | if title == "" { |
| 288 | return issuesdb.Issue{}, ErrEmptyTitle |
| 289 | } |
| 290 | if len(title) > 256 { |
| 291 | return issuesdb.Issue{}, ErrTitleTooLong |
| 292 | } |
| 293 | } |
| 294 | body := cur.Body |
| 295 | if p.Body != nil { |
| 296 | body = *p.Body |
| 297 | if len(body) > 65535 { |
| 298 | return issuesdb.Issue{}, ErrBodyTooLong |
| 299 | } |
| 300 | } |
| 301 | html, _ := renderBody(ctx, deps, body) |
| 302 | if err := q.UpdateIssueTitleBody(ctx, tx, issuesdb.UpdateIssueTitleBodyParams{ |
| 303 | ID: p.IssueID, Title: title, Body: body, |
| 304 | BodyHtmlCached: pgtype.Text{String: html, Valid: html != ""}, |
| 305 | }); err != nil { |
| 306 | return issuesdb.Issue{}, fmt.Errorf("update: %w", err) |
| 307 | } |
| 308 | // Re-index cross-references when the body changed; new refs land, |
| 309 | // stale ones are no longer indexed (existing rows are left alone, |
| 310 | // matching how GitHub leaves prior references in place). |
| 311 | if p.Body != nil { |
| 312 | fresh, _ := q.GetIssueByID(ctx, tx, p.IssueID) |
| 313 | if err := insertReferencesFromBody(ctx, tx, deps, fresh, body, "issue_body", fresh.ID); err != nil { |
| 314 | return issuesdb.Issue{}, fmt.Errorf("refs: %w", err) |
| 315 | } |
| 316 | } |
| 317 | if err := tx.Commit(ctx); err != nil { |
| 318 | return issuesdb.Issue{}, fmt.Errorf("commit: %w", err) |
| 319 | } |
| 320 | committed = true |
| 321 | return q.GetIssueByID(ctx, deps.Pool, p.IssueID) |
| 322 | } |
| 323 | |
| 324 | // SetState closes or reopens an issue and emits an `closed` / |
| 325 | // `reopened` event. |
| 326 | func SetState(ctx context.Context, deps Deps, actorUserID, issueID int64, newState, reason string) error { |
| 327 | return setState(ctx, deps, actorUserID, issueID, newState, reason, 0) |
| 328 | } |
| 329 | |
| 330 | // SetStateWithComment is used by the issue comment form when the submit |
| 331 | // button both creates a comment and changes state. The timeline event stores |
| 332 | // the comment id so the UI can keep the state badge adjacent to the comment |
| 333 | // that caused it. |
| 334 | func SetStateWithComment(ctx context.Context, deps Deps, actorUserID, issueID int64, newState, reason string, commentID int64) error { |
| 335 | return setState(ctx, deps, actorUserID, issueID, newState, reason, commentID) |
| 336 | } |
| 337 | |
| 338 | func setState(ctx context.Context, deps Deps, actorUserID, issueID int64, newState, reason string, commentID int64) error { |
| 339 | if newState != "open" && newState != "closed" { |
| 340 | return errors.New("issues: state must be open or closed") |
| 341 | } |
| 342 | tx, err := deps.Pool.Begin(ctx) |
| 343 | if err != nil { |
| 344 | return err |
| 345 | } |
| 346 | committed := false |
| 347 | defer func() { |
| 348 | if !committed { |
| 349 | _ = tx.Rollback(ctx) |
| 350 | } |
| 351 | }() |
| 352 | |
| 353 | q := issuesdb.New() |
| 354 | closedBy := pgtype.Int8{} |
| 355 | if newState == "closed" && actorUserID != 0 { |
| 356 | closedBy = pgtype.Int8{Int64: actorUserID, Valid: true} |
| 357 | } |
| 358 | stateReason := pgtype.Text{} |
| 359 | if reason != "" { |
| 360 | stateReason = pgtype.Text{String: reason, Valid: true} |
| 361 | } |
| 362 | if err := q.SetIssueState(ctx, tx, issuesdb.SetIssueStateParams{ |
| 363 | ID: issueID, |
| 364 | State: issuesdb.IssueState(newState), |
| 365 | StateReason: issuesdb.NullIssueStateReason{IssueStateReason: issuesdb.IssueStateReason(stateReason.String), Valid: stateReason.Valid}, |
| 366 | ClosedByUserID: closedBy, |
| 367 | }); err != nil { |
| 368 | return err |
| 369 | } |
| 370 | kind := "closed" |
| 371 | if newState == "open" { |
| 372 | kind = "reopened" |
| 373 | } |
| 374 | meta := emptyMeta |
| 375 | if commentID != 0 { |
| 376 | meta = []byte(`{"comment_id":` + strconv.FormatInt(commentID, 10) + `}`) |
| 377 | } |
| 378 | if _, err := q.InsertIssueEvent(ctx, tx, issuesdb.InsertIssueEventParams{ |
| 379 | IssueID: issueID, |
| 380 | ActorUserID: pgtype.Int8{Int64: actorUserID, Valid: actorUserID != 0}, |
| 381 | Kind: kind, |
| 382 | Meta: meta, |
| 383 | }); err != nil { |
| 384 | return err |
| 385 | } |
| 386 | // Lifecycle domain event so the notif fan-out + S33 webhook |
| 387 | // pipeline pick up state changes the same way they pick up |
| 388 | // comments. |
| 389 | issue, _ := q.GetIssueByID(ctx, tx, issueID) |
| 390 | repoVis, _ := repoVisibilityPublic(ctx, tx, issue.RepoID) |
| 391 | stateKind := "issue_" + kind // issue_closed | issue_reopened |
| 392 | if issue.Kind == issuesdb.IssueKindPr { |
| 393 | stateKind = "pr_" + kind |
| 394 | } |
| 395 | if err := emitIssueEventTx(ctx, tx, stateKind, issue, actorUserID, repoVis, nil); err != nil { |
| 396 | return fmt.Errorf("emit event: %w", err) |
| 397 | } |
| 398 | if err := tx.Commit(ctx); err != nil { |
| 399 | return err |
| 400 | } |
| 401 | committed = true |
| 402 | if deps.Audit != nil { |
| 403 | _ = deps.Audit.Record(ctx, deps.Pool, actorUserID, |
| 404 | audit.ActionIssueStateChanged, audit.TargetIssue, issueID, |
| 405 | map[string]any{"state": newState, "reason": reason}) |
| 406 | } |
| 407 | return nil |
| 408 | } |
| 409 | |
| 410 | // emptyMeta is the JSON object passed when an event carries no metadata. |
| 411 | // The column is NOT NULL DEFAULT '{}'::jsonb, but binding nil from Go |
| 412 | // sends SQL NULL rather than letting the DEFAULT fire — so callers |
| 413 | // pass this explicitly. |
| 414 | var emptyMeta = []byte("{}") |
| 415 | |
| 416 | // SetLock toggles the locked flag and emits an event. |
| 417 | func SetLock(ctx context.Context, deps Deps, actorUserID, issueID int64, locked bool, reason string) error { |
| 418 | q := issuesdb.New() |
| 419 | tx, err := deps.Pool.Begin(ctx) |
| 420 | if err != nil { |
| 421 | return err |
| 422 | } |
| 423 | committed := false |
| 424 | defer func() { |
| 425 | if !committed { |
| 426 | _ = tx.Rollback(ctx) |
| 427 | } |
| 428 | }() |
| 429 | rsn := pgtype.Text{} |
| 430 | if reason != "" { |
| 431 | rsn = pgtype.Text{String: reason, Valid: true} |
| 432 | } |
| 433 | if err := q.SetIssueLock(ctx, tx, issuesdb.SetIssueLockParams{ |
| 434 | ID: issueID, Locked: locked, LockReason: rsn, |
| 435 | }); err != nil { |
| 436 | return err |
| 437 | } |
| 438 | kind := "locked" |
| 439 | if !locked { |
| 440 | kind = "unlocked" |
| 441 | } |
| 442 | if _, err := q.InsertIssueEvent(ctx, tx, issuesdb.InsertIssueEventParams{ |
| 443 | IssueID: issueID, ActorUserID: pgtype.Int8{Int64: actorUserID, Valid: actorUserID != 0}, |
| 444 | Kind: kind, |
| 445 | Meta: emptyMeta, |
| 446 | }); err != nil { |
| 447 | return err |
| 448 | } |
| 449 | if err := tx.Commit(ctx); err != nil { |
| 450 | return err |
| 451 | } |
| 452 | committed = true |
| 453 | if deps.Audit != nil { |
| 454 | _ = deps.Audit.Record(ctx, deps.Pool, actorUserID, |
| 455 | audit.ActionIssueLockChanged, audit.TargetIssue, issueID, |
| 456 | map[string]any{"locked": locked, "reason": reason}) |
| 457 | } |
| 458 | return nil |
| 459 | } |
| 460 | |
| 461 | // renderBody renders markdown to sanitized HTML and returns the |
| 462 | // resolved mention list. Body length is bounded upstream |
| 463 | // (orchestrator validation + DB CHECK at 65535), so |
| 464 | // ErrInputTooLarge is structurally impossible here — but if it ever |
| 465 | // fires, log loudly: it means a precondition somewhere upstream |
| 466 | // regressed. Mentions feed the S29 fan-out worker via the event |
| 467 | // payload's `mentions` array. |
| 468 | func renderBody(ctx context.Context, deps Deps, body string) (string, []mdrender.Mention) { |
| 469 | if body == "" { |
| 470 | return "", nil |
| 471 | } |
| 472 | html, _, mentions, err := mdrender.Render(ctx, []byte(body), mdrender.Options{ |
| 473 | SoftBreakAsBR: true, |
| 474 | }) |
| 475 | if err != nil && deps.Logger != nil { |
| 476 | deps.Logger.WarnContext(ctx, "issues: markdown render failed", |
| 477 | "error", err, "body_bytes", len(body)) |
| 478 | return "", nil |
| 479 | } |
| 480 | return string(html), mentions |
| 481 | } |
| 482 |