Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
17.0 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.31.1
// source: wecom_install_session.sql

package db

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const claimDueWecomInstallSession = `-- name: ClaimDueWecomInstallSession :one
UPDATE wecom_install_session
SET lease_token       = $1,
    lease_expires_at  = $2,
    updated_at        = now()
WHERE id = (
    SELECT id FROM wecom_install_session
    WHERE status IN ('creating', 'pending')
      AND poll_after <= now()
      AND (lease_expires_at IS NULL OR lease_expires_at <= now())
    ORDER BY poll_after, created_at
    LIMIT 1
    FOR UPDATE SKIP LOCKED
)
RETURNING id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at
`

type ClaimDueWecomInstallSessionParams struct {
	LeaseToken     pgtype.Text        `json:"lease_token"`
	LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
}

// Install worker's claim primitive. Picks the earliest due `creating` or
// `pending` row whose lease is absent or expired, and rewrites the lease
// atomically. Backed by idx_wecom_install_session_due (partial index on
// status IN ('creating','pending') ordered by poll_after, created_at).
// FOR UPDATE SKIP LOCKED lets multiple replicas share the workload without
// blocking each other on hot rows.
func (q *Queries) ClaimDueWecomInstallSession(ctx context.Context, arg ClaimDueWecomInstallSessionParams) (WecomInstallSession, error) {
	row := q.db.QueryRow(ctx, claimDueWecomInstallSession, arg.LeaseToken, arg.LeaseExpiresAt)
	var i WecomInstallSession
	err := row.Scan(
		&i.ID,
		&i.RequestKeyHash,
		&i.WorkspaceID,
		&i.AgentID,
		&i.InitiatorUserID,
		&i.ScodeEncrypted,
		&i.QrCodeUrlEncrypted,
		&i.Status,
		&i.PollAfter,
		&i.ExpiresAt,
		&i.LeaseToken,
		&i.LeaseExpiresAt,
		&i.InstallationID,
		&i.ErrorReason,
		&i.ErrorMessage,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const completeWecomInstallSession = `-- name: CompleteWecomInstallSession :execrows
UPDATE wecom_install_session
SET status                  = 'success',
    installation_id         = $1,
    scode_encrypted         = NULL,
    qr_code_url_encrypted   = NULL,
    lease_token             = NULL,
    lease_expires_at        = NULL,
    updated_at              = now()
WHERE id = $2
  AND lease_token = $3
  AND status = 'pending'
`

type CompleteWecomInstallSessionParams struct {
	InstallationID pgtype.UUID `json:"installation_id"`
	ID             pgtype.UUID `json:"id"`
	LeaseToken     pgtype.Text `json:"lease_token"`
}

// Finalize-success terminator. Wipes short-lived ciphertext, records the
// installation id, flips status to 'success'. Fenced on lease_token AND
// status='pending' so a stale worker cannot override the owner's success.
func (q *Queries) CompleteWecomInstallSession(ctx context.Context, arg CompleteWecomInstallSessionParams) (int64, error) {
	result, err := q.db.Exec(ctx, completeWecomInstallSession, arg.InstallationID, arg.ID, arg.LeaseToken)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const countWecomInstallSessionsInWindow = `-- name: CountWecomInstallSessionsInWindow :one
SELECT
    count(*)                                                                   AS total,
    count(*) FILTER (WHERE initiator_user_id = $1)  AS by_user
FROM wecom_install_session
WHERE workspace_id = $2
  AND created_at >= $3::timestamptz
`

type CountWecomInstallSessionsInWindowParams struct {
	InitiatorUserID pgtype.UUID        `json:"initiator_user_id"`
	WorkspaceID     pgtype.UUID        `json:"workspace_id"`
	Since           pgtype.Timestamptz `json:"since"`
}

type CountWecomInstallSessionsInWindowRow struct {
	Total  int64 `json:"total"`
	ByUser int64 `json:"by_user"`
}

// Rate-window count for the (workspace, initiator) 10-minute budget. Called
// under the LockWecomInstallBeginWorkspace advisory lock so a burst of
// concurrent begins from the same user cannot slip past the cap. Includes
// every status — failed and terminated sessions still consumed a quota slot
// via generate.
func (q *Queries) CountWecomInstallSessionsInWindow(ctx context.Context, arg CountWecomInstallSessionsInWindowParams) (CountWecomInstallSessionsInWindowRow, error) {
	row := q.db.QueryRow(ctx, countWecomInstallSessionsInWindow, arg.InitiatorUserID, arg.WorkspaceID, arg.Since)
	var i CountWecomInstallSessionsInWindowRow
	err := row.Scan(&i.Total, &i.ByUser)
	return i, err
}

const createWecomInstallSession = `-- name: CreateWecomInstallSession :one
INSERT INTO wecom_install_session (
    workspace_id, agent_id, initiator_user_id, request_key_hash, status, poll_after
) VALUES (
    $1,
    $2,
    $3,
    $4,
    'creating',
    now()
)
RETURNING id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at
`

type CreateWecomInstallSessionParams struct {
	WorkspaceID     pgtype.UUID `json:"workspace_id"`
	AgentID         pgtype.UUID `json:"agent_id"`
	InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
	RequestKeyHash  string      `json:"request_key_hash"`
}

// Inserts the fresh `creating` row after LockWecomInstallBeginWorkspace has
// ruled out replay/pending/active/rate-limit. `poll_after=now()` explicitly
// so ClaimDueWecomInstallSession picks it up on the very next sweep — the
// claim predicate is `poll_after <= now()`, not "NULL means due", and this
// avoids that ambiguity.
func (q *Queries) CreateWecomInstallSession(ctx context.Context, arg CreateWecomInstallSessionParams) (WecomInstallSession, error) {
	row := q.db.QueryRow(ctx, createWecomInstallSession,
		arg.WorkspaceID,
		arg.AgentID,
		arg.InitiatorUserID,
		arg.RequestKeyHash,
	)
	var i WecomInstallSession
	err := row.Scan(
		&i.ID,
		&i.RequestKeyHash,
		&i.WorkspaceID,
		&i.AgentID,
		&i.InitiatorUserID,
		&i.ScodeEncrypted,
		&i.QrCodeUrlEncrypted,
		&i.Status,
		&i.PollAfter,
		&i.ExpiresAt,
		&i.LeaseToken,
		&i.LeaseExpiresAt,
		&i.InstallationID,
		&i.ErrorReason,
		&i.ErrorMessage,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const deferClaimedWecomInstallSession = `-- name: DeferClaimedWecomInstallSession :execrows
UPDATE wecom_install_session
SET lease_token       = NULL,
    lease_expires_at  = NULL,
    poll_after        = $1,
    status            = $2,
    scode_encrypted   = COALESCE($3,
                                 wecom_install_session.scode_encrypted),
    qr_code_url_encrypted = COALESCE($4,
                                     wecom_install_session.qr_code_url_encrypted),
    expires_at        = COALESCE($5, wecom_install_session.expires_at),
    updated_at        = now()
WHERE id = $6
  AND lease_token = $7
  AND status IN ('creating', 'pending')
`

type DeferClaimedWecomInstallSessionParams struct {
	PollAfter          pgtype.Timestamptz `json:"poll_after"`
	Status             string             `json:"status"`
	ScodeEncrypted     pgtype.Text        `json:"scode_encrypted"`
	QrCodeUrlEncrypted pgtype.Text        `json:"qr_code_url_encrypted"`
	ExpiresAt          pgtype.Timestamptz `json:"expires_at"`
	ID                 pgtype.UUID        `json:"id"`
	LeaseToken         pgtype.Text        `json:"lease_token"`
}

// Releases the current lease and schedules the next poll. Used when the
// upstream generate/query call yielded init/pending (not terminal) — worker
// steps back so any replica can pick up when poll_after arrives.
// Match-on-lease so a stale worker whose lease already expired cannot
// clobber a new owner's claim.
func (q *Queries) DeferClaimedWecomInstallSession(ctx context.Context, arg DeferClaimedWecomInstallSessionParams) (int64, error) {
	result, err := q.db.Exec(ctx, deferClaimedWecomInstallSession,
		arg.PollAfter,
		arg.Status,
		arg.ScodeEncrypted,
		arg.QrCodeUrlEncrypted,
		arg.ExpiresAt,
		arg.ID,
		arg.LeaseToken,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const failWecomInstallSession = `-- name: FailWecomInstallSession :execrows
UPDATE wecom_install_session
SET status                  = 'error',
    error_reason            = $1,
    error_message           = $2,
    scode_encrypted         = NULL,
    qr_code_url_encrypted   = NULL,
    lease_token             = NULL,
    lease_expires_at        = NULL,
    updated_at              = now()
WHERE id = $3
  AND lease_token = $4
  AND status IN ('creating', 'pending')
`

type FailWecomInstallSessionParams struct {
	ErrorReason  pgtype.Text `json:"error_reason"`
	ErrorMessage pgtype.Text `json:"error_message"`
	ID           pgtype.UUID `json:"id"`
	LeaseToken   pgtype.Text `json:"lease_token"`
}

// Terminal failure. Idempotent: only mutates a still-active session. Wipes
// short-lived ciphertext so a leaked DB dump cannot resurrect the QR after
// the fact. Lease is dropped so the row is not re-claimed.
// Match-on-lease like every other mutation here: without it a worker whose
// lease had already expired could mark a session error out from under the new
// owner that is mid-way through creating the bot.
func (q *Queries) FailWecomInstallSession(ctx context.Context, arg FailWecomInstallSessionParams) (int64, error) {
	result, err := q.db.Exec(ctx, failWecomInstallSession,
		arg.ErrorReason,
		arg.ErrorMessage,
		arg.ID,
		arg.LeaseToken,
	)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const getActiveWecomInstallationForAgent = `-- name: GetActiveWecomInstallationForAgent :one
SELECT id, workspace_id, agent_id, channel_type, config, status, ws_lease_token, ws_lease_expires_at, installer_user_id, installed_at, created_at, updated_at FROM channel_installation
WHERE workspace_id = $1
  AND agent_id = $2
  AND channel_type = 'wecom'
  AND status = 'active'
`

type GetActiveWecomInstallationForAgentParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	AgentID     pgtype.UUID `json:"agent_id"`
}

// Existing active WeCom installation guard for begin. One row per
// (workspace, agent, channel_type='wecom') can be active at a time; the
// handler returns 409 wecom_agent_already_connected here rather than starting an
// install that would fail at finalize.
func (q *Queries) GetActiveWecomInstallationForAgent(ctx context.Context, arg GetActiveWecomInstallationForAgentParams) (ChannelInstallation, error) {
	row := q.db.QueryRow(ctx, getActiveWecomInstallationForAgent, arg.WorkspaceID, arg.AgentID)
	var i ChannelInstallation
	err := row.Scan(
		&i.ID,
		&i.WorkspaceID,
		&i.AgentID,
		&i.ChannelType,
		&i.Config,
		&i.Status,
		&i.WsLeaseToken,
		&i.WsLeaseExpiresAt,
		&i.InstallerUserID,
		&i.InstalledAt,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getPendingWecomInstallSessionByAgent = `-- name: GetPendingWecomInstallSessionByAgent :one
SELECT id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at FROM wecom_install_session
WHERE workspace_id = $1
  AND agent_id = $2
  AND status IN ('creating', 'pending')
`

type GetPendingWecomInstallSessionByAgentParams struct {
	WorkspaceID pgtype.UUID `json:"workspace_id"`
	AgentID     pgtype.UUID `json:"agent_id"`
}

// Recovery lookup for the (workspace, agent) pending slot. At most one row
// per (workspace, agent) has status IN ('creating', 'pending') (indexed by
// idx_wecom_install_session_agent_pending UNIQUE); a begin with a different
// Idempotency-Key returns the existing session.
func (q *Queries) GetPendingWecomInstallSessionByAgent(ctx context.Context, arg GetPendingWecomInstallSessionByAgentParams) (WecomInstallSession, error) {
	row := q.db.QueryRow(ctx, getPendingWecomInstallSessionByAgent, arg.WorkspaceID, arg.AgentID)
	var i WecomInstallSession
	err := row.Scan(
		&i.ID,
		&i.RequestKeyHash,
		&i.WorkspaceID,
		&i.AgentID,
		&i.InitiatorUserID,
		&i.ScodeEncrypted,
		&i.QrCodeUrlEncrypted,
		&i.Status,
		&i.PollAfter,
		&i.ExpiresAt,
		&i.LeaseToken,
		&i.LeaseExpiresAt,
		&i.InstallationID,
		&i.ErrorReason,
		&i.ErrorMessage,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getWecomInstallSession = `-- name: GetWecomInstallSession :one
SELECT id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at FROM wecom_install_session WHERE id = $1
`

func (q *Queries) GetWecomInstallSession(ctx context.Context, id pgtype.UUID) (WecomInstallSession, error) {
	row := q.db.QueryRow(ctx, getWecomInstallSession, id)
	var i WecomInstallSession
	err := row.Scan(
		&i.ID,
		&i.RequestKeyHash,
		&i.WorkspaceID,
		&i.AgentID,
		&i.InitiatorUserID,
		&i.ScodeEncrypted,
		&i.QrCodeUrlEncrypted,
		&i.Status,
		&i.PollAfter,
		&i.ExpiresAt,
		&i.LeaseToken,
		&i.LeaseExpiresAt,
		&i.InstallationID,
		&i.ErrorReason,
		&i.ErrorMessage,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const getWecomInstallSessionByRequestHash = `-- name: GetWecomInstallSessionByRequestHash :one
SELECT id, request_key_hash, workspace_id, agent_id, initiator_user_id, scode_encrypted, qr_code_url_encrypted, status, poll_after, expires_at, lease_token, lease_expires_at, installation_id, error_reason, error_message, created_at, updated_at FROM wecom_install_session
WHERE workspace_id = $1
  AND initiator_user_id = $2
  AND request_key_hash = $3
`

type GetWecomInstallSessionByRequestHashParams struct {
	WorkspaceID     pgtype.UUID `json:"workspace_id"`
	InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
	RequestKeyHash  string      `json:"request_key_hash"`
}

// Idempotent replay lookup for the Idempotency-Key header. Same
// (workspace, initiator, request_key_hash) always returns the same session
// (indexed by idx_wecom_install_session_request UNIQUE). Cross-agent replay
// is caught by the caller comparing the session's agent_id.
func (q *Queries) GetWecomInstallSessionByRequestHash(ctx context.Context, arg GetWecomInstallSessionByRequestHashParams) (WecomInstallSession, error) {
	row := q.db.QueryRow(ctx, getWecomInstallSessionByRequestHash, arg.WorkspaceID, arg.InitiatorUserID, arg.RequestKeyHash)
	var i WecomInstallSession
	err := row.Scan(
		&i.ID,
		&i.RequestKeyHash,
		&i.WorkspaceID,
		&i.AgentID,
		&i.InitiatorUserID,
		&i.ScodeEncrypted,
		&i.QrCodeUrlEncrypted,
		&i.Status,
		&i.PollAfter,
		&i.ExpiresAt,
		&i.LeaseToken,
		&i.LeaseExpiresAt,
		&i.InstallationID,
		&i.ErrorReason,
		&i.ErrorMessage,
		&i.CreatedAt,
		&i.UpdatedAt,
	)
	return i, err
}

const lockWecomInstallBeginWorkspace = `-- name: LockWecomInstallBeginWorkspace :exec

SELECT pg_advisory_xact_lock(
    hashtext('wecom_install_begin'),
    hashtext(($1::uuid)::text)
)
`

// WeCom scan-code install session queries.
//
// The session survives across replicas: the HTTP handler inserts a `creating`
// row via LockWecomInstallBeginWorkspace + insert; the install worker on any
// replica claims due `creating` / `pending` rows via ClaimDueWecomInstallSession
// using an expiring lease so a crashed worker cannot indefinitely hold the row.
//
// No FK / no CASCADE (repo hard rule). workspace_id-scoped rows are cleaned up
// inside DeleteWorkspaceLeafData; the install worker also purges terminal rows
// via PurgeTerminalWecomInstallSessions every minute.
// Serializes the read-then-insert admission decision (request-hash dedupe,
// pending-session recovery, active-installation guard, and 10-minute rate
// window count) across replicas for one (workspace) key. Inline hashtext
// avoids a table-locking pg_advisory_xact_lock namespace collision — the
// 'wecom_install_begin' string keys this namespace apart from any other
// workspace-scoped advisory lock we may add later.
func (q *Queries) LockWecomInstallBeginWorkspace(ctx context.Context, workspaceID pgtype.UUID) error {
	_, err := q.db.Exec(ctx, lockWecomInstallBeginWorkspace, workspaceID)
	return err
}

const purgeTerminalWecomInstallSessions = `-- name: PurgeTerminalWecomInstallSessions :execrows
DELETE FROM wecom_install_session
WHERE (status IN ('success', 'error')
       AND updated_at < $1::timestamptz)
   OR (status = 'creating'
       AND created_at < $2::timestamptz)
`

type PurgeTerminalWecomInstallSessionsParams struct {
	TerminalCutoff pgtype.Timestamptz `json:"terminal_cutoff"`
	CreatingCutoff pgtype.Timestamptz `json:"creating_cutoff"`
}

// GC for terminated sessions older than the retention window (terminal
// sessions preserved for 30 minutes so the frontend can read
// final status after the dialog closes). Also sweeps out `creating` rows
// older than twice the generate deadline, as a defence-in-depth
// for the worker being fully offline.
func (q *Queries) PurgeTerminalWecomInstallSessions(ctx context.Context, arg PurgeTerminalWecomInstallSessionsParams) (int64, error) {
	result, err := q.db.Exec(ctx, purgeTerminalWecomInstallSessions, arg.TerminalCutoff, arg.CreatingCutoff)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}