Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: Queues v0 (#30300)

Ivan Vasilov54d11a6a7f6a
diff --git a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
index 55da43b43fe..1c61bf21c79 100644
--- a/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/UserOverview.tsx
@@ -465,7 +465,7 @@ export const UserOverview = ({ user, onDeleteSuccess }: UserOverviewProps) => {
)
}
-const RowData = ({ property, value }: { property: string; value?: string | boolean }) => {
+export const RowData = ({ property, value }: { property: string; value?: string | boolean }) => {
return (
<div className="flex items-center gap-x-2 group">
<p className="w-36 text-foreground-light text-sm">{property}</p>
@@ -499,7 +499,7 @@ const RowData = ({ property, value }: { property: string; value?: string | boole
)
}
-const RowAction = ({
+export const RowAction = ({
title,
description,
button,
diff --git a/apps/studio/components/interfaces/Integrations/Queues/CreateQueueSheet.tsx b/apps/studio/components/interfaces/Integrations/Queues/CreateQueueSheet.tsx
new file mode 100644
index 00000000000..41622dc9eea
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/CreateQueueSheet.tsx
@@ -0,0 +1,341 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useState } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import z from 'zod'
+
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import EnableExtensionModal from 'components/interfaces/Database/Extensions/EnableExtensionModal'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { useDatabaseQueueCreateMutation } from 'data/database-queues/database-queues-create-mutation'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import {
+ Badge,
+ Button,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Input,
+ Input_Shadcn_,
+ RadioGroupStacked,
+ RadioGroupStackedItem,
+ Separator,
+ SheetFooter,
+ SheetHeader,
+ SheetSection,
+ SheetTitle,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { QUEUE_TYPES } from './Queues.constants'
+
+export interface CreateQueueSheetProps {
+ isClosing: boolean
+ setIsClosing: (v: boolean) => void
+ onClose: () => void
+}
+
+const normalQueueSchema = z.object({
+ type: z.literal('normal'),
+})
+
+const partitionedQueueSchema = z.object({
+ type: z.literal('partitioned'),
+ partitionInterval: z.number(),
+ retentionInterval: z.number(),
+})
+
+const unloggedQueueSchema = z.object({
+ type: z.literal('unlogged'),
+})
+
+const FormSchema = z.object({
+ name: z
+ .string()
+ .trim()
+ .min(1, 'Please provide a name for your queue')
+ .max(47, "The name can't be longer than 47 characters"),
+ values: z.discriminatedUnion('type', [
+ normalQueueSchema,
+ partitionedQueueSchema,
+ unloggedQueueSchema,
+ ]),
+})
+
+export type CreateQueueForm = z.infer<typeof FormSchema>
+export type QueueType = CreateQueueForm['values']
+
+const FORM_ID = 'create-queue-sidepanel'
+
+export const CreateQueueSheet = ({ isClosing, setIsClosing, onClose }: CreateQueueSheetProps) => {
+ const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
+ const { mutate: createQueue, isLoading } = useDatabaseQueueCreateMutation()
+
+ const canToggleExtensions = useCheckPermissions(
+ PermissionAction.TENANT_SQL_ADMIN_WRITE,
+ 'extensions'
+ )
+
+ const form = useForm<CreateQueueForm>({
+ resolver: zodResolver(FormSchema),
+ defaultValues: {
+ name: '',
+ values: {
+ type: 'normal',
+ },
+ },
+ })
+
+ const { project } = useProjectContext()
+ const isEdited = form.formState.isDirty
+
+ // if the form hasn't been touched and the user clicked esc or the backdrop, close the sheet
+ if (!isEdited && isClosing) {
+ onClose()
+ }
+
+ const onClosePanel = () => {
+ if (isEdited) {
+ setIsClosing(true)
+ } else {
+ onClose()
+ }
+ }
+
+ const onSubmit: SubmitHandler<CreateQueueForm> = async ({ name, values }) => {
+ let query = `SELECT pgmq.create('${name}');`
+ if (values.type === 'partitioned') {
+ query = `select from pgmq.create_partitioned('${name}', '${values.partitionInterval}', '${values.retentionInterval}');`
+ }
+ if (values.type === 'unlogged') {
+ query = `SELECT pgmq.create_unlogged('${name}');`
+ }
+
+ createQueue(
+ {
+ projectRef: project!.ref,
+ connectionString: project?.connectionString,
+ query,
+ },
+ {
+ onSuccess: () => {
+ toast.success(`Successfully created queue ${name}`)
+ onClose()
+ },
+ }
+ )
+ }
+
+ const { data } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const pgPartmanExtension = (data ?? []).find((ext) => ext.name === 'pg_partman')
+ const pgPartmanExtensionInstalled = pgPartmanExtension?.installed_version != undefined
+
+ const queueType = form.watch('values.type')
+
+ return (
+ <>
+ <div className="flex flex-col h-full" tabIndex={-1}>
+ <SheetHeader>
+ <SheetTitle>Create a new queue</SheetTitle>
+ </SheetHeader>
+
+ <div className="overflow-auto flex-grow">
+ <Form_Shadcn_ {...form}>
+ <form
+ id={FORM_ID}
+ className="flex-grow overflow-auto"
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ <SheetSection>
+ <FormField_Shadcn_
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItemLayout label="Name" layout="vertical" className="gap-1">
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ <Separator />
+ <SheetSection>
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.type"
+ render={({ field }) => (
+ <FormItemLayout label="Type" layout="vertical" className="gap-1">
+ <FormControl_Shadcn_>
+ <RadioGroupStacked
+ id="queue_type"
+ name="queue_type"
+ value={field.value}
+ disabled={field.disabled}
+ onValueChange={field.onChange}
+ >
+ {QUEUE_TYPES.map((definition) => (
+ <RadioGroupStackedItem
+ key={definition.value}
+ id={definition.value}
+ value={definition.value}
+ label=""
+ disabled={
+ !pgPartmanExtensionInstalled && definition.value === 'partitioned'
+ }
+ showIndicator={false}
+ >
+ <div className="flex items-center gap-x-5">
+ <div className="text-foreground">{definition.icon}</div>
+ <div className="flex flex-col">
+ <div className="flex gap-x-2">
+ <p className="text-foreground">{definition.label}</p>
+ </div>
+ <p className="text-foreground-light text-left">
+ {definition.description}
+ </p>
+ </div>
+ </div>
+ {definition.value === 'partitioned' ? (
+ <div className="pt-2 pl-10">
+ <Badge variant="warning">COMING SOON</Badge>
+ </div>
+ ) : null}
+ {/* {!pgPartmanExtensionInstalled &&
+ definition.value === 'partitioned' ? (
+ <div className="w-full flex gap-x-2 pl-11 py-2 items-center">
+ <WarningIcon />
+ <span className="text-xs">
+ <code>pg_partman</code> needs to be installed to use this type
+ </span>
+ </div>
+ ) : null} */}
+ </RadioGroupStackedItem>
+ ))}
+ </RadioGroupStacked>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ {/* {!pgPartmanExtensionInstalled && (
+ <Admonition
+ type="note"
+ // @ts-ignore
+ title={
+ <span>
+ Enable <code className="text-xs w-min">pg_partman</code> for partitioned
+ queues
+ </span>
+ }
+ description={
+ <div className="flex flex-col gap-y-2">
+ <span>
+ This will allow you to create partitioned queues which can handle a large
+ amount of messages
+ </span>
+ <ButtonTooltip
+ type="default"
+ className="w-min"
+ disabled={!canToggleExtensions}
+ onClick={() => setShowEnableExtensionModal(true)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: 'You need additional permissions to enable database extensions',
+ },
+ }}
+ >
+ Install pg_partman extension
+ </ButtonTooltip>
+ </div>
+ }
+ />
+ )} */}
+ </SheetSection>
+ <Separator />
+ {queueType === 'partitioned' && (
+ <>
+ <SheetSection className="flex flex-col gap-3">
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.partitionInterval"
+ render={({ field: { ref, ...rest } }) => (
+ <FormItemLayout label="Partition interval" className="gap-1">
+ <Input
+ {...rest}
+ type="number"
+ placeholder="1000"
+ actions={<p className="text-foreground-light pr-2">ms</p>}
+ />
+ </FormItemLayout>
+ )}
+ />
+ <FormField_Shadcn_
+ control={form.control}
+ name="values.retentionInterval"
+ render={({ field: { ref, ...rest } }) => (
+ <FormItemLayout label="Retention interval" className="gap-1">
+ <Input
+ {...rest}
+ type="number"
+ placeholder="1000"
+ actions={<p className="text-foreground-light pr-2">ms</p>}
+ />
+ </FormItemLayout>
+ )}
+ />
+ </SheetSection>
+ </>
+ )}
+ </form>
+ </Form_Shadcn_>
+ </div>
+ <SheetFooter>
+ <Button
+ size="tiny"
+ type="default"
+ htmlType="button"
+ onClick={onClosePanel}
+ disabled={isLoading}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="tiny"
+ type="primary"
+ form={FORM_ID}
+ htmlType="submit"
+ disabled={isLoading}
+ loading={isLoading}
+ >
+ Create queue
+ </Button>
+ </SheetFooter>
+ </div>
+ <ConfirmationModal
+ visible={isClosing}
+ title="Discard changes"
+ confirmLabel="Discard"
+ onCancel={() => setIsClosing(false)}
+ onConfirm={() => onClose()}
+ >
+ <p className="text-sm text-foreground-light">
+ There are unsaved changes. Are you sure you want to close the panel? Your changes will be
+ lost.
+ </p>
+ </ConfirmationModal>
+ {pgPartmanExtension && (
+ <EnableExtensionModal
+ visible={showEnableExtensionModal}
+ extension={pgPartmanExtension}
+ onCancel={() => setShowEnableExtensionModal(false)}
+ />
+ )}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Queues/Queues.constants.tsx b/apps/studio/components/interfaces/Integrations/Queues/Queues.constants.tsx
new file mode 100644
index 00000000000..6ba001477a5
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/Queues.constants.tsx
@@ -0,0 +1,23 @@
+import { Rows2, Rows3, Rows4 } from 'lucide-react'
+
+export const QUEUE_TYPES = [
+ {
+ value: 'normal',
+ icon: <Rows4 strokeWidth={1} />,
+ label: 'Normal queue',
+ description: 'Create a normal queue.',
+ },
+ {
+ value: 'partitioned',
+ icon: <Rows3 strokeWidth={1} />,
+ label: 'Partitioned queue',
+ description: 'Create a partitioned queue which is optimized for large amount of messages',
+ },
+
+ {
+ value: 'unlogged',
+ icon: <Rows2 strokeWidth={1} />,
+ label: 'Unlogged queue',
+ description: 'Creates an unlogged queue which loses all data on database restart.',
+ },
+] as const
diff --git a/apps/studio/components/interfaces/Integrations/Queues/QueuesDisabledState.tsx b/apps/studio/components/interfaces/Integrations/Queues/QueuesDisabledState.tsx
new file mode 100644
index 00000000000..ad4331f6706
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/QueuesDisabledState.tsx
@@ -0,0 +1,88 @@
+import * as Tooltip from '@radix-ui/react-tooltip'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { ExternalLink } from 'lucide-react'
+import Link from 'next/link'
+import { useState } from 'react'
+
+import EnableExtensionModal from 'components/interfaces/Database/Extensions/EnableExtensionModal'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { Button } from 'ui'
+
+export const QueuesDisabledState = () => {
+ const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
+ const { project } = useProjectContext()
+ const canToggleExtensions = useCheckPermissions(
+ PermissionAction.TENANT_SQL_ADMIN_WRITE,
+ 'extensions'
+ )
+
+ const { data } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const pgmqExtension = (data ?? []).find((ext) => ext.name === 'pgmq')
+
+ if (!pgmqExtension) return null
+
+ return (
+ <>
+ <div className="w-full h-full flex items-center justify-center">
+ <ProductEmptyState title="Queues">
+ <div className="text-sm text-foreground-light mb-4 grid gap-2">
+ <p>
+ Message queues in PostgreSQL allow you to handle asynchronous tasks, manage workloads,
+ and enable reliable communication between different parts of your application.
+ </p>
+ <p>Enable queues in your project.</p>
+ </div>
+
+ <div className="flex items-center gap-3 mt-4">
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ <Button type="primary" onClick={() => setShowEnableExtensionModal(true)}>
+ Enable Queues
+ </Button>
+ </Tooltip.Trigger>
+ {!canToggleExtensions && (
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground">
+ You need additional permissions to enable pgmq for this project
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ )}
+ </Tooltip.Root>
+ <Button asChild type="text" icon={<ExternalLink />}>
+ <Link
+ href="https://supabase.com/docs/guides/database/extensions/pgmq"
+ target="_blank"
+ rel="noreferrer"
+ >
+ Documentation
+ </Link>
+ </Button>
+ </div>
+ </ProductEmptyState>
+ </div>
+
+ <EnableExtensionModal
+ visible={showEnableExtensionModal}
+ extension={pgmqExtension}
+ onCancel={() => setShowEnableExtensionModal(false)}
+ />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Queues/QueuesListing.tsx b/apps/studio/components/interfaces/Integrations/Queues/QueuesListing.tsx
new file mode 100644
index 00000000000..f34ad985e9d
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/QueuesListing.tsx
@@ -0,0 +1,134 @@
+import { useEffect, useState } from 'react'
+
+import EnableExtensionModal from 'components/interfaces/Database/Extensions/EnableExtensionModal'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import Table from 'components/to-be-cleaned/Table'
+import AlertError from 'components/ui/AlertError'
+import { FormHeader } from 'components/ui/Forms/FormHeader'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
+import { useQueuesQuery } from 'data/database-queues/database-queues-query'
+import { Search } from 'lucide-react'
+import { useQueryState } from 'nuqs'
+import { Button, Input, Sheet, SheetContent } from 'ui'
+import { CreateQueueSheet } from './CreateQueueSheet'
+import { QueuesDisabledState } from './QueuesDisabledState'
+import { QueuesRows } from './QueuesRows'
+
+export const QueuesListing = () => {
+ const { project } = useProjectContext()
+
+ const [showEnableExtensionModal, setShowEnableExtensionModal] = useState(false)
+ // used for confirmation prompt in the Create Queue Sheet
+ const [isClosingCreateQueueSheet, setIsClosingCreateQueueSheet] = useState(false)
+ const [createQueueSheetShown, setCreateQueueSheetShown] = useState(false)
+
+ const {
+ data: queues,
+ error,
+ isLoading,
+ isError,
+ refetch,
+ } = useQueuesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { data: extensions, isLoading: isLoadingExtensions } = useDatabaseExtensionsQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ })
+
+ const pgmqExtension = (extensions ?? []).find((ext) => ext.name === 'pgmq')
+ // TODO: Change this to true for local development to work
+ const pgmqExtensionInstalled = pgmqExtension?.installed_version
+
+ useEffect(() => {
+ // refetch the queues after the pgmq extension has been installed
+ if (pgmqExtensionInstalled && isError) {
+ refetch()
+ }
+ }, [isError, pgmqExtensionInstalled, refetch])
+
+ const [searchQuery, setSearchQuery] = useQueryState('search')
+
+ // this avoid showing loading screen when the extension is not installed. Otherwise, we'll have to wait for three
+ // retries (which are sure to fail because the extension is not installed)
+ if (isLoadingExtensions) return <GenericSkeletonLoader />
+ if (!pgmqExtensionInstalled) return <QueuesDisabledState />
+ if (isLoading) return <GenericSkeletonLoader />
+ if (isError) return <AlertError error={error} subject="Failed to retrieve database queues" />
+
+ return (
+ <>
+ <div className="w-full space-y-4">
+ <FormHeader
+ title="Queues"
+ description="Use message queues to handle asynchronous tasks, manage workloads, and enable reliable communication between different parts of your application."
+ />
+ {queues.length === 0 ? (
+ <div
+ className={
+ 'border rounded border-default px-20 py-16 flex flex-col items-center justify-center space-y-4'
+ }
+ >
+ <p className="text-sm text-foreground-light">No queues created yet</p>
+ <Button onClick={() => setCreateQueueSheetShown(true)}>Add a new queue</Button>
+ </div>
+ ) : (
+ <div className="w-full space-y-4">
+ <div className="flex items-center justify-between flex-wrap">
+ <Input
+ placeholder="Search for a queue"
+ size="small"
+ icon={<Search size={14} />}
+ value={searchQuery || ''}
+ className="w-64"
+ onChange={(e) => setSearchQuery(e.target.value)}
+ />
+
+ <Button onClick={() => setCreateQueueSheetShown(true)}>Create a queue</Button>
+ </div>
+
+ <Table
+ className="table-fixed overflow-x-auto"
+ head={
+ <>
+ <Table.th key="name">Name</Table.th>
+ <Table.th key="arguments" className="table-cell">
+ Type
+ </Table.th>
+ <Table.th key="created_at" className="table-cell">
+ Created at
+ </Table.th>
+ <Table.th key="buttons" className="table-cell"></Table.th>
+ </>
+ }
+ body={<QueuesRows queues={queues} filterString={searchQuery || ''} />}
+ />
+ </div>
+ )}
+ </div>
+
+ <Sheet open={createQueueSheetShown} onOpenChange={() => setIsClosingCreateQueueSheet(true)}>
+ <SheetContent size="default" tabIndex={undefined}>
+ <CreateQueueSheet
+ onClose={() => {
+ setIsClosingCreateQueueSheet(false)
+ setCreateQueueSheetShown(false)
+ }}
+ isClosing={isClosingCreateQueueSheet}
+ setIsClosing={setIsClosingCreateQueueSheet}
+ />
+ </SheetContent>
+ </Sheet>
+ {pgmqExtension ? (
+ <EnableExtensionModal
+ visible={showEnableExtensionModal}
+ extension={pgmqExtension}
+ onCancel={() => setShowEnableExtensionModal(false)}
+ />
+ ) : null}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Queues/QueuesRows.tsx b/apps/studio/components/interfaces/Integrations/Queues/QueuesRows.tsx
new file mode 100644
index 00000000000..ec68ed69772
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/QueuesRows.tsx
@@ -0,0 +1,70 @@
+import dayjs from 'dayjs'
+import { includes, sortBy } from 'lodash'
+import { ChevronRight } from 'lucide-react'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import Table from 'components/to-be-cleaned/Table'
+import { PostgresQueue } from 'data/database-queues/database-queues-query'
+import { DATETIME_FORMAT } from 'lib/constants'
+import { useRouter } from 'next/router'
+
+interface QueuesRowsProps {
+ queues: PostgresQueue[]
+ filterString: string
+}
+
+export const QueuesRows = ({ queues: fetchedQueues, filterString }: QueuesRowsProps) => {
+ const router = useRouter()
+ const { project: selectedProject } = useProjectContext()
+
+ const filteredQueues = fetchedQueues.filter((x) =>
+ includes(x.queue_name.toLowerCase(), filterString.toLowerCase())
+ )
+ const queues = sortBy(filteredQueues, (func) => func.queue_name.toLocaleLowerCase())
+
+ if (queues.length === 0 && filterString.length > 0) {
+ return (
+ <Table.tr>
+ <Table.td colSpan={4}>
+ <p className="text-sm text-foreground">No results found</p>
+ <p className="text-sm text-foreground-light">
+ Your search for "{filterString}" did not return any results
+ </p>
+ </Table.td>
+ </Table.tr>
+ )
+ }
+
+ return (
+ <>
+ {queues.map((q) => {
+ const type = q.is_partitioned ? 'Partitioned' : q.is_unlogged ? 'Unlogged' : 'Regular'
+
+ return (
+ <Table.tr
+ key={q.queue_name}
+ onClick={() => {
+ router.push(`/project/${selectedProject?.ref}/integrations/queues/${q.queue_name}`)
+ }}
+ className="hover:"
+ >
+ <Table.td className="truncate">
+ <p title={q.queue_name}>{q.queue_name}</p>
+ </Table.td>
+ <Table.td className="table-cell overflow-auto">
+ <p title={type.toLocaleLowerCase()} className="truncate">
+ {type}
+ </p>
+ </Table.td>
+ <Table.td className="table-cell">
+ <p title={q.created_at}>{dayjs(q.created_at).format(DATETIME_FORMAT)}</p>
+ </Table.td>
+ <Table.td className="flex items-center justify-end">
+ <ChevronRight />
+ </Table.td>
+ </Table.tr>
+ )
+ })}
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/DeleteQueue.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/DeleteQueue.tsx
new file mode 100644
index 00000000000..20c9e6812f8
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/DeleteQueue.tsx
@@ -0,0 +1,62 @@
+import { useRouter } from 'next/router'
+import { toast } from 'sonner'
+
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDatabaseQueueDeleteMutation } from 'data/database-queues/database-queues-delete-mutation'
+import TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'
+
+interface DeleteQueueProps {
+ queueName: string
+ visible: boolean
+ onClose: () => void
+}
+
+const DeleteQueue = ({ queueName, visible, onClose }: DeleteQueueProps) => {
+ const { project } = useProjectContext()
+ const router = useRouter()
+
+ const { mutate: deleteDatabaseQueue, isLoading } = useDatabaseQueueDeleteMutation({
+ onSuccess: () => {
+ toast.success(`Successfully removed queue ${queueName}`)
+ router.push(`/project/${project?.ref}/integrations/queues`)
+ onClose()
+ },
+ })
+
+ async function handleDelete() {
+ if (!project) return console.error('Project is required')
+
+ deleteDatabaseQueue({
+ queueName: queueName,
+ projectRef: project.ref,
+ connectionString: project.connectionString,
+ })
+ }
+
+ if (!queueName) {
+ return null
+ }
+
+ return (
+ <TextConfirmModal
+ variant="destructive"
+ visible={visible}
+ onCancel={() => onClose()}
+ onConfirm={handleDelete}
+ title="Delete this queue"
+ loading={isLoading}
+ confirmLabel={`Delete queue ${queueName}`}
+ confirmPlaceholder="Type in name of queue"
+ confirmString={queueName ?? 'Unknown'}
+ text={
+ <>
+ <span>This will delete the queue</span>{' '}
+ <span className="text-bold text-foreground">{queueName}</span>
+ </>
+ }
+ alert={{ title: 'You cannot recover this queue and its messages once deleted.' }}
+ />
+ )
+}
+
+export default DeleteQueue
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx
new file mode 100644
index 00000000000..e7fed0b97e2
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/MessageDetailsPanel.tsx
@@ -0,0 +1,148 @@
+import { isNil, noop } from 'lodash'
+import { Archive, X } from 'lucide-react'
+import { useState } from 'react'
+
+import { useParams } from 'common'
+import { MonacoEditor } from 'components/grid/components/common/MonacoEditor'
+import { RowAction, RowData } from 'components/interfaces/Auth/Users/UserOverview'
+import { useDatabaseQueueMessageArchiveMutation } from 'data/database-queues/database-queue-messages-archive-mutation'
+import { PostgresQueueMessage } from 'data/database-queues/database-queue-messages-infinite-query'
+import dayjs from 'dayjs'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { prettifyJSON } from 'lib/helpers'
+import {
+ Button,
+ ResizablePanel,
+ Separator,
+ Tabs_Shadcn_,
+ TabsContent_Shadcn_,
+ TabsList_Shadcn_,
+ TabsTrigger_Shadcn_,
+} from 'ui'
+
+export const DATE_FORMAT = 'DD MMM, YYYY HH:mm'
+
+interface MessageDetailsPanelProps {
+ selectedMessage: PostgresQueueMessage
+ setSelectedMessage: (value: number | null) => void
+}
+
+const tryFormatInitialValue = (value: string) => {
+ try {
+ const jsonValue = JSON.parse(value)
+ return JSON.stringify(jsonValue)
+ } catch (err) {
+ if (typeof value === 'string') {
+ return value.replaceAll(`\"`, `"`)
+ } else {
+ return JSON.stringify(value)
+ }
+ }
+}
+
+export const MessageDetailsPanel = ({
+ selectedMessage,
+ setSelectedMessage,
+}: MessageDetailsPanelProps) => {
+ const { id: _id } = useParams()
+ const { name: queueName } = useParams()
+ const project = useSelectedProject()
+
+ const { mutate, isLoading, isSuccess } = useDatabaseQueueMessageArchiveMutation()
+
+ const initialValue = JSON.stringify(selectedMessage?.message)
+ const jsonString = prettifyJSON(!isNil(initialValue) ? tryFormatInitialValue(initialValue) : '')
+
+ const [view, setView] = useState<'details' | 'suggestion'>('details')
+
+ return (
+ <ResizablePanel
+ defaultSize={30}
+ maxSize={45}
+ minSize={30}
+ collapsible
+ onCollapse={() => setSelectedMessage(null)}
+ className="bg-studio border-t pointer-events-auto"
+ >
+ <Button
+ type="text"
+ className="absolute top-3 right-3 px-1"
+ icon={<X />}
+ onClick={() => setSelectedMessage(null)}
+ />
+
+ <Tabs_Shadcn_
+ value={view}
+ className="flex flex-col h-full"
+ onValueChange={(value: any) => {
+ setView(value)
+ }}
+ >
+ <TabsList_Shadcn_ className="px-5 flex gap-x-4 min-h-[46px]">
+ <TabsTrigger_Shadcn_
+ value="details"
+ className="px-0 pb-0 h-full text-xs data-[state=active]:bg-transparent !shadow-none"
+ >
+ Overview
+ </TabsTrigger_Shadcn_>
+ </TabsList_Shadcn_>
+ <TabsContent_Shadcn_ value="details" className="w-full mt-0 overflow-y-auto grow">
+ <div className="flex flex-col px-4 py-4 text-sm">
+ <RowData property="Message ID" value={`${selectedMessage.msg_id}`} />
+ <RowData
+ property="Added at"
+ value={dayjs(selectedMessage.enqueued_at).format(DATE_FORMAT)}
+ />
+ <RowData
+ property="Available at"
+ value={dayjs(selectedMessage.vt).format(DATE_FORMAT)}
+ />
+ <RowData property="Retries" value={`${selectedMessage.read_ct}`} />
+
+ <div>
+ <h3 className="text-foreground-light pt-1">Payload</h3>
+ <MonacoEditor
+ key={selectedMessage.msg_id}
+ onChange={noop}
+ width="100%"
+ value={jsonString || 'NULL'}
+ language="json"
+ readOnly
+ />
+ </div>
+ </div>
+ <Separator />
+ <div className="flex flex-col px-4 py-4">
+ {!selectedMessage.archived_at ? (
+ <RowAction
+ title="Archive message"
+ description="The message will be marked as archived and hidden from future reads by consumers"
+ button={{
+ icon: <Archive />,
+ text: 'Archive',
+ isLoading: isLoading,
+ onClick: () => {
+ mutate({
+ projectRef: project!.ref,
+ connectionString: project?.connectionString,
+ queryName: queueName!,
+ messageId: selectedMessage.msg_id,
+ })
+ },
+ }}
+ success={
+ isSuccess
+ ? {
+ title: 'Archived',
+ description: 'The message is archived successfully.',
+ }
+ : undefined
+ }
+ />
+ ) : null}
+ </div>
+ </TabsContent_Shadcn_>
+ </Tabs_Shadcn_>
+ </ResizablePanel>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/Queue.utils.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/Queue.utils.tsx
new file mode 100644
index 00000000000..3f72dc4ede4
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/Queue.utils.tsx
@@ -0,0 +1,9 @@
+import { capitalize } from 'lodash'
+
+export const QUEUE_MESSAGE_TYPES = ['archived', 'available', 'scheduled'] as const
+export type QUEUE_MESSAGE_TYPE = (typeof QUEUE_MESSAGE_TYPES)[number]
+
+export const QUEUE_MESSAGE_OPTIONS = QUEUE_MESSAGE_TYPES.map((type) => ({
+ id: type,
+ name: capitalize(type),
+}))
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueDataGrid.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueDataGrid.tsx
new file mode 100644
index 00000000000..e5e30783d41
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueDataGrid.tsx
@@ -0,0 +1,214 @@
+import dayjs from 'dayjs'
+import { TextSearch } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { parseAsInteger, useQueryState } from 'nuqs'
+import { UIEvent, useMemo, useRef } from 'react'
+import DataGrid, { Column, DataGridHandle, Row } from 'react-data-grid'
+
+import { PostgresQueueMessage } from 'data/database-queues/database-queue-messages-infinite-query'
+import { Badge, ResizableHandle, ResizablePanel, ResizablePanelGroup, cn } from 'ui'
+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
+import { DATE_FORMAT, MessageDetailsPanel } from './MessageDetailsPanel'
+
+interface QueueDataGridProps {
+ isLoading: boolean
+ messages: PostgresQueueMessage[]
+ fetchNextPage: () => void
+}
+
+function isAtBottom({ currentTarget }: React.UIEvent<HTMLDivElement>): boolean {
+ return currentTarget.scrollTop + 10 >= currentTarget.scrollHeight - currentTarget.clientHeight
+}
+
+const messagesCols = [
+ {
+ id: 'id',
+ name: 'ID',
+ description: undefined,
+ minWidth: 50,
+ width: 70,
+ value: (row: PostgresQueueMessage) => (
+ <div className="flex items-center gap-1.5">
+ <h3 className="text-xs">{row.msg_id}</h3>
+ </div>
+ ),
+ },
+ {
+ id: 'enqueued_at',
+ name: 'Added at',
+ description: undefined,
+ minWidth: 160,
+ width: 180,
+ value: (row: PostgresQueueMessage) => (
+ <div className="flex items-center gap-1 text-xs">
+ {dayjs(row.enqueued_at).format(DATE_FORMAT)}
+ </div>
+ ),
+ },
+ {
+ id: 'status',
+ name: 'Status',
+ description: undefined,
+ minWidth: 280,
+ width: 300,
+ value: (row: PostgresQueueMessage) => {
+ const isAvailable = new Date() > new Date(row.vt)
+
+ if (row.archived_at) {
+ return (
+ <Badge variant="default">Archived at {dayjs(row.archived_at).format(DATE_FORMAT)}</Badge>
+ )
+ }
+
+ return (
+ <Badge variant={isAvailable ? 'brand' : 'warning'}>
+ {isAvailable ? 'Available ' : `Available at ${dayjs(row.vt).format(DATE_FORMAT)}`}
+ </Badge>
+ )
+ },
+ },
+ {
+ id: 'retries',
+ name: 'Retries',
+ description: undefined,
+ minWidth: 50,
+ width: 70,
+ value: (row: PostgresQueueMessage) => <span>{row.read_ct}</span>,
+ },
+ {
+ id: 'payload',
+ name: 'Payload',
+ description: undefined,
+ minWidth: 600,
+ value: (row: PostgresQueueMessage) => <span>{JSON.stringify(row.message)}</span>,
+ },
+]
+
+const columns = messagesCols.map((col) => {
+ const result: Column<PostgresQueueMessage> = {
+ key: col.id,
+ name: col.name,
+ resizable: true,
+ minWidth: col.minWidth ?? 120,
+ width: col.width,
+ headerCellClass: 'first:pl-6 cursor-pointer',
+ renderHeaderCell: () => {
+ return (
+ <div className="flex items-center justify-between font-normal text-xs w-full">
+ <div className="flex items-center gap-x-2">
+ <p className="!text-foreground">{col.name}</p>
+ {col.description && <p className="text-foreground-lighter">{col.description}</p>}
+ </div>
+ </div>
+ )
+ },
+ renderCell: (props) => {
+ const value = col.value(props.row)
+
+ return (
+ <div
+ className={cn(
+ 'w-full flex flex-col justify-center font-mono text-xs',
+ typeof value === 'number' ? 'text-right' : ''
+ )}
+ >
+ <span>{value}</span>
+ </div>
+ )
+ },
+ }
+ return result
+})
+
+export const QueueMessagesDataGrid = ({
+ isLoading,
+ messages,
+ fetchNextPage,
+}: QueueDataGridProps) => {
+ const gridRef = useRef<DataGridHandle>(null)
+ const router = useRouter()
+
+ const [selectedMessageId, setSelectedMessageId] = useQueryState('id', parseAsInteger)
+
+ const handleScroll = (event: UIEvent<HTMLDivElement>) => {
+ if (isLoading || !isAtBottom(event)) return
+ fetchNextPage()
+ }
+
+ const selectedMessage = useMemo(
+ () => messages.find((m) => m.msg_id === selectedMessageId),
+ [messages, selectedMessageId]
+ )
+
+ return (
+ <div className="relative h-full">
+ <DataGrid
+ ref={gridRef}
+ className="h-full"
+ rowHeight={44}
+ headerRowHeight={36}
+ columns={columns}
+ onScroll={handleScroll}
+ rows={messages}
+ rowClass={(message) => {
+ const isSelected = message.msg_id === selectedMessageId
+ return [
+ `${isSelected ? 'bg-surface-300 dark:bg-surface-300' : 'bg-200'} cursor-pointer`,
+ `${isSelected ? '[&>div:first-child]:border-l-4 border-l-secondary [&>div]:border-l-foreground' : ''}`,
+ '[&>.rdg-cell]:border-box [&>.rdg-cell]:outline-none [&>.rdg-cell]:shadow-none',
+ '[&>.rdg-cell:first-child>div]:ml-4',
+ ].join(' ')
+ }}
+ renderers={{
+ renderRow(idx, props) {
+ return (
+ <Row
+ key={props.row.msg_id}
+ {...props}
+ onClick={() => {
+ if (typeof idx === 'number' && idx >= 0) {
+ setSelectedMessageId(props.row.msg_id)
+ gridRef.current?.scrollToCell({ idx: 0, rowIdx: idx })
+ const { id, ...rest } = router.query
+ router.push({ ...router, query: { ...rest, id: props.row.msg_id } })
+ }
+ }}
+ />
+ )
+ },
+ noRowsFallback: isLoading ? (
+ <div className="absolute top-14 px-6 w-full">
+ <GenericSkeletonLoader />
+ </div>
+ ) : (
+ <div className="absolute top-28 px-6 flex flex-col items-center justify-center w-full gap-y-2">
+ <TextSearch className="text-foreground-muted" strokeWidth={1} />
+ <div className="text-center">
+ <p className="text-foreground">No messages found</p>
+ <p className="text-foreground-light">
+ The selected queue doesn't have any messages.
+ </p>
+ </div>
+ </div>
+ ),
+ }}
+ />
+ <ResizablePanelGroup
+ direction="horizontal"
+ className="absolute inset-0 z-10 pointer-events-none"
+ autoSaveId="queue-messages-layout-v1"
+ >
+ <ResizablePanel defaultSize={1} />
+ {selectedMessage && (
+ <>
+ <ResizableHandle withHandle className="pointer-events-auto" />
+ <MessageDetailsPanel
+ selectedMessage={selectedMessage}
+ setSelectedMessage={setSelectedMessageId}
+ />
+ </>
+ )}
+ </ResizablePanelGroup>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueFilters.tsx b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueFilters.tsx
new file mode 100644
index 00000000000..2fd77da9157
--- /dev/null
+++ b/apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueFilters.tsx
@@ -0,0 +1,29 @@
+import { FilterPopover } from 'components/ui/FilterPopover'
+import { QUEUE_MESSAGE_OPTIONS, QUEUE_MESSAGE_TYPE } from './Queue.utils'
+
+interface QueueFiltersProps {
+ selectedTypes: QUEUE_MESSAGE_TYPE[]
+ setSelectedTypes: (value: QUEUE_MESSAGE_TYPE[]) => void
+}
+
+export const QueueFilters = ({ selectedTypes, setSelectedTypes }: QueueFiltersProps) => {
+ return (
+ <div className="bg-surface-200 py-3 px-6 flex items-center justify-between border-t">
+ <div className="flex items-center gap-x-2">
+ <FilterPopover
+ name={selectedTypes.length === 0 ? 'All types' : 'Types'}
+ title="Select types to show"
+ buttonType={selectedTypes.length === 0 ? 'dashed' : 'default'}
+ options={QUEUE_MESSAGE_OPTIONS} // Ignore user image column
+ labelKey="name"
+ valueKey="id"
+ labelClass="text-xs"
+ maxHeightClass="h-[190px]"
+ clearButtonText="Reset"
+ activeOptions={selectedTypes}
+ onSaveFilters={(value) => setSelectedTypes(value as any)}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout.tsx b/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout.tsx
index e945199971f..1366ec37662 100644
--- a/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout.tsx
+++ b/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout.tsx
@@ -11,12 +11,13 @@ import ProjectLayout from '../ProjectLayout/ProjectLayout'
import { generateProjectIntegrationsMenu } from './ProjectIntegrationsMenu.utils'
export interface ProjectIntegrationsLayoutProps {
- title?: string
+ title: string
}
const ProjectIntegrationsMenu = () => {
// if running on self-hosted, cron UI should be always enabled
const cronUiEnabled = useFlag('cronUi') || !IS_PLATFORM
+ const queuesUiEnabled = useFlag('queues')
const project = useSelectedProject()
const router = useRouter()
@@ -29,6 +30,8 @@ const ProjectIntegrationsMenu = () => {
const pgNetExtensionExists = (data ?? []).find((ext) => ext.name === 'pg_net') !== undefined
const graphqlExtensionExists = (data ?? []).find((ext) => ext.name === 'pg_graphql') !== undefined
+ // TODO: Change this to true for local development to work
+ const pgmqExtensionExists = (data ?? []).find((ext) => ext.name === 'pgmq') !== undefined
return (
<>
@@ -37,7 +40,9 @@ const ProjectIntegrationsMenu = () => {
menu={generateProjectIntegrationsMenu(project, {
pgNetExtensionExists,
cronUiEnabled,
+ queuesUiEnabled,
graphqlExtensionExists,
+ pgmqExtensionExists,
})}
/>
</>
@@ -46,9 +51,11 @@ const ProjectIntegrationsMenu = () => {
const ProjectIntegrationsLayout = ({
children,
+ title,
}: PropsWithChildren<ProjectIntegrationsLayoutProps>) => {
return (
<ProjectLayout
+ title={title}
product="Integrations"
productMenu={<ProjectIntegrationsMenu />}
isBlocking={false}
diff --git a/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsMenu.utils.tsx b/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsMenu.utils.tsx
index 78f2f91eb6a..85a9c5501b6 100644
--- a/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsMenu.utils.tsx
+++ b/apps/studio/components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsMenu.utils.tsx
@@ -6,11 +6,19 @@ export const generateProjectIntegrationsMenu = (
flags?: {
pgNetExtensionExists: boolean
cronUiEnabled: boolean
+ queuesUiEnabled: boolean
graphqlExtensionExists: boolean
+ pgmqExtensionExists: boolean
}
): ProductMenuGroup[] => {
const ref = project?.ref ?? 'default'
- const { pgNetExtensionExists, cronUiEnabled, graphqlExtensionExists } = flags || {}
+ const {
+ pgNetExtensionExists,
+ cronUiEnabled,
+ queuesUiEnabled,
+ graphqlExtensionExists,
+ pgmqExtensionExists,
+ } = flags || {}
return [
{
@@ -60,6 +68,16 @@ export const generateProjectIntegrationsMenu = (
items: [],
label: 'BETA',
},
+ ...(!!(queuesUiEnabled && pgmqExtensionExists)
+ ? [
+ {
+ name: 'Queues',
+ key: 'queues',
+ url: `/project/${ref}/integrations/queues`,
+ items: [],
+ },
+ ]
+ : []),
],
},
]
diff --git a/apps/studio/components/ui/FilterPopover.tsx b/apps/studio/components/ui/FilterPopover.tsx
index f47c47d1f8d..f3448d2880d 100644
--- a/apps/studio/components/ui/FilterPopover.tsx
+++ b/apps/studio/components/ui/FilterPopover.tsx
@@ -10,12 +10,12 @@ import {
ScrollArea,
} from 'ui'
-interface FilterPopoverProps {
+interface FilterPopoverProps<T> {
title?: string
- options: any[]
- activeOptions: any[]
- valueKey: string
- labelKey: string
+ options: T[]
+ activeOptions: string[]
+ valueKey: keyof T
+ labelKey: keyof T
iconKey?: string
name: string
variant?: 'rectangular' | 'rounded'
@@ -27,7 +27,7 @@ interface FilterPopoverProps {
onSaveFilters: (options: string[]) => void
}
-export const FilterPopover = ({
+export const FilterPopover = <T extends Record<string, any>>({
title,
options = [],
activeOptions = [],
@@ -42,7 +42,7 @@ export const FilterPopover = ({
maxHeightClass = 'h-[205px]',
clearButtonText = 'Clear',
onSaveFilters,
-}: FilterPopoverProps) => {
+}: FilterPopoverProps<T>) => {
const [open, setOpen] = useState(false)
const [selectedOptions, setSelectedOptions] = useState<string[]>([])
@@ -140,7 +140,7 @@ export const FilterPopover = ({
type="primary"
onClick={() => {
// Order the selection based on the options provided
- const sortingOrder = options.map((option) => option[valueKey])
+ const sortingOrder = options.map((option) => option[valueKey]) as string[]
const sortedSelection = selectedOptions.sort(
(a, b) => sortingOrder.indexOf(a) - sortingOrder.indexOf(b)
)
diff --git a/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts b/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts
new file mode 100644
index 00000000000..7b62fde3f48
--- /dev/null
+++ b/apps/studio/data/database-queues/database-queue-messages-archive-mutation.ts
@@ -0,0 +1,68 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseQueuesKeys } from './keys'
+
+export type DatabaseQueueMessageArchiveVariables = {
+ projectRef: string
+ connectionString?: string
+ queryName: string
+ messageId: number
+}
+
+export async function archiveDatabaseQueueMessage({
+ projectRef,
+ connectionString,
+ queryName,
+ messageId,
+}: DatabaseQueueMessageArchiveVariables) {
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `SELECT * FROM pgmq.archive('${queryName}', ${messageId})`,
+ queryKey: databaseQueuesKeys.create(),
+ })
+
+ return result
+}
+
+type DatabaseQueueMessageArchiveData = Awaited<ReturnType<typeof archiveDatabaseQueueMessage>>
+
+export const useDatabaseQueueMessageArchiveMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<
+ DatabaseQueueMessageArchiveData,
+ ResponseError,
+ DatabaseQueueMessageArchiveVariables
+ >,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<
+ DatabaseQueueMessageArchiveData,
+ ResponseError,
+ DatabaseQueueMessageArchiveVariables
+ >((vars) => archiveDatabaseQueueMessage(vars), {
+ async onSuccess(data, variables, context) {
+ const { projectRef, queryName } = variables
+ await queryClient.invalidateQueries(
+ databaseQueuesKeys.getMessagesInfinite(projectRef, queryName)
+ )
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to archive database queue message: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/database-queues/database-queue-messages-infinite-query.ts b/apps/studio/data/database-queues/database-queue-messages-infinite-query.ts
new file mode 100644
index 00000000000..8ac655704c1
--- /dev/null
+++ b/apps/studio/data/database-queues/database-queue-messages-infinite-query.ts
@@ -0,0 +1,106 @@
+import { UseInfiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'
+import { QUEUE_MESSAGE_TYPE } from 'components/interfaces/Integrations/Queues/SingleQueue/Queue.utils'
+import { executeSql } from 'data/sql/execute-sql-query'
+import dayjs from 'dayjs'
+import { DATE_FORMAT } from 'lib/constants'
+import { last } from 'lodash'
+import { ResponseError } from 'types'
+import { databaseQueuesKeys } from './keys'
+
+export type DatabaseQueueVariables = {
+ projectRef?: string
+ connectionString?: string
+ queueName: string
+ status: QUEUE_MESSAGE_TYPE[]
+}
+
+export type PostgresQueueMessage = {
+ msg_id: number
+ read_ct: number
+ enqueued_at: string
+ archived_at: string
+ vt: Date
+ message: Record<string, never>
+}
+
+export const QUEUE_MESSAGES_PAGE_SIZE = 30
+
+export async function getDatabaseQueue({
+ projectRef,
+ connectionString,
+ queueName,
+ afterTimestamp,
+ status,
+}: DatabaseQueueVariables & { afterTimestamp: string }) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ if (status.length === 0) {
+ return []
+ }
+
+ // handles when scheduled and available are deselected
+ let queueQuery = ``
+ if (status.includes('available') && status.includes('scheduled')) {
+ queueQuery = `SELECT msg_id, enqueued_at, read_ct, vt, message, NULL as archived_at FROM "pgmq"."q_${queueName}"`
+ } else if (status.includes('available') && !status.includes('scheduled')) {
+ queueQuery = `SELECT msg_id, enqueued_at, read_ct, vt, message, NULL as archived_at FROM "pgmq"."q_${queueName}" WHERE vt < '${dayjs(new Date()).format(DATE_FORMAT)}'`
+ } else if (!status.includes('available') && status.includes('scheduled')) {
+ queueQuery = `SELECT msg_id, enqueued_at, read_ct, vt, message, NULL as archived_at FROM "pgmq"."q_${queueName}" WHERE vt > '${dayjs(new Date()).format(DATE_FORMAT)}'`
+ }
+
+ let archivedQuery = ``
+ if (status.includes('archived')) {
+ archivedQuery = `SELECT msg_id, enqueued_at, read_ct, vt, message, archived_at FROM "pgmq"."a_${queueName}"`
+ }
+
+ let query = `SELECT
+ *
+ FROM
+ (
+ ${[queueQuery, archivedQuery].filter(Boolean).join(' UNION ALL ')}
+ ) AS combined`
+ if (afterTimestamp) {
+ query += ` WHERE enqueued_at > '${afterTimestamp}'`
+ }
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `${query} order by enqueued_at LIMIT ${QUEUE_MESSAGES_PAGE_SIZE}`,
+ })
+ return result as DatabaseQueueData
+}
+
+export type DatabaseQueueData = PostgresQueueMessage[]
+export type DatabaseQueueError = ResponseError
+
+export const useQueueMessagesInfiniteQuery = <TData = DatabaseQueueData>(
+ { projectRef, connectionString, queueName, status }: DatabaseQueueVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseInfiniteQueryOptions<DatabaseQueueData, DatabaseQueueError, TData> = {}
+) =>
+ useInfiniteQuery<DatabaseQueueData, DatabaseQueueError, TData>(
+ databaseQueuesKeys.getMessagesInfinite(projectRef, queueName, { status }),
+ ({ pageParam }) => {
+ return getDatabaseQueue({
+ projectRef,
+ connectionString,
+ queueName,
+ afterTimestamp: pageParam,
+ status,
+ })
+ },
+ {
+ staleTime: 0,
+ enabled: enabled && typeof projectRef !== 'undefined',
+
+ getNextPageParam(lastPage) {
+ const hasNextPage = lastPage.length <= QUEUE_MESSAGES_PAGE_SIZE
+ if (!hasNextPage) return undefined
+ return last(lastPage)?.enqueued_at
+ },
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/database-queues/database-queues-create-mutation.ts b/apps/studio/data/database-queues/database-queues-create-mutation.ts
new file mode 100644
index 00000000000..7f08d7a9840
--- /dev/null
+++ b/apps/studio/data/database-queues/database-queues-create-mutation.ts
@@ -0,0 +1,59 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseQueuesKeys } from './keys'
+
+export type DatabaseQueueCreateVariables = {
+ projectRef: string
+ connectionString?: string
+ query: string
+}
+
+export async function createDatabaseQueue({
+ projectRef,
+ connectionString,
+ query,
+}: DatabaseQueueCreateVariables) {
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: query,
+ queryKey: databaseQueuesKeys.create(),
+ })
+
+ return result
+}
+
+type DatabaseQueueCreateData = Awaited<ReturnType<typeof createDatabaseQueue>>
+
+export const useDatabaseQueueCreateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseQueueCreateData, ResponseError, DatabaseQueueCreateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseQueueCreateData, ResponseError, DatabaseQueueCreateVariables>(
+ (vars) => createDatabaseQueue(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries(databaseQueuesKeys.list(projectRef))
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to create database queue: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database-queues/database-queues-delete-mutation.ts b/apps/studio/data/database-queues/database-queues-delete-mutation.ts
new file mode 100644
index 00000000000..7cdd8b3df41
--- /dev/null
+++ b/apps/studio/data/database-queues/database-queues-delete-mutation.ts
@@ -0,0 +1,62 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import type { ResponseError } from 'types'
+import { databaseQueuesKeys } from './keys'
+
+export type DatabaseQueueDeleteVariables = {
+ projectRef: string
+ connectionString?: string
+ queueName: string
+}
+
+export async function deleteDatabaseQueue({
+ projectRef,
+ connectionString,
+ queueName,
+}: DatabaseQueueDeleteVariables) {
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: `select * from pgmq.drop_queue('${queueName}');`,
+ queryKey: databaseQueuesKeys.delete(),
+ })
+
+ return result
+}
+
+type DatabaseQueueDeleteData = Awaited<ReturnType<typeof deleteDatabaseQueue>>
+
+export const useDatabaseQueueDeleteMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<DatabaseQueueDeleteData, ResponseError, DatabaseQueueDeleteVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<DatabaseQueueDeleteData, ResponseError, DatabaseQueueDeleteVariables>(
+ (vars) => deleteDatabaseQueue(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef, queueName } = variables
+ await queryClient.invalidateQueries(databaseQueuesKeys.list(projectRef))
+ await queryClient.invalidateQueries(
+ databaseQueuesKeys.getMessagesInfinite(projectRef, queueName)
+ )
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to delete database queue: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/database-queues/database-queues-query.ts b/apps/studio/data/database-queues/database-queues-query.ts
new file mode 100644
index 00000000000..f6d2168e947
--- /dev/null
+++ b/apps/studio/data/database-queues/database-queues-query.ts
@@ -0,0 +1,45 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { executeSql } from 'data/sql/execute-sql-query'
+import { ResponseError } from 'types'
+import { databaseQueuesKeys } from './keys'
+
+export type DatabaseQueuesVariables = {
+ projectRef?: string
+ connectionString?: string
+}
+
+export type PostgresQueue = {
+ queue_name: string
+ is_partitioned: boolean
+ is_unlogged: boolean
+ created_at: string
+}
+
+const queueSqlQuery = `select * from pgmq.list_queues();`
+
+export async function getDatabaseQueues({ projectRef, connectionString }: DatabaseQueuesVariables) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ const { result } = await executeSql({
+ projectRef,
+ connectionString,
+ sql: queueSqlQuery,
+ })
+ return result
+}
+
+export type DatabaseQueueData = PostgresQueue[]
+export type DatabaseQueueError = ResponseError
+
+export const useQueuesQuery = <TData = DatabaseQueueData>(
+ { projectRef, connectionString }: DatabaseQueuesVariables,
+ { enabled = true, ...options }: UseQueryOptions<DatabaseQueueData, DatabaseQueueError, TData> = {}
+) =>
+ useQuery<DatabaseQueueData, DatabaseQueueError, TData>(
+ databaseQueuesKeys.list(projectRef),
+ () => getDatabaseQueues({ projectRef, connectionString }),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/database-queues/keys.ts b/apps/studio/data/database-queues/keys.ts
new file mode 100644
index 00000000000..c0c484c93aa
--- /dev/null
+++ b/apps/studio/data/database-queues/keys.ts
@@ -0,0 +1,7 @@
+export const databaseQueuesKeys = {
+ create: () => ['queues', 'create'] as const,
+ delete: () => ['queues', 'delete'] as const,
+ getMessagesInfinite: (projectRef: string | undefined, queueName: string, options?: object) =>
+ ['projects', projectRef, 'queues', queueName, options].filter(Boolean),
+ list: (projectRef: string | undefined) => ['projects', projectRef, 'queues'] as const,
+}
diff --git a/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx b/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx
index cb183f11488..329da3177e4 100644
--- a/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx
+++ b/apps/studio/pages/project/[ref]/integrations/cron-jobs.tsx
@@ -1,7 +1,7 @@
import { CronJobsListing } from 'components/interfaces/Integrations/CronJobs/CronJobsListing'
+import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import type { NextPageWithLayout } from 'types'
-import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
const CronJobsPage: NextPageWithLayout = () => {
// TODO: Change this to the correct permissions
@@ -24,7 +24,7 @@ const CronJobsPage: NextPageWithLayout = () => {
}
CronJobsPage.getLayout = (page) => (
- <ProjectIntegrationsLayout title="Database">{page}</ProjectIntegrationsLayout>
+ <ProjectIntegrationsLayout title="Cron Jobs">{page}</ProjectIntegrationsLayout>
)
export default CronJobsPage
diff --git a/apps/studio/pages/project/[ref]/integrations/hooks.tsx b/apps/studio/pages/project/[ref]/integrations/hooks.tsx
index 31474bccbda..980c6005e31 100644
--- a/apps/studio/pages/project/[ref]/integrations/hooks.tsx
+++ b/apps/studio/pages/project/[ref]/integrations/hooks.tsx
@@ -6,7 +6,7 @@ import { useParams } from 'common'
import DeleteHookModal from 'components/interfaces/Database/Hooks/DeleteHookModal'
import EditHookPanel from 'components/interfaces/Database/Hooks/EditHookPanel'
import HooksList from 'components/interfaces/Database/Hooks/HooksList/HooksList'
-import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
+import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
@@ -16,7 +16,6 @@ import { useHooksEnableMutation } from 'data/database/hooks-enable-mutation'
import { useSchemasQuery } from 'data/database/schemas-query'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
import type { NextPageWithLayout } from 'types'
-import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
const HooksPage: NextPageWithLayout = () => {
const { project } = useProjectContext()
@@ -126,7 +125,7 @@ const HooksPage: NextPageWithLayout = () => {
}
HooksPage.getLayout = (page) => (
- <ProjectIntegrationsLayout title="Hooks">{page}</ProjectIntegrationsLayout>
+ <ProjectIntegrationsLayout title="Webhooks">{page}</ProjectIntegrationsLayout>
)
export default HooksPage
diff --git a/apps/studio/pages/project/[ref]/integrations/queues/[name].tsx b/apps/studio/pages/project/[ref]/integrations/queues/[name].tsx
new file mode 100644
index 00000000000..0acaa3f36ca
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/integrations/queues/[name].tsx
@@ -0,0 +1,77 @@
+import { useMemo, useState } from 'react'
+
+import { useParams } from 'common'
+import DeleteQueue from 'components/interfaces/Integrations/Queues/SingleQueue/DeleteQueue'
+import { QUEUE_MESSAGE_TYPE } from 'components/interfaces/Integrations/Queues/SingleQueue/Queue.utils'
+import { QueueMessagesDataGrid } from 'components/interfaces/Integrations/Queues/SingleQueue/QueueDataGrid'
+import { QueueFilters } from 'components/interfaces/Integrations/Queues/SingleQueue/QueueFilters'
+import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { FormHeader } from 'components/ui/Forms/FormHeader'
+import { useQueueMessagesInfiniteQuery } from 'data/database-queues/database-queue-messages-infinite-query'
+import type { NextPageWithLayout } from 'types'
+import { Button, LoadingLine } from 'ui'
+
+const QueueMessagesPage: NextPageWithLayout = () => {
+ // TODO: Change this to the correct permissions
+ // const canReadFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
+ // const isPermissionsLoaded = usePermissionsLoaded()
+
+ // if (isPermissionsLoaded && !canReadFunctions) {
+ // return <NoPermission isFullPage resourceText="manage database queues" />
+ // }
+
+ const { name: queueName } = useParams()
+ const { project } = useProjectContext()
+ const [deleteQueueModalShown, setDeleteQueueModalShown] = useState(false)
+ const [selectedTypes, setSelectedTypes] = useState<QUEUE_MESSAGE_TYPE[]>([])
+
+ const { data, isLoading, isError, fetchNextPage, isFetching } = useQueueMessagesInfiniteQuery(
+ {
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ queueName: queueName!,
+ // when no types are selected, include all types of messages
+ status: selectedTypes.length === 0 ? ['archived', 'available', 'scheduled'] : selectedTypes,
+ },
+ { staleTime: 30 }
+ )
+ const messages = useMemo(() => data?.pages.flatMap((p) => p), [data?.pages])
+
+ if (isLoading && isError) {
+ return null
+ }
+
+ return (
+ <div className="h-full flex flex-col">
+ <FormHeader
+ className="py-4 px-6 !mb-0"
+ title={`Queue ${queueName}`}
+ actions={
+ <Button type="danger" onClick={() => setDeleteQueueModalShown(true)}>
+ Delete the queue
+ </Button>
+ }
+ />
+
+ <QueueFilters selectedTypes={selectedTypes} setSelectedTypes={setSelectedTypes} />
+ <LoadingLine loading={isFetching} />
+ <QueueMessagesDataGrid
+ messages={messages || []}
+ isLoading={isLoading}
+ fetchNextPage={fetchNextPage}
+ />
+ <DeleteQueue
+ queueName={queueName!}
+ visible={deleteQueueModalShown}
+ onClose={() => setDeleteQueueModalShown(false)}
+ />
+ </div>
+ )
+}
+
+QueueMessagesPage.getLayout = (page) => (
+ <ProjectIntegrationsLayout title="Queues">{page}</ProjectIntegrationsLayout>
+)
+
+export default QueueMessagesPage
diff --git a/apps/studio/pages/project/[ref]/integrations/queues/index.tsx b/apps/studio/pages/project/[ref]/integrations/queues/index.tsx
new file mode 100644
index 00000000000..de0b4eb246f
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/integrations/queues/index.tsx
@@ -0,0 +1,30 @@
+import { QueuesListing } from 'components/interfaces/Integrations/Queues/QueuesListing'
+import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import type { NextPageWithLayout } from 'types'
+
+const QueuesPage: NextPageWithLayout = () => {
+ // TODO: Change this to the correct permissions
+ // const canReadFunctions = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_READ, 'functions')
+ // const isPermissionsLoaded = usePermissionsLoaded()
+
+ // if (isPermissionsLoaded && !canReadFunctions) {
+ // return <NoPermission isFullPage resourceText="manage database queues" />
+ // }
+
+ return (
+ <ScaffoldContainer className="h-full">
+ <ScaffoldSection className="h-full">
+ <div className="col-span-12 h-full pb-8">
+ <QueuesListing />
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
+ )
+}
+
+QueuesPage.getLayout = (page) => (
+ <ProjectIntegrationsLayout title="Queues">{page}</ProjectIntegrationsLayout>
+)
+
+export default QueuesPage
diff --git a/apps/studio/pages/project/[ref]/integrations/wrappers/new.tsx b/apps/studio/pages/project/[ref]/integrations/wrappers/new.tsx
index fbf85a115a6..babc1819c1e 100644
--- a/apps/studio/pages/project/[ref]/integrations/wrappers/new.tsx
+++ b/apps/studio/pages/project/[ref]/integrations/wrappers/new.tsx
@@ -1,7 +1,7 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { CreateWrapper } from 'components/interfaces/Database'
-import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
+import ProjectIntegrationsLayout from 'components/layouts/ProjectIntegrationsLayout/ProjectIntegrationsLayout'
import NoPermission from 'components/ui/NoPermission'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
import type { NextPageWithLayout } from 'types'
@@ -17,6 +17,8 @@ const DatabaseWrappersNew: NextPageWithLayout = () => {
return <CreateWrapper />
}
-DatabaseWrappersNew.getLayout = (page) => <DatabaseLayout title="Wrappers">{page}</DatabaseLayout>
+DatabaseWrappersNew.getLayout = (page) => (
+ <ProjectIntegrationsLayout title="Wrappers">{page}</ProjectIntegrationsLayout>
+)
export default DatabaseWrappersNew