ProjectUpgradeAlert.tsx292 lines · main
1import { zodResolver } from '@hookform/resolvers/zod'
2import { useFlag, useParams } from 'common'
3import { AlertCircle, AlertTriangle } from 'lucide-react'
4import Link from 'next/link'
5import { useRouter } from 'next/router'
6import { useEffect, useState } from 'react'
7import { useForm } from 'react-hook-form'
8import { toast } from 'sonner'
9import {
10 Alert,
11 AlertDescription,
12 AlertTitle,
13 Badge,
14 Button,
15 Form,
16 FormControl,
17 FormField,
18 Modal,
19 Select,
20 SelectContent,
21 SelectGroup,
22 SelectItem,
23 SelectTrigger,
24 SelectValue,
25 Tooltip,
26 TooltipContent,
27 TooltipTrigger,
28} from 'ui'
29import { Admonition } from 'ui-patterns/admonition'
30import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
31import { z } from 'zod'
32
33import { PLAN_DETAILS } from '@/components/interfaces/DiskManagement/ui/DiskManagement.constants'
34import { Markdown } from '@/components/interfaces/Markdown'
35import { extractPostgresVersionDetails } from '@/components/interfaces/ProjectCreation/PostgresVersionSelector'
36import { useDiskAttributesQuery } from '@/data/config/disk-attributes-query'
37import {
38 ProjectUpgradeTargetVersion,
39 useProjectUpgradeEligibilityQuery,
40} from '@/data/config/project-upgrade-eligibility-query'
41import { useSetProjectStatus } from '@/data/projects/project-detail-query'
42import { useProjectUpgradeMutation } from '@/data/projects/project-upgrade-mutation'
43import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
44import { DOCS_URL, PROJECT_STATUS } from '@/lib/constants'
45
46const formatValue = ({ postgres_version, release_channel }: ProjectUpgradeTargetVersion) => {
47 return `${postgres_version}|${release_channel}`
48}
49
50export const ProjectUpgradeAlert = () => {
51 const router = useRouter()
52 const { ref } = useParams()
53 const { data: org } = useSelectedOrganizationQuery()
54 const { setProjectStatus } = useSetProjectStatus()
55
56 const [showUpgradeModal, setShowUpgradeModal] = useState(false)
57 const projectUpgradeDisabled = useFlag('disableProjectUpgrade')
58
59 const planId = org?.plan.id ?? 'free'
60
61 const { data: diskAttributes } = useDiskAttributesQuery({ projectRef: ref })
62 const { includedDiskGB: includedDiskGBMeta } = PLAN_DETAILS[planId]
63 const includedDiskGB = includedDiskGBMeta[diskAttributes?.attributes.type ?? 'gp3']
64 const isDiskSizeUpdated = diskAttributes?.attributes.size_gb !== includedDiskGB
65
66 const { data } = useProjectUpgradeEligibilityQuery({ projectRef: ref })
67 const currentPgVersion = (data?.current_app_version ?? '').split('briven-postgres-')[1]
68 const latestPgVersion = (data?.latest_app_version ?? '').split('briven-postgres-')[1]
69
70 const durationEstimateHours = data?.duration_estimate_hours || 1
71 const legacyAuthCustomRoles = data?.legacy_auth_custom_roles || []
72
73 const { mutate: upgradeProject, isPending: isUpgrading } = useProjectUpgradeMutation({
74 onSuccess: (res, variables) => {
75 setProjectStatus({ ref: variables.ref, status: PROJECT_STATUS.UPGRADING })
76 toast.success('Upgrading project')
77 router.push(`/project/${variables.ref}?upgradeInitiated=true&trackingId=${res.tracking_id}`)
78 },
79 })
80
81 const onConfirmUpgrade = async (values: z.infer<typeof FormSchema>) => {
82 if (!ref) return toast.error('Project ref not found')
83
84 const { postgresVersionSelection } = values
85
86 const versionDetails = extractPostgresVersionDetails(postgresVersionSelection)
87 if (!versionDetails) return toast.error('Invalid Postgres version')
88 if (!versionDetails.postgresEngine) return toast.error('Missing target version')
89
90 upgradeProject({
91 ref,
92 target_version: versionDetails.postgresEngine,
93 release_channel: versionDetails.releaseChannel,
94 })
95 }
96
97 const FormSchema = z.object({
98 postgresVersionSelection: z.string(),
99 })
100
101 const form = useForm<z.infer<typeof FormSchema>>({
102 resolver: zodResolver(FormSchema as any),
103 mode: 'onChange',
104 defaultValues: {
105 postgresVersionSelection: '',
106 },
107 })
108
109 useEffect(() => {
110 const defaultValue = data?.target_upgrade_versions?.[0]
111 ? formatValue(data.target_upgrade_versions[0])
112 : ''
113 form.setValue('postgresVersionSelection', defaultValue)
114 }, [data, form])
115
116 return (
117 <>
118 <Alert title="Your project can be upgraded to the latest version of Postgres">
119 <AlertTitle>Your project can be upgraded to the latest version of Postgres</AlertTitle>
120 <AlertDescription>
121 <p>The latest version of Postgres ({latestPgVersion}) is available for your project.</p>
122 <Tooltip>
123 <TooltipTrigger asChild>
124 <Button
125 size="tiny"
126 type="primary"
127 className="mt-2"
128 onClick={() => setShowUpgradeModal(true)}
129 disabled={projectUpgradeDisabled}
130 >
131 Upgrade project
132 </Button>
133 </TooltipTrigger>
134 {projectUpgradeDisabled && (
135 <TooltipContent side="bottom" align="center">
136 Project upgrade is currently disabled
137 </TooltipContent>
138 )}
139 </Tooltip>
140 </AlertDescription>
141 </Alert>
142
143 <Modal
144 hideFooter
145 size="small"
146 visible={showUpgradeModal}
147 onCancel={() => setShowUpgradeModal(false)}
148 header="Confirm to upgrade Postgres version"
149 >
150 <Form {...form}>
151 <form onSubmit={form.handleSubmit(onConfirmUpgrade)}>
152 <Admonition
153 type="warning"
154 className="border-x-0 border-t-0 rounded-none"
155 title={`Your project will be offline for up to ${durationEstimateHours} hour${durationEstimateHours === 1 ? '' : 's'}`}
156 description="It is advised to upgrade at a time when there will be minimal impact for your application."
157 />
158 <Modal.Content>
159 <div className="space-y-4">
160 <p className="text-sm">
161 All services will be offline and you will not be able to downgrade back to
162 Postgres {currentPgVersion}.
163 </p>
164 {isDiskSizeUpdated && (
165 <Markdown
166 extLinks
167 className="text-foreground"
168 content={`Your current disk size of ${diskAttributes?.attributes.size_gb}GB will also be
169 [right-sized](${DOCS_URL}/guides/platform/upgrading#disk-sizing) with the upgrade.`}
170 />
171 )}
172 {/* @ts-ignore */}
173 {(data?.potential_breaking_changes ?? []).length > 0 && (
174 <Alert variant="destructive" title="Breaking changes">
175 <AlertCircle className="h-4 w-4" strokeWidth={2} />
176 <AlertTitle>Breaking changes</AlertTitle>
177 <AlertDescription className="flex flex-col gap-3">
178 <p>
179 Your project will be upgraded across major versions of Postgres. This may
180 involve breaking changes.
181 </p>
182
183 <div>
184 <Button size="tiny" type="default" asChild>
185 <Link
186 href={`${DOCS_URL}/guides/platform/migrating-and-upgrading-projects#caveats`}
187 target="_blank"
188 rel="noreferrer"
189 >
190 View docs
191 </Link>
192 </Button>
193 </div>
194 </AlertDescription>
195 </Alert>
196 )}
197 {legacyAuthCustomRoles.length > 0 && (
198 <Alert
199 variant="warning"
200 title="Custom Postgres roles using md5 authentication have been detected"
201 >
202 <AlertTriangle className="h-4 w-4" strokeWidth={2} />
203 <AlertTitle>
204 Custom Postgres roles will not work automatically after upgrade
205 </AlertTitle>
206 <AlertDescription className="flex flex-col gap-3">
207 <p>You must run a series of commands after upgrading.</p>
208 <p>
209 This is because new Postgres versions use scram-sha-256 authentication by
210 default and do not support md5, as it has been deprecated.
211 </p>
212 <div>
213 <p className="mb-1">Run the following commands after the upgrade:</p>
214 <div className="flex items-baseline gap-2">
215 <code className="text-xs">
216 {legacyAuthCustomRoles.map((role) => (
217 <div key={role} className="pb-1">
218 ALTER ROLE <span className="text-brand">{role}</span> WITH PASSWORD
219 '<span className="text-brand">newpassword</span>';
220 </div>
221 ))}
222 </code>
223 </div>
224 </div>
225 <div>
226 <Button size="tiny" type="default" asChild>
227 <Link
228 href={`${DOCS_URL}/guides/platform/migrating-and-upgrading-projects#caveats`}
229 target="_blank"
230 rel="noreferrer"
231 >
232 View docs
233 </Link>
234 </Button>
235 </div>
236 </AlertDescription>
237 </Alert>
238 )}
239 <FormField
240 control={form.control}
241 name="postgresVersionSelection"
242 render={({ field }) => (
243 <FormItemLayout label="Select the version of Postgres to upgrade to">
244 <FormControl>
245 <Select value={field.value} onValueChange={field.onChange}>
246 <SelectTrigger>
247 <SelectValue placeholder="Select a Postgres version" />
248 </SelectTrigger>
249 <SelectContent>
250 <SelectGroup>
251 {(data?.target_upgrade_versions || [])?.map((value) => {
252 const postgresVersion =
253 value.app_version.split('briven-postgres-')[1]
254 return (
255 <SelectItem key={formatValue(value)} value={formatValue(value)}>
256 <div className="flex items-center gap-3">
257 <span className="text-foreground">{postgresVersion}</span>
258 {value.release_channel !== 'ga' && (
259 <Badge variant="warning">{value.release_channel}</Badge>
260 )}
261 </div>
262 </SelectItem>
263 )
264 })}
265 </SelectGroup>
266 </SelectContent>
267 </Select>
268 </FormControl>
269 </FormItemLayout>
270 )}
271 />
272 </div>
273 </Modal.Content>
274 <Modal.Separator />
275 <Modal.Content className="flex items-center space-x-2 justify-end">
276 <Button
277 type="default"
278 onClick={() => setShowUpgradeModal(false)}
279 disabled={isUpgrading}
280 >
281 Cancel
282 </Button>
283 <Button htmlType="submit" disabled={isUpgrading} loading={isUpgrading}>
284 Confirm upgrade
285 </Button>
286 </Modal.Content>
287 </form>
288 </Form>
289 </Modal>
290 </>
291 )
292}