ProjectUpgradeAlert.tsx 12 KB

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