Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6625: enforce prepaid member seat capacity (#7491)
Multica Eveda7131ab59b5
diff --git a/.env.example b/.env.exampleindex c4bfb6cee2..5d02ce9402 100644--- a/.env.example+++ b/.env.example@@ -214,6 +214,18 @@ MULTICA_ENTITLEMENT_STALE_GRACE=15m# all gates off without contacting Cloud; it cannot enable a policy.MULTICA_ENTITLEMENT_EMERGENCY_DISABLED=false+# Managed pre-purchased member-seat executor. Cloud remains the commercial+# authority; the product only records and retries idempotent capacity intents.+# Keep disabled for self-hosting. The token must match Cloud's+# billing.subscriptions.service_token_env secret.+MULTICA_SUBSCRIPTION_CAPACITY_ENABLED=false+# Keep this true while pausing enforcement so previously recorded confirm and+# release intents continue draining. Enforcement=true implies worker=true.+MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED=false+MULTICA_SUBSCRIPTION_CAPACITY_URL=+MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN=+MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT=3s+# Self-host image channel# Default stable release channel. Pin to an exact release like v0.2.4 if you# want to stay on a specific version. If the selected tag has not beendiff --git a/apps/web/app/join/page.test.tsx b/apps/web/app/join/page.test.tsxindex 04a42bf74d..e3703ba323 100644--- a/apps/web/app/join/page.test.tsx+++ b/apps/web/app/join/page.test.tsx@@ -6,6 +6,7 @@ import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "@multica/views/locales/en/common.json";import enAuth from "@multica/views/locales/en/auth.json";import enSettings from "@multica/views/locales/en/settings.json";+import { ApiError } from "@multica/core/api";import type { ReactNode } from "react";const TEST_RESOURCES = {@@ -60,13 +61,19 @@ vi.mock("@multica/core/auth", async () => {return { ...actual, useAuthStore };});-vi.mock("@multica/core/api", () => ({- api: {- getShareLinkInfo: mockGetShareLinkInfo,- joinByShareLink: mockJoinByShareLink,- listWorkspaces: mockListWorkspaces,- },-}));+vi.mock("@multica/core/api", async () => {+ const actual = await vi.importActual<typeof import("@multica/core/api")>(+ "@multica/core/api",+ );+ return {+ ...actual,+ api: {+ getShareLinkInfo: mockGetShareLinkInfo,+ joinByShareLink: mockJoinByShareLink,+ listWorkspaces: mockListWorkspaces,+ },+ };+});import JoinPage from "./page";@@ -214,4 +221,28 @@ describe("JoinPage", () => {).toBeInTheDocument(),);});++ it.each([+ [+ "seat_capacity_full",+ "All purchased member seats are in use. Ask a workspace admin to add a seat before trying again.",+ ],+ [+ "seat_capacity_unavailable",+ "Member capacity could not be verified. Please try again.",+ ],+ ])("maps %s to a user-facing capacity message", async (code, message) => {+ const user = userEvent.setup();+ authStateRef.state.user = { id: "u1", email: "[email protected]" };+ mockJoinByShareLink.mockRejectedValue(+ new ApiError("server fallback", 409, "Conflict", { code }),+ );++ render(<JoinPage />, { wrapper: createWrapper() });++ await user.click(+ await screen.findByRole("button", { name: "Join Workspace" }),+ );+ await waitFor(() => expect(screen.getByText(message)).toBeInTheDocument());+ });});diff --git a/apps/web/app/join/page.tsx b/apps/web/app/join/page.tsxindex 2912641d43..4cfdf69932 100644--- a/apps/web/app/join/page.tsx+++ b/apps/web/app/join/page.tsx@@ -3,7 +3,7 @@import { useEffect, useState, Suspense } from "react";import { useRouter, useSearchParams } from "next/navigation";import { useQueryClient } from "@tanstack/react-query";-import { api } from "@multica/core/api";+import { api, errorCode } from "@multica/core/api";import { Button } from "@multica/ui/components/ui/button";import { Card, CardContent } from "@multica/ui/components/ui/card";import { Badge } from "@multica/ui/components/ui/badge";@@ -65,6 +65,7 @@ function JoinInner() {}, 1200);}).catch(async (e) => {+ const code = errorCode(e);const msg = e instanceof Error ? e.message : "";if (msg.includes("already a member")) {// Already joined: go straight to the workspace this invite points at@@ -88,6 +89,14 @@ function JoinInner() {return;}setJoining(false);+ if (code === "seat_capacity_full") {+ setJoinError("All purchased member seats are in use. Ask a workspace admin to add a seat before trying again.");+ return;+ }+ if (code === "seat_capacity_unavailable") {+ setJoinError("Member capacity could not be verified. Please try again.");+ return;+ }setJoinError(msg || "Failed to join the workspace. The link may have expired.");});};diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex 46447728d2..2e9fda1a3d 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -25,6 +25,10 @@ data:MULTICA_ENTITLEMENT_POLICY_TIMEOUT: {{ .Values.backend.config.entitlementPolicy.timeout | quote }}MULTICA_ENTITLEMENT_STALE_GRACE: {{ .Values.backend.config.entitlementPolicy.staleGrace | quote }}MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: {{ .Values.backend.config.entitlementPolicy.emergencyDisabled | quote }}+ MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: {{ .Values.backend.config.subscriptionCapacity.enabled | quote }}+ MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: {{ .Values.backend.config.subscriptionCapacity.workerEnabled | quote }}+ MULTICA_SUBSCRIPTION_CAPACITY_URL: {{ .Values.backend.config.subscriptionCapacity.url | quote }}+ MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: {{ .Values.backend.config.subscriptionCapacity.timeout | quote }}GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}GOOGLE_REDIRECT_URI: {{ .Values.backend.config.googleRedirectUri | quote }}S3_BUCKET: {{ .Values.backend.config.s3Bucket | quote }}diff --git a/deploy/helm/multica/templates/prometheusrule.yaml b/deploy/helm/multica/templates/prometheusrule.yamlindex 6b4640e76d..4180a77ba6 100644--- a/deploy/helm/multica/templates/prometheusrule.yaml+++ b/deploy/helm/multica/templates/prometheusrule.yaml@@ -40,4 +40,23 @@ spec:annotations:summary: "Business sampler query p95 is high"description: "Business sampler query {{ "{{ $labels.name }}" }} p95 is above 300ms, leaving little headroom before the 500ms statement_timeout."+ - alert: MulticaSeatCapacityOutboxDeadLettered+ expr: |+ sum by (action) (multica_seat_capacity_outbox_dead_lettered) > 0+ for: {{ .Values.monitoring.prometheusRule.seatCapacityDeadLetteredFor | quote }}+ labels:+ severity: {{ .Values.monitoring.prometheusRule.severity | quote }}+ annotations:+ summary: "Seat capacity intent requires repair"+ description: "At least one {{ "{{ $labels.action }}" }} seat capacity intent exhausted automatic retries and entered the dead-letter state."+ - alert: MulticaSeatCapacityOutboxStalled+ expr: |+ max by (action) (multica_seat_capacity_outbox_oldest_pending_age_seconds)+ > {{ .Values.monitoring.prometheusRule.seatCapacityPendingAgeSeconds }}+ for: {{ .Values.monitoring.prometheusRule.seatCapacityPendingFor | quote }}+ labels:+ severity: {{ .Values.monitoring.prometheusRule.severity | quote }}+ annotations:+ summary: "Seat capacity outbox is stalled"+ description: "The oldest {{ "{{ $labels.action }}" }} seat capacity intent has remained unsettled beyond the configured age threshold."{{- end }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex b29753bb5c..fe5cc44359 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -29,6 +29,7 @@ images:# --from-literal=GOOGLE_CLIENT_SECRET="" \# --from-literal=CLOUDFRONT_PRIVATE_KEY="" \# --from-literal=MULTICA_ENTITLEMENT_SERVICE_TOKEN="" \+# --from-literal=MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN="" \# --from-literal=MULTICA_DEV_VERIFICATION_CODE=""## External postgres (postgres.external.enabled=true):@@ -40,6 +41,7 @@ images:# --from-literal=GOOGLE_CLIENT_SECRET="" \# --from-literal=CLOUDFRONT_PRIVATE_KEY="" \# --from-literal=MULTICA_ENTITLEMENT_SERVICE_TOKEN="" \+# --from-literal=MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN="" \# --from-literal=MULTICA_DEV_VERIFICATION_CODE=""## The chart references this Secret by name; it does not template it, so real@@ -148,6 +150,15 @@ backend:staleGrace: 15m# Local down switch applied by the next chart rollout; it only forces off.emergencyDisabled: false+ # Managed Cloud seat-capacity executor. Keep off for self-hosting. When+ # enabled, put the matching service token in existingSecret.+ subscriptionCapacity:+ enabled: false+ # Keep settlement running while enforcement is paused so durable+ # confirm/release intents drain. enabled=true also starts the worker.+ workerEnabled: false+ url: ""+ timeout: 3sgoogleClientId: ""googleRedirectUri: http://multica.dev.lan/auth/callbacks3Bucket: ""@@ -232,4 +243,7 @@ monitoring:additionalLabels: {}samplerQueryErrorsFor: 5msamplerQueryLatencyFor: 10m+ seatCapacityDeadLetteredFor: 5m+ seatCapacityPendingAgeSeconds: 900+ seatCapacityPendingFor: 5mseverity: warningdiff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 458492b19e..9ded8af82a 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -114,6 +114,12 @@ services:MULTICA_ENTITLEMENT_POLICY_TIMEOUT: ${MULTICA_ENTITLEMENT_POLICY_TIMEOUT:-3s}MULTICA_ENTITLEMENT_STALE_GRACE: ${MULTICA_ENTITLEMENT_STALE_GRACE:-15m}MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: ${MULTICA_ENTITLEMENT_EMERGENCY_DISABLED:-false}+ # Managed seat capacity is also opt-in and stays off for self-hosting.+ MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: ${MULTICA_SUBSCRIPTION_CAPACITY_ENABLED:-false}+ MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: ${MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED:-false}+ MULTICA_SUBSCRIPTION_CAPACITY_URL: ${MULTICA_SUBSCRIPTION_CAPACITY_URL:-}+ MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN: ${MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN:-}+ MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: ${MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT:-3s}GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}GITHUB_WEBHOOK_SECRET: ${GITHUB_WEBHOOK_SECRET:-}# App API credentials. The pull_request webhook is what mirrors a PRdiff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex b96368942d..623c97d924 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -225,6 +225,8 @@"summary_loading": "Loading subscription seat details","summary_unavailable_title": "Some seat details are unavailable","summary_unavailable_description": "The current plan is still shown, but purchased and scheduled seat quantities could not be loaded.",+ "members_over_capacity_title": "Members exceed purchased seats",+ "members_over_capacity_description": "This workspace has {{actual}} members but only {{purchased}} purchased seats. Add enough seats or remove members before sending more invitations.","updated": "Seats refreshed","reconciled": "Current members: {{actual}} · billed seats: {{billed}}"},diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 0d9d3e81cd..6bb61c381c 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1157,6 +1157,9 @@"inviting": "Inviting...","toast_invitation_sent": "Invitation sent","toast_invitation_failed": "Failed to send invitation",+ "toast_seat_capacity_full": "All purchased member seats are in use. Add a seat before inviting someone else.",+ "toast_seat_capacity_unavailable": "Member capacity could not be verified. Please try again.",+ "add_seats_action": "Add seats","no_members": "No members found.","pending_title": "Pending invitations ({{count}})","pending_status": "Pending",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 0d7b22eb71..70163e9344 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -221,6 +221,8 @@"summary_loading": "サブスクリプションの席数詳細を読み込み中","summary_unavailable_title": "一部の席数詳細を利用できません","summary_unavailable_description": "現在のプランは表示できますが、購入済みの席数と変更予定の席数を読み込めませんでした。",+ "members_over_capacity_title": "メンバー数が購入済みの席数を超えています",+ "members_over_capacity_description": "このワークスペースには {{actual}} 人のメンバーがいますが、購入済みの席は {{purchased}} 席です。さらに招待する前に席を追加するか、メンバーを削除してください。","updated": "席数を更新しました","reconciled": "現在のメンバー: {{actual}} · 請求席数: {{billed}}"},diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 9af44e6c08..d849636863 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1154,6 +1154,9 @@"inviting": "招待中...","toast_invitation_sent": "招待を送信しました","toast_invitation_failed": "招待を送信できませんでした",+ "toast_seat_capacity_full": "購入済みのメンバー席をすべて使用しています。新しいメンバーを招待する前に席を追加してください。",+ "toast_seat_capacity_unavailable": "メンバー席を確認できませんでした。もう一度お試しください。",+ "add_seats_action": "席を追加","no_members": "メンバーが見つかりません。","pending_title": "保留中の招待({{count}})","pending_status": "保留中",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex db4b2f4479..ea42d9d213 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -221,6 +221,8 @@"summary_loading": "구독 좌석 상세 정보 불러오는 중","summary_unavailable_title": "일부 좌석 상세 정보를 불러올 수 없습니다","summary_unavailable_description": "현재 요금제는 계속 표시되지만 구매한 좌석과 예정 좌석 수를 불러오지 못했습니다.",+ "members_over_capacity_title": "멤버 수가 구매한 좌석 수를 초과합니다",+ "members_over_capacity_description": "이 워크스페이스에는 멤버가 {{actual}}명이지만 구매한 좌석은 {{purchased}}개입니다. 더 초대하기 전에 좌석을 추가하거나 멤버를 제거하세요.","updated": "좌석 새로고침됨","reconciled": "현재 멤버: {{actual}} · 결제 좌석: {{billed}}"},diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 885a72d702..58b2f53929 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -892,6 +892,9 @@"inviting": "초대하는 중...","toast_invitation_sent": "초대를 보냈습니다","toast_invitation_failed": "초대를 보내지 못했습니다",+ "toast_seat_capacity_full": "구매한 멤버 좌석을 모두 사용 중입니다. 새 멤버를 초대하기 전에 좌석을 추가하세요.",+ "toast_seat_capacity_unavailable": "멤버 좌석을 확인할 수 없습니다. 다시 시도해 주세요.",+ "add_seats_action": "좌석 추가","no_members": "멤버를 찾을 수 없습니다.","pending_title": "대기 중인 초대 ({{count}})","pending_status": "대기 중",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 5d58397d7e..d77ab855d0 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -221,6 +221,8 @@"summary_loading": "正在加载订阅席位详情","summary_unavailable_title": "部分席位详情不可用","summary_unavailable_description": "当前套餐仍会显示,但暂时无法加载已购席位和待生效席位。",+ "members_over_capacity_title": "成员数超过已购席位",+ "members_over_capacity_description": "当前工作区有 {{actual}} 名成员,但只购买了 {{purchased}} 个席位。继续邀请前,请补足席位或移除成员。","updated": "席位已刷新","reconciled": "当前成员:{{actual}} · 计费席位:{{billed}}"},diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 4c365a3a9b..9328666c0e 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1154,6 +1154,9 @@"inviting": "邀请中...","toast_invitation_sent": "已发送邀请","toast_invitation_failed": "发送邀请失败",+ "toast_seat_capacity_full": "已购买的成员席位已全部使用,请先增加席位再邀请新成员。",+ "toast_seat_capacity_unavailable": "暂时无法核验成员席位,请稍后重试。",+ "add_seats_action": "增加席位","no_members": "未找到成员。","pending_title": "待处理邀请({{count}})","pending_status": "待处理",diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 143a00233f..f9931b4c15 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -1389,6 +1389,55 @@ describe("BillingTab", () => {);});+ it("warns when actual members exceed purchased seats", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ version: 3,+ });+ Object.assign(mocks.summary, {+ actualSeats: 5,+ usedSeats: 4,+ billedSeats: 4,+ reservedSeats: 0,+ purchaseVersion: 9,+ });++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Members exceed purchased seats")).toBeInTheDocument();+ expect(+ screen.getByText(+ "This workspace has 5 members but only 4 purchased seats. Add enough seats or remove members before sending more invitations.",+ ),+ ).toBeInTheDocument();+ });++ it("does not expose a transient used-seat ledger delay to customers", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ version: 3,+ });+ Object.assign(mocks.summary, {+ actualSeats: 5,+ usedSeats: 4,+ billedSeats: 5,+ reservedSeats: 0,+ purchaseVersion: 9,+ });++ renderWithI18n(<BillingTab />);++ expect(+ screen.queryByText("Members exceed purchased seats"),+ ).not.toBeInTheDocument();+ });+it.each(["canceled", "incomplete_expired"])("keeps management and self-service repurchase available for %s Free",(status) => {diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex a7b866e397..f9f80c4478 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -905,6 +905,12 @@ function BillingTabContent() {const billedSeats = summaryQuery.data?.billedSeats;const pendingSeatQuantity = summaryQuery.data?.pendingSeatQuantity;const reservedSeats = summaryQuery.data?.reservedSeats ?? 0;+ const membersExceedPurchasedSeats =+ hasManagedSubscription &&+ summaryQuery.data !== undefined &&+ billedSeats !== null &&+ billedSeats !== undefined &&+ actualSeats > billedSeats;const availableSeats =billedSeats === null || billedSeats === undefined? null@@ -1486,6 +1492,35 @@ function BillingTabContent() {<AlertDescription>{reconcileMessage}</AlertDescription></Alert>) : null}+ {membersExceedPurchasedSeats ? (+ <Alert className="mb-3">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.seats.members_over_capacity_title)}+ </AlertTitle>+ <AlertDescription>+ <p>+ {t(($) => $.workspace.seats.members_over_capacity_description, {+ actual: actualSeats,+ purchased: billedSeats,+ })}+ </p>+ {canAddSeats ? (+ <Button+ className="mt-3"+ type="button"+ variant="outline"+ size="sm"+ disabled={isMutating}+ onClick={() => handleSeatPurchaseOpenChange(true)}+ >+ <Plus />+ {t(($) => $.workspace.actions.add_seats)}+ </Button>+ ) : null}+ </AlertDescription>+ </Alert>+ ) : null}{activeSeatPurchase ? (<Alert className="mb-3">{seatPurchasePollingTimedOut ? (diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsxindex 57f73efeca..b42b200ab5 100644--- a/packages/views/settings/components/members-tab.tsx+++ b/packages/views/settings/components/members-tab.tsx@@ -42,7 +42,7 @@ import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace } from "@multica/core/paths";import { memberListOptions, invitationListOptions, shareLinkListOptions, workspaceKeys } from "@multica/core/workspace/queries";-import { api } from "@multica/core/api";+import { api, errorCode } from "@multica/core/api";import { useT } from "../../i18n";import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";@@ -348,6 +348,22 @@ export function MembersTab() {qc.invalidateQueries({ queryKey: workspaceKeys.invitations(wsId) });toast.success(t(($) => $.members.toast_invitation_sent));} catch (e) {+ const code = errorCode(e);+ if (code === "seat_capacity_full") {+ toast.error(t(($) => $.members.toast_seat_capacity_full), {+ action: navigation+ ? {+ label: t(($) => $.members.add_seats_action),+ onClick: () => navigation.push(`/${workspace.slug}/settings?tab=billing`),+ }+ : undefined,+ });+ return;+ }+ if (code === "seat_capacity_unavailable") {+ toast.error(t(($) => $.members.toast_seat_capacity_unavailable));+ return;+ }toast.error(e instanceof Error ? e.message : t(($) => $.members.toast_invitation_failed));} finally {setInviteLoading(false);diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.shindex 1be96b89ce..1ef483b12a 100644--- a/scripts/helm-config.test.sh+++ b/scripts/helm-config.test.sh@@ -35,10 +35,14 @@ default_config="$(require_rendered_value "$default_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "true"'require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "false"'require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_URL: ""'+require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: "false"'+require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: "false"'+require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL: ""'require_rendered_value "$default_config" 'MULTICA_TASK_QUEUED_TTL: "2h"'require_rendered_value "$default_config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: "3m"'require_rendered_value "$default_config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: "5s"'reject_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'+reject_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN'queued_ttl_config="$(helm template multica "$CHART_DIR" \@@ -79,4 +83,27 @@ require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_STALE_GRACE: "require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: "false"'reject_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'+capacity_config="$(+ helm template multica "$CHART_DIR" \+ --show-only templates/configmap.yaml \+ --set backend.config.subscriptionCapacity.enabled=true \+ --set backend.config.subscriptionCapacity.workerEnabled=true \+ --set-string backend.config.subscriptionCapacity.url=https://multica-cloud.internal \+ --set-string backend.config.subscriptionCapacity.timeout=2s+)"+require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: "true"'+require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: "true"'+require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL: "https://multica-cloud.internal"'+require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: "2s"'+reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN'++capacity_alerts="$(+ helm template multica "$CHART_DIR" \+ --show-only templates/prometheusrule.yaml \+ --set monitoring.prometheusRule.enabled=true+)"+require_rendered_value "$capacity_alerts" 'alert: MulticaSeatCapacityOutboxDeadLettered'+require_rendered_value "$capacity_alerts" 'alert: MulticaSeatCapacityOutboxStalled'+require_rendered_value "$capacity_alerts" 'multica_seat_capacity_outbox_oldest_pending_age_seconds'+echo "helm config rendering ok"diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 7757150ef1..a48765564e 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -261,6 +261,9 @@ var concurrentIndexCleanups = map[string]string{"412_issue_source_context_object_intent_key_index": "idx_issue_source_context_object_intent_key","413_issue_source_context_object_intent_due_index": "idx_issue_source_context_object_intent_due","414_issue_source_context_object_intent_context_index": "idx_issue_source_context_object_intent_context",+ "416_seat_capacity_operation_token_index": "idx_seat_capacity_outbox_operation_token",+ "418_seat_capacity_due_index": "idx_seat_capacity_outbox_due",+ "419_seat_capacity_share_join_index": "idx_seat_capacity_outbox_share_join",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex f3e67d5990..90535e283d 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -487,6 +487,7 @@ func main() {var samplerPool *pgxpool.Poolvar channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetricsvar channelLeaseMetrics *obsmetrics.ChannelLeaseMetrics+ var seatCapacityMetrics *obsmetrics.SeatCapacityMetricsvar wecomMetrics *obsmetrics.WecomMetricsif metricsConfig.Enabled() {// Build a dedicated tiny pool for the BusinessSamplerCollector@@ -517,6 +518,7 @@ func main() {businessMetrics = metricsRegistry.BusinesschannelMediaMetrics = metricsRegistry.ChannelMediachannelLeaseMetrics = metricsRegistry.ChannelLease+ seatCapacityMetrics = metricsRegistry.SeatCapacitywecomMetrics = metricsRegistry.Wecom// Forward inbound daemon WS frames into the per-kind counter so// dashboards can split heartbeat / unknown / invalid traffic.@@ -554,6 +556,7 @@ func main() {HTTPMetrics: httpMetrics,BusinessMetrics: businessMetrics,ChannelLeaseMetrics: channelLeaseMetrics,+ SeatCapacityMetrics: seatCapacityMetrics,ChannelLeaseRedis: channelLeaseRedis,WecomMetrics: wecomMetrics,DaemonHub: daemonHub,@@ -613,6 +616,9 @@ func main() {if h.WebhookDeliveryWorker != nil {go h.WebhookDeliveryWorker.Run(sweepCtx)}+ if h.SeatCapacityWorker != nil {+ go h.SeatCapacityWorker.Run(sweepCtx)+ }if h.TelegramOutbound != nil {h.TelegramOutbound.Start(sweepCtx)}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 4d4df96599..d4381cad2a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -37,6 +37,7 @@ import (obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/seatcapacity""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util"@@ -215,6 +216,7 @@ type RouterOptions struct {HTTPMetrics *obsmetrics.HTTPMetricsBusinessMetrics *obsmetrics.BusinessMetricsChannelLeaseMetrics *obsmetrics.ChannelLeaseMetrics+ SeatCapacityMetrics *obsmetrics.SeatCapacityMetrics// ChannelLeaseRedis is a dedicated non-blocking Redis client/pool. It is// required only when CHANNEL_WS_LEASE_BACKEND=redis.ChannelLeaseRedis *redis.Client@@ -419,6 +421,35 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}+ capacityEnforcementEnabled := envBool("MULTICA_SUBSCRIPTION_CAPACITY_ENABLED", false)+ // Settlement remains independently enabled during an enforcement rollback+ // so existing confirm/release intents keep draining. Enforcement always+ // implies settlement; operators only need the separate flag when pausing+ // new capacity admission.+ capacityWorkerEnabled := capacityEnforcementEnabled || envBool("MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED", false)+ capacityClient, capacityErr := seatcapacity.New(seatcapacity.Config{+ Enabled: capacityWorkerEnabled,+ BaseURL: strings.TrimSpace(os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_URL")),+ ServiceToken: os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN"),+ Timeout: envDuration("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", 3*time.Second),+ })+ if capacityErr != nil {+ // Explicit enablement with malformed config must not silently restore+ // unlimited membership. The fail-closed executor returns 503 until the+ // operator repairs the service URL or credential.+ slog.Error("subscription seat capacity executor unavailable", "error", capacityErr)+ h.SeatCapacity = seatcapacity.NewUnavailable(capacityErr)+ } else {+ h.SeatCapacity = capacityClient+ }+ h.SeatCapacityEnforcementEnabled = capacityEnforcementEnabled+ capacityLocker := seatcapacity.NewWorkspaceLocker(pool)+ h.SeatCapacityLocker = capacityLocker+ if capacityWorkerEnabled && h.SeatCapacity.Enabled() {+ h.SeatCapacityWorker = seatcapacity.NewWorker(queries, h.SeatCapacity, capacityLocker, seatcapacity.WorkerConfig{+ Metrics: opts.SeatCapacityMetrics,+ })+ }if opts.BusinessMetrics != nil {// Wire the BusinessMetrics receiver into the cloud runtime client// so every outbound Fleet/Gateway request feeds thediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex ae670ab4c7..fb4de4f3dd 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -36,6 +36,7 @@ import (obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/seatcapacity""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/util"@@ -190,13 +191,19 @@ type Handler struct {AutopilotService *service.AutopilotService// Entitlements supplies workspace-scoped commercial gates. A nil provider// preserves the self-hosted and pre-rollout behavior without extra reads.- Entitlements entitlement.Provider- EmailService *service.EmailService- UpdateStore UpdateStore- ModelListStore ModelListStore- LocalSkillListStore LocalSkillListStore- LocalSkillImportStore LocalSkillImportStore- FeatureFlags *featureflag.Service+ Entitlements entitlement.Provider+ // SeatCapacity executes Cloud's pre-purchased human-seat protocol. Nil or+ // disabled preserves self-hosted behavior.+ SeatCapacity seatcapacity.Executor+ SeatCapacityEnforcementEnabled bool+ SeatCapacityLocker seatcapacity.WorkspaceLocker+ SeatCapacityWorker *seatcapacity.Worker+ EmailService *service.EmailService+ UpdateStore UpdateStore+ ModelListStore ModelListStore+ LocalSkillListStore LocalSkillListStore+ LocalSkillImportStore LocalSkillImportStore+ FeatureFlags *featureflag.Service// IssueStatusCatalog reads the workspace status catalog. Defaults to// Queries; a test can substitute a counting wrapper to assert HOW MANY// catalog reads a request performs, which is the only property thatdiff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex db9c1d32a2..87c2ef088e 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -8,10 +8,12 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/google/uuid""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/logger"obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/seatcapacity"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -99,14 +101,23 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {// Drop any past-due pending invitations to 'expired' first. The partial unique// index idx_invitation_unique_pending only filters by status = 'pending', so a// stale row would otherwise block CreateInvitation below — see issue #2055.- if err := h.Queries.ExpireStalePendingInvitations(r.Context(), db.ExpireStalePendingInvitationsParams{- WorkspaceID: requester.WorkspaceID,- InviteeEmail: email,- }); err != nil {+ expiredInvitations, err := h.Queries.ExpireStalePendingInvitations(r.Context(), db.ExpireStalePendingInvitationsParams{+ WorkspaceID: requester.WorkspaceID, InviteeEmail: email,+ })+ if err != nil {slog.Warn("expire stale invitations failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID, "email", email)...)writeError(w, http.StatusInternalServerError, "failed to create invitation")return}+ if h.seatCapacitySettlementEnabled() {+ for _, expired := range expiredInvitations {+ if err := enqueueCapacityRelease(r.Context(), h.Queries, uuid.UUID(expired.WorkspaceID.Bytes), uuid.UUID(expired.ID.Bytes)); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to release expired invitation capacity")+ return+ }+ h.compensateCapacityIntent(r.Context(), uuid.UUID(expired.ID.Bytes))+ }+ }// Check if there is still a live pending invitation._, err = h.Queries.GetPendingInvitationByEmail(r.Context(), db.GetPendingInvitationByEmailParams{@@ -136,14 +147,47 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {inviteeUserID = existingUser.ID}- inv, err := h.Queries.CreateInvitation(r.Context(), db.CreateInvitationParams{- WorkspaceID: requester.WorkspaceID,- InviterID: requester.UserID,- InviteeEmail: email,- InviteeUserID: inviteeUserID,- Role: role,- })+ invitationID := uuid.New()+ expiresAt := time.Now().Add(7 * 24 * time.Hour)+ if err := h.reserveInvitationCapacity(r.Context(), uuid.UUID(requester.WorkspaceID.Bytes), invitationID, expiresAt); err != nil {+ writeSeatCapacityError(w, err)+ return+ }++ createParams := db.CreateInvitationParams{+ ID: uuidToPG(invitationID), WorkspaceID: requester.WorkspaceID, InviterID: requester.UserID,+ InviteeEmail: email, InviteeUserID: inviteeUserID, Role: role,+ ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},+ }+ var inv db.WorkspaceInvitation+ if h.seatCapacityEnabled() {+ tx, txErr := h.TxStarter.Begin(r.Context())+ if txErr != nil {+ h.compensateCapacityIntent(r.Context(), invitationID)+ writeError(w, http.StatusInternalServerError, "failed to create invitation")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)+ inv, err = qtx.CreateInvitation(r.Context(), createParams)+ if err == nil {+ err = qtx.DeleteSeatCapacityIntentForAction(r.Context(), db.DeleteSeatCapacityIntentForActionParams{+ OperationToken: uuidToPG(invitationID), Action: seatcapacity.ActionReserveInvitation,+ })+ }+ if err == nil {+ err = tx.Commit(r.Context())+ }+ if err != nil {+ // Release transaction locks before the out-of-transaction Cloud+ // compensation below reads and transitions the durable intent.+ _ = tx.Rollback(r.Context())+ }+ } else {+ inv, err = h.Queries.CreateInvitation(r.Context(), createParams)+ }if err != nil {+ h.compensateCapacityIntent(r.Context(), invitationID)if isUniqueViolation(err) {writeError(w, http.StatusConflict, "invitation already pending for this email")return@@ -253,10 +297,35 @@ func (h *Handler) RevokeInvitation(w http.ResponseWriter, r *http.Request) {return}- if err := h.Queries.RevokeInvitation(r.Context(), inv.ID); err != nil {+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {writeError(w, http.StatusInternalServerError, "failed to revoke invitation")return}+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)+ rows, err := qtx.RevokeInvitation(r.Context(), inv.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to revoke invitation")+ return+ }+ if rows != 1 {+ writeError(w, http.StatusNotFound, "invitation not found")+ return+ }+ if h.seatCapacitySettlementEnabled() {+ if err := enqueueCapacityRelease(r.Context(), qtx, uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes)); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to revoke invitation")+ return+ }+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to revoke invitation")+ return+ }+ if h.seatCapacitySettlementEnabled() {+ h.compensateCapacityIntent(r.Context(), uuid.UUID(inv.ID.Bytes))+ }slog.Info("invitation revoked", "invitation_id", invitationID, "workspace_id", workspaceID)@@ -408,6 +477,11 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusGone, "invitation has expired")return}+ capacityActive, err := h.beginCapacityConsume(r.Context(), uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(user.ID.Bytes))+ if err != nil {+ writeSeatCapacityError(w, err)+ return+ }// Use a transaction: mark accepted + create member atomically.tx, err := h.TxStarter.Begin(r.Context())@@ -454,11 +528,20 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to mark user onboarded")return}+ if capacityActive {+ if err := transitionCapacityIntentToConfirm(r.Context(), qtx, uuid.UUID(inv.ID.Bytes), uuid.UUID(member.ID.Bytes), seatcapacity.ActionConsumeInvitation); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to accept invitation")+ return+ }+ }if err := tx.Commit(r.Context()); err != nil {writeError(w, http.StatusInternalServerError, "failed to accept invitation")return}+ if capacityActive {+ h.confirmCapacityIntent(r.Context(), uuid.UUID(accepted.WorkspaceID.Bytes), uuid.UUID(accepted.ID.Bytes), uuid.UUID(member.ID.Bytes))+ }slog.Info("invitation accepted", "invitation_id", invitationID, "user_id", userID, "workspace_id", uuidToString(accepted.WorkspaceID))@@ -546,11 +629,31 @@ func (h *Handler) DeclineInvitation(w http.ResponseWriter, r *http.Request) {return}- declined, err := h.Queries.DeclineInvitation(r.Context(), inv.ID)+ tx, err := h.TxStarter.Begin(r.Context())if err != nil {writeError(w, http.StatusInternalServerError, "failed to decline invitation")return}+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)+ declined, err := qtx.DeclineInvitation(r.Context(), inv.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to decline invitation")+ return+ }+ if h.seatCapacitySettlementEnabled() {+ if err := enqueueCapacityRelease(r.Context(), qtx, uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes)); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to decline invitation")+ return+ }+ }+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to decline invitation")+ return+ }+ if h.seatCapacitySettlementEnabled() {+ h.compensateCapacityIntent(r.Context(), uuid.UUID(inv.ID.Bytes))+ }slog.Info("invitation declined", "invitation_id", invitationID, "user_id", userID)diff --git a/server/internal/handler/invitation_test.go b/server/internal/handler/invitation_test.goindex ee2e4a1153..7ce7e7f995 100644--- a/server/internal/handler/invitation_test.go+++ b/server/internal/handler/invitation_test.go@@ -13,12 +13,68 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/seatcapacity")const invitationTestEmail = "[email protected]"+type stubSeatCapacity struct {+ reserveDecision seatcapacity.Decision+ reserveErr error+ reserveCalls int+ releaseCalls int+ consumeCalls int+ consumeDecision *seatcapacity.Decision+ consumeErr error+}++func (s *stubSeatCapacity) Enabled() bool { return true }+func (s *stubSeatCapacity) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (seatcapacity.Decision, error) {+ s.reserveCalls+++ return s.reserveDecision, s.reserveErr+}+func (s *stubSeatCapacity) ClaimShareJoin(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *stubSeatCapacity) Consume(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ s.consumeCalls+++ decision := seatcapacity.Decision{Managed: true, Allowed: true}+ if s.consumeDecision != nil {+ decision = *s.consumeDecision+ }+ return decision, s.consumeErr+}+func (s *stubSeatCapacity) Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *stubSeatCapacity) Release(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ s.releaseCalls+++ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *stubSeatCapacity) ReleaseMember(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *stubSeatCapacity) GetOperation(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{}, nil+}++func useSeatCapacity(t *testing.T, executor seatcapacity.Executor) {+ t.Helper()+ previous := testHandler.SeatCapacity+ previousEnforcement := testHandler.SeatCapacityEnforcementEnabled+ testHandler.SeatCapacity = executor+ testHandler.SeatCapacityEnforcementEnabled = true+ t.Cleanup(func() {+ testHandler.SeatCapacity = previous+ testHandler.SeatCapacityEnforcementEnabled = previousEnforcement+ })+}+func TestDefaultInvitationRateLimits(t *testing.T) {limits := DefaultInvitationRateLimits()want := SlidingWindowRateLimit{Limit: 6, Window: 24 * time.Hour}@@ -90,6 +146,27 @@ func clearInvitationsForTestWorkspace(t *testing.T) {})}+type rollbackOnCommitTx struct {+ pgx.Tx+}++func (tx rollbackOnCommitTx) Commit(ctx context.Context) error {+ _ = tx.Tx.Rollback(ctx)+ return errors.New("forced commit failure")+}++type rollbackOnCommitTxStarter struct {+ pool *pgxpool.Pool+}++func (s rollbackOnCommitTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return nil, err+ }+ return rollbackOnCommitTx{Tx: tx}, nil+}+// Sanity check: a fresh, live pending invitation must block re-invitation.func TestCreateInvitation_BlocksWhilePending(t *testing.T) {clearInvitationsForTestWorkspace(t)@@ -129,6 +206,91 @@ func TestCreateInvitation_BlocksWhilePending(t *testing.T) {}}+func TestCreateInvitation_BlocksWhenPurchasedCapacityIsFull(t *testing.T) {+ clearInvitationsForTestWorkspace(t)+ if _, err := testPool.Exec(context.Background(), `DELETE FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("clear capacity outbox: %v", err)+ }+ capacity := &stubSeatCapacity{reserveDecision: seatcapacity.Decision{+ Managed: true, Allowed: false, Reason: "capacity_full",+ }}+ useSeatCapacity(t, capacity)++ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{+ Email: "[email protected]", Role: "member",+ })+ req = withURLParam(req, "id", testWorkspaceID)+ rec := httptest.NewRecorder()+ testHandler.CreateInvitation(rec, req)++ if rec.Code != http.StatusConflict {+ t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())+ }+ var body struct {+ Code string `json:"code"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ if body.Code != "seat_capacity_full" {+ t.Fatalf("code = %q, want seat_capacity_full", body.Code)+ }+ if capacity.reserveCalls != 1 {+ t.Fatalf("reserve calls = %d, want 1", capacity.reserveCalls)+ }+ var invitationCount, outboxCount int+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM workspace_invitation WHERE workspace_id = $1 AND invitee_email = $2`, parseUUID(testWorkspaceID), "[email protected]").Scan(&invitationCount); err != nil {+ t.Fatal(err)+ }+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)).Scan(&outboxCount); err != nil {+ t.Fatal(err)+ }+ if invitationCount != 0 || outboxCount != 0 {+ t.Fatalf("persisted invitation=%d outbox=%d, want both zero", invitationCount, outboxCount)+ }+}++func TestCreateInvitation_CompensatesCapacityWhenCommitRollsBack(t *testing.T) {+ clearInvitationsForTestWorkspace(t)+ ctx := context.Background()+ workspaceID := parseUUID(testWorkspaceID)+ if _, err := testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE workspace_id = $1`, workspaceID); err != nil {+ t.Fatalf("clear capacity outbox: %v", err)+ }++ capacity := &stubSeatCapacity{reserveDecision: seatcapacity.Decision{Managed: true, Allowed: true}}+ useSeatCapacity(t, capacity)+ previousTxStarter := testHandler.TxStarter+ testHandler.TxStarter = rollbackOnCommitTxStarter{pool: testPool}+ t.Cleanup(func() { testHandler.TxStarter = previousTxStarter })++ const email = "[email protected]"+ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{+ Email: email, Role: "member",+ })+ req = withURLParam(req, "id", testWorkspaceID)+ rec := httptest.NewRecorder()+ testHandler.CreateInvitation(rec, req)++ if rec.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want 500: %s", rec.Code, rec.Body.String())+ }+ if capacity.reserveCalls != 1 || capacity.releaseCalls != 1 {+ t.Fatalf("reserve calls = %d, release calls = %d; want one each", capacity.reserveCalls, capacity.releaseCalls)+ }++ var invitationCount, outboxCount int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace_invitation WHERE workspace_id = $1 AND invitee_email = $2`, workspaceID, email).Scan(&invitationCount); err != nil {+ t.Fatal(err)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM seat_capacity_outbox WHERE workspace_id = $1`, workspaceID).Scan(&outboxCount); err != nil {+ t.Fatal(err)+ }+ if invitationCount != 0 || outboxCount != 0 {+ t.Fatalf("persisted invitation=%d outbox=%d, want both zero after compensation", invitationCount, outboxCount)+ }+}+// Regression for issue #2055: an expired pending invitation must NOT block a// new invitation to the same email. The stale row should be flipped to// 'expired' and a fresh pending row should be created.diff --git a/server/internal/handler/seat_capacity.go b/server/internal/handler/seat_capacity.gonew file mode 100644index 0000000000..7c3fe9d5d6--- /dev/null+++ b/server/internal/handler/seat_capacity.go@@ -0,0 +1,339 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/seatcapacity"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++var (+ errSeatCapacityFull = errors.New("no purchased member seats are available")+ errSeatCapacityUnavailable = errors.New("seat capacity service is unavailable")+)++const seatCapacityWorkspaceLockWait = 2 * time.Second++func (h *Handler) seatCapacityEnabled() bool {+ return h != nil && h.SeatCapacityEnforcementEnabled && h.seatCapacitySettlementEnabled()+}++func (h *Handler) seatCapacitySettlementEnabled() bool {+ return h != nil && h.SeatCapacity != nil && h.SeatCapacity.Enabled()+}++func (h *Handler) lockSeatCapacityWorkspace(ctx context.Context, workspaceID uuid.UUID) (*db.Queries, func(), error) {+ if h == nil {+ return nil, nil, errors.New("seat capacity handler is unavailable")+ }+ if h.SeatCapacityLocker == nil {+ return h.Queries, func() {}, nil+ }+ lockCtx, cancel := context.WithTimeout(ctx, seatCapacityWorkspaceLockWait)+ defer cancel()+ lockedDB, unlock, err := h.SeatCapacityLocker.Lock(lockCtx, workspaceID)+ if err != nil {+ return nil, nil, err+ }+ return db.New(lockedDB), unlock, nil+}++func capacityIntentParams(workspaceID, token uuid.UUID, action string, due time.Time) db.UpsertSeatCapacityIntentParams {+ return db.UpsertSeatCapacityIntentParams{+ WorkspaceID: uuidToPG(workspaceID),+ OperationToken: uuidToPG(token),+ Action: action,+ NextAttemptAt: pgtype.Timestamptz{Time: due, Valid: true},+ }+}++func (h *Handler) reserveInvitationCapacity(ctx context.Context, workspaceID, invitationID uuid.UUID, expiresAt time.Time) error {+ if !h.seatCapacityEnabled() {+ return nil+ }+ q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)+ if err != nil {+ return fmt.Errorf("%w: acquire workspace capacity lock: %v", errSeatCapacityUnavailable, err)+ }+ defer unlock()+ params := capacityIntentParams(workspaceID, invitationID, seatcapacity.ActionReserveInvitation, seatcapacity.RecoveryDue(time.Now()).Time)+ params.SubjectID = uuidToPG(invitationID)+ params.InvitationID = uuidToPG(invitationID)+ params.ExpiresAt = pgtype.Timestamptz{Time: expiresAt, Valid: true}+ if _, err := q.UpsertSeatCapacityIntent(ctx, params); err != nil {+ return fmt.Errorf("record invitation capacity intent: %w", err)+ }+ decision, err := h.SeatCapacity.ReserveInvitation(ctx, workspaceID, invitationID, expiresAt)+ if err != nil {+ h.compensateCapacityIntentLocked(ctx, q, invitationID)+ return fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)+ }+ if !decision.Managed {+ return deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation)+ }+ if !decision.Allowed {+ _ = deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation)+ if decision.Reason == "capacity_full" || decision.Reason == "denied" {+ return errSeatCapacityFull+ }+ return fmt.Errorf("%w: reservation rejected in state %s", errSeatCapacityUnavailable, decision.Reason)+ }+ if err := q.MarkSeatCapacityIntentDelivered(ctx, db.MarkSeatCapacityIntentDeliveredParams{+ OperationToken: uuidToPG(invitationID), Action: seatcapacity.ActionReserveInvitation,+ }); err != nil {+ h.compensateCapacityIntentLocked(ctx, q, invitationID)+ return fmt.Errorf("record invitation capacity reservation: %w", err)+ }+ return nil+}++func (h *Handler) beginCapacityConsume(ctx context.Context, workspaceID, token, invitationID, userID uuid.UUID) (bool, error) {+ if !h.seatCapacitySettlementEnabled() {+ return false, nil+ }+ enforced := h.seatCapacityEnabled()+ q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)+ if err != nil {+ return false, fmt.Errorf("%w: acquire workspace capacity lock: %v", errSeatCapacityUnavailable, err)+ }+ defer unlock()+ params := capacityIntentParams(workspaceID, token, seatcapacity.ActionConsumeInvitation, seatcapacity.RecoveryDue(time.Now()).Time)+ params.SubjectID = uuidToPG(token)+ params.InvitationID = uuidToPG(invitationID)+ params.UserID = uuidToPG(userID)+ if _, err := q.UpsertSeatCapacityIntent(ctx, params); err != nil {+ return false, fmt.Errorf("record invitation consume intent: %w", err)+ }+ decision, err := h.SeatCapacity.Consume(ctx, workspaceID, token)+ if err != nil {+ if !enforced {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConsumeInvitation); deleteErr != nil {+ return false, fmt.Errorf("discard unenforced invitation consume intent: %w", deleteErr)+ }+ return false, nil+ }+ return false, fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)+ }+ if !decision.Managed {+ return false, deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConsumeInvitation)+ }+ if !decision.Allowed {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConsumeInvitation); deleteErr != nil {+ return false, fmt.Errorf("discard rejected invitation consume intent: %w", deleteErr)+ }+ if !enforced {+ return false, nil+ }+ _ = q.ExpireInvitationForCapacityRecovery(ctx, uuidToPG(invitationID))+ return false, errSeatCapacityFull+ }+ err = q.MarkSeatCapacityIntentDelivered(ctx, db.MarkSeatCapacityIntentDeliveredParams{+ OperationToken: uuidToPG(token), Action: seatcapacity.ActionConsumeInvitation,+ })+ return err == nil, err+}++func (h *Handler) beginShareJoinCapacity(ctx context.Context, workspaceID, shareLinkID, userID uuid.UUID) (uuid.UUID, error) {+ if !h.seatCapacityEnabled() {+ return uuid.Nil, nil+ }+ q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)+ if err != nil {+ return uuid.Nil, fmt.Errorf("%w: acquire workspace capacity lock: %v", errSeatCapacityUnavailable, err)+ }+ defer unlock()+ intent, err := q.CreateOrReactivateShareJoinCapacityIntent(ctx, db.CreateOrReactivateShareJoinCapacityIntentParams{+ WorkspaceID: uuidToPG(workspaceID), OperationToken: uuidToPG(uuid.New()),+ ShareLinkID: uuidToPG(shareLinkID), UserID: uuidToPG(userID),+ NextAttemptAt: seatcapacity.RecoveryDue(time.Now()),+ })+ if err != nil {+ return uuid.Nil, fmt.Errorf("record share-join capacity intent: %w", err)+ }+ token := uuid.UUID(intent.OperationToken.Bytes)+ decision, err := h.SeatCapacity.ClaimShareJoin(ctx, workspaceID, token)+ if err != nil {+ return uuid.Nil, fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)+ }+ if !decision.Managed {+ return uuid.Nil, deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin)+ }+ if !decision.Allowed {+ _ = deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin)+ return uuid.Nil, errSeatCapacityFull+ }+ if err := q.MarkSeatCapacityIntentDelivered(ctx, db.MarkSeatCapacityIntentDeliveredParams{+ OperationToken: uuidToPG(token), Action: seatcapacity.ActionClaimShareJoin,+ }); err != nil {+ return uuid.Nil, err+ }+ return token, nil+}++func transitionCapacityIntentToConfirm(ctx context.Context, q *db.Queries, token, memberID uuid.UUID, currentAction string) error {+ rows, err := q.TransitionSeatCapacityIntent(ctx, db.TransitionSeatCapacityIntentParams{+ NextAction: seatcapacity.ActionConfirm, CurrentAction: currentAction,+ MemberID: uuidToPG(memberID), OperationToken: uuidToPG(token),+ NextAttemptAt: seatcapacity.RetryDue(time.Now()),+ })+ if err != nil {+ return err+ }+ if rows != 1 {+ return errors.New("seat capacity intent changed concurrently")+ }+ return nil+}++func enqueueCapacityRelease(ctx context.Context, q *db.Queries, workspaceID, token uuid.UUID) error {+ _, err := q.EnqueueSeatCapacityRelease(ctx, db.EnqueueSeatCapacityReleaseParams{+ WorkspaceID: uuidToPG(workspaceID), OperationToken: uuidToPG(token),+ SubjectID: uuidToPG(token), NextAttemptAt: seatcapacity.RetryDue(time.Now()),+ })+ return err+}++func enqueueMemberCapacityRelease(ctx context.Context, q *db.Queries, workspaceID, memberID uuid.UUID) error {+ operationToken := uuid.New()+ params := capacityIntentParams(workspaceID, operationToken, seatcapacity.ActionReleaseMember, time.Now())+ params.MemberID = uuidToPG(memberID)+ _, err := q.UpsertSeatCapacityIntent(ctx, params)+ return err+}++func (h *Handler) confirmCapacityIntent(ctx context.Context, workspaceID, token, memberID uuid.UUID) {+ if !h.seatCapacitySettlementEnabled() {+ return+ }+ q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)+ if err != nil {+ slog.WarnContext(ctx, "seat capacity confirm deferred while workspace lock is unavailable",+ "workspace_id", workspaceID.String(), "operation_token", token.String(), "error", err)+ return+ }+ defer unlock()+ intent, err := q.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if err != nil || intent.Action != seatcapacity.ActionConfirm {+ return+ }+ decision, err := h.SeatCapacity.Confirm(ctx, workspaceID, token, memberID)+ if err == nil && (!decision.Managed || decision.Allowed) {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConfirm); deleteErr == nil {+ return+ } else {+ err = deleteErr+ }+ }+ if err == nil {+ err = fmt.Errorf("confirm rejected in state %s", decision.Reason)+ }+ recordCapacityFailure(ctx, q, token, seatcapacity.ActionConfirm, err)+}++func (h *Handler) compensateCapacityIntent(ctx context.Context, token uuid.UUID) {+ if !h.seatCapacitySettlementEnabled() {+ return+ }+ intent, err := h.Queries.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if err != nil {+ return+ }+ q, unlock, err := h.lockSeatCapacityWorkspace(ctx, uuid.UUID(intent.WorkspaceID.Bytes))+ if err != nil {+ return+ }+ defer unlock()+ h.compensateCapacityIntentLocked(ctx, q, token)+}++func (h *Handler) compensateCapacityIntentLocked(ctx context.Context, q *db.Queries, token uuid.UUID) {+ intent, err := q.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if err != nil {+ return+ }+ // A confirm row belongs to a product transaction that already committed.+ // A losing duplicate request must never release the winning member's seat.+ if intent.Action == seatcapacity.ActionConfirm || intent.Action == seatcapacity.ActionReleaseMember {+ return+ }+ rows, err := q.TransitionSeatCapacityIntent(ctx, db.TransitionSeatCapacityIntentParams{+ NextAction: seatcapacity.ActionRelease, CurrentAction: intent.Action,+ OperationToken: uuidToPG(token), NextAttemptAt: seatcapacity.RetryDue(time.Now()),+ })+ if err != nil || rows != 1 {+ return+ }+ decision, releaseErr := h.SeatCapacity.Release(ctx, uuid.UUID(intent.WorkspaceID.Bytes), token)+ if (releaseErr == nil && (!decision.Managed || decision.Allowed || decision.Reason == "released" || decision.Reason == "denied")) || seatcapacity.IsNotFound(releaseErr) {+ _ = deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionRelease)+ return+ }+ if releaseErr == nil {+ releaseErr = fmt.Errorf("release rejected in state %s", decision.Reason)+ }+ recordCapacityFailure(ctx, q, token, seatcapacity.ActionRelease, releaseErr)+}++func (h *Handler) settleMemberCapacityRelease(ctx context.Context, workspaceID, memberID uuid.UUID) {+ if !h.seatCapacitySettlementEnabled() {+ return+ }+ q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)+ if err != nil {+ return+ }+ defer unlock()+ intent, err := q.GetMemberReleaseCapacityIntent(ctx, db.GetMemberReleaseCapacityIntentParams{+ WorkspaceID: uuidToPG(workspaceID), MemberID: uuidToPG(memberID),+ })+ if err != nil {+ return+ }+ decision, releaseErr := h.SeatCapacity.ReleaseMember(ctx, workspaceID, memberID)+ if (releaseErr == nil && (!decision.Managed || decision.Allowed || decision.Reason == "released")) || seatcapacity.IsNotFound(releaseErr) {+ _ = deleteCapacityIntentForAction(ctx, q, uuid.UUID(intent.OperationToken.Bytes), seatcapacity.ActionReleaseMember)+ return+ }+ if releaseErr == nil {+ releaseErr = fmt.Errorf("member release rejected in state %s", decision.Reason)+ }+ recordCapacityFailure(ctx, q, uuid.UUID(intent.OperationToken.Bytes), intent.Action, releaseErr)+}++func deleteCapacityIntentForAction(ctx context.Context, q *db.Queries, token uuid.UUID, action string) error {+ return q.DeleteSeatCapacityIntentForAction(ctx, db.DeleteSeatCapacityIntentForActionParams{+ OperationToken: uuidToPG(token), Action: action,+ })+}++func recordCapacityFailure(ctx context.Context, q *db.Queries, token uuid.UUID, action string, capacityErr error) {+ if capacityErr == nil {+ return+ }+ _ = q.MarkSeatCapacityIntentFailed(ctx, db.MarkSeatCapacityIntentFailedParams{+ LastError: capacityErr.Error(), NextAttemptAt: pgtype.Timestamptz{Time: time.Now().Add(5 * time.Second), Valid: true},+ OperationToken: uuidToPG(token), Action: action,+ })+ slog.WarnContext(ctx, "seat capacity intent deferred to outbox",+ "operation_token", token.String(), "action", action, "error", capacityErr)+}++func writeSeatCapacityError(w http.ResponseWriter, err error) {+ switch {+ case errors.Is(err, errSeatCapacityFull):+ writeErrorCode(w, http.StatusConflict, "seat_capacity_full", "No purchased member seats are available. Add seats in Billing before adding another member.")+ default:+ writeErrorCode(w, http.StatusServiceUnavailable, "seat_capacity_unavailable", "Member capacity could not be verified. Please try again.")+ }+}++func uuidToPG(value uuid.UUID) pgtype.UUID {+ return pgtype.UUID{Bytes: value, Valid: value != uuid.Nil}+}diff --git a/server/internal/handler/seat_capacity_test.go b/server/internal/handler/seat_capacity_test.gonew file mode 100644index 0000000000..acaf7b9cd1--- /dev/null+++ b/server/internal/handler/seat_capacity_test.go@@ -0,0 +1,594 @@+package handler++import (+ "context"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/seatcapacity"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type deadlineRecordingWorkspaceLocker struct {+ deadline time.Time+ ok bool+}++func (l *deadlineRecordingWorkspaceLocker) Lock(ctx context.Context, _ uuid.UUID) (db.DBTX, func(), error) {+ l.deadline, l.ok = ctx.Deadline()+ return nil, nil, context.DeadlineExceeded+}++func TestSeatCapacityHandlerBoundsWorkspaceLockWait(t *testing.T) {+ locker := &deadlineRecordingWorkspaceLocker{}+ h := &Handler{Queries: testHandler.Queries, SeatCapacityLocker: locker}+ started := time.Now()++ if _, _, err := h.lockSeatCapacityWorkspace(context.Background(), uuid.New()); !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("workspace lock error = %v, want context deadline exceeded", err)+ }+ if !locker.ok {+ t.Fatal("workspace lock context has no deadline")+ }+ wait := locker.deadline.Sub(started)+ if wait < time.Second || wait > 3*time.Second {+ t.Fatalf("workspace lock wait budget = %v, want a bounded 1-3s budget", wait)+ }+}++func TestSeatCapacityWorkspaceLockWaitersDoNotPinPoolConnections(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ config := testPool.Config()+ config.MaxConns = 8+ config.MinConns = 0+ pool, err := pgxpool.NewWithConfig(ctx, config)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ locker := seatcapacity.NewWorkspaceLocker(pool)+ workspaceID := uuid.New()++ _, unlock, err := locker.Lock(ctx, workspaceID)+ if err != nil {+ t.Fatal(err)+ }+ defer unlock()++ const waiterCount = 12+ start := make(chan struct{})+ ready := sync.WaitGroup{}+ ready.Add(waiterCount)+ errs := make(chan error, waiterCount)+ for range waiterCount {+ go func() {+ ready.Done()+ <-start+ waitCtx, waitCancel := context.WithTimeout(context.Background(), 200*time.Millisecond)+ defer waitCancel()+ _, waiterUnlock, lockErr := locker.Lock(waitCtx, workspaceID)+ if waiterUnlock != nil {+ waiterUnlock()+ }+ errs <- lockErr+ }()+ }+ ready.Wait()+ started := time.Now()+ close(start)+ time.Sleep(50 * time.Millisecond)+ if got := pool.Stat().AcquiredConns(); got != 1 {+ t.Fatalf("acquired connections with %d queued waiters = %d, want only the lock holder", waiterCount, got)+ }++ for range waiterCount {+ if lockErr := <-errs; !errors.Is(lockErr, context.DeadlineExceeded) {+ t.Fatalf("queued lock error = %v, want context deadline exceeded", lockErr)+ }+ }+ if elapsed := time.Since(started); elapsed > 750*time.Millisecond {+ t.Fatalf("queued lock attempts took %v, want bounded completion", elapsed)+ }++ _, secondUnlock, err := locker.Lock(ctx, uuid.New())+ if err != nil {+ t.Fatal(err)+ }+ defer secondUnlock()+ thirdResult := make(chan error, 1)+ go func() {+ thirdCtx, thirdCancel := context.WithTimeout(context.Background(), 200*time.Millisecond)+ defer thirdCancel()+ _, thirdUnlock, thirdErr := locker.Lock(thirdCtx, uuid.New())+ if thirdUnlock != nil {+ thirdUnlock()+ }+ thirdResult <- thirdErr+ }()+ time.Sleep(50 * time.Millisecond)+ if got := pool.Stat().AcquiredConns(); got != 2 {+ t.Fatalf("acquired connections at the capacity lock limit = %d, want 2 of 8", got)+ }+ if thirdErr := <-thirdResult; !errors.Is(thirdErr, context.DeadlineExceeded) {+ t.Fatalf("third workspace lock error = %v, want context deadline exceeded", thirdErr)+ }+}++func TestSeatCapacityIntentCannotRegressOrBeDeletedByStaleWorker(t *testing.T) {+ ctx := context.Background()+ workspaceID := parseUUID(testWorkspaceID)+ token, linkID, userID, memberID := uuid.New(), uuid.New(), uuid.New(), uuid.New()+ queries := db.New(testPool)++ _, err := queries.UpsertSeatCapacityIntent(ctx, db.UpsertSeatCapacityIntentParams{+ WorkspaceID: uuidToPG(uuid.UUID(workspaceID.Bytes)), OperationToken: uuidToPG(token),+ Action: seatcapacity.ActionClaimShareJoin, SubjectID: uuidToPG(token),+ ShareLinkID: uuidToPG(linkID), UserID: uuidToPG(userID),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE workspace_id = $1`, workspaceID)+ })++ rows, err := queries.TransitionSeatCapacityIntent(ctx, db.TransitionSeatCapacityIntentParams{+ NextAction: seatcapacity.ActionConfirm, CurrentAction: seatcapacity.ActionClaimShareJoin,+ MemberID: uuidToPG(memberID), OperationToken: uuidToPG(token),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ })+ if err != nil || rows != 1 {+ t.Fatalf("transition rows=%d err=%v", rows, err)+ }++ _, err = queries.UpsertSeatCapacityIntent(ctx, db.UpsertSeatCapacityIntentParams{+ WorkspaceID: uuidToPG(uuid.UUID(workspaceID.Bytes)), OperationToken: uuidToPG(token),+ Action: seatcapacity.ActionClaimShareJoin, SubjectID: uuidToPG(token),+ ShareLinkID: uuidToPG(linkID), UserID: uuidToPG(userID),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now().Add(time.Minute), Valid: true},+ })+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("regressive upsert error = %v, want pgx.ErrNoRows", err)+ }+ if err := queries.DeleteSeatCapacityIntentForAction(ctx, db.DeleteSeatCapacityIntentForActionParams{+ OperationToken: uuidToPG(token), Action: seatcapacity.ActionClaimShareJoin,+ }); err != nil {+ t.Fatal(err)+ }+ intent, err := queries.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if err != nil {+ t.Fatal(err)+ }+ if intent.Action != seatcapacity.ActionConfirm || !intent.MemberID.Valid || intent.MemberID.Bytes != memberID {+ t.Fatalf("intent regressed or was deleted: %+v", intent)+ }+ if err := enqueueCapacityRelease(ctx, queries, uuid.UUID(workspaceID.Bytes), token); !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("release over confirm error = %v, want pgx.ErrNoRows", err)+ }+ intent, err = queries.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if err != nil {+ t.Fatal(err)+ }+ if intent.Action != seatcapacity.ActionConfirm {+ t.Fatalf("release regressed confirmed intent to %q", intent.Action)+ }++ if err := queries.DeleteSeatCapacityConfirmIntentsForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ if err := queries.PrepareSeatCapacityOperationReleasesForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ if err := queries.PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ if err := queries.PrepareSeatCapacityMemberReleasesForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ _, err = queries.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("confirmed token intent survived workspace deletion: %v", err)+ }+ var memberReleases int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM seat_capacity_outbox+ WHERE workspace_id = $1 AND action = 'release_member'+ `, workspaceID).Scan(&memberReleases); err != nil {+ t.Fatal(err)+ }+ if memberReleases == 0 {+ t.Fatal("workspace deletion did not enqueue member capacity releases")+ }+}++func TestCapacitySettlementContinuesForInvitationWhileEnforcementIsPaused(t *testing.T) {+ ctx := context.Background()+ workspaceID := uuid.UUID(parseUUID(testWorkspaceID).Bytes)+ token, userID := uuid.New(), uuid.New()+ executor := &stubSeatCapacity{}+ useSeatCapacity(t, executor)+ testHandler.SeatCapacityEnforcementEnabled = false+ previousLocker := testHandler.SeatCapacityLocker+ testHandler.SeatCapacityLocker = seatcapacity.NewWorkspaceLocker(testPool)+ t.Cleanup(func() {+ testHandler.SeatCapacityLocker = previousLocker+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, token)+ })++ active, err := testHandler.beginCapacityConsume(ctx, workspaceID, token, token, userID)+ if err != nil {+ t.Fatal(err)+ }+ if !active || executor.consumeCalls != 1 {+ t.Fatalf("active=%v consumeCalls=%d, want true/1", active, executor.consumeCalls)+ }+ intent, err := testHandler.Queries.GetSeatCapacityIntent(ctx, uuidToPG(token))+ if err != nil {+ t.Fatal(err)+ }+ if intent.Action != seatcapacity.ActionConsumeInvitation || !intent.DeliveredAt.Valid {+ t.Fatalf("paused-enforcement consume intent = %+v", intent)+ }+}++func TestCapacityEnforcementPauseFailsOpenConsumeError(t *testing.T) {+ ctx := context.Background()+ workspaceID := uuid.UUID(parseUUID(testWorkspaceID).Bytes)+ token, userID := uuid.New(), uuid.New()+ executor := &stubSeatCapacity{consumeErr: errors.New("capacity service unavailable")}+ useSeatCapacity(t, executor)+ testHandler.SeatCapacityEnforcementEnabled = false+ t.Cleanup(func() {+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, token)+ })++ active, err := testHandler.beginCapacityConsume(ctx, workspaceID, token, token, userID)+ if err != nil {+ t.Fatal(err)+ }+ if active || executor.consumeCalls != 1 {+ t.Fatalf("active=%v consumeCalls=%d, want false/1", active, executor.consumeCalls)+ }+ if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, uuidToPG(token)); intents != 0 {+ t.Fatalf("capacity intents = %d, want 0 after fail-open", intents)+ }+}++func TestAcceptInvitationAllowsDeniedCapacityWhenEnforcementIsPaused(t *testing.T) {+ ctx := context.Background()+ email := "paused-capacity-invite-" + uuid.NewString() + "@multica.ai"+ userID := dbfx.User(t, "Paused Capacity Invitee", email)+ invitationID := dbfx.Insert(t, "workspace_invitation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "inviter_id": testUserID,+ "invitee_email": email,+ "invitee_user_id": userID,+ "role": "member",+ "status": "pending",+ "expires_at": testutil.Raw("now() + interval '1 day'"),+ })+ dbfx.Cleanup(t, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID))+ dbfx.Cleanup(t, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, parseUUID(invitationID))++ denied := seatcapacity.Decision{Managed: true, Allowed: false, Reason: "capacity_full"}+ executor := &stubSeatCapacity{consumeDecision: &denied}+ useSeatCapacity(t, executor)+ testHandler.SeatCapacityEnforcementEnabled = false++ req := newRequest("POST", "/api/invitations/"+invitationID+"/accept", nil)+ req.Header.Set("X-User-ID", userID)+ req = withURLParam(req, "id", invitationID)+ rec := testutil.Call(t, testHandler.AcceptInvitation, req)+ rec.Want(200)++ var invitationStatus string+ if err := testPool.QueryRow(ctx, `SELECT status FROM workspace_invitation WHERE id = $1`, parseUUID(invitationID)).Scan(&invitationStatus); err != nil {+ t.Fatal(err)+ }+ if invitationStatus != "accepted" {+ t.Fatalf("invitation status = %q, want accepted", invitationStatus)+ }+ if members := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID)); members != 1 {+ t.Fatalf("member count = %d, want 1", members)+ }+ if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, parseUUID(invitationID)); intents != 0 {+ t.Fatalf("capacity intents = %d, want 0 after fail-open", intents)+ }+ if executor.consumeCalls != 1 {+ t.Fatalf("capacity consume calls = %d, want 1", executor.consumeCalls)+ }+}++func TestSeatCapacityWorkspaceDeletionSettlesOverlappingInvitationIntent(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ workspaceID := parseUUID(testWorkspaceID)+ invitationID := uuid.MustParse(dbfx.Insert(t, "workspace_invitation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "inviter_id": testUserID,+ "invitee_email": uuid.NewString() + "@multica.ai",+ "role": "member",+ "status": "pending",+ "expires_at": testutil.Raw("now() + interval '1 day'"),+ }))+ t.Cleanup(func() {+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, invitationID)+ })+ _, err := queries.UpsertSeatCapacityIntent(ctx, db.UpsertSeatCapacityIntentParams{+ WorkspaceID: workspaceID, OperationToken: uuidToPG(invitationID),+ Action: seatcapacity.ActionReserveInvitation, SubjectID: uuidToPG(invitationID),+ InvitationID: uuidToPG(invitationID),+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }++ if err := queries.PrepareSeatCapacityOperationReleasesForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ if err := queries.PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ intent, err := queries.GetSeatCapacityIntent(ctx, uuidToPG(invitationID))+ if err != nil {+ t.Fatal(err)+ }+ if intent.Action != seatcapacity.ActionRelease || intent.MemberID.Valid || intent.DeadLetteredAt.Valid {+ t.Fatalf("overlapping invitation intent = %+v, want live release", intent)+ }+}++func TestSeatCapacityWorkspaceDeletionCannotRegressConcurrentConfirm(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ workspaceID := parseUUID(testWorkspaceID)+ invitationID := uuid.MustParse(dbfx.Insert(t, "workspace_invitation", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "inviter_id": testUserID,+ "invitee_email": uuid.NewString() + "@multica.ai",+ "role": "member",+ "status": "pending",+ "expires_at": testutil.Raw("now() + interval '1 day'"),+ }))+ t.Cleanup(func() {+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, invitationID)+ })+ _, err := queries.UpsertSeatCapacityIntent(ctx, db.UpsertSeatCapacityIntentParams{+ WorkspaceID: workspaceID, OperationToken: uuidToPG(invitationID),+ Action: seatcapacity.ActionConfirm, SubjectID: uuidToPG(invitationID),+ InvitationID: uuidToPG(invitationID), MemberID: uuidToPG(uuid.New()),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }++ if err := queries.PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion(ctx, workspaceID); err != nil {+ t.Fatal(err)+ }+ intent, err := queries.GetSeatCapacityIntent(ctx, uuidToPG(invitationID))+ if err != nil {+ t.Fatal(err)+ }+ if intent.Action != seatcapacity.ActionConfirm || !intent.MemberID.Valid {+ t.Fatalf("workspace deletion regressed concurrent confirm: %+v", intent)+ }+}++func TestShareJoinCapacityIntentReusesDeadLetterAndSerializesConcurrentCreates(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ workspaceID := parseUUID(testWorkspaceID)+ shareLinkID, userID := uuid.New(), uuid.New()+ cleanup := func() {+ _, _ = testPool.Exec(ctx, `+ DELETE FROM seat_capacity_outbox+ WHERE workspace_id = $1 AND share_link_id = $2 AND user_id = $3+ `, workspaceID, shareLinkID, userID)+ }+ cleanup()+ t.Cleanup(cleanup)++ create := func(candidate uuid.UUID) (db.SeatCapacityOutbox, error) {+ return queries.CreateOrReactivateShareJoinCapacityIntent(ctx, db.CreateOrReactivateShareJoinCapacityIntentParams{+ WorkspaceID: workspaceID, OperationToken: uuidToPG(candidate),+ ShareLinkID: uuidToPG(shareLinkID), UserID: uuidToPG(userID),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ })+ }++ first, err := create(uuid.New())+ if err != nil {+ t.Fatal(err)+ }+ if _, err := testPool.Exec(ctx, `+ UPDATE seat_capacity_outbox+ SET attempt_count = 10, dead_lettered_at = now(), last_error = 'stuck'+ WHERE operation_token = $1+ `, first.OperationToken); err != nil {+ t.Fatal(err)+ }+ second, err := create(uuid.New())+ if err != nil {+ t.Fatal(err)+ }+ if second.OperationToken != first.OperationToken {+ t.Fatalf("dead-letter retry token=%v, want original %v", second.OperationToken, first.OperationToken)+ }+ if second.DeadLetteredAt.Valid || second.AttemptCount != 0 || second.LastError.Valid {+ t.Fatalf("dead-letter retry was not reactivated: %+v", second)+ }++ cleanup()+ start := make(chan struct{})+ results := make(chan db.SeatCapacityOutbox, 2)+ errs := make(chan error, 2)+ var wg sync.WaitGroup+ for range 2 {+ wg.Add(1)+ go func() {+ defer wg.Done()+ <-start+ intent, createErr := create(uuid.New())+ results <- intent+ errs <- createErr+ }()+ }+ close(start)+ wg.Wait()+ close(results)+ close(errs)+ for createErr := range errs {+ if createErr != nil {+ t.Fatal(createErr)+ }+ }+ var token pgtype.UUID+ for intent := range results {+ if !token.Valid {+ token = intent.OperationToken+ } else if intent.OperationToken != token {+ t.Fatalf("concurrent creates returned different tokens: %v and %v", token, intent.OperationToken)+ }+ }+ var count int+ if err := testPool.QueryRow(ctx, `+ SELECT count(*) FROM seat_capacity_outbox+ WHERE workspace_id = $1 AND share_link_id = $2 AND user_id = $3+ `, workspaceID, shareLinkID, userID).Scan(&count); err != nil {+ t.Fatal(err)+ }+ if count != 1 {+ t.Fatalf("logical share join rows=%d, want 1", count)+ }+}++func TestStaleSeatCapacityWorkerCannotMutateReactivatedIntent(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ workspaceID := parseUUID(testWorkspaceID)+ shareLinkID, userID := uuid.New(), uuid.New()+ created, err := queries.CreateOrReactivateShareJoinCapacityIntent(ctx, db.CreateOrReactivateShareJoinCapacityIntentParams{+ WorkspaceID: workspaceID, OperationToken: uuidToPG(uuid.New()),+ ShareLinkID: uuidToPG(shareLinkID), UserID: uuidToPG(userID),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now().Add(-time.Hour), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, created.OperationToken)+ })+ claimed, err := queries.ClaimNextDueSeatCapacityIntent(ctx, pgtype.Timestamptz{Time: time.Now().Add(5 * time.Minute), Valid: true})+ if err != nil {+ t.Fatal(err)+ }+ if claimed.OperationToken != created.OperationToken || !claimed.LeaseToken.Valid {+ t.Fatalf("claimed unexpected intent: %+v", claimed)+ }+ if _, err := queries.CreateOrReactivateShareJoinCapacityIntent(ctx, db.CreateOrReactivateShareJoinCapacityIntentParams{+ WorkspaceID: workspaceID, OperationToken: uuidToPG(uuid.New()),+ ShareLinkID: uuidToPG(shareLinkID), UserID: uuidToPG(userID),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now().Add(5 * time.Minute), Valid: true},+ }); err != nil {+ t.Fatal(err)+ }++ transitioned, err := queries.TransitionClaimedSeatCapacityIntent(ctx, db.TransitionClaimedSeatCapacityIntentParams{+ NextAction: seatcapacity.ActionRelease, CurrentAction: claimed.Action,+ OperationToken: claimed.OperationToken, LeaseToken: claimed.LeaseToken,+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ })+ if err != nil || transitioned != 0 {+ t.Fatalf("stale transition rows=%d err=%v, want 0", transitioned, err)+ }+ failed, err := queries.MarkClaimedSeatCapacityIntentFailed(ctx, db.MarkClaimedSeatCapacityIntentFailedParams{+ LastError: "stale", NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ OperationToken: claimed.OperationToken, Action: claimed.Action, LeaseToken: claimed.LeaseToken,+ })+ if err != nil || failed != 0 {+ t.Fatalf("stale failure rows=%d err=%v, want 0", failed, err)+ }+ deadLettered, err := queries.MarkClaimedSeatCapacityIntentDeadLettered(ctx, db.MarkClaimedSeatCapacityIntentDeadLetteredParams{+ LastError: "stale", OperationToken: claimed.OperationToken,+ Action: claimed.Action, LeaseToken: claimed.LeaseToken,+ })+ if err != nil || deadLettered != 0 {+ t.Fatalf("stale dead letter rows=%d err=%v, want 0", deadLettered, err)+ }+ deleted, err := queries.DeleteClaimedSeatCapacityIntent(ctx, db.DeleteClaimedSeatCapacityIntentParams{+ OperationToken: claimed.OperationToken, Action: claimed.Action, LeaseToken: claimed.LeaseToken,+ })+ if err != nil || deleted != 0 {+ t.Fatalf("stale delete rows=%d err=%v, want 0", deleted, err)+ }+ intent, err := queries.GetSeatCapacityIntent(ctx, created.OperationToken)+ if err != nil {+ t.Fatal(err)+ }+ if intent.Action != seatcapacity.ActionClaimShareJoin || intent.DeadLetteredAt.Valid || intent.LeaseToken.Valid {+ t.Fatalf("reactivated intent was changed by stale worker: %+v", intent)+ }+}++func TestClaimNextDueSeatCapacityIntentIsExclusiveAcrossReplicas(t *testing.T) {+ ctx := context.Background()+ queries := db.New(testPool)+ workspaceID := parseUUID(testWorkspaceID)+ token := uuid.New()+ _, err := queries.UpsertSeatCapacityIntent(ctx, db.UpsertSeatCapacityIntentParams{+ WorkspaceID: workspaceID, OperationToken: uuidToPG(token),+ Action: seatcapacity.ActionConfirm, MemberID: uuidToPG(uuid.New()),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now().Add(-time.Minute), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, token)+ })++ start := make(chan struct{})+ results := make(chan error, 2)+ var wg sync.WaitGroup+ for range 2 {+ wg.Add(1)+ go func() {+ defer wg.Done()+ <-start+ _, claimErr := queries.ClaimNextDueSeatCapacityIntent(ctx, pgtype.Timestamptz{+ Time: time.Now().Add(5 * time.Minute), Valid: true,+ })+ results <- claimErr+ }()+ }+ close(start)+ wg.Wait()+ close(results)++ var claimed, empty int+ for claimErr := range results {+ switch {+ case claimErr == nil:+ claimed+++ case errors.Is(claimErr, pgx.ErrNoRows):+ empty+++ default:+ t.Fatal(claimErr)+ }+ }+ if claimed != 1 || empty != 1 {+ t.Fatalf("claimed=%d empty=%d, want 1/1", claimed, empty)+ }+}diff --git a/server/internal/handler/share_link.go b/server/internal/handler/share_link.goindex 8c3fc0945e..f26e13c2a4 100644--- a/server/internal/handler/share_link.go+++ b/server/internal/handler/share_link.go@@ -4,6 +4,7 @@ import ("crypto/rand""encoding/hex""encoding/json"+ "errors""fmt""log/slog""math"@@ -12,8 +13,11 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/google/uuid"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/seatcapacity"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -281,6 +285,30 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {return}+ linkPreview, err := h.Queries.GetActiveShareLinkByCode(r.Context(), code)+ if err != nil {+ writeError(w, http.StatusNotFound, "share link not found or expired")+ return+ }+ if _, memberErr := h.Queries.GetMemberByUserAndWorkspace(r.Context(), db.GetMemberByUserAndWorkspaceParams{+ UserID: user.ID, WorkspaceID: linkPreview.WorkspaceID,+ }); memberErr == nil {+ writeError(w, http.StatusConflict, "you are already a member of this workspace")+ return+ } else if !errors.Is(memberErr, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to join workspace")+ return+ }++ var capacityToken uuid.UUID+ if h.seatCapacityEnabled() {+ capacityToken, err = h.beginShareJoinCapacity(r.Context(), uuid.UUID(linkPreview.WorkspaceID.Bytes), uuid.UUID(linkPreview.ID.Bytes), uuid.UUID(user.ID.Bytes))+ if err != nil {+ writeSeatCapacityError(w, err)+ return+ }+ }+// Open the transaction first, then atomically claim the link. The claim is// a conditional UPDATE that revalidates active/not-expired/below-max_uses// and increments use_count in one statement, so concurrent joins cannot@@ -294,7 +322,7 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {qtx := h.Queries.WithTx(tx)- link, err := qtx.ClaimShareLinkByCode(r.Context(), code)+ link, err := qtx.ClaimShareLinkByID(r.Context(), linkPreview.ID)if err != nil {writeError(w, http.StatusNotFound, "share link not found or expired")return@@ -317,6 +345,7 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {})if err != nil {if isUniqueViolation(err) {+ h.compensateCapacityIntent(r.Context(), capacityToken)writeError(w, http.StatusConflict, "you are already a member of this workspace")return}@@ -330,11 +359,20 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to finalize onboarding")return}+ if capacityToken != uuid.Nil {+ if err := transitionCapacityIntentToConfirm(r.Context(), qtx, capacityToken, uuid.UUID(member.ID.Bytes), seatcapacity.ActionClaimShareJoin); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to join workspace")+ return+ }+ }if err := tx.Commit(r.Context()); err != nil {writeError(w, http.StatusInternalServerError, "failed to join workspace")return}+ if capacityToken != uuid.Nil {+ h.confirmCapacityIntent(r.Context(), uuid.UUID(link.WorkspaceID.Bytes), capacityToken, uuid.UUID(member.ID.Bytes))+ }wsID := uuidToString(link.WorkspaceID)slog.Info("user joined via share link", "user_id", userID, "workspace_id", wsID)diff --git a/server/internal/handler/share_link_test.go b/server/internal/handler/share_link_test.goindex 8a1c0fb988..65e7560199 100644--- a/server/internal/handler/share_link_test.go+++ b/server/internal/handler/share_link_test.go@@ -12,13 +12,57 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/google/uuid""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/seatcapacity"db "github.com/multica-ai/multica/server/pkg/db/generated")var testSeq atomic.Int64+type shareJoinCapacityStub struct {+ mu sync.Mutex+ claimTokens []uuid.UUID+ claimGate *sync.WaitGroup+}++func (s *shareJoinCapacityStub) Enabled() bool { return true }+func (s *shareJoinCapacityStub) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *shareJoinCapacityStub) ClaimShareJoin(_ context.Context, _ uuid.UUID, token uuid.UUID) (seatcapacity.Decision, error) {+ s.mu.Lock()+ s.claimTokens = append(s.claimTokens, token)+ s.mu.Unlock()+ if s.claimGate != nil {+ s.claimGate.Done()+ s.claimGate.Wait()+ }+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *shareJoinCapacityStub) Consume(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *shareJoinCapacityStub) Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *shareJoinCapacityStub) Release(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *shareJoinCapacityStub) ReleaseMember(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{Managed: true, Allowed: true}, nil+}+func (s *shareJoinCapacityStub) GetOperation(context.Context, uuid.UUID, uuid.UUID) (seatcapacity.Decision, error) {+ return seatcapacity.Decision{}, nil+}++func (s *shareJoinCapacityStub) tokens() []uuid.UUID {+ s.mu.Lock()+ defer s.mu.Unlock()+ return append([]uuid.UUID(nil), s.claimTokens...)+}+func pgInt32(v int32) *int32 { return &v }func clearShareLinksForTestWorkspace(t *testing.T) {@@ -375,6 +419,109 @@ func TestJoinShareLink_DuplicateJoinDoesNotConsumeUse(t *testing.T) {}}+func TestJoinShareLink_ReactivatesDeadLetterWithSameCapacityToken(t *testing.T) {+ clearShareLinksForTestWorkspace(t)+ link := createTestShareLink(t, testWorkspaceID, "member", 5, 0)+ userID := createTestUserAndMember(t, "")+ stub := &shareJoinCapacityStub{}+ useSeatCapacity(t, stub)++ queries := db.New(testPool)+ originalToken := uuid.New()+ intent, err := queries.CreateOrReactivateShareJoinCapacityIntent(context.Background(), db.CreateOrReactivateShareJoinCapacityIntentParams{+ WorkspaceID: link.WorkspaceID, OperationToken: uuidToPG(originalToken),+ ShareLinkID: link.ID, UserID: parseUUID(userID),+ NextAttemptAt: pgtype.Timestamptz{Time: time.Now(), Valid: true},+ })+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, intent.OperationToken)+ })+ if _, err := testPool.Exec(context.Background(), `+ UPDATE seat_capacity_outbox+ SET attempt_count = 10, dead_lettered_at = now(), last_error = 'stuck'+ WHERE operation_token = $1+ `, intent.OperationToken); err != nil {+ t.Fatal(err)+ }++ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})+ req.Header.Set("X-User-ID", userID)+ w := httptest.NewRecorder()+ testHandler.JoinByShareLink(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("join: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ tokens := stub.tokens()+ if len(tokens) != 1 || tokens[0] != originalToken {+ t.Fatalf("claim tokens=%v, want original %s", tokens, originalToken)+ }+}++func TestJoinShareLink_ConcurrentSameUserUsesOneCapacityOperation(t *testing.T) {+ clearShareLinksForTestWorkspace(t)+ link := createTestShareLink(t, testWorkspaceID, "member", 5, 0)+ userID := createTestUserAndMember(t, "")+ gate := &sync.WaitGroup{}+ gate.Add(2)+ stub := &shareJoinCapacityStub{claimGate: gate}+ useSeatCapacity(t, stub)+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `+ DELETE FROM seat_capacity_outbox+ WHERE workspace_id = $1 AND share_link_id = $2 AND user_id = $3+ `, link.WorkspaceID, link.ID, parseUUID(userID))+ })++ start := make(chan struct{})+ statuses := make(chan int, 2)+ var wg sync.WaitGroup+ for range 2 {+ wg.Add(1)+ go func() {+ defer wg.Done()+ <-start+ req := newRequest("POST", "/api/share-links/join", JoinByShareLinkRequest{Code: link.Code})+ req.Header.Set("X-User-ID", userID)+ w := httptest.NewRecorder()+ testHandler.JoinByShareLink(w, req)+ statuses <- w.Code+ }()+ }+ close(start)+ wg.Wait()+ close(statuses)+ var successes, conflicts int+ for status := range statuses {+ switch status {+ case http.StatusOK:+ successes+++ case http.StatusConflict:+ conflicts+++ default:+ t.Fatalf("unexpected concurrent join status %d", status)+ }+ }+ if successes != 1 || conflicts != 1 {+ t.Fatalf("successes=%d conflicts=%d, want 1/1", successes, conflicts)+ }+ tokens := stub.tokens()+ if len(tokens) != 2 || tokens[0] != tokens[1] {+ t.Fatalf("concurrent claim tokens=%v, want one logical operation", tokens)+ }+ var members int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2+ `, link.WorkspaceID, parseUUID(userID)).Scan(&members); err != nil {+ t.Fatal(err)+ }+ if members != 1 {+ t.Fatalf("member rows=%d, want 1", members)+ }+}+func TestGetShareLinkInfo_PublicResponseSlim(t *testing.T) {clearShareLinksForTestWorkspace(t)link := createTestShareLink(t, testWorkspaceID, "admin", 0, 0)diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 60cfe20617..6ac2db640c 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -12,6 +12,7 @@ import ("time""github.com/go-chi/chi/v5"+ "github.com/google/uuid""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"@@ -553,80 +554,6 @@ func normalizeMemberRole(role string) (string, bool) {}}-func (h *Handler) CreateMember(w http.ResponseWriter, r *http.Request) {- workspaceID := workspaceIDFromURL(r, "id")- requester, ok := h.workspaceMember(w, r, workspaceID)- if !ok {- return- }-- var req CreateMemberRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- writeError(w, http.StatusBadRequest, "invalid request body")- return- }-- email := strings.ToLower(strings.TrimSpace(req.Email))- if email == "" {- writeError(w, http.StatusBadRequest, "email is required")- return- }-- role, valid := normalizeMemberRole(req.Role)- if !valid {- writeError(w, http.StatusBadRequest, "invalid member role")- return- }- if role == "owner" && requester.Role != "owner" {- writeError(w, http.StatusForbidden, "insufficient permissions")- return- }-- user, err := h.Queries.GetUserByEmail(r.Context(), email)- if err != nil {- if isNotFound(err) {- // Auto-create user with email so they can be invited before signing up- user, err = h.Queries.CreateUser(r.Context(), db.CreateUserParams{- Name: email,- Email: email,- })- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to create user")- return- }- } else {- writeError(w, http.StatusInternalServerError, "failed to load user")- return- }- }-- member, err := h.Queries.CreateMember(r.Context(), db.CreateMemberParams{- WorkspaceID: requester.WorkspaceID,- UserID: user.ID,- Role: role,- })- if err != nil {- if isUniqueViolation(err) {- writeError(w, http.StatusConflict, "user is already a member")- return- }- slog.Warn("create member failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID, "email", email)...)- writeError(w, http.StatusInternalServerError, "failed to create member")- return- }-- slog.Info("member added", append(logger.RequestAttrs(r), "member_id", uuidToString(member.ID), "workspace_id", workspaceID, "email", email, "role", role)...)- userID := requestUserID(r)- eventPayload := map[string]any{"member": h.memberWithUserResponse(member, user)}- if ws, err := h.Queries.GetWorkspace(r.Context(), requester.WorkspaceID); err == nil {- eventPayload["workspace_name"] = ws.Name- }- h.publish(protocol.EventMemberAdded, uuidToString(requester.WorkspaceID), "member", userID, eventPayload)- h.notifyDaemonWorkspacesChanged(uuidToString(user.ID))-- writeJSON(w, http.StatusCreated, h.memberWithUserResponse(member, user))-}-type UpdateMemberRequest struct {Role string `json:"role"`}@@ -749,6 +676,7 @@ func (h *Handler) DeleteMember(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to delete member")return}+ h.settleMemberCapacityRelease(r.Context(), uuid.UUID(target.WorkspaceID.Bytes), uuid.UUID(target.ID.Bytes))h.MembershipCache.Invalidate(r.Context(), uuidToString(target.UserID), workspaceID)@@ -792,6 +720,7 @@ func (h *Handler) LeaveWorkspace(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to leave workspace")return}+ h.settleMemberCapacityRelease(r.Context(), uuid.UUID(member.WorkspaceID.Bytes), uuid.UUID(member.ID.Bytes))h.MembershipCache.Invalidate(r.Context(), uuidToString(member.UserID), workspaceID)@@ -1225,6 +1154,27 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "prepare relationship graph",run: func() error { return qtx.PrepareWorkspaceDeletionLinks(ctx, requester.WorkspaceID) },},+ {+ // These FK-free intents deliberately survive the transaction so the+ // worker can release every invitation/member seat after local rows+ // disappear. Skipped for self-hosted/unmanaged deployments.+ name: "prepare seat capacity release",+ run: func() error {+ if !h.seatCapacitySettlementEnabled() {+ return nil+ }+ if err := qtx.DeleteSeatCapacityConfirmIntentsForWorkspaceDeletion(ctx, requester.WorkspaceID); err != nil {+ return err+ }+ if err := qtx.PrepareSeatCapacityOperationReleasesForWorkspaceDeletion(ctx, requester.WorkspaceID); err != nil {+ return err+ }+ if err := qtx.PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion(ctx, requester.WorkspaceID); err != nil {+ return err+ }+ return qtx.PrepareSeatCapacityMemberReleasesForWorkspaceDeletion(ctx, requester.WorkspaceID)+ },+ },{name: "delete chat pins",run: func() error { return qtx.DeleteChatPinnedAgentsByWorkspace(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex cc002e125a..7db3958811 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -106,6 +106,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"quick_action": workspaceDelete,"runtime_profile": workspaceDelete,"schema_migrations": workspaceDeleteKeep,+ "seat_capacity_outbox": workspaceDeleteSettle,"skill": workspaceDelete,"skill_file": workspaceDelete,"skill_to_label": workspaceDelete,diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex e4f6bbc3b1..221be16d5e 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -4,6 +4,7 @@ import ("context""log/slog"+ "github.com/google/uuid""github.com/jackc/pgx/v5/pgtype"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -210,6 +211,11 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID// never followed by a failed member-delete (which would leave the user// still a member with a dead runtime), and a failed revoke never leaves// the user out of the workspace with a still-online runtime.+ if h.seatCapacitySettlementEnabled() {+ if err := enqueueMemberCapacityRelease(ctx, qtx, uuid.UUID(workspaceID.Bytes), uuid.UUID(memberID.Bytes)); err != nil {+ return empty, err+ }+ }if err := qtx.DeleteMember(ctx, memberID); err != nil {return empty, err}diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.goindex e4a3984c3a..c42641a1b5 100644--- a/server/internal/metrics/registry.go+++ b/server/internal/metrics/registry.go@@ -32,6 +32,7 @@ type Registry struct {Business *BusinessMetricsChannelMedia *ChannelMediaReconcilerMetricsChannelLease *ChannelLeaseMetrics+ SeatCapacity *SeatCapacityMetricsWecom *WecomMetrics// Sampler is non-nil only when RegistryOptions.BusinessSampler was// supplied with a valid Pool. Exposed so the cmd/server entrypoint@@ -63,6 +64,9 @@ func NewRegistry(opts RegistryOptions) *Registry {channelLease := NewChannelLeaseMetrics()reg.MustRegister(channelLease.Collectors()...)+ seatCapacity := NewSeatCapacityMetrics()+ reg.MustRegister(seatCapacity.Collectors()...)+wecomMetrics := NewWecomMetrics()reg.MustRegister(wecomMetrics.Collectors()...)@@ -87,6 +91,7 @@ func NewRegistry(opts RegistryOptions) *Registry {Business: businessMetrics,ChannelMedia: channelMedia,ChannelLease: channelLease,+ SeatCapacity: seatCapacity,Wecom: wecomMetrics,Sampler: sampler,}diff --git a/server/internal/metrics/seat_capacity.go b/server/internal/metrics/seat_capacity.gonew file mode 100644index 0000000000..0c79c64d96--- /dev/null+++ b/server/internal/metrics/seat_capacity.go@@ -0,0 +1,71 @@+package metrics++import "github.com/prometheus/client_golang/prometheus"++var seatCapacityActions = []string{+ "reserve_invitation",+ "consume_invitation",+ "claim_share_join",+ "confirm",+ "release",+ "release_member",+}++// SeatCapacityMetrics exposes product-side billing intents without using+// workspace IDs as labels. Operators can alert on an action becoming old or+// entering the terminal dead-letter state while preserving tenant privacy.+type SeatCapacityMetrics struct {+ Pending *prometheus.GaugeVec+ DeadLettered *prometheus.GaugeVec+ OldestPendingAge *prometheus.GaugeVec+}++func NewSeatCapacityMetrics() *SeatCapacityMetrics {+ m := &SeatCapacityMetrics{+ Pending: prometheus.NewGaugeVec(prometheus.GaugeOpts{+ Namespace: "multica",+ Subsystem: "seat_capacity_outbox",+ Name: "pending",+ Help: "Product-side seat capacity intents waiting to settle by action.",+ }, []string{"action"}),+ DeadLettered: prometheus.NewGaugeVec(prometheus.GaugeOpts{+ Namespace: "multica",+ Subsystem: "seat_capacity_outbox",+ Name: "dead_lettered",+ Help: "Terminal seat capacity intents requiring operator repair by action.",+ }, []string{"action"}),+ OldestPendingAge: prometheus.NewGaugeVec(prometheus.GaugeOpts{+ Namespace: "multica",+ Subsystem: "seat_capacity_outbox",+ Name: "oldest_pending_age_seconds",+ Help: "Age in seconds of the oldest unsettled seat capacity intent by action.",+ }, []string{"action"}),+ }+ m.ResetOutbox()+ return m+}++func (m *SeatCapacityMetrics) ResetOutbox() {+ if m == nil {+ return+ }+ m.Pending.Reset()+ m.DeadLettered.Reset()+ m.OldestPendingAge.Reset()+ for _, action := range seatCapacityActions {+ m.SetOutbox(action, 0, 0, 0)+ }+}++func (m *SeatCapacityMetrics) SetOutbox(action string, pending, deadLettered int64, oldestPendingAgeSeconds float64) {+ if m == nil {+ return+ }+ m.Pending.WithLabelValues(action).Set(float64(pending))+ m.DeadLettered.WithLabelValues(action).Set(float64(deadLettered))+ m.OldestPendingAge.WithLabelValues(action).Set(oldestPendingAgeSeconds)+}++func (m *SeatCapacityMetrics) Collectors() []prometheus.Collector {+ return []prometheus.Collector{m.Pending, m.DeadLettered, m.OldestPendingAge}+}diff --git a/server/internal/metrics/seat_capacity_test.go b/server/internal/metrics/seat_capacity_test.gonew file mode 100644index 0000000000..4e12c55384--- /dev/null+++ b/server/internal/metrics/seat_capacity_test.go@@ -0,0 +1,34 @@+package metrics++import (+ "testing"++ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/testutil"+)++func TestSeatCapacityMetricsExposePendingAndDeadLettersByAction(t *testing.T) {+ metrics := NewSeatCapacityMetrics()+ registry := prometheus.NewPedanticRegistry()+ registry.MustRegister(metrics.Collectors()...)++ metrics.SetOutbox("release", 3, 1, 901)++ if got := testutil.ToFloat64(metrics.Pending.WithLabelValues("release")); got != 3 {+ t.Fatalf("pending release=%v, want 3", got)+ }+ if got := testutil.ToFloat64(metrics.DeadLettered.WithLabelValues("release")); got != 1 {+ t.Fatalf("dead-lettered release=%v, want 1", got)+ }+ if got := testutil.ToFloat64(metrics.OldestPendingAge.WithLabelValues("release")); got != 901 {+ t.Fatalf("oldest release age=%v, want 901", got)+ }+ if _, err := registry.Gather(); err != nil {+ t.Fatal(err)+ }++ metrics.ResetOutbox()+ if got := testutil.ToFloat64(metrics.DeadLettered.WithLabelValues("release")); got != 0 {+ t.Fatalf("dead-lettered release after reset=%v, want 0", got)+ }+}diff --git a/server/internal/seatcapacity/client.go b/server/internal/seatcapacity/client.gonew file mode 100644index 0000000000..2f246c3d55--- /dev/null+++ b/server/internal/seatcapacity/client.go@@ -0,0 +1,260 @@+// Package seatcapacity is the product-side executor for Multica Cloud's+// pre-purchased workspace-seat protocol.+package seatcapacity++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/google/uuid"+)++const (+ defaultTimeout = 3 * time.Second+ maxTimeout = 5 * time.Second+ maxResponseBodySize = 64 << 10+ minServiceTokenSize = 32+)++var ErrInvalidConfig = errors.New("seat capacity: invalid configuration")++type Config struct {+ Enabled bool+ BaseURL string+ ServiceToken string+ Timeout time.Duration+ HTTPClient *http.Client+}++type Capacity struct {+ PurchasedSeats int `json:"purchased_seats"`+ UsedSeats int `json:"used_seats"`+ ReservedSeats int `json:"reserved_seats"`+ Version int64 `json:"version"`+}++type Operation struct {+ Token uuid.UUID `json:"token"`+ WorkspaceID uuid.UUID `json:"workspace_id"`+ Kind string `json:"kind"`+ SubjectID uuid.UUID `json:"subject_id"`+ State string `json:"state"`+ ExpiresAt *time.Time `json:"expires_at,omitempty"`+}++type Decision struct {+ Managed bool `json:"managed"`+ Allowed bool `json:"allowed"`+ Reason string `json:"reason,omitempty"`+ Operation *Operation `json:"operation,omitempty"`+ Capacity *Capacity `json:"capacity,omitempty"`+}++type Executor interface {+ Enabled() bool+ ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (Decision, error)+ ClaimShareJoin(context.Context, uuid.UUID, uuid.UUID) (Decision, error)+ Consume(context.Context, uuid.UUID, uuid.UUID) (Decision, error)+ Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (Decision, error)+ Release(context.Context, uuid.UUID, uuid.UUID) (Decision, error)+ ReleaseMember(context.Context, uuid.UUID, uuid.UUID) (Decision, error)+ GetOperation(context.Context, uuid.UUID, uuid.UUID) (Decision, error)+}++type unavailableExecutor struct{ err error }++// NewUnavailable preserves fail-closed behavior when an operator explicitly+// enabled capacity enforcement with invalid configuration.+func NewUnavailable(err error) Executor { return &unavailableExecutor{err: err} }++func (u *unavailableExecutor) Enabled() bool { return true }+func (u *unavailableExecutor) fail() (Decision, error) {+ return Decision{}, fmt.Errorf("seat capacity executor unavailable: %w", u.err)+}+func (u *unavailableExecutor) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (Decision, error) {+ return u.fail()+}+func (u *unavailableExecutor) ClaimShareJoin(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return u.fail()+}+func (u *unavailableExecutor) Consume(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return u.fail()+}+func (u *unavailableExecutor) Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (Decision, error) {+ return u.fail()+}+func (u *unavailableExecutor) Release(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return u.fail()+}+func (u *unavailableExecutor) ReleaseMember(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return u.fail()+}+func (u *unavailableExecutor) GetOperation(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return u.fail()+}++type Client struct {+ enabled bool+ baseURL *url.URL+ serviceToken string+ timeout time.Duration+ httpClient *http.Client+}++var _ Executor = (*Client)(nil)++func New(cfg Config) (*Client, error) {+ if !cfg.Enabled {+ return &Client{}, nil+ }+ rawURL := strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/")+ baseURL, err := url.Parse(rawURL)+ if err != nil || (baseURL.Scheme != "http" && baseURL.Scheme != "https") || baseURL.Host == "" ||+ baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {+ return nil, fmt.Errorf("%w: base URL must be absolute and contain no credentials, query, or fragment", ErrInvalidConfig)+ }+ if cfg.ServiceToken != strings.TrimSpace(cfg.ServiceToken) || strings.ContainsAny(cfg.ServiceToken, " \t\r\n") || len(cfg.ServiceToken) < minServiceTokenSize {+ return nil, fmt.Errorf("%w: service token must contain at least %d non-whitespace bytes", ErrInvalidConfig, minServiceTokenSize)+ }+ timeout := cfg.Timeout+ if timeout == 0 {+ timeout = defaultTimeout+ }+ if timeout < 0 || timeout > maxTimeout {+ return nil, fmt.Errorf("%w: timeout must be positive and at most %s", ErrInvalidConfig, maxTimeout)+ }+ httpClient := &http.Client{}+ if cfg.HTTPClient != nil {+ clone := *cfg.HTTPClient+ httpClient = &clone+ }+ // The machine credential must never cross an HTTP redirect boundary.+ httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ return &Client{+ enabled: true,+ baseURL: baseURL,+ serviceToken: cfg.ServiceToken,+ timeout: timeout,+ httpClient: httpClient,+ }, nil+}++func (c *Client) Enabled() bool { return c != nil && c.enabled }++func (c *Client) ReserveInvitation(ctx context.Context, workspaceID, invitationID uuid.UUID, expiresAt time.Time) (Decision, error) {+ return c.post(ctx, workspaceID, "reserve", map[string]any{+ "token": invitationID, "kind": "invitation", "subject_id": invitationID, "expires_at": expiresAt,+ })+}++func (c *Client) ClaimShareJoin(ctx context.Context, workspaceID, intentID uuid.UUID) (Decision, error) {+ return c.post(ctx, workspaceID, "claim", map[string]any{+ "token": intentID, "kind": "share_join", "subject_id": intentID,+ })+}++func (c *Client) Consume(ctx context.Context, workspaceID, token uuid.UUID) (Decision, error) {+ return c.post(ctx, workspaceID, "consume", map[string]any{"token": token})+}++func (c *Client) Confirm(ctx context.Context, workspaceID, token, memberID uuid.UUID) (Decision, error) {+ return c.post(ctx, workspaceID, "confirm", map[string]any{"token": token, "member_id": memberID})+}++func (c *Client) Release(ctx context.Context, workspaceID, token uuid.UUID) (Decision, error) {+ return c.post(ctx, workspaceID, "release", map[string]any{"token": token})+}++func (c *Client) ReleaseMember(ctx context.Context, workspaceID, memberID uuid.UUID) (Decision, error) {+ return c.post(ctx, workspaceID, "release-member", map[string]any{"member_id": memberID})+}++func (c *Client) GetOperation(ctx context.Context, workspaceID, token uuid.UUID) (Decision, error) {+ return c.do(ctx, http.MethodGet, workspaceID, "operations/"+token.String(), nil)+}++func (c *Client) post(ctx context.Context, workspaceID uuid.UUID, action string, value any) (Decision, error) {+ body, err := json.Marshal(value)+ if err != nil {+ return Decision{}, err+ }+ return c.do(ctx, http.MethodPost, workspaceID, action, body)+}++func (c *Client) do(ctx context.Context, method string, workspaceID uuid.UUID, suffix string, body []byte) (Decision, error) {+ if !c.Enabled() {+ return Decision{Allowed: true}, nil+ }+ if workspaceID == uuid.Nil {+ return Decision{}, fmt.Errorf("seat capacity: workspace ID is required")+ }+ u := *c.baseURL+ u.Path = strings.TrimRight(c.baseURL.Path, "/") + "/api/v1/internal/subscriptions/" + workspaceID.String() + "/capacity/" + suffix++ requestCtx, cancel := context.WithTimeout(ctx, c.timeout)+ defer cancel()+ var reader io.Reader+ if len(body) > 0 {+ reader = bytes.NewReader(body)+ }+ req, err := http.NewRequestWithContext(requestCtx, method, u.String(), reader)+ if err != nil {+ return Decision{}, err+ }+ req.Header.Set("Accept", "application/json")+ req.Header.Set("Authorization", "Bearer "+c.serviceToken)+ if len(body) > 0 {+ req.Header.Set("Content-Type", "application/json")+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return Decision{}, fmt.Errorf("seat capacity request failed: %w", err)+ }+ defer resp.Body.Close()+ payload, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize+1))+ if err != nil {+ return Decision{}, fmt.Errorf("seat capacity response read failed: %w", err)+ }+ if len(payload) > maxResponseBodySize {+ return Decision{}, fmt.Errorf("seat capacity response exceeded %d bytes", maxResponseBodySize)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ var remote struct {+ Error string `json:"error"`+ Code string `json:"code"`+ }+ _ = json.Unmarshal(payload, &remote)+ return Decision{}, &HTTPError{StatusCode: resp.StatusCode, Code: remote.Code, Message: remote.Error}+ }+ var out Decision+ if err := json.Unmarshal(payload, &out); err != nil {+ return Decision{}, fmt.Errorf("seat capacity response decode failed: %w", err)+ }+ return out, nil+}++type HTTPError struct {+ StatusCode int+ Code string+ Message string+}++func (e *HTTPError) Error() string {+ if e.Code != "" {+ return fmt.Sprintf("seat capacity request returned %d (%s)", e.StatusCode, e.Code)+ }+ return fmt.Sprintf("seat capacity request returned %d", e.StatusCode)+}++func IsNotFound(err error) bool {+ var remote *HTTPError+ return errors.As(err, &remote) && remote.StatusCode == http.StatusNotFound+}diff --git a/server/internal/seatcapacity/client_test.go b/server/internal/seatcapacity/client_test.gonew file mode 100644index 0000000000..493e753453--- /dev/null+++ b/server/internal/seatcapacity/client_test.go@@ -0,0 +1,96 @@+package seatcapacity++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"+)++func TestClientReserveInvitation(t *testing.T) {+ workspaceID, invitationID := uuid.New(), uuid.New()+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/base/api/v1/internal/subscriptions/"+workspaceID.String()+"/capacity/reserve" {+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)+ }+ if got := r.Header.Get("Authorization"); got != "Bearer "+strings.Repeat("s", 32) {+ t.Fatalf("Authorization = %q", got)+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"managed":true,"allowed":false,"reason":"capacity_full"}`))+ }))+ defer server.Close()++ client, err := New(Config{Enabled: true, BaseURL: server.URL + "/base", ServiceToken: strings.Repeat("s", 32)})+ if err != nil {+ t.Fatal(err)+ }+ decision, err := client.ReserveInvitation(context.Background(), workspaceID, invitationID, time.Now().Add(time.Hour))+ if err != nil {+ t.Fatal(err)+ }+ if !decision.Managed || decision.Allowed || decision.Reason != "capacity_full" {+ t.Fatalf("decision = %+v", decision)+ }+}++func TestClientRejectsRedirectAndDoesNotForwardCredential(t *testing.T) {+ var redirectedAuth string+ target := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {+ redirectedAuth = r.Header.Get("Authorization")+ }))+ defer target.Close()+ source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)+ }))+ defer source.Close()++ client, err := New(Config{Enabled: true, BaseURL: source.URL, ServiceToken: strings.Repeat("s", 32)})+ if err != nil {+ t.Fatal(err)+ }+ _, err = client.Release(context.Background(), uuid.New(), uuid.New())+ var remote *HTTPError+ if !errors.As(err, &remote) || remote.StatusCode != http.StatusTemporaryRedirect {+ t.Fatalf("error = %v", err)+ }+ if redirectedAuth != "" {+ t.Fatalf("credential reached redirect target: %q", redirectedAuth)+ }+}++func TestDisabledClientPreservesLegacyBehavior(t *testing.T) {+ client, err := New(Config{})+ if err != nil {+ t.Fatal(err)+ }+ decision, err := client.ClaimShareJoin(context.Background(), uuid.New(), uuid.New())+ if err != nil || !decision.Allowed || decision.Managed {+ t.Fatalf("decision=%+v err=%v", decision, err)+ }+}++func TestEnabledClientRejectsUnsafeConfiguration(t *testing.T) {+ tests := []struct {+ name string+ cfg Config+ }{+ {name: "missing URL", cfg: Config{Enabled: true, ServiceToken: strings.Repeat("s", 32)}},+ {name: "URL credentials", cfg: Config{Enabled: true, BaseURL: "https://user:[email protected]", ServiceToken: strings.Repeat("s", 32)}},+ {name: "short token", cfg: Config{Enabled: true, BaseURL: "https://example.com", ServiceToken: "short"}},+ {name: "token whitespace", cfg: Config{Enabled: true, BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 31) + "\n"}},+ {name: "excessive timeout", cfg: Config{Enabled: true, BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 32), Timeout: 6 * time.Second}},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if _, err := New(tt.cfg); !errors.Is(err, ErrInvalidConfig) {+ t.Fatalf("New() error = %v, want ErrInvalidConfig", err)+ }+ })+ }+}diff --git a/server/internal/seatcapacity/worker.go b/server/internal/seatcapacity/worker.gonew file mode 100644index 0000000000..3d8299fbfb--- /dev/null+++ b/server/internal/seatcapacity/worker.go@@ -0,0 +1,378 @@+package seatcapacity++import (+ "context"+ "errors"+ "log/slog"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ ActionReserveInvitation = "reserve_invitation"+ ActionConsumeInvitation = "consume_invitation"+ ActionClaimShareJoin = "claim_share_join"+ ActionConfirm = "confirm"+ ActionRelease = "release"+ ActionReleaseMember = "release_member"++ defaultReconcileInterval = 30 * time.Second+ defaultRecoveryGrace = 5 * time.Minute+ defaultClaimLease = 5 * time.Minute+ defaultWorkspaceLockWait = 30 * time.Second+ defaultBatchSize = 100+ defaultMaxAttempts = 10+)++type WorkerConfig struct {+ ReconcileInterval time.Duration+ BatchSize int32+ MaxAttempts int32+ Logger *slog.Logger+ Metrics WorkerMetrics+}++type workerQueries interface {+ ClaimNextDueSeatCapacityIntent(context.Context, pgtype.Timestamptz) (db.SeatCapacityOutbox, error)+ DeleteClaimedSeatCapacityIntent(context.Context, db.DeleteClaimedSeatCapacityIntentParams) (int64, error)+ ExpireInvitationForCapacityRecovery(context.Context, pgtype.UUID) error+ GetClaimedSeatCapacityIntent(context.Context, db.GetClaimedSeatCapacityIntentParams) (db.SeatCapacityOutbox, error)+ GetInvitation(context.Context, pgtype.UUID) (db.WorkspaceInvitation, error)+ MarkClaimedSeatCapacityIntentDeadLettered(context.Context, db.MarkClaimedSeatCapacityIntentDeadLetteredParams) (int64, error)+ MarkClaimedSeatCapacityIntentFailed(context.Context, db.MarkClaimedSeatCapacityIntentFailedParams) (int64, error)+ SeatCapacityOutboxStats(context.Context) ([]db.SeatCapacityOutboxStatsRow, error)+ TransitionClaimedSeatCapacityIntent(context.Context, db.TransitionClaimedSeatCapacityIntentParams) (int64, error)+}++type WorkerMetrics interface {+ ResetOutbox()+ SetOutbox(action string, pending, deadLettered int64, oldestPendingAgeSeconds float64)+}++// Worker settles durable product-side intents. Each row is claimed atomically+// before a Cloud request, so API replicas do not amplify the same backlog.+type Worker struct {+ queries workerQueries+ executor Executor+ reconcileInterval time.Duration+ batchSize int32+ maxAttempts int32+ logger *slog.Logger+ metrics WorkerMetrics+ workspaceLocker WorkspaceLocker+ now func() time.Time+}++func NewWorker(queries *db.Queries, executor Executor, locker WorkspaceLocker, cfg WorkerConfig) *Worker {+ worker := newWorker(queries, executor, cfg)+ worker.workspaceLocker = locker+ return worker+}++func newWorker(queries workerQueries, executor Executor, cfg WorkerConfig) *Worker {+ interval := cfg.ReconcileInterval+ if interval <= 0 {+ interval = defaultReconcileInterval+ }+ batch := cfg.BatchSize+ if batch <= 0 {+ batch = defaultBatchSize+ }+ maxAttempts := cfg.MaxAttempts+ if maxAttempts <= 0 {+ maxAttempts = defaultMaxAttempts+ }+ logger := cfg.Logger+ if logger == nil {+ logger = slog.Default()+ }+ return &Worker{+ queries: queries, executor: executor, reconcileInterval: interval,+ batchSize: batch, maxAttempts: maxAttempts, logger: logger,+ metrics: cfg.Metrics, now: time.Now,+ }+}++func (w *Worker) Enabled() bool {+ return w != nil && w.queries != nil && w.executor != nil && w.executor.Enabled()+}++func (w *Worker) Run(ctx context.Context) {+ if !w.Enabled() {+ return+ }+ ticker := time.NewTicker(w.reconcileInterval)+ defer ticker.Stop()+ for {+ if err := w.ReconcileOnce(ctx); err != nil && ctx.Err() == nil {+ w.logger.WarnContext(ctx, "seat capacity outbox reconciliation failed", "error", err)+ }+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ }+ }+}++func (w *Worker) ReconcileOnce(ctx context.Context) error {+ if !w.Enabled() {+ return nil+ }+ for i := int32(0); i < w.batchSize; i++ {+ intent, err := w.queries.ClaimNextDueSeatCapacityIntent(ctx, pgtype.Timestamptz{+ Time: w.now().Add(defaultClaimLease), Valid: true,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ break+ }+ if err != nil {+ return err+ }+ settleErr := w.settleWithWorkspaceLimit(ctx, intent)+ if settleErr != nil {+ w.recordFailure(ctx, intent, settleErr)+ }+ }+ return w.refreshMetrics(ctx)+}++func (w *Worker) settleWithWorkspaceLimit(ctx context.Context, intent db.SeatCapacityOutbox) error {+ if w.workspaceLocker == nil {+ return w.settle(ctx, intent)+ }+ lockCtx, cancel := context.WithTimeout(ctx, defaultWorkspaceLockWait)+ defer cancel()+ lockedDB, unlock, err := w.workspaceLocker.Lock(lockCtx, uuidFromPG(intent.WorkspaceID))+ if err != nil {+ return err+ }+ defer unlock()+ lockedQueries := w.queries+ if lockedDB != nil {+ lockedQueries = db.New(lockedDB)+ }+ current, err := lockedQueries.GetClaimedSeatCapacityIntent(ctx, db.GetClaimedSeatCapacityIntentParams{+ OperationToken: intent.OperationToken, Action: intent.Action, LeaseToken: intent.LeaseToken,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ if err != nil {+ return err+ }+ lockedWorker := *w+ lockedWorker.queries = lockedQueries+ return lockedWorker.settle(ctx, current)+}++func (w *Worker) settle(ctx context.Context, intent db.SeatCapacityOutbox) error {+ if !intent.LeaseToken.Valid {+ return errors.New("claimed seat capacity intent omitted lease token")+ }+ workspaceID := uuidFromPG(intent.WorkspaceID)+ token := uuidFromPG(intent.OperationToken)+ switch intent.Action {+ case ActionReserveInvitation:+ return w.recoverReserve(ctx, intent, workspaceID, token)+ case ActionConsumeInvitation, ActionClaimShareJoin:+ return w.recoverConsuming(ctx, intent, workspaceID, token)+ case ActionConfirm:+ decision, err := w.executor.Confirm(ctx, workspaceID, token, uuidFromPG(intent.MemberID))+ if err != nil {+ return err+ }+ if !decision.Allowed {+ return errors.New("capacity confirm rejected in state " + decision.Reason)+ }+ return w.deleteCurrent(ctx, intent)+ case ActionRelease:+ decision, err := w.executor.Release(ctx, workspaceID, token)+ if err != nil && !IsNotFound(err) {+ return err+ }+ if err == nil && decision.Managed && !decision.Allowed && decision.Reason != "released" && decision.Reason != "denied" {+ return errors.New("capacity release rejected in state " + decision.Reason)+ }+ return w.deleteCurrent(ctx, intent)+ case ActionReleaseMember:+ decision, err := w.executor.ReleaseMember(ctx, workspaceID, uuidFromPG(intent.MemberID))+ if err != nil && !IsNotFound(err) {+ return err+ }+ if err == nil && decision.Managed && !decision.Allowed && decision.Reason != "released" {+ return errors.New("capacity member release rejected in state " + decision.Reason)+ }+ return w.deleteCurrent(ctx, intent)+ default:+ return errors.New("unknown seat capacity outbox action")+ }+}++func (w *Worker) recoverReserve(ctx context.Context, intent db.SeatCapacityOutbox, workspaceID, token uuid.UUID) error {+ decision, err := w.executor.GetOperation(ctx, workspaceID, token)+ if IsNotFound(err) || (err == nil && !decision.Managed) {+ return w.deleteCurrent(ctx, intent)+ }+ if err != nil {+ return err+ }+ if decision.Operation == nil {+ return errors.New("managed capacity operation response omitted operation")+ }+ switch decision.Operation.State {+ case "denied", "released":+ return w.deleteCurrent(ctx, intent)+ case "reserved":+ invitationID := intent.InvitationID+ if !invitationID.Valid {+ _, transitionErr := w.transition(ctx, intent, ActionRelease, pgtype.UUID{})+ return transitionErr+ }+ invitation, getErr := w.queries.GetInvitation(ctx, invitationID)+ if getErr == nil && invitation.Status == "pending" {+ return w.deleteCurrent(ctx, intent)+ }+ if getErr != nil && !errors.Is(getErr, pgx.ErrNoRows) {+ return getErr+ }+ _, transitionErr := w.transition(ctx, intent, ActionRelease, pgtype.UUID{})+ return transitionErr+ default:+ return errors.New("unexpected recovered invitation reservation state " + decision.Operation.State)+ }+}++func (w *Worker) recoverConsuming(ctx context.Context, intent db.SeatCapacityOutbox, workspaceID, token uuid.UUID) error {+ decision, err := w.executor.GetOperation(ctx, workspaceID, token)+ if IsNotFound(err) || (err == nil && !decision.Managed) {+ return w.deleteCurrent(ctx, intent)+ }+ if err != nil {+ return err+ }+ if decision.Operation == nil {+ return errors.New("managed capacity operation response omitted operation")+ }+ switch decision.Operation.State {+ case "reserved":+ // The consume request never took effect. Keep the invitation usable.+ return w.deleteCurrent(ctx, intent)+ case "used":+ // A concurrent request already committed and confirmed the member. A+ // stale consuming worker must not try to release that used seat.+ return w.deleteCurrent(ctx, intent)+ case "denied", "released":+ if intent.Action == ActionConsumeInvitation && intent.InvitationID.Valid {+ _ = w.queries.ExpireInvitationForCapacityRecovery(ctx, intent.InvitationID)+ }+ return w.deleteCurrent(ctx, intent)+ case "consuming":+ // No product transaction committed: that transaction would atomically+ // change this row to confirm. Retire the abandoned user request rather+ // than hold capacity forever.+ changed, err := w.transition(ctx, intent, ActionRelease, pgtype.UUID{})+ if err != nil || !changed {+ return err+ }+ if intent.Action == ActionConsumeInvitation && intent.InvitationID.Valid {+ if err := w.queries.ExpireInvitationForCapacityRecovery(ctx, intent.InvitationID); err != nil {+ return err+ }+ }+ return nil+ default:+ return errors.New("unexpected recovered consuming capacity state " + decision.Operation.State)+ }+}++func (w *Worker) transition(ctx context.Context, intent db.SeatCapacityOutbox, action string, memberID pgtype.UUID) (bool, error) {+ rows, err := w.queries.TransitionClaimedSeatCapacityIntent(ctx, db.TransitionClaimedSeatCapacityIntentParams{+ NextAction: action, CurrentAction: intent.Action, MemberID: memberID, OperationToken: intent.OperationToken,+ NextAttemptAt: pgtype.Timestamptz{Time: w.now(), Valid: true}, LeaseToken: intent.LeaseToken,+ })+ return rows == 1, err+}++func (w *Worker) deleteCurrent(ctx context.Context, intent db.SeatCapacityOutbox) error {+ _, err := w.queries.DeleteClaimedSeatCapacityIntent(ctx, db.DeleteClaimedSeatCapacityIntentParams{+ OperationToken: intent.OperationToken,+ Action: intent.Action,+ LeaseToken: intent.LeaseToken,+ })+ return err+}++func (w *Worker) recordFailure(ctx context.Context, intent db.SeatCapacityOutbox, settleErr error) {+ if intent.AttemptCount+1 >= w.maxAttempts {+ rows, err := w.queries.MarkClaimedSeatCapacityIntentDeadLettered(ctx, db.MarkClaimedSeatCapacityIntentDeadLetteredParams{+ LastError: settleErr.Error(), OperationToken: intent.OperationToken, Action: intent.Action,+ LeaseToken: intent.LeaseToken,+ })+ if err != nil {+ w.logger.WarnContext(ctx, "seat capacity outbox dead letter could not be recorded", "error", err)+ return+ }+ if rows == 1 {+ w.logger.ErrorContext(ctx, "seat capacity outbox intent moved to dead letter",+ "workspace_id", workspaceIDString(intent.WorkspaceID), "action", intent.Action,+ "attempt", intent.AttemptCount+1, "error", settleErr)+ }+ return+ }+ backoff := 5 * time.Second+ for i := int32(0); i < intent.AttemptCount && backoff < 5*time.Minute; i++ {+ backoff *= 2+ }+ if backoff > 5*time.Minute {+ backoff = 5 * time.Minute+ }+ rows, err := w.queries.MarkClaimedSeatCapacityIntentFailed(ctx, db.MarkClaimedSeatCapacityIntentFailedParams{+ LastError: settleErr.Error(), NextAttemptAt: pgtype.Timestamptz{Time: w.now().Add(backoff), Valid: true},+ OperationToken: intent.OperationToken, Action: intent.Action, LeaseToken: intent.LeaseToken,+ })+ if err != nil {+ w.logger.WarnContext(ctx, "seat capacity outbox failure could not be recorded", "error", err)+ }+ if rows == 1 && (intent.AttemptCount == 0 || (intent.AttemptCount+1)%10 == 0) {+ w.logger.WarnContext(ctx, "seat capacity outbox intent remains unsettled",+ "workspace_id", workspaceIDString(intent.WorkspaceID), "action", intent.Action,+ "attempt", intent.AttemptCount+1, "error", settleErr)+ }+}++func (w *Worker) refreshMetrics(ctx context.Context) error {+ if w.metrics == nil {+ return nil+ }+ stats, err := w.queries.SeatCapacityOutboxStats(ctx)+ if err != nil {+ return err+ }+ w.metrics.ResetOutbox()+ for _, stat := range stats {+ w.metrics.SetOutbox(stat.Action, stat.PendingCount, stat.DeadLetteredCount, stat.OldestPendingAgeSeconds)+ }+ return nil+}++func uuidFromPG(value pgtype.UUID) uuid.UUID {+ if !value.Valid {+ return uuid.Nil+ }+ return uuid.UUID(value.Bytes)+}++func workspaceIDString(value pgtype.UUID) string { return uuidFromPG(value).String() }++func RecoveryDue(now time.Time) pgtype.Timestamptz {+ return pgtype.Timestamptz{Time: now.Add(defaultRecoveryGrace), Valid: true}+}++func RetryDue(now time.Time) pgtype.Timestamptz {+ return pgtype.Timestamptz{Time: now, Valid: true}+}diff --git a/server/internal/seatcapacity/worker_test.go b/server/internal/seatcapacity/worker_test.gonew file mode 100644index 0000000000..f1f1609de2--- /dev/null+++ b/server/internal/seatcapacity/worker_test.go@@ -0,0 +1,332 @@+package seatcapacity++import (+ "context"+ "errors"+ "net/http"+ "sync"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type workerTestExecutor struct {+ decision Decision+ err error+ confirms int+}++type workerTestLocker struct {+ locks int+ unlocks int+}++func (l *workerTestLocker) Lock(context.Context, uuid.UUID) (db.DBTX, func(), error) {+ l.locks+++ return nil, func() { l.unlocks++ }, nil+}++func (e *workerTestExecutor) Enabled() bool { return true }+func (e *workerTestExecutor) ReserveInvitation(context.Context, uuid.UUID, uuid.UUID, time.Time) (Decision, error) {+ return Decision{}, nil+}+func (e *workerTestExecutor) ClaimShareJoin(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return Decision{}, nil+}+func (e *workerTestExecutor) Consume(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return Decision{}, nil+}+func (e *workerTestExecutor) Confirm(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) (Decision, error) {+ e.confirms+++ return e.decision, e.err+}+func (e *workerTestExecutor) Release(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return e.decision, e.err+}+func (e *workerTestExecutor) ReleaseMember(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return e.decision, e.err+}+func (e *workerTestExecutor) GetOperation(context.Context, uuid.UUID, uuid.UUID) (Decision, error) {+ return e.decision, e.err+}++type workerTestQueries struct {+ mu sync.Mutex++ intent db.SeatCapacityOutbox+ claimAvailable bool+ invitation db.WorkspaceInvitation+ invitationError error+ stats []db.SeatCapacityOutboxStatsRow++ transitions int+ deletes int+ expires int+ failures int+ deadLetters int+}++func (q *workerTestQueries) ClaimNextDueSeatCapacityIntent(context.Context, pgtype.Timestamptz) (db.SeatCapacityOutbox, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if !q.claimAvailable {+ return db.SeatCapacityOutbox{}, pgx.ErrNoRows+ }+ q.claimAvailable = false+ q.intent.LeaseToken = uuidToTestPG(uuid.New())+ return q.intent, nil+}++func (q *workerTestQueries) DeleteClaimedSeatCapacityIntent(_ context.Context, arg db.DeleteClaimedSeatCapacityIntentParams) (int64, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if q.intent.OperationToken == arg.OperationToken && q.intent.Action == arg.Action && q.intent.LeaseToken == arg.LeaseToken {+ q.deletes+++ return 1, nil+ }+ return 0, nil+}++func (q *workerTestQueries) ExpireInvitationForCapacityRecovery(context.Context, pgtype.UUID) error {+ q.mu.Lock()+ defer q.mu.Unlock()+ q.expires+++ return nil+}++func (q *workerTestQueries) GetInvitation(context.Context, pgtype.UUID) (db.WorkspaceInvitation, error) {+ return q.invitation, q.invitationError+}++func (q *workerTestQueries) GetClaimedSeatCapacityIntent(_ context.Context, arg db.GetClaimedSeatCapacityIntentParams) (db.SeatCapacityOutbox, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if q.intent.OperationToken != arg.OperationToken || q.intent.Action != arg.Action || q.intent.LeaseToken != arg.LeaseToken {+ return db.SeatCapacityOutbox{}, pgx.ErrNoRows+ }+ return q.intent, nil+}++func (q *workerTestQueries) MarkClaimedSeatCapacityIntentDeadLettered(_ context.Context, arg db.MarkClaimedSeatCapacityIntentDeadLetteredParams) (int64, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if q.intent.OperationToken != arg.OperationToken || q.intent.Action != arg.Action || q.intent.LeaseToken != arg.LeaseToken {+ return 0, nil+ }+ q.deadLetters+++ q.intent.LeaseToken = pgtype.UUID{}+ return 1, nil+}++func (q *workerTestQueries) MarkClaimedSeatCapacityIntentFailed(_ context.Context, arg db.MarkClaimedSeatCapacityIntentFailedParams) (int64, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if q.intent.OperationToken != arg.OperationToken || q.intent.Action != arg.Action || q.intent.LeaseToken != arg.LeaseToken {+ return 0, nil+ }+ q.failures+++ q.intent.LeaseToken = pgtype.UUID{}+ return 1, nil+}++func (q *workerTestQueries) SeatCapacityOutboxStats(context.Context) ([]db.SeatCapacityOutboxStatsRow, error) {+ return q.stats, nil+}++func (q *workerTestQueries) TransitionClaimedSeatCapacityIntent(_ context.Context, arg db.TransitionClaimedSeatCapacityIntentParams) (int64, error) {+ q.mu.Lock()+ defer q.mu.Unlock()+ if q.intent.OperationToken != arg.OperationToken || q.intent.Action != arg.CurrentAction || q.intent.LeaseToken != arg.LeaseToken {+ return 0, nil+ }+ q.intent.Action = arg.NextAction+ q.intent.LeaseToken = pgtype.UUID{}+ q.transitions+++ return 1, nil+}++func (q *workerTestQueries) counts() (transitions, deletes, expires, failures, deadLetters int) {+ q.mu.Lock()+ defer q.mu.Unlock()+ return q.transitions, q.deletes, q.expires, q.failures, q.deadLetters+}++func workerTestIntent(action string) db.SeatCapacityOutbox {+ return db.SeatCapacityOutbox{+ WorkspaceID: uuidToTestPG(uuid.New()), OperationToken: uuidToTestPG(uuid.New()),+ Action: action, InvitationID: uuidToTestPG(uuid.New()), LeaseToken: uuidToTestPG(uuid.New()),+ }+}++func uuidToTestPG(value uuid.UUID) pgtype.UUID {+ return pgtype.UUID{Bytes: value, Valid: true}+}++func recoveredDecision(state string) Decision {+ return Decision{Managed: true, Operation: &Operation{State: state}}+}++func TestRecoverConsumingTransitionsAbandonedOperationToRelease(t *testing.T) {+ intent := workerTestIntent(ActionConsumeInvitation)+ queries := &workerTestQueries{intent: intent}+ worker := newWorker(queries, &workerTestExecutor{decision: recoveredDecision("consuming")}, WorkerConfig{})++ if err := worker.recoverConsuming(context.Background(), intent, uuidFromPG(intent.WorkspaceID), uuidFromPG(intent.OperationToken)); err != nil {+ t.Fatal(err)+ }+ transitions, deletes, expires, _, _ := queries.counts()+ if transitions != 1 || deletes != 0 || expires != 1 {+ t.Fatalf("transitions=%d deletes=%d expires=%d, want 1/0/1", transitions, deletes, expires)+ }+ if queries.intent.Action != ActionRelease {+ t.Fatalf("action=%q, want %q", queries.intent.Action, ActionRelease)+ }+}++func TestRecoverConsumingUsedDeletesWithoutReleasing(t *testing.T) {+ intent := workerTestIntent(ActionConsumeInvitation)+ queries := &workerTestQueries{intent: intent}+ worker := newWorker(queries, &workerTestExecutor{decision: recoveredDecision("used")}, WorkerConfig{})++ if err := worker.recoverConsuming(context.Background(), intent, uuidFromPG(intent.WorkspaceID), uuidFromPG(intent.OperationToken)); err != nil {+ t.Fatal(err)+ }+ transitions, deletes, expires, _, _ := queries.counts()+ if transitions != 0 || deletes != 1 || expires != 0 {+ t.Fatalf("transitions=%d deletes=%d expires=%d, want 0/1/0", transitions, deletes, expires)+ }+}++func TestRecoverReserveKeepsPendingInvitationReservation(t *testing.T) {+ intent := workerTestIntent(ActionReserveInvitation)+ queries := &workerTestQueries{+ intent: intent,+ invitation: db.WorkspaceInvitation{+ ID: intent.InvitationID, Status: "pending",+ },+ }+ worker := newWorker(queries, &workerTestExecutor{decision: recoveredDecision("reserved")}, WorkerConfig{})++ if err := worker.recoverReserve(context.Background(), intent, uuidFromPG(intent.WorkspaceID), uuidFromPG(intent.OperationToken)); err != nil {+ t.Fatal(err)+ }+ transitions, deletes, expires, _, _ := queries.counts()+ if transitions != 0 || deletes != 1 || expires != 0 {+ t.Fatalf("transitions=%d deletes=%d expires=%d, want 0/1/0", transitions, deletes, expires)+ }+}++func TestRecoveryCleansUnknownOrUnmanagedOperations(t *testing.T) {+ tests := []struct {+ name string+ decision Decision+ err error+ }{+ {name: "not found", err: &HTTPError{StatusCode: http.StatusNotFound}},+ {name: "unmanaged", decision: Decision{Managed: false}},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ intent := workerTestIntent(ActionConsumeInvitation)+ queries := &workerTestQueries{intent: intent}+ worker := newWorker(queries, &workerTestExecutor{decision: tt.decision, err: tt.err}, WorkerConfig{})++ if err := worker.recoverConsuming(context.Background(), intent, uuidFromPG(intent.WorkspaceID), uuidFromPG(intent.OperationToken)); err != nil {+ t.Fatal(err)+ }+ _, deletes, expires, _, _ := queries.counts()+ if deletes != 1 || expires != 0 {+ t.Fatalf("deletes=%d expires=%d, want 1/0", deletes, expires)+ }+ })+ }+}++func TestConcurrentRecoveryOnlyOneReplicaTransitionsIntent(t *testing.T) {+ intent := workerTestIntent(ActionConsumeInvitation)+ queries := &workerTestQueries{intent: intent}+ executor := &workerTestExecutor{decision: recoveredDecision("consuming")}+ workerA := newWorker(queries, executor, WorkerConfig{})+ workerB := newWorker(queries, executor, WorkerConfig{})++ var wg sync.WaitGroup+ errs := make(chan error, 2)+ for _, worker := range []*Worker{workerA, workerB} {+ wg.Add(1)+ go func(w *Worker) {+ defer wg.Done()+ errs <- w.recoverConsuming(context.Background(), intent, uuidFromPG(intent.WorkspaceID), uuidFromPG(intent.OperationToken))+ }(worker)+ }+ wg.Wait()+ close(errs)+ for err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }++ transitions, _, expires, _, _ := queries.counts()+ if transitions != 1 || expires != 1 {+ t.Fatalf("transitions=%d expires=%d, want 1/1", transitions, expires)+ }+}++func TestWorkerDeadLettersAfterMaximumAttempts(t *testing.T) {+ intent := workerTestIntent(ActionConfirm)+ intent.AttemptCount = 1+ queries := &workerTestQueries{intent: intent, claimAvailable: true}+ worker := newWorker(queries, &workerTestExecutor{err: errors.New("cloud unavailable")}, WorkerConfig{+ MaxAttempts: 2,+ })++ if err := worker.ReconcileOnce(context.Background()); err != nil {+ t.Fatal(err)+ }+ _, _, _, failures, deadLetters := queries.counts()+ if failures != 0 || deadLetters != 1 {+ t.Fatalf("failures=%d deadLetters=%d, want 0/1", failures, deadLetters)+ }+}++func TestWorkerUsesWorkspaceSerializationBeforeCloudCall(t *testing.T) {+ intent := workerTestIntent(ActionConfirm)+ queries := &workerTestQueries{intent: intent}+ locker := &workerTestLocker{}+ worker := newWorker(queries, &workerTestExecutor{decision: Decision{Managed: true, Allowed: true}}, WorkerConfig{})+ worker.workspaceLocker = locker++ if err := worker.settleWithWorkspaceLimit(context.Background(), intent); err != nil {+ t.Fatal(err)+ }+ if locker.locks != 1 || locker.unlocks != 1 {+ t.Fatalf("locks=%d unlocks=%d, want 1/1", locker.locks, locker.unlocks)+ }+}++func TestWorkerSkipsCloudCallWhenClaimWasReactivatedBeforeWorkspaceLock(t *testing.T) {+ intent := workerTestIntent(ActionConfirm)+ queries := &workerTestQueries{intent: intent}+ executor := &workerTestExecutor{decision: Decision{Managed: true, Allowed: true}}+ worker := newWorker(queries, executor, WorkerConfig{})+ worker.workspaceLocker = &workerTestLocker{}+ queries.intent.LeaseToken = pgtype.UUID{}++ if err := worker.settleWithWorkspaceLimit(context.Background(), intent); err != nil {+ t.Fatal(err)+ }+ if executor.confirms != 0 {+ t.Fatalf("stale worker made %d Cloud confirm calls, want 0", executor.confirms)+ }+}++func TestRecoveryDueAllowsRetryableRequestFailuresToSettle(t *testing.T) {+ now := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC)+ if got := RecoveryDue(now).Time.Sub(now); got != 5*time.Minute {+ t.Fatalf("RecoveryDue delay=%s, want 5m", got)+ }+}diff --git a/server/internal/seatcapacity/workspace_locker.go b/server/internal/seatcapacity/workspace_locker.gonew file mode 100644index 0000000000..8209e88510--- /dev/null+++ b/server/internal/seatcapacity/workspace_locker.go@@ -0,0 +1,181 @@+package seatcapacity++import (+ "context"+ "crypto/sha256"+ "encoding/binary"+ "fmt"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgxpool"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const workspaceLockReleaseTimeout = 3 * time.Second+const defaultWorkspaceCooldown = 75 * time.Millisecond+const workspaceLockPollInterval = 25 * time.Millisecond+const maxWorkspaceLockConnections = 4+const workspaceLockPoolFraction = 4++type WorkspaceLocker interface {+ Lock(context.Context, uuid.UUID) (db.DBTX, func(), error)+}++// postgresWorkspaceLocker serializes Cloud capacity calls for one workspace+// across API replicas. It pins a PostgreSQL session because advisory locks are+// session-scoped; returning the connection before unlock would leak the lock+// into an unrelated pool borrower.+type postgresWorkspaceLocker struct {+ pool *pgxpool.Pool++ mu sync.Mutex+ localLocks map[uuid.UUID]*localWorkspaceLock+ // slots bounds connections pinned across Cloud calls so capacity traffic+ // cannot consume the primary pool. New callers wait here without a DB+ // connection, using at most one quarter of the pool and never more than 4.+ slots chan struct{}+}++type localWorkspaceLock struct {+ gate chan struct{}+ refs int+}++func NewWorkspaceLocker(pool *pgxpool.Pool) WorkspaceLocker {+ if pool == nil {+ return nil+ }+ slotCount := int(pool.Config().MaxConns / workspaceLockPoolFraction)+ if slotCount < 1 {+ slotCount = 1+ }+ if slotCount > maxWorkspaceLockConnections {+ slotCount = maxWorkspaceLockConnections+ }+ return &postgresWorkspaceLocker{+ pool: pool,+ localLocks: make(map[uuid.UUID]*localWorkspaceLock),+ slots: make(chan struct{}, slotCount),+ }+}++func (l *postgresWorkspaceLocker) Lock(ctx context.Context, workspaceID uuid.UUID) (db.DBTX, func(), error) {+ releaseLocal, err := l.acquireLocal(ctx, workspaceID)+ if err != nil {+ return nil, nil, fmt.Errorf("queue workspace capacity lock: %w", err)+ }+ select {+ case l.slots <- struct{}{}:+ case <-ctx.Done():+ releaseLocal()+ return nil, nil, fmt.Errorf("queue workspace capacity lock connection: %w", ctx.Err())+ }+ acquired := false+ defer func() {+ if !acquired {+ <-l.slots+ releaseLocal()+ }+ }()++ key := workspaceAdvisoryLockKey(workspaceID)+ var conn *pgxpool.Conn+ for {+ conn, err = l.pool.Acquire(ctx)+ if err != nil {+ return nil, nil, fmt.Errorf("acquire workspace capacity lock connection: %w", err)+ }+ var locked bool+ if err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, key).Scan(&locked); err != nil {+ conn.Release()+ return nil, nil, fmt.Errorf("try workspace capacity lock: %w", err)+ }+ if locked {+ break+ }+ conn.Release()+ conn = nil+ timer := time.NewTimer(workspaceLockPollInterval)+ select {+ case <-ctx.Done():+ if !timer.Stop() {+ <-timer.C+ }+ return nil, nil, fmt.Errorf("wait for workspace capacity lock: %w", ctx.Err())+ case <-timer.C:+ }+ }+ acquired = true+ var once sync.Once+ return conn, func() {+ once.Do(func() {+ defer releaseLocal()+ defer func() { <-l.slots }()+ timer := time.NewTimer(defaultWorkspaceCooldown)+ <-timer.C+ unlockCtx, cancel := context.WithTimeout(context.Background(), workspaceLockReleaseTimeout)+ defer cancel()+ var unlocked bool+ err := conn.QueryRow(unlockCtx, `SELECT pg_advisory_unlock($1)`, key).Scan(&unlocked)+ if err != nil || !unlocked {+ // A session-level lock must never return to the pool if explicit+ // unlock failed. Closing the hijacked connection releases it in+ // PostgreSQL and keeps the next pool borrower isolated.+ _ = conn.Hijack().Close(unlockCtx)+ return+ }+ conn.Release()+ })+ }, nil+}++// acquireLocal makes same-process callers wait in Go instead of each pinning+// one pool connection while another request owns the workspace lock. One+// caller per process polls PostgreSQL so locks remain coordinated across pods.+func (l *postgresWorkspaceLocker) acquireLocal(ctx context.Context, workspaceID uuid.UUID) (func(), error) {+ l.mu.Lock()+ local := l.localLocks[workspaceID]+ if local == nil {+ local = &localWorkspaceLock{gate: make(chan struct{}, 1)}+ local.gate <- struct{}{}+ l.localLocks[workspaceID] = local+ }+ local.refs+++ l.mu.Unlock()++ select {+ case <-ctx.Done():+ l.dropLocalRef(workspaceID, local)+ return nil, ctx.Err()+ case <-local.gate:+ if err := ctx.Err(); err != nil {+ local.gate <- struct{}{}+ l.dropLocalRef(workspaceID, local)+ return nil, err+ }+ }++ var once sync.Once+ return func() {+ once.Do(func() {+ local.gate <- struct{}{}+ l.dropLocalRef(workspaceID, local)+ })+ }, nil+}++func (l *postgresWorkspaceLocker) dropLocalRef(workspaceID uuid.UUID, local *localWorkspaceLock) {+ l.mu.Lock()+ defer l.mu.Unlock()+ local.refs--+ if local.refs == 0 && l.localLocks[workspaceID] == local {+ delete(l.localLocks, workspaceID)+ }+}++func workspaceAdvisoryLockKey(workspaceID uuid.UUID) int64 {+ sum := sha256.Sum256(append([]byte("multica-seat-capacity:"), workspaceID[:]...))+ return int64(binary.BigEndian.Uint64(sum[:8]))+}diff --git a/server/internal/seatcapacity/workspace_locker_test.go b/server/internal/seatcapacity/workspace_locker_test.gonew file mode 100644index 0000000000..b83cf2aaa9--- /dev/null+++ b/server/internal/seatcapacity/workspace_locker_test.go@@ -0,0 +1,18 @@+package seatcapacity++import (+ "testing"++ "github.com/google/uuid"+)++func TestWorkspaceAdvisoryLockKeyIsStableAndWorkspaceScoped(t *testing.T) {+ workspaceA := uuid.MustParse("0193f876-4f3a-7d9c-8d8e-cb944847a001")+ workspaceB := uuid.MustParse("0193f876-4f3a-7d9c-8d8e-cb944847a002")+ if workspaceAdvisoryLockKey(workspaceA) != workspaceAdvisoryLockKey(workspaceA) {+ t.Fatal("workspace advisory lock key is not stable")+ }+ if workspaceAdvisoryLockKey(workspaceA) == workspaceAdvisoryLockKey(workspaceB) {+ t.Fatal("different workspaces share an advisory lock key")+ }+}diff --git a/server/migrations/415_seat_capacity_outbox.down.sql b/server/migrations/415_seat_capacity_outbox.down.sqlnew file mode 100644index 0000000000..416c1be983--- /dev/null+++ b/server/migrations/415_seat_capacity_outbox.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS seat_capacity_outbox;diff --git a/server/migrations/415_seat_capacity_outbox.up.sql b/server/migrations/415_seat_capacity_outbox.up.sqlnew file mode 100644index 0000000000..b581d236b0--- /dev/null+++ b/server/migrations/415_seat_capacity_outbox.up.sql@@ -0,0 +1,34 @@+-- Product-side durable intents for Cloud's pre-purchased seat protocol. This+-- table contains no commercial limits; it only records cross-service writes+-- until their idempotent Cloud operation is settled.+CREATE TABLE seat_capacity_outbox (+ workspace_id UUID NOT NULL,+ operation_token UUID NOT NULL,+ action TEXT NOT NULL CHECK (action IN (+ 'reserve_invitation',+ 'consume_invitation',+ 'claim_share_join',+ 'confirm',+ 'release',+ 'release_member'+ )),+ subject_id UUID,+ member_id UUID,+ invitation_id UUID,+ share_link_id UUID,+ user_id UUID,+ expires_at TIMESTAMPTZ,+ delivered_at TIMESTAMPTZ,+ attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ lease_token UUID,+ last_error TEXT,+ dead_lettered_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CHECK ((action <> 'reserve_invitation') OR (invitation_id IS NOT NULL AND expires_at IS NOT NULL)),+ CHECK ((action <> 'consume_invitation') OR (invitation_id IS NOT NULL AND user_id IS NOT NULL)),+ CHECK ((action <> 'claim_share_join') OR (share_link_id IS NOT NULL AND user_id IS NOT NULL)),+ CHECK ((action <> 'confirm') OR member_id IS NOT NULL),+ CHECK ((action <> 'release_member') OR member_id IS NOT NULL)+);diff --git a/server/migrations/416_seat_capacity_operation_token_index.down.sql b/server/migrations/416_seat_capacity_operation_token_index.down.sqlnew file mode 100644index 0000000000..f623058691--- /dev/null+++ b/server/migrations/416_seat_capacity_operation_token_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_seat_capacity_outbox_operation_token;diff --git a/server/migrations/416_seat_capacity_operation_token_index.up.sql b/server/migrations/416_seat_capacity_operation_token_index.up.sqlnew file mode 100644index 0000000000..721c7a79ce--- /dev/null+++ b/server/migrations/416_seat_capacity_operation_token_index.up.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX CONCURRENTLY idx_seat_capacity_outbox_operation_token+ ON seat_capacity_outbox(operation_token);diff --git a/server/migrations/417_seat_capacity_primary_key.down.sql b/server/migrations/417_seat_capacity_primary_key.down.sqlnew file mode 100644index 0000000000..146bd2c642--- /dev/null+++ b/server/migrations/417_seat_capacity_primary_key.down.sql@@ -0,0 +1,2 @@+ALTER TABLE seat_capacity_outbox+ DROP CONSTRAINT IF EXISTS seat_capacity_outbox_pkey;diff --git a/server/migrations/417_seat_capacity_primary_key.up.sql b/server/migrations/417_seat_capacity_primary_key.up.sqlnew file mode 100644index 0000000000..c3c21ba84e--- /dev/null+++ b/server/migrations/417_seat_capacity_primary_key.up.sql@@ -0,0 +1,3 @@+ALTER TABLE seat_capacity_outbox+ ADD CONSTRAINT seat_capacity_outbox_pkey+ PRIMARY KEY USING INDEX idx_seat_capacity_outbox_operation_token;diff --git a/server/migrations/418_seat_capacity_due_index.down.sql b/server/migrations/418_seat_capacity_due_index.down.sqlnew file mode 100644index 0000000000..221e776fc2--- /dev/null+++ b/server/migrations/418_seat_capacity_due_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_seat_capacity_outbox_due;diff --git a/server/migrations/418_seat_capacity_due_index.up.sql b/server/migrations/418_seat_capacity_due_index.up.sqlnew file mode 100644index 0000000000..8577793b5a--- /dev/null+++ b/server/migrations/418_seat_capacity_due_index.up.sql@@ -0,0 +1,3 @@+CREATE INDEX CONCURRENTLY idx_seat_capacity_outbox_due+ ON seat_capacity_outbox(next_attempt_at, created_at)+ WHERE dead_lettered_at IS NULL;diff --git a/server/migrations/419_seat_capacity_share_join_index.down.sql b/server/migrations/419_seat_capacity_share_join_index.down.sqlnew file mode 100644index 0000000000..be25f7d95f--- /dev/null+++ b/server/migrations/419_seat_capacity_share_join_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_seat_capacity_outbox_share_join;diff --git a/server/migrations/419_seat_capacity_share_join_index.up.sql b/server/migrations/419_seat_capacity_share_join_index.up.sqlnew file mode 100644index 0000000000..6612e5f28f--- /dev/null+++ b/server/migrations/419_seat_capacity_share_join_index.up.sql@@ -0,0 +1,5 @@+-- One user joining through one share link must keep one Cloud operation until+-- that operation is settled, including while it is dead-lettered or releasing.+CREATE UNIQUE INDEX CONCURRENTLY idx_seat_capacity_outbox_share_join+ ON seat_capacity_outbox(workspace_id, share_link_id, user_id)+ WHERE share_link_id IS NOT NULL AND user_id IS NOT NULL;diff --git a/server/pkg/db/generated/invitation.sql.go b/server/pkg/db/generated/invitation.sql.goindex e4b745bbe1..31f9b5dbd3 100644--- a/server/pkg/db/generated/invitation.sql.go+++ b/server/pkg/db/generated/invitation.sql.go@@ -37,26 +37,30 @@ func (q *Queries) AcceptInvitation(ctx context.Context, id pgtype.UUID) (Workspa}const createInvitation = `-- name: CreateInvitation :one-INSERT INTO workspace_invitation (workspace_id, inviter_id, invitee_email, invitee_user_id, role)-VALUES ($1, $2, $3, $4, $5)+INSERT INTO workspace_invitation (id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, expires_at)+VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at`type CreateInvitationParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- InviterID pgtype.UUID `json:"inviter_id"`- InviteeEmail string `json:"invitee_email"`- InviteeUserID pgtype.UUID `json:"invitee_user_id"`- Role string `json:"role"`+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InviterID pgtype.UUID `json:"inviter_id"`+ InviteeEmail string `json:"invitee_email"`+ InviteeUserID pgtype.UUID `json:"invitee_user_id"`+ Role string `json:"role"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`}func (q *Queries) CreateInvitation(ctx context.Context, arg CreateInvitationParams) (WorkspaceInvitation, error) {row := q.db.QueryRow(ctx, createInvitation,+ arg.ID,arg.WorkspaceID,arg.InviterID,arg.InviteeEmail,arg.InviteeUserID,arg.Role,+ arg.ExpiresAt,)var i WorkspaceInvitationerr := row.Scan(@@ -99,13 +103,14 @@ func (q *Queries) DeclineInvitation(ctx context.Context, id pgtype.UUID) (Workspreturn i, err}-const expireStalePendingInvitations = `-- name: ExpireStalePendingInvitations :exec+const expireStalePendingInvitations = `-- name: ExpireStalePendingInvitations :manyUPDATE workspace_invitationSET status = 'expired', updated_at = now()WHERE workspace_id = $1AND invitee_email = $2AND status = 'pending'AND expires_at <= now()+RETURNING id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, status, created_at, updated_at, expires_at`type ExpireStalePendingInvitationsParams struct {@@ -117,9 +122,35 @@ type ExpireStalePendingInvitationsParams struct {// so the next CreateInvitation does not collide with the partial unique index// idx_invitation_unique_pending (which is WHERE status = 'pending' and cannot// itself reference now() in its predicate).-func (q *Queries) ExpireStalePendingInvitations(ctx context.Context, arg ExpireStalePendingInvitationsParams) error {- _, err := q.db.Exec(ctx, expireStalePendingInvitations, arg.WorkspaceID, arg.InviteeEmail)- return err+func (q *Queries) ExpireStalePendingInvitations(ctx context.Context, arg ExpireStalePendingInvitationsParams) ([]WorkspaceInvitation, error) {+ rows, err := q.db.Query(ctx, expireStalePendingInvitations, arg.WorkspaceID, arg.InviteeEmail)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []WorkspaceInvitation{}+ for rows.Next() {+ var i WorkspaceInvitation+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.InviterID,+ &i.InviteeEmail,+ &i.InviteeUserID,+ &i.Role,+ &i.Status,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.ExpiresAt,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil}const getInvitation = `-- name: GetInvitation :one@@ -300,12 +331,15 @@ func (q *Queries) ListPendingInvitationsForUser(ctx context.Context, arg ListPenreturn items, nil}-const revokeInvitation = `-- name: RevokeInvitation :exec+const revokeInvitation = `-- name: RevokeInvitation :execrowsDELETE FROM workspace_invitationWHERE id = $1 AND status = 'pending'`-func (q *Queries) RevokeInvitation(ctx context.Context, id pgtype.UUID) error {- _, err := q.db.Exec(ctx, revokeInvitation, id)- return err+func (q *Queries) RevokeInvitation(ctx context.Context, id pgtype.UUID) (int64, error) {+ result, err := q.db.Exec(ctx, revokeInvitation, id)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 6ecf0645cc..1f140a4fbf 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -1174,6 +1174,26 @@ type RuntimeProfile struct {UpdatedAt pgtype.Timestamptz `json:"updated_at"`}+type SeatCapacityOutbox struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ SubjectID pgtype.UUID `json:"subject_id"`+ MemberID pgtype.UUID `json:"member_id"`+ InvitationID pgtype.UUID `json:"invitation_id"`+ ShareLinkID pgtype.UUID `json:"share_link_id"`+ UserID pgtype.UUID `json:"user_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ DeliveredAt pgtype.Timestamptz `json:"delivered_at"`+ AttemptCount int32 `json:"attempt_count"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+ LeaseToken pgtype.UUID `json:"lease_token"`+ LastError pgtype.Text `json:"last_error"`+ DeadLetteredAt pgtype.Timestamptz `json:"dead_lettered_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`+}+type Skill struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`diff --git a/server/pkg/db/generated/seat_capacity.sql.go b/server/pkg/db/generated/seat_capacity.sql.gonew file mode 100644index 0000000000..6f59e5d915--- /dev/null+++ b/server/pkg/db/generated/seat_capacity.sql.go@@ -0,0 +1,749 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: seat_capacity.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const claimNextDueSeatCapacityIntent = `-- name: ClaimNextDueSeatCapacityIntent :one+WITH due AS (+ SELECT operation_token+ FROM seat_capacity_outbox+ WHERE dead_lettered_at IS NULL+ AND next_attempt_at <= now()+ ORDER BY next_attempt_at, created_at+ FOR UPDATE SKIP LOCKED+ LIMIT 1+)+UPDATE seat_capacity_outbox AS outbox+SET next_attempt_at = $1,+ lease_token = gen_random_uuid(),+ updated_at = now()+FROM due+WHERE outbox.operation_token = due.operation_token+RETURNING outbox.workspace_id, outbox.operation_token, outbox.action, outbox.subject_id, outbox.member_id, outbox.invitation_id, outbox.share_link_id, outbox.user_id, outbox.expires_at, outbox.delivered_at, outbox.attempt_count, outbox.next_attempt_at, outbox.lease_token, outbox.last_error, outbox.dead_lettered_at, outbox.created_at, outbox.updated_at+`++func (q *Queries) ClaimNextDueSeatCapacityIntent(ctx context.Context, leaseUntil pgtype.Timestamptz) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, claimNextDueSeatCapacityIntent, leaseUntil)+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const createOrReactivateShareJoinCapacityIntent = `-- name: CreateOrReactivateShareJoinCapacityIntent :one+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, share_link_id, user_id,+ next_attempt_at+) VALUES (+ $1, $2, 'claim_share_join',+ $2, $3, $4,+ $5+)+ON CONFLICT (workspace_id, share_link_id, user_id)+WHERE share_link_id IS NOT NULL AND user_id IS NOT NULL+DO UPDATE SET+ action = 'claim_share_join',+ subject_id = seat_capacity_outbox.operation_token,+ member_id = NULL,+ invitation_id = NULL,+ expires_at = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = EXCLUDED.next_attempt_at,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action IN ('claim_share_join', 'release')+RETURNING workspace_id, operation_token, action, subject_id, member_id, invitation_id, share_link_id, user_id, expires_at, delivered_at, attempt_count, next_attempt_at, lease_token, last_error, dead_lettered_at, created_at, updated_at+`++type CreateOrReactivateShareJoinCapacityIntentParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OperationToken pgtype.UUID `json:"operation_token"`+ ShareLinkID pgtype.UUID `json:"share_link_id"`+ UserID pgtype.UUID `json:"user_id"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+}++func (q *Queries) CreateOrReactivateShareJoinCapacityIntent(ctx context.Context, arg CreateOrReactivateShareJoinCapacityIntentParams) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, createOrReactivateShareJoinCapacityIntent,+ arg.WorkspaceID,+ arg.OperationToken,+ arg.ShareLinkID,+ arg.UserID,+ arg.NextAttemptAt,+ )+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const deleteClaimedSeatCapacityIntent = `-- name: DeleteClaimedSeatCapacityIntent :execrows+DELETE FROM seat_capacity_outbox+WHERE operation_token = $1+ AND action = $2+ AND lease_token = $3+`++type DeleteClaimedSeatCapacityIntentParams struct {+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ LeaseToken pgtype.UUID `json:"lease_token"`+}++func (q *Queries) DeleteClaimedSeatCapacityIntent(ctx context.Context, arg DeleteClaimedSeatCapacityIntentParams) (int64, error) {+ result, err := q.db.Exec(ctx, deleteClaimedSeatCapacityIntent, arg.OperationToken, arg.Action, arg.LeaseToken)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const deleteSeatCapacityConfirmIntentsForWorkspaceDeletion = `-- name: DeleteSeatCapacityConfirmIntentsForWorkspaceDeletion :exec+DELETE FROM seat_capacity_outbox+WHERE workspace_id = $1+ AND action = 'confirm'+`++// Confirmed seats are released only through the member-scoped operation below.+// Never rewrite them to token release: Cloud may accept token release for a+// used operation, which would let a stale confirm bypass member ownership.+func (q *Queries) DeleteSeatCapacityConfirmIntentsForWorkspaceDeletion(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteSeatCapacityConfirmIntentsForWorkspaceDeletion, workspaceID)+ return err+}++const deleteSeatCapacityIntentForAction = `-- name: DeleteSeatCapacityIntentForAction :exec+DELETE FROM seat_capacity_outbox+WHERE operation_token = $1 AND action = $2+`++type DeleteSeatCapacityIntentForActionParams struct {+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+}++func (q *Queries) DeleteSeatCapacityIntentForAction(ctx context.Context, arg DeleteSeatCapacityIntentForActionParams) error {+ _, err := q.db.Exec(ctx, deleteSeatCapacityIntentForAction, arg.OperationToken, arg.Action)+ return err+}++const enqueueSeatCapacityRelease = `-- name: EnqueueSeatCapacityRelease :one+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, next_attempt_at+) VALUES (+ $1, $2, 'release',+ $3, $4+)+ON CONFLICT (operation_token) DO UPDATE SET+ action = 'release',+ subject_id = EXCLUDED.subject_id,+ member_id = NULL,+ invitation_id = NULL,+ share_link_id = NULL,+ user_id = NULL,+ expires_at = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = EXCLUDED.next_attempt_at,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action IN (+ 'reserve_invitation', 'consume_invitation', 'claim_share_join', 'release'+)+RETURNING workspace_id, operation_token, action, subject_id, member_id, invitation_id, share_link_id, user_id, expires_at, delivered_at, attempt_count, next_attempt_at, lease_token, last_error, dead_lettered_at, created_at, updated_at+`++type EnqueueSeatCapacityReleaseParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OperationToken pgtype.UUID `json:"operation_token"`+ SubjectID pgtype.UUID `json:"subject_id"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+}++func (q *Queries) EnqueueSeatCapacityRelease(ctx context.Context, arg EnqueueSeatCapacityReleaseParams) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, enqueueSeatCapacityRelease,+ arg.WorkspaceID,+ arg.OperationToken,+ arg.SubjectID,+ arg.NextAttemptAt,+ )+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const expireInvitationForCapacityRecovery = `-- name: ExpireInvitationForCapacityRecovery :exec+UPDATE workspace_invitation+SET status = 'expired', updated_at = now()+WHERE id = $1 AND status = 'pending'+`++func (q *Queries) ExpireInvitationForCapacityRecovery(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, expireInvitationForCapacityRecovery, id)+ return err+}++const getClaimedSeatCapacityIntent = `-- name: GetClaimedSeatCapacityIntent :one+SELECT workspace_id, operation_token, action, subject_id, member_id, invitation_id, share_link_id, user_id, expires_at, delivered_at, attempt_count, next_attempt_at, lease_token, last_error, dead_lettered_at, created_at, updated_at FROM seat_capacity_outbox+WHERE operation_token = $1+ AND action = $2+ AND lease_token = $3+`++type GetClaimedSeatCapacityIntentParams struct {+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ LeaseToken pgtype.UUID `json:"lease_token"`+}++func (q *Queries) GetClaimedSeatCapacityIntent(ctx context.Context, arg GetClaimedSeatCapacityIntentParams) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, getClaimedSeatCapacityIntent, arg.OperationToken, arg.Action, arg.LeaseToken)+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getMemberReleaseCapacityIntent = `-- name: GetMemberReleaseCapacityIntent :one+SELECT workspace_id, operation_token, action, subject_id, member_id, invitation_id, share_link_id, user_id, expires_at, delivered_at, attempt_count, next_attempt_at, lease_token, last_error, dead_lettered_at, created_at, updated_at FROM seat_capacity_outbox+WHERE workspace_id = $1+ AND member_id = $2+ AND action = 'release_member'+ORDER BY created_at DESC+LIMIT 1+`++type GetMemberReleaseCapacityIntentParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ MemberID pgtype.UUID `json:"member_id"`+}++func (q *Queries) GetMemberReleaseCapacityIntent(ctx context.Context, arg GetMemberReleaseCapacityIntentParams) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, getMemberReleaseCapacityIntent, arg.WorkspaceID, arg.MemberID)+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const getSeatCapacityIntent = `-- name: GetSeatCapacityIntent :one+SELECT workspace_id, operation_token, action, subject_id, member_id, invitation_id, share_link_id, user_id, expires_at, delivered_at, attempt_count, next_attempt_at, lease_token, last_error, dead_lettered_at, created_at, updated_at FROM seat_capacity_outbox WHERE operation_token = $1+`++func (q *Queries) GetSeatCapacityIntent(ctx context.Context, operationToken pgtype.UUID) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, getSeatCapacityIntent, operationToken)+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}++const markClaimedSeatCapacityIntentDeadLettered = `-- name: MarkClaimedSeatCapacityIntentDeadLettered :execrows+UPDATE seat_capacity_outbox+SET attempt_count = attempt_count + 1,+ last_error = left($1, 1000),+ dead_lettered_at = now(),+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = $2+ AND action = $3+ AND lease_token = $4+ AND dead_lettered_at IS NULL+`++type MarkClaimedSeatCapacityIntentDeadLetteredParams struct {+ LastError string `json:"last_error"`+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ LeaseToken pgtype.UUID `json:"lease_token"`+}++func (q *Queries) MarkClaimedSeatCapacityIntentDeadLettered(ctx context.Context, arg MarkClaimedSeatCapacityIntentDeadLetteredParams) (int64, error) {+ result, err := q.db.Exec(ctx, markClaimedSeatCapacityIntentDeadLettered,+ arg.LastError,+ arg.OperationToken,+ arg.Action,+ arg.LeaseToken,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const markClaimedSeatCapacityIntentFailed = `-- name: MarkClaimedSeatCapacityIntentFailed :execrows+UPDATE seat_capacity_outbox+SET attempt_count = attempt_count + 1,+ last_error = left($1, 1000),+ next_attempt_at = $2,+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = $3+ AND action = $4+ AND lease_token = $5+`++type MarkClaimedSeatCapacityIntentFailedParams struct {+ LastError string `json:"last_error"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ LeaseToken pgtype.UUID `json:"lease_token"`+}++func (q *Queries) MarkClaimedSeatCapacityIntentFailed(ctx context.Context, arg MarkClaimedSeatCapacityIntentFailedParams) (int64, error) {+ result, err := q.db.Exec(ctx, markClaimedSeatCapacityIntentFailed,+ arg.LastError,+ arg.NextAttemptAt,+ arg.OperationToken,+ arg.Action,+ arg.LeaseToken,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const markSeatCapacityIntentDelivered = `-- name: MarkSeatCapacityIntentDelivered :exec+UPDATE seat_capacity_outbox+SET delivered_at = now(),+ attempt_count = attempt_count + 1,+ lease_token = NULL,+ last_error = NULL,+ updated_at = now()+WHERE operation_token = $1 AND action = $2+`++type MarkSeatCapacityIntentDeliveredParams struct {+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+}++func (q *Queries) MarkSeatCapacityIntentDelivered(ctx context.Context, arg MarkSeatCapacityIntentDeliveredParams) error {+ _, err := q.db.Exec(ctx, markSeatCapacityIntentDelivered, arg.OperationToken, arg.Action)+ return err+}++const markSeatCapacityIntentFailed = `-- name: MarkSeatCapacityIntentFailed :exec+UPDATE seat_capacity_outbox+SET attempt_count = attempt_count + 1,+ last_error = left($1, 1000),+ next_attempt_at = $2,+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = $3 AND action = $4+`++type MarkSeatCapacityIntentFailedParams struct {+ LastError string `json:"last_error"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+}++func (q *Queries) MarkSeatCapacityIntentFailed(ctx context.Context, arg MarkSeatCapacityIntentFailedParams) error {+ _, err := q.db.Exec(ctx, markSeatCapacityIntentFailed,+ arg.LastError,+ arg.NextAttemptAt,+ arg.OperationToken,+ arg.Action,+ )+ return err+}++const prepareSeatCapacityInvitationReleasesForWorkspaceDeletion = `-- name: PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion :exec+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, invitation_id,+ next_attempt_at+)+SELECT invitation.workspace_id, invitation.id, 'release', invitation.id, invitation.id, now()+FROM workspace_invitation AS invitation+WHERE invitation.workspace_id = $1+ AND invitation.status = 'pending'+ON CONFLICT (operation_token) DO UPDATE SET+ action = 'release',+ member_id = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = now(),+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action IN (+ 'reserve_invitation', 'consume_invitation', 'claim_share_join', 'release'+)+`++func (q *Queries) PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, prepareSeatCapacityInvitationReleasesForWorkspaceDeletion, workspaceID)+ return err+}++const prepareSeatCapacityMemberReleasesForWorkspaceDeletion = `-- name: PrepareSeatCapacityMemberReleasesForWorkspaceDeletion :exec+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, member_id, next_attempt_at+)+SELECT m.workspace_id, gen_random_uuid(), 'release_member', m.id, now()+FROM member AS m+WHERE m.workspace_id = $1+ AND NOT EXISTS (+ SELECT 1+ FROM seat_capacity_outbox AS existing+ WHERE existing.workspace_id = m.workspace_id+ AND existing.member_id = m.id+ AND existing.action = 'release_member'+ )+`++func (q *Queries) PrepareSeatCapacityMemberReleasesForWorkspaceDeletion(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, prepareSeatCapacityMemberReleasesForWorkspaceDeletion, workspaceID)+ return err+}++const prepareSeatCapacityOperationReleasesForWorkspaceDeletion = `-- name: PrepareSeatCapacityOperationReleasesForWorkspaceDeletion :exec+UPDATE seat_capacity_outbox+SET action = 'release',+ member_id = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = now(),+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE workspace_id = $1+ AND action NOT IN ('confirm', 'release_member')+`++// Workspace teardown commits these compensations atomically with removal of+// the product rows. The FK-free outbox intentionally survives so Cloud can be+// reconciled after the local workspace no longer exists.+func (q *Queries) PrepareSeatCapacityOperationReleasesForWorkspaceDeletion(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, prepareSeatCapacityOperationReleasesForWorkspaceDeletion, workspaceID)+ return err+}++const seatCapacityOutboxStats = `-- name: SeatCapacityOutboxStats :many+SELECT action,+ count(*) FILTER (WHERE dead_lettered_at IS NULL)::bigint AS pending_count,+ count(*) FILTER (WHERE dead_lettered_at IS NOT NULL)::bigint AS dead_lettered_count,+ COALESCE(+ EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE dead_lettered_at IS NULL)),+ 0+ )::double precision AS oldest_pending_age_seconds+FROM seat_capacity_outbox+GROUP BY action+`++type SeatCapacityOutboxStatsRow struct {+ Action string `json:"action"`+ PendingCount int64 `json:"pending_count"`+ DeadLetteredCount int64 `json:"dead_lettered_count"`+ OldestPendingAgeSeconds float64 `json:"oldest_pending_age_seconds"`+}++func (q *Queries) SeatCapacityOutboxStats(ctx context.Context) ([]SeatCapacityOutboxStatsRow, error) {+ rows, err := q.db.Query(ctx, seatCapacityOutboxStats)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []SeatCapacityOutboxStatsRow{}+ for rows.Next() {+ var i SeatCapacityOutboxStatsRow+ if err := rows.Scan(+ &i.Action,+ &i.PendingCount,+ &i.DeadLetteredCount,+ &i.OldestPendingAgeSeconds,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const transitionClaimedSeatCapacityIntent = `-- name: TransitionClaimedSeatCapacityIntent :execrows+UPDATE seat_capacity_outbox+SET action = $1,+ member_id = $2,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = $3,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE operation_token = $4+ AND action = $5+ AND lease_token = $6+`++type TransitionClaimedSeatCapacityIntentParams struct {+ NextAction string `json:"next_action"`+ MemberID pgtype.UUID `json:"member_id"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+ OperationToken pgtype.UUID `json:"operation_token"`+ CurrentAction string `json:"current_action"`+ LeaseToken pgtype.UUID `json:"lease_token"`+}++func (q *Queries) TransitionClaimedSeatCapacityIntent(ctx context.Context, arg TransitionClaimedSeatCapacityIntentParams) (int64, error) {+ result, err := q.db.Exec(ctx, transitionClaimedSeatCapacityIntent,+ arg.NextAction,+ arg.MemberID,+ arg.NextAttemptAt,+ arg.OperationToken,+ arg.CurrentAction,+ arg.LeaseToken,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const transitionSeatCapacityIntent = `-- name: TransitionSeatCapacityIntent :execrows+UPDATE seat_capacity_outbox+SET action = $1,+ member_id = $2,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = $3,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE operation_token = $4+ AND action = $5+`++type TransitionSeatCapacityIntentParams struct {+ NextAction string `json:"next_action"`+ MemberID pgtype.UUID `json:"member_id"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+ OperationToken pgtype.UUID `json:"operation_token"`+ CurrentAction string `json:"current_action"`+}++func (q *Queries) TransitionSeatCapacityIntent(ctx context.Context, arg TransitionSeatCapacityIntentParams) (int64, error) {+ result, err := q.db.Exec(ctx, transitionSeatCapacityIntent,+ arg.NextAction,+ arg.MemberID,+ arg.NextAttemptAt,+ arg.OperationToken,+ arg.CurrentAction,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}++const upsertSeatCapacityIntent = `-- name: UpsertSeatCapacityIntent :one+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, member_id,+ invitation_id, share_link_id, user_id, expires_at, next_attempt_at+) VALUES (+ $1, $2, $3,+ $4, $5, $6,+ $7, $8, $9,+ $10+)+ON CONFLICT (operation_token) DO UPDATE SET+ action = EXCLUDED.action,+ subject_id = EXCLUDED.subject_id,+ member_id = EXCLUDED.member_id,+ invitation_id = EXCLUDED.invitation_id,+ share_link_id = EXCLUDED.share_link_id,+ user_id = EXCLUDED.user_id,+ expires_at = EXCLUDED.expires_at,+ attempt_count = CASE+ WHEN seat_capacity_outbox.dead_lettered_at IS NOT NULL THEN 0+ WHEN seat_capacity_outbox.action <> EXCLUDED.action THEN 0+ ELSE seat_capacity_outbox.attempt_count+ END,+ delivered_at = CASE+ WHEN seat_capacity_outbox.action = EXCLUDED.action THEN seat_capacity_outbox.delivered_at+ ELSE NULL+ END,+ next_attempt_at = EXCLUDED.next_attempt_at,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action = EXCLUDED.action+ OR (seat_capacity_outbox.action = 'reserve_invitation' AND EXCLUDED.action = 'consume_invitation')+RETURNING workspace_id, operation_token, action, subject_id, member_id, invitation_id, share_link_id, user_id, expires_at, delivered_at, attempt_count, next_attempt_at, lease_token, last_error, dead_lettered_at, created_at, updated_at+`++type UpsertSeatCapacityIntentParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ OperationToken pgtype.UUID `json:"operation_token"`+ Action string `json:"action"`+ SubjectID pgtype.UUID `json:"subject_id"`+ MemberID pgtype.UUID `json:"member_id"`+ InvitationID pgtype.UUID `json:"invitation_id"`+ ShareLinkID pgtype.UUID `json:"share_link_id"`+ UserID pgtype.UUID `json:"user_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`+}++func (q *Queries) UpsertSeatCapacityIntent(ctx context.Context, arg UpsertSeatCapacityIntentParams) (SeatCapacityOutbox, error) {+ row := q.db.QueryRow(ctx, upsertSeatCapacityIntent,+ arg.WorkspaceID,+ arg.OperationToken,+ arg.Action,+ arg.SubjectID,+ arg.MemberID,+ arg.InvitationID,+ arg.ShareLinkID,+ arg.UserID,+ arg.ExpiresAt,+ arg.NextAttemptAt,+ )+ var i SeatCapacityOutbox+ err := row.Scan(+ &i.WorkspaceID,+ &i.OperationToken,+ &i.Action,+ &i.SubjectID,+ &i.MemberID,+ &i.InvitationID,+ &i.ShareLinkID,+ &i.UserID,+ &i.ExpiresAt,+ &i.DeliveredAt,+ &i.AttemptCount,+ &i.NextAttemptAt,+ &i.LeaseToken,+ &i.LastError,+ &i.DeadLetteredAt,+ &i.CreatedAt,+ &i.UpdatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/generated/share_link.sql.go b/server/pkg/db/generated/share_link.sql.goindex 029f56dbeb..f798417bb4 100644--- a/server/pkg/db/generated/share_link.sql.go+++ b/server/pkg/db/generated/share_link.sql.go@@ -11,23 +11,21 @@ import ("github.com/jackc/pgx/v5/pgtype")-const claimShareLinkByCode = `-- name: ClaimShareLinkByCode :one+const claimShareLinkByID = `-- name: ClaimShareLinkByID :oneUPDATE workspace_share_linkSET use_count = use_count + 1-WHERE code = $1+WHERE id = $1AND is_active = trueAND (expires_at IS NULL OR expires_at > now())AND (max_uses IS NULL OR use_count < max_uses)RETURNING id, workspace_id, code, created_by, role, expires_at, max_uses, use_count, is_active, created_at`-// Atomically consume one use of a share link. The conditional UPDATE both-// revalidates validity (active, not expired, below max_uses) and increments-// use_count in a single statement, so concurrent joins cannot exceed max_uses-// and a join cannot slip in after the link was revoked or expired. Returns the-// row only if the link is still usable.-func (q *Queries) ClaimShareLinkByCode(ctx context.Context, code string) (WorkspaceShareLink, error) {- row := q.db.QueryRow(ctx, claimShareLinkByCode, code)+// The caller first resolves the opaque code and then atomically consumes the+// non-secret row ID. The conditional UPDATE revalidates validity and the use+// limit so a join cannot race past revocation or expiry.+func (q *Queries) ClaimShareLinkByID(ctx context.Context, id pgtype.UUID) (WorkspaceShareLink, error) {+ row := q.db.QueryRow(ctx, claimShareLinkByID, id)var i WorkspaceShareLinkerr := row.Scan(&i.ID,@@ -95,6 +93,32 @@ func (q *Queries) DeactivateWorkspaceShareLinks(ctx context.Context, workspaceIDreturn err}+const getActiveShareLinkByCode = `-- name: GetActiveShareLinkByCode :one+SELECT id, workspace_id, code, created_by, role, expires_at, max_uses, use_count, is_active, created_at FROM workspace_share_link+WHERE code = $1+ AND is_active = true+ AND (expires_at IS NULL OR expires_at > now())+ AND (max_uses IS NULL OR use_count < max_uses)+`++func (q *Queries) GetActiveShareLinkByCode(ctx context.Context, code string) (WorkspaceShareLink, error) {+ row := q.db.QueryRow(ctx, getActiveShareLinkByCode, code)+ var i WorkspaceShareLink+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Code,+ &i.CreatedBy,+ &i.Role,+ &i.ExpiresAt,+ &i.MaxUses,+ &i.UseCount,+ &i.IsActive,+ &i.CreatedAt,+ )+ return i, err+}+const getShareLinkInfoByCode = `-- name: GetShareLinkInfoByCode :oneSELECT wsl.role,w.name AS workspace_name,diff --git a/server/pkg/db/queries/invitation.sql b/server/pkg/db/queries/invitation.sqlindex 1aa2d4d783..e4672e4280 100644--- a/server/pkg/db/queries/invitation.sql+++ b/server/pkg/db/queries/invitation.sql@@ -1,6 +1,6 @@-- name: CreateInvitation :one-INSERT INTO workspace_invitation (workspace_id, inviter_id, invitee_email, invitee_user_id, role)-VALUES ($1, $2, $3, $4, $5)+INSERT INTO workspace_invitation (id, workspace_id, inviter_id, invitee_email, invitee_user_id, role, expires_at)+VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING *;-- name: GetInvitation :one@@ -41,7 +41,7 @@ SET status = 'declined', updated_at = now()WHERE id = $1 AND status = 'pending'RETURNING *;--- name: RevokeInvitation :exec+-- name: RevokeInvitation :execrowsDELETE FROM workspace_invitationWHERE id = $1 AND status = 'pending';@@ -49,7 +49,7 @@ WHERE id = $1 AND status = 'pending';SELECT * FROM workspace_invitationWHERE workspace_id = $1 AND invitee_email = $2 AND status = 'pending' AND expires_at > now();--- name: ExpireStalePendingInvitations :exec+-- name: ExpireStalePendingInvitations :many-- Mark any past-due pending invitations for (workspace_id, invitee_email) as expired,-- so the next CreateInvitation does not collide with the partial unique index-- idx_invitation_unique_pending (which is WHERE status = 'pending' and cannot@@ -59,4 +59,5 @@ SET status = 'expired', updated_at = now()WHERE workspace_id = $1AND invitee_email = $2AND status = 'pending'- AND expires_at <= now();+ AND expires_at <= now()+RETURNING *;diff --git a/server/pkg/db/queries/seat_capacity.sql b/server/pkg/db/queries/seat_capacity.sqlnew file mode 100644index 0000000000..ab80fa1e2b--- /dev/null+++ b/server/pkg/db/queries/seat_capacity.sql@@ -0,0 +1,283 @@+-- name: UpsertSeatCapacityIntent :one+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, member_id,+ invitation_id, share_link_id, user_id, expires_at, next_attempt_at+) VALUES (+ sqlc.arg('workspace_id'), sqlc.arg('operation_token'), sqlc.arg('action'),+ sqlc.narg('subject_id'), sqlc.narg('member_id'), sqlc.narg('invitation_id'),+ sqlc.narg('share_link_id'), sqlc.narg('user_id'), sqlc.narg('expires_at'),+ sqlc.arg('next_attempt_at')+)+ON CONFLICT (operation_token) DO UPDATE SET+ action = EXCLUDED.action,+ subject_id = EXCLUDED.subject_id,+ member_id = EXCLUDED.member_id,+ invitation_id = EXCLUDED.invitation_id,+ share_link_id = EXCLUDED.share_link_id,+ user_id = EXCLUDED.user_id,+ expires_at = EXCLUDED.expires_at,+ attempt_count = CASE+ WHEN seat_capacity_outbox.dead_lettered_at IS NOT NULL THEN 0+ WHEN seat_capacity_outbox.action <> EXCLUDED.action THEN 0+ ELSE seat_capacity_outbox.attempt_count+ END,+ delivered_at = CASE+ WHEN seat_capacity_outbox.action = EXCLUDED.action THEN seat_capacity_outbox.delivered_at+ ELSE NULL+ END,+ next_attempt_at = EXCLUDED.next_attempt_at,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action = EXCLUDED.action+ OR (seat_capacity_outbox.action = 'reserve_invitation' AND EXCLUDED.action = 'consume_invitation')+RETURNING *;++-- name: EnqueueSeatCapacityRelease :one+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, next_attempt_at+) VALUES (+ sqlc.arg('workspace_id'), sqlc.arg('operation_token'), 'release',+ sqlc.narg('subject_id'), sqlc.arg('next_attempt_at')+)+ON CONFLICT (operation_token) DO UPDATE SET+ action = 'release',+ subject_id = EXCLUDED.subject_id,+ member_id = NULL,+ invitation_id = NULL,+ share_link_id = NULL,+ user_id = NULL,+ expires_at = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = EXCLUDED.next_attempt_at,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action IN (+ 'reserve_invitation', 'consume_invitation', 'claim_share_join', 'release'+)+RETURNING *;++-- name: GetSeatCapacityIntent :one+SELECT * FROM seat_capacity_outbox WHERE operation_token = $1;++-- name: GetClaimedSeatCapacityIntent :one+SELECT * FROM seat_capacity_outbox+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('action')+ AND lease_token = sqlc.arg('lease_token');++-- name: CreateOrReactivateShareJoinCapacityIntent :one+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, share_link_id, user_id,+ next_attempt_at+) VALUES (+ sqlc.arg('workspace_id'), sqlc.arg('operation_token'), 'claim_share_join',+ sqlc.arg('operation_token'), sqlc.arg('share_link_id'), sqlc.arg('user_id'),+ sqlc.arg('next_attempt_at')+)+ON CONFLICT (workspace_id, share_link_id, user_id)+WHERE share_link_id IS NOT NULL AND user_id IS NOT NULL+DO UPDATE SET+ action = 'claim_share_join',+ subject_id = seat_capacity_outbox.operation_token,+ member_id = NULL,+ invitation_id = NULL,+ expires_at = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = EXCLUDED.next_attempt_at,+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action IN ('claim_share_join', 'release')+RETURNING *;++-- name: GetMemberReleaseCapacityIntent :one+SELECT * FROM seat_capacity_outbox+WHERE workspace_id = $1+ AND member_id = $2+ AND action = 'release_member'+ORDER BY created_at DESC+LIMIT 1;++-- name: DeleteSeatCapacityConfirmIntentsForWorkspaceDeletion :exec+-- Confirmed seats are released only through the member-scoped operation below.+-- Never rewrite them to token release: Cloud may accept token release for a+-- used operation, which would let a stale confirm bypass member ownership.+DELETE FROM seat_capacity_outbox+WHERE workspace_id = sqlc.arg('workspace_id')+ AND action = 'confirm';++-- name: PrepareSeatCapacityOperationReleasesForWorkspaceDeletion :exec+-- Workspace teardown commits these compensations atomically with removal of+-- the product rows. The FK-free outbox intentionally survives so Cloud can be+-- reconciled after the local workspace no longer exists.+UPDATE seat_capacity_outbox+SET action = 'release',+ member_id = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = now(),+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE workspace_id = sqlc.arg('workspace_id')+ AND action NOT IN ('confirm', 'release_member');++-- name: PrepareSeatCapacityInvitationReleasesForWorkspaceDeletion :exec+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, subject_id, invitation_id,+ next_attempt_at+)+SELECT invitation.workspace_id, invitation.id, 'release', invitation.id, invitation.id, now()+FROM workspace_invitation AS invitation+WHERE invitation.workspace_id = sqlc.arg('workspace_id')+ AND invitation.status = 'pending'+ON CONFLICT (operation_token) DO UPDATE SET+ action = 'release',+ member_id = NULL,+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = now(),+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE seat_capacity_outbox.action IN (+ 'reserve_invitation', 'consume_invitation', 'claim_share_join', 'release'+);++-- name: PrepareSeatCapacityMemberReleasesForWorkspaceDeletion :exec+INSERT INTO seat_capacity_outbox (+ workspace_id, operation_token, action, member_id, next_attempt_at+)+SELECT m.workspace_id, gen_random_uuid(), 'release_member', m.id, now()+FROM member AS m+WHERE m.workspace_id = sqlc.arg('workspace_id')+ AND NOT EXISTS (+ SELECT 1+ FROM seat_capacity_outbox AS existing+ WHERE existing.workspace_id = m.workspace_id+ AND existing.member_id = m.id+ AND existing.action = 'release_member'+ );++-- name: ClaimNextDueSeatCapacityIntent :one+WITH due AS (+ SELECT operation_token+ FROM seat_capacity_outbox+ WHERE dead_lettered_at IS NULL+ AND next_attempt_at <= now()+ ORDER BY next_attempt_at, created_at+ FOR UPDATE SKIP LOCKED+ LIMIT 1+)+UPDATE seat_capacity_outbox AS outbox+SET next_attempt_at = sqlc.arg('lease_until'),+ lease_token = gen_random_uuid(),+ updated_at = now()+FROM due+WHERE outbox.operation_token = due.operation_token+RETURNING outbox.*;++-- name: SeatCapacityOutboxStats :many+SELECT action,+ count(*) FILTER (WHERE dead_lettered_at IS NULL)::bigint AS pending_count,+ count(*) FILTER (WHERE dead_lettered_at IS NOT NULL)::bigint AS dead_lettered_count,+ COALESCE(+ EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE dead_lettered_at IS NULL)),+ 0+ )::double precision AS oldest_pending_age_seconds+FROM seat_capacity_outbox+GROUP BY action;++-- name: MarkSeatCapacityIntentDelivered :exec+UPDATE seat_capacity_outbox+SET delivered_at = now(),+ attempt_count = attempt_count + 1,+ lease_token = NULL,+ last_error = NULL,+ updated_at = now()+WHERE operation_token = $1 AND action = $2;++-- name: MarkSeatCapacityIntentFailed :exec+UPDATE seat_capacity_outbox+SET attempt_count = attempt_count + 1,+ last_error = left(sqlc.arg('last_error'), 1000),+ next_attempt_at = sqlc.arg('next_attempt_at'),+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = sqlc.arg('operation_token') AND action = sqlc.arg('action');++-- name: MarkClaimedSeatCapacityIntentDeadLettered :execrows+UPDATE seat_capacity_outbox+SET attempt_count = attempt_count + 1,+ last_error = left(sqlc.arg('last_error'), 1000),+ dead_lettered_at = now(),+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('action')+ AND lease_token = sqlc.arg('lease_token')+ AND dead_lettered_at IS NULL;++-- name: TransitionSeatCapacityIntent :execrows+UPDATE seat_capacity_outbox+SET action = sqlc.arg('next_action'),+ member_id = sqlc.narg('member_id'),+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = sqlc.arg('next_attempt_at'),+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('current_action');++-- name: TransitionClaimedSeatCapacityIntent :execrows+UPDATE seat_capacity_outbox+SET action = sqlc.arg('next_action'),+ member_id = sqlc.narg('member_id'),+ delivered_at = NULL,+ attempt_count = 0,+ next_attempt_at = sqlc.arg('next_attempt_at'),+ lease_token = NULL,+ last_error = NULL,+ dead_lettered_at = NULL,+ updated_at = now()+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('current_action')+ AND lease_token = sqlc.arg('lease_token');++-- name: MarkClaimedSeatCapacityIntentFailed :execrows+UPDATE seat_capacity_outbox+SET attempt_count = attempt_count + 1,+ last_error = left(sqlc.arg('last_error'), 1000),+ next_attempt_at = sqlc.arg('next_attempt_at'),+ lease_token = NULL,+ updated_at = now()+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('action')+ AND lease_token = sqlc.arg('lease_token');++-- name: DeleteSeatCapacityIntentForAction :exec+DELETE FROM seat_capacity_outbox+WHERE operation_token = $1 AND action = $2;++-- name: DeleteClaimedSeatCapacityIntent :execrows+DELETE FROM seat_capacity_outbox+WHERE operation_token = sqlc.arg('operation_token')+ AND action = sqlc.arg('action')+ AND lease_token = sqlc.arg('lease_token');++-- name: ExpireInvitationForCapacityRecovery :exec+UPDATE workspace_invitation+SET status = 'expired', updated_at = now()+WHERE id = $1 AND status = 'pending';diff --git a/server/pkg/db/queries/share_link.sql b/server/pkg/db/queries/share_link.sqlindex 08321625d1..7192747a28 100644--- a/server/pkg/db/queries/share_link.sql+++ b/server/pkg/db/queries/share_link.sql@@ -3,20 +3,25 @@ INSERT INTO workspace_share_link (workspace_id, code, created_by, role, expires_VALUES ($1, $2, $3, $4, $5, $6)RETURNING *;--- name: ClaimShareLinkByCode :one--- Atomically consume one use of a share link. The conditional UPDATE both--- revalidates validity (active, not expired, below max_uses) and increments--- use_count in a single statement, so concurrent joins cannot exceed max_uses--- and a join cannot slip in after the link was revoked or expired. Returns the--- row only if the link is still usable.+-- name: ClaimShareLinkByID :one+-- The caller first resolves the opaque code and then atomically consumes the+-- non-secret row ID. The conditional UPDATE revalidates validity and the use+-- limit so a join cannot race past revocation or expiry.UPDATE workspace_share_linkSET use_count = use_count + 1-WHERE code = $1+WHERE id = $1AND is_active = trueAND (expires_at IS NULL OR expires_at > now())AND (max_uses IS NULL OR use_count < max_uses)RETURNING *;+-- name: GetActiveShareLinkByCode :one+SELECT * FROM workspace_share_link+WHERE code = $1+ AND is_active = true+ AND (expires_at IS NULL OR expires_at > now())+ AND (max_uses IS NULL OR use_count < max_uses);+-- name: GetShareLinkInfoByCode :oneSELECT wsl.role,w.name AS workspace_name,