Documentation
¶
Overview ¶
Package api: post-commit promotion of project.db action_log rows into the project's per-project events.db.
This file implements Stream 3.1 of the td-watch rich UI plan (docs/td-watch-rich-ui-plan.md §7.1). It runs after every mutation handler that wrote to project.db via wrapServeHandler and atomically (a) inserts the corresponding events into events.db and (b) flips action_log.synced_at + .server_seq on the source rows.
Key design points:
Atomicity: SQLite ATTACH DATABASE is used so a single transaction spans both project.db and events.db. On any error we ROLLBACK and return; the action_log rows stay synced_at IS NULL so the *next* call into the same project will retry. This is the recovery valve called out in the plan and we deliberately do NOT add a separate outbox.
Per-row session preservation: we use sync.GetPendingEventsPreserveSession (NOT GetPendingEvents) so each event keeps the session_id stamped on its action_log row by resolveTdWatchSession (e.g. "twu_<user>", "twa_<admin>_as_<target>"). GetPendingEvents would overwrite all events with a single caller-supplied session — wrong for this path.
Device id is the constant TdWatchServerDeviceID = "td_watch_server" (plan §10 Q2). td-watch is not a /sync/pull client, so a single server-originated device id keeps the events dedupe key (device_id, session_id, client_action_id) intact without per-browser device registration.
Package api: periodic apply-cursor lag sampler.
Plan §9.3 (b): expose, per project currently held open in the live pool, the gap between events.db head (MAX(server_seq) over events) and project.db applied_events cursor (MAX(server_seq) over applied_events). Lag is the canonical drift signal for the post-commit promotion + push-apply paths (Streams 3.1 / 3.2). Steady-state value is 0; a sustained > 0 lag means project.db is falling behind events.db.
This file deliberately avoids introducing a metrics dependency. Instead it emits one structured slog line per project per tick, which downstream scraping (Loki / Vector / etc.) can convert into a gauge. The plan calls out an alert at lag > 100 for > 30s; that alerting lives outside this process, this file just emits the raw signal.
Package api: project-scoped middleware for the td-watch BFF surface.
These middlewares are intended for the new Perch-shape /v1/projects/{id}/* routes (see plan §6.3). They are deliberately separate from the existing /v1/sync/* path so the legacy CLI sync flow is unaffected.
requireProjectMembership composes the existing API-key auth with a per-project role check. resolveTdWatchSession derives the session_id that will eventually be stamped onto action_log rows so `td monitor` and audit surfaces preserve actor provenance for td-watch-originated writes.
Package api: Perch-shape REST routes that wrap td-serve's pure handler functions against per-project project.db handles.
This file is the Stream 2.3 deliverable for the td-watch rich UI plan (docs/td-watch-rich-ui-plan.md §6). It registers the `/v1/projects/{id}/{issues,boards,focus,stats,sessions,labels}` surface alongside the existing /v1/projects/{id}/sync/* CLI sync routes, composing:
requireAuth -> requireProjectMembership -> resolveTdWatchSession -> wrapServeHandler(serve.HandleXxx)
wrapServeHandler acquires the per-project project.db from ProjectLivePool, builds a serve.HandlerContext, re-keys URL path values so the serve handlers can read their familiar names (`id`, `comment_id`, etc.) instead of the project-scoped names (`iid`, `cid`, ...), and invokes the pure handler. After successful mutations, a TODO marker indicates where Stream 3 will add post-commit action_log -> events.db promotion.
Index ¶
- Constants
- Variables
- func HasAnyScope(scopes string, required ...string) bool
- func HasScope(scopes string, required string) bool
- func TdWatchSessionFromCtx(ctx context.Context) string
- func ValidateEmailConfig(cfg Config) []string
- func ValidateScopes(scopes string) error
- type APIError
- type AckResponse
- type ActingUser
- type AddMemberRequest
- type AuthUser
- type Config
- type CreateInvitationRequest
- type CreateProjectRequest
- type ErrorResponse
- type EventInput
- type EventType
- type InvitationResponse
- type MemberResponse
- type Metrics
- type MetricsSnapshot
- type ProjectDBPool
- type ProjectEvent
- type ProjectLivePool
- type ProjectResponse
- type PullEvent
- type PullResponse
- type PushRequest
- type PushResponse
- type RateLimiter
- type RejectResponse
- type SSEHub
- type SSEHubRegistry
- type Server
- type SnapshotQuerySource
- func (s *SnapshotQuerySource) GetComments(issueID string) ([]models.Comment, error)
- func (s *SnapshotQuerySource) GetDependencies(issueID string) ([]string, error)
- func (s *SnapshotQuerySource) GetIssue(id string) (*models.Issue, error)
- func (s *SnapshotQuerySource) GetIssuesWithOpenDeps() (map[string]bool, error)
- func (s *SnapshotQuerySource) GetLatestHandoff(issueID string) (*models.Handoff, error)
- func (s *SnapshotQuerySource) GetLinkedFiles(issueID string) ([]models.IssueFile, error)
- func (s *SnapshotQuerySource) GetLogs(issueID string, limit int) ([]models.Log, error)
- func (s *SnapshotQuerySource) GetRejectedInProgressIssueIDs() (map[string]bool, error)
- func (s *SnapshotQuerySource) ListIssues(opts db.ListIssuesOptions) ([]models.Issue, error)
- type SyncStatusResponse
- type UpdateMemberRequest
- type UpdateProjectRequest
Constants ¶
const ( AdminScopeReadServer = "admin:read:server" AdminScopeReadProjects = "admin:read:projects" AdminScopeReadEvents = "admin:read:events" AdminScopeReadSnapshots = "admin:read:snapshots" AdminScopeExport = "admin:export" AdminScopeWriteUsers = "admin:write:users" )
Admin scope constants for the admin API.
const ( ErrCodeBadRequest = "bad_request" ErrCodeNotFound = "not_found" ErrCodeInternal = "internal" ErrCodeForbidden = "forbidden" ErrCodeInsufficientAdminScope = "insufficient_admin_scope" ErrCodeRateLimited = "rate_limited" ErrCodeSignupDisabled = "signup_disabled" ErrCodeExpired = "expired" ErrCodeAlreadyUsed = "already_used" ErrCodeNoEvents = "no_events" ErrCodeNotImplemented = "not_implemented" ErrCodeMethodNotAllowedViewAs = "method_not_allowed_view_as" // New codes for sections 9.5, 10 ErrCodeProjectDeleted = "project_deleted" ErrCodeExportTooLarge = "export_too_large" ErrCodeInvalidQuery = "invalid_query" )
Error code constants for structured API error responses.
const ErrCodeInsufficientScope = "insufficient_scope"
ErrCodeInsufficientScope is the error code returned when a caller has valid credentials but lacks the required scope to access a project route.
const HeaderTdWatchImpersonate = "X-Td-Watch-Impersonate"
HeaderTdWatchImpersonate carries the target user id when an admin uses td-watch's "view as user" feature. The td-watch BFF is the only writer of this header; td-sync still authenticates the request against the admin's own API key, so the header alone is never sufficient to act as someone else.
const HeaderTdWatchSession = "X-Td-Watch-Session"
HeaderTdWatchSession carries the td-watch app session id (NOT a Claude/td session). td-watch's BFF forwards this for every project-scoped request so td-sync can derive a stable, attributable action_log session_id.
const ImpersonationScopeRead = "impersonation:read"
ImpersonationScopeRead is the scope carried by admin "view-as" ephemeral keys. It is NOT an admin scope — it grants read-only access to the target user's /v1/projects/* surface and nothing else.
const TdWatchServerDeviceID = "td_watch_server"
TdWatchServerDeviceID is the constant device_id for events promoted from td-watch-originated writes. Per plan §10 Q2, td-watch is not a /sync/pull client, so a single server-originated device id keeps dedupe semantics (device_id, session_id, client_action_id) intact without requiring a per-browser device registration.
Variables ¶
var ValidAdminScopes = map[string]bool{ AdminScopeReadServer: true, AdminScopeReadProjects: true, AdminScopeReadEvents: true, AdminScopeReadSnapshots: true, AdminScopeExport: true, AdminScopeWriteUsers: true, }
ValidAdminScopes contains all recognized admin scopes.
Functions ¶
func HasAnyScope ¶ added in v0.50.0
HasAnyScope reports whether the comma-separated scopes string contains ANY of the required scopes. Returns false if no required scopes are provided.
func HasScope ¶ added in v0.32.0
HasScope reports whether the comma-separated scopes string contains the required scope.
func TdWatchSessionFromCtx ¶ added in v0.45.0
TdWatchSessionFromCtx returns the resolved td-watch session_id stashed by resolveTdWatchSession, or "" if the middleware did not run.
func ValidateEmailConfig ¶ added in v0.49.0
ValidateEmailConfig checks the email provider configuration and returns a list of warning strings for any missing or unrecognized settings.
func ValidateScopes ¶ added in v0.32.0
ValidateScopes checks that every comma-separated scope is either "sync", a recognized admin scope, or the impersonation:read scope. Returns an error listing the first invalid scope.
Types ¶
type AckResponse ¶
type AckResponse struct {
ClientActionID int64 `json:"client_action_id"`
ServerSeq int64 `json:"server_seq"`
}
AckResponse is a single acknowledged event.
type ActingUser ¶ added in v0.45.0
ActingUser is the effective user identity for td-watch-originated /v1/projects* requests. When admin view-as is active, this is the target user rather than the authenticated admin.
type AddMemberRequest ¶
type AddMemberRequest struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Role string `json:"role"`
}
AddMemberRequest is the JSON body for POST /v1/projects/{id}/members.
type Config ¶
type Config struct {
ListenAddr string
ServerDBPath string
ProjectDataDir string
ShutdownTimeout time.Duration
AllowSignup bool
BaseURL string
LogFormat string // "json" (default) or "text"
LogLevel string // "debug", "info" (default), "warn", "error"
RateLimitAuth int // /auth/* per IP per minute (default: 10)
RateLimitPush int // /sync/push per API key per minute (default: 60)
RateLimitPull int // /sync/pull per API key per minute (default: 120)
RateLimitOther int // all other per API key per minute (default: 300)
TrustedProxies []string // trusted proxy IPs; when empty, X-Forwarded-For is ignored
CORSAllowedOrigins []string // allowed origins for admin CORS; empty = disabled
AuthEventRetention time.Duration // retention period for auth events (default: 90 days)
RateLimitEventRetention time.Duration // retention period for rate limit events (default: 30 days)
EmailProvider string // "cloudflare", "memory", "log"; default "log" for dev
CloudflareAccountID string
CloudflareEmailAPIToken string
CloudflareEmailFrom string // e.g. login@opentangle.com
CloudflareEmailFromName string // e.g. td-watch
CloudflareEmailReplyTo string // e.g. haplab@vorwaller.net
AuthWebCallbackURL string // e.g. https://watch.haplab.com/home/login/complete
AuthEmailBaseURL string // e.g. https://sync.haplab.com (for link generation)
LegacyDeviceAuth bool // When true, enables /v1/auth/login/start, /v1/auth/login/poll, GET/POST /auth/verify
// DevEmailInspect, when true, allows GET /internal/dev/last-email to return
// the most recently sent magic-link email in plaintext. This is a DEV/TEST
// ONLY affordance: the endpoint additionally requires the in-memory email
// provider (*email.MemorySender), which production never uses. Both gates
// must hold, so this flag is inert in prod even if accidentally set.
DevEmailInspect bool
}
Config holds the server configuration, loaded from environment variables.
func LoadConfig ¶
func LoadConfig() Config
LoadConfig reads configuration from environment variables with sensible defaults.
type CreateInvitationRequest ¶ added in v0.50.0
type CreateProjectRequest ¶
type CreateProjectRequest struct {
Name string `json:"name"`
Description string `json:"description"`
}
CreateProjectRequest is the JSON body for POST /v1/projects.
type ErrorResponse ¶
type ErrorResponse struct {
Error APIError `json:"error"`
}
ErrorResponse wraps an APIError for JSON serialization.
type EventInput ¶
type EventInput struct {
ClientActionID int64 `json:"client_action_id"`
ActionType string `json:"action_type"`
EntityType string `json:"entity_type"`
EntityID string `json:"entity_id"`
Payload json.RawMessage `json:"payload"`
ClientTimestamp string `json:"client_timestamp"`
}
EventInput represents a single event in a push request.
type EventType ¶ added in v0.45.0
type EventType string
EventType identifies the kind of realtime event.
const ( // EventIssueUpserted fires when an issue is created or updated. EventIssueUpserted EventType = "issue.upserted" // EventIssueDeleted fires when an issue is deleted. EventIssueDeleted EventType = "issue.deleted" // EventRefresh fires when a client should do a full refresh (e.g. slow // consumer dropped an event, or the server cannot determine exact diff). EventRefresh EventType = "refresh" )
type InvitationResponse ¶ added in v0.50.0
type InvitationResponse struct {
ID string `json:"id"`
ProjectID string `json:"project_id"`
Email string `json:"email"`
Role string `json:"role"`
InvitedBy string `json:"invited_by"`
Status string `json:"status"`
CreatedAt string `json:"created_at"`
ExpiresAt string `json:"expires_at"`
AcceptedAt *string `json:"accepted_at,omitempty"`
}
type MemberResponse ¶
type MemberResponse struct {
ProjectID string `json:"project_id"`
UserID string `json:"user_id"`
Role string `json:"role"`
InvitedBy string `json:"invited_by"`
CreatedAt string `json:"created_at"`
}
MemberResponse is the JSON representation of a membership.
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics collects in-memory server metrics using atomic counters.
func NewMetrics ¶
func NewMetrics() *Metrics
NewMetrics creates a new Metrics instance with the current time as start.
func (*Metrics) RecordClientError ¶
func (m *Metrics) RecordClientError()
RecordClientError increments the client error (4xx) counter.
func (*Metrics) RecordError ¶
func (m *Metrics) RecordError()
RecordError increments the server error (5xx) counter.
func (*Metrics) RecordPullRequest ¶
func (m *Metrics) RecordPullRequest()
RecordPullRequest increments the pull request counter.
func (*Metrics) RecordPushEvents ¶
RecordPushEvents adds n to the accepted push events counter.
func (*Metrics) RecordRequest ¶
func (m *Metrics) RecordRequest()
RecordRequest increments the total request counter.
func (*Metrics) Snapshot ¶
func (m *Metrics) Snapshot() MetricsSnapshot
Snapshot returns a point-in-time copy of the metrics.
type MetricsSnapshot ¶
type MetricsSnapshot struct {
UptimeSeconds float64 `json:"uptime_seconds"`
Requests int64 `json:"requests"`
ServerErrors int64 `json:"server_errors"`
ClientErrors int64 `json:"client_errors"`
PushEventsAccepted int64 `json:"push_events_accepted"`
PullRequests int64 `json:"pull_requests"`
}
MetricsSnapshot is a point-in-time view of server metrics.
type ProjectDBPool ¶
type ProjectDBPool struct {
// contains filtered or unexported fields
}
ProjectDBPool manages per-project SQLite connections for event logs.
func NewProjectDBPool ¶
func NewProjectDBPool(dataDir string) *ProjectDBPool
NewProjectDBPool creates a new pool that stores project databases under dataDir.
func (*ProjectDBPool) CloseAll ¶
func (p *ProjectDBPool) CloseAll()
CloseAll closes all open project database connections. Uses PASSIVE (not TRUNCATE) so the shutdown checkpoint doesn't stall when another process still holds the -shm. SQLite's autocheckpoint handles routine WAL maintenance; aggressive TRUNCATE on exit is unnecessary.
func (*ProjectDBPool) Create ¶
func (p *ProjectDBPool) Create(projectID string) (*sql.DB, error)
Create creates a new project database directory and initializes the event log.
func (*ProjectDBPool) Delete ¶ added in v0.43.0
func (p *ProjectDBPool) Delete(projectID string) error
Delete closes the connection for a project (if open), removes it from the pool, and removes the project database directory from disk.
type ProjectEvent ¶ added in v0.45.0
type ProjectEvent struct {
Type EventType `json:"type"`
IssueID string `json:"issue_id,omitempty"`
ChangeToken string `json:"change_token"`
Timestamp time.Time `json:"timestamp"`
}
ProjectEvent is the payload broadcast to SSE subscribers for a project.
type ProjectLivePool ¶ added in v0.45.0
type ProjectLivePool struct {
// contains filtered or unexported fields
}
ProjectLivePool manages per-project handles to the project-live SQLite database (one DB per project, located at `{baseDir}/{projectID}/project.db`).
The project-live DB holds the full td CLI schema (issues, action_log, boards, ...) and is the read+write target for the Perch-shaped REST handlers being added in Stream 2 (see docs/td-watch-rich-ui-plan.md §6). It is distinct from `events.db`, which remains the authoritative event log managed by ProjectDBPool.
On first acquire for a project, if `project.db` does not exist, the pool performs a one-time bootstrap:
- Initialize a fresh td schema in a temporary directory via `tddb.Initialize` (this guarantees the schema matches the td CLI exactly, including all migrations).
- Copy the resulting issues.db file to `project.db`.
- Re-open `project.db` and replay every event in `events.db` (in `server_seq` order) into it via `tdsync.ApplyRemoteEvents`.
- Record the highest applied `server_seq` in a small `applied_events` bookkeeping table inside project.db.
This is the **one-time bootstrap path only**. Ongoing event application (post-commit promotion of action_log → events.db, and inbound /v1/sync/push → project.db) is the responsibility of Stream 3 and is intentionally out of scope here.
Concurrency:
- Acquire/Release are safe under concurrent use. Each acquired handle is refcounted; Release decrements, and Close releases all handles unconditionally.
- First-touch initialization for a given project is serialized by a per-project sync.Mutex so concurrent goroutines that all see "no project.db" cooperate on a single bootstrap rather than racing.
- The underlying *sql.DB is opened with WAL mode and a 5s busy_timeout (defaults from tddb.OpenSQLite), which lets concurrent reads proceed while a single writer is active.
Lifecycle decision: handles are kept open after Release (a "hot" pool). Refcounts are tracked for observability and so that Close can be reasoned about, but a zero refcount does NOT trigger close. Closing every handle on the last Release would cause a thrashing open/close pattern under typical HTTP traffic. Close (called on server shutdown) tears every handle down.
func NewProjectLivePool ¶ added in v0.45.0
func NewProjectLivePool(baseDir string) *ProjectLivePool
NewProjectLivePool creates a pool whose project.db files live under baseDir (one project directory per projectID, file named project.db inside that directory).
func (*ProjectLivePool) Acquire ¶ added in v0.45.0
func (p *ProjectLivePool) Acquire(projectID string) (*tddb.DB, error)
Acquire returns an opened handle to the project-live DB for projectID, creating and bootstrapping it from events.db on first access. Each successful Acquire must be paired with a Release.
func (*ProjectLivePool) Close ¶ added in v0.45.0
func (p *ProjectLivePool) Close() error
Close closes every cached handle and clears the pool. Safe to call multiple times.
func (*ProjectLivePool) Release ¶ added in v0.45.0
func (p *ProjectLivePool) Release(projectID string)
Release decrements the refcount for projectID. The handle is intentionally kept open even at zero refcount (hot pool); Close tears everything down on shutdown.
func (*ProjectLivePool) Snapshot ¶ added in v0.45.0
func (p *ProjectLivePool) Snapshot() []string
Snapshot returns the set of project IDs that currently have an open handle in the pool. Used by periodic background tasks (e.g. the apply-cursor lag sampler in metrics_lag.go) that want to iterate live projects without holding the pool's mutex while doing slow per-project I/O. The returned slice is a copy and safe to mutate; the pool itself is not held during use.
type ProjectResponse ¶
type ProjectResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Slug string `json:"slug"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
DeletedAt *string `json:"deleted_at,omitempty"`
}
ProjectResponse is the JSON representation of a project.
type PullEvent ¶
type PullEvent struct {
ServerSeq int64 `json:"server_seq"`
DeviceID string `json:"device_id"`
SessionID string `json:"session_id"`
ClientActionID int64 `json:"client_action_id"`
ActionType string `json:"action_type"`
EntityType string `json:"entity_type"`
EntityID string `json:"entity_id"`
Payload json.RawMessage `json:"payload"`
ClientTimestamp string `json:"client_timestamp"`
}
PullEvent is a single event in a pull response.
type PullResponse ¶
type PullResponse struct {
Events []PullEvent `json:"events"`
LastServerSeq int64 `json:"last_server_seq"`
HasMore bool `json:"has_more"`
}
PullResponse is the JSON response for a pull request.
type PushRequest ¶
type PushRequest struct {
DeviceID string `json:"device_id"`
SessionID string `json:"session_id"`
Events []EventInput `json:"events"`
}
PushRequest is the JSON body for POST /v1/projects/{id}/sync/push.
type PushResponse ¶
type PushResponse struct {
Accepted int `json:"accepted"`
Acks []AckResponse `json:"acks"`
Rejected []RejectResponse `json:"rejected,omitempty"`
}
PushResponse is the JSON response for a push request.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements per-key fixed-window rate limiting.
func NewRateLimiter ¶
func NewRateLimiter() *RateLimiter
NewRateLimiter creates a RateLimiter and starts background cleanup.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string, limit int) bool
Allow checks if the key is within the rate limit (limit per 1-minute window).
func (*RateLimiter) Stop ¶ added in v0.43.0
func (rl *RateLimiter) Stop()
Stop terminates the background cleanup goroutine.
type RejectResponse ¶
type RejectResponse struct {
ClientActionID int64 `json:"client_action_id"`
Reason string `json:"reason"`
ServerSeq int64 `json:"server_seq,omitempty"`
}
RejectResponse is a single rejected event.
type SSEHub ¶ added in v0.45.0
type SSEHub struct {
// contains filtered or unexported fields
}
SSEHub manages a set of subscriber channels for a single project. Events are pushed by write paths (via Broadcast) and fanned out to all registered clients. The hub does NOT poll; it is driven externally.
Each subscriber channel has capacity eventSlots+1 (17). Broadcast treats the first 16 positions as normal-event slots and the 17th as a reserved refresh slot: when the first 16 are full it queues a refresh event instead of the original event. If the channel is at full capacity (all 17 slots taken, meaning a refresh is already pending) the event is silently dropped; the client will still perform a full resync when it drains the already-pending refresh.
Because Broadcast holds the hub mutex for its entire duration, the len check is safe: only the subscriber goroutine reads from the channel concurrently, which can only decrease len (making the check conservative, never unsafe).
func (*SSEHub) Broadcast ¶ added in v0.45.0
func (h *SSEHub) Broadcast(ev ProjectEvent)
Broadcast sends ev to all registered subscribers. If a subscriber's normal event slots (positions 0–15) are all occupied, Broadcast queues a refresh event in the reserved 17th slot instead. If even that slot is taken (a refresh is already pending), the event is dropped; the client will recover when it drains the pending refresh.
Broadcast holds h.mu for its entire execution, so the len check before each direct send is safe: the only concurrent accessor of a subscriber channel is its reader goroutine, which can only reduce len.
func (*SSEHub) ClientCount ¶ added in v0.45.0
ClientCount returns the number of active subscribers.
func (*SSEHub) Register ¶ added in v0.45.0
func (h *SSEHub) Register() chan ProjectEvent
Register adds a new subscriber and returns its channel. The channel has capacity eventSlots+1 (17): 16 for normal events and 1 reserved for a refresh event when the normal slots are all full.
func (*SSEHub) Unregister ¶ added in v0.45.0
func (h *SSEHub) Unregister(ch chan ProjectEvent)
Unregister removes a subscriber channel and closes it. If this was the last subscriber, onEmpty is called to allow the registry to remove the idle hub.
type SSEHubRegistry ¶ added in v0.45.0
type SSEHubRegistry struct {
// contains filtered or unexported fields
}
SSEHubRegistry maps project IDs to their SSEHub. Get-or-create is safe for concurrent use. Idle hubs (zero subscribers) are removed automatically when the last subscriber unregisters.
func NewSSEHubRegistry ¶ added in v0.45.0
func NewSSEHubRegistry() *SSEHubRegistry
NewSSEHubRegistry creates an empty registry.
func (*SSEHubRegistry) Broadcast ¶ added in v0.45.0
func (r *SSEHubRegistry) Broadcast(projectID string, ev ProjectEvent)
Broadcast sends ev to all subscribers of projectID. No-ops if no hub exists.
func (*SSEHubRegistry) GetOrCreate ¶ added in v0.45.0
func (r *SSEHubRegistry) GetOrCreate(projectID string) *SSEHub
GetOrCreate returns the existing hub for projectID, or creates one if none exists. The returned hub is safe to use immediately.
func (*SSEHubRegistry) HubCount ¶ added in v0.45.0
func (r *SSEHubRegistry) HubCount() int
HubCount returns the number of projects with active hubs. For observability.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the HTTP API server for td-sync.
func (*Server) CORSMiddleware ¶ added in v0.32.0
CORSMiddleware handles CORS for admin routes. If no allowed origins are configured, it passes through without setting headers.
type SnapshotQuerySource ¶ added in v0.32.0
type SnapshotQuerySource struct {
// contains filtered or unexported fields
}
SnapshotQuerySource implements query.QuerySource for read-only snapshot databases. It runs SQL directly against a snapshot *sql.DB (same schema as the client-side DB).
func NewSnapshotQuerySource ¶ added in v0.32.0
func NewSnapshotQuerySource(sqlDB *sql.DB) *SnapshotQuerySource
NewSnapshotQuerySource wraps a read-only *sql.DB as a QuerySource.
func (*SnapshotQuerySource) GetComments ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetComments(issueID string) ([]models.Comment, error)
GetComments retrieves comments for an issue.
func (*SnapshotQuerySource) GetDependencies ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetDependencies(issueID string) ([]string, error)
GetDependencies returns IDs of issues that issueID depends on.
func (*SnapshotQuerySource) GetIssue ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetIssue(id string) (*models.Issue, error)
GetIssue retrieves a single issue by ID.
func (*SnapshotQuerySource) GetIssuesWithOpenDeps ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetIssuesWithOpenDeps() (map[string]bool, error)
GetIssuesWithOpenDeps returns issue IDs that have at least one non-closed dependency.
func (*SnapshotQuerySource) GetLatestHandoff ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetLatestHandoff(issueID string) (*models.Handoff, error)
GetLatestHandoff retrieves the latest handoff for an issue.
func (*SnapshotQuerySource) GetLinkedFiles ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetLinkedFiles(issueID string) ([]models.IssueFile, error)
GetLinkedFiles returns files linked to an issue.
func (*SnapshotQuerySource) GetLogs ¶ added in v0.32.0
GetLogs retrieves logs for an issue, including work session logs.
func (*SnapshotQuerySource) GetRejectedInProgressIssueIDs ¶ added in v0.32.0
func (s *SnapshotQuerySource) GetRejectedInProgressIssueIDs() (map[string]bool, error)
GetRejectedInProgressIssueIDs returns IDs of open or in_progress issues that have a recent reject action without a subsequent review action (needs rework). Rejected issues are reset to open; they may then be picked up (in_progress).
func (*SnapshotQuerySource) ListIssues ¶ added in v0.32.0
func (s *SnapshotQuerySource) ListIssues(opts db.ListIssuesOptions) ([]models.Issue, error)
ListIssues queries the issues table with filters from ListIssuesOptions.
type SyncStatusResponse ¶
type SyncStatusResponse struct {
EventCount int64 `json:"event_count"`
LastServerSeq int64 `json:"last_server_seq"`
LastEventTime string `json:"last_event_time,omitempty"`
}
SyncStatusResponse is the JSON response for GET /v1/projects/{id}/sync/status.
type UpdateMemberRequest ¶
type UpdateMemberRequest struct {
Role string `json:"role"`
}
UpdateMemberRequest is the JSON body for PATCH /v1/projects/{id}/members/{userID}.
type UpdateProjectRequest ¶
type UpdateProjectRequest struct {
Name *string `json:"name"`
Description *string `json:"description"`
}
UpdateProjectRequest is the JSON body for PATCH /v1/projects/{id}.
Source Files
¶
- action_log_promotion.go
- admin_events.go
- admin_middleware.go
- admin_projects.go
- admin_scopes.go
- admin_server.go
- admin_snapshots.go
- admin_users.go
- auth.go
- broadcast.go
- config.go
- cors.go
- dbpool.go
- dev_email.go
- errors.go
- events_handler.go
- invitations.go
- members.go
- metrics.go
- metrics_lag.go
- middleware.go
- project_live_pool.go
- project_middleware.go
- project_routes.go
- projects.go
- ratelimit.go
- server.go
- snapshot_query_source.go
- sse_hub.go
- sync.go
- sync_apply.go