Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,31 +1,68 @@
package com.specificlanguages.mops.cli

import com.specificlanguages.mops.protocol.DaemonPaths
import com.specificlanguages.mops.protocol.DaemonWorkspace
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.io.CleanupMode
import org.junit.jupiter.api.io.TempDir
import org.junit.jupiter.api.parallel.ResourceLock
import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.createDirectories
import kotlin.io.path.isRegularFile
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.pathString
import kotlin.io.path.readText
import kotlin.io.path.writeText
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
import kotlin.test.assertFalse

@Tag("smoke")
@ResourceLock("system-streams")
class LibraryModelRefreshIntegrationTest {
@TempDir(cleanup = CleanupMode.ON_SUCCESS)
lateinit var tempDir: Path

@Test
fun `external edits of a library model outside the project folder are visible in the same daemon and after a restart`() {
val project = prepareProject()
val daemonHome = tempDir.resolve("daemon-home").createDirectories()
exerciseEdits(project, daemonHome) { args ->
runCommandLine(project, "--daemon-home", daemonHome.pathString, *javaAndMpsHomeArgs(), *args.toTypedArray())
}
if (watcherExpected) {
assertContains(daemonLogs(daemonHome), "refreshed external changes using file watcher events")
}
}

@Test
fun `external edits are visible with the native file watcher turned off`() {
val project = prepareProject()
val daemonHome = tempDir.resolve("daemon-home").createDirectories()
val cli = InstalledCli(
project, daemonHome, tempDir,
mapOf("MOPS_DAEMON_JAVA_OPTIONS" to "-Didea.filewatcher.disabled=true"),
)
exerciseEdits(project, daemonHome) { args -> cli.run(*args.toTypedArray()) }
val logs = daemonLogs(daemonHome)
assertContains(logs, "using a full walk because the file watcher is not operational")
assertFalse("using file watcher events" in logs, logs)
}

/** Copies the library fixture and moves its library folder out of the project folder. */
private fun prepareProject(): Path {
val project = copyTestProject("project-library", tempDir.resolve("project"))
val shared = Files.move(project.resolve("libs"), tempDir.resolve("shared"))
Files.move(project.resolve("libs"), tempDir.resolve("shared"))
val libraries = project.resolve(".mps/libraries.xml")
libraries.writeText(libraries.readText().replace("${'$'}PROJECT_DIR${'$'}/libs", "${'$'}PROJECT_DIR${'$'}/../shared"))
val libraryModel = shared.resolve("library/models/values.mps")
return project
}

private fun exerciseEdits(project: Path, daemonHome: Path, run: (List<String>) -> CliResult) {
val libraryModel = tempDir.resolve("shared/library/models/values.mps")
val projectModel = project.resolve("solutions/tests/models/library@tests.mps")
val daemonHome = tempDir.resolve("daemon-home").createDirectories()
val program = tempDir.resolve("names.groovy").also {
it.writeText("""
project.read {
Expand All @@ -35,10 +72,8 @@ class LibraryModelRefreshIntegrationTest {
}
""".trimIndent())
}
fun run(vararg args: String): CliResult =
runCommandLine(project, "--daemon-home", daemonHome.pathString, *javaAndMpsHomeArgs(), *args)
fun names(): String {
val result = run("code", "run", program.pathString)
val result = run(listOf("code", "run", program.pathString))
assertEquals(0, result.exitCode, result.output)
return result.stdout.trim()
}
Expand All @@ -58,11 +93,22 @@ class LibraryModelRefreshIntegrationTest {
rename(libraryModel, "LibraryValue", "LibraryValueEdited")
assertEquals("LibraryValueEdited;LibraryPassEdited", names(), "library model edit in the same daemon")

assertEquals(0, run("daemon", "stop").exitCode)
assertEquals(0, run(listOf("daemon", "stop")).exitCode)
rename(libraryModel, "LibraryValueEdited", "LibraryValueAfterRestart")
assertEquals("LibraryValueAfterRestart;LibraryPassEdited", names(), "edit while the daemon was stopped")
} finally {
stopDaemons(project, daemonHome)
}
}

private fun daemonLogs(daemonHome: Path): String =
DaemonPaths(daemonHome).projects.listDirectoryEntries()
.map { DaemonWorkspace(it).logFile() }.filter { it.isRegularFile() }.joinToString("\n") { it.readText() }

private companion object {
// Every supported MPS version ships fsnotifier for macOS and for Linux on x86-64.
val watcherExpected = System.getProperty("os.name").let { os ->
os.startsWith("Mac") || os.startsWith("Linux") && System.getProperty("os.arch") in setOf("amd64", "x86_64")
}
}
}
7 changes: 7 additions & 0 deletions daemon-mps-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ dependencies {
include("lib/mps-openapi.jar")
include("lib/mps-persistence.jar")
include("lib/util.jar")
// NativeFileWatcherImpl, PluggableFileWatcher, Notifications and their supertypes, for
// HeadlessNativeFileWatcher.
include("lib/util-8.jar")
include("lib/app.jar")
include("lib/intellij.platform.core.jar")
include("lib/intellij.platform.ide.core.jar")
include("lib/intellij.platform.ide.impl.jar")
include("plugins/mps-java/lib/java-core.jar")
include("plugins/java/lib/ecj/eclipse.jar")
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
package com.specificlanguages.mops.daemon.plugin

import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.vfs.impl.local.NativeFileWatcherImpl
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong

/**
* Adapter. The platform's native file watcher (`fsnotifier`), enabled in a headless application. The platform registers
* its own instance, which stays off in command-line and test applications; this second registration differs only in
* that check, and can still be turned off with `-Didea.filewatcher.disabled=true`.
*
* Hides: how the platform's native file watcher behaves in a headless application, including when it may have missed
* changes.
*
* Breaks `connascence-in-types`: the daemon calls [changeCount] and [recursiveRoots] by name, because the plugin class
* loader loads this class and the daemon cannot share a type with it. For the same reason, it names the platform's
* `idea.filewatcher.disabled` property itself, as `FileWatcherExecutable` in the daemon does.
*
* Breaks `adapter-cache`: it keeps the watch roots it was given and whether the watcher reported a failure, which are
* not a cache. The platform tells it about them only by calling [setWatchRoots] and by posting notifications, so
* [changeCount] and [recursiveRoots] are computed from what it kept.
*
* Thread-safe: the platform sets the roots and posts notifications on its own threads while request threads read
* [changeCount] and [recursiveRoots].
*/
class HeadlessNativeFileWatcher : NativeFileWatcherImpl() {
private val rootChanges = AtomicLong()

@Volatile
private var recursive: List<String> = emptyList()

@Volatile
private var flat: List<String> = emptyList()

@Volatile
private var failed = false

private val startAttempts: AtomicInteger? = startAttemptCounter()

init {
ApplicationManager.getApplication().messageBus.connect().subscribe(
Notifications.TOPIC,
object : Notifications {
override fun notify(notification: Notification) {
if (notification.groupId == FAILURE_GROUP) failed = true
}
},
)
}

override fun isDisabled(): Boolean = java.lang.Boolean.getBoolean(DISABLED_PROPERTY)

override fun setWatchRoots(recursive: List<String>, flat: List<String>, shuttingDown: Boolean) {
if (recursive != this.recursive || flat != this.flat) {
this.recursive = recursive
this.flat = flat
rootChanges.incrementAndGet()
}
super.setWatchRoots(recursive, flat, shuttingDown)
}

/**
* A number that changes whenever the watcher may have missed changes: when the watch roots change and when the
* `fsnotifier` process is started again. `null` once the watcher has reported a failure, such as the Linux inotify
* watch limit, or when the start count cannot be read.
*/
fun changeCount(): Long? {
val starts = startAttempts ?: return null
return if (failed) null else rootChanges.get() + starts.get()
}

/** The recursive watch roots as last set, canonical and system-dependent. */
fun recursiveRoots(): List<String> = recursive

/**
* The platform restarts a terminated `fsnotifier` without reporting anything as changed, but counts each start in a
* private field.
*/
private fun startAttemptCounter(): AtomicInteger? =
try {
NativeFileWatcherImpl::class.java.getDeclaredField("myStartAttemptCount")
.apply { isAccessible = true }
.get(this) as? AtomicInteger
} catch (_: ReflectiveOperationException) {
null
}

private companion object {
const val DISABLED_PROPERTY = "idea.filewatcher.disabled"
const val FAILURE_GROUP = "File Watcher Messages"
}
}
4 changes: 4 additions & 0 deletions daemon-mps-plugin/src/main/resources/META-INF/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,8 @@
<plugin id="jetbrains.mps.core" />
<plugin id="jetbrains.mps.ide.java" />
</dependencies>
<extensions defaultExtensionNs="com.intellij">
<vfs.local.pluggableFileWatcher
implementation="com.specificlanguages.mops.daemon.plugin.HeadlessNativeFileWatcher"/>
</extensions>
</idea-plugin>
Loading
Loading