Skip to content

fix: importing stacks if files are in the data/stacks directory#161

Merged
kmendell merged 13 commits intomainfrom
fix/stack-import
May 11, 2025
Merged

fix: importing stacks if files are in the data/stacks directory#161
kmendell merged 13 commits intomainfrom
fix/stack-import

Conversation

@kmendell
Copy link
Member

@kmendell kmendell commented May 11, 2025

Fixes: #159

This PR also removes the auto update switch per satck, and requires a certain label to be used in the compose file

Summary by CodeRabbit

  • Documentation

    • Added a new guide explaining how to enable and configure automatic stack updates, including setup steps, label usage, and important considerations.
  • New Features

    • Improved detection of stacks eligible for auto-updates by inspecting Docker Compose service labels.
  • Bug Fixes

    • Enhanced handling of missing compose and metadata files, improving robustness when loading or importing stacks.
  • Refactor

    • Unified stack identification by directory name and removed reliance on deprecated metadata files.
    • Simplified stack rename and update logic for greater reliability.
  • Style

    • Updated user interface to remove auto-update toggles and related options from the stack editor.
  • Chores

    • Adjusted API and utility function signatures to streamline data handling and callback usage.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 11, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This change removes the autoUpdate property from stack metadata, API payloads, and UI, and refactors the auto-update eligibility check to rely on a specific label in the Docker Compose file (arcane.stack.auto-update: "true") instead of a metadata flag. Stack management is unified by using directory names as stack IDs, removing reliance on .stack.json files, and improving stack renaming and external stack import logic. Documentation is updated with a new guide explaining the label-based auto-update mechanism.

Changes

Files/Areas Change Summary
docs/docs/guides/auto-update.md Added a new documentation guide detailing Arcane's auto-update feature, explaining the label-based eligibility mechanism, configuration, and operational considerations.
src/lib/services/api/stack-api-service.ts Removed the autoUpdate parameter from the save method and from the payload sent to the API.
src/lib/services/docker/auto-update-service.ts Refactored the stack eligibility logic for auto-update: now parses each stack's compose YAML and checks for the arcane.stack.auto-update: "true" label on any service, instead of relying on a metadata flag. Improved error handling and logging.
src/lib/services/docker/stack-service.ts Removed reliance on .stack.json metadata files; stack ID and name are now set to the directory name. Improved handling of missing files, directory renaming, and external stack import. Simplified stack loading, updating, and creation logic. Updated function signatures and error handling accordingly.
src/lib/types/docker/stack.type.ts Updated the Stack interface: removed the optional meta property and added 'unknown' as a possible value for the status property.
src/lib/utils/api.util.ts Changed the handleApiResultWithCallbacks function: callbacks now receive unwrapped data or error instead of the full Result object, and loading state handling is clarified.
src/routes/api/stacks/[stackId]/+server.ts Removed extraction and usage of the autoUpdate property in the PUT handler; no longer passes it to the update service.
src/routes/stacks/[stackId]/+page.server.ts Removed the autoUpdate property from the editorState object returned by the load function.
src/routes/stacks/[stackId]/+page.svelte Removed all UI and logic related to the autoUpdate property. Updated save logic to handle only name, compose content, and env content. Enhanced navigation after save to handle stack ID changes. Disabled stack renaming in the UI when the stack is running.

Possibly related PRs

  • ofkm/arcane#143: Refactors stack handling by removing reliance on metadata files and using directory names as stack IDs, closely related to this PR's changes in stack directory naming and metadata removal.
  • ofkm/arcane#83: Introduces the original auto-update feature, including the autoUpdate flag in stack metadata and eligibility filtering, which this PR refactors to use label-based detection instead.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@kmendell kmendell changed the title fix: import 'non-running stacks fix: importing stacks if files are in the data/stacks directory May 11, 2025
@kmendell kmendell marked this pull request as ready for review May 11, 2025 03:53
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/lib/types/docker/stack.type.ts (1)

41-41: ⚠️ Potential issue

Remove unused autoUpdate property from StackUpdate interface.

The autoUpdate property is still present in the StackUpdate interface despite being removed from all the API methods and UI components. This appears to be an oversight since the PR removes the auto-update switch per stack.

 export interface StackUpdate {
 	name?: string;
 	composeContent?: string;
 	envContent?: string;
-	autoUpdate?: boolean;
 }
🧹 Nitpick comments (2)
docs/docs/guides/auto-update.md (1)

14-17: Align label syntax across the guide for clarity

The prose section uses the YAML-map style (arcane.stack.auto-update: "true"), whereas the example snippet later switches to the array style ('arcane.stack.auto-update=true'). New users may copy-paste the latter into a map block or vice-versa and hit a compose-parsing error.
Consider adding a short sentence explaining both styles and ensuring the sample matches the earlier wording, e.g.:

-      - 'arcane.stack.auto-update=true' # Enables auto-update …
+      # Either array or map style works – choose one:
+      # - 'arcane.stack.auto-update=true'   # array style
+      # arcane.stack.auto-update: "true"    # map style

Also applies to: 41-42

src/lib/services/docker/auto-update-service.ts (1)

115-133: Potential performance bottleneck – getStack serial lookup

Inside the eligibility loop we await getStack sequentially, which increases execution time proportionally to stack count.
Consider batching with Promise.all or at least parallelising eligibility checks:

const eligibleStacksForProcessing = (
  await Promise.all(
    allListedStacks
      .filter((s) => ['running', 'partially running'].includes(s.status))
      .map(async (s) => {
        try {
          const full = await getStack(s.id);
          return hasAutoUpdateLabel(full) ? s : null;
        } catch {
          return null;
        }
      })
  )
).filter(Boolean) as Stack[];

This remains bounded because per-stack work is mostly I/O-bound.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bae85ae and 975906b.

📒 Files selected for processing (9)
  • docs/docs/guides/auto-update.md (1 hunks)
  • src/lib/services/api/stack-api-service.ts (1 hunks)
  • src/lib/services/docker/auto-update-service.ts (2 hunks)
  • src/lib/services/docker/stack-service.ts (8 hunks)
  • src/lib/types/docker/stack.type.ts (1 hunks)
  • src/lib/utils/api.util.ts (1 hunks)
  • src/routes/api/stacks/[stackId]/+server.ts (1 hunks)
  • src/routes/stacks/[stackId]/+page.server.ts (0 hunks)
  • src/routes/stacks/[stackId]/+page.svelte (4 hunks)
💤 Files with no reviewable changes (1)
  • src/routes/stacks/[stackId]/+page.server.ts
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/routes/api/stacks/[stackId]/+server.ts (2)
src/lib/utils/try-catch.ts (1)
  • tryCatch (14-21)
src/lib/services/docker/stack-service.ts (1)
  • updateStack (533-595)
src/lib/services/docker/auto-update-service.ts (2)
src/lib/services/docker/stack-service.ts (3)
  • listStacks (1168-1192)
  • getStack (482-528)
  • fullyRedeployStack (794-827)
src/lib/types/docker/stack.type.ts (1)
  • Stack (22-35)
🪛 LanguageTool
docs/docs/guides/auto-update.md

[uncategorized] ~56-~56: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ggered, Arcane will typically perform a full stack redeployment (similar to `docker-compos...

(EN_COMPOUND_ADJECTIVE_INTERNAL)

🪛 Biome (1.9.4)
src/lib/services/docker/auto-update-service.ts

[error] 135-135: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (19)
src/routes/api/stacks/[stackId]/+server.ts (2)

9-9: Removed autoUpdate from request destructuring.

The destructuring of the request JSON now only extracts name, composeContent, and envContent, removing the previously extracted autoUpdate property. This change properly aligns with the PR objective of removing the auto-update switch per stack.


11-11: Updated stack update call to remove autoUpdate parameter.

The call to updateStack has been modified to only pass name, composeContent, and envContent as parameters, removing the autoUpdate flag. This properly implements the PR objective of removing auto-update per stack in favor of using labels in the compose file.

src/lib/services/api/stack-api-service.ts (1)

42-42: Removed autoUpdate parameter from save method signature.

The save method no longer accepts the autoUpdate parameter, which is consistent with the changes in the API endpoint and the overall goal of removing the per-stack auto-update flag. The method now only accepts the stack ID, name, content, and optional environment content.

src/lib/types/docker/stack.type.ts (1)

28-28: Added 'unknown' as a possible stack status value.

The status field in the Stack interface now includes 'unknown' as a possible value, which improves error handling when a stack's status cannot be determined. This change supports the goal of better stack import and management mentioned in the PR.

src/routes/stacks/[stackId]/+page.svelte (6)

14-14: Added navigation imports for stack ID changes.

Updated imports to include invalidateAll and goto from $app/navigation, which are needed for proper navigation handling after saving a stack with a modified ID. This is an important enhancement that supports the improved stack renaming mentioned in the PR objective.


46-46: Removed autoUpdate from change detection.

The hasChanges derived state calculation no longer includes checking for changes in the autoUpdate property, which is consistent with removing the auto-update switch per stack as described in the PR objectives.


61-63: Added tracking of original stack ID for redirection after save.

Now storing the original stack ID before saving, which enables the redirection logic to work correctly if the stack ID changes during the save operation (such as when renaming a stack). This enhancement improves the UX for stack renaming.


65-65: Removed autoUpdate parameter from save API call.

The call to stackApi.save now only passes the stack ID, name, compose content, and environment content, removing the autoUpdate parameter. This is consistent with the changes in the API service and the PR objective.


68-84: Enhanced navigation after stack save.

Added smarter navigation logic to handle the case when a stack ID changes after saving (such as during a rename operation). Now it will use goto to navigate to the new stack URL if the ID changed, maintaining a consistent UX. This improvement aligns with the PR goal of enhancing stack renaming.


253-256: Improved stack name editing UX.

Added appropriate UI restrictions for stack name editing by disabling the input field when the stack is running or partially running. Also added a helpful explanatory message to guide users. This improves the user experience by preventing potentially problematic rename operations while a stack is active.

src/lib/services/docker/auto-update-service.ts (3)

125-156: Label-detection logic can be simplified & hardened

  1. Optional chaining removes several null checks (service.labels?.).
  2. Support both = and : separators in array style, because users might write 'key:"true"'.
  3. Using some() over services is clearer.
-let stackIsEligibleByLabel = false;
-
-if (composeData && composeData.services) {
-  for (const serviceName in composeData.services) {
-    const service = composeData.services[serviceName];
-    if (service.labels) {
-      let labelValue: string | undefined = undefined;
-      if (Array.isArray(service.labels)) {
-        const foundLabel = service.labels.find((l: string) => l.startsWith('arcane.stack.auto-update='));
-        if (foundLabel) {
-          labelValue = foundLabel.split('=')[1];
-        }
-      } else if (typeof service.labels === 'object' && service.labels !== null) {
-        labelValue = service.labels['arcane.stack.auto-update'];
-      }
-      if (labelValue === 'true') {
-        stackIsEligibleByLabel = true;
-        break; // Found one service with the label, stack is eligible
-      }
-    }
-  }
-}
+const stackIsEligibleByLabel =
+  composeData?.services &&
+  Object.values(composeData.services).some((svc: any) => {
+    const labels = svc.labels;
+    if (!labels) return false;
+    if (Array.isArray(labels)) {
+      return labels.some((l: string) =>
+        /^arcane\.stack\.auto-update[:=]["']?true["']?$/i.test(l.trim())
+      );
+    }
+    return labels['arcane.stack.auto-update'] === 'true';
+  });

Benefits: fewer branches, case-insensitive match, and prevention of the Biome optional-chain warning.
[ suggest_essential_refactor ]

🧰 Tools
🪛 Biome (1.9.4)

[error] 135-135: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


183-187: checkStackImagesUpdate re-loads stack content inside tight loop

checkStackImagesUpdate internally calls getStack again, resulting in two disk reads per stack (eligibility + update check). Passing composeContent you already hold would halve the I/O:

-const updateAvailable = await checkStackImagesUpdate(stackToUpdate);
+const updateAvailable = await checkStackImagesUpdate({ ...stackToUpdate, composeContent: fullStack.composeContent });

Alternatively overload the util to accept raw compose as second arg.
[ suggest_optional_refactor ]


179-181: Lock handling looks correct – good job

The Set-based guard plus deletion in both success and error paths prevents stuck locks and concurrent redeploys.

Also applies to: 195-196, 200-207

src/lib/services/docker/stack-service.ts (6)

120-140: getStackMetaPath appears to be dead code – safe to delete.

Since .stack.json / meta.json files are no longer part of the design, this helper is no longer referenced anywhere in the module. Keeping it around:

  • keeps an unused StackMeta type import alive (line 11)
  • increases cognitive load for future readers

Consider deleting the helper and the StackMeta import to keep the codebase lean.

-import type { Stack, StackMeta, StackService, StackUpdate } from '$lib/types/docker/stack.type';
+import type { Stack, StackService, StackUpdate } from '$lib/types/docker/stack.type';
@@
-async function getStackMetaPath(stackId: string): Promise<string | null> {
-
-}

[ suggest_essential_refactor ]


235-253: Expensive full–container scan each call – use Docker API filters first.

getStackServices calls docker.listContainers({ all:true }) and then filters the entire container list in memory.
On hosts running many containers this becomes O(N) per stack inspection and can seriously degrade UI latency.

Because every Compose-created container carries com.docker.compose.project=<stackId> you can narrow the list at the daemon side:

-const containers = await docker.listContainers({
-  all: true
-});
+const containers = await docker.listContainers({
+  all: true,
+  filters: JSON.stringify({ label: [`com.docker.compose.project=${stackId}`] })
+});

Keep the secondary “name starts with” heuristic as a fallback only when the primary query returns zero results.

This change slashes both network payload and local CPU usage.
[ suggest_essential_refactor , performance ]


874-949: renameStack suffers from a race & missing atomicity safeguards.

  1. Between the directoryExists check (lines 910-918) and the subsequent fs.rename, another process could create the target directory, leading to an overwrite or unexpected EEXIST.
  2. The loop only retries 100 times; under a race it may still throw even though a name is actually free.
  3. No advisory lock is taken, so two concurrent rename requests can clash.

A safer pattern:

-while (counter <= MAX_ATTEMPTS) {
-  const pathToCheck = join(stacksDir, newUniqueDirName);
-  const exists = await directoryExists(pathToCheck);
-  if (!exists && newUniqueDirName !== currentStackId) break;
-
-}
+while (counter <= MAX_ATTEMPTS) {
+  try {
+    await fs.mkdir(join(stacksDir, newUniqueDirName), { recursive: false });
+    // If mkdir succeeds we immediately rename into the *empty* dir,
+    // guaranteeing uniqueness without TOCTOU.
+    await fs.rmdir(join(stacksDir, newUniqueDirName)); // remove the placeholder
+    break;
+  } catch (e: any) {
+    if (e.code !== 'EEXIST') throw e; // real error
+    newUniqueDirName = `${newDirBaseName}-${counter++}`;
+  }
+}

Alternatively wrap the whole operation in a filesystem lock (e.g., fs.open with O_EXCL).
[ suggest_optional_refactor , concurrency ]


1056-1119: Path-traversal / information-disclosure via untrusted label paths.

importExternalStack blindly trusts com.docker.compose.project.config_files, allowing a container author to point Arcane at any host-readable path (e.g. /etc/shadow).
Because you read the file and return its content to the UI/API, this is a serious security gap.

Mitigation guideline:

  1. Limit reads to a whitelist (e.g., sub-paths of /data/stacks, /var/lib/docker/volumes/**, etc.).
  2. Reject absolute paths that are outside the allowed roots.
  3. Use path.resolve() + prefix check before fs.readFile.

Example hardening patch:

-actualComposeFilePathUsed = pathToTry;
+const resolved = path.resolve(pathToTry);
+const allowedRoots = ['/data', '/var/lib/docker/volumes'];
+if (!allowedRoots.some((root) => resolved.startsWith(root))) {
+  throw new Error(
+    `Refusing to read compose file outside allowed roots: ${resolved}`
+  );
+}
+actualComposeFilePathUsed = resolved;

Fail fast rather than silently generating a new compose file; that makes exploitation harder and highlights mis-configured labels.
[ raise_critical_issue , security ]


1180-1189: Minor: keep hasArcaneMeta consistent or drop it.

discoverExternalStacks never sets hasArcaneMeta, so you patch it here.
If the flag is now redundant (metadata files are gone) consider removing it altogether to avoid future confusion.
Otherwise guarantee the field exists on all Stack objects by normalising in a single helper.
[ suggest_nitpick ]


1199-1223: isStackRunning duplicates container queries – combine them.

Two separate docker.listContainers calls double the network chatter.
You can reuse the first full list when the label filter returns nothing, or better – call the broad query once and partition locally.

const all = await docker.listContainers({ all: true });
const byLabel = all.filter(...label test...)
if (byLabel.length) return byLabel.some(c => c.State === 'running');
const byName = all.filter(...name test...);
return byName.some(c => c.State === 'running');

Saves an extra daemon round-trip and simplifies error handling.
[ suggest_optional_refactor , performance ]

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented May 11, 2025

Deploying arcane with  Cloudflare Pages  Cloudflare Pages

Latest commit: 9154fa4
Status: ✅  Deploy successful!
Preview URL: https://5e07bfff.arcane-7v3.pages.dev
Branch Preview URL: https://fix-stack-import.arcane-7v3.pages.dev

View logs

@kmendell kmendell merged commit 9bfb479 into main May 11, 2025
6 checks passed
@kmendell kmendell deleted the fix/stack-import branch May 11, 2025 17:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐞 Bug: import stacks doesnt work

1 participant