Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MetadataCondition } from "@ctrlplane/validators/releases";
import { useState } from "react";
import { useParams } from "next/navigation";
import { IconLoader2 } from "@tabler/icons-react";

import { cn } from "@ctrlplane/ui";
import { Button } from "@ctrlplane/ui/button";
Expand All @@ -22,14 +23,30 @@ import { useMatchSorter } from "~/utils/useMatchSorter";
export const MetadataConditionRender: React.FC<
ReleaseConditionRenderProps<MetadataCondition>
> = ({ condition, onChange, className }) => {
const { workspaceSlug, systemSlug } = useParams();
const wSlug = workspaceSlug! as string;
const sSlug = systemSlug as string | undefined;
const { workspaceSlug, systemSlug } = useParams<{
workspaceSlug: string;
systemSlug?: string;
}>();

const metadataKeys = api.release.metadataKeys.useQuery({
workspaceSlug: wSlug,
systemSlug: sSlug,
});
const workspaceQ = api.workspace.bySlug.useQuery(workspaceSlug);
const workspace = workspaceQ.data;
const systemQ = api.system.bySlug.useQuery(
{ workspaceSlug, systemSlug: systemSlug ?? "" },
{ enabled: systemSlug != null },
);
Comment on lines +33 to +36
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid passing empty systemSlug when it is null

When systemSlug is null, the query is still receiving systemSlug: "", which may not be necessary and could lead to unintended behavior. It's better to conditionally include systemSlug only when it is defined.

Consider modifying the query parameters as follows:

const systemQ = api.system.bySlug.useQuery(
-  { workspaceSlug, systemSlug: systemSlug ?? "" },
+  systemSlug ? { workspaceSlug, systemSlug } : undefined,
  { enabled: systemSlug != null },
);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const systemQ = api.system.bySlug.useQuery(
{ workspaceSlug, systemSlug: systemSlug ?? "" },
{ enabled: systemSlug != null },
);
const systemQ = api.system.bySlug.useQuery(
systemSlug ? { workspaceSlug, systemSlug } : undefined,
{ enabled: systemSlug != null },
);

const system = systemQ.data;

const workspaceMetadataKeys = api.release.metadataKeys.byWorkspace.useQuery(
workspace?.id ?? "",
{ enabled: workspace != null && system == null },
);
const systemMetadataKeys = api.release.metadataKeys.bySystem.useQuery(
system?.id ?? "",
{ enabled: system != null },
);

const metadataKeys =
systemMetadataKeys.data ?? workspaceMetadataKeys.data ?? [];

const setKey = (key: string) => onChange({ ...condition, key });

Expand All @@ -49,10 +66,13 @@ export const MetadataConditionRender: React.FC<
: onChange({ ...condition, operator, value: condition.value ?? "" });

const [open, setOpen] = useState(false);
const filteredMetadataKeys = useMatchSorter(
metadataKeys.data ?? [],
condition.key,
);
const filteredMetadataKeys = useMatchSorter(metadataKeys, condition.key);

const loadingMetadataKeys =
workspaceQ.isLoading ||
systemQ.isLoading ||
workspaceMetadataKeys.isLoading ||
systemMetadataKeys.isLoading;
Comment on lines +71 to +75
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for query failures

Currently, the code does not handle potential errors from the queries. To enhance user experience, consider checking for errors and providing appropriate feedback if any query fails.

You can check the isError property of your queries and display an error message or fallback UI:

if (
  workspaceQ.isError ||
  systemQ.isError ||
  workspaceMetadataKeys.isError ||
  systemMetadataKeys.isError
) {
  return <div className="p-2 text-sm text-red-500">Error loading metadata keys.</div>;
}


return (
<div className={cn("flex w-full items-center gap-2", className)}>
Expand All @@ -72,20 +92,27 @@ export const MetadataConditionRender: React.FC<
className="scrollbar-thin scrollbar-track-neutral-950 scrollbar-thumb-neutral-800 max-h-[300px] overflow-y-auto p-0 text-sm"
onOpenAutoFocus={(e) => e.preventDefault()}
>
{filteredMetadataKeys.map((k) => (
<Button
variant="ghost"
size="sm"
key={k}
className="w-full rounded-none text-left"
onClick={() => {
setKey(k);
setOpen(false);
}}
>
<div className="w-full">{k}</div>
</Button>
))}
{!loadingMetadataKeys &&
filteredMetadataKeys.map((k) => (
<Button
variant="ghost"
size="sm"
key={k}
className="w-full rounded-none text-left"
onClick={() => {
setKey(k);
setOpen(false);
}}
>
<div className="w-full">{k}</div>
</Button>
))}
{loadingMetadataKeys && (
<div className="flex h-8 items-center gap-1 pl-2 text-xs text-muted-foreground">
<IconLoader2 className="h-3 w-3 animate-spin" /> Loading
keys...
</div>
)}
</PopoverContent>
</Popover>
</div>
Expand Down
96 changes: 39 additions & 57 deletions packages/api/src/router/release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import {
releaseMetadata,
system,
target,
workspace,
} from "@ctrlplane/db/schema";
import {
cancelOldReleaseJobTriggersOnJobDispatch,
Expand Down Expand Up @@ -417,61 +416,44 @@ export const releaseRouter = createTRPCRouter({
);
}),

metadataKeys: protectedProcedure
.meta({
authorizationCheck: async ({ canUser, input }) => {
if (input.systemSlug != null) {
const sys = await db
.select()
.from(system)
.where(eq(system.slug, input.systemSlug))
.then(takeFirstOrNull);
if (sys == null) return false;

return canUser
.perform(Permission.ReleaseGet)
.on({ type: "system", id: sys.id });
}

const ws = await db
.select()
.from(workspace)
.where(eq(workspace.slug, input.workspaceSlug))
.then(takeFirstOrNull);
if (ws == null) return false;

return canUser
.perform(Permission.ReleaseGet)
.on({ type: "workspace", id: ws.id });
},
})
.input(
z.object({
workspaceSlug: z.string(),
systemSlug: z.string().optional(),
}),
)
.query(async ({ input }) => {
const baseQuery = db
.selectDistinct({ key: releaseMetadata.key })
.from(release)
.innerJoin(releaseMetadata, eq(releaseMetadata.releaseId, release.id))
.innerJoin(deployment, eq(release.deploymentId, deployment.id))
.innerJoin(system, eq(deployment.systemId, system.id))
.innerJoin(workspace, eq(system.workspaceId, workspace.id));

if (input.systemSlug != null)
return baseQuery
.where(
and(
eq(system.slug, input.systemSlug),
eq(workspace.slug, input.workspaceSlug),
),
)
.then((r) => r.map((row) => row.key));
metadataKeys: createTRPCRouter({
bySystem: protectedProcedure
.meta({
authorizationCheck: ({ canUser, input }) =>
canUser.perform(Permission.ReleaseGet).on({
type: "system",
id: input,
}),
})
.input(z.string().uuid())
.query(async ({ input, ctx }) =>
ctx.db
.selectDistinct({ key: releaseMetadata.key })
.from(release)
.innerJoin(releaseMetadata, eq(releaseMetadata.releaseId, release.id))
.innerJoin(deployment, eq(release.deploymentId, deployment.id))
.where(eq(deployment.systemId, input))
.then((r) => r.map((row) => row.key)),
),
Comment on lines +420 to +437
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider refactoring duplicated code in metadataKeys procedures

The bySystem and byWorkspace procedures share nearly identical query logic, differing mainly in the authorization checks and the where clause conditions. To enhance maintainability and reduce code duplication, consider abstracting the common query logic into a shared helper function or method that accepts parameters for the varying parts, such as the entity type and ID.

Also applies to: 439-457


return baseQuery
.where(eq(workspace.slug, input.workspaceSlug))
.then((r) => r.map((row) => row.key));
}),
byWorkspace: protectedProcedure
.meta({
authorizationCheck: ({ canUser, input }) =>
canUser.perform(Permission.ReleaseGet).on({
type: "workspace",
id: input,
}),
})
.input(z.string().uuid())
.query(async ({ input, ctx }) =>
ctx.db
.selectDistinct({ key: releaseMetadata.key })
.from(release)
.innerJoin(releaseMetadata, eq(releaseMetadata.releaseId, release.id))
.innerJoin(deployment, eq(release.deploymentId, deployment.id))
.innerJoin(system, eq(deployment.systemId, system.id))
.where(eq(system.workspaceId, input))
.then((r) => r.map((row) => row.key)),
),
}),
});