feat: greenfield Go rewrite (Phase 2A + 2B + 2C core)
Replaces the Python v1 (preserved on archive/python-v1 branch).
Stack: Go 1.23 + chi router + sqlx + MySQL 8. Distroless static
container. 12-factor config from env. Embedded SQL migrations.
Schema (internal/db/migrations/001_init.sql):
- topics: 议题 with 4-timestamp lifecycle (signup_open/close +
debate_start/end), visibility (default private), status state machine,
verdict_schema FK
- signups: agent self-enrollment with willing_camps (JSON array of
pro|con|judge), pre_validated audit flag, (topic,agent) unique
- camps: post-allocation lock (one row per topic+camp) — written by
Phase 2D allocator
- rounds + arguments: chronological debate transcript
- verdicts: judge structured output, one per topic, with token-cost
trail for future budgeting
- agent_keys + system_keys: peppered sha256 hashes, never raw
- verdict_schemas: seeded with binary, claim-resolution (for
analyze-intel), policy-recommendation, free-form
Auth (internal/auth):
- AgentAPIKey: real bearer-token middleware against agent_keys;
best-effort last_used_at touch on success
- OIDCBrowser: Phase 2 stub. Dev mode accepts x-dev-bypass header
(constant-time compare); prod 401s with a Phase-4-pending hint.
Real Keycloak JWKS verification lands with the frontend rewrite.
HTTP API (internal/httpapi):
- /api/healthz — db ping + version + uptime
- GET /api/topics — list with status/visibility/limit/offset filters;
anonymous callers see public only
- GET /api/topics/{id} — visibility-gated (private → 404 hide)
- POST /api/topics — create with RFC3339 lifecycle validation
(signup_open < signup_close <= debate_start < debate_end)
- PUT /api/topics/{id}/visibility — dialectic-admin role gate
- POST /api/topics/{id}/signups — agent self-enroll; rejects when
topic.status != signup_open OR outside signup window; idempotent
upsert per (topic, agent)
- GET /api/topics/{id}/signups — list (any authed caller)
Auth chains:
- optionalAuth: try bearer → try oidc → fall through anonymous
(handlers branch on Caller.Kind == ""). Uses captureWriter to demote
inner 401s to "try next" without leaking response bytes.
- requireAnyAuth: chain that 401s if neither succeeds.
- requireAgent: strict bearer-only (signup POST).
Run: `docker compose -f docker-compose.dev.yml up --build`. Migrations
auto-apply on first connect; idempotent on reboot. README documents
env vars, dev bypass usage, agent-key provisioning SQL, and the
Phase 2D/E/3/4/5 roadmap.
go vet clean, gofmt clean, single 11M static binary.
This commit is contained in:
95
internal/store/signup_store.go
Normal file
95
internal/store/signup_store.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
|
||||
)
|
||||
|
||||
type SignupStore struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewSignupStore(db *sqlx.DB) *SignupStore { return &SignupStore{db: db} }
|
||||
|
||||
type UpsertSignupInput struct {
|
||||
TopicID string
|
||||
AgentID string
|
||||
WillingCamps []models.Camp
|
||||
PreValidated bool
|
||||
}
|
||||
|
||||
// Upsert creates or updates an agent's signup for a topic. Re-signup
|
||||
// replaces willing_camps (intentional: lets an agent change their mind
|
||||
// before signup_close_at).
|
||||
func (s *SignupStore) Upsert(ctx context.Context, in UpsertSignupInput) (*models.SignupView, error) {
|
||||
if len(in.WillingCamps) == 0 {
|
||||
return nil, fmt.Errorf("willing_camps must be non-empty")
|
||||
}
|
||||
for _, c := range in.WillingCamps {
|
||||
if !models.IsCampValid(c) {
|
||||
return nil, fmt.Errorf("invalid camp %q", c)
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(in.WillingCamps)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Try insert; on duplicate (topic, agent), update.
|
||||
id := uuid.NewString()
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
INSERT INTO signups (id, topic_id, agent_id, willing_camps, pre_validated)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
willing_camps = VALUES(willing_camps),
|
||||
pre_validated = VALUES(pre_validated)`,
|
||||
id, in.TopicID, in.AgentID, raw, in.PreValidated)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("upsert signup: %w", err)
|
||||
}
|
||||
return s.GetByPair(ctx, in.TopicID, in.AgentID)
|
||||
}
|
||||
|
||||
func (s *SignupStore) GetByPair(ctx context.Context, topicID, agentID string) (*models.SignupView, error) {
|
||||
var row models.Signup
|
||||
err := s.db.GetContext(ctx, &row,
|
||||
`SELECT * FROM signups WHERE topic_id = ? AND agent_id = ?`, topicID, agentID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := row.View()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// ListByTopic returns all signups for a topic. Used by the allocation
|
||||
// algorithm at signup_close_at and by the topic-detail UI.
|
||||
func (s *SignupStore) ListByTopic(ctx context.Context, topicID string) ([]models.SignupView, error) {
|
||||
var rows []models.Signup
|
||||
if err := s.db.SelectContext(ctx, &rows,
|
||||
`SELECT * FROM signups WHERE topic_id = ? ORDER BY created_at ASC`, topicID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]models.SignupView, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
v, err := r.View()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
106
internal/store/topic_store.go
Normal file
106
internal/store/topic_store.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"git.hangman-lab.top/hzhang/Dialectic.Backend/internal/models"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
type TopicStore struct {
|
||||
db *sqlx.DB
|
||||
}
|
||||
|
||||
func NewTopicStore(db *sqlx.DB) *TopicStore { return &TopicStore{db: db} }
|
||||
|
||||
type CreateTopicInput struct {
|
||||
Title string
|
||||
Summary string
|
||||
Visibility models.Visibility
|
||||
VerdictSchemaID string
|
||||
SignupOpenAt string // RFC3339; parsed by SQL
|
||||
SignupCloseAt string
|
||||
DebateStartAt string
|
||||
DebateEndAt string
|
||||
CreatorUserID string
|
||||
}
|
||||
|
||||
func (s *TopicStore) Create(ctx context.Context, in CreateTopicInput) (*models.Topic, error) {
|
||||
id := uuid.NewString()
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT INTO topics (id, title, summary, visibility, verdict_schema_id,
|
||||
signup_open_at, signup_close_at, debate_start_at, debate_end_at, creator_user_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
id, in.Title, in.Summary, in.Visibility, in.VerdictSchemaID,
|
||||
in.SignupOpenAt, in.SignupCloseAt, in.DebateStartAt, in.DebateEndAt, in.CreatorUserID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("insert topic: %w", err)
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *TopicStore) GetByID(ctx context.Context, id string) (*models.Topic, error) {
|
||||
var t models.Topic
|
||||
err := s.db.GetContext(ctx, &t, `SELECT * FROM topics WHERE id = ?`, id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Status string // empty = all
|
||||
Visibility string // empty = all
|
||||
Limit int // 0 = default 50
|
||||
Offset int
|
||||
}
|
||||
|
||||
func (s *TopicStore) List(ctx context.Context, f ListFilter) ([]models.Topic, error) {
|
||||
if f.Limit <= 0 || f.Limit > 200 {
|
||||
f.Limit = 50
|
||||
}
|
||||
q := "SELECT * FROM topics"
|
||||
args := []any{}
|
||||
var clauses []string
|
||||
if f.Status != "" {
|
||||
clauses = append(clauses, "status = ?")
|
||||
args = append(args, f.Status)
|
||||
}
|
||||
if f.Visibility != "" {
|
||||
clauses = append(clauses, "visibility = ?")
|
||||
args = append(args, f.Visibility)
|
||||
}
|
||||
if len(clauses) > 0 {
|
||||
q += " WHERE " + strings.Join(clauses, " AND ")
|
||||
}
|
||||
q += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
||||
args = append(args, f.Limit, f.Offset)
|
||||
|
||||
var rows []models.Topic
|
||||
if err := s.db.SelectContext(ctx, &rows, q, args...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// SetVisibility flips public/private; records who/when. Returns updated row.
|
||||
func (s *TopicStore) SetVisibility(ctx context.Context, id string, v models.Visibility, byUserID string) (*models.Topic, error) {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
UPDATE topics SET visibility = ?, visibility_changed_by = ?, visibility_changed_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?`, v, byUserID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetByID(ctx, id)
|
||||
}
|
||||
Reference in New Issue
Block a user