Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/env-default-worker-group.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@trigger.dev/core": patch
---

Add an optional `defaultWorkerGroupId` to the authenticated environment shape, enabling per-environment default region selection (falls back to the project, then global, default).
6 changes: 6 additions & 0 deletions .server-changes/per-environment-default-region.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
area: webapp
type: improvement
---

Default region selection is now per-environment instead of per-project, falling back to the project default and then the global default.
1 change: 1 addition & 0 deletions apps/webapp/app/models/runtimeEnvironment.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export function toAuthenticated(
builtInEnvironmentVariableOverrides: env.builtInEnvironmentVariableOverrides,
createdAt: env.createdAt,
updatedAt: env.updatedAt,
defaultWorkerGroupId: env.defaultWorkerGroupId,
project: {
id: env.project.id,
slug: env.project.slug,
Expand Down
78 changes: 32 additions & 46 deletions apps/webapp/app/presenters/v3/RegionsPresenter.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { type WorkloadType } from "@trigger.dev/database";
import { type Project } from "~/models/project.server";
import { type User } from "~/models/user.server";
import { FEATURE_FLAG } from "~/v3/featureFlags";
import { makeFlag } from "~/v3/featureFlags.server";
import { defaultVisibilityFilter, resolveComputeAccess } from "~/v3/regionAccess.server";
import { WorkerGroupService } from "~/v3/services/worker/workerGroupService.server";
import { BasePresenter } from "./basePresenter.server";
import { getCurrentPlan } from "~/services/platform.v3.server";

Expand All @@ -24,17 +23,18 @@ export class RegionsPresenter extends BasePresenter {
public async call({
userId,
projectSlug,
environmentId,
isAdmin = false,
}: {
userId: User["id"];
projectSlug: Project["slug"];
environmentId?: string;
isAdmin?: boolean;
}) {
const project = await this._replica.project.findFirst({
select: {
id: true,
organizationId: true,
defaultWorkerGroupId: true,
allowedWorkerQueues: true,
organization: {
select: { featureFlags: true },
Expand All @@ -56,14 +56,21 @@ export class RegionsPresenter extends BasePresenter {
throw new Error("Project not found");
}

const getFlag = makeFlag(this._replica);
const defaultWorkerInstanceGroupId = await getFlag({
key: FEATURE_FLAG.defaultWorkerInstanceGroupId,
});
const environment = environmentId
? await this._replica.runtimeEnvironment.findFirst({
select: { defaultWorkerGroupId: true },
where: { id: environmentId, projectId: project.id, archivedAt: null },
})
: null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.

if (!defaultWorkerInstanceGroupId) {
throw new Error("Default worker instance group not found");
}
// Resolve via the same path the trigger uses (env -> project -> global, each
// existence-checked) so the UI default always matches where runs route and can
// never point at a deleted region.
const defaultWorkerGroup = await new WorkerGroupService().getDefaultWorkerGroupForProject({
projectId: project.id,
environmentDefaultWorkerGroupId: environment?.defaultWorkerGroupId,
});
const effectiveDefaultId = defaultWorkerGroup?.id;

const hasComputeAccess = await resolveComputeAccess(
this._replica,
Expand Down Expand Up @@ -103,47 +110,26 @@ export class RegionsPresenter extends BasePresenter {
cloudProvider: region.cloudProvider ?? undefined,
location: region.location ?? undefined,
staticIPs: region.staticIPs ?? undefined,
isDefault: region.id === defaultWorkerInstanceGroupId,
isDefault: region.id === effectiveDefaultId,
isHidden: region.hidden,
workloadType: region.workloadType,
}));

if (project.defaultWorkerGroupId) {
const defaultWorkerGroup = await this._replica.workerInstanceGroup.findFirst({
select: {
id: true,
name: true,
masterQueue: true,
description: true,
cloudProvider: true,
location: true,
staticIPs: true,
hidden: true,
workloadType: true,
},
where: { id: project.defaultWorkerGroupId },
// The default may not be in the visible list (e.g. a hidden region set as the
// env/project default) — include the already-resolved group so it still shows.
if (defaultWorkerGroup && !regions.some((region) => region.id === defaultWorkerGroup.id)) {
regions.push({
id: defaultWorkerGroup.id,
name: defaultWorkerGroup.name,
masterQueue: defaultWorkerGroup.masterQueue,
description: defaultWorkerGroup.description ?? undefined,
cloudProvider: defaultWorkerGroup.cloudProvider ?? undefined,
location: defaultWorkerGroup.location ?? undefined,
staticIPs: defaultWorkerGroup.staticIPs ?? undefined,
isDefault: true,
isHidden: defaultWorkerGroup.hidden,
workloadType: defaultWorkerGroup.workloadType,
});

if (defaultWorkerGroup) {
// Unset the default region
const defaultRegion = regions.find((region) => region.isDefault);
if (defaultRegion) {
defaultRegion.isDefault = false;
}

regions.push({
id: defaultWorkerGroup.id,
name: defaultWorkerGroup.name,
masterQueue: defaultWorkerGroup.masterQueue,
description: defaultWorkerGroup.description ?? undefined,
cloudProvider: defaultWorkerGroup.cloudProvider ?? undefined,
location: defaultWorkerGroup.location ?? undefined,
staticIPs: defaultWorkerGroup.staticIPs ?? undefined,
isDefault: true,
isHidden: defaultWorkerGroup.hidden,
workloadType: defaultWorkerGroup.workloadType,
});
}
}

// Default first
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
new RegionsPresenter().call({
userId: user.id,
projectSlug: projectParam,
environmentId: environment.id,
isAdmin: user.admin || user.isImpersonating,
}),
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,26 +52,37 @@ import { useOrganization } from "~/hooks/useOrganizations";
import { useHasAdminAccess } from "~/hooks/useUser";
import { redirectWithErrorMessage, redirectWithSuccessMessage } from "~/models/message.server";
import { findProjectBySlug } from "~/models/project.server";
import { findEnvironmentBySlug } from "~/models/runtimeEnvironment.server";
import { type Region, RegionsPresenter } from "~/presenters/v3/RegionsPresenter.server";
import { requireUser } from "~/services/session.server";
import {
docsPath,
EnvironmentParamSchema,
ProjectParamSchema,
regionsPath,
v3BillingPath,
} from "~/utils/pathBuilder";
import { SetDefaultRegionService } from "~/v3/services/setDefaultRegion.server";

export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const user = await requireUser(request);
const { projectParam } = ProjectParamSchema.parse(params);
const { organizationSlug, projectParam, envParam } = EnvironmentParamSchema.parse(params);

const project = await findProjectBySlug(organizationSlug, projectParam, user.id);
if (!project) {
throw new Response(undefined, { status: 404, statusText: "Project not found" });
}

const environment = await findEnvironmentBySlug(project.id, envParam, user.id);
if (!environment) {
throw new Response(undefined, { status: 404, statusText: "Environment not found" });
}

const presenter = new RegionsPresenter();
const [error, result] = await tryCatch(
presenter.call({
userId: user.id,
projectSlug: projectParam,
environmentId: environment.id,
isAdmin: user.admin || user.isImpersonating,
})
);
Expand All @@ -90,6 +101,20 @@ const FormSchema = z.object({
regionId: z.string(),
});

// Lets the parent layout route revalidate its cached regions after a new
// default is set — the action redirects to the same URL, so a pathname check
// alone wouldn't refresh the default shown by useRegions().
export function isSetDefaultRegionFormSubmission(
formMethod: string | undefined,
formData: FormData | undefined
) {
if (!formMethod || !formData) {
return false;
}

return formMethod.toLowerCase() === "post" && formData.has("regionId");
}

export const action = async ({ request, params }: ActionFunctionArgs) => {
const user = await requireUser(request);
const { organizationSlug, projectParam, envParam } = EnvironmentParamSchema.parse(params);
Expand All @@ -106,6 +131,11 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
throw redirectWithErrorMessage(redirectPath, request, "Project not found");
}

const environment = await findEnvironmentBySlug(project.id, envParam, user.id);
if (!environment) {
throw redirectWithErrorMessage(redirectPath, request, "Environment not found");
}

const formData = await request.formData();
const parsedFormData = FormSchema.safeParse(Object.fromEntries(formData));

Expand All @@ -116,7 +146,7 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
const service = new SetDefaultRegionService();
const [error, result] = await tryCatch(
service.call({
projectId: project.id,
environmentId: environment.id,
regionId: parsedFormData.data.regionId,
isAdmin: user.admin || user.isImpersonating,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
new RegionsPresenter().call({
userId: user.id,
projectSlug: projectParam,
environmentId: environment.id,
isAdmin: user.admin || user.isImpersonating,
}),
]);
Expand Down
8 changes: 7 additions & 1 deletion apps/webapp/app/routes/_app.orgs.$organizationSlug/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { requireUser } from "~/services/session.server";
import { telemetry } from "~/services/telemetry.server";
import { organizationPath } from "~/utils/pathBuilder";
import { isEnvironmentPauseResumeFormSubmission } from "../_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.queues/route";
import { isSetDefaultRegionFormSubmission } from "../_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.regions/route";

const ParamsSchema = z.object({
organizationSlug: z.string(),
Expand Down Expand Up @@ -53,6 +54,11 @@ export const shouldRevalidate: ShouldRevalidateFunction = (params) => {
return true;
}

// Invalidate so useRegions() reflects a newly set default region
if (isSetDefaultRegionFormSubmission(params.formMethod, params.formData)) {
return true;
}

// This prevents revalidation when there are search params changes
// IMPORTANT: If the loader function depends on search params, this should be updated
return params.currentUrl.pathname !== params.nextUrl.pathname;
Expand Down Expand Up @@ -106,7 +112,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
}),
shouldLoadRegions
? new RegionsPresenter()
.call({ userId: user.id, projectSlug: projectParam! })
.call({ userId: user.id, projectSlug: projectParam!, environmentId: environment?.id })
.then(({ regions }) => regions)
.catch(() => [] as Region[])
: Promise.resolve([] as Region[]),
Comment thread
myftija marked this conversation as resolved.
Expand Down
9 changes: 8 additions & 1 deletion apps/webapp/app/routes/api.v1.workers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,19 @@ export const loader = createLoaderApiRoute(
projectId: authentication.environment.projectId,
});

// Reuse the trigger path's resolution so isDefault matches where runs
// actually route: env default -> project default -> global default.
const defaultWorkerGroup = await service.getDefaultWorkerGroupForProject({
projectId: authentication.environment.projectId,
environmentDefaultWorkerGroupId: authentication.environment.defaultWorkerGroupId,
});

return json(
workers.map((w) => ({
type: w.type,
name: w.name,
description: w.description,
isDefault: w.id === authentication.environment.project.defaultWorkerGroupId,
isDefault: w.id === defaultWorkerGroup?.id,
updatedAt: w.updatedAt,
}))
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
new RegionsPresenter().call({
userId,
projectSlug: run.project.slug,
environmentId: environment.id,
isAdmin: user.admin || user.isImpersonating,
}),
]);
Expand Down
1 change: 1 addition & 0 deletions apps/webapp/app/runEngine/concerns/queues.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ export class DefaultQueueManager implements QueueManager {
const [error, workerGroup] = await tryCatch(
workerGroupService.getDefaultWorkerGroupForProject({
projectId: environment.projectId,
environmentDefaultWorkerGroupId: environment.defaultWorkerGroupId,
regionOverride,
})
);
Expand Down
2 changes: 2 additions & 0 deletions apps/webapp/app/services/upsertBranch.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ export class UpsertBranchService {
pkApiKey,
shortcode,
maximumConcurrencyLimit: parentEnvironment.maximumConcurrencyLimit,
// Inherit the region from the parent preview environment.
defaultWorkerGroupId: parentEnvironment.defaultWorkerGroupId,
organization: {
connect: {
id: parentEnvironment.organization.id,
Expand Down
19 changes: 12 additions & 7 deletions apps/webapp/app/v3/services/computeTemplateCreation.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { ServiceValidationError } from "./baseService.server";
import { FailDeploymentService } from "./failDeployment.server";
import { resolveComputeAccess } from "../regionAccess.server";
import { WorkerGroupService } from "./worker/workerGroupService.server";

type TemplateCreationMode = "required" | "shadow" | "skip";

Expand Down Expand Up @@ -56,7 +57,7 @@ export class ComputeTemplateCreationService {
prisma: PrismaClientOrTransaction;
writer?: WritableStreamDefaultWriter;
}): Promise<void> {
const mode = await this.resolveMode(options.projectId, options.prisma);
const mode = await this.resolveMode(options.authenticatedEnv, options.prisma);

if (mode === "skip") {
return;
Expand Down Expand Up @@ -134,19 +135,16 @@ export class ComputeTemplateCreationService {
}

async resolveMode(
projectId: string,
authenticatedEnv: AuthenticatedEnvironment,
prisma: PrismaClientOrTransaction
): Promise<TemplateCreationMode> {
if (!this.client) {
return "skip";
}

const project = await prisma.project.findFirst({
where: { id: projectId },
where: { id: authenticatedEnv.projectId },
select: {
defaultWorkerGroup: {
select: { workloadType: true },
},
organization: {
select: { featureFlags: true },
},
Expand All @@ -157,7 +155,14 @@ export class ComputeTemplateCreationService {
return "skip";
}

if (project.defaultWorkerGroup?.workloadType === "MICROVM") {
// Reuse the trigger path's resolution so the template decision matches the
// region runs actually deploy to: env default -> project default -> global default.
const defaultWorkerGroup = await new WorkerGroupService().getDefaultWorkerGroupForProject({
projectId: authenticatedEnv.projectId,
environmentDefaultWorkerGroupId: authenticatedEnv.defaultWorkerGroupId,
});

if (defaultWorkerGroup?.workloadType === "MICROVM") {
return "required";
}

Expand Down
Loading
Loading