diff --git a/.claude/skills/go/SKILL.md b/.claude/skills/go/SKILL.md index b138396011..757de1ba5d 100644 --- a/.claude/skills/go/SKILL.md +++ b/.claude/skills/go/SKILL.md @@ -20,6 +20,7 @@ These rules are the choices this repo makes. General Go style is not repeated he - Pass `ctx context.Context` as the first parameter. Do not store a request's context in a struct. A service may hold a lifetime context made in `New`, with its cancel function, as `channels.Service` does. - Start no goroutine in `init()` or in a constructor. Start it in `Start(ctx)` or `Run(ctx)`, as `chatlog.Log.Start` does. - Return a nil slice for "none". A JSON response is the exception: it sends `[]`, not `null`. +- Query Postgres through bun's builders (`NewSelect`, `NewInsert ... On("CONFLICT ...")`, `NewUpdate`, `NewDelete`) on a model, not `NewRaw` or `ExecContext` with a SQL string. A table without a model gets a small unexported one. An insert lists `.Column(...)` so database defaults still apply. Keep SQL raw only where the builder cannot write it or would change what it does: advisory locks, `SET LOCAL`, DDL and catalog reads, `INSERT ... SELECT`, `WITH RECURSIVE`, window and `GROUPING SETS` queries, a statement whose SQL text a test matches, and jsonb that must refuse `\u0000` (bun stores it as text). - Defensive code (a retry, a fallback, a second check) gets a comment that names the concrete threat: concurrent writers, a network failure the caller retries, malformed input. If you cannot name one, do not add it (see "Code style" in AGENTS.md). ## Comments diff --git a/acceleration/internal/store/activity.go b/acceleration/internal/store/activity.go index a4ded6c222..76836ea2e7 100644 --- a/acceleration/internal/store/activity.go +++ b/acceleration/internal/store/activity.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "slices" - "strings" "time" "github.com/uptrace/bun" @@ -85,37 +84,47 @@ func (s *Store) RecordActivity(ctx context.Context, deltas []ActivityDelta) erro return nil } +// activityUpsert is one customer_activity row as writeActivity upserts it. +type activityUpsert struct { + bun.BaseModel `bun:"table:customer_activity,alias:act"` + + OrganizationID string `bun:"organization_id,notnull"` + AppID string `bun:"app_id,pk"` + Area string `bun:"area,pk"` + Client string `bun:"client,pk"` + Day string `bun:"day,pk"` + Requests int64 `bun:"requests,notnull"` + Refused int64 `bun:"refused,notnull"` + LastRefusalCode string `bun:"last_refusal_code,nullzero"` + LastRefusalAt time.Time `bun:"last_refusal_at,nullzero"` + FirstAt time.Time `bun:"first_at,notnull"` + LastAt time.Time `bun:"last_at,notnull"` +} + // writeActivity upserts the rows of keys in one statement. func writeActivity(ctx context.Context, tx bun.Tx, folded map[activityKey]*ActivityDelta, keys []activityKey) error { - rows := make([]string, 0, len(keys)) - args := make([]any, 0, len(keys)*11) + rows := make([]activityUpsert, 0, len(keys)) for _, key := range keys { delta := folded[key] - var refusedAt *time.Time - if !delta.LastRefusalAt.IsZero() { - refusedAt = &delta.LastRefusalAt - } - rows = append(rows, "(?, ?, ?, ?, ?::date, ?, ?, NULLIF(?, ''), ?::timestamptz, ?, ?)") - args = append(args, delta.OrganizationID, key.appID, key.area, key.client, key.day, - delta.Requests, delta.Refused, delta.LastRefusalCode, refusedAt, delta.FirstAt, delta.LastAt) + rows = append(rows, activityUpsert{ + OrganizationID: delta.OrganizationID, AppID: key.appID, Area: key.area, Client: key.client, Day: key.day, + Requests: delta.Requests, Refused: delta.Refused, LastRefusalCode: delta.LastRefusalCode, + LastRefusalAt: delta.LastRefusalAt, FirstAt: delta.FirstAt, LastAt: delta.LastAt, + }) } - query := ` -INSERT INTO customer_activity (organization_id, app_id, area, client, day, requests, refused, - last_refusal_code, last_refusal_at, first_at, last_at) -VALUES ` + strings.Join(rows, ", ") + ` -ON CONFLICT (app_id, area, client, day) DO UPDATE SET - organization_id = EXCLUDED.organization_id, - requests = customer_activity.requests + EXCLUDED.requests, - refused = customer_activity.refused + EXCLUDED.refused, - last_refusal_code = CASE - WHEN customer_activity.last_refusal_at IS NULL - OR EXCLUDED.last_refusal_at >= customer_activity.last_refusal_at + _, err := tx.NewInsert().Model(&rows). + On("CONFLICT (app_id, area, client, day) DO UPDATE"). + Set("organization_id = EXCLUDED.organization_id"). + Set("requests = act.requests + EXCLUDED.requests"). + Set("refused = act.refused + EXCLUDED.refused"). + Set(`last_refusal_code = CASE + WHEN act.last_refusal_at IS NULL OR EXCLUDED.last_refusal_at >= act.last_refusal_at THEN EXCLUDED.last_refusal_code - ELSE customer_activity.last_refusal_code END, - last_refusal_at = GREATEST(customer_activity.last_refusal_at, EXCLUDED.last_refusal_at), - first_at = LEAST(customer_activity.first_at, EXCLUDED.first_at), - last_at = GREATEST(customer_activity.last_at, EXCLUDED.last_at)` - _, err := tx.ExecContext(ctx, query, args...) + ELSE act.last_refusal_code END`). + Set("last_refusal_at = GREATEST(act.last_refusal_at, EXCLUDED.last_refusal_at)"). + Set("first_at = LEAST(act.first_at, EXCLUDED.first_at)"). + Set("last_at = GREATEST(act.last_at, EXCLUDED.last_at)"). + Exec(ctx) return err } diff --git a/acceleration/internal/store/campaign_dispatch.go b/acceleration/internal/store/campaign_dispatch.go index e777da5879..d0cf9da615 100644 --- a/acceleration/internal/store/campaign_dispatch.go +++ b/acceleration/internal/store/campaign_dispatch.go @@ -222,26 +222,26 @@ func (s *Store) settleContact(ctx context.Context, owner, contactID string, sett return err } } - result, err := tx.ExecContext(ctx, `UPDATE campaign_contacts cc SET - stage = CASE WHEN ? AND (cc.reason = 'stopped' OR cp.state = ?) THEN ? ELSE ? END, - next_attempt_at = CASE WHEN ? AND (cc.reason = 'stopped' OR cp.state = ?) THEN NULL ELSE ?::timestamptz END, - reason = CASE WHEN (? AND cc.reason = 'stopped') OR (? AND cp.state = ?) THEN cc.reason ELSE ? END, - step_id = COALESCE(?, cc.step_id), - attempt = ?, - outcome = ?, - converted = ?, - call_id = COALESCE(?, cc.call_id), - vendor_call_id = COALESCE(?, cc.vendor_call_id), - leased_by = '', - leased_until = NULL -FROM campaigns cp -WHERE cp.id = cc.campaign_id AND cc.id = ? AND cc.leased_by = ? AND cc.stage IN (?, ?)`, - stoppable, Stopped, ContactStopped, settle.Stage, - stoppable, Stopped, settle.NextAttemptAt, - keepsMark, stoppable, Stopped, nullable(settle.Reason), - nullable(settle.StepID), settle.Attempt, settle.Outcome, settle.Converted, - nullable(settle.CallID), nullable(settle.VendorCallID), - contactID, owner, InProgress, AwaitingOutcome) + result, err := tx.NewUpdate().Model((*Contact)(nil)). + TableExpr("campaigns AS cp"). + Set("stage = CASE WHEN ? AND (cc.reason = 'stopped' OR cp.state = ?) THEN ? ELSE ? END", + stoppable, Stopped, ContactStopped, settle.Stage). + Set("next_attempt_at = CASE WHEN ? AND (cc.reason = 'stopped' OR cp.state = ?) THEN NULL ELSE ?::timestamptz END", + stoppable, Stopped, settle.NextAttemptAt). + Set("reason = CASE WHEN (? AND cc.reason = 'stopped') OR (? AND cp.state = ?) THEN cc.reason ELSE ? END", + keepsMark, stoppable, Stopped, nullable(settle.Reason)). + Set("step_id = COALESCE(?, cc.step_id)", nullable(settle.StepID)). + Set("attempt = ?", settle.Attempt). + Set("outcome = ?", settle.Outcome). + Set("converted = ?", settle.Converted). + Set("call_id = COALESCE(?, cc.call_id)", nullable(settle.CallID)). + Set("vendor_call_id = COALESCE(?, cc.vendor_call_id)", nullable(settle.VendorCallID)). + Set("leased_by = ''"). + Set("leased_until = NULL"). + Where("cp.id = cc.campaign_id"). + Where("cc.id = ? AND cc.leased_by = ?", contactID, owner). + Where("cc.stage IN (?, ?)", InProgress, AwaitingOutcome). + Exec(ctx) if err != nil { return fmt.Errorf("store: settle contact: %w", err) }