-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(webapp): per-org S2 basin migration #3516
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ericallam
wants to merge
13
commits into
main
Choose a base branch
from
feature/tri-9073-stop-s2-chat-input-streams-from-being-deleted-while-sessions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0f9d1de
feat(webapp,run-engine): per-org S2 basin migration
ericallam a1d4564
chore(webapp): server-changes file for per-org basin migration
ericallam 692a257
fix(webapp): address coderabbit review on per-org basin migration
ericallam d6d3586
refactor(webapp): drop plan vocabulary from streamBasinProvisioner
ericallam 054d1af
fix(webapp): address review on per-org basin migration
ericallam fc88017
refactor(webapp): per-org basins for paid orgs only
ericallam 97eb08e
fix(webapp): address review on per-org basin migration
ericallam 871b993
fix(webapp): early-return reconcile when per-org basins disabled
ericallam b065509
fix(webapp): row-optional session-channel routes default to org basin
ericallam f55746d
docs(webapp): clarify reconfigure admin route's default vs retention …
ericallam 684fc2e
chore(webapp): trim per-org-basin comments
ericallam 9cb611d
refactor(webapp): cloud-driven basin sync, drop reconcile worker
ericallam 4ce5998
fix(webapp): match writer basin in session-stream wait race-check
ericallam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| area: webapp | ||
| type: feature | ||
| --- | ||
|
|
||
| Per-org S2 stream basins with plan-tied retention (free 7d / hobby 30d / pro 365d), gated by `REALTIME_STREAMS_PER_ORG_BASINS_ENABLED`. Stops basin retention from deleting streams out from under live chat sessions and unlocks per-org cost attribution via S2 basin metrics. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
165 changes: 165 additions & 0 deletions
165
apps/webapp/app/routes/admin.api.v1.stream-basins.backfill.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,165 @@ | ||
| import { json, type ActionFunctionArgs } from "@remix-run/server-runtime"; | ||
| import { z } from "zod"; | ||
| import { prisma } from "~/db.server"; | ||
| import { requireAdminApiRequest } from "~/services/personalAccessToken.server"; | ||
| import { isPerOrgBasinsEnabled } from "~/services/realtime/streamBasinProvisioner.server"; | ||
| import { commonWorker } from "~/v3/commonWorker.server"; | ||
| import { logger } from "~/services/logger.server"; | ||
|
|
||
| /** | ||
| * One-shot backfill that enqueues `v3.provisionStreamBasinForOrg` for | ||
| * every org with `streamBasinName: null`. Idempotent — re-running picks | ||
| * up only the orgs that haven't been provisioned yet, and the worker | ||
| * job itself is also idempotent (the provisioner short-circuits if the | ||
| * org column is already set). | ||
| * | ||
| * - Admin auth via `requireAdminApiRequest` (PAT in `Authorization`). | ||
| * - Refuses to run when `REALTIME_STREAMS_PER_ORG_BASINS_ENABLED=false` | ||
| * so OSS / s2-lite installs can't accidentally trigger basin | ||
| * creation against a misconfigured backend. | ||
| * - `dryRun=true` (default false) returns the count without enqueueing. | ||
| * - `limit` (default 1000, max 10000) caps a single invocation. Run | ||
| * again to process more — the column filter naturally walks the | ||
| * queue forward each call. | ||
| * - Each job is keyed `provisionStreamBasin:<orgId>` so concurrent | ||
| * backfill calls converge to one job per org instead of duplicating. | ||
| * | ||
| * Run from a shell: | ||
| * curl -X POST -H "Authorization: Bearer $PAT" \ | ||
| * "https://api.trigger.dev/admin/api/v1/stream-basins/backfill?limit=200&dryRun=true" | ||
| */ | ||
|
|
||
| const BodySchema = z | ||
| .object({ | ||
| dryRun: z.boolean().optional().default(false), | ||
| limit: z.number().int().min(1).max(10_000).optional().default(1000), | ||
| }) | ||
| .strict(); | ||
|
|
||
| type BackfillResponse = { | ||
| ok: true; | ||
| dryRun: boolean; | ||
| enqueued: number; | ||
| pending: number; | ||
| remaining: number; | ||
| orgIds: string[]; | ||
| }; | ||
|
|
||
| export async function action({ request }: ActionFunctionArgs) { | ||
| await requireAdminApiRequest(request); | ||
|
|
||
| if (!isPerOrgBasinsEnabled()) { | ||
| return json( | ||
| { | ||
| ok: false, | ||
| error: | ||
| "Per-org stream basins are disabled. Set REALTIME_STREAMS_PER_ORG_BASINS_ENABLED=true before running the backfill.", | ||
| }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| // `application/json` POST body — empty body falls back to defaults so | ||
| // a parameterless POST does the right thing for the default backfill. | ||
| let parsed: z.infer<typeof BodySchema>; | ||
| try { | ||
| const text = await request.text(); | ||
| const raw = text.length > 0 ? JSON.parse(text) : {}; | ||
| const result = BodySchema.safeParse(raw); | ||
| if (!result.success) { | ||
| return json({ ok: false, error: result.error.flatten() }, { status: 400 }); | ||
| } | ||
| parsed = result.data; | ||
| } catch { | ||
| return json({ ok: false, error: "Invalid JSON body" }, { status: 400 }); | ||
| } | ||
|
|
||
| const { dryRun, limit } = parsed; | ||
|
|
||
| // Page candidate orgs. Ordered by createdAt so re-runs walk the queue | ||
| // forward predictably; deletedAt filter avoids resurrecting orgs. | ||
| const candidates = await prisma.organization.findMany({ | ||
| where: { | ||
| streamBasinName: null, | ||
| deletedAt: null, | ||
| }, | ||
| orderBy: { createdAt: "asc" }, | ||
| take: limit, | ||
| select: { id: true }, | ||
| }); | ||
|
|
||
| // Total count of remaining nulls (for progress reporting). | ||
| const remainingTotal = await prisma.organization.count({ | ||
| where: { streamBasinName: null, deletedAt: null }, | ||
| }); | ||
|
|
||
| if (dryRun) { | ||
| const response: BackfillResponse = { | ||
| ok: true, | ||
| dryRun: true, | ||
| enqueued: 0, | ||
| pending: candidates.length, | ||
| remaining: Math.max(0, remainingTotal - candidates.length), | ||
| orgIds: candidates.map((o) => o.id), | ||
| }; | ||
| return json(response); | ||
| } | ||
|
|
||
| // Enqueue one job per org. Per-org dedupe key collapses concurrent | ||
| // backfill calls into a single pending job, and a job that's already | ||
| // run (basin set) is a no-op on the worker side. | ||
| let enqueued = 0; | ||
| for (const org of candidates) { | ||
| try { | ||
| await commonWorker.enqueue({ | ||
| job: "v3.provisionStreamBasinForOrg", | ||
| payload: { orgId: org.id }, | ||
| id: `provisionStreamBasin:${org.id}`, | ||
| }); | ||
| enqueued += 1; | ||
| } catch (error) { | ||
| logger.error("[stream-basins-backfill] enqueue failed", { | ||
| orgId: org.id, | ||
| error: error instanceof Error ? error.message : String(error), | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| const response: BackfillResponse = { | ||
| ok: true, | ||
| dryRun: false, | ||
| enqueued, | ||
| pending: candidates.length, | ||
| remaining: Math.max(0, remainingTotal - enqueued), | ||
| orgIds: candidates.map((o) => o.id), | ||
| }; | ||
|
|
||
| logger.info("[stream-basins-backfill] enqueued provisioning jobs", { | ||
| enqueued, | ||
| candidates: candidates.length, | ||
| remaining: response.remaining, | ||
| }); | ||
|
|
||
| return json(response); | ||
| } | ||
|
|
||
| // GET returns the current state without doing anything — useful for | ||
| // monitoring "is the backfill done yet?" from a dashboard / curl. | ||
| export async function loader({ request }: ActionFunctionArgs) { | ||
| await requireAdminApiRequest(request); | ||
|
|
||
| const totalOrgs = await prisma.organization.count({ where: { deletedAt: null } }); | ||
| const provisioned = await prisma.organization.count({ | ||
| where: { deletedAt: null, NOT: { streamBasinName: null } }, | ||
| }); | ||
| const remaining = totalOrgs - provisioned; | ||
|
|
||
| return json({ | ||
| ok: true, | ||
| perOrgBasinsEnabled: isPerOrgBasinsEnabled(), | ||
| totalOrgs, | ||
| provisioned, | ||
| remaining, | ||
| completion: totalOrgs === 0 ? 1 : provisioned / totalOrgs, | ||
| }); | ||
| } |
72 changes: 72 additions & 0 deletions
72
apps/webapp/app/routes/admin.api.v1.stream-basins.reconfigure.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| import { json, type ActionFunctionArgs } from "@remix-run/server-runtime"; | ||
| import { z } from "zod"; | ||
| import { requireAdminApiRequest } from "~/services/personalAccessToken.server"; | ||
| import { | ||
| isPerOrgBasinsEnabled, | ||
| reconfigureBasinForOrg, | ||
| } from "~/services/realtime/streamBasinProvisioner.server"; | ||
| import { commonWorker } from "~/v3/commonWorker.server"; | ||
|
|
||
| /** | ||
| * Admin trigger for `v3.reconfigureStreamBasinForOrg`. The plan-change | ||
| * path in `setPlan` enqueues this automatically when billing is wired; | ||
|
ericallam marked this conversation as resolved.
Outdated
|
||
| * this route exists for ops + e2e testing. | ||
| * | ||
| * - Default (`{ orgId }`): enqueues the worker job which resolves the | ||
| * retention from the org's plan and PATCHes the basin to match. | ||
| * No-op when billing isn't configured (OSS). | ||
| * - With `retention`: bypasses the billing lookup and runs reconfigure | ||
| * inline against the given duration string (e.g. `"7d"`, `"30d"`, | ||
| * `"365d"`, `"1y"`). Useful for validating the PATCH wire shape | ||
| * end-to-end and as a manual override (e.g. enterprise contracts). | ||
| */ | ||
| const BodySchema = z | ||
| .object({ | ||
| orgId: z.string(), | ||
| retention: z.string().optional(), | ||
| }) | ||
|
ericallam marked this conversation as resolved.
Outdated
|
||
| .strict(); | ||
|
|
||
| export async function action({ request }: ActionFunctionArgs) { | ||
| await requireAdminApiRequest(request); | ||
|
|
||
| if (!isPerOrgBasinsEnabled()) { | ||
| return json( | ||
| { ok: false, error: "Per-org stream basins are disabled." }, | ||
| { status: 400 } | ||
| ); | ||
| } | ||
|
|
||
| let parsed: ReturnType<typeof BodySchema.safeParse>; | ||
| try { | ||
| const text = await request.text(); | ||
| const raw = text.length > 0 ? JSON.parse(text) : {}; | ||
| parsed = BodySchema.safeParse(raw); | ||
| } catch { | ||
| return json({ ok: false, error: "Invalid JSON body" }, { status: 400 }); | ||
| } | ||
| if (!parsed.success) { | ||
| return json({ ok: false, error: parsed.error.flatten() }, { status: 400 }); | ||
| } | ||
|
|
||
| if (parsed.data.retention) { | ||
| // Direct, synchronous reconfigure with the explicit retention. | ||
| // Skips the worker queue + billing lookup so the PATCH is | ||
| // verifiable in the response. Errors surface as 500. | ||
| await reconfigureBasinForOrg(parsed.data.orgId, parsed.data.retention); | ||
| return json({ | ||
| ok: true, | ||
| mode: "inline", | ||
| orgId: parsed.data.orgId, | ||
| retention: parsed.data.retention, | ||
| }); | ||
| } | ||
|
|
||
| await commonWorker.enqueue({ | ||
| job: "v3.reconfigureStreamBasinForOrg", | ||
| payload: { orgId: parsed.data.orgId }, | ||
| id: `reconfigureStreamBasin:${parsed.data.orgId}`, | ||
| }); | ||
|
|
||
| return json({ ok: true, mode: "queued", enqueued: parsed.data.orgId }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.