Skip to content

Commit

Permalink
feat(sdf, dal): Adding the ability to set a webhook url for a workspace
Browse files Browse the repository at this point in the history
We currently only post to that webhook from the change set approval flow but we want to make this more of an opt-in to what you can / can't to
  • Loading branch information
stack72 committed Dec 10, 2024
1 parent 67e7c0d commit f6dec5d
Show file tree
Hide file tree
Showing 18 changed files with 495 additions and 14 deletions.
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>
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,17 @@
label="Copy Workspace Token"
@click="copyWorkspaceToken"
/>
<DropdownMenuItem
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,13 +52,16 @@ 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 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();
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();
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 @@ -67,6 +67,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,
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;

#[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",
&[&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)
}
}
7 changes: 7 additions & 0 deletions lib/sdf-server/src/service/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub mod admin;
pub mod audit_log;
pub mod change_set;
pub mod func;
pub mod integrations;
pub mod management;
pub mod module;
pub mod variant;
Expand All @@ -16,6 +17,8 @@ const PREFIX: &str = "/workspaces/:workspace_id/change-sets/:change_set_id";
// use this if you don't need to pass in the change_set id
const CHANGE_SET_PREFIX: &str = "/workspaces/:workspace_id/change-sets";

const INTEGRATIONS_PREFIX: &str = "/workspaces/:workspace_id";

pub fn routes(state: AppState) -> Router<AppState> {
Router::new()
.nest("/admin", admin::v2_routes(state.clone()))
Expand All @@ -26,4 +29,8 @@ pub fn routes(state: AppState) -> Router<AppState> {
.nest(&format!("{PREFIX}/schema-variants"), variant::v2_routes())
.nest(&format!("{PREFIX}/management"), management::v2_routes())
.nest(&format!("{PREFIX}/views"), view::v2_routes())
.nest(
&format!("{INTEGRATIONS_PREFIX}/integrations"),
integrations::v2_routes(),
)
}
Loading

0 comments on commit f6dec5d

Please sign in to comment.