Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sdf, dal): Adding the ability to set a webhook url for a workspace #5095

Merged
merged 1 commit into from
Dec 10, 2024
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
48 changes: 48 additions & 0 deletions app/web/src/components/WorkspaceIntegrationsModal.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<template>
<Modal
ref="modalRef"
type="save"
size="sm"
saveLabel="Save"
title="Save Integrations"
@save="updateIntegrations"
>
<VormInput ref="labelRef" v-model="webhookUrl" label="Slack Webhook Url" />
</Modal>
</template>

<script setup lang="ts">
import { Modal, VormInput } from "@si/vue-lib/design-system";
import { ref, computed } from "vue";
import { useWorkspacesStore } from "@/store/workspaces.store";

const workspacesStore = useWorkspacesStore();

const modalRef = ref<InstanceType<typeof Modal>>();

const integration = computed(() => workspacesStore.getIntegrations);

function open() {
if (
integration.value &&
integration.value.slackWebhookUrl &&
integration.value.slackWebhookUrl !== ""
) {
webhookUrl.value = integration.value.slackWebhookUrl;
}
modalRef.value?.open();
}

const webhookUrl = ref("");

const updateIntegrations = () => {
if (!webhookUrl.value || webhookUrl.value === "" || !integration.value?.pk)
return;
workspacesStore.UPDATE_INTEGRATION(integration.value?.pk, webhookUrl.value);

modalRef.value?.close();
webhookUrl.value = "";
};

defineExpose({ open });
</script>
12 changes: 12 additions & 0 deletions app/web/src/components/layout/navbar/WorkspaceSettingsMenu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,18 @@
label="Copy Workspace Token"
@click="copyWorkspaceToken"
/>
<DropdownMenuItem
v-if="featureFlagsStore.SLACK_WEBHOOK"
icon="settings"
label="Workspace Integrations"
@click="integrationsModalRef?.open()"
/>
</template>
</NavbarButton>

<WorkspaceImportModal ref="importModalRef" />
<WorkspaceExportModal ref="exportModalRef" />
<WorkspaceIntegrationsModal ref="integrationsModalRef" />
</template>

<script setup lang="ts">
Expand All @@ -46,16 +53,21 @@ import { ref, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import WorkspaceImportModal from "@/components/WorkspaceImportModal.vue";
import WorkspaceExportModal from "@/components/WorkspaceExportModal.vue";
import WorkspaceIntegrationsModal from "@/components/WorkspaceIntegrationsModal.vue";
import { useWorkspacesStore } from "@/store/workspaces.store";
import { useChangeSetsStore } from "@/store/change_sets.store";
import { useFeatureFlagsStore } from "@/store/feature_flags.store";
import NavbarButton from "./NavbarButton.vue";

const AUTH_PORTAL_URL = import.meta.env.VITE_AUTH_PORTAL_URL;
const importModalRef = ref<InstanceType<typeof WorkspaceImportModal>>();
const exportModalRef = ref<InstanceType<typeof WorkspaceExportModal>>();
const integrationsModalRef =
ref<InstanceType<typeof WorkspaceIntegrationsModal>>();

const workspacesStore = useWorkspacesStore();
const changeSetStore = useChangeSetsStore();
const featureFlagsStore = useFeatureFlagsStore();
const router = useRouter();
const route = useRoute();

Expand Down
1 change: 1 addition & 0 deletions app/web/src/store/feature_flags.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const FLAG_MAPPING = {
AI_GENERATOR: "ai-generator",
REBAC: "rebac",
OUTLINER_VIEWS: "diagram-outline-show-views",
SLACK_WEBHOOK: "slack_webhook",
};

type FeatureFlags = keyof typeof FLAG_MAPPING;
Expand Down
56 changes: 55 additions & 1 deletion app/web/src/store/workspaces.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import handleStoreError from "./errors";
import { AuthApiRequest } from ".";

export type WorkspacePk = string;
export type WorkspaceIntegrationId = string;

type WorkspaceExportId = string;
type WorkspaceExportSummary = {
Expand Down Expand Up @@ -39,6 +40,12 @@ export type WorkspaceImportSummary = {
importedWorkspaceName: string;
};

export type WorkspaceIntegration = {
pk: WorkspaceIntegrationId;
workspaceId: WorkspacePk;
slackWebhookUrl?: string;
};

const LOCAL_STORAGE_LAST_WORKSPACE_PK = "si-last-workspace-pk";

// Note(victor): The workspace import exists outside a change set context
Expand All @@ -60,6 +67,7 @@ export const useWorkspacesStore = () => {
importId: null as string | null,
importLoading: false as boolean,
importError: undefined as string | undefined,
integrations: null as WorkspaceIntegration | null,
}),
getters: {
allWorkspaces: (state) => _.values(state.workspacesByPk),
Expand All @@ -79,6 +87,9 @@ export const useWorkspacesStore = () => {
null,
);
},
getIntegrations(): WorkspaceIntegration | null {
return this.integrations || null;
},
},

