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
92 changes: 45 additions & 47 deletions apps/studio/components/interfaces/Auth/PerformanceSettingsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export const PerformanceSettingsForm = () => {
</ScaffoldSection>

<ScaffoldSection isFullWidth>
<ScaffoldSectionTitle className="mb-4">Request Duration</ScaffoldSectionTitle>
<ScaffoldSectionTitle className="mb-4">Request duration</ScaffoldSectionTitle>

<Form_Shadcn_ {...requestDurationForm}>
<form onSubmit={requestDurationForm.handleSubmit(onSubmitRequestDurationForm)}>
Expand All @@ -217,28 +217,31 @@ export const PerformanceSettingsForm = () => {
layout="flex-row-reverse"
label="Maximum allowed duration for an Auth request"
description={
<>
<p>
Requests that exceed this time limit will be terminated. Used to manage
server load.
</p>
<p>We recommend a minimum of 10 seconds.</p>
</>
<p className="text-balance">
Requests that exceed this time limit are terminated to help manage server
load.
</p>
}
>
<FormControl_Shadcn_>
<div className="relative">
<PrePostTab postTab="seconds">
<Input_Shadcn_
type="number"
min={5}
max={30}
{...field}
disabled={!canUpdateConfig || promptProPlanUpgrade}
/>
</PrePostTab>
</div>
</FormControl_Shadcn_>
<div className="flex flex-col gap-2">
<FormControl_Shadcn_>
<div className="relative">
<PrePostTab postTab="seconds">
<Input_Shadcn_
type="number"
min={5}
max={30}
{...field}
disabled={!canUpdateConfig || promptProPlanUpgrade}
/>
</PrePostTab>
</div>
</FormControl_Shadcn_>

<p className="text-xs text-right text-foreground-muted">
10+ seconds recommended
</p>
</div>
</FormItemLayout>
)}
/>
Expand All @@ -251,7 +254,7 @@ export const PerformanceSettingsForm = () => {
</Button>
)}
<Button
type="primary"
type={promptProPlanUpgrade ? 'default' : 'primary'}
htmlType="submit"
disabled={
!canUpdateConfig ||
Expand All @@ -270,7 +273,7 @@ export const PerformanceSettingsForm = () => {
</ScaffoldSection>

<ScaffoldSection isFullWidth>
<ScaffoldSectionTitle className="mb-4">Connection Management</ScaffoldSectionTitle>
<ScaffoldSectionTitle className="mb-4">Connection management</ScaffoldSectionTitle>

<Form_Shadcn_ {...databaseForm}>
<form onSubmit={databaseForm.handleSubmit(onSubmitDatabaseForm)} className="space-y-4">
Expand All @@ -284,15 +287,11 @@ export const PerformanceSettingsForm = () => {
layout="flex-row-reverse"
label="Allocation strategy"
description={
<>
<p>
Choose to allocate a percentage or an absolute number of connections to
the Auth server.
</p>
<p>
We recommend a percentage strategy as it grows with your instance size.
</p>
</>
<p className="text-balance">
Choose whether to allocate a percentage or a fixed number of connections
to the Auth server. We recommend a percentage, as it scales automatically
with your instance size.
</p>
}
>
<FormControl_Shadcn_>
Expand Down Expand Up @@ -345,6 +344,8 @@ export const PerformanceSettingsForm = () => {
</FormItemLayout>
)}
/>
</CardContent>
<CardContent>
<FormField_Shadcn_
control={databaseForm.control}
name="DB_MAX_POOL_SIZE"
Expand All @@ -353,16 +354,13 @@ export const PerformanceSettingsForm = () => {
layout="flex-row-reverse"
label="Maximum connections"
description={
<>
<p>
Maximum number of connections that the Auth server will take up under
highest load.
</p>
<p>
<em className="text-brand !not-italic">Connections are not reserved</em>{' '}
and returned to Postgres a few minutes after being idle.
</p>
</>
<p className="text-balance">
The maximum number of connections the Auth server can use under peak load.{' '}
<em className="text-foreground-light font-medium not-italic">
Connections are not reserved
</em>{' '}
and are returned to Postgres after a short idle period.
</p>
}
>
<FormControl_Shadcn_>
Expand All @@ -385,16 +383,16 @@ export const PerformanceSettingsForm = () => {
{isLoadingMaxConns ? (
<ShimmeringLoader className="py-2 w-16 ml-auto" />
) : (
<div className="text-xs text-muted w-full text-end">
<span className="text-brand">
<p className="text-xs text-right text-foreground-muted">
<span className="text-foreground-light">
{chosenUnit === 'percent'
? Math.floor(
maxConnectionLimit * (Math.min(100, field.value!) / 100)
).toString()
: Math.min(maxConnectionLimit, field.value!)}
</span>{' '}
/ {maxConnectionLimit} max
</div>
/ {maxConnectionLimit}
</p>
)}
</div>
</FormControl_Shadcn_>
Expand All @@ -410,7 +408,7 @@ export const PerformanceSettingsForm = () => {
</Button>
)}
<Button
type="primary"
type={promptProPlanUpgrade ? 'default' : 'primary'}
htmlType="submit"
disabled={
!canUpdateConfig || isUpdatingDatabaseForm || !databaseForm.formState.isDirty
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQueryClient } from '@tanstack/react-query'
import { DatabaseZap, DollarSign, GitMerge, Github, Loader2 } from 'lucide-react'
import { Check, DatabaseZap, DollarSign, GitMerge, Github, Loader2 } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import { useCallback, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'

import { useDebounce } from '@uidotdev/usehooks'
import { useFlag, useParams } from 'common'
import { useIsBranching2Enabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { BranchingPITRNotice } from 'components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice'
Expand Down Expand Up @@ -72,6 +73,8 @@ export const CreateBranchModal = () => {
const gitlessBranching = useIsBranching2Enabled()
const allowDataBranching = useFlag('allowDataBranching')

const [isGitBranchValid, setIsGitBranchValid] = useState(false)

const { can: canCreateBranch } = useAsyncCheckPermissions(
PermissionAction.CREATE,
'preview_branches'
Expand All @@ -86,52 +89,36 @@ export const CreateBranchModal = () => {
projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined

const formId = 'create-branch-form'
const FormSchema = z
.object({
branchName: z
.string()
.min(1, 'Branch name cannot be empty')
.refine(
(val) => /^[a-zA-Z0-9\-_]+$/.test(val),
'Branch name can only contain alphanumeric characters, hyphens, and underscores.'
)
.refine(
(val) => (branches ?? []).every((branch) => branch.name !== val),
'A branch with this name already exists'
),
gitBranchName: z
.string()
.refine(
(val) => gitlessBranching || !githubConnection || (val && val.length > 0),
'Git branch name is required when GitHub is connected'
),
withData: z.boolean().default(false).optional(),
})
.superRefine(async (val, ctx) => {
if (val.gitBranchName && val.gitBranchName.length > 0 && githubConnection?.repository.id) {
try {
await checkGithubBranchValidity({
repositoryId: githubConnection.repository.id,
branchName: val.gitBranchName,
})
// valid – no issues added
} catch (error) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Unable to find branch "${val.gitBranchName}" in ${repoOwner}/${repoName}`,
path: ['gitBranchName'],
})
}
}
})
const FormSchema = z.object({
branchName: z
.string()
.min(1, 'Branch name cannot be empty')
.refine(
(val) => /^[a-zA-Z0-9\-_]+$/.test(val),
'Branch name can only contain alphanumeric characters, hyphens, and underscores.'
)
.refine(
(val) => (branches ?? []).every((branch) => branch.name !== val),
'A branch with this name already exists'
),
gitBranchName: z
.string()
.refine(
(val) => gitlessBranching || !githubConnection || (val && val.length > 0),
'Git branch name is required when GitHub is connected'
),
withData: z.boolean().default(false).optional(),
})

const form = useForm<z.infer<typeof FormSchema>>({
mode: 'onSubmit',
reValidateMode: 'onBlur',
resolver: zodResolver(FormSchema),
defaultValues: { branchName: '', gitBranchName: '', withData: false },
})
const withData = form.watch('withData')

const { withData, gitBranchName } = form.watch()
const debouncedGitBranchName = useDebounce(gitBranchName, 500)

const {
data: connections,
Expand Down Expand Up @@ -178,7 +165,7 @@ export const CreateBranchModal = () => {

const { mutate: sendEvent } = useSendEventMutation()

const { mutateAsync: checkGithubBranchValidity, isPending: isCheckingGHBranchValidity } =
const { mutate: checkGithubBranchValidity, isPending: isCheckingGHBranchValidity } =
useCheckGithubBranchValidity({
onError: () => {},
})
Expand Down Expand Up @@ -215,8 +202,10 @@ export const CreateBranchModal = () => {
const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
const prodBranch = branches?.find((branch) => branch.is_default)
const [repoOwner, repoName] = githubConnection?.repository.name.split('/') ?? []
const isFormValid = form.formState.isValid && (!gitBranchName || isGitBranchValid)

const isDisabled =
!isFormValid ||
!canCreateBranch ||
!isSuccessAddons ||
!isSuccessConnections ||
Expand All @@ -226,6 +215,44 @@ export const CreateBranchModal = () => {
isCreatingBranch ||
isCheckingGHBranchValidity

const tooltipText = promptPlanUpgrade
? 'Upgrade to unlock branching'
: !gitlessBranching && !githubConnection
? 'Set up a GitHub connection first to create branches'
: undefined

const validateGitBranchName = useCallback(
(branchName: string) => {
if (!githubConnection) {
return console.error(
'[CreateBranchModal > validateGitBranchName] GitHub Connection is missing'
)
}

const repositoryId = githubConnection.repository.id

checkGithubBranchValidity(
{ repositoryId, branchName },
{
onSuccess: () => {
if (form.getValues('gitBranchName') !== branchName) return
setIsGitBranchValid(true)
form.clearErrors('gitBranchName')
},
onError: (error) => {
if (form.getValues('gitBranchName') !== branchName) return
setIsGitBranchValid(false)
form.setError('gitBranchName', {
...error,
message: `Unable to find branch "${branchName}" in ${repoOwner}/${repoName}`,
})
},
}
)
},
[githubConnection, form, checkGithubBranchValidity, repoOwner, repoName]
)

const onSubmit = (data: z.infer<typeof FormSchema>) => {
if (!projectRef) return console.error('Project ref is required')
createBranch({
Expand All @@ -249,6 +276,17 @@ export const CreateBranchModal = () => {
}
}, [form, showCreateBranchModal])

useEffect(() => {
if (!githubConnection || !debouncedGitBranchName) {
setIsGitBranchValid(gitlessBranching)
form.clearErrors('gitBranchName')
return
}

form.clearErrors('gitBranchName')
validateGitBranchName(debouncedGitBranchName)
}, [debouncedGitBranchName, validateGitBranchName, form, githubConnection, gitlessBranching])

return (
<Dialog open={showCreateBranchModal} onOpenChange={(open) => setShowCreateBranchModal(open)}>
<DialogContent
Expand Down Expand Up @@ -336,12 +374,20 @@ export const CreateBranchModal = () => {
{...field}
placeholder="e.g. main, feat/some-feature"
autoComplete="off"
onChange={(e) => {
field.onChange(e)
setIsGitBranchValid(false)
}}
/>
</FormControl_Shadcn_>
<div className="absolute top-2.5 right-3 flex items-center gap-2">
{isCheckingGHBranchValidity && (
<Loader2 size={14} className="animate-spin" />
)}
{field.value ? (
isCheckingGHBranchValidity ? (
<Loader2 size={14} className="animate-spin" />
) : isGitBranchValid ? (
<Check size={14} className="text-brand" strokeWidth={2} />
) : null
) : null}
</div>
</div>
</FormItemLayout>
Expand Down Expand Up @@ -585,15 +631,12 @@ export const CreateBranchModal = () => {
form={formId}
disabled={isDisabled}
loading={isCreatingBranch}
type="primary"
type={promptPlanUpgrade ? 'default' : 'primary'}
htmlType="submit"
tooltip={{
content: {
side: 'bottom',
text:
!gitlessBranching && !githubConnection
? 'Set up a GitHub connection first to create branches'
: undefined,
text: tooltipText,
},
}}
>
Expand Down
Loading
Loading