Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

batch at the useGetSecretValue layer

DimitrisStaratzise79d45ba5168
diff --git a/frontend/src/hooks/api/dashboard/queries.tsx b/frontend/src/hooks/api/dashboard/queries.tsx
index ec3253b644..f0cd489d70 100644
--- a/frontend/src/hooks/api/dashboard/queries.tsx
+++ b/frontend/src/hooks/api/dashboard/queries.tsx
@@ -31,7 +31,7 @@ import { OrderByDirection } from "@app/hooks/api/generic/types";
import { mergePersonalSecrets } from "@app/hooks/api/secrets/queries";
import { groupBy, unique } from "@app/lib/fn/array";
-import { SecretV3Raw } from "../types";
+import { SecretType, SecretV3Raw } from "../types";
export const dashboardKeys = {
all: () => ["dashboard"] as const,
@@ -686,6 +686,94 @@ export const fetchSecretValue = async (params: TGetSecretValueDTO) => {
return data;
};
+type TPendingSecretValue = {
+ params: TGetSecretValueDTO;
+ resolve: (value: DashboardSecretValue) => void;
+ reject: (reason: unknown) => void;
+};
+
+// Every visible overview row asks for its own value, so revealing a page, searching or expanding an
+// import would send one request per row. Requests made in the same tick are grouped by folder and
+// sent as one secrets-by-keys call instead.
+const pendingSecretValues = new Map<string, TPendingSecretValue[]>();
+
+const fetchSecretValuesIndividually = (requests: TPendingSecretValue[]) => {
+ requests.forEach(({ params, resolve, reject }) => {
+ fetchSecretValue(params).then(resolve, reject);
+ });
+};
+
+const fetchSecretValueGroup = async (requests: TPendingSecretValue[]) => {
+ if (requests.length === 1) {
+ fetchSecretValuesIndividually(requests);
+ return;
+ }
+
+ const { projectId, environment, secretPath } = requests[0].params;
+ let secrets: SecretV3Raw[];
+ try {
+ ({ secrets } = await fetchDashboardProjectSecretsByKeys({
+ projectId,
+ environment,
+ secretPath,
+ keys: [...new Set(requests.map(({ params }) => params.secretKey))],
+ viewSecretValue: true
+ }));
+ } catch (error) {
+ // one value the user cannot read fails the whole request, so each value is fetched on its own
+ if (error instanceof AxiosError && error.status === 403) {
+ fetchSecretValuesIndividually(requests);
+ } else {
+ requests.forEach(({ reject }) => reject(error));
+ }
+ return;
+ }
+
+ const secretsByTypeAndKey = new Map(
+ secrets.map((secret) => [`${secret.type}:${secret.secretKey}`, secret])
+ );
+ const unresolved: TPendingSecretValue[] = [];
+ requests.forEach((request) => {
+ const { secretKey, isOverride } = request.params;
+ const type = isOverride ? SecretType.Personal : SecretType.Shared;
+ const secret = secretsByTypeAndKey.get(`${type}:${secretKey}`);
+ const value = secret?.secretValue;
+ if (!secret || secret.secretValueHidden || value === undefined) {
+ unresolved.push(request);
+ return;
+ }
+
+ request.resolve(
+ isOverride ? { value: undefined, valueOverride: value } : { value, valueOverride: undefined }
+ );
+ });
+
+ // a value reached through an import of this folder (cross-project imports) only resolves
+ // through /secret-value
+ fetchSecretValuesIndividually(unresolved);
+};
+
+const fetchSecretValueBatched = (params: TGetSecretValueDTO) =>
+ new Promise<DashboardSecretValue>((resolve, reject) => {
+ if (!pendingSecretValues.size) {
+ setTimeout(() => {
+ const groups = [...pendingSecretValues.values()];
+ pendingSecretValues.clear();
+ groups.forEach((requests) => {
+ // anything unexpected must still settle every row, or it would stay loading forever
+ fetchSecretValueGroup(requests).catch((error) =>
+ requests.forEach((request) => request.reject(error))
+ );
+ });
+ });
+ }
+
+ const groupKey = JSON.stringify([params.projectId, params.environment, params.secretPath]);
+ const requests = pendingSecretValues.get(groupKey) ?? [];
+ requests.push({ params, resolve, reject });
+ pendingSecretValues.set(groupKey, requests);
+ });
+
export const useGetSecretValue = (
params: TGetSecretValueDTO,
options?: Omit<
@@ -700,7 +788,7 @@ export const useGetSecretValue = (
) => {
return useQuery({
queryKey: dashboardKeys.getSecretValue(params),
- queryFn: async () => fetchSecretValue(params),
+ queryFn: async () => fetchSecretValueBatched(params),
staleTime: 1000 * 60,
retry: (count, error) => {
// retrying a throttled request only extends the throttle
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index e47c365873..9246cf4ecb 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -35,7 +35,6 @@ import {
GroupIcon,
InfoIcon,
LayersIcon,
- LoaderCircleIcon,
LockIcon,
TrashIcon,
UsersIcon
@@ -188,11 +187,7 @@ import {
} from "@app/hooks/api";
import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
-import {
- dashboardKeys,
- fetchDashboardProjectSecretsByKeys,
- useGetProjectSecretsOverview
-} from "@app/hooks/api/dashboard/queries";
+import { dashboardKeys, useGetProjectSecretsOverview } from "@app/hooks/api/dashboard/queries";
import { DashboardSecretsOrderBy, ProjectSecretsImportedBy } from "@app/hooks/api/dashboard/types";
import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
import { useGetFolderCommitsCount } from "@app/hooks/api/folderCommits";
@@ -445,7 +440,6 @@ const OverviewPageContent = () => {
);
const [isSingleEnvSecretsVisible, setIsSingleEnvSecretsVisible] = useToggle();
- const [isRevealingAllSecrets, setIsRevealingAllSecrets] = useToggle();
// scott: keeping incase we bring it back
// const [collapseEnvironments, setCollapseEnvironments] = useToggle(
@@ -2426,95 +2420,6 @@ const OverviewPageContent = () => {
[getSecretByKey, isBatchModeActive, pendingChanges.secrets]
);
- // read again once the requests resolve, so a reveal started before switching environment or
- // folder does not turn values on for the new one
- const revealTargetRef = useRef("");
- revealTargetRef.current = JSON.stringify([visibleEnvs[0]?.slug, secretPath]);
-
- // Rows fetch their own value once visible, so the cache is primed with one request per
- // environment and path before they are shown instead of letting each row call the API.
- const handleRevealAllSecrets = async () => {
- const [{ slug: environment }] = visibleEnvs;
- const revealTarget = revealTargetRef.current;
- const groups: Record<string, { environment: string; secretPath: string; keys: string[] }> = {};
- const addKey = (groupEnvironment: string, groupSecretPath: string, key: string) => {
- const groupKey = JSON.stringify([groupEnvironment, groupSecretPath]);
- groups[groupKey] ??= { environment: groupEnvironment, secretPath: groupSecretPath, keys: [] };
- groups[groupKey].keys.push(key);
- };
-
- // one shared value the user cannot read fails the whole request, so those keys (and any
- // personal override on them) are left for their rows to fetch
- mergedSecKeys.forEach((key) => {
- const secret = getSecretByKey(environment, key);
- if (secret && !secret.isEmpty && !secret.secretValueHidden) {
- addKey(environment, secretPath, key);
- }
- });
-
- // expanded imports show values for their keys matching the search; cross-project imports are
- // skipped since their environments are not part of this project
- sortableImportItems.forEach((imp) => {
- const isExpanded = activeTableRows.has(getTableRowActivityId("secret-import", imp.id));
- if (!isExpanded || imp.importEnv.projectId !== projectId) return;
-
- const importedFolder = importedSecretsFlat.find(
- (item) =>
- item.environment === imp.importEnv.slug &&
- item.secretPath === imp.importPath &&
- item.sourceEnv === environment
- );
- importedFolder?.secrets.forEach(({ key, isEmpty }) => {
- const matchesSearch = key.toUpperCase().includes(searchFilter.toUpperCase());
- if (!isEmpty && matchesSearch) addKey(imp.importEnv.slug, imp.importPath, key);
- });
- });
-
- setIsRevealingAllSecrets.on();
- try {
- await Promise.all(
- Object.values(groups).map(async (group) => {
- const { secrets: fetchedSecrets } = await fetchDashboardProjectSecretsByKeys({
- projectId,
- environment: group.environment,
- secretPath: group.secretPath,
- keys: group.keys,
- viewSecretValue: true
- }).catch((error) => {
- // every other group is an import; one the user cannot read in bulk should not block
- // the rest, and its cells fetch their own values as before
- const isImport = group.environment !== environment || group.secretPath !== secretPath;
- if (isImport) return { secrets: [] };
- throw error;
- });
-
- fetchedSecrets.forEach((fetchedSecret) => {
- if (fetchedSecret.secretValueHidden || fetchedSecret.secretValue === undefined) return;
-
- const isOverride = fetchedSecret.type === SecretType.Personal;
- queryClient.setQueryData(
- dashboardKeys.getSecretValue({
- projectId,
- environment: group.environment,
- secretPath: group.secretPath,
- secretKey: fetchedSecret.secretKey,
- ...(isOverride ? { isOverride: true } : {})
- }),
- isOverride
- ? { value: undefined, valueOverride: fetchedSecret.secretValue }
- : { value: fetchedSecret.secretValue, valueOverride: undefined }
- );
- });
- })
- );
- if (revealTargetRef.current === revealTarget) setIsSingleEnvSecretsVisible.on();
- } catch {
- createNotification({ type: "error", text: "Failed to reveal secret values" });
- } finally {
- setIsRevealingAllSecrets.off();
- }
- };
-
const mergedFolderNamesAndDescriptions = useMemo(() => {
if (!isBatchModeActive)
return folderNamesAndDescriptions.map((f) => ({ ...f, pendingAction: undefined }));
@@ -3907,18 +3812,13 @@ const OverviewPageContent = () => {
<Badge variant="ghost" asChild>
<button
type="button"
- disabled={isRevealingAllSecrets}
onClick={() => {
overviewTelemetry.interaction({
action: isSingleEnvSecretsVisible ? "hide" : "reveal",
source: "header",
resourceType: "secret"
});
- if (isSingleEnvSecretsVisible) {
- setIsSingleEnvSecretsVisible.off();
- } else {
- handleRevealAllSecrets();
- }
+ setIsSingleEnvSecretsVisible.toggle();
}}
>
{isSingleEnvSecretsVisible ? (
@@ -3928,11 +3828,7 @@ const OverviewPageContent = () => {
</>
) : (
<>
- {isRevealingAllSecrets ? (
- <LoaderCircleIcon className="animate-spin" />
- ) : (
- <EyeIcon />
- )}
+ <EyeIcon />
Reveal All
</>
)}