mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
feat: overwrite or discard each path conflict when reassigning user items (#12683)
* feat: overwrite or discard each path conflict when reassigning user items Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: guard offboarding conflict resolution against stale rows and cascades Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: match the departing user's rows literally in offboarding cleanup Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
71f22fc6e9
commit
b3ab8e22b3
@@ -482,12 +482,130 @@ async fn test_offboard_conflicts(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
.any(|c| c.as_str().unwrap().contains("conflict_script")),
|
||||
"conflict should mention conflict_script"
|
||||
);
|
||||
// The UI resolves each conflict by deleting one side, so both paths must be reported.
|
||||
let items = body["conflict_items"]
|
||||
.as_array()
|
||||
.expect("conflict_items should be array");
|
||||
assert_eq!(items.len(), conflicts.len());
|
||||
let item = items
|
||||
.iter()
|
||||
.find(|c| c["source_path"] == "u/test-user-2/conflict_script")
|
||||
.expect("conflict_items should include conflict_script");
|
||||
assert_eq!(item["kind"], "script");
|
||||
assert_eq!(item["target_path"], "u/test-user/conflict_script");
|
||||
assert_eq!(item["workspace_id"], "test-workspace");
|
||||
// No summary when conflicts exist
|
||||
assert!(body["summary"].is_null());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Usernames may hold `_`, a LIKE wildcard: another user's item matched by it maps to itself, so
|
||||
/// it must be neither reported as a conflict (which offers to delete it) nor cleaned up as stale.
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))]
|
||||
async fn test_offboard_conflicts_underscore_username(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO usr (workspace_id, email, username, is_admin, role)
|
||||
VALUES ('test-workspace', 'underscore@windmill.dev', 'test_user', false, 'User')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO variable (workspace_id, path, value, is_secret, description)
|
||||
VALUES ('test-workspace', 'u/testxuser/var', 'v', false, '')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind)
|
||||
VALUES ('test-workspace', 'main', 'datatable', 'u/testxuser/s', 'script')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path)
|
||||
VALUES ('test-workspace', 'u/testxuser/s', 'script', 'f/shared/lib')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
let resp = authed(client().post(ws_url(port, "offboard/test_user")))
|
||||
.json(&json!({ "reassign_to": "u/test-user", "delete_user": false }))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await?;
|
||||
assert!(body["conflict_items"].is_null(), "{body}");
|
||||
let untouched: i64 = sqlx::query_scalar(
|
||||
"SELECT (SELECT COUNT(*) FROM asset WHERE usage_path = 'u/testxuser/s')
|
||||
+ (SELECT COUNT(*) FROM dependency_map WHERE importer_path = 'u/testxuser/s')
|
||||
+ (SELECT COUNT(*) FROM variable WHERE path = 'u/testxuser/var')",
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert_eq!(untouched, 3, "another user's rows must survive the reassignment");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolving a conflict by deleting the target leaves that script's `dependency_map` and `asset`
|
||||
/// rows behind, on the keys the departing user's rows are renamed onto.
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))]
|
||||
async fn test_offboard_over_deleted_target(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
let server = ApiServer::start(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path)
|
||||
VALUES ('test-workspace', 'u/test-user/conflict_script', 'script', 'f/shared/lib'),
|
||||
('test-workspace', 'u/test-user-2/conflict_script', 'script', 'f/shared/lib')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO asset (workspace_id, path, kind, usage_path, usage_kind)
|
||||
VALUES ('test-workspace', 'main', 'datatable', 'u/test-user/conflict_script', 'script'),
|
||||
('test-workspace', 'main', 'datatable', 'u/test-user-2/conflict_script', 'script')",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
let resp = authed(client().post(format!(
|
||||
"http://localhost:{port}/api/w/test-workspace/scripts/delete/p/u/test-user/conflict_script"
|
||||
)))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200, "{}", resp.text().await?);
|
||||
|
||||
let resp = authed(client().post(ws_url(port, "offboard/test-user-2")))
|
||||
.json(&json!({ "reassign_to": "u/test-user", "delete_user": false }))
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await?;
|
||||
assert!(body["summary"].is_object(), "{body}");
|
||||
|
||||
let importers: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT importer_path FROM dependency_map
|
||||
WHERE workspace_id = 'test-workspace' AND imported_path = 'f/shared/lib'",
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
assert_eq!(importers, vec!["u/test-user/conflict_script".to_string()]);
|
||||
let users: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT usage_path FROM asset WHERE workspace_id = 'test-workspace' AND path = 'main'",
|
||||
)
|
||||
.fetch_all(&db)
|
||||
.await?;
|
||||
assert_eq!(users, vec!["u/test-user/conflict_script".to_string()]);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "offboarding_test"))]
|
||||
async fn test_offboard_tokens_deleted(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
|
||||
@@ -33947,9 +33947,34 @@ components:
|
||||
items:
|
||||
type: string
|
||||
description: "List of path conflicts that block the offboarding. Empty on success."
|
||||
conflict_items:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/OffboardPathConflict"
|
||||
description: "The same conflicts as `conflicts`, structured. Empty on success."
|
||||
summary:
|
||||
$ref: "#/components/schemas/OffboardSummary"
|
||||
|
||||
OffboardPathConflict:
|
||||
type: object
|
||||
properties:
|
||||
workspace_id:
|
||||
type: string
|
||||
kind:
|
||||
type: string
|
||||
description: "Item kind, as its table name (script, flow, app, resource, variable, schedule, eval_dataset, http_trigger, ...)"
|
||||
source_path:
|
||||
type: string
|
||||
description: "The offboarded user's item, under u/{username}/"
|
||||
target_path:
|
||||
type: string
|
||||
description: "The existing item at the reassignment target"
|
||||
required:
|
||||
- workspace_id
|
||||
- kind
|
||||
- source_path
|
||||
- target_path
|
||||
|
||||
OffboardSummary:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
@@ -85,10 +85,44 @@ fn default_true() -> bool {
|
||||
pub(crate) struct OffboardResponse {
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
conflicts: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
conflict_items: Vec<PathConflict>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
summary: Option<OffboardSummary>,
|
||||
}
|
||||
|
||||
impl OffboardResponse {
|
||||
fn conflicts(conflict_items: Vec<PathConflict>, global: bool) -> Self {
|
||||
let conflicts = conflict_items
|
||||
.iter()
|
||||
.map(|c| {
|
||||
if global {
|
||||
format!("[{}] {}: {}", c.workspace_id, c.kind, c.target_path)
|
||||
} else {
|
||||
format!("{}: {}", c.kind, c.target_path)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Self { conflicts, conflict_items, summary: None }
|
||||
}
|
||||
|
||||
fn done(summary: OffboardSummary) -> Self {
|
||||
Self { conflicts: vec![], conflict_items: vec![], summary: Some(summary) }
|
||||
}
|
||||
}
|
||||
|
||||
/// An item of the departing user whose reassigned path is already taken.
|
||||
#[derive(Serialize)]
|
||||
struct PathConflict {
|
||||
workspace_id: String,
|
||||
/// The table the item lives in (`script`, `flow`, `http_trigger`, ...).
|
||||
kind: String,
|
||||
/// The departing user's item, under `u/{username}/`.
|
||||
source_path: String,
|
||||
/// The existing item the reassignment would collide with.
|
||||
target_path: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OffboardSummary {
|
||||
scripts_reassigned: i64,
|
||||
@@ -415,7 +449,7 @@ pub(crate) async fn offboard_workspace_user(
|
||||
|
||||
let conflicts = check_path_conflicts(&db, &w_id, &username, &req.reassign_to).await?;
|
||||
if !conflicts.is_empty() {
|
||||
return Ok(Json(OffboardResponse { conflicts, summary: None }));
|
||||
return Ok(Json(OffboardResponse::conflicts(conflicts, false)));
|
||||
}
|
||||
|
||||
let email = sqlx::query_scalar!(
|
||||
@@ -478,10 +512,7 @@ pub(crate) async fn offboard_workspace_user(
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(Json(OffboardResponse {
|
||||
conflicts: vec![],
|
||||
summary: Some(summary),
|
||||
}))
|
||||
Ok(Json(OffboardResponse::done(summary)))
|
||||
}
|
||||
|
||||
// ---- Instance-level endpoints ----
|
||||
@@ -557,16 +588,11 @@ pub(crate) async fn offboard_global_user(
|
||||
&reassignment.reassign_to,
|
||||
)
|
||||
.await?;
|
||||
for c in conflicts {
|
||||
all_conflicts.push(format!("[{}] {}", &ws.workspace_id, c));
|
||||
}
|
||||
all_conflicts.extend(conflicts);
|
||||
}
|
||||
}
|
||||
if !all_conflicts.is_empty() {
|
||||
return Ok(Json(OffboardResponse {
|
||||
conflicts: all_conflicts,
|
||||
summary: None,
|
||||
}));
|
||||
return Ok(Json(OffboardResponse::conflicts(all_conflicts, true)));
|
||||
}
|
||||
|
||||
let mut tx = db.begin().await?;
|
||||
@@ -654,10 +680,7 @@ pub(crate) async fn offboard_global_user(
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(Json(OffboardResponse {
|
||||
conflicts: vec![],
|
||||
summary: Some(total_summary),
|
||||
}))
|
||||
Ok(Json(OffboardResponse::done(total_summary)))
|
||||
}
|
||||
|
||||
// ---- Validation helpers ----
|
||||
@@ -769,7 +792,7 @@ async fn check_path_conflicts(
|
||||
w_id: &str,
|
||||
username: &str,
|
||||
reassign_to: &str,
|
||||
) -> Result<Vec<String>> {
|
||||
) -> Result<Vec<PathConflict>> {
|
||||
let new_prefix = format!("{}/", reassign_to);
|
||||
let mut conflicts = Vec::new();
|
||||
|
||||
@@ -800,11 +823,14 @@ async fn check_path_conflicts(
|
||||
"flow" => " AND NOT t1.archived",
|
||||
_ => "",
|
||||
};
|
||||
// A conflict is resolved by deleting one of its two paths, so the source must be the
|
||||
// departing user's: `starts_with` rather than LIKE, where the `_` usernames may hold
|
||||
// matches any character and would report another user's item as conflicting with itself.
|
||||
// SAFETY: `table_name` comes from a hardcoded allowlist `tables`, not user input.
|
||||
let rows: Vec<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \
|
||||
let rows: Vec<(String, String)> = sqlx::query_as(&format!(
|
||||
"SELECT DISTINCT t1.path, REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \
|
||||
FROM {table} t1 \
|
||||
WHERE t1.path LIKE ('u/' || $1 || '/%') AND t1.workspace_id = $2{extra_filter} \
|
||||
WHERE starts_with(t1.path, 'u/' || $1 || '/') AND t1.workspace_id = $2{extra_filter} \
|
||||
AND EXISTS ( \
|
||||
SELECT 1 FROM {table} t2 \
|
||||
WHERE t2.path = REGEXP_REPLACE(t1.path, '^u/' || $1 || '/', $3) \
|
||||
@@ -818,8 +844,13 @@ async fn check_path_conflicts(
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
|
||||
for path in rows {
|
||||
conflicts.push(format!("{}: {}", table_name, path));
|
||||
for (source_path, target_path) in rows {
|
||||
conflicts.push(PathConflict {
|
||||
workspace_id: w_id.to_string(),
|
||||
kind: table_name.to_string(),
|
||||
source_path,
|
||||
target_path,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1216,12 +1247,47 @@ async fn offboard_user_from_workspace<'c>(
|
||||
&new_prefix, username, w_id
|
||||
).execute(&mut **tx).await?;
|
||||
|
||||
// Deleting a script or flow by path leaves its asset usages behind, on the keys the moved
|
||||
// usages take; such a row is an orphan or the same usage, so it is dropped, not renamed onto.
|
||||
sqlx::query(
|
||||
"DELETE FROM asset d WHERE d.workspace_id = $3 AND EXISTS ( \
|
||||
SELECT 1 FROM asset s \
|
||||
WHERE s.workspace_id = $3 AND starts_with(s.usage_path, 'u/' || $2 || '/') \
|
||||
AND s.ctid <> d.ctid AND s.path = d.path AND s.kind = d.kind AND s.usage_kind = d.usage_kind \
|
||||
AND REGEXP_REPLACE(s.usage_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.usage_path)",
|
||||
)
|
||||
.bind(&new_prefix)
|
||||
.bind(username)
|
||||
.bind(w_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
r#"UPDATE asset SET usage_path = REGEXP_REPLACE(usage_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE usage_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#,
|
||||
&new_prefix, username, w_id
|
||||
).execute(&mut **tx).await?;
|
||||
|
||||
// ---- dependency_map ----
|
||||
// Deleting an item by path leaves its rows here, so an item deleted to make room at the
|
||||
// target still holds the keys the moved rows take. A row already holding a moved row's final
|
||||
// key is such an orphan or the same edge, so it is dropped rather than renamed onto.
|
||||
// SAFETY: `column` comes from the hardcoded list below, not user input.
|
||||
for column in ["importer_path", "imported_path"] {
|
||||
sqlx::query(&format!(
|
||||
"DELETE FROM dependency_map d WHERE d.workspace_id = $3 AND EXISTS ( \
|
||||
SELECT 1 FROM dependency_map s \
|
||||
WHERE s.workspace_id = $3 AND starts_with(s.{column}, 'u/' || $2 || '/') \
|
||||
AND s.ctid <> d.ctid AND s.importer_node_id = d.importer_node_id AND s.importer_kind = d.importer_kind \
|
||||
AND REGEXP_REPLACE(s.importer_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.importer_path \
|
||||
AND REGEXP_REPLACE(s.imported_path, '^u/' || $2 || '/(.*)', $1 || '/\\1') = d.imported_path)"
|
||||
))
|
||||
.bind(&new_prefix)
|
||||
.bind(username)
|
||||
.bind(w_id)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
r#"UPDATE dependency_map SET importer_path = REGEXP_REPLACE(importer_path, 'u/' || $2 || '/(.*)', $1 || '/\1') WHERE importer_path LIKE ('u/' || $2 || '/%') AND workspace_id = $3"#,
|
||||
&new_prefix, username, w_id
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
import { apiErrorMessage, classNames } from '$lib/utils'
|
||||
import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte'
|
||||
import { UserService, FolderService } from '$lib/gen'
|
||||
import type { WorkspaceOffboardPreview } from '$lib/gen'
|
||||
import type { OffboardPathConflict, WorkspaceOffboardPreview } from '$lib/gen'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte'
|
||||
import { countPaths } from './offboarding-utils'
|
||||
import OffboardConflictList from './OffboardConflictList.svelte'
|
||||
import { countPaths, withoutConflict } from './offboarding-utils'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
@@ -25,7 +26,7 @@
|
||||
let submitting = $state(false)
|
||||
let doReassign = $state(true)
|
||||
let deleteUser = $state(true)
|
||||
let conflicts: string[] = $state([])
|
||||
let conflicts: OffboardPathConflict[] = $state([])
|
||||
|
||||
$effect(() => {
|
||||
deleteUser = !reassignOnly
|
||||
@@ -169,8 +170,8 @@
|
||||
delete_user: deleteUser
|
||||
}
|
||||
})
|
||||
if (result.conflicts && result.conflicts.length > 0) {
|
||||
conflicts = result.conflicts
|
||||
if (result.conflict_items && result.conflict_items.length > 0) {
|
||||
conflicts = result.conflict_items
|
||||
} else {
|
||||
sendUserToast(
|
||||
deleteUser
|
||||
@@ -315,17 +316,11 @@
|
||||
{/if}
|
||||
|
||||
{#if conflicts.length > 0}
|
||||
<Alert type="error" title="Path conflicts detected">
|
||||
<p class="text-xs mb-1"
|
||||
>These items already exist at the target. Rename or delete them, or choose a
|
||||
different user/folder.</p
|
||||
>
|
||||
<ul class="text-xs list-disc list-inside max-h-32 overflow-y-auto">
|
||||
{#each conflicts as conflict, i (i)}
|
||||
<li>{conflict}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Alert>
|
||||
<OffboardConflictList
|
||||
{conflicts}
|
||||
showWorkspace
|
||||
onResolved={(c) => (conflicts = withoutConflict(conflicts, c))}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Button } from '$lib/components/common'
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import type { OffboardPathConflict } from '$lib/gen'
|
||||
import { apiErrorMessage } from '$lib/utils'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import {
|
||||
canDeleteKind,
|
||||
conflictsGoneAfterDelete,
|
||||
deleteItemOfKind,
|
||||
isTrashedKind,
|
||||
itemHref,
|
||||
kindLabel
|
||||
} from './offboarding-utils'
|
||||
|
||||
type Props = {
|
||||
conflicts: OffboardPathConflict[]
|
||||
/** Prefix each line with its workspace (instance-level offboarding). */
|
||||
showWorkspace?: boolean
|
||||
onResolved: (conflict: OffboardPathConflict) => void
|
||||
}
|
||||
|
||||
let { conflicts, showWorkspace = false, onResolved }: Props = $props()
|
||||
|
||||
type Action = 'overwrite' | 'discard'
|
||||
let pending: { conflict: OffboardPathConflict; action: Action } | undefined = $state(undefined)
|
||||
let deleting = $state(false)
|
||||
|
||||
function pathToDelete(p: NonNullable<typeof pending>): string {
|
||||
return p.action === 'overwrite' ? p.conflict.target_path : p.conflict.source_path
|
||||
}
|
||||
|
||||
async function confirm() {
|
||||
if (!pending) return
|
||||
const { conflict } = pending
|
||||
const path = pathToDelete(pending)
|
||||
deleting = true
|
||||
try {
|
||||
await deleteItemOfKind(conflict.kind, conflict.workspace_id, path)
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not delete ${path}: ${apiErrorMessage(e)}`, true)
|
||||
deleting = false
|
||||
return
|
||||
}
|
||||
sendUserToast(`Deleted ${kindLabel(conflict.kind)} ${path}`)
|
||||
const remaining = conflicts.filter((c) => c !== conflict)
|
||||
onResolved(conflict)
|
||||
pending = undefined
|
||||
try {
|
||||
for (const gone of await conflictsGoneAfterDelete(conflict.kind, remaining)) {
|
||||
onResolved(gone)
|
||||
}
|
||||
} catch (e) {
|
||||
sendUserToast(`Could not refresh the remaining conflicts: ${apiErrorMessage(e)}`, true)
|
||||
} finally {
|
||||
deleting = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Alert type="error" title="Path conflicts detected">
|
||||
<p class="text-xs mb-2">
|
||||
These items already exist at the target. For each one, overwrite the existing item with the
|
||||
reassigned one, or discard the reassigned one and keep the existing item. You can also choose a
|
||||
different user/folder.
|
||||
</p>
|
||||
<ul class="flex flex-col gap-1 max-h-48 overflow-y-auto">
|
||||
{#each conflicts as conflict (`${conflict.workspace_id}:${conflict.kind}:${conflict.source_path}`)}
|
||||
{@const href = itemHref(conflict.kind, conflict.target_path)}
|
||||
<li class="flex items-center gap-2 text-xs">
|
||||
<span class="flex-1 min-w-0 truncate" title={conflict.target_path}>
|
||||
{#if showWorkspace}
|
||||
<span class="text-secondary">[{conflict.workspace_id}]</span>
|
||||
{/if}
|
||||
<span class="text-secondary">{kindLabel(conflict.kind)}:</span>
|
||||
{#if href && !showWorkspace}
|
||||
<a {href} target="_blank" rel="noopener noreferrer">{conflict.target_path}</a>
|
||||
{:else}
|
||||
{conflict.target_path}
|
||||
{/if}
|
||||
</span>
|
||||
{#if canDeleteKind(conflict.kind)}
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
disabled={deleting}
|
||||
destructive
|
||||
title="Delete the existing {conflict.target_path} so {conflict.source_path} can take its place"
|
||||
onclick={() => (pending = { conflict, action: 'overwrite' })}
|
||||
>
|
||||
Overwrite target
|
||||
</Button>
|
||||
<Button
|
||||
unifiedSize="xs"
|
||||
variant="default"
|
||||
disabled={deleting}
|
||||
title="Delete {conflict.source_path} and keep the existing {conflict.target_path}"
|
||||
onclick={() => (pending = { conflict, action: 'discard' })}
|
||||
>
|
||||
Discard
|
||||
</Button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Alert>
|
||||
|
||||
<ConfirmationModal
|
||||
open={pending != undefined}
|
||||
title={pending?.action === 'overwrite' ? 'Overwrite target' : 'Discard reassigned item'}
|
||||
confirmationText="Delete"
|
||||
loading={deleting}
|
||||
trashbin={pending != undefined && isTrashedKind(pending.conflict.kind)}
|
||||
zIndexClass="z-[6000]"
|
||||
alwaysPortal
|
||||
onConfirmed={confirm}
|
||||
onCanceled={() => (pending = undefined)}
|
||||
>
|
||||
{#if pending}
|
||||
<p class="text-sm">
|
||||
{#if pending.action === 'overwrite'}
|
||||
The existing {kindLabel(pending.conflict.kind)}
|
||||
<span class="font-mono">{pending.conflict.target_path}</span> will be deleted, and
|
||||
<span class="font-mono">{pending.conflict.source_path}</span> will be moved to that path on reassignment.
|
||||
{:else}
|
||||
The {kindLabel(pending.conflict.kind)}
|
||||
<span class="font-mono">{pending.conflict.source_path}</span> will be deleted instead of
|
||||
being reassigned. The existing
|
||||
<span class="font-mono">{pending.conflict.target_path}</span> is kept.
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
</ConfirmationModal>
|
||||
@@ -4,12 +4,13 @@
|
||||
import { apiErrorMessage, classNames } from '$lib/utils'
|
||||
import { AlertTriangle, CornerDownLeft, Loader2 } from 'lucide-svelte'
|
||||
import { UserService, FolderService } from '$lib/gen'
|
||||
import type { OffboardPreview } from '$lib/gen/types.gen'
|
||||
import type { OffboardPathConflict, OffboardPreview } from '$lib/gen/types.gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import OffboardWorkspaceSection from './OffboardWorkspaceSection.svelte'
|
||||
import { countPaths } from './offboarding-utils'
|
||||
import OffboardConflictList from './OffboardConflictList.svelte'
|
||||
import { countPaths, withoutConflict } from './offboarding-utils'
|
||||
|
||||
type Props = {
|
||||
open: boolean
|
||||
@@ -24,7 +25,7 @@
|
||||
let preview = $state(undefined as OffboardPreview | undefined)
|
||||
let loading = $state(false)
|
||||
let submitting = $state(false)
|
||||
let conflicts: string[] = $state([])
|
||||
let conflicts: OffboardPathConflict[] = $state([])
|
||||
|
||||
let doReassign = $state(true)
|
||||
let targetKind: 'user' | 'folder' = $state('user')
|
||||
@@ -117,8 +118,8 @@
|
||||
delete_user: deleteUser
|
||||
}
|
||||
})
|
||||
if (result.conflicts && result.conflicts.length > 0) {
|
||||
conflicts = result.conflicts
|
||||
if (result.conflict_items && result.conflict_items.length > 0) {
|
||||
conflicts = result.conflict_items
|
||||
} else {
|
||||
sendUserToast(
|
||||
deleteUser
|
||||
@@ -221,17 +222,10 @@
|
||||
{/if}
|
||||
|
||||
{#if conflicts.length > 0}
|
||||
<Alert type="error" title="Path conflicts detected">
|
||||
<p class="text-xs mb-1"
|
||||
>These items already exist at the target. Rename or delete them, or choose a
|
||||
different user/folder.</p
|
||||
>
|
||||
<ul class="text-xs list-disc list-inside max-h-32 overflow-y-auto">
|
||||
{#each conflicts as conflict, i (i)}
|
||||
<li>{conflict}</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</Alert>
|
||||
<OffboardConflictList
|
||||
{conflicts}
|
||||
onResolved={(c) => (conflicts = withoutConflict(conflicts, c))}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -1,4 +1,25 @@
|
||||
import type { OffboardAffectedPaths } from '$lib/gen'
|
||||
import {
|
||||
AiEvalsService,
|
||||
AmqpTriggerService,
|
||||
AppService,
|
||||
AzureTriggerService,
|
||||
EmailTriggerService,
|
||||
FlowService,
|
||||
GcpTriggerService,
|
||||
HttpTriggerService,
|
||||
KafkaTriggerService,
|
||||
MqttTriggerService,
|
||||
NatsTriggerService,
|
||||
PostgresTriggerService,
|
||||
ResourceService,
|
||||
ScheduleService,
|
||||
ScriptService,
|
||||
SqsTriggerService,
|
||||
VariableService,
|
||||
WebsocketTriggerService,
|
||||
type OffboardAffectedPaths,
|
||||
type OffboardPathConflict
|
||||
} from '$lib/gen'
|
||||
|
||||
export function pl(n: number, singular: string): string {
|
||||
return `${n} ${singular}${n === 1 ? '' : 's'}`
|
||||
@@ -115,3 +136,85 @@ export function downloadCsv(rows: string[][], filename: string) {
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
type DeleteFn = (p: { workspace: string; path: string }) => Promise<unknown>
|
||||
|
||||
// Keyed by the table names the offboarding conflict check reports. Scripts and flows are
|
||||
// deleted rather than archived: an archived item still holds its path and keeps the conflict.
|
||||
const DELETE_BY_KIND: Record<string, DeleteFn> = {
|
||||
script: (p) => ScriptService.deleteScriptByPath(p),
|
||||
flow: (p) => FlowService.deleteFlowByPath(p),
|
||||
app: (p) => AppService.deleteApp(p),
|
||||
resource: (p) => ResourceService.deleteResource(p),
|
||||
variable: (p) => VariableService.deleteVariable(p),
|
||||
schedule: (p) => ScheduleService.deleteSchedule(p),
|
||||
eval_dataset: (p) => AiEvalsService.deleteEvalDataset(p),
|
||||
http_trigger: (p) => HttpTriggerService.deleteHttpTrigger(p),
|
||||
websocket_trigger: (p) => WebsocketTriggerService.deleteWebsocketTrigger(p),
|
||||
kafka_trigger: (p) => KafkaTriggerService.deleteKafkaTrigger(p),
|
||||
postgres_trigger: (p) => PostgresTriggerService.deletePostgresTrigger(p),
|
||||
mqtt_trigger: (p) => MqttTriggerService.deleteMqttTrigger(p),
|
||||
amqp_trigger: (p) => AmqpTriggerService.deleteAmqpTrigger(p),
|
||||
nats_trigger: (p) => NatsTriggerService.deleteNatsTrigger(p),
|
||||
sqs_trigger: (p) => SqsTriggerService.deleteSqsTrigger(p),
|
||||
gcp_trigger: (p) => GcpTriggerService.deleteGcpTrigger(p),
|
||||
azure_trigger: (p) => AzureTriggerService.deleteAzureTrigger(p),
|
||||
email_trigger: (p) => EmailTriggerService.deleteEmailTrigger(p)
|
||||
}
|
||||
|
||||
const TRASHED_KINDS = new Set(['script', 'flow', 'app', 'resource', 'variable', 'schedule'])
|
||||
|
||||
export function canDeleteKind(kind: string): boolean {
|
||||
return kind in DELETE_BY_KIND
|
||||
}
|
||||
|
||||
export function isTrashedKind(kind: string): boolean {
|
||||
return TRASHED_KINDS.has(kind)
|
||||
}
|
||||
|
||||
export async function deleteItemOfKind(
|
||||
kind: string,
|
||||
workspace: string,
|
||||
path: string
|
||||
): Promise<void> {
|
||||
const del = DELETE_BY_KIND[kind]
|
||||
if (!del) throw new Error(`Cannot delete items of kind ${kind}`)
|
||||
await del({ workspace, path })
|
||||
}
|
||||
|
||||
export function withoutConflict(
|
||||
conflicts: OffboardPathConflict[],
|
||||
resolved: OffboardPathConflict
|
||||
): OffboardPathConflict[] {
|
||||
return conflicts.filter(
|
||||
(c) =>
|
||||
!(
|
||||
c.workspace_id === resolved.workspace_id &&
|
||||
c.kind === resolved.kind &&
|
||||
c.source_path === resolved.source_path
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deleting a resource also deletes the variables linked to it, which can remove one side of a
|
||||
* variable conflict. Returns the remaining conflicts that no longer have both sides, so the list
|
||||
* does not offer to "keep" an item that is already gone.
|
||||
*/
|
||||
export async function conflictsGoneAfterDelete(
|
||||
deletedKind: string,
|
||||
remaining: OffboardPathConflict[]
|
||||
): Promise<OffboardPathConflict[]> {
|
||||
if (deletedKind !== 'resource') return []
|
||||
const variables = remaining.filter((c) => c.kind === 'variable')
|
||||
const gone = await Promise.all(
|
||||
variables.map(async (c) => {
|
||||
const [source, target] = await Promise.all([
|
||||
VariableService.existsVariable({ workspace: c.workspace_id, path: c.source_path }),
|
||||
VariableService.existsVariable({ workspace: c.workspace_id, path: c.target_path })
|
||||
])
|
||||
return !source || !target
|
||||
})
|
||||
)
|
||||
return variables.filter((_, i) => gone[i])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user