actions: {
Expand Down Expand Up @@ -162,14 +173,56 @@ export const useWorkspacesStore = () => {
},
});
},

async GET_INTEGRATIONS() {
if (
this.selectedWorkspacePk === null ||
this.selectedWorkspacePk === ""
)
return;
return new ApiRequest({
method: "get",
url: `v2/workspaces/${this.selectedWorkspacePk}/integrations`,
onSuccess: (response) => {
this.integrations = {
pk: response.integration.pk,
workspaceId: response.integration.workspace_pk,
slackWebhookUrl: response.integration.slack_webhook_url,
};
},
});
},

async UPDATE_INTEGRATION(
workspaceIntegrationId: WorkspaceIntegrationId,
webhookUrl: string,
) {
if (
this.selectedWorkspacePk === null ||
this.selectedWorkspacePk === ""
)
return;
return new ApiRequest({
method: "post",
url: `v2/workspaces/${this.selectedWorkspacePk}/integrations/${workspaceIntegrationId}`,
params: {
slackWebhookUrl: webhookUrl,
},
onSuccess: (response) => {
this.integrations = response.integration;
},
});
},
},

onActivated() {
const authStore = useAuthStore();
watch(
() => authStore.userIsLoggedInAndInitialized,
(loggedIn) => {
if (loggedIn) this.FETCH_USER_WORKSPACES();
if (loggedIn) {
this.FETCH_USER_WORKSPACES();
}
},
{ immediate: true },
);
Expand All @@ -181,6 +234,7 @@ export const useWorkspacesStore = () => {
watch(
() => this.selectedWorkspacePk,
() => {
this.GET_INTEGRATIONS();
stack72 marked this conversation as resolved.
Show resolved Hide resolved
realtimeStore.subscribe(
this.$id,
`workspace/${this.selectedWorkspacePk}`,
Expand Down
1 change: 1 addition & 0 deletions lib/dal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ pub mod user;
pub mod validation;
pub mod visibility;
pub mod workspace;
pub mod workspace_integrations;
pub mod workspace_snapshot;
pub mod ws_event;

Expand Down
11 changes: 11 additions & 0 deletions lib/dal/src/migrations/U3410__workspace_integration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE TABLE workspace_integrations
(
pk ident primary key default ident_create_v1(),
slack_webhook_url text NULL,
stack72 marked this conversation as resolved.
Show resolved Hide resolved
workspace_pk ident NOT NULL
);
CREATE UNIQUE INDEX ON workspace_integrations (pk);
CREATE UNIQUE INDEX ON workspace_integrations (workspace_pk);
CREATE UNIQUE INDEX ON workspace_integrations (slack_webhook_url, workspace_pk);
CREATE INDEX ON workspace_integrations (slack_webhook_url);
CREATE INDEX ON workspace_integrations (workspace_pk);
6 changes: 6 additions & 0 deletions lib/dal/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::builtins::func::migrate_intrinsics_no_commit;
use crate::change_set::{ChangeSet, ChangeSetError, ChangeSetId};
use crate::feature_flags::FeatureFlag;
use crate::layer_db_types::ContentTypes;
use crate::workspace_integrations::{WorkspaceIntegration, WorkspaceIntegrationsError};
use crate::workspace_snapshot::graph::WorkspaceSnapshotGraphDiscriminants;
use crate::workspace_snapshot::WorkspaceSnapshotError;
use crate::{
Expand Down Expand Up @@ -84,6 +85,8 @@ pub enum WorkspaceError {
Transactions(#[from] TransactionsError),
#[error(transparent)]
User(#[from] UserError),
#[error("workspace integration error: {0}")]
WorkspaceIntegration(#[from] WorkspaceIntegrationsError),
#[error("workspace not found: {0}")]
WorkspaceNotFound(WorkspacePk),
#[error("workspace snapshot error: {0}")]
Expand Down Expand Up @@ -367,6 +370,9 @@ impl Workspace {
)
.await?;

// Create an entry in the workspace integrations table by default
WorkspaceIntegration::new(ctx, None).await?;

Ok(workspace)
}

Expand Down
126 changes: 126 additions & 0 deletions lib/dal/src/workspace_integrations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
use crate::{workspace::WorkspaceId, DalContext, TransactionsError};
use serde::{Deserialize, Serialize};
use si_data_pg::{PgError, PgRow};
use thiserror::Error;

#[remain::sorted]
#[derive(Error, Debug)]
pub enum WorkspaceIntegrationsError {
#[error(transparent)]
Pg(#[from] PgError),
#[error("transactions error: {0}")]
Transactions(#[from] TransactionsError),
}

pub type WorkspaceIntegrationsResult<T> = Result<T, WorkspaceIntegrationsError>;

pub use si_id::WorkspaceIntegrationId;
stack72 marked this conversation as resolved.
Show resolved Hide resolved

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct WorkspaceIntegration {
pk: WorkspaceIntegrationId,
workspace_pk: WorkspaceId,
slack_webhook_url: Option<String>,
}

impl TryFrom<PgRow> for WorkspaceIntegration {
type Error = WorkspaceIntegrationsError;

fn try_from(row: PgRow) -> Result<Self, Self::Error> {
Ok(Self {
pk: row.try_get("pk")?,
workspace_pk: row.try_get("workspace_pk")?,
slack_webhook_url: row.try_get("slack_webhook_url")?,
})
}
}

impl WorkspaceIntegration {
pub fn pk(&self) -> &WorkspaceIntegrationId {
&self.pk
}

pub fn slack_webhook_url(&self) -> Option<String> {
self.slack_webhook_url.clone()
}

pub async fn update_webhook_url(
&mut self,
ctx: &DalContext,
webhook_url: String,
) -> WorkspaceIntegrationsResult<()> {
ctx.txns()
.await?
.pg()
.query_none(
"UPDATE workspace_integrations SET slack_webhook_url = $2 WHERE pk = $1",
&[&self.pk, &webhook_url],
)
.await?;
self.slack_webhook_url = Some(webhook_url);

Ok(())
}

pub async fn new(
ctx: &DalContext,
webhook_url: Option<String>,
) -> WorkspaceIntegrationsResult<Self> {
let workspace_pk = ctx.workspace_pk()?;

let row = ctx
.txns()
.await?
.pg()
.query_one(
"INSERT INTO workspace_integrations (workspace_pk, slack_webhook_url) VALUES ($1, $2) RETURNING *",
&[&workspace_pk, &webhook_url],
)
.await?;

let workspace_integration = Self::try_from(row)?;

Ok(workspace_integration)
}

pub async fn get_integrations_for_workspace_pk(
ctx: &DalContext,
) -> WorkspaceIntegrationsResult<Option<Self>> {
let workspace_pk = ctx.workspace_pk()?;

let maybe_row = ctx
.txns()
.await?
.pg()
.query_opt(
"SELECT * FROM workspace_integrations AS w WHERE workspace_pk = $1",
stack72 marked this conversation as resolved.
Show resolved Hide resolved
&[&workspace_pk],
)
.await?;
let maybe_workspace_integration = match maybe_row {
Some(found) => Some(Self::try_from(found)?),
None => None,
};
Ok(maybe_workspace_integration)
}

pub async fn get_by_pk(
ctx: &DalContext,
workspace_integration_id: WorkspaceIntegrationId,
) -> WorkspaceIntegrationsResult<Option<Self>> {
let maybe_row = ctx
.txns()
.await?
.pg()
.query_opt(
"SELECT * FROM workspace_integrations AS w WHERE pk = $1",
&[&workspace_integration_id],
)
.await?;
let maybe_workspace_integration = match maybe_row {
Some(found) => Some(Self::try_from(found)?),
None => None,
};
Ok(maybe_workspace_integration)
}
}
Loading
Loading