Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3.8k
improvement(secrets): parallelize save mutations and add admin visibility for workspace secrets#4032
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
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
improvement(secrets): parallelize save mutations and add admin visibility for workspace secrets #4032
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
614d156
improvement(secrets): parallelize save mutations and add admin visibi…
waleedlatif1 74e0509
fix(secrets): sequence workspace upsert/delete to avoid read-modify-w…
waleedlatif1 1cb5810
fix(secrets): use Promise.allSettled to ensure credential invalidatio…
waleedlatif1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
81 changes: 62 additions & 19 deletions
81 apps/sim/app/workspace/[workspaceId]/settings/components/credentials/credentials-manager.tsx
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 |
|---|---|---|
| @@ -2,6 +2,7 @@ | ||
| import { useCallback, useEffect, useMemo, useRef, useState } from 'react' | ||
| import { createLogger } from '@sim/logger' | ||
| import { useQueryClient } from '@tanstack/react-query' | ||
| import { Check, Clipboard, Key, Search } from 'lucide-react' | ||
| import { useParams, useRouter } from 'next/navigation' | ||
| import { | ||
| @@ -42,6 +43,7 @@ import { | ||
| useWorkspaceCredentials, | ||
| type WorkspaceCredential, | ||
| type WorkspaceCredentialRole, | ||
| workspaceCredentialKeys, | ||
| } from '@/hooks/queries/credentials' | ||
| import { | ||
| usePersonalEnvironment, | ||
| @@ -125,6 +127,7 @@ interface WorkspaceVariableRowProps { | ||
| renamingKey: string | null | ||
| pendingKeyValue: string | ||
| hasCredential: boolean | ||
| isAdmin: boolean | ||
| onRenameStart: (key: string) => void | ||
| onPendingKeyChange: (value: string) => void | ||
| onRenameEnd: (key: string, value: string) => void | ||
| @@ -138,12 +141,18 @@ function WorkspaceVariableRow({ | ||
| renamingKey, | ||
| pendingKeyValue, | ||
| hasCredential, | ||
| isAdmin, | ||
| onRenameStart, | ||
| onPendingKeyChange, | ||
| onRenameEnd, | ||
| onDelete, | ||
| onViewDetails, | ||
| }: WorkspaceVariableRowProps) { | ||
| const [valueFocused, setValueFocused] = useState(false) | ||
| const maskedValueStyle = | ||
| isAdmin && !valueFocused ? ({ WebkitTextSecurity: 'disc' } as React.CSSProperties) : undefined | ||
| return ( | ||
| <div className='contents'> | ||
| <EmcnInput | ||
| @@ -163,12 +172,19 @@ function WorkspaceVariableRow({ | ||
| /> | ||
| <div /> | ||
| <EmcnInput | ||
| value={value ? '\u2022'.repeat(value.length) : ''} | ||
| value={isAdmin ? value : value ? '\u2022'.repeat(value.length) : ''} | ||
| readOnly | ||
| onFocus={() => { | ||
| if (isAdmin) setValueFocused(true) | ||
| }} | ||
| onBlur={() => { | ||
| if (isAdmin) setValueFocused(false) | ||
| }} | ||
| autoComplete='off' | ||
| autoCorrect='off' | ||
| autoCapitalize='off' | ||
| spellCheck='false' | ||
| style={maskedValueStyle} | ||
| className='h-9' | ||
| /> | ||
| <Button | ||
| @@ -298,6 +314,14 @@ export function CredentialsManager() { | ||
| ) | ||
| const { data: workspacePermissions } = useWorkspacePermissionsQuery(workspaceId || null) | ||
| const queryClient = useQueryClient() | ||
| const isAdmin = useMemo(() => { | ||
| const userId = session?.user?.id | ||
| if (!userId || !workspacePermissions?.users) return false | ||
| const currentUser = workspacePermissions.users.find((user) => user.userId === userId) | ||
| return currentUser?.permissionType === 'admin' | ||
| }, [session?.user?.id, workspacePermissions?.users]) | ||
| const isLoading = isPersonalLoading || isWorkspaceLoading | ||
| const variables = useMemo(() => personalEnvData || {}, [personalEnvData]) | ||
| @@ -923,6 +947,7 @@ export function CredentialsManager() { | ||
| const prevInitialVars = [...initialVarsRef.current] | ||
| const prevInitialWorkspaceVars = { ...initialWorkspaceVarsRef.current } | ||
| const mutations: Promise<unknown>[] = [] | ||
| try { | ||
| setShowUnsavedChanges(false) | ||
| @@ -944,8 +969,6 @@ export function CredentialsManager() { | ||
| .filter((v) => v.key && v.value) | ||
| .reduce<Record<string, string>>((acc, { key, value }) => ({ ...acc, [key]: value }), {}) | ||
| await savePersonalMutation.mutateAsync({ variables: validVariables }) | ||
| const before = prevInitialWorkspaceVars | ||
| const after = mergedWorkspaceVars | ||
| const toUpsert: Record<string, string> = {} | ||
| @@ -961,33 +984,52 @@ export function CredentialsManager() { | ||
| if (!(k in after)) toDelete.push(k) | ||
| } | ||
| if (workspaceId) { | ||
| if (Object.keys(toUpsert).length) { | ||
| await upsertWorkspaceMutation.mutateAsync({ workspaceId, variables: toUpsert }) | ||
| } | ||
| if (toDelete.length) { | ||
| await removeWorkspaceMutation.mutateAsync({ workspaceId, keys: toDelete }) | ||
| const personalChanged = (() => { | ||
| const initialMap = new Map( | ||
| prevInitialVars.filter((v) => v.key && v.value).map((v) => [v.key, v.value]) | ||
| ) | ||
| const currentKeys = Object.keys(validVariables) | ||
| if (initialMap.size !== currentKeys.length) return true | ||
| for (const [key, value] of Object.entries(validVariables)) { | ||
| if (initialMap.get(key) !== value) return true | ||
| } | ||
| return false | ||
| })() | ||
| if (personalChanged) { | ||
| mutations.push(savePersonalMutation.mutateAsync({ variables: validVariables })) | ||
| } | ||
| if (workspaceId && (Object.keys(toUpsert).length || toDelete.length)) { | ||
| mutations.push( | ||
| (async () => { | ||
| if (Object.keys(toUpsert).length) { | ||
| await upsertWorkspaceMutation.mutateAsync({ workspaceId, variables: toUpsert }) | ||
| } | ||
| if (toDelete.length) { | ||
| await removeWorkspaceMutation.mutateAsync({ workspaceId, keys: toDelete }) | ||
| } | ||
| })() | ||
| ) | ||
| } | ||
| const results = await Promise.allSettled(mutations) | ||
| const firstFailure = results.find((r): r is PromiseRejectedResult => r.status === 'rejected') | ||
| if (firstFailure) throw firstFailure.reason | ||
| setWorkspaceVars(mergedWorkspaceVars) | ||
| setNewWorkspaceRows([createEmptyEnvVar()]) | ||
| } catch (error) { | ||
| hasSavedRef.current = false | ||
| initialVarsRef.current = prevInitialVars | ||
| initialWorkspaceVarsRef.current = prevInitialWorkspaceVars | ||
| logger.error('Failed to save environment variables:', error) | ||
| } finally { | ||
| if (mutations.length > 0) { | ||
| queryClient.invalidateQueries({ queryKey: workspaceCredentialKeys.lists() }) | ||
| } | ||
waleedlatif1 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| } | ||
| }, [ | ||
| isListSaving, | ||
| envVars, | ||
| workspaceVars, | ||
| newWorkspaceRows, | ||
| workspaceId, | ||
| savePersonalMutation, | ||
| upsertWorkspaceMutation, | ||
| removeWorkspaceMutation, | ||
| ]) | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps -- mutation objects and queryClient are stable (TanStack Query v5) | ||
| }, [isListSaving, envVars, workspaceVars, newWorkspaceRows, workspaceId]) | ||
| const handleDiscardAndNavigate = useCallback(() => { | ||
| shouldBlockNavRef.current = false | ||
| @@ -1494,6 +1536,7 @@ export function CredentialsManager() { | ||
| renamingKey={renamingKey} | ||
| pendingKeyValue={pendingKeyValue} | ||
| hasCredential={envKeyToCredential.has(key)} | ||
| isAdmin={isAdmin} | ||
| onRenameStart={setRenamingKey} | ||
| onPendingKeyChange={setPendingKeyValue} | ||
| onRenameEnd={handleWorkspaceKeyRename} | ||
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.
Uh oh!
There was an error while loading. Please reload this page.
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.