Skip to content

Conversation

@purejava
Copy link
Contributor

@coderabbitai
Copy link

coderabbitai bot commented Jul 31, 2025

Walkthrough

Adds Flatpak update support: pom.xml introduces properties for slf4j, jackson, and flatpak-update-portal and adds dependencies for jackson-databind and flatpak-update-portal. module-info.java gains requires for org.purejava.portal, java.net.http, and com.fasterxml.jackson.databind, opens the update package to the integrations API, and provides UpdateMechanism with FlatpakUpdater. New classes: FlatpakUpdater (implements update checks, DBus-monitored preparation, cancellation/await/apply flow, and Appstream response models) and FlatpakUpdateInfo (record). A service provider file registers FlatpakUpdater as an UpdateService implementation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java for:
    • HTTP appstream parsing, version selection/semver comparison, and JSON mapping types.
    • Concurrency and lifecycle (CountDownLatch, AtomicBoolean, signal handler registration/unregistration, portal/monitor closure).
    • Error handling and exception propagation (UpdateFailedException, InterruptedException, DBus errors).
    • apply/update spawn logic and process arguments/flags.
  • Confirm module-info.java additions match actual module/artifact names and required exports/opens.
  • Verify pom.xml dependency versions and that added dependencies are used/imported correctly.
  • Check META-INF/services entry correctness and FlatpakUpdateInfo public API surface.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Feature/flatpak update portal' is directly related to the main changes in the changeset, which implement Flatpak-based update support for Linux via the UpdatePortal service.
Description check ✅ Passed The description references a dependency on a related PR in the integrations-api repository, which is relevant context for understanding the changes in this PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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: 5

🧹 Nitpick comments (2)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (2)

49-52: Remove redundant CreateUpdateMonitor call in constructor.

The CreateUpdateMonitor call in the constructor appears redundant as it's called again in getUpdateMonitor() method, and its return value is ignored here.

 public FlatpakUpdater() {
     this.portal = new UpdatePortal();
-    portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY);
 }

173-193: Consider extracting a helper method to reduce code duplication.

The pattern of extracting string values from variants is repeated multiple times.

+private String extractStringFromVariant(Map<String, Variant<?>> map, String key) {
+    Variant<?> variant = map.get(key);
+    return variant != null ? (String) variant.getValue() : "";
+}
+
 private void notifyOnUpdateAvailable(Flatpak.UpdateMonitor.UpdateAvailable signal) {
-    String remoteCommit = "";
-    Variant<?> remoteCommitVariant = signal.update_info.get("remote-commit");
-    if (null != remoteCommitVariant) {
-        remoteCommit = (String) remoteCommitVariant.getValue();
-    }
-    String runningCommit = "";
-    Variant<?> runningCommitVariant = signal.update_info.get("running-commit");
-    if (null != runningCommitVariant) {
-        runningCommit = (String) runningCommitVariant.getValue();
-    }
-    String localCommit = "";
-    Variant<?> localCommitVariant = signal.update_info.get("local-commit");
-    if (null != localCommitVariant) {
-        localCommit = (String) localCommitVariant.getValue();
-    }
+    String remoteCommit = extractStringFromVariant(signal.update_info, "remote-commit");
+    String runningCommit = extractStringFromVariant(signal.update_info, "running-commit");
+    String localCommit = extractStringFromVariant(signal.update_info, "local-commit");
     UpdateAvailable updateAvailable = new UpdateAvailable(runningCommit, localCommit, remoteCommit);
     for (UpdateAvailableListener listener : updateAvailableListeners) {
         listener.onUpdateAvailable(updateAvailable);
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 48d0261 and a2607d7.

📒 Files selected for processing (4)
  • pom.xml (2 hunks)
  • src/main/java/module-info.java (2 hunks)
  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1 hunks)
  • src/main/resources/META-INF/services/org.cryptomator.integrations.update.UpdateService (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
src/main/java/module-info.java (1)

Learnt from: infeo
PR: #80
File: src/main/java/org/cryptomator/linux/autostart/FreedesktopAutoStartService.java:56-62
Timestamp: 2024-07-16T22:36:32.769Z
Learning: For the FreedesktopAutoStartService in the Cryptomator project, exceptions are preferred to contain all necessary debugging information without additional logging before throwing them.

src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1)

Learnt from: infeo
PR: #80
File: src/main/java/org/cryptomator/linux/autostart/FreedesktopAutoStartService.java:56-62
Timestamp: 2024-07-16T22:36:32.769Z
Learning: For the FreedesktopAutoStartService in the Cryptomator project, exceptions are preferred to contain all necessary debugging information without additional logging before throwing them.

🔇 Additional comments (4)
src/main/resources/META-INF/services/org.cryptomator.integrations.update.UpdateService (1)

1-1: LGTM!

The service provider configuration correctly registers the FlatpakUpdater implementation.

pom.xml (2)

43-43: Verify the use of SNAPSHOT version for production readiness.

The PR depends on a SNAPSHOT version of integrations-api. If this PR is intended for production, consider waiting for the stable release of version 1.7.0.


46-46: LGTM!

The new Flatpak update portal dependency is properly configured with a stable version.

Also applies to: 92-96

src/main/java/module-info.java (1)

6-6: LGTM!

The module configuration correctly integrates the new Flatpak update service with proper dependencies, service provisions, and package access.

Also applies to: 9-9, 14-14, 22-22, 31-31, 36-36

Comment on lines 60 to 67
public UpdateCheckerTask getLatestReleaseChecker(DistributionChannel.Value channel) {
if (channel != DistributionChannel.Value.LINUX_FLATPAK) {
LOG.error("Wrong channel provided: {}", channel);
return null;
}
portal.setUpdateCheckerTaskFor(APP_NAME);
return portal.getUpdateCheckerTaskFor(APP_NAME);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Throw exception instead of returning null for invalid channel.

Returning null for an invalid channel could lead to NullPointerException in the calling code. Consider throwing an IllegalArgumentException instead.

 @Override
 public UpdateCheckerTask getLatestReleaseChecker(DistributionChannel.Value channel) {
     if (channel != DistributionChannel.Value.LINUX_FLATPAK) {
-        LOG.error("Wrong channel provided: {}", channel);
-        return null;
+        throw new IllegalArgumentException("Wrong channel provided: " + channel + ". Expected: LINUX_FLATPAK");
     }
     portal.setUpdateCheckerTaskFor(APP_NAME);
     return portal.getUpdateCheckerTaskFor(APP_NAME);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public UpdateCheckerTask getLatestReleaseChecker(DistributionChannel.Value channel) {
if (channel != DistributionChannel.Value.LINUX_FLATPAK) {
LOG.error("Wrong channel provided: {}", channel);
return null;
}
portal.setUpdateCheckerTaskFor(APP_NAME);
return portal.getUpdateCheckerTaskFor(APP_NAME);
}
@Override
public UpdateCheckerTask getLatestReleaseChecker(DistributionChannel.Value channel) {
if (channel != DistributionChannel.Value.LINUX_FLATPAK) {
throw new IllegalArgumentException("Wrong channel provided: " + channel + ". Expected: LINUX_FLATPAK");
}
portal.setUpdateCheckerTaskFor(APP_NAME);
return portal.getUpdateCheckerTaskFor(APP_NAME);
}
🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
60 to 67, the method getLatestReleaseChecker returns null when an invalid
channel is provided, which risks causing NullPointerExceptions. Replace the null
return with throwing an IllegalArgumentException that clearly states the channel
is invalid. This change ensures callers are immediately informed of the misuse
and can handle the error properly.

Comment on lines 70 to 73
public void triggerUpdate() throws UpdateFailedException {
var monitor = getUpdateMonitor();
portal.updateApp("x11:0", monitor, UpdatePortal.OPTIONS_DUMMY);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid hardcoding the display parameter.

The hardcoded "x11:0" display parameter may not work correctly in Wayland environments or other display configurations.

Consider obtaining the display parameter dynamically:

 @Override
 public void triggerUpdate() throws UpdateFailedException {
     var monitor = getUpdateMonitor();
-    portal.updateApp("x11:0", monitor, UpdatePortal.OPTIONS_DUMMY);
+    String display = System.getenv("DISPLAY");
+    if (display == null || display.isEmpty()) {
+        display = System.getenv("WAYLAND_DISPLAY");
+        if (display != null && !display.isEmpty()) {
+            display = "wayland:" + display;
+        } else {
+            display = "x11:0"; // fallback
+        }
+    }
+    portal.updateApp(display, monitor, UpdatePortal.OPTIONS_DUMMY);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void triggerUpdate() throws UpdateFailedException {
var monitor = getUpdateMonitor();
portal.updateApp("x11:0", monitor, UpdatePortal.OPTIONS_DUMMY);
}
@Override
public void triggerUpdate() throws UpdateFailedException {
var monitor = getUpdateMonitor();
String display = System.getenv("DISPLAY");
if (display == null || display.isEmpty()) {
display = System.getenv("WAYLAND_DISPLAY");
if (display != null && !display.isEmpty()) {
display = "wayland:" + display;
} else {
display = "x11:0"; // fallback
}
}
portal.updateApp(display, monitor, UpdatePortal.OPTIONS_DUMMY);
}
🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
70 to 73, the display parameter "x11:0" is hardcoded in the portal.updateApp
call, which can cause issues in Wayland or other display environments. Modify
the code to dynamically obtain the display parameter from the environment or
system properties instead of using a fixed string. Replace the hardcoded "x11:0"
with a variable that retrieves the current display setting at runtime.

Comment on lines 98 to 108
@Override
public void close() throws Exception {
try {
if (null != updateMonitor) {
portal.cancelUpdateMonitor(updateMonitor);
}
portal.close();
} catch (Exception e) {
LOG.error(e.toString(), e.getCause());
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve exception handling in close method.

The current implementation catches a generic Exception and the logging could be more informative.

 @Override
 public void close() throws Exception {
     try {
         if (null != updateMonitor) {
             portal.cancelUpdateMonitor(updateMonitor);
         }
         portal.close();
-    } catch (Exception e) {
-        LOG.error(e.toString(), e.getCause());
+    } catch (DBusException e) {
+        LOG.error("Failed to close DBus connection properly", e);
+        throw e;
+    } catch (Exception e) {
+        LOG.error("Unexpected error during resource cleanup", e);
+        throw e;
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public void close() throws Exception {
try {
if (null != updateMonitor) {
portal.cancelUpdateMonitor(updateMonitor);
}
portal.close();
} catch (Exception e) {
LOG.error(e.toString(), e.getCause());
}
}
@Override
public void close() throws Exception {
try {
if (null != updateMonitor) {
portal.cancelUpdateMonitor(updateMonitor);
}
portal.close();
} catch (DBusException e) {
LOG.error("Failed to close DBus connection properly", e);
throw e;
} catch (Exception e) {
LOG.error("Unexpected error during resource cleanup", e);
throw e;
}
}
🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
98 to 108, improve the exception handling in the close method by catching more
specific exceptions if possible, and enhance the logging to provide a clearer
and more informative message. Instead of logging e.toString() and e.getCause()
separately, log the full exception with its stack trace to capture complete
context for debugging.

Comment on lines 195 to 226
private void notifyOnUpdateProceeds(Flatpak.UpdateMonitor.Progress signal) {
long status = ((UInt32) signal.info.get("status").getValue()).longValue();
long progress = 0;
Variant<?> progressVariant = signal.info.get("progress");
if (null != progressVariant) {
progress = ((UInt32) progressVariant.getValue()).longValue();
}
long nOps = -1;
Variant<?> nOpsVariant = signal.info.get("n_ops");
if (null != nOpsVariant) {
nOps = ((UInt32) nOpsVariant.getValue()).longValue();
}
long oP = -1;
Variant<?> oPVariant = signal.info.get("op");
if (null != oPVariant) {
oP = ((UInt32) oPVariant.getValue()).longValue();
}
String error = "";
Variant<?> errorVariant = signal.info.get("error");
if (null != errorVariant) {
error = (String) errorVariant.getValue();
}
String errorMessage = "";
Variant<?> errorMessageVariant = signal.info.get("error_message");
if (null != errorMessageVariant) {
errorMessage = (String) errorMessageVariant.getValue();
}
Progress p = new Progress(nOps, oP, status, progress, error, errorMessage);
for (ProgressListener listener : progressListeners) {
listener.onProgress(p);
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add type safety checks and reduce code duplication.

The direct cast without type checking could throw ClassCastException. Also, the code has repetitive patterns.

+private long extractLongFromVariant(Map<String, Variant<?>> map, String key, long defaultValue) {
+    Variant<?> variant = map.get(key);
+    if (variant != null && variant.getValue() instanceof UInt32) {
+        return ((UInt32) variant.getValue()).longValue();
+    }
+    return defaultValue;
+}
+
 private void notifyOnUpdateProceeds(Flatpak.UpdateMonitor.Progress signal) {
-    long status = ((UInt32) signal.info.get("status").getValue()).longValue();
-    long progress = 0;
-    Variant<?> progressVariant = signal.info.get("progress");
-    if (null != progressVariant) {
-        progress = ((UInt32) progressVariant.getValue()).longValue();
-    }
-    long nOps = -1;
-    Variant<?> nOpsVariant = signal.info.get("n_ops");
-    if (null != nOpsVariant) {
-        nOps = ((UInt32) nOpsVariant.getValue()).longValue();
-    }
-    long oP = -1;
-    Variant<?> oPVariant = signal.info.get("op");
-    if (null != oPVariant) {
-        oP = ((UInt32) oPVariant.getValue()).longValue();
-    }
-    String error = "";
-    Variant<?> errorVariant = signal.info.get("error");
-    if (null != errorVariant) {
-        error = (String) errorVariant.getValue();
-    }
-    String errorMessage = "";
-    Variant<?> errorMessageVariant = signal.info.get("error_message");
-    if (null != errorMessageVariant) {
-        errorMessage = (String) errorMessageVariant.getValue();
-    }
+    long status = extractLongFromVariant(signal.info, "status", 0);
+    long progress = extractLongFromVariant(signal.info, "progress", 0);
+    long nOps = extractLongFromVariant(signal.info, "n_ops", -1);
+    long oP = extractLongFromVariant(signal.info, "op", -1);
+    String error = extractStringFromVariant(signal.info, "error");
+    String errorMessage = extractStringFromVariant(signal.info, "error_message");
     Progress p = new Progress(nOps, oP, status, progress, error, errorMessage);
     for (ProgressListener listener : progressListeners) {
         listener.onProgress(p);
     }
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java lines 195 to
226, the method notifyOnUpdateProceeds directly casts values from signal.info
without type checks, risking ClassCastException, and repeats similar code
patterns. Refactor by adding type checks before casting to ensure safety, and
extract the repeated pattern of retrieving and casting values from the map into
a helper method to reduce duplication and improve readability.

Copy link

@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: 1

♻️ Duplicate comments (4)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (4)

59-62: Avoid hardcoding the display parameter.

The hardcoded "x11:0" display parameter may not work correctly in Wayland environments or other display configurations.

Consider obtaining the display parameter dynamically:

 @Override
 public void triggerUpdate() throws UpdateFailedException {
 	var monitor = getUpdateMonitor();
-	portal.updateApp("x11:0", monitor, UpdatePortal.OPTIONS_DUMMY);
+	String display = System.getenv("DISPLAY");
+	if (display == null || display.isEmpty()) {
+		display = System.getenv("WAYLAND_DISPLAY");
+		if (display != null && !display.isEmpty()) {
+			display = "wayland:" + display;
+		} else {
+			display = "x11:0"; // fallback
+		}
+	}
+	portal.updateApp(display, monitor, UpdatePortal.OPTIONS_DUMMY);
 }

82-92: Improve exception handling in close method.

The current implementation catches a generic Exception and the logging could be more informative. Additionally, exceptions should not be swallowed in close() method as per AutoCloseable contract.

 @Override
 public void close() throws Exception {
 	try {
 		if (null != updateMonitor) {
 			portal.cancelUpdateMonitor(updateMonitor);
 		}
 		portal.close();
-	} catch (Exception e) {
-		LOG.error(e.toString(), e.getCause());
+	} catch (DBusException e) {
+		LOG.error("Failed to close DBus connection properly", e);
+		throw e;
+	} catch (Exception e) {
+		LOG.error("Unexpected error during resource cleanup", e);
+		throw e;
 	}
 }

124-135: Add type safety checks to prevent ClassCastException.

The direct cast without type checking could throw ClassCastException. Add proper type validation before casting.

 private void notifyOnUpdateProceeds(Flatpak.UpdateMonitor.Progress signal) {
-	long status = ((UInt32) signal.info.get("status").getValue()).longValue();
+	long status = 0;
+	Variant<?> statusVariant = signal.info.get("status");
+	if (statusVariant != null && statusVariant.getValue() instanceof UInt32) {
+		status = ((UInt32) statusVariant.getValue()).longValue();
+	} else {
+		LOG.warn("Missing or invalid status in update progress signal");
+	}
+	
 	long progress = 0;
 	Variant<?> progressVariant = signal.info.get("progress");
-	if (null != progressVariant) {
+	if (progressVariant != null && progressVariant.getValue() instanceof UInt32) {
 		progress = ((UInt32) progressVariant.getValue()).longValue();
 	}
 	Progress p = new Progress(status, progress);
 	for (ProgressListener listener : progressListeners) {
 		listener.onProgress(p);
 	}
 }

94-112: Handle monitor creation failure more robustly.

The method can return null if monitor creation fails, which could cause NullPointerException in triggerUpdate(). Additionally, only the Progress signal handler is registered, missing the UpdateAvailable handler mentioned in past reviews.

-private synchronized Flatpak.UpdateMonitor getUpdateMonitor() {
+private synchronized Flatpak.UpdateMonitor getUpdateMonitor() throws UpdateFailedException {
 	if (updateMonitor == null) {
 		var updateMonitorPath = portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY);
 		if (updateMonitorPath != null) {
 			LOG.debug("UpdateMonitor successful created at {}", updateMonitorPath);
 			updateMonitor = portal.getUpdateMonitor(updateMonitorPath.toString());
 			try {
+				portal.getDBusConnection().addSigHandler(Flatpak.UpdateMonitor.UpdateAvailable.class, signal -> {
+					LOG.info("Update available signal received");
+					// Handle update available notification if needed
+				});
 				portal.getDBusConnection().addSigHandler(Flatpak.UpdateMonitor.Progress.class, signal -> {
 					notifyOnUpdateProceeds(signal);
 				});
 			} catch (DBusException e) {
-				LOG.error(e.toString(), e.getCause());
+				updateMonitor = null; // Reset on error
+				throw new UpdateFailedException("Failed to register DBus signal handlers", e);
 			}
 		} else {
-			LOG.error("Failed to create UpdateMonitor on DBus");
+			throw new UpdateFailedException("Failed to create UpdateMonitor on DBus");
 		}
 	}
 	return updateMonitor;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a2607d7 and 4976dde.

📒 Files selected for processing (1)
  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: for the `freedesktopautostartservice` in the cryptomator project, exceptions are preferred to contai...
Learnt from: infeo
PR: cryptomator/integrations-linux#80
File: src/main/java/org/cryptomator/linux/autostart/FreedesktopAutoStartService.java:56-62
Timestamp: 2024-07-16T22:36:32.769Z
Learning: For the `FreedesktopAutoStartService` in the Cryptomator project, exceptions are preferred to contain all necessary debugging information without additional logging before throwing them.

Applied to files:

  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java

Comment on lines +42 to +45
public FlatpakUpdater() {
this.portal = new UpdatePortal();
portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unnecessary monitor creation in constructor.

The constructor creates an update monitor but doesn't check or use the result. This monitor should be created lazily when first needed via getUpdateMonitor().

 public FlatpakUpdater() {
 	this.portal = new UpdatePortal();
-	portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public FlatpakUpdater() {
this.portal = new UpdatePortal();
portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY);
}
public FlatpakUpdater() {
this.portal = new UpdatePortal();
}
🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java between lines
42 and 45, remove the call to
portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY) from the constructor
since the update monitor is created but never used there. Instead, implement
lazy initialization of the update monitor inside the getUpdateMonitor() method
so that the monitor is only created when first accessed.

Copy link

@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

♻️ Duplicate comments (2)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (2)

41-44: Remove redundant monitor creation in constructor

portal.CreateUpdateMonitor(...) is invoked eagerly but its result is ignored and a fresh monitor is created later in prepareUpdate(), wasting a DBus round-trip. Drop this call and lazily create the monitor only when needed.


99-106: Handle potential DBusException from updateApp and make display selection dynamic

  1. portal.updateApp(...) can throw DBusException; wrap the call in try/catch and fail the latch accordingly.
  2. The display parameter is hard-coded to "x11:0", which breaks on Wayland or non-standard X11 displays. Obtain it from DISPLAY / WAYLAND_DISPLAY env vars with a fallback.
🧹 Nitpick comments (1)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1)

109-116: Null-safety for signal map access

signal.info.get("progress") is accessed without null-check before the cast at Line 114. Although unlikely, a missing key would raise NullPointerException. Guard with a null check:

Variant<?> progressVariant = signal.info.get("progress");
if (progressVariant != null && progressVariant.getValue() instanceof UInt32 u) {
    progress = u.doubleValue() / 100.0;
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4976dde and 2aa7b15.

📒 Files selected for processing (2)
  • src/main/java/module-info.java (2 hunks)
  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/module-info.java
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-16T22:36:32.769Z
Learnt from: infeo
PR: cryptomator/integrations-linux#80
File: src/main/java/org/cryptomator/linux/autostart/FreedesktopAutoStartService.java:56-62
Timestamp: 2024-07-16T22:36:32.769Z
Learning: For the `FreedesktopAutoStartService` in the Cryptomator project, exceptions are preferred to contain all necessary debugging information without additional logging before throwing them.

Applied to files:

  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java

Comment on lines 51 to 73
@Override
public boolean isUpdateAvailable() {
var cdl = new CountDownLatch(1);
portal.setUpdateCheckerTaskFor(APP_NAME);
var checkTask = portal.getUpdateCheckerTaskFor(APP_NAME);
var updateAvailable = new AtomicBoolean(false);
checkTask.setOnSucceeded(latestVersion -> {
updateAvailable.set(true); // TODO: compare version strings before setting this to true
cdl.countDown();
});
checkTask.setOnFailed(error -> {
LOG.warn("Error while checking for updates.", error);
cdl.countDown();
});
try {
cdl.await();
return updateAvailable.get();
} catch (InterruptedException e) {
checkTask.cancel();
Thread.currentThread().interrupt();
return false;
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add timeout and proper version comparison in update check

isUpdateAvailable() blocks indefinitely on cdl.await() and sets the flag to true without validating that latestVersion is newer than the running one.
• Specify a sensible timeout (e.g. 30 s) and abort gracefully.
• Compare latestVersion with BuildConfig.version() (or similar) before returning true.

🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java between lines
51 and 73, the isUpdateAvailable() method currently blocks indefinitely on
cdl.await() and sets updateAvailable to true without verifying if the
latestVersion is actually newer than the current version. To fix this, add a
timeout (e.g., 30 seconds) to the cdl.await() call to prevent indefinite
blocking and handle the timeout case gracefully. Also, modify the onSucceeded
handler to compare the received latestVersion string with the current version
from BuildConfig.version() (or equivalent) and only set updateAvailable to true
if the latestVersion is newer.

Comment on lines +154 to +158
portal.cancelUpdateMonitor(monitor);
stopReceivingSignals();
portal.close(); // TODO: is this right? belongs to parent class. update can not be retried afterwards. or should each process have its own portal instance?
error = new UpdateFailedException("Update cancelled by user");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Portal lifecycle & resource leak

cancel() closes the shared portal, but the normal success path (applyUpdate) never does, leaving the DBus connection open for the lifetime of the JVM. Either:
• Make FlatpakUpdateProcess own a dedicated UpdatePortal and always close it in finally, or
• Let FlatpakUpdater implement AutoCloseable and close the portal when the application shuts down.

🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
154 to 158, the shared portal is closed on cancel but not on successful update,
causing a resource leak. To fix this, either refactor FlatpakUpdateProcess to
own a dedicated UpdatePortal instance and ensure it is closed in a finally block
after update attempts, or modify FlatpakUpdater to implement AutoCloseable and
close the shared portal when the application shuts down, ensuring the DBus
connection is properly released in all cases.

Copy link

@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

♻️ Duplicate comments (4)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (4)

40-43: Remove unused UpdateMonitor creation in constructor.

The constructor creates an UpdateMonitor at line 42 but doesn't capture or use the result. This is wasteful since firstStep() creates its own monitor when needed. Remove this call and rely on lazy initialization.

Apply this diff:

 public FlatpakUpdater() {
 	this.portal = new UpdatePortal();
-	portal.CreateUpdateMonitor(UpdatePortal.OPTIONS_DUMMY);
 }

101-110: Avoid hardcoding the display parameter.

Line 109 hardcodes "x11:0" which will fail in Wayland or non-standard X11 display configurations. Obtain the display parameter dynamically from environment variables.

Consider this approach:

+	private static String getDisplayParameter() {
+		String display = System.getenv("DISPLAY");
+		if (display != null && !display.isEmpty()) {
+			return display;
+		}
+		String waylandDisplay = System.getenv("WAYLAND_DISPLAY");
+		if (waylandDisplay != null && !waylandDisplay.isEmpty()) {
+			return "wayland:" + waylandDisplay;
+		}
+		return "x11:0"; // fallback
+	}
+
 	@Override
 	public void start() {
 		try {
 			this.signalHandler = portal.getDBusConnection().addSigHandler(Flatpak.UpdateMonitor.Progress.class, this::handleProgressSignal);
 		} catch (DBusException e) {
 			LOG.error("DBus error", e);
 			latch.countDown();
 		}
-		portal.updateApp("x11:0", monitor, UpdatePortal.OPTIONS_DUMMY);
+		portal.updateApp(getDisplayParameter(), monitor, UpdatePortal.OPTIONS_DUMMY);
 	}

156-162: Portal lifecycle issue: shared resource closed prematurely.

Line 160 closes the shared portal instance from the parent FlatpakUpdater, making it unusable for subsequent operations. The TODO comment indicates developer uncertainty. Either:

  • Let the parent FlatpakUpdater manage portal lifecycle (don't close here), or
  • Give each FlatpakUpdateStep its own portal instance

Recommended approach - remove portal closure from cancel:

 	@Override
 	public void cancel() {
 		portal.cancelUpdateMonitor(monitor);
 		stopReceivingSignals();
-		portal.close(); // TODO: is this right? belongs to parent class. update can not be retried afterwards. or should each process have its own portal instance?
 		error = new UpdateFailedException("Update cancelled by user");
 	}

And ensure FlatpakUpdater properly closes the portal when the updater itself is disposed (implement AutoCloseable or add cleanup method).


50-72: Add timeout to update availability check.

The cdl.await() call at line 65 blocks indefinitely. If the update check signal never arrives (e.g., due to DBus issues), this will hang forever. Add a reasonable timeout (e.g., 30 seconds) and handle the timeout case.

Apply this diff:

 	try {
-		cdl.await();
-		return updateAvailable.get();
+		if (!cdl.await(30, TimeUnit.SECONDS)) {
+			LOG.warn("Update check timed out after 30 seconds");
+			checkTask.cancel();
+			return false;
+		}
+		return updateAvailable.get();
 	} catch (InterruptedException e) {
 		checkTask.cancel();
 		Thread.currentThread().interrupt();
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08a7742 and ffb84d8.

📒 Files selected for processing (1)
  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1)
src/main/java/org/cryptomator/linux/autostart/FreedesktopAutoStartService.java (1)
  • CheckAvailability (21-81)
🔇 Additional comments (9)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (9)

45-48: LGTM!

The availability check correctly delegates to the portal's availability status.


74-82: LGTM!

The method properly validates the monitor creation and throws an appropriate exception on failure.


92-94: LGTM!

Simple constructor correctly stores the monitor reference.


96-99: LGTM!

Progress description is clear and properly formatted.


140-149: LGTM!

Signal handler cleanup is properly implemented with appropriate error handling.


151-154: LGTM!

Progress getter is correctly implemented with volatile field for thread safety.


164-172: LGTM!

Await methods correctly delegate to the CountDownLatch.


174-182: LGTM!

The non-blocking completion check with proper interrupt handling is correctly implemented.


184-187: LGTM!

Clean use of the UpdateStep.of() factory method.

Comment on lines +112 to +138
private void handleProgressSignal(Flatpak.UpdateMonitor.Progress signal) {
int status = ((UInt32) signal.info.get("status").getValue()).intValue();
switch (status) {
case 0 -> { // In progress
Variant<?> progressVariant = signal.info.get("progress");
if (progressVariant != null) {
progress = ((UInt32) progressVariant.getValue()).doubleValue() / 100.0; // progress reported as int in range [0, 100]
}
}
case 1 -> { // No update available
error = new UpdateFailedException("No update available");
latch.countDown();
}
case 2 -> { // Update complete
progress = 1.0;
latch.countDown();
}
case 3 -> { // Update failed
error = new UpdateFailedException("Update preparation failed");
latch.countDown();
}
default -> {
error = new UpdateFailedException("Unknown update status " + status);
latch.countDown();
}
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add null and type safety checks for signal data.

Line 113 performs an unsafe cast without checking if signal.info.get("status") is null or if the value is actually a UInt32. This risks NullPointerException or ClassCastException.

Apply defensive checks:

 private void handleProgressSignal(Flatpak.UpdateMonitor.Progress signal) {
-	int status = ((UInt32) signal.info.get("status").getValue()).intValue();
+	Variant<?> statusVariant = signal.info.get("status");
+	if (statusVariant == null || !(statusVariant.getValue() instanceof UInt32)) {
+		LOG.warn("Invalid or missing status in progress signal");
+		return;
+	}
+	int status = ((UInt32) statusVariant.getValue()).intValue();
 	switch (status) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private void handleProgressSignal(Flatpak.UpdateMonitor.Progress signal) {
int status = ((UInt32) signal.info.get("status").getValue()).intValue();
switch (status) {
case 0 -> { // In progress
Variant<?> progressVariant = signal.info.get("progress");
if (progressVariant != null) {
progress = ((UInt32) progressVariant.getValue()).doubleValue() / 100.0; // progress reported as int in range [0, 100]
}
}
case 1 -> { // No update available
error = new UpdateFailedException("No update available");
latch.countDown();
}
case 2 -> { // Update complete
progress = 1.0;
latch.countDown();
}
case 3 -> { // Update failed
error = new UpdateFailedException("Update preparation failed");
latch.countDown();
}
default -> {
error = new UpdateFailedException("Unknown update status " + status);
latch.countDown();
}
}
}
private void handleProgressSignal(Flatpak.UpdateMonitor.Progress signal) {
Variant<?> statusVariant = signal.info.get("status");
if (statusVariant == null || !(statusVariant.getValue() instanceof UInt32)) {
LOG.warn("Invalid or missing status in progress signal");
return;
}
int status = ((UInt32) statusVariant.getValue()).intValue();
switch (status) {
case 0 -> { // In progress
Variant<?> progressVariant = signal.info.get("progress");
if (progressVariant != null) {
progress = ((UInt32) progressVariant.getValue()).doubleValue() / 100.0; // progress reported as int in range [0, 100]
}
}
case 1 -> { // No update available
error = new UpdateFailedException("No update available");
latch.countDown();
}
case 2 -> { // Update complete
progress = 1.0;
latch.countDown();
}
case 3 -> { // Update failed
error = new UpdateFailedException("Update preparation failed");
latch.countDown();
}
default -> {
error = new UpdateFailedException("Unknown update status " + status);
latch.countDown();
}
}
}
🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
112 to 138, the code unsafely casts signal.info.get("status").getValue() to
UInt32 and similarly assumes "progress" exists and is UInt32 — add defensive
null and type checks: retrieve the Variant<?> statusVariant =
signal.info.get("status"), if null set error = new
UpdateFailedException("Missing update status") and latch.countDown(); otherwise
get Object statusVal = statusVariant.getValue(), verify statusVal instanceof
UInt32 before casting, and if not set error with a descriptive message and
latch.countDown(); apply the same pattern for the "progress" variant (check null
and instanceof UInt32 before using), and ensure every early-error path sets
error and counts down the latch so the caller is not left waiting.

Comment on lines 189 to 209
public UpdateStep applyUpdate() throws IllegalStateException, IOException {
if (!isDone()) {
throw new IllegalStateException("Update preparation is not complete");
}
stopReceivingSignals();
if (error != null) {
throw error;
}

// spawn new Cryptomator process:
var cwdPath = Util.stringToByteList(System.getProperty("user.dir"));
List<List<Byte>> argv = List.of(
Util.stringToByteList(APP_NAME));
Map<UInt32, FileDescriptor> fds = Collections.emptyMap();
Map<String, String> envs = Map.of();
UInt32 flags = new UInt32(FlatpakSpawnFlag.LATEST_VERSION.getValue());
Map<String, Variant<?>> options = UpdatePortal.OPTIONS_DUMMY;
var pid = portal.Spawn(cwdPath, argv, fds, envs, flags, options).longValue();
LOG.info("Spawned updated Cryptomator process with PID {}", pid);
return null;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Complete the implementation: return ProcessHandle instead of null.

Line 208 returns null, which violates the return type contract. The spawned process PID is logged but not returned as a ProcessHandle. Additionally, the portal is never closed in the success path, leaving the DBus connection open.

Consider these improvements:

 public UpdateStep applyUpdate() throws IllegalStateException, IOException {
 	if (!isDone()) {
 		throw new IllegalStateException("Update preparation is not complete");
 	}
 	stopReceivingSignals();
 	if (error != null) {
 		throw error;
 	}

 	// spawn new Cryptomator process:
 	var cwdPath = Util.stringToByteList(System.getProperty("user.dir"));
 	List<List<Byte>> argv = List.of(
 			Util.stringToByteList(APP_NAME));
 	Map<UInt32, FileDescriptor> fds = Collections.emptyMap();
 	Map<String, String> envs = Map.of();
 	UInt32 flags = new UInt32(FlatpakSpawnFlag.LATEST_VERSION.getValue());
 	Map<String, Variant<?>> options = UpdatePortal.OPTIONS_DUMMY;
-	var pid = portal.Spawn(cwdPath, argv, fds, envs, flags, options).longValue();
+	long pid = portal.Spawn(cwdPath, argv, fds, envs, flags, options).longValue();
 	LOG.info("Spawned updated Cryptomator process with PID {}", pid);
-	return null;
+	try {
+		return UpdateStep.of("Update complete", () -> ProcessHandle.of(pid).orElseThrow());
+	} catch (Exception e) {
+		throw new IOException("Failed to obtain ProcessHandle for spawned process", e);
+	}
 }

Note: Also address the portal lifecycle issue raised in the cancel() method review to ensure proper resource cleanup.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
189 to 209, the method applyUpdate currently logs the spawned process PID but
returns null and never closes the portal; change it to return a ProcessHandle
corresponding to the spawned PID (e.g., ProcessHandle.of(pid).orElseThrow(...)
or similar) instead of null, and ensure the portal is closed in the success path
before returning (mirror the cleanup used in the cancel() method or refactor
portal lifecycle so both success and cancel paths close it reliably), making
sure any thrown exceptions still result in portal closure to avoid leaking the
DBus connection.

Copy link

@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: 1

♻️ Duplicate comments (1)
src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1)

135-135: Stop hardcoding the X11 display for portal.updateApp.
Wayland sessions (and even non-:0 X11 seats) choke on "x11:0", so updateApp throws and the preparation step aborts immediately. Resolve the display token from DISPLAY/WAYLAND_DISPLAY with a fallback instead of hardcoding the X11 default.

-            portal.updateApp("x11:0", monitor, UpdatePortal.OPTIONS_DUMMY);
+            String displayToken = System.getenv("DISPLAY");
+            if (displayToken == null || displayToken.isBlank()) {
+                String waylandDisplay = System.getenv("WAYLAND_DISPLAY");
+                if (waylandDisplay != null && !waylandDisplay.isBlank()) {
+                    displayToken = "wayland:" + waylandDisplay;
+                }
+            }
+            if (displayToken == null || displayToken.isBlank()) {
+                displayToken = "x11:0";
+            }
+            portal.updateApp(displayToken, monitor, UpdatePortal.OPTIONS_DUMMY);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d20b008 and 92a010c.

📒 Files selected for processing (4)
  • pom.xml (3 hunks)
  • src/main/java/module-info.java (1 hunks)
  • src/main/java/org/cryptomator/linux/update/FlatpakUpdateInfo.java (1 hunks)
  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-16T22:36:32.769Z
Learnt from: infeo
Repo: cryptomator/integrations-linux PR: 80
File: src/main/java/org/cryptomator/linux/autostart/FreedesktopAutoStartService.java:56-62
Timestamp: 2024-07-16T22:36:32.769Z
Learning: For the `FreedesktopAutoStartService` in the Cryptomator project, exceptions are preferred to contain all necessary debugging information without additional logging before throwing them.

Applied to files:

  • src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java
🔇 Additional comments (1)
src/main/java/org/cryptomator/linux/update/FlatpakUpdateInfo.java (1)

6-7: FlatpakUpdateInfo record fits the UpdateInfo contract.
The record cleanly carries the version plus mechanism and lines up with the generics expected by UpdateInfo.

Comment on lines +183 to +188
public void cancel() {
portal.cancelUpdateMonitor(monitor);
stopReceivingSignals();
portal.close(); // TODO: is this right? belongs to parent class. update can not be retried afterwards. or should each process have its own portal instance?
error = new UpdateFailedException("Update cancelled by user");
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Ensure cancel completes and leaves the portal reusable.
After a user cancels, callers waiting on await()/isDone() block forever because the latch is never counted down. On top of that, closing the shared UpdatePortal here makes every subsequent update attempt with this FlatpakUpdater fail against the closed connection. Drop the close from the per-step cancel path and count the latch down so cancellation is deterministic; manage portal lifecycle at the updater level instead.

-            portal.cancelUpdateMonitor(monitor);
-            stopReceivingSignals();
-            portal.close(); // TODO: is this right? belongs to parent class. update can not be retried afterwards. or should each process have its own portal instance?
-            error = new UpdateFailedException("Update cancelled by user");
+            portal.cancelUpdateMonitor(monitor);
+            stopReceivingSignals();
+            error = new UpdateFailedException("Update cancelled by user");
+            latch.countDown();
🤖 Prompt for AI Agents
In src/main/java/org/cryptomator/linux/update/FlatpakUpdater.java around lines
183-188, the cancel() method currently closes the shared UpdatePortal and never
signals completion, causing await()/isDone() to block and later updates to fail
on a closed portal; modify cancel() to NOT call portal.close() (remove that
line), ensure the latch or completion signal used by await()/isDone() is counted
down (or set the done flag and notify listeners) so callers unblock
deterministically, keep portal.cancelUpdateMonitor(monitor) and
stopReceivingSignals(), and manage the portal lifecycle at the updater level
instead of per-step so subsequent updates can reuse the portal.

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.

2 participants