diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8ee43eb --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,191 @@ +name: CI + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + push: + branches: [main] + +permissions: + contents: read + +jobs: + linux: + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + # Tomcat 9 and 10.1 on the JDK most projects use. + - java: "17" + tomcat: "" + # The oldest JDK the provider supports runs Tomcat 9, Maven and Gradle 8. + - java: "8" + tomcat: "9.0.124" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + # 17 compiles the provider (javac --release 8); the last version listed is the default. + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 17 + ${{ matrix.java }} + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: 8.14.3 + # The runner image sets GRADLE_HOME to its own Gradle, which the provider + # prefers over PATH; point it at the Gradle installed above. + - name: Use the installed Gradle + run: echo "GRADLE_HOME=$(dirname "$(dirname "$(readlink -f "$(command -v gradle)")")")" >> "$GITHUB_ENV" + - name: Download the pinned Tomcat versions + run: node scripts/test/fetch-tomcat.mjs + - name: Check the manifest and build the archives + env: + JAVA_HOME: ${{ env.JAVA_HOME_17_X64 }} + PATH_PREFIX: ${{ env.JAVA_HOME_17_X64 }}/bin + run: PATH="$PATH_PREFIX:$PATH" node scripts/package.mjs + - name: Run Web modules on real Tomcat + run: | + if [[ -n "${{ matrix.tomcat }}" ]]; then + export LITHE_TEST_TOMCAT_HOMES="$PWD/.artifacts/tomcat/apache-tomcat-${{ matrix.tomcat }}" + fi + java -version + node scripts/test.mjs + - name: Hand the Windows archive to the Windows job + if: matrix.java == '17' + uses: actions/upload-artifact@v4 + with: + name: tomcat-windows + path: dist/tomcat-*-windows.zip + if-no-files-found: error + - name: Validate against Lithe Store rules + if: matrix.java == '17' + run: | + git clone --depth 1 https://github.com/Lithe-IDEA/Lithe-store "$RUNNER_TEMP/store" + node --input-type=module -e " + import { readPackageManifests, checkManifest } from '$RUNNER_TEMP/store/scripts/validate-index.mjs'; + import { readdirSync, readFileSync } from 'node:fs'; + const manifest = JSON.parse(readFileSync('io.github.lithe-idea.tomcat/plugin.json', 'utf8')); + const entry = { id: manifest.id }; + let failed = false; + for (const name of readdirSync('dist').filter((name) => name.endsWith('.zip'))) { + const { manifests, unsafe } = readPackageManifests('dist/' + name, entry.id); + const problems = [...unsafe, ...checkManifest(manifests, entry, manifest)]; + for (const problem of problems) { console.error(name + ': ' + problem); failed = true; } + } + process.exit(failed ? 1 : 0); + " + - name: Upload timing reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: timings-linux-java-${{ matrix.java }} + path: .artifacts/test-stability/ + if-no-files-found: warn + + # The plugin in the real desktop host (e2e/host/, host pinned by e2e/host/lithe-host.json): + # installed through the host's installer next to the pinned Java Support package, a Web + # module runs and debugs from its run configuration. The host builds its own pinned Core. + host: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + needs: linux + runs-on: ubuntu-latest + timeout-minutes: 50 + steps: + - uses: actions/checkout@v4 + - name: Read the pinned host revision + id: host + run: echo "revision=$(node -p 'require("./e2e/host/lithe-host.json").revision')" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + repository: 1lck/Lithe-IDEA + ref: ${{ steps.host.outputs.revision }} + path: .artifacts/host-go + sparse-checkout: desktop/go.mod + sparse-checkout-cone-mode: false + - uses: actions/setup-go@v5 + with: + go-version-file: .artifacts/host-go/desktop/go.mod + cache: false + - uses: dtolnay/rust-toolchain@1.100.0 + - uses: actions/setup-node@v4 + with: + node-version: 22 + # 17 compiles the provider; 21 is the default, because the Java plugin's language + # server, which runs its java debug adapter, refuses older JDKs. + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: | + 17 + 21 + - name: Build the archives + env: + JAVA_HOME: ${{ env.JAVA_HOME_17_X64 }} + PATH_PREFIX: ${{ env.JAVA_HOME_17_X64 }}/bin + run: PATH="$PATH_PREFIX:$PATH" node scripts/package.mjs + - name: Download the pinned Tomcat versions + run: node scripts/test/fetch-tomcat.mjs + - name: Run and debug a Web module in the desktop host + run: | + version="$(node -p 'require("./io.github.lithe-idea.tomcat/plugin.json").version')" + export LITHE_TEST_TOMCAT_PLUGIN_ARCHIVE="$PWD/dist/tomcat-$version-linux.zip" + java_plugin="$(node scripts/test/fetch-java-plugin.mjs linux-x64)" + export LITHE_TEST_JAVA_PLUGIN_ARCHIVE="$java_plugin" + # Java Support finds the JDT language server outside its package, as a user installs it. + jdtls="$(node scripts/test/fetch-java-plugin.mjs --jdtls)" + export JDTLS_HOME="$jdtls" + export LITHE_TEST_TOMCAT_HOME="$PWD/.artifacts/tomcat/apache-tomcat-10.1.62" + java -version + node scripts/e2e-host.mjs + + # The Windows archive built above runs every Web module through mvn.cmd and + # gradle.bat, on the same Tomcat versions. + windows: + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + needs: linux + runs-on: windows-latest + timeout-minutes: 25 + defaults: + run: + shell: pwsh + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: 8.14.3 + - name: Use the installed Gradle + run: | + $gradle = (Get-Command gradle).Source + "GRADLE_HOME=$(Split-Path (Split-Path $gradle -Parent) -Parent)" | Out-File $env:GITHUB_ENV -Append -Encoding utf8 + - uses: actions/download-artifact@v4 + with: + name: tomcat-windows + path: ${{ runner.temp }}/archive + - name: Unpack the Windows archive + run: | + $archive = Get-ChildItem "$env:RUNNER_TEMP\archive\tomcat-*-windows.zip" | Select-Object -First 1 + Expand-Archive -Path $archive.FullName -DestinationPath "dist\package" + - name: Download the pinned Tomcat versions + run: node scripts/test/fetch-tomcat.mjs + - name: Run Web modules on real Tomcat + run: node scripts/test.mjs + - name: Upload timing reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: timings-windows + path: .artifacts/test-stability/ + if-no-files-found: warn diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..c1d4d37 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,63 @@ +name: Release + +# Push a tag v matching plugin.json to publish a draft GitHub Release. +# Lithe Store's tracker picks up stable releases and opens index pull requests. +# docs/releases/.md, when present, lists the changes. +on: + push: + tags: ["v*"] + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: gradle/actions/setup-gradle@v4 + with: + gradle-version: 8.14.3 + - name: Use the installed Gradle + run: echo "GRADLE_HOME=$(dirname "$(dirname "$(readlink -f "$(command -v gradle)")")")" >> "$GITHUB_ENV" + - name: Build the archives + run: | + set -o pipefail + node scripts/package.mjs --expect-tag "$GITHUB_REF_NAME" | tee "$RUNNER_TEMP/checksums.txt" + - name: Run Web modules on real Tomcat + run: | + node scripts/test/fetch-tomcat.mjs + node scripts/test.mjs + - name: Publish the draft release + env: + GH_TOKEN: ${{ github.token }} + run: | + { + if [[ -s "docs/releases/$GITHUB_REF_NAME.md" ]]; then + cat "docs/releases/$GITHUB_REF_NAME.md" + echo + else + # shellcheck disable=SC2016 # the template literal is JavaScript + node -e ' + const m = require("./io.github.lithe-idea.tomcat/plugin.json"); + const needs = Object.entries(m.requires || {}).map(([k, v]) => `${k} ${v}`).join("、"); + console.log(`兼容性:按插件契约 v${m.schemaVersion}(pluginAPIVersion ${m.pluginAPIVersion})编写,需要支持 ${needs} 的 Lithe 桌面端。`); + ' + echo + fi + echo "安装:Lithe Store(https://github.com/Lithe-IDEA/Lithe-store)中的 Tomcat 条目合并后,可在 设置 → 插件 → 插件市场 中搜索 Tomcat 并安装。" + echo + echo "SHA-256:" + echo '```' + grep '^dist/' "$RUNNER_TEMP/checksums.txt" | sed 's#^dist/##' + echo '```' + } > "$RUNNER_TEMP/notes.md" + gh release create "$GITHUB_REF_NAME" dist/*.zip --draft --title "Tomcat $GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/notes.md" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cf6ef60 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.artifacts/ +dist/ +provider/target/ +.DS_Store diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..69bef1d --- /dev/null +++ b/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and + for which the editorial revisions, annotations, elaborations, + or other modifications represent, as a whole, an original work + of authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely link + (or bind by name) to the interfaces of, the Work and Derivative Works + thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of + its distribution, then any Derivative Works that You + distribute must include a readable copy of the attribution + notices contained within such NOTICE file, excluding those + notices that do not pertain to any part of the Derivative + Works, in at least one of the following places: within a + NOTICE text file distributed as part of the Derivative Works; + within the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing + the origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as + a result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[ ]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..ab3eb1c --- /dev/null +++ b/NOTICE @@ -0,0 +1,11 @@ +Tomcat for Lithe +Copyright 2026 Lithe Community contributors + +This product is licensed under the Apache License, Version 2.0 (see LICENSE). + +vendor/lithe-plugin-sdk-java comes from the Lithe-core-rust repository +(shared/plugins/sdk/java) at the revision sdk.lock.json records, under the +license in vendor/LICENSE. + +The plugin does not include Apache Tomcat. It runs the Tomcat installation the +user chooses. diff --git a/README.md b/README.md index 7f65a1a..5090843 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,144 @@ -# lithe-plugin-tomcat -Lithe 的 Tomcat 支持插件 / Tomcat support plugin for Lithe +# Tomcat for Lithe + +为 [Lithe](https://github.com/1lck/Lithe-IDEA) 提供 Apache Tomcat 支持:识别工作区里的 Web 模块,构建后在 +Tomcat 上运行,并可以用 Java 调试器调试。这是一个**社区插件**,用插件契约 v0 的构建系统接口 +(`buildSystems`)和构建提供者(`buildProviders`)实现:一份 `plugin.json` 加一个 Java 8 编写的提供者 jar。 +Tomcat 进程由 Lithe 启动、停止和调试,插件只负责准备启动计划。 + +> English: Apache Tomcat support for Lithe. The plugin finds the Web modules of a workspace (Maven and Gradle +> `war` modules, Eclipse Dynamic Web Projects and plain Web folders), builds them, and prepares a Tomcat launch that +> Lithe starts, stops and debugs like any other service. Each module runs in its own CATALINA_BASE in Lithe's +> workspace state; the Tomcat installation, the workspace and the plugin package are only read. + +> **兼容性**:按插件契约 v0(`schemaVersion: 0`、`pluginAPIVersion: 0`)编写,需要支持 `buildSystems 0`、 +> `buildProviders 0` 和 `settings 0` 的 Lithe 桌面端。插件不带 Tomcat,运行用户自己安装的 Tomcat。 + +## 功能 + +| 功能 | 说明 | +| --- | --- | +| 识别 Web 模块 | Maven:`pom.xml` 的 `war`。Gradle:`build.gradle(.kts)` 应用了 `war` 插件。Eclipse Dynamic Web Project:`.settings/org.eclipse.wst.common.component` 把某个目录部署到 `/`。普通 Web 目录:`WEB-INF/web.xml` 在 `web`、`WebContent`、`WebRoot`、`webapp` 或 `src/main/webapp` 下 | +| 运行 | 每个 Web 模块在构建窗口和运行配置里有一项“Run on Tomcat”。Maven 模块在反应堆根用 `-pl <模块> -am -DskipTests package` 构建,先构建它依赖的模块;Gradle 模块运行 `war` 任务 | +| 原地运行 | Eclipse 项目和普通 Web 目录不打包,直接以 Web 目录作为应用,编译输出目录(`.classpath` 的 `output`,或 `out/production/<名字>`、`build/classes`、`bin`、`classes`)挂到 `/WEB-INF/classes`,并开启类重载。修改 JSP、HTML 后刷新即可看到,不需要重新部署 | +| 调试 | 运行配置选“调试”时,Tomcat 以 `suspend=y` 等待调试器,Lithe 用已安装的 Java 调试器(调试类型 `java`)连接到它自己分配的端口 | +| 访问地址 | `http://localhost:<端口><上下文路径>/`。上下文路径:Eclipse 项目用组件文件的 `context-root`,Maven 模块用 `artifactId`,其他用目录名 | +| 同步 | `pom.xml`、`build.gradle(.kts)`、`.project`、`web.xml` 变化后重新读取模块 | + +## 设置 + +设置 → 插件 → Tomcat →「设置」,也显示在 Tomcat 构建系统的设置页: + +| 设置 | 说明 | +| --- | --- | +| Tomcat 安装目录 | 运行用的 Tomcat(CATALINA_HOME)。留空时使用环境变量 `CATALINA_HOME`。必须包含 `bin/bootstrap.jar`、`bin/tomcat-juli.jar`、`lib/catalina.jar` 和 `conf/web.xml` | +| HTTP 端口 | Tomcat 在 `127.0.0.1` 上监听的端口,默认 8080,可按项目覆盖。运行前会检查端口是否被占用 | + +运行配置里的“VM 选项”和环境变量会传给 Tomcat 的 JVM。Tomcat 运行不接受程序参数,填写时运行会报错,而不是被悄悄忽略。 + +## 工作方式 + +1. Lithe 发现工作区里有 `pom.xml`、`build.gradle(.kts)`、`.project` 或 `web.xml` 时,建立 Tomcat 构建实例。 + 用户第一次打开构建窗口或运行时,Lithe 用项目 JDK 启动 `lib/lithe-tomcat-provider.jar`。 +2. 提供者回答 `lithe/build/model`:有界遍历实例目录(最多 8 层、5000 个目录,跳过 `target`、`build`、 + `out`、`bin`、`node_modules`、`src` 和以点开头的目录),每个 Web 模块是一个项目和一个带 + `web-application` 标签的目标。没有 Web 模块的 Maven 或 Gradle 项目,模型为空。 +3. 运行时提供者回答 `lithe/build/prepareRun`: + - 重新检测模块,模块已经不是 Web 模块时报错,不使用过期的模型; + - 检查 Tomcat 安装目录和 HTTP 端口; + - 用项目的 Maven Wrapper、`MAVEN_HOME` 或 `PATH` 上的 `mvn`(Gradle 同理:`gradlew`、`GRADLE_HOME`、`gradle`)构建,输出显示在运行窗口; + 没有设置 `JAVA_HOME` 时,构建使用 Lithe 启动提供者的同一个 JDK; + - 在 Lithe 的工作区状态目录 `bases/<哈希>/` 写出这个模块专用的 CATALINA_BASE:`server.xml`(只有一个绑定 + `127.0.0.1` 的 HTTP 连接器,关闭端口为 `-1`)、只输出到控制台的 `logging.properties`、从安装目录复制的其他 + `conf/` 文件,以及指向模块的 `conf/Catalina/localhost/<上下文>.xml`; + - 返回启动计划:在项目 JDK 上运行 `org.apache.catalina.startup.Bootstrap start`,系统属性与 `catalina.sh run` + 相同,`JDK_JAVA_OPTIONS` 带上 `catalina.sh` 在 Java 9+ 使用的 `--add-opens`(Java 8 会忽略这个变量)。 +4. Lithe 启动、停止 Tomcat,并把标准输出和标准错误显示在运行窗口。 + +插件只读 Tomcat 安装目录、工作区和插件包。每次运行会重写 CATALINA_BASE 的 `conf/`、清空 `webapps/` 和 +`temp/`;`work/`(编译过的 JSP)保留,下次启动更快。Gradle 构建结束后 Gradle daemon 按 Gradle 自己的规则留在后台, +和在终端运行 `gradle` 一样。 + +## 诊断日志 + +提供者用 Java SDK 与 Lithe 协商日志协议,日志进入 Lithe 日志窗口的该插件通道: + +| 操作 | 成功 | 失败(ERROR) | 降级(WARN) | +| --- | --- | --- | --- | +| `lithe/build/model` 读取模块 | 不记录(被监视的文件一改就重新读取,属于高频读取) | SDK 记录真实失败,类别 `tomcat.invalidRoot` 或 `internal_error` | `buildFileUnreadable`(构建文件存在但读不了或无法解析,按次数记一次);`webModuleScanTruncated`(目录数超过上限,模型不完整) | +| `lithe/build/prepareRun` 准备运行 | INFO(SDK 记录一次) | `tomcat.run.noHome`、`invalidHome`、`portInUse`、`notWebModule`、`buildFailed`、`noTool`、`noArtifact`、`unsupportedArguments`、`invalidProject`、`invalidDebug` | `buildFileUnreadable` | + +取消运行准备不记录失败。日志只带类别和计数,不含路径、命令输出或用户输入;返回给用户的错误提示也不含路径。 +运行失败时 Lithe 显示提供者的错误提示(需要包含 [1lck/Lithe-IDEA#2143](https://github.com/1lck/Lithe-IDEA/issues/2143) +修复的桌面端)。提示有中英文两套,按 `initialize` 的 `locale` 选择;插件契约目前还不向提供者传界面语言 +([1lck/Lithe-IDEA#2144](https://github.com/1lck/Lithe-IDEA/issues/2144)),所以暂时总是英文。 +Maven、Gradle 的构建输出和 Tomcat 自己的日志只出现在运行窗口,不写日志文件。 + +## 安装 + +Lithe Store 收录后,在 设置 → 插件 → 插件市场 搜索 Tomcat。也可以从 +[Releases](https://github.com/Lithe-IDEA/lithe-plugin-tomcat/releases) 下载 `tomcat-<版本>-<平台>.zip`,在 +设置 → 插件 中点击 从文件安装…。三个平台的 ZIP 内容相同。调试需要另装提供 `java` 调试类型的 Java 插件。 + +## 开发 + +需要 Node.js 22、JDK 17 或更新版本(编译用 `javac --release 8`)、Maven 和 `zip`。 + +```sh +node scripts/package.mjs # 校验 SDK 哈希,编译提供者,生成 dist/tomcat-<版本>-{darwin,linux,windows}.zip +node scripts/test/fetch-tomcat.mjs # 下载 test/tomcat-versions.json 固定的 Tomcat,按 SHA-512 校验后解压 +node scripts/test.mjs # 用真实 Tomcat 运行端到端测试 +``` + +`scripts/test.mjs` 对每个 Tomcat(默认 `.artifacts/tomcat/apache-tomcat-*`,或 `LITHE_TEST_TOMCAT_HOMES`) +以 Lithe 的方式启动打包后的提供者,读取 `test/fixtures/workspace/` 中四个实例的模型,准备并启动每个模块,通过 +HTTP 读取页面;同时检查调试启动(JDWP 握手)、端口占用、程序参数和过期目标的报错、修改 JSP 后无需重新部署、 +日志记录、以及插件包和 Tomcat 安装目录在测试前后完全一致。Gradle 用 `GRADLE_HOME`、`PATH` 或 +`.artifacts/gradle/gradle-*`,测试使用独立的 `GRADLE_USER_HOME` 并在结束时停止它启动的 daemon。 + +### 宿主端到端测试 + +`e2e/host/` 下的测试用 Lithe 桌面端自己的测试框架(内部 Go 包)驱动真实工作台:用真实的安装器装上本插件包和 +Java Support 插件包,打开一个 Eclipse Dynamic Web Project,从运行配置运行(页面能访问、运行窗口显示 Tomcat +日志、Stop 后端口释放),以及调试(Tomcat 挂起等待,Java 调试器连接后请求停在项目源码的断点上,Continue 后 +请求完成)。测试最后检查插件包和 Tomcat 安装目录没有被改动。 + +```sh +JAVA_HOME= \ +LITHE_TEST_TOMCAT_PLUGIN_ARCHIVE=dist/tomcat-<版本>-darwin.zip \ +LITHE_TEST_JAVA_PLUGIN_ARCHIVE="$(node scripts/test/fetch-java-plugin.mjs)" \ +LITHE_TEST_TOMCAT_HOME=.artifacts/tomcat/apache-tomcat-10.1.62 \ +node scripts/e2e-host.mjs +``` + +`scripts/test/fetch-java-plugin.mjs` 按 `test/java-plugin.json` 固定的版本和 SHA-256 下载本机平台的 Java Support 包。 +Java Support 不带 Eclipse JDT 语言服务器,按用户的安装查找(设置、`JDTLS_HOME`、`PATH`、Homebrew 等);本机没有装时, +用 `JDTLS_HOME="$(node scripts/test/fetch-java-plugin.mjs --jdtls)"` 取得同一文件固定的 JDT LS 1.61.0(与 Java 插件 CI 相同)。 +`JAVA_HOME` 必须是 JDK 21 或更新版本:Java Support 的 JDT 语言服务器(它运行 `java` 调试适配器)拒绝更旧的 JDK。 +测试按用户的顺序操作:先打开项目读取构建模型(这时提供者用默认设置启动),再在设置里选择 Tomcat,然后运行, +所以它同时验证了宿主在插件设置改动后重启构建提供者 +([1lck/Lithe-IDEA#2142](https://github.com/1lck/Lithe-IDEA/issues/2142))。 + +脚本把 `e2e/host/lithe-host.json` 固定的宿主修订检出到 `.artifacts/lithe-host`,再以 overlay 方式加入这里的测试 +文件,用宿主的 `scripts/desktop/desktop-go.sh test` 运行(第一次会编译该宿主固定的 Core)。CI 在 PR 标记 ready 后和 +main 上用 Linux 包跑同一组测试(`host` 任务)。 + +### 构建资源 + +| 资源 | 来源与校验 | 位置 | 能否在工作树之间复制 | +| --- | --- | --- | --- | +| Java 插件 SDK | Core 仓库 `shared/plugins/sdk/java`,`sdk.lock.json` 记录 commit 和每个文件的 SHA-256,打包前校验 | `vendor/`(入库) | 随仓库 | +| 提供者 jar | 打包时用 `javac --release 8` 编译 | `provider/target/`、`dist/` | 可以,但每次打包都会重建 | +| Tomcat(仅测试) | `test/tomcat-versions.json` 固定版本、URL 和 SHA-512 | `.artifacts/tomcat/` | 可以,按版本目录复制;不进插件包 | +| Gradle(仅本地测试) | Gradle 官方发行包,按 `.sha256` 校验 | `.artifacts/gradle/` | 可以 | +| 测试工作目录 | 每次测试重建 | `.artifacts/test-work/` | 不要复制,包含运行时状态 | +| Java Support 插件包(仅宿主测试) | `test/java-plugin.json` 固定版本、下载地址和 SHA-256 | `.artifacts/java-plugin/` | 可以,按文件复制;不进插件包 | +| Eclipse JDT LS(仅宿主测试) | `test/java-plugin.json` 的 `jdtls` 固定版本、下载地址和 SHA-256 | `.artifacts/jdtls/<版本>/` | 可以,按版本目录复制;不进插件包 | +| 宿主检出(仅宿主测试) | `e2e/host/lithe-host.json` 固定的 Lithe-IDEA 修订,部分克隆 `desktop/` 与 `scripts/` | `.artifacts/lithe-host/` | 源码可以复制;其中编译出的 Core 只能在同一修订、平台和工具链下复用 | + +## 功能矩阵 + +见 [docs/feature-matrix.md](docs/feature-matrix.md)。 + +## 许可 + +Apache License 2.0,见 [LICENSE](LICENSE) 和 [NOTICE](NOTICE)。 diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md new file mode 100644 index 0000000..570cbc8 --- /dev/null +++ b/docs/feature-matrix.md @@ -0,0 +1,35 @@ +# 功能矩阵 + +本页记录 Tomcat 插件自己的跨平台功能状态。插件能力不写进 Lithe 主仓库的功能矩阵;改动插件行为的 PR 同时更新本页。 + +## 状态取值 + +| 字段 | 取值 | +| --- | --- | +| 实现 | `implemented` 已实现;`partial` 部分实现;`missing` 未实现;`not-applicable` 该平台不适用 | +| 验证 | `verified` 已在真实 Lithe 宿主中按“验证方法”完整验收;`pending` 尚未完整验收;`not-applicable` 无需验收 | + +自动化测试的结果写在“最近验证”里,不能代替宿主验收。三个平台的 ZIP 逐字节相同。 + +## 总览 + +| ID | 能力 | macOS | Windows | Linux | 最近验证 | +| --- | --- | --- | --- | --- | --- | +| `tomcat-web-modules` | 识别 Maven war、Gradle war、Eclipse Dynamic Web Project 和普通 Web 目录 | implemented / pending | implemented / pending | implemented / pending | 2026-11-18 `scripts/test.mjs` 通过(macOS arm64,Tomcat 9.0.124 与 10.1.62,JDK 17;Tomcat 9.0.124,JDK 8) | +| `tomcat-run` | 构建模块并在私有 CATALINA_BASE 中运行,HTTP 可访问 | implemented / pending | implemented / pending | implemented / pending | 同上;2026-11-18 宿主端到端测试 `TestTomcatPluginRunsAWebModule` 通过(macOS arm64,宿主 1lck/Lithe-IDEA c47ae049,含 #2145,Tomcat 9.0.124 与 10.1.62):运行配置启动、页面可访问、运行窗口有 Tomcat 日志、Stop 释放端口 | +| `tomcat-in-place` | Eclipse 项目和普通 Web 目录原地运行,挂载编译输出,JSP 修改无需重新部署 | implemented / pending | implemented / pending | implemented / pending | 同上 | +| `tomcat-debug` | 按 `java` 调试类型连接调试,Tomcat 以 `suspend=y` 等待 | implemented / pending | implemented / pending | implemented / pending | `scripts/test.mjs` 验证到 JDWP 握手;2026-11-18 宿主端到端测试 `TestTomcatPluginDebugsAWebModule` 通过(同上,Java Support 4.0.1,JDK 21):Java 调试器连接,请求停在项目源码断点,Continue 后完成 | +| `tomcat-settings` | Tomcat 安装目录与 HTTP 端口设置,中英文 | implemented / pending | implemented / pending | implemented / pending | 2026-11-18 清单与翻译通过 Core 校验;宿主端到端测试在读取模型后保存设置再运行,新值生效(需要 1lck/Lithe-IDEA#2142 的修复);宿主界面未验收。提供者错误提示暂时只有英文(1lck/Lithe-IDEA#2144) | + +## 证据与验证方法 + +| ID | 实现 | 自动化测试 | 验证方法(宿主) | +| --- | --- | --- | --- | +| `tomcat-web-modules` | `provider/.../WebModules.java` | `scripts/test.mjs`:“the model lists each Web module and nothing else” | 打开含四类模块的工作区,构建窗口的 Tomcat 实例列出每个 Web 模块,jar 模块不出现 | +| `tomcat-run` | `Preparation.java`、`CatalinaBase.java` | “the Maven module builds…”、“the Gradle war module…” | 从运行配置运行,运行窗口显示构建输出和 Tomcat 启动日志,浏览器打开 `http://localhost:<端口><上下文>/` | +| `tomcat-in-place` | `WebModules.java`(WTP、普通目录)、`CatalinaBase.contextXml` | “the Eclipse project is served in place…”、“a plain Web folder…” | 运行 Eclipse 项目,修改 JSP 后刷新页面看到新内容 | +| `tomcat-debug` | `Preparation.launch`、`plugin.json` 的 `debug.configurationType` | “a debug run suspends Tomcat…” | 装好 Java 插件后调试运行,在 Servlet 或 JSP 编译出的类上设断点并命中 | +| `tomcat-settings` | `plugin.json` 的 `settings`、`l10n/zh-Hans.json` | `scripts/test.mjs`:缺少 Tomcat 时的中文提示 | 中英文界面下打开设置页,修改安装目录和端口后运行使用新值 | + +CI(`.github/workflows/ci.yml`)在 Linux 上用 JDK 17 和 JDK 8 运行同一套测试,ready 状态的 PR 还会在 Windows 上用 +`mvn.cmd` 和 `gradle.bat` 运行,并在 Linux 上对固定的宿主运行宿主端到端测试(`host` 任务)。 diff --git a/e2e/host/desktop/internal/workbench/tomcat_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/tomcat_plugin_e2e_test.go new file mode 100644 index 0000000..6a86876 --- /dev/null +++ b/e2e/host/desktop/internal/workbench/tomcat_plugin_e2e_test.go @@ -0,0 +1,376 @@ +package workbench + +import ( + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// These opt-in tests install the Tomcat archive and the released Java Support archive through +// the real installer and drive the workbench as a user does. Java Support declares the java +// tool the launch plan names and the java debug adapter the run's debug type selects. The +// workspace is an Eclipse Dynamic Web Project, which Tomcat serves in place, so no Maven or +// Gradle download is involved. They skip unless the Tomcat archive is named and fail rather +// than skip once a named archive cannot do its work. + +const tomcatPluginID = "io.github.lithe-idea.tomcat" + +// tomcatInputs are the archives and the Tomcat installation the tests need. +type tomcatInputs struct{ archive, javaArchive, home string } + +func requireTomcatInputs(t *testing.T) tomcatInputs { + t.Helper() + inputs := tomcatInputs{ + archive: os.Getenv("LITHE_TEST_TOMCAT_PLUGIN_ARCHIVE"), + javaArchive: os.Getenv("LITHE_TEST_JAVA_PLUGIN_ARCHIVE"), + home: os.Getenv("LITHE_TEST_TOMCAT_HOME"), + } + if inputs.archive == "" { + t.Skip("set LITHE_TEST_TOMCAT_PLUGIN_ARCHIVE to a tomcat--darwin.zip") + } + if inputs.javaArchive == "" { + t.Fatal("set LITHE_TEST_JAVA_PLUGIN_ARCHIVE to a Lithe-Java-Support--darwin-.zip") + } + if inputs.home == "" { + t.Fatal("set LITHE_TEST_TOMCAT_HOME to an unpacked Tomcat (CATALINA_HOME)") + } + if _, err := os.Stat(filepath.Join(inputs.home, "bin", "bootstrap.jar")); err != nil { + t.Fatalf("LITHE_TEST_TOMCAT_HOME is not a Tomcat installation: %v", err) + } + return inputs +} + +// eclipseWebProject writes an Eclipse Dynamic Web Project below root, served at +// /eclipse/demo, and compiles its one class into the project's output folder, as the Java +// plugin's build does. The page calls the class, so a breakpoint in it stops a request. +func eclipseWebProject(t *testing.T, root string) (source string) { + t.Helper() + writePluginFixture(t, root, map[string]string{ + ".project": ` + + wtp-demo + + org.eclipse.jdt.core.javanature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + +`, + ".classpath": ` + + + + + +`, + ".settings/org.eclipse.wst.common.component": ` + + + + + + + +`, + "WebContent/WEB-INF/web.xml": ` + +`, + "WebContent/index.jsp": `<%@ page contentType="text/plain; charset=UTF-8" %><%= demo.wtp.Message.text() %> +`, + "src/demo/wtp/Message.java": `package demo.wtp; + +public final class Message { + public static String text() { + String greeting = "Hello from Lithe on Tomcat"; + return greeting; + } +} +`, + }) + source = filepath.Join(root, "src", "demo", "wtp", "Message.java") + classes := filepath.Join(root, "build", "classes") + if err := os.MkdirAll(classes, 0o700); err != nil { + t.Fatal(err) + } + if output, err := exec.Command("javac", "-g", "-source", "8", "-target", "8", "-nowarn", "-d", classes, source).CombinedOutput(); err != nil { + t.Fatalf("javac: %v\n%s", err, output) + } + return source +} + +func tomcatFreePort(t *testing.T) int { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := listener.Addr().(*net.TCPAddr).Port + if err := listener.Close(); err != nil { + t.Fatal(err) + } + return port +} + +// openTomcatProject installs both archives, opens a fresh Eclipse Web project, waits for the +// Tomcat model, points the plugin at the Tomcat installation and a free port, and returns the +// one run configuration the model gives. +func openTomcatProject(t *testing.T, h *harness, inputs tomcatInputs) (p *project, installed string, before map[string]string, id, source string, port int) { + t.Helper() + installed = installOfficialPluginArchive(t, h, inputs.archive, tomcatPluginID) + installPluginArchiveInto(t, h.app.plugins, inputs.javaArchive, "io.github.lithe-idea.java-support") + before = packageDigest(t, installed) + root := t.TempDir() + source = eclipseWebProject(t, root) + h.open(root) + p = h.app.project + if p == nil { + t.Fatal("the project did not open") + } + h.app.post(func(a *App) { a.loadTitleRunConfigs(p) }) + instance := awaitBuildModel(t, h, p, "tomcat", 2*time.Minute) + if got := len(instance.Model.Targets); got != 1 || instance.Model.Targets[0].Name != "wtp-demo" { + t.Fatalf("the Tomcat model has targets %+v, want only wtp-demo", instance.Model.Targets) + } + port = tomcatFreePort(t) + saveGlobalPluginSettings(t, h, instance, map[string]any{"tomcatHome": inputs.home, "httpPort": port}) + awaitStateWithin(t, h, time.Minute, "the run configurations", func() bool { + return p.runConfigsSettled() && p.runConfigs.generation > 0 + }) + if p.runConfigs.failure != "" { + t.Fatalf("the run configurations failed: %s", p.runConfigs.failure) + } + var services []core.RunConfiguration + for _, configuration := range p.runConfigs.list { + if configuration.Execution == "service" { + services = append(services, configuration) + } + } + if len(services) != 1 { + t.Fatalf("the run configurations are %+v, want one Tomcat service", p.runConfigs.list) + } + t.Logf("run configuration %q", services[0].Name) + return p, installed, before, services[0].ID, source, port +} + +// getText answers the body of url once it serves 200, or the last error after limit. +func getText(url string, limit time.Duration) (string, error) { + client := &http.Client{Timeout: limit} + deadline := time.Now().Add(limit) + for { + response, err := client.Get(url) + if err == nil { + data, readErr := io.ReadAll(io.LimitReader(response.Body, 4096)) + _ = response.Body.Close() + if readErr == nil && response.StatusCode == http.StatusOK { + return strings.TrimSpace(string(data)), nil + } + err = readErr + if err == nil { + err = &httpStatusError{status: response.StatusCode} + } + } + if time.Now().After(deadline) { + return "", err + } + time.Sleep(500 * time.Millisecond) + } +} + +type httpStatusError struct{ status int } + +func (e *httpStatusError) Error() string { return "HTTP " + strconv.Itoa(e.status) } + +func assertPortFree(t *testing.T, port int) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(port)) + if err != nil { + t.Fatalf("Tomcat's port is still taken after Stop: %v", err) + } + _ = listener.Close() +} + +// TestTomcatPluginRunsAWebModule runs the Web module from its run configuration: the provider +// writes a private CATALINA_BASE, Lithe starts Tomcat on the project's JDK and shows its log in +// the Run window, the page answers over HTTP, and Stop ends Tomcat and frees its port. The +// installed package and the Tomcat installation stay unchanged. +func TestTomcatPluginRunsAWebModule(t *testing.T) { + inputs := requireTomcatInputs(t) + h := newHarness(t, &testKernel{Client: core.NewClient()}) + h.app.logSink = &pluginFilesLog{directory: t.TempDir()} + homeBefore := packageDigest(t, inputs.home) + p, installed, before, id, _, port := openTomcatProject(t, h, inputs) + + var op *buildOperation + var startErr error + h.app.post(func(a *App) { op, startErr = a.startRunConfiguration(p, id) }) + awaitStateWithin(t, h, 10*time.Second, "the run operation", func() bool { return op != nil || startErr != nil }) + if startErr != nil { + t.Fatalf("start the Tomcat run: %v", startErr) + } + output := func() string { return op.session.output.all() } + t.Cleanup(func() { + if t.Failed() { + t.Logf("run summary %q, notice %q, run console:\n%s", op.session.summary, lastNotice(h), output()) + } + }) + + url := "http://127.0.0.1:" + strconv.Itoa(port) + "/eclipse/demo/" + answers := make(chan string, 1) + go func() { + body, err := getText(url, 3*time.Minute) + if err != nil { + body = "error: " + err.Error() + } + answers <- body + }() + var body string + deadline := time.Now().Add(3*time.Minute + 10*time.Second) + for body == "" { + if time.Now().After(deadline) { + t.Fatalf("Tomcat did not answer; status=%q output:\n%s", p.build.status, output()) + } + // Pump only: settle waits for every background task, and the running server is one. + if err := h.driver.Pump(); err != nil { + t.Fatal(err) + } + if !p.build.active() { + t.Fatalf("the run ended before Tomcat answered; summary=%q output:\n%s", op.session.summary, output()) + } + select { + case body = <-answers: + case <-time.After(100 * time.Millisecond): + } + } + if body != "Hello from Lithe on Tomcat" { + t.Fatalf("GET %s = %q", url, body) + } + awaitStateWithin(t, h, time.Minute, "Tomcat's startup log in the Run window", func() bool { + return strings.Contains(output(), "Server startup in") + }) + + h.app.post(func(a *App) { a.stopBuildOperation(p) }) + awaitStateWithin(t, h, time.Minute, "the stopped run", func() bool { return !p.build.active() }) + assertPortFree(t, port) + + h.app.closeProject() + awaitStateWithin(t, h, 30*time.Second, "the closed project", func() bool { return h.app.project == nil }) + h.settle() + assertPackageUnchanged(t, installed, before) + assertPackageUnchanged(t, inputs.home, homeBefore) +} + +// TestTomcatPluginDebugsAWebModule debugs the same run configuration: Tomcat starts suspended +// on a host-chosen port, the Java debugger attaches, a request stops on a breakpoint in the +// project's source, Continue lets the request finish, and Stop in the Debug window ends Tomcat. +func TestTomcatPluginDebugsAWebModule(t *testing.T) { + inputs := requireTomcatInputs(t) + h := newHarness(t, &testKernel{Client: core.NewClient()}) + // Java Support starts its language server, which runs the java adapter, with ${logDir}. + h.app.logSink = &pluginFilesLog{directory: t.TempDir()} + p, installed, before, id, source, port := openTomcatProject(t, h, inputs) + line := tomcatSourceLine(t, source, "return greeting;") + reference := tomcatBuildReference(t, p, id) + if facts := p.titleConfigurationFacts(p.buildInstanceIndex(reference), reference); facts.Debuggable == nil || !*facts.Debuggable { + t.Fatal("the Tomcat run configuration is not debuggable") + } + var console func() string + t.Cleanup(func() { + if t.Failed() { + text := "" + if console != nil { + text = console() + } + t.Logf("build status %q, debug state %q status %q failure %q, notice %q, debug output:\n%s\nrun console:\n%s", + p.build.status, p.debug.state, p.debug.status, p.debug.failure, lastNotice(h), strings.Join(p.debug.output, ""), text) + } + }) + + h.app.post(func(a *App) { + a.toggleBreakpointAt(p, source, line) + a.chooseTitleConfiguration(p, id) + a.titleDebug(p) + }) + awaitStateWithin(t, h, 30*time.Second, "the debugged run", func() bool { return p.build.latest() != nil }) + op := p.build.latest() + console = func() string { return op.session.output.all() } + awaitStateWithin(t, h, 5*time.Minute, "the attached debugger", func() bool { + session := p.debug.activeSession() + return session != nil && session.adapter.Declaration.ID == "java" && p.debug.state == "running" + }) + + url := "http://127.0.0.1:" + strconv.Itoa(port) + "/eclipse/demo/" + answers := make(chan string, 1) + go func() { + body, err := getText(url, 5*time.Minute) + if err != nil { + body = "error: " + err.Error() + } + answers <- body + }() + awaitStateWithin(t, h, 5*time.Minute, "the stop on the breakpoint", func() bool { + return p.debug.pausedThread != nil && len(p.debug.frames) > 0 + }) + top := p.debug.frames[0] + if filepath.Base(top.SourcePath) != "Message.java" || top.Line != line { + t.Fatalf("stopped at %s:%d in %s, want Message.java:%d", top.SourcePath, top.Line, top.Name, line) + } + select { + case got := <-answers: + t.Fatalf("the request finished while Tomcat was stopped on the breakpoint: %q", got) + default: + } + + h.app.post(func(a *App) { a.continueDebug(p) }) + if got := awaitValueWithin(t, h, time.Minute, answers, "the request after Continue"); got != "Hello from Lithe on Tomcat" { + t.Fatalf("GET %s after Continue = %q", url, got) + } + + h.app.post(func(a *App) { a.stopDebugByUser(p) }) + awaitStateWithin(t, h, time.Minute, "the stopped Tomcat", func() bool { + return !p.build.active() && p.debug.activeSession() == nil + }) + assertPortFree(t, port) + + h.app.closeProject() + awaitStateWithin(t, h, 30*time.Second, "the closed project", func() bool { return h.app.project == nil }) + h.settle() + assertPackageUnchanged(t, installed, before) +} + +// tomcatSourceLine is the one-based line of path that contains text. +func tomcatSourceLine(t *testing.T, path, text string) int64 { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + for index, line := range strings.Split(string(data), "\n") { + if strings.Contains(line, text) { + return int64(index + 1) + } + } + t.Fatalf("%s has no line with %q", path, text) + return 0 +} + +// tomcatBuildReference is the build provider reference of configuration id. +func tomcatBuildReference(t *testing.T, p *project, id string) core.RunProviderReference { + t.Helper() + configuration := p.runConfigs.configuration(id) + if configuration == nil { + t.Fatalf("no configuration %q", id) + } + reference, ok := configuration.BuildReference() + if !ok { + t.Fatalf("configuration %q does not start through a build provider", id) + } + return reference +} diff --git a/e2e/host/desktop/internal/workbench/tomcat_plugin_helpers_test.go b/e2e/host/desktop/internal/workbench/tomcat_plugin_helpers_test.go new file mode 100644 index 0000000..4681e41 --- /dev/null +++ b/e2e/host/desktop/internal/workbench/tomcat_plugin_helpers_test.go @@ -0,0 +1,193 @@ +package workbench + +// Helpers shared by this plugin's host tests: install a plugin archive through the real +// installer, prove the installed package did not change, wait for a build model, and save +// plugin settings the way the settings window does. They follow the Maven plugin's host +// tests (Lithe-IDEA/lithe-plugin-maven e2e/host), which drive the same internal harness. + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" +) + +// installOfficialPluginArchive installs and enables archive in an isolated +// plugin root and returns the installed package directory. +func installOfficialPluginArchive(t *testing.T, h *harness, archive, id string) string { + t.Helper() + service, err := pluginservice.Open(core.NewClient(), h.store, t.TempDir()) + if err != nil { + t.Fatal(err) + } + // The app gives its service these resolvers when it opens it (app.go); a provider or backend + // that runs on a tool, such as a jar on java, cannot start without them, and a language + // server whose launch uses ${logDir} cannot start without the log directory. + service.Backend.SetToolResolver(h.app.resolveBackendTool) + service.Backend.SetToolEntryResolver(h.app.resolveBackendToolEntry) + service.LanguageTool = h.app.resolveLanguageTool + service.LogDirectory = h.app.pluginLogDirectory + h.app.plugins = service + return installPluginArchiveInto(t, service, archive, id) +} + +// installPluginArchiveInto installs and enables archive in service's plugin root, next to the +// plugins already there, and returns the installed package directory. +func installPluginArchiveInto(t *testing.T, service *pluginservice.Service, archive, id string) string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + plan, err := service.Installer.Prepare(ctx, plugininstall.Request{ArchivePath: archive, Root: service.Root, Source: plugintrust.Disk}) + if err != nil { + t.Fatalf("prepare %s: %v", archive, err) + } + if plan.ID != id { + _ = service.Installer.Discard(plan) + t.Fatalf("archive holds %s, want %s", plan.ID, id) + } + installed, err := service.Installer.Commit(plan) + if err != nil { + _ = service.Installer.Discard(plan) + t.Fatalf("install %s: %v", id, err) + } + if err := service.Manager.SetEnabled(id, true); err != nil { + t.Fatal(err) + } + return installed.Path +} + +// packageDigest hashes every file of an installed package, so a test can prove a +// workflow left the package byte-for-byte as installed. +func packageDigest(t *testing.T, root string) map[string]string { + t.Helper() + digest := map[string]string{} + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + file, err := os.Open(path) + if err != nil { + return err + } + // JDK module images are large; stream the unchanged-package proof so + // test buffers do not inflate the headless host's memory observations. + sum := sha256.New() + _, readErr := io.Copy(sum, file) + closeErr := file.Close() + if readErr != nil { + return readErr + } + if closeErr != nil { + return closeErr + } + relative, err := filepath.Rel(root, path) + if err != nil { + return err + } + digest[relative] = hex.EncodeToString(sum.Sum(nil)) + return nil + }) + if err != nil { + t.Fatal(err) + } + return digest +} + +func assertPackageUnchanged(t *testing.T, root string, before map[string]string) { + t.Helper() + after := packageDigest(t, root) + if len(after) != len(before) { + t.Fatalf("the installed package now has %d files, it had %d", len(after), len(before)) + } + for name, sum := range before { + if after[name] != sum { + t.Fatalf("the workflow changed the installed package file %s", name) + } + } +} + +// awaitBuildModel waits until detection found an instance of buildSystemID and its +// model is loaded, failing with the model error when the plugin's command failed. +func awaitBuildModel(t *testing.T, h *harness, p *project, buildSystemID string, limit time.Duration) *buildInstance { + t.Helper() + var instance *buildInstance + awaitStateWithin(t, h, limit, buildSystemID+" detection and model", func() bool { + for index := range p.build.instances { + candidate := &p.build.instances[index] + if candidate.BuildSystemID != buildSystemID { + continue + } + if candidate.modelError != "" { + t.Fatalf("the %s model failed: %s", buildSystemID, candidate.modelError) + } + if candidate.modelLoaded { + p.build.selected = index + instance = candidate + return true + } + } + if p.build.failed != "" { + t.Fatalf("build detection failed: %s", p.build.failed) + } + return false + }) + return instance +} + +// saveGlobalPluginSettings saves values to the plugin's global settings layer the way the +// settings window does, then dispatches the effects Core answered for the change. +func saveGlobalPluginSettings(t *testing.T, h *harness, instance *buildInstance, values map[string]any) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + store := pluginsettings.New(h.app.kernel, h.store.Dir()) + snapshot, err := store.Load(ctx, instance.Manifest, h.app.project.root) + if err != nil { + t.Fatalf("load the plugin settings: %v", err) + } + ids := make([]string, 0, len(values)) + for id := range values { + ids = append(ids, id) + } + sort.Strings(ids) + edits := make([]core.PluginSettingEdit, 0, len(ids)) + for _, id := range ids { + value, err := json.Marshal(values[id]) + if err != nil { + t.Fatal(err) + } + edits = append(edits, core.PluginSettingEdit{ID: id, Value: value}) + } + result, err := store.Save(ctx, snapshot, "global", edits, nil) + if err != nil || !result.Committed { + t.Fatalf("save the plugin settings: committed=%v err=%v", result.Committed, err) + } + h.app.applyPluginSettingsEffects(core.PluginSettingsOwner{PluginID: instance.PluginID, Version: instance.Version}, result.Effects) +} + +// writePluginFixture writes files (relative path to content) below root. +func writePluginFixture(t *testing.T, root string, files map[string]string) { + t.Helper() + for name, content := range files { + path := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } +} diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json new file mode 100644 index 0000000..6bab9c1 --- /dev/null +++ b/e2e/host/lithe-host.json @@ -0,0 +1,13 @@ +{ + "repository": "https://github.com/1lck/Lithe-IDEA.git", + "revision": "c47ae0496a1b7cde7c016a9b40a10c2ff54fdaac", + "packages": { + "./internal/workbench": "^TestTomcatPlugin(RunsAWebModule|DebugsAWebModule)$" + }, + "requiredEnvironment": { + "LITHE_TEST_TOMCAT_PLUGIN_ARCHIVE": "tomcat--darwin.zip to install, for example dist/tomcat-0.1.0-darwin.zip", + "LITHE_TEST_JAVA_PLUGIN_ARCHIVE": "Lithe-Java-Support--darwin-.zip from Lithe-IDEA/lithe-plugin-java releases; its java tool launches Tomcat and its java adapter debugs it", + "LITHE_TEST_TOMCAT_HOME": "an unpacked Tomcat, for example .artifacts/tomcat/apache-tomcat-10.1.62 from scripts/test/fetch-tomcat.mjs", + "JAVA_HOME": "a JDK 21 or later: the Java plugin's JDT language server, which runs its java debug adapter, refuses older JDKs; Tomcat also runs on it" + } +} diff --git a/io.github.lithe-idea.tomcat/l10n/zh-Hans.json b/io.github.lithe-idea.tomcat/l10n/zh-Hans.json new file mode 100644 index 0000000..ffa45e5 --- /dev/null +++ b/io.github.lithe-idea.tomcat/l10n/zh-Hans.json @@ -0,0 +1,13 @@ +{ + "settings": { + "tomcatHome": { + "title": "Tomcat 安装目录", + "description": "所有 Web 模块使用的 Tomcat 目录(CATALINA_HOME)。留空时使用 CATALINA_HOME 环境变量。Lithe 只读取这个目录,每个模块在 Lithe 工作区状态目录里使用自己的 CATALINA_BASE。", + "placeholder": "自动:CATALINA_HOME" + }, + "httpPort": { + "title": "HTTP 端口", + "description": "Tomcat 在 127.0.0.1 上提供该模块的端口。" + } + } +} diff --git a/io.github.lithe-idea.tomcat/plugin.json b/io.github.lithe-idea.tomcat/plugin.json new file mode 100644 index 0000000..9924ce5 --- /dev/null +++ b/io.github.lithe-idea.tomcat/plugin.json @@ -0,0 +1,126 @@ +{ + "schemaVersion": 0, + "id": "io.github.lithe-idea.tomcat", + "displayName": "Tomcat", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { + "buildSystems": 0, + "buildProviders": 0, + "settings": 0 + }, + "requiresTools": [ + "java" + ], + "vendor": { + "id": "io.github.lithe-idea", + "displayName": "Lithe Community", + "signatureRequirement": "none" + }, + "permissions": [ + "process.build", + "languageServer.launch" + ], + "activationEvents": [ + "onBuildSystem:tomcat" + ], + "languages": [], + "settings": [ + { + "id": "tomcatHome", + "type": "directory", + "title": "Tomcat installation", + "description": "The Tomcat directory (CATALINA_HOME) every Web module runs on. Leave empty to use the CATALINA_HOME environment variable. Lithe only reads it: each module runs in its own CATALINA_BASE in Lithe's workspace state.", + "default": "", + "placeholder": "Automatic: CATALINA_HOME", + "page": { + "buildSystemID": "tomcat" + }, + "section": "Tomcat" + }, + { + "id": "httpPort", + "type": "integer", + "title": "HTTP port", + "description": "The port Tomcat serves the module on, on 127.0.0.1.", + "default": 8080, + "minimum": 1, + "maximum": 65535, + "scope": "project", + "page": { + "buildSystemID": "tomcat" + }, + "section": "Tomcat" + } + ], + "buildSystems": [ + { + "id": "tomcat", + "displayName": "Tomcat", + "detection": { + "markers": [ + "pom.xml", + "build.gradle", + "build.gradle.kts", + ".project", + "web.xml" + ], + "nesting": "outermost" + }, + "invocation": { + "executables": [ + { + "kind": "toolchain", + "toolchainID": "java" + } + ] + }, + "provider": { + "launch": { + "kind": "runtime", + "tool": "java", + "minimumVersion": "8", + "entry": "lib/lithe-tomcat-provider.jar" + }, + "arguments": [ + "--state", + "${workspaceStateDir}" + ], + "initializationOptions": { + "tomcatHome": "${setting:tomcatHome}", + "httpPort": "${setting:httpPort}" + }, + "executesProjectCode": true, + "mayUseNetwork": true + }, + "model": { + "source": "provider" + }, + "run": [ + { + "id": "tomcat", + "source": "provider", + "name": "Run on Tomcat", + "fromTargets": { + "tags": [ + "web-application" + ] + }, + "execution": "service", + "debug": { + "configurationType": "java" + } + } + ], + "sync": { + "watch": [ + "pom.xml", + "build.gradle", + "build.gradle.kts", + ".project", + "web.xml" + ] + } + } + ] +} diff --git a/provider/src/main/java/io/github/litheidea/tomcat/CatalinaBase.java b/provider/src/main/java/io/github/litheidea/tomcat/CatalinaBase.java new file mode 100644 index 0000000..3d1cfc9 --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/tomcat/CatalinaBase.java @@ -0,0 +1,178 @@ +package io.github.litheidea.tomcat; + +import java.io.IOException; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Locale; + +/** + * The private CATALINA_BASE one Web module runs in, under the workspace + * state directory Lithe gives the build system: + * {@code /bases/}. + * + *

Each preparation rewrites {@code conf/}: {@code server.xml} with one + * HTTP connector on the loopback address and no shutdown port, a copy of + * a console-only {@code logging.properties}, a copy of the other top-level + * files of the installation's {@code conf/}, and one context file that + * points at the module. {@code work/} (compiled JSPs) is + * kept between runs; {@code webapps/} is emptied, so a rebuilt WAR is + * expanded again. The installation itself is only read, and nothing goes + * into the workspace, the plugin package or the installation. + */ +final class CatalinaBase { + /** + * Tomcat's logging for a Lithe run: the console only, which Lithe shows in + * the Run window, at Tomcat's usual INFO level. The installation's file + * handlers would write dated log files into the workspace state, which is + * not a log directory, so they are left out. + */ + static final String LOGGING = "# Generated by the Lithe Tomcat plugin; rewritten on every start.\n" + + "handlers = java.util.logging.ConsoleHandler\n" + + ".handlers = java.util.logging.ConsoleHandler\n" + + ".level = INFO\n" + + "java.util.logging.ConsoleHandler.level = FINE\n" + + "java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter\n" + + "java.util.logging.ConsoleHandler.encoding = UTF-8\n"; + + final Path directory; + + private CatalinaBase(Path directory) { + this.directory = directory; + } + + static CatalinaBase write(Path state, Path home, String key, int httpPort, String contextPath, + Path docBase, Path classes) throws IOException { + Path base = state.resolve("bases").resolve(hash(key)); + Path conf = base.resolve("conf"); + Files.createDirectories(conf); + for (String folder : new String[] {"temp", "work", "webapps"}) { + Files.createDirectories(base.resolve(folder)); + } + clear(base.resolve("webapps")); + clear(base.resolve("temp")); + clear(conf); + try (DirectoryStream files = Files.newDirectoryStream(home.resolve("conf"))) { + for (Path file : files) { + String name = file.getFileName().toString(); + if (Files.isRegularFile(file) && !name.equals("server.xml") && !name.equals("logging.properties")) { + Files.copy(file, conf.resolve(name), StandardCopyOption.REPLACE_EXISTING); + } + } + } + writeText(conf.resolve("server.xml"), serverXml(httpPort)); + writeText(conf.resolve("logging.properties"), LOGGING); + Path contexts = conf.resolve("Catalina").resolve("localhost"); + Files.createDirectories(contexts); + writeText(contexts.resolve(contextFileName(contextPath) + ".xml"), contextXml(docBase, classes)); + return new CatalinaBase(base); + } + + static String serverXml(int httpPort) { + return "\n" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "\n"; + } + + /** + * The context of the module: {@code docBase} is the exploded application + * or the WAR, and compiled classes outside it are mounted at + * {@code /WEB-INF/classes} ahead of the application's own, with class + * reloading on, as Eclipse WTP serves a Dynamic Web Project. + */ + static String contextXml(Path docBase, Path classes) { + StringBuilder xml = new StringBuilder(); + xml.append("\n"); + xml.append("\n"); + return xml.toString(); + } + xml.append(" reloadable=\"true\">\n"); + xml.append(" \n"); + xml.append(" \n"); + xml.append(" \n"); + xml.append("\n"); + return xml.toString(); + } + + /** {@code ROOT} for the root context, otherwise the path with {@code #} for {@code /}. */ + static String contextFileName(String contextPath) { + String path = contextPath.startsWith("/") ? contextPath.substring(1) : contextPath; + return path.isEmpty() ? "ROOT" : path.replace('/', '#'); + } + + static String attribute(String value) { + return value.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">"); + } + + private static void writeText(Path file, String text) throws IOException { + Path partial = Files.createTempFile(file.getParent(), file.getFileName().toString(), ".tmp"); + try (Writer writer = Files.newBufferedWriter(partial, StandardCharsets.UTF_8)) { + writer.write(text); + } + Files.move(partial, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } + + /** Deletes what {@code directory} holds; links are removed, never followed. */ + static void clear(Path directory) throws IOException { + try (DirectoryStream entries = Files.newDirectoryStream(directory)) { + for (Path entry : entries) { + if (Files.isDirectory(entry) && !Files.isSymbolicLink(entry)) { + Files.walkFileTree(entry, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path visited, IOException failure) throws IOException { + if (failure != null) { + throw failure; + } + Files.delete(visited); + return FileVisitResult.CONTINUE; + } + }); + } else { + Files.delete(entry); + } + } + } + } + + static String hash(String text) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder(); + for (int index = 0; index < 8; index++) { + hex.append(String.format(Locale.ROOT, "%02x", digest[index])); + } + return hex.toString(); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/provider/src/main/java/io/github/litheidea/tomcat/Messages.java b/provider/src/main/java/io/github/litheidea/tomcat/Messages.java new file mode 100644 index 0000000..42c53db --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/tomcat/Messages.java @@ -0,0 +1,75 @@ +package io.github.litheidea.tomcat; + +import java.util.Locale; + +/** + * The provider's user-facing text in the interface language Lithe sends as + * {@code locale} in {@code initialize}: Chinese for {@code zh*}, English + * otherwise. Lithe shows a failed preparation's message as it is, so no + * message carries a path, a stack trace or tool output. + */ +final class Messages { + private final boolean chinese; + + Messages(String locale) { + chinese = locale != null && locale.toLowerCase(Locale.ROOT).startsWith("zh"); + } + + String noHome() { + return chinese + ? "没有设置 Tomcat。请在 Tomcat 设置中选择 Tomcat 安装目录,或设置 CATALINA_HOME 环境变量。" + : "No Tomcat installation is set. Choose the Tomcat directory in the Tomcat settings, or set CATALINA_HOME."; + } + + String invalidHome() { + return chinese + ? "所选目录不是完整的 Tomcat 安装:缺少 bin/bootstrap.jar、bin/tomcat-juli.jar、lib/catalina.jar 或 conf/web.xml。" + : "The chosen directory is not a complete Tomcat installation: bin/bootstrap.jar, bin/tomcat-juli.jar, lib/catalina.jar or conf/web.xml is missing."; + } + + String portBusy(int port) { + return chinese + ? "HTTP 端口 " + port + " 已被占用。请停止占用它的程序,或在 Tomcat 设置中换一个端口。" + : "HTTP port " + port + " is in use. Stop the program using it, or choose another port in the Tomcat settings."; + } + + String notWebModule(String module) { + return chinese + ? module + " 已不是 Web 模块。请重新加载 Tomcat 构建模型。" + : module + " is no longer a Web module. Reload the Tomcat build model."; + } + + String building(String module) { + return chinese ? "正在构建 " + module + "…" : "Building " + module + "…"; + } + + String buildFailed(String tool, int exitCode) { + return chinese + ? tool + " 构建失败(退出码 " + exitCode + "),详见运行窗口中的构建输出。" + : "The " + tool + " build failed (exit code " + exitCode + "). See the build output in the Run window."; + } + + String noTool(String command) { + return chinese + ? "在 PATH 中找不到 " + command + "。请安装它,或在项目里加入对应的 wrapper。" + : command + " is not on PATH. Install it, or add its wrapper to the project."; + } + + String noArtifact(String tool) { + return chinese + ? tool + " 构建完成,但没有找到唯一的 WAR 产物。请检查模块的打包配置。" + : "The " + tool + " build finished without exactly one WAR artifact. Check the module's packaging."; + } + + String unsupportedArguments() { + return chinese + ? "Tomcat 运行不接受程序参数。JVM 参数请填在运行配置的“VM 选项”里。" + : "A Tomcat run takes no program arguments. Put JVM options in the run configuration's VM options."; + } + + String startingTomcat(String module, String context, int port) { + return chinese + ? "Tomcat 将在 http://localhost:" + port + context + " 提供 " + module + : "Tomcat will serve " + module + " at http://localhost:" + port + context; + } +} diff --git a/provider/src/main/java/io/github/litheidea/tomcat/Preparation.java b/provider/src/main/java/io/github/litheidea/tomcat/Preparation.java new file mode 100644 index 0000000..266c63f --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/tomcat/Preparation.java @@ -0,0 +1,516 @@ +package io.github.litheidea.tomcat; + +import io.github.litheidea.plugin.sdk.CallContext; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import io.github.litheidea.plugin.sdk.Processes; +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * Answers {@code lithe/build/prepareRun} for a {@code web-application} + * target: builds the module when Maven or Gradle owns it, writes the + * module's private CATALINA_BASE ({@link CatalinaBase}) and returns the + * launch of {@code org.apache.catalina.startup.Bootstrap start} on the + * project's JDK, as {@code catalina.sh run} would start it. Lithe starts, + * stops and debugs that process. + * + *

An Eclipse Dynamic Web Project or a plain Web folder is served where it + * is, with its compiled classes mounted from the output folder the Java + * plugin builds into, so an edit needs no deployment step. + */ +final class Preparation { + static final String JAVA_TOOL = "java"; + static final String BOOTSTRAP = "org.apache.catalina.startup.Bootstrap"; + /** The modules {@code catalina.sh} opens to Tomcat on Java 9 and later; Java 8 ignores the variable. */ + static final List ADD_OPENS = Collections.unmodifiableList(Arrays.asList( + "java.base/java.lang", "java.base/java.lang.invoke", "java.base/java.lang.reflect", "java.base/java.io", + "java.base/java.util", "java.base/java.util.concurrent", "java.rmi/sun.rmi.transport")); + private static final int OUTPUT_CHUNK = 32 * 1024; + + private final Path workspace; + private final Path state; + private final Settings settings; + private final Messages messages; + + Preparation(Path workspace, Path state, Settings settings, Messages messages) { + this.workspace = workspace; + this.state = state; + this.settings = settings; + this.messages = messages; + } + + Map prepare(Map params, CallContext context) throws Exception { + Request request = Request.of(params); + if (!request.arguments.isEmpty() || !request.userArguments.isEmpty()) { + throw new PluginError("tomcat.run.unsupportedArguments", messages.unsupportedArguments()); + } + Path instance = workspace.resolve(request.root).normalize(); + String projectPath = relative(request.root, request.projectPath); + Path directory = instance.resolve(projectPath).normalize(); + if (!directory.startsWith(instance)) { + throw new PluginError("tomcat.run.invalidProject", "The project is outside the build root."); + } + WebModules.Unreadable unreadable = new WebModules.Unreadable(); + WebModules.Module module = WebModules.detect(instance, directory, unreadable); + unreadable.report(context, "lithe/build/prepareRun"); + if (module == null || (request.kind != null && !request.kind.equals(module.kind.id))) { + throw new PluginError("tomcat.run.notWebModule", messages.notWebModule(request.targetName)); + } + Path home = home(); + int port = settings.httpPort; + if (inUse(port)) { + throw new PluginError("tomcat.run.portInUse", messages.portBusy(port)); + } + Map environment = environment(request.environment); + Path docBase; + Path classes = null; + switch (module.kind) { + case MAVEN: + docBase = maven(context, instance, directory, module, request, environment); + break; + case GRADLE: + docBase = gradle(context, instance, directory, module, request, environment); + break; + default: + docBase = instance.resolve(module.webRoot).normalize(); + if (module.classes != null) { + classes = instance.resolve(module.classes).normalize(); + } + break; + } + CatalinaBase base = CatalinaBase.write(state, home, request.root + "\n" + projectPath, port, module.contextPath, + docBase, classes); + context.progress(messages.startingTomcat(module.name, module.contextPath.isEmpty() ? "/" : module.contextPath, port), + null, null); + return launch(request, home, base.directory); + } + + /** The launch plan; {@code catalina.sh run} with the same system properties. */ + Map launch(Request request, Path home, Path base) { + List arguments = new ArrayList<>(request.runtimeArguments); + if (request.debugPort > 0) { + arguments.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + + request.debugHost + ":" + request.debugPort); + } + arguments.add("-Dcatalina.home=" + home); + arguments.add("-Dcatalina.base=" + base); + arguments.add("-Djava.io.tmpdir=" + base.resolve("temp")); + Path logging = base.resolve("conf").resolve("logging.properties"); + if (Files.isRegularFile(logging)) { + arguments.add("-Djava.util.logging.config.file=" + logging); + } + arguments.add("-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager"); + arguments.add("-Djdk.tls.ephemeralDHKeySize=2048"); + arguments.add("-Djava.protocol.handler.pkgs=org.apache.catalina.webresources"); + arguments.add("-classpath"); + arguments.add(home.resolve("bin").resolve("bootstrap.jar") + File.pathSeparator + + home.resolve("bin").resolve("tomcat-juli.jar")); + arguments.add(BOOTSTRAP); + arguments.add("start"); + Map environment = new LinkedHashMap<>(request.launchEnvironment); + StringBuilder opens = new StringBuilder(); + for (String module : ADD_OPENS) { + opens.append(opens.length() == 0 ? "" : " ").append("--add-opens=").append(module).append("=ALL-UNNAMED"); + } + String existing = environment.get("JDK_JAVA_OPTIONS"); + environment.put("JDK_JAVA_OPTIONS", existing == null || existing.trim().isEmpty() + ? opens.toString() : existing + " " + opens); + Map executable = new LinkedHashMap<>(); + executable.put("kind", "toolchain"); + executable.put("value", JAVA_TOOL); + Map plan = new LinkedHashMap<>(); + plan.put("executable", executable); + plan.put("arguments", arguments); + plan.put("workingDirectory", request.workingDirectory != null ? request.workingDirectory : request.projectPath); + plan.put("environment", environment); + return plan; + } + + /** The Tomcat installation: the setting, otherwise {@code CATALINA_HOME}. */ + Path home() { + String chosen = settings.tomcatHome.trim(); + if (chosen.isEmpty()) { + String variable = System.getenv("CATALINA_HOME"); + chosen = variable == null ? "" : variable.trim(); + } + if (chosen.isEmpty()) { + throw new PluginError("tomcat.run.noHome", messages.noHome()); + } + Path home; + try { + home = Paths.get(chosen).toAbsolutePath().normalize(); + } catch (java.nio.file.InvalidPathException invalid) { + throw new PluginError("tomcat.run.invalidHome", messages.invalidHome()); + } + for (String required : new String[] {"bin/bootstrap.jar", "bin/tomcat-juli.jar", "lib/catalina.jar", "conf/web.xml"}) { + if (!Files.isRegularFile(home.resolve(required))) { + throw new PluginError("tomcat.run.invalidHome", messages.invalidHome()); + } + } + return home; + } + + /** True when something accepts connections on, or holds, the loopback port. */ + static boolean inUse(int port) { + InetAddress loopback = InetAddress.getLoopbackAddress(); + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress(loopback, port), 300); + return true; + } catch (IOException free) { + // Nothing answers; a bound but idle socket is caught below. + } + // The platform's default address reuse, as Tomcat binds its connector: a + // port a just-stopped Tomcat left in TIME_WAIT is free for the next run. + try (ServerSocket socket = new ServerSocket()) { + socket.bind(new InetSocketAddress(loopback, port)); + return false; + } catch (IOException taken) { + return true; + } + } + + /** + * Builds a Maven {@code war} module with {@code package -DskipTests} and + * returns the exploded application Maven writes next to the WAR. A + * module of a reactor builds from the reactor root with {@code -pl -am}, + * so the modules it depends on are built first. + */ + private Path maven(CallContext context, Path instance, Path directory, WebModules.Module module, Request request, + Map environment) throws Exception { + Path root = mavenRoot(instance, directory); + boolean windows = File.separatorChar == '\\'; + List command = new ArrayList<>(); + command.add(executable(mavenCommand(root, environment, windows), environment, windows)); + command.add("-B"); + command.add("-ntp"); + command.addAll(request.optionArguments); + if (!root.equals(directory)) { + command.add("-pl"); + command.add("./" + WebModules.relative(root, directory)); + command.add("-am"); + } + command.add("-DskipTests"); + command.add("package"); + build(context, command, root, environment, module, "Maven"); + Path war = singleWar(directory.resolve("target"), "Maven"); + String name = war.getFileName().toString(); + Path exploded = war.resolveSibling(name.substring(0, name.length() - ".war".length())); + return Files.isDirectory(exploded.resolve("WEB-INF")) ? exploded : war; + } + + /** Builds a Gradle {@code war} module with its {@code war} task and returns the WAR. */ + private Path gradle(CallContext context, Path instance, Path directory, WebModules.Module module, Request request, + Map environment) throws Exception { + Path root = gradleRoot(instance, directory); + boolean windows = File.separatorChar == '\\'; + List command = new ArrayList<>(); + command.add(executable(gradleCommand(root, environment, windows), environment, windows)); + command.add("--console=plain"); + command.addAll(request.optionArguments); + command.add("-p"); + command.add(directory.toString()); + command.add("war"); + build(context, command, root, environment, module, "Gradle"); + return singleWar(directory.resolve("build").resolve("libs"), "Gradle"); + } + + private void build(CallContext context, List command, Path directory, Map environment, + WebModules.Module module, String tool) throws Exception { + context.progress(messages.building(module.name), null, null); + Processes.Result result = context.run(command, new Processes.Options() + .directory(directory) + .environment(environment) + .cancellation(context.cancellation()) + .maxOutputBytes(64 * 1024) + .onStdout(text -> stream(context, text)) + .onStderr(text -> stream(context, text))); + if (result.exitCode() != 0) { + throw new PluginError("tomcat.run.buildFailed", messages.buildFailed(tool, result.exitCode())); + } + } + + /** The one WAR in {@code directory}, leaving out Gradle's {@code -plain} archive. */ + private Path singleWar(Path directory, String tool) throws IOException { + List wars = new ArrayList<>(); + if (Files.isDirectory(directory)) { + try (DirectoryStream files = Files.newDirectoryStream(directory, "*.war")) { + for (Path file : files) { + if (Files.isRegularFile(file) && !file.getFileName().toString().endsWith("-plain.war")) { + wars.add(file); + } + } + } + } + if (wars.size() != 1) { + throw new PluginError("tomcat.run.noArtifact", messages.noArtifact(tool)); + } + return wars.get(0); + } + + /** + * The outermost directory, inside the instance, whose {@code pom.xml} + * lists the next directory down as a module, starting at the module. + */ + static Path mavenRoot(Path instance, Path directory) { + Path root = directory; + while (!root.equals(instance) && root.getParent() != null && root.getParent().startsWith(instance)) { + Path parent = root.getParent(); + Path pom = parent.resolve("pom.xml"); + if (!Files.isRegularFile(pom) || !listsModule(pom, parent, root)) { + break; + } + root = parent; + } + return root; + } + + private static boolean listsModule(Path pom, Path parent, Path child) { + Document document = WebModules.xml(pom); + if (document == null) { + return false; + } + org.w3c.dom.NodeList modules = document.getElementsByTagNameNS("*", "module"); + for (int index = 0; index < modules.getLength(); index++) { + Node node = modules.item(index); + String text = node.getTextContent().trim(); + if (!text.isEmpty() && parent.resolve(text).normalize().equals(child)) { + return true; + } + } + return false; + } + + /** The nearest directory, from the module up to the instance root, holding a Gradle settings file. */ + static Path gradleRoot(Path instance, Path directory) { + for (Path candidate = directory; candidate != null && candidate.startsWith(instance); candidate = candidate.getParent()) { + if (Files.isRegularFile(candidate.resolve("settings.gradle")) || Files.isRegularFile(candidate.resolve("settings.gradle.kts"))) { + return candidate; + } + } + return directory; + } + + /** The project's Maven wrapper, otherwise {@code MAVEN_HOME}, otherwise {@code mvn}. */ + static String mavenCommand(Path root, Map environment, boolean windows) { + Path wrapper = root.resolve(windows ? "mvnw.cmd" : "mvnw"); + if (Files.isRegularFile(wrapper) && Files.isRegularFile(root.resolve(".mvn/wrapper/maven-wrapper.properties"))) { + return wrapper.toString(); + } + String home = variable(environment, "MAVEN_HOME", windows); + if (home != null && !home.isEmpty()) { + Path candidate = Paths.get(home, "bin", windows ? "mvn.cmd" : "mvn"); + if (Files.isRegularFile(candidate)) { + return candidate.toString(); + } + } + return "mvn"; + } + + /** The project's Gradle wrapper, otherwise {@code GRADLE_HOME}, otherwise {@code gradle}. */ + static String gradleCommand(Path root, Map environment, boolean windows) { + Path wrapper = root.resolve(windows ? "gradlew.bat" : "gradlew"); + if (Files.isRegularFile(wrapper) && Files.isRegularFile(root.resolve("gradle/wrapper/gradle-wrapper.properties"))) { + return wrapper.toString(); + } + String home = variable(environment, "GRADLE_HOME", windows); + if (home != null && !home.isEmpty()) { + Path candidate = Paths.get(home, "bin", windows ? "gradle.bat" : "gradle"); + if (Files.isRegularFile(candidate)) { + return candidate.toString(); + } + } + return "gradle"; + } + + /** + * The path to start for {@code command}: a bare name is looked up on the + * {@code PATH} of {@code environment}, trying each {@code PATHEXT} + * extension on Windows, where Java would otherwise find only + * {@code .exe} files. + */ + String executable(String command, Map environment, boolean windows) { + if (command.indexOf('/') >= 0 || (windows && (command.indexOf('\\') >= 0 || command.indexOf(':') >= 0))) { + return command; + } + List names = new ArrayList<>(); + String extensions = variable(environment, "PATHEXT", windows); + if (windows && command.indexOf('.') < 0) { + for (String extension : (extensions == null || extensions.isEmpty() ? ".COM;.EXE;.BAT;.CMD" : extensions).split(";")) { + if (!extension.isEmpty()) { + names.add(command + extension.toLowerCase(Locale.ROOT)); + } + } + } else { + names.add(command); + } + String path = variable(environment, "PATH", windows); + if (path != null) { + for (String folder : path.split(File.pathSeparator)) { + if (folder.isEmpty()) { + continue; + } + for (String name : names) { + Path candidate; + try { + candidate = Paths.get(folder.replace("\"", ""), name); + } catch (java.nio.file.InvalidPathException ignored) { + break; + } + if (Files.isRegularFile(candidate) && (windows || Files.isExecutable(candidate))) { + return candidate.toString(); + } + } + } + } + throw new PluginError("tomcat.run.noTool", messages.noTool(command)); + } + + private static String variable(Map environment, String name, boolean windows) { + if (!windows) { + return environment.get(name); + } + for (Map.Entry entry : environment.entrySet()) { + if (entry.getKey().equalsIgnoreCase(name)) { + return entry.getValue(); + } + } + return null; + } + + /** + * The build's environment: the provider's own with the build options' + * variables on top, and {@code JAVA_HOME} set to the JDK Lithe started + * the provider on when nothing sets it, so the build uses the project JDK. + */ + static Map environment(Map overrides) { + Map environment = new LinkedHashMap<>(System.getenv()); + environment.putAll(overrides); + if (variable(environment, "JAVA_HOME", File.separatorChar == '\\') == null) { + Path java = Paths.get(System.getProperty("java.home")); + // A Java 8 runtime reports its jre folder; the JDK is its parent. + if (java.getFileName() != null && "jre".equals(java.getFileName().toString()) + && Files.isDirectory(java.getParent().resolve("bin"))) { + java = java.getParent(); + } + environment.put("JAVA_HOME", java.toString()); + } + return environment; + } + + private static void stream(CallContext context, String text) { + for (int start = 0; start < text.length(); start += OUTPUT_CHUNK) { + context.progress(null, null, text.substring(start, Math.min(text.length(), start + OUTPUT_CHUNK))); + } + } + + /** {@code path} relative to {@code root}, both workspace-relative with forward slashes. */ + static String relative(String root, String path) { + if (".".equals(root) || root.isEmpty()) { + return path.isEmpty() ? "." : path; + } + if (path.equals(root)) { + return "."; + } + if (path.startsWith(root + "/")) { + return path.substring(root.length() + 1); + } + throw new PluginError("tomcat.run.invalidProject", "The project is outside the build root."); + } + + static List strings(Object value) { + List result = new ArrayList<>(); + if (value instanceof List) { + for (Object item : (List) value) { + result.add(String.valueOf(item)); + } + } + return result; + } + + private static Map stringMap(Object value) { + Map result = new LinkedHashMap<>(); + if (value instanceof Map) { + for (Map.Entry entry : ((Map) value).entrySet()) { + result.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); + } + } + return result; + } + + private static Map object(Object value) { + return value instanceof Map ? Json.object(value) : Collections.emptyMap(); + } + + private static String text(Object value) { + if (value == null) { + return null; + } + String text = value.toString().trim(); + return text.isEmpty() ? null : text; + } + + /** The fields of one prepareRun request this provider uses. */ + static final class Request { + String root = "."; + String projectPath = "."; + String targetName = ""; + String kind; + List optionArguments = new ArrayList<>(); + Map environment = new LinkedHashMap<>(); + List runtimeArguments = new ArrayList<>(); + List arguments = new ArrayList<>(); + List userArguments = new ArrayList<>(); + Map launchEnvironment = new LinkedHashMap<>(); + String workingDirectory; + String debugHost; + int debugPort; + + static Request of(Map params) { + Request request = new Request(); + String root = text(params.get("root")); + request.root = root == null ? "." : root; + String projectPath = text(object(params.get("project")).get("path")); + request.projectPath = projectPath == null ? request.root : projectPath; + Map target = object(params.get("target")); + String name = text(target.get("name")); + request.targetName = name == null ? "" : name; + request.kind = text(object(target.get("properties")).get("kind")); + request.optionArguments = strings(params.get("optionArguments")); + request.environment = stringMap(params.get("environment")); + request.userArguments = strings(params.get("userArguments")); + Map options = object(params.get("launchOptions")); + request.runtimeArguments = strings(options.get("runtimeArguments")); + request.arguments = strings(options.get("arguments")); + request.launchEnvironment = stringMap(options.get("environment")); + request.workingDirectory = text(options.get("workingDirectory")); + if (options.get("debug") instanceof Map) { + Map endpoint = object(Json.object(options.get("debug")).get("target")); + request.debugHost = text(endpoint.get("host")); + Object port = endpoint.get("port"); + request.debugPort = port instanceof Number ? ((Number) port).intValue() : 0; + if (request.debugHost == null || request.debugPort < 1 || request.debugPort > 65535) { + throw new PluginError("tomcat.run.invalidDebug", "The debug target is not a local connection."); + } + } + return request; + } + } +} diff --git a/provider/src/main/java/io/github/litheidea/tomcat/Settings.java b/provider/src/main/java/io/github/litheidea/tomcat/Settings.java new file mode 100644 index 0000000..08e6709 --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/tomcat/Settings.java @@ -0,0 +1,30 @@ +package io.github.litheidea.tomcat; + +import java.util.Map; + +/** + * The plugin settings Lithe passes in {@code initializationOptions}. Lithe + * restarts the provider when one changes, so they are fixed for a process. + */ +final class Settings { + static final int DEFAULT_HTTP_PORT = 8080; + + /** CATALINA_HOME chosen in the settings; empty means "use CATALINA_HOME". */ + final String tomcatHome; + final int httpPort; + + private Settings(String tomcatHome, int httpPort) { + this.tomcatHome = tomcatHome; + this.httpPort = httpPort; + } + + static Settings of(Map options) { + Object home = options.get("tomcatHome"); + Object port = options.get("httpPort"); + int httpPort = port instanceof Number ? ((Number) port).intValue() : DEFAULT_HTTP_PORT; + if (httpPort < 1 || httpPort > 65535) { + httpPort = DEFAULT_HTTP_PORT; + } + return new Settings(home instanceof String ? (String) home : "", httpPort); + } +} diff --git a/provider/src/main/java/io/github/litheidea/tomcat/TomcatProvider.java b/provider/src/main/java/io/github/litheidea/tomcat/TomcatProvider.java new file mode 100644 index 0000000..fa7f122 --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/tomcat/TomcatProvider.java @@ -0,0 +1,69 @@ +package io.github.litheidea.tomcat; + +import io.github.litheidea.plugin.sdk.Backend; +import io.github.litheidea.plugin.sdk.Json; +import io.github.litheidea.plugin.sdk.PluginError; +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; +import java.util.Map; + +/** + * The Tomcat build provider process. Lithe starts it on the first build + * request of a Tomcat build instance and talks to it over stdio: + * {@code lithe/build/model} lists the Web modules of the instance, and + * {@code lithe/build/prepareRun} builds one module and returns the launch of + * a Tomcat whose private CATALINA_BASE serves it. Lithe starts, stops and + * debugs that process; this one never owns a server. + * + *

Arguments: {@code --state

}, the workspace state directory Lithe + * gives the build system, which holds the generated CATALINA_BASE folders. + * Settings arrive as {@code initializationOptions}. + */ +public final class TomcatProvider { + private TomcatProvider() {} + + public static void main(String[] args) throws Exception { + Path state = state(args); + Backend backend = Backend.create("lithe-tomcat-provider", TomcatProvider.class.getPackage().getImplementationVersion()); + backend.onModel((params, context) -> new WebModules(workspace(backend), context).model(params)); + backend.onPrepareRun((params, context) -> new Preparation(workspace(backend), state, settings(backend), messages(backend)) + .prepare(params, context)); + // The model is read again whenever a watched build file changes; its + // success is routine, and a failure or a degraded scan is still logged. + backend.suppressSuccessDiagnostics("lithe/build/model"); + backend.listen(); + } + + private static Path state(String[] args) { + for (int index = 0; index + 1 < args.length; index++) { + if ("--state".equals(args[index])) { + return Paths.get(args[index + 1]).toAbsolutePath().normalize(); + } + } + throw new IllegalArgumentException("usage: --state "); + } + + /** The workspace folder Lithe sent in {@code initialize}. */ + static Path workspace(Backend backend) { + Map initialize = backend.initializeParams(); + Object root = initialize == null ? null : initialize.get("rootUri"); + if (!(root instanceof String)) { + throw new PluginError("tomcat.noWorkspace", "Lithe sent no workspace folder."); + } + return Paths.get(URI.create((String) root)).toAbsolutePath().normalize(); + } + + private static Settings settings(Backend backend) { + Map initialize = backend.initializeParams(); + Object options = initialize == null ? null : initialize.get("initializationOptions"); + return Settings.of(options instanceof Map ? Json.object(options) : Collections.emptyMap()); + } + + private static Messages messages(Backend backend) { + Map initialize = backend.initializeParams(); + Object locale = initialize == null ? null : initialize.get("locale"); + return new Messages(locale instanceof String ? (String) locale : null); + } +} diff --git a/provider/src/main/java/io/github/litheidea/tomcat/WebModules.java b/provider/src/main/java/io/github/litheidea/tomcat/WebModules.java new file mode 100644 index 0000000..88eb398 --- /dev/null +++ b/provider/src/main/java/io/github/litheidea/tomcat/WebModules.java @@ -0,0 +1,463 @@ +package io.github.litheidea.tomcat; + +import io.github.litheidea.plugin.sdk.CallContext; +import io.github.litheidea.plugin.sdk.PluginError; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * Finds the Web modules of one Tomcat build instance and answers + * {@code lithe/build/model} with one project and one + * {@code web-application} target for each. + * + *

A directory is a Web module when, checked in this order: + *

    + *
  1. its {@code pom.xml} has {@code war} (Maven);
  2. + *
  3. its {@code build.gradle} or {@code build.gradle.kts} applies the + * {@code war} plugin (Gradle);
  4. + *
  5. its Eclipse WTP component file deploys a folder to {@code /} + * (Eclipse Dynamic Web Project);
  6. + *
  7. one of the usual Web roots holds {@code WEB-INF/web.xml}.
  8. + *
+ * A directory with a Maven or Gradle build file is only ever a Maven or + * Gradle module, so an Eclipse or IntelliJ project generated from it is not + * listed twice. The scan reads no file twice per request and keeps nothing + * between requests: Lithe asks again when a watched file changes. + */ +final class WebModules { + static final String TAG = "web-application"; + /** Directory levels below the instance root the scan enters. */ + static final int MAX_DEPTH = 8; + /** Directories one scan visits before it reports the model as partial. */ + static final int MAX_DIRECTORIES = 5_000; + private static final int MAX_BUILD_FILE = 1 << 20; + private static final Set SKIPPED = new HashSet<>(Arrays.asList( + "target", "build", "out", "bin", "node_modules", "src", "WEB-INF", "META-INF")); + static final List WEB_ROOTS = Collections.unmodifiableList(Arrays.asList( + "src/main/webapp", "WebContent", "WebRoot", "webapp", "web")); + private static final Pattern GRADLE_WAR = Pattern.compile( + "(?m)^\\s*(?:war\\s*$|id\\s*\\(?\\s*[\"']war[\"']|apply\\s*\\(?\\s*plugin\\s*[:=]\\s*[\"']war[\"'])"); + private static final String WTP_COMPONENT = ".settings/org.eclipse.wst.common.component"; + + /** How a module is built and where its files come from. */ + enum Kind { + MAVEN("maven"), GRADLE("gradle"), WTP("eclipse"), PLAIN("plain"); + + final String id; + + Kind(String id) { + this.id = id; + } + } + + /** One Web module; paths are relative to the instance root, with {@code /}. */ + static final class Module { + final Kind kind; + final String path; + final String name; + final String contextPath; + /** The folder served as the application, for modules nothing builds. */ + final String webRoot; + /** Compiled classes mounted at {@code /WEB-INF/classes}, when they are outside the Web root. */ + final String classes; + + Module(Kind kind, String path, String name, String contextPath, String webRoot, String classes) { + this.kind = kind; + this.path = path; + this.name = name; + this.contextPath = contextPath; + this.webRoot = webRoot; + this.classes = classes; + } + } + + /** + * Build files that exist but could not be read or parsed during one + * request. A module behind one is left out, so the request reports the + * count once as a degraded result instead of hiding it. + */ + static final class Unreadable { + long count; + + void report(CallContext context, String operation) { + if (count > 0) { + context.diagnostics().degraded(operation, "buildFileUnreadable", count); + } + } + } + + private final Path workspace; + private final CallContext context; + + WebModules(Path workspace, CallContext context) { + this.workspace = workspace; + this.context = context; + } + + Map model(Map params) throws IOException { + Object root = params.get("root"); + Path instance = workspace.resolve(root instanceof String ? (String) root : ".").normalize(); + if (!instance.startsWith(workspace)) { + throw new PluginError("tomcat.invalidRoot", "The build root is outside the workspace."); + } + List> projects = new ArrayList<>(); + List> targets = new ArrayList<>(); + Unreadable unreadable = new Unreadable(); + List modules = scan(instance, unreadable); + unreadable.report(context, "lithe/build/model"); + for (Module module : modules) { + Map properties = new LinkedHashMap<>(); + properties.put("kind", module.kind.id); + Map project = new LinkedHashMap<>(); + project.put("path", module.path); + project.put("name", module.name); + project.put("properties", properties); + projects.add(project); + Map targetProperties = new LinkedHashMap<>(properties); + targetProperties.put("contextPath", module.contextPath); + if (module.webRoot != null) { + targetProperties.put("webRoot", module.webRoot); + } + Map target = new LinkedHashMap<>(); + target.put("project", module.path); + target.put("path", module.path); + target.put("name", module.name); + target.put("tags", Collections.singletonList(TAG)); + target.put("properties", targetProperties); + targets.add(target); + } + Map model = new LinkedHashMap<>(); + model.put("format", "litheBuildModel"); + model.put("version", 0); + model.put("projects", projects); + model.put("targets", targets); + model.put("tasks", Collections.emptyList()); + model.put("contentRoots", Collections.emptyList()); + model.put("optionValues", Collections.emptyMap()); + return model; + } + + /** Every Web module below {@code instance}, in directory order. */ + List scan(Path instance, Unreadable unreadable) throws IOException { + List modules = new ArrayList<>(); + Deque pending = new ArrayDeque<>(); + Deque depths = new ArrayDeque<>(); + pending.add(instance); + depths.add(0); + int visited = 0; + while (!pending.isEmpty()) { + context.throwIfCancelled(); + Path directory = pending.removeFirst(); + int depth = depths.removeFirst(); + if (++visited > MAX_DIRECTORIES) { + context.diagnostics().degraded("lithe/build/model", "webModuleScanTruncated", (long) MAX_DIRECTORIES); + break; + } + Module module = detect(instance, directory, unreadable); + if (module != null) { + modules.add(module); + } + if (depth >= MAX_DEPTH) { + continue; + } + List children = new ArrayList<>(); + try (DirectoryStream entries = Files.newDirectoryStream(directory)) { + for (Path child : entries) { + String name = child.getFileName().toString(); + if (!name.startsWith(".") && !SKIPPED.contains(name) && Files.isDirectory(child) + && !Files.isSymbolicLink(child) && !isWebRoot(instance, child, module)) { + children.add(child); + } + } + } catch (IOException failed) { + unreadable.count++; + continue; + } + Collections.sort(children); + for (Path child : children) { + pending.add(child); + depths.add(depth + 1); + } + } + return modules; + } + + private static boolean isWebRoot(Path instance, Path child, Module module) { + return module != null && module.webRoot != null && child.equals(instance.resolve(module.webRoot)); + } + + /** The module at {@code directory}, or null when it is none. */ + static Module detect(Path instance, Path directory, Unreadable unreadable) { + String path = relative(instance, directory); + String folder = directory.getFileName() == null || path.equals(".") + ? folderName(directory) : directory.getFileName().toString(); + if (directory.equals(instance) && "WEB-INF".equals(folder) && Files.isRegularFile(directory.resolve("web.xml"))) { + return webInfRoot(instance, directory); + } + Path pom = directory.resolve("pom.xml"); + Path gradle = Files.isRegularFile(directory.resolve("build.gradle.kts")) + ? directory.resolve("build.gradle.kts") : directory.resolve("build.gradle"); + if (Files.isRegularFile(pom)) { + Document document = xml(pom); + if (document == null) { + unreadable.count++; + return null; + } + if (!"war".equals(childText(document.getDocumentElement(), "packaging"))) { + return null; + } + String artifact = childText(document.getDocumentElement(), "artifactId"); + String name = artifact == null ? folder : artifact; + return new Module(Kind.MAVEN, path, name, "/" + segment(name), null, null); + } + if (Files.isRegularFile(gradle)) { + String text = read(gradle); + if (text == null) { + unreadable.count++; + return null; + } + if (!GRADLE_WAR.matcher(stripComments(text)).find()) { + return null; + } + return new Module(Kind.GRADLE, path, folder, "/" + segment(folder), null, null); + } + Module wtp = wtp(instance, directory, path, folder, unreadable); + if (wtp != null) { + return wtp; + } + for (String candidate : WEB_ROOTS) { + Path webRoot = directory.resolve(candidate); + if (Files.isRegularFile(webRoot.resolve("WEB-INF/web.xml"))) { + String classes = firstDirectory(directory, + "out/production/" + folder, "build/classes/java/main", "build/classes", "bin", "classes"); + return new Module(Kind.PLAIN, path, folder, "/" + segment(folder), + relative(instance, webRoot), classes == null ? null : join(path, classes)); + } + } + return null; + } + + /** + * A plain Web folder found by its {@code web.xml} alone. Lithe makes the + * folder holding the marker, {@code WEB-INF}, the instance root, so the + * module is that instance: the application is the folder above it, and + * the project it belongs to is the one above a usual Web-root name + * ({@code web}, {@code WebContent}, {@code src/main/webapp}...), whose + * output folder supplies the compiled classes. + */ + private static Module webInfRoot(Path instance, Path webInf) { + Path webRoot = webInf.getParent(); + Path project = webRoot; + for (String candidate : WEB_ROOTS) { + Path owner = webRoot; + for (int level = candidate.split("/").length; level > 0 && owner != null; level--) { + owner = owner.getParent(); + } + if (owner != null && owner.resolve(candidate).normalize().equals(webRoot)) { + project = owner; + break; + } + } + String name = folderName(project); + String classes = firstDirectory(project, "out/production/" + name, "build/classes/java/main", "build/classes", "bin", "classes"); + return new Module(Kind.PLAIN, ".", name, "/" + segment(name), relative(instance, webRoot), + classes == null ? null : relative(instance, project.resolve(classes))); + } + + /** An Eclipse Dynamic Web Project: its component file names the Web root and the context root. */ + private static Module wtp(Path instance, Path directory, String path, String folder, Unreadable unreadable) { + Path component = directory.resolve(WTP_COMPONENT); + if (!Files.isRegularFile(component) || !Files.isRegularFile(directory.resolve(".project"))) { + return null; + } + Document document = xml(component); + if (document == null) { + unreadable.count++; + return null; + } + NodeList modules = document.getElementsByTagName("wb-module"); + if (modules.getLength() == 0) { + return null; + } + Element module = (Element) modules.item(0); + String webRoot = null; + String contextRoot = null; + for (Node child = module.getFirstChild(); child != null; child = child.getNextSibling()) { + if (!(child instanceof Element)) { + continue; + } + Element element = (Element) child; + if ("wb-resource".equals(element.getTagName()) && "/".equals(element.getAttribute("deploy-path")) && webRoot == null) { + webRoot = trimSlashes(element.getAttribute("source-path")); + } else if ("property".equals(element.getTagName()) && "context-root".equals(element.getAttribute("name"))) { + contextRoot = trimSlashes(element.getAttribute("value")); + } + } + if (webRoot == null || webRoot.isEmpty() || webRoot.contains("..") || !Files.isDirectory(directory.resolve(webRoot))) { + return null; + } + String deployName = module.getAttribute("deploy-name"); + String name = deployName == null || deployName.trim().isEmpty() ? folder : deployName.trim(); + String context = contextRoot == null ? segment(name) : contextPath(contextRoot); + String output = eclipseOutput(directory, unreadable); + String classes = output != null && Files.isDirectory(directory.resolve(output)) ? join(path, output) : null; + return new Module(Kind.WTP, path, name, context.isEmpty() ? "" : "/" + context, + relative(instance, directory.resolve(webRoot)), classes); + } + + /** The {@code output} entry of an Eclipse {@code .classpath}. */ + private static String eclipseOutput(Path directory, Unreadable unreadable) { + Path classpath = directory.resolve(".classpath"); + if (!Files.isRegularFile(classpath)) { + return null; + } + Document document = xml(classpath); + if (document == null) { + unreadable.count++; + return null; + } + NodeList entries = document.getElementsByTagName("classpathentry"); + for (int index = 0; index < entries.getLength(); index++) { + Element entry = (Element) entries.item(index); + if ("output".equals(entry.getAttribute("kind"))) { + String output = trimSlashes(entry.getAttribute("path")); + return output.isEmpty() || output.contains("..") ? null : output; + } + } + return null; + } + + private static String firstDirectory(Path directory, String... candidates) { + for (String candidate : candidates) { + if (Files.isDirectory(directory.resolve(candidate))) { + return candidate; + } + } + return null; + } + + /** A context root made of safe path segments; empty is the root context. */ + static String contextPath(String value) { + StringBuilder result = new StringBuilder(); + for (String part : value.split("/")) { + if (part.isEmpty()) { + continue; + } + if (result.length() > 0) { + result.append('/'); + } + result.append(segment(part)); + } + return result.toString(); + } + + /** One URL path segment Tomcat can also use in a context file name. */ + static String segment(String value) { + StringBuilder result = new StringBuilder(); + for (char character : value.toCharArray()) { + result.append(Character.isLetterOrDigit(character) && character < 128 || character == '.' || character == '-' + || character == '_' ? character : '_'); + } + String text = result.toString(); + return text.isEmpty() || text.equals(".") || text.equals("..") ? "app" : text; + } + + static String relative(Path instance, Path path) { + String relative = instance.relativize(path).toString().replace('\\', '/'); + return relative.isEmpty() ? "." : relative; + } + + static String join(String parent, String child) { + return ".".equals(parent) ? child : parent + "/" + child; + } + + private static String folderName(Path directory) { + Path name = directory.toAbsolutePath().normalize().getFileName(); + return name == null ? "app" : name.toString(); + } + + private static String trimSlashes(String value) { + String text = value == null ? "" : value.trim().replace('\\', '/'); + while (text.startsWith("/")) { + text = text.substring(1); + } + while (text.endsWith("/")) { + text = text.substring(0, text.length() - 1); + } + return text; + } + + private static String childText(Element parent, String name) { + for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) { + if (child instanceof Element && name.equals(localName(child))) { + String text = child.getTextContent().trim(); + return text.isEmpty() ? null : text; + } + } + return null; + } + + private static String localName(Node node) { + String name = node.getLocalName() != null ? node.getLocalName() : node.getNodeName(); + int colon = name.indexOf(':'); + return colon < 0 ? name : name.substring(colon + 1); + } + + /** Drops line and block comments so a commented-out {@code war} plugin does not count. */ + static String stripComments(String text) { + return text.replaceAll("(?s)/\\*.*?\\*/", "").replaceAll("(?m)//.*$", ""); + } + + private static String read(Path file) { + try { + if (Files.size(file) > MAX_BUILD_FILE) { + return null; + } + return new String(Files.readAllBytes(file), StandardCharsets.UTF_8); + } catch (IOException unreadable) { + return null; + } + } + + /** A parsed XML file, or null when it cannot be read; no DTD or external entity is loaded. */ + static Document xml(Path file) { + try (InputStream input = Files.newInputStream(file)) { + if (Files.size(file) > MAX_BUILD_FILE) { + return null; + } + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setExpandEntityReferences(false); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + DocumentBuilder builder = factory.newDocumentBuilder(); + // Report a malformed file as an exception, not as text on standard error. + builder.setErrorHandler(new org.xml.sax.helpers.DefaultHandler()); + return builder.parse(input); + } catch (Exception unreadable) { + return null; + } + } +} diff --git a/scripts/e2e-host.mjs b/scripts/e2e-host.mjs new file mode 100644 index 0000000..0820ff7 --- /dev/null +++ b/scripts/e2e-host.mjs @@ -0,0 +1,84 @@ +// Runs this plugin's host end-to-end tests against a pinned Lithe desktop host. +// +// node scripts/e2e-host.mjs [--source ] [--ref ] [--run ] [--suite ] +// +// The tests in e2e/host/ drive the real plugin package through the desktop host's own test +// harness (an internal Go package), so they cannot be built in this repository. Each run checks +// out the host revision pinned in e2e/host/lithe-host.json into the disposable .artifacts/lithe-host +// (desktop/ and scripts/ only) and overlays the plugin's test files while running +// the host's scripts/desktop/desktop-go.sh test, which builds the Core +// revision that host pins. The host repository never reads this repository: the tests live here +// and the pin says which host they last passed on. Bumping the pin can require adapting the tests +// to changes in the host's internal harness. +// +// Every variable listed in lithe-host.json "requiredEnvironment" must be set, because the tests +// skip without their plugin input and a skipped run proves nothing. "repositoryEnvironment" maps a +// variable to a path in this repository, used when the variable is not set. --source and --ref override +// the pin, for example to try an unmerged host branch; --run overrides the test selection. +// --suite selects a named test group and its required plugin inputs. +import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'; +import { join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; +import { runCommand, withInterrupts } from './process.mjs'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const tests = join(root, 'e2e', 'host'); +const work = join(root, '.artifacts', 'lithe-host'); + +/** Lists the files under e2e/host/desktop, relative to e2e/host. */ +async function hostTestFiles(directory = join(tests, 'desktop')) { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const path = join(directory, entry.name); + if (entry.isDirectory()) files.push(...await hostTestFiles(path)); + else if (entry.isFile()) files.push(relative(tests, path)); + } + return files; +} + +/** Checks out `ref` from `source` into the disposable work directory, desktop/ and scripts/ only. */ +async function checkoutHost(source, ref, signal) { + const run = (args) => runCommand('git', args, { timeoutMs: 120_000, signal }); + await mkdir(work, { recursive: true }); + await run(['init', '-q', work]); + await run(['-C', work, 'sparse-checkout', 'set', '--cone', 'desktop', 'scripts']); + // A named remote, because the partial clone fetches missing blobs from it later. + await run(['-C', work, 'config', 'remote.origin.url', source]); + await run(['-C', work, 'fetch', '-q', '--depth', '1', '--filter=blob:none', 'origin', ref]); + await run(['-C', work, 'checkout', '-q', '--force', '--detach', 'FETCH_HEAD']); + // Discard test files left by earlier versions of this runner in its disposable checkout. + await run(['-C', work, 'clean', '-q', '-f', '-d', '--', 'desktop']); +} + +const { values } = parseArgs({ + options: { source: { type: 'string' }, ref: { type: 'string' }, run: { type: 'string' }, suite: { type: 'string' } }, +}); +const pin = JSON.parse(await readFile(join(tests, 'lithe-host.json'), 'utf8')); +for (const [name, path] of Object.entries(pin.repositoryEnvironment ?? {})) { + process.env[name] ||= join(root, path); +} +const suite = values.suite && pin.suites?.[values.suite]; +if (values.suite && !suite) throw new Error(`Unknown host E2E suite: ${values.suite}`); +const required = suite?.requiredEnvironment ?? Object.keys(pin.requiredEnvironment ?? {}); +const missing = required.filter((name) => !process.env[name]); +if (missing.length > 0) { + throw new Error(`Set the plugin inputs first:\n${missing.map((name) => ` ${name}: ${pin.requiredEnvironment[name]}`).join('\n')}`); +} + +// git runs inside the checkout, so a local source must be absolute. +const given = values.source ?? pin.repository; +const source = !/^[a-z]+:\/\//.test(given) ? resolve(given) : given; +await withInterrupts(async (signal) => { + await checkoutHost(source, values.ref ?? pin.revision, signal); + const overlay = join(root, '.artifacts', 'lithe-host-overlay.json'); + const files = await hostTestFiles(); + await writeFile(overlay, JSON.stringify({ + Replace: Object.fromEntries(files.map((file) => [join(work, file), join(tests, file)])), + })); + for (const [pkg, selection] of Object.entries(suite?.packages ?? pin.packages)) { + await runCommand('bash', ['scripts/desktop/desktop-go.sh', 'test', '-overlay', overlay, pkg, + '-count=1', '-v', '-timeout', pin.timeout ?? '20m', '-run', values.run ?? selection], + { cwd: work, timeoutMs: 1_200_000, signal }); + } +}); diff --git a/scripts/lib/backend-client.mjs b/scripts/lib/backend-client.mjs new file mode 100644 index 0000000..ea09a5f --- /dev/null +++ b/scripts/lib/backend-client.mjs @@ -0,0 +1,183 @@ +// Talks to a plugin's Java process the way Lithe does: LSP base-protocol +// frames over the process's stdio, `initialize` offering litheBuild 0 and 1 +// with the plugin's initializationOptions and the interface locale, then +// lithe/build/* requests. Every wait is bounded, and the backend runs in its +// own process group so a test can always end whatever it left behind. +import { execFileSync, spawn } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export const WAIT_MS = 20_000; +const MAX_FRAME_BYTES = 16 * 1024 * 1024; +const MAX_HEADER_BYTES = 8 * 1024; +const MAX_STDERR_BYTES = 64 * 1024; +const MAX_DIAGNOSTICS = 1000; + +export class BackendClient { + #buffer = Buffer.alloc(0); + #pending = new Map(); + #nextId = 1; + stderr = ""; + /** The tail of the build output the backend reported with lithe/build/progress. */ + output = ""; + diagnostics = []; + + /** Starts `java -jar --state ` (or `args`); `javaOptions` go before `-jar`. */ + constructor({ java = "java", jar, state, env = process.env, javaOptions = [], timeoutMs = WAIT_MS, args, hostRequests = {} }) { + this.timeoutMs = timeoutMs; + // Answers to requests the backend sends to the host, keyed by method. + this.hostRequests = hostRequests; + this.child = spawn(java, [...javaOptions, "-jar", jar, ...(args ?? ["--state", state])], { + env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, + }); + this.exited = new Promise((resolve) => this.child.once("exit", (code, signal) => { + this.#fail(`the backend exited with ${signal ?? `status ${code}`}`); + resolve(signal ?? code); + })); + this.child.once("error", (error) => this.#fail(`cannot start the backend: ${error.message}`)); + this.child.stdout.on("data", (chunk) => this.#read(chunk)); + this.child.stderr.on("data", (chunk) => { + this.stderr = Buffer.concat([Buffer.from(this.stderr), chunk]).subarray(-MAX_STDERR_BYTES).toString("utf8"); + }); + this.child.stdin.on("error", () => {}); + } + + /** Sends a request; `response` settles with the whole response message. */ + send(method, params) { + const id = this.#nextId++; + const response = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.#pending.delete(id); + reject(new Error(`no response to ${method} #${id} within ${this.timeoutMs} ms\nbackend stderr:\n${this.stderr}`)); + }, this.timeoutMs); + this.#pending.set(id, (message) => { + clearTimeout(timer); + if (message instanceof Error) reject(message); + else resolve(message); + }); + }); + this.#write({ jsonrpc: "2.0", id, method, params }); + return { id, response }; + } + + /** Sends a request and resolves with its result, or rejects with its error. */ + async request(method, params) { + this.output = ""; + const message = await this.send(method, params).response; + if (message.error) { + const error = new Error(`${method} failed: ${message.error.message}${this.output ? `\nbuild output:\n${this.output}` : ""}`); + error.response = message.error; + throw error; + } + return message.result; + } + + notify(method, params) { + this.#write({ jsonrpc: "2.0", method, params }); + } + + cancel(id) { + this.notify("$/cancelRequest", { id }); + } + + async initialize(root, { functions = false, initializationOptions, locale } = {}) { + const result = await this.request("initialize", { + processId: process.pid, + rootUri: pathToFileURL(root).href, + ...(initializationOptions === undefined ? {} : { initializationOptions }), + ...(locale === undefined ? {} : { locale }), + capabilities: { experimental: { + ...(functions ? { litheFunctions: { versions: [0] } } : { litheBuild: { versions: [0, 1] } }), + litheLogging: { versions: [0] }, + } }, + }); + this.notify("initialized", {}); + return result; + } + + /** `shutdown` and `exit`; resolves with the exit code. */ + async close() { + if (this.child.exitCode === null && this.child.signalCode === null) { + await this.request("shutdown", null); + this.notify("exit", null); + this.child.stdin.end(); + } + return bounded(this.exited, "the backend to exit"); + } + + /** Ends the backend's whole process group, for teardown after a failure. */ + kill() { + if (!this.child.pid || this.child.exitCode !== null || this.child.signalCode !== null) return; + if (process.platform === "win32") { + try { + execFileSync("taskkill.exe", ["/PID", String(this.child.pid), "/T", "/F"], {timeout: 5000, windowsHide: true, stdio: "ignore"}); + } catch (error) { + // taskkill returns 128 when the owned process exited before it ran. + if (error.status !== 128) throw error; + } + return; + } + // macOS answers EPERM for a group whose members already exited but are not reaped yet. + try { process.kill(-this.child.pid, "SIGKILL"); } + catch (error) { if (error.code !== "ESRCH" && error.code !== "EPERM") throw error; } + } + + #write(message) { + const body = Buffer.from(JSON.stringify(message), "utf8"); + this.child.stdin.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`, "ascii"), body])); + } + + /** Rejects every waiting request; nothing more will answer them. */ + #fail(reason) { + const error = new Error(`${reason}\nbackend stderr:\n${this.stderr}`); + for (const settle of this.#pending.values()) settle(error); + this.#pending.clear(); + } + + #read(chunk) { + if (this.#buffer.length + chunk.length > MAX_FRAME_BYTES + MAX_HEADER_BYTES) return this.#broken("an oversized input buffer"); + this.#buffer = Buffer.concat([this.#buffer, chunk]); + for (;;) { + const headerEnd = this.#buffer.indexOf("\r\n\r\n"); + if (headerEnd < 0) { + if (this.#buffer.length > MAX_HEADER_BYTES) return this.#broken("an oversized frame header"); + return; + } + if (headerEnd > MAX_HEADER_BYTES) return this.#broken("an oversized frame header"); + const length = Number(/Content-Length: *(\d+)/i.exec(this.#buffer.subarray(0, headerEnd).toString("ascii"))?.[1]); + if (length > MAX_FRAME_BYTES) return this.#broken("an oversized frame"); + if (!Number.isSafeInteger(length)) return this.#broken("a frame without Content-Length"); + if (this.#buffer.length < headerEnd + 4 + length) return; + let message; + try { message = JSON.parse(this.#buffer.subarray(headerEnd + 4, headerEnd + 4 + length).toString("utf8")); } + catch { return this.#broken("a frame that is not JSON"); } + this.#buffer = this.#buffer.subarray(headerEnd + 4 + length); + if (message.method === "lithe/log") { + if (this.diagnostics.length >= MAX_DIAGNOSTICS) return this.#broken("too many diagnostic facts"); + this.diagnostics.push(message.params); + } else if (message.method === "lithe/build/progress") { + if (typeof message.params?.output === "string") this.output = (this.output + message.params.output).slice(-MAX_STDERR_BYTES); + } else if (message.id !== undefined && message.method !== undefined) { + const answer = this.hostRequests[message.method]; + this.#write(answer === undefined + ? { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unsupported" } } + : { jsonrpc: "2.0", id: message.id, result: answer(message.params) }); + } else if (message.id !== undefined && message.method === undefined) { + this.#pending.get(message.id)?.(message); + this.#pending.delete(message.id); + } + } + } + + #broken(what) { + this.#fail(`the backend wrote ${what}`); + this.kill(); + } +} + +export function bounded(promise, description, timeoutMs = WAIT_MS) { + let timer; + return Promise.race([ + promise, + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out waiting for ${description}`)), timeoutMs); }), + ]).finally(() => clearTimeout(timer)); +} diff --git a/scripts/lib/report.mjs b/scripts/lib/report.mjs new file mode 100644 index 0000000..75bfb9b --- /dev/null +++ b/scripts/lib/report.mjs @@ -0,0 +1,48 @@ +// Dependency-free per-step reports for packaging and the Maven integration lane. +import { mkdirSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { performance } from "node:perf_hooks"; + +const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({ + "&": "&", "<": "<", ">": ">", '"': """, "'": "'", +})[char]); + +export function createReport(lane) { + const started = performance.now(); + const tests = []; + const step = async (name, body) => { + const before = performance.now(); + const test = { name, suite: lane, status: "passed", durationMs: 0 }; + tests.push(test); + try { return await body(); } + catch (error) { + test.status = "failed"; + test.details = error.stack ?? String(error); + throw error; + } finally { + test.durationMs = performance.now() - before; + console.log(`${test.status === "passed" ? "✓" : "✗"} ${name} (${test.durationMs.toFixed(1)} ms)`); + } + }; + const write = () => { + const directory = resolve(process.env.LITHE_REPORT_DIR ?? ".artifacts/test-stability"); + mkdirSync(directory, { recursive: true }); + const durationMs = performance.now() - started; + const failures = tests.filter((test) => test.status === "failed").length; + const errors = tests.filter((test) => test.status === "error").length; + const report = { schemaVersion: 1, runner: "node", lane, warnMs: 1_000, maxMs: 610_000, durationMs, tests }; + writeFileSync(join(directory, `${lane}.json`), `${JSON.stringify(report, null, 2)}\n`); + const cases = tests.map((test) => { + const tag = test.status === "error" ? "error" : "failure"; + return ` ${test.details ? `<${tag} message="step failed">${escape(test.details)}` : ""}`; + }); + writeFileSync(join(directory, `${lane}.junit.xml`), `\n\n${cases.join("\n")}\n\n`); + const rows = tests.map((test) => `${escape(test.name)}${test.durationMs.toFixed(1)}${test.status}${test.details ? `
${escape(test.details)}
` : ""}`); + writeFileSync(join(directory, `${lane}.html`), `${escape(lane)}

${escape(lane)}

${tests.length} steps, ${failures} failures, ${errors} errors, ${durationMs.toFixed(1)} ms total

${rows.join("\n")}
StepDuration (ms)Result
\n`); + console.log(`Timing reports: ${join(directory, `${lane}.html`)} (JSON, JUnit alongside)`); + }; + const failure = (name, error) => { + tests.push({ name, suite: lane, status: "error", durationMs: 0, details: error.stack ?? String(error) }); + }; + return { step, write, failure }; +} diff --git a/scripts/package.mjs b/scripts/package.mjs new file mode 100644 index 0000000..c1703e1 --- /dev/null +++ b/scripts/package.mjs @@ -0,0 +1,105 @@ +#!/usr/bin/env node +// Packages the plugin into dist/tomcat--.zip, the asset +// names Lithe Store's release tracker recognizes. +// +// The package is plugin.json, its translations and one jar: the build +// provider in provider/, compiled with javac for Java 8 together with the +// vendored Java plugin SDK. It carries no native code and no Tomcat, so one +// archive serves every platform; the Linux and Windows assets are copies. +// Packaging needs POSIX zip, so it runs on macOS or Linux. The unpacked +// package stays in dist/package/ for installing a development copy. +// +// Usage: node scripts/package.mjs [--expect-tag ] + +import { runCommand, withInterrupts, ZIP_TIMEOUT_MS } from "./process.mjs"; +import { verifySdk } from "./sdk/verify-sdk.mjs"; +import { createReport } from "./lib/report.mjs"; +import { createHash } from "node:crypto"; +import { cpSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const PACKAGE_DIR = "io.github.lithe-idea.tomcat"; +const ASSET_PREFIX = "tomcat"; +const PROVIDER_JAR = "lithe-tomcat-provider.jar"; +const MAIN_CLASS = "io.github.litheidea.tomcat.TomcatProvider"; +const BUILD_TIMEOUT_MS = 120_000; +export const PACKAGE_ROOT = join("dist", "package"); + +const manifest = JSON.parse(readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8")); +const problems = []; +if (manifest.id !== PACKAGE_DIR) problems.push(`plugin.json id ${manifest.id} must equal the directory ${PACKAGE_DIR}`); +if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(manifest.version)) problems.push(`version ${manifest.version} is not MAJOR.MINOR.PATCH`); +if (manifest.vendor?.signatureRequirement !== "none") problems.push('vendor.signatureRequirement must be "none"'); +if (manifest.buildSystems?.[0]?.provider?.launch?.entry !== `lib/${PROVIDER_JAR}`) { + problems.push(`the provider launch entry must be lib/${PROVIDER_JAR}`); +} +const tagFlag = process.argv.indexOf("--expect-tag"); +if (tagFlag >= 0) { + const tag = process.argv[tagFlag + 1]; + if (tag !== `v${manifest.version}`) problems.push(`tag ${tag} does not match plugin.json version ${manifest.version}`); +} +if (problems.length > 0) { + for (const problem of problems) console.error(`✗ ${problem}`); + process.exit(1); +} + +const sha256 = (path) => createHash("sha256").update(readFileSync(path)).digest("hex"); +const sources = (path) => readdirSync(path, { withFileTypes: true }) + .flatMap((entry) => entry.isDirectory() ? sources(join(path, entry.name)) : entry.name.endsWith(".java") ? [join(path, entry.name)] : []) + .sort(); + +/** Lithe refuses packages with symbolic links, so refuse them before zipping. */ +function assertNoLinks(directory) { + for (const name of readdirSync(directory)) { + const path = join(directory, name); + const stat = lstatSync(path); + if (stat.isSymbolicLink()) throw new Error(`${path} is a symbolic link`); + if (stat.isDirectory()) assertNoLinks(path); + } +} + +const report = createReport("package"); +await withInterrupts(async (signal) => { + try { + await report.step("verify the vendored SDK", () => verifySdk()); + await report.step("build the provider jar", async () => { + const build = "provider/target"; + rmSync(build, { recursive: true, force: true }); + mkdirSync(join(build, "classes"), { recursive: true }); + await runCommand("javac", ["--release", "8", "-encoding", "UTF-8", "-Xlint:all,-options", "-Werror", "-d", join(build, "classes"), + ...sources("provider/src/main/java"), ...sources("vendor/lithe-plugin-sdk-java/src/main/java")], { timeoutMs: BUILD_TIMEOUT_MS, signal }); + writeFileSync(join(build, "MANIFEST.MF"), `Main-Class: ${MAIN_CLASS}\nImplementation-Version: ${manifest.version}\n`); + await runCommand("jar", ["--create", "--file", join(build, PROVIDER_JAR), "--manifest", join(build, "MANIFEST.MF"), + "--date", "2026-11-18T00:00:00Z", "-C", join(build, "classes"), "."], { timeoutMs: BUILD_TIMEOUT_MS, signal }); + }); + await report.step("assemble the plugin package", () => { + signal.throwIfAborted(); + rmSync("dist", { recursive: true, force: true }); + const packageRoot = join(PACKAGE_ROOT, PACKAGE_DIR); + cpSync(PACKAGE_DIR, packageRoot, { recursive: true }); + mkdirSync(join(packageRoot, "lib"), { recursive: true }); + cpSync(join("provider/target", PROVIDER_JAR), join(packageRoot, "lib", PROVIDER_JAR)); + cpSync("vendor/LICENSE", join(packageRoot, "SDK-LICENSE")); + cpSync("LICENSE", join(packageRoot, "LICENSE")); + cpSync("NOTICE", join(packageRoot, "NOTICE")); + assertNoLinks(packageRoot); + }); + const asset = resolve("dist", `${ASSET_PREFIX}-${manifest.version}-darwin.zip`); + // -X drops extra file attributes; -y keeps a link a link so Lithe refuses it. + await report.step("archive the plugin package", () => runCommand("zip", ["-qrXy", asset, PACKAGE_DIR, "-x", "*.DS_Store"], { + cwd: PACKAGE_ROOT, timeoutMs: ZIP_TIMEOUT_MS, signal, + })); + console.log(`dist/${ASSET_PREFIX}-${manifest.version}-darwin.zip ${sha256(asset)}`); + for (const platform of ["linux", "windows"]) { + const copy = resolve("dist", `${ASSET_PREFIX}-${manifest.version}-${platform}.zip`); + cpSync(asset, copy); + console.log(`dist/${ASSET_PREFIX}-${manifest.version}-${platform}.zip ${sha256(copy)}`); + } + } catch (error) { + report.failure("packaging failed", error); + console.error(error.stack); + process.exitCode = 1; + } finally { + report.write(); + } +}); diff --git a/scripts/process.mjs b/scripts/process.mjs new file mode 100644 index 0000000..1e024eb --- /dev/null +++ b/scripts/process.mjs @@ -0,0 +1,167 @@ +// Own each command's POSIX process group, including Maven's forked JVMs. +// Async spawn keeps the watchdog and interrupt handlers runnable even when +// the command ignores SIGTERM; execFileSync's timeout cannot guarantee that. +// +// Windows has no process groups and Node cannot start mvn.cmd without a +// shell, so there the command runs under cmd.exe, which resolves `mvn` +// through PATHEXT as Lithe does, and stopping it kills the whole process tree +// with taskkill while the command is still running. +import { spawn } from "node:child_process"; +import { performance } from "node:perf_hooks"; + +export const MAVEN_TIMEOUT_MS = 120_000; +export const ZIP_TIMEOUT_MS = 30_000; +const GRACE_MS = 500; +const KILL_WAIT_MS = 2_000; +const WINDOWS = process.platform === "win32"; + +/** + * The cmd.exe command line for one command. Arguments that cmd.exe or a batch + * file would expand or split are rejected rather than escaped. + */ +export function windowsCommandLine(command, args) { + return [command, ...args].map((arg) => { + if (/["%!\r\n\0]/.test(arg)) throw new Error(`cannot pass ${JSON.stringify(arg)} through cmd.exe`); + if (/^[A-Za-z0-9_\-+=.,:/\\@${}]+$/.test(arg)) return arg; + // Backslashes before the closing quote would escape it for the program. + return `"${arg.replace(/(\\+)$/, "$1$1")}"`; + }).join(" "); +} + +export function mavenTimeout() { + const value = process.env.LITHE_MAVEN_TIMEOUT_MS; + if (value === undefined) return MAVEN_TIMEOUT_MS; + const timeout = Number(value); + if (!/^\d+$/.test(value) || !Number.isSafeInteger(timeout) || timeout < 1 || timeout > 600_000) { + throw new Error("LITHE_MAVEN_TIMEOUT_MS must be an integer from 1 to 600000"); + } + return timeout; +} + +export function runCommand(command, args, { + cwd = process.cwd(), env = process.env, stdio = "inherit", timeoutMs = MAVEN_TIMEOUT_MS, + graceMs = GRACE_MS, killWaitMs = KILL_WAIT_MS, signal, +} = {}) { + for (const [name, value] of Object.entries({ timeoutMs, graceMs, killWaitMs })) { + if (!Number.isSafeInteger(value) || value < 1 || value > 3_600_000) { + throw new Error(`${name} must be an integer from 1 to 3600000`); + } + } + signal?.throwIfAborted(); + const started = performance.now(); + const invocation = [command, ...args].map((arg) => JSON.stringify(arg)).join(" "); + const line = WINDOWS ? windowsCommandLine(command, args) : undefined; + + return new Promise((resolve, reject) => { + const child = WINDOWS + ? spawn(process.env.ComSpec ?? "cmd.exe", ["/d", "/v:off", "/s", "/c", `"${line}"`], { + cwd, env, stdio, windowsHide: true, windowsVerbatimArguments: true, + }) + : spawn(command, args, { cwd, env, stdio, detached: true, shell: false }); + let closed = false; + let code; + let exitSignal; + let failure; + let stopping = false; + let settled = false; + let graceTimer; + let killTimer; + let pollTimer; + + const diagnostic = (message) => new Error( + `${message} after ${Math.round(performance.now() - started)} ms\ncommand: ${invocation}\ncwd: ${cwd}`, + ); + let killing; + const groupExists = () => { + // Windows cannot find a tree once its root has exited; send() kills it before. + if (WINDOWS || !child.pid) return false; + try { process.kill(-child.pid, 0); return true; } + catch (error) { if (error.code === "ESRCH") return false; throw error; } + }; + const send = (value) => { + if (!child.pid) return; + if (WINDOWS) { + if (child.exitCode !== null || child.signalCode !== null || killing) return; + killing = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }); + killing.once("error", (error) => { failure ??= diagnostic(`cannot run taskkill: ${error.message}`); }); + killing.once("exit", () => { killing = undefined; }); + return; + } + try { process.kill(-child.pid, value); } + catch (error) { if (error.code !== "ESRCH") failure ??= diagnostic(`cannot send ${value}: ${error.message}`); } + }; + const finish = () => { + if (settled) return; + settled = true; + clearTimeout(timeoutTimer); + clearTimeout(graceTimer); + clearTimeout(killTimer); + clearTimeout(pollTimer); + signal?.removeEventListener("abort", onAbort); + if (failure) reject(failure); + else if (code !== 0) reject(diagnostic(`command exited with ${exitSignal ? `signal ${exitSignal}` : `status ${code}`}`)); + else resolve(); + }; + // Poll only the owned OS process group, with the cleanup deadline below. + const inspect = () => { + try { + if (closed && !groupExists()) return finish(); + } catch (error) { failure ??= diagnostic(`cannot inspect process group: ${error.message}`); } + pollTimer = setTimeout(inspect, 20); + }; + const stop = () => { + if (stopping) return; + stopping = true; + clearTimeout(timeoutTimer); + send("SIGTERM"); + graceTimer = setTimeout(() => send("SIGKILL"), graceMs); + killTimer = setTimeout(() => { + send("SIGKILL"); + const cleanup = diagnostic("process group did not disappear before the cleanup deadline"); + failure = failure ? new Error(`${failure.message}\ncleanup: ${cleanup.message}`, { cause: failure }) : cleanup; + // A descendant may keep a pipe open after its parent has exited. + for (const stream of child.stdio) stream?.destroy?.(); + child.unref(); + finish(); + }, graceMs + killWaitMs); + inspect(); + }; + const onAbort = () => { + failure ??= diagnostic(`command cancelled: ${signal.reason?.message ?? signal.reason ?? "abort"}`); + stop(); + }; + const timeoutTimer = setTimeout(() => { + failure ??= diagnostic(`command timed out (limit ${timeoutMs} ms)`); + stop(); + }, timeoutMs); + child.once("error", (error) => { + failure ??= diagnostic(`cannot run command: ${error.message}`); + stop(); + }); + child.once("exit", (status, value) => { + code = status; + exitSignal = value; + stop(); + }); + child.once("close", () => { closed = true; stop(); }); + signal?.addEventListener("abort", onAbort, { once: true }); + if (signal?.aborted) onAbort(); + }); +} + +// Keep handlers installed through scratch cleanup and report writing. A repeated +// interrupt still follows the same bounded escalation instead of orphaning JVMs. +export async function withInterrupts(body) { + const controller = new AbortController(); + let interrupted; + const handlers = new Map(["SIGINT", "SIGTERM"].map((name) => [name, () => { + interrupted ??= name; + controller.abort(new Error(name)); + }])); + for (const [name, handler] of handlers) process.on(name, handler); + try { await body(controller.signal); } + finally { + for (const [name, handler] of handlers) process.off(name, handler); + if (interrupted) process.exitCode = interrupted === "SIGINT" ? 130 : 143; + } +} diff --git a/scripts/sdk/verify-sdk.mjs b/scripts/sdk/verify-sdk.mjs new file mode 100644 index 0000000..78028b8 --- /dev/null +++ b/scripts/sdk/verify-sdk.mjs @@ -0,0 +1,42 @@ +import { createHash } from 'node:crypto'; +import { lstat, readFile, readdir } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const repository = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); + +/** Verify every vendored production source before building the backend. */ +export async function verifySdk(root = repository) { + const lock = JSON.parse(await readFile(join(root, 'sdk.lock.json'), 'utf8')); + if (lock.schemaVersion !== 1 || !/^[0-9a-f]{40}$/.test(lock.source?.revision) || !Array.isArray(lock.files) || lock.source.repository !== 'https://github.com/Lithe-IDEA/Lithe-core-rust') { + throw new Error('The SDK lock must identify its upstream base and every source hash.'); + } + const expected = new Set(); + for (const entry of lock.files) { + if (!entry.path?.startsWith('vendor/') || entry.path.includes('\\') + || entry.path.split('/').some((part) => !part || part === '.' || part === '..') + || !/^[0-9a-f]{64}$/.test(entry.sha256) || expected.has(entry.path) + || Object.hasOwn(entry, 'localChanges') || !entry.upstream?.startsWith('shared/plugins/')) { + throw new Error('Invalid or duplicate SDK source lock entry.'); + } + const file = join(root, entry.path); + if (!(await lstat(file)).isFile()) throw new Error(`SDK input is not a regular file: ${entry.path}`); + const digest = createHash('sha256').update(await readFile(file)).digest('hex'); + if (digest !== entry.sha256) throw new Error(`SDK SHA-256 mismatch: ${entry.path}`); + expected.add(entry.path); + } + async function walk(directory, prefix) { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const name = `${prefix}/${entry.name}`; + if (entry.isDirectory()) await walk(join(directory, entry.name), name); + else if (!expected.delete(name)) throw new Error(`Unpinned SDK input: ${name}`); + } + } + await walk(join(root, 'vendor'), 'vendor'); + if (expected.size) throw new Error('A pinned SDK source is missing.'); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await verifySdk(); + console.log('Vendored Java SDK source hashes verified.'); +} diff --git a/scripts/test.mjs b/scripts/test.mjs new file mode 100644 index 0000000..8c7043b --- /dev/null +++ b/scripts/test.mjs @@ -0,0 +1,404 @@ +#!/usr/bin/env node +// End-to-end test of the packaged plugin against real Tomcat installations. +// +// For each Tomcat home it starts the packaged build provider the way Lithe +// does, asks it for the model of every fixture instance, prepares a run of +// each Web module, starts the returned launch plan with `java` (as Lithe +// starts it with the project's JDK) and reads the page over HTTP. It also +// checks the debug launch (a JDWP handshake on the host's port), the +// errors a user can meet, that an edited JSP is served without a new +// deployment, and that neither the plugin package nor the Tomcat +// installation changed. +// +// Inputs: +// dist/package/ built by scripts/package.mjs +// LITHE_TEST_TOMCAT_HOMES Tomcat homes separated by the path delimiter; +// default: every .artifacts/tomcat/apache-tomcat-* +// GRADLE_HOME or gradle on PATH; default: .artifacts/gradle/gradle-* +// +// Every wait is bounded and every process the test starts is stopped in a +// finally block, also after a failure. + +import { BackendClient, bounded } from "./lib/backend-client.mjs"; +import { createReport } from "./lib/report.mjs"; +import { withInterrupts } from "./process.mjs"; +import assert from "node:assert/strict"; +import { execFileSync, spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import http from "node:http"; +import net from "node:net"; +import { delimiter, join, relative, resolve } from "node:path"; + +const PACKAGE_DIR = "io.github.lithe-idea.tomcat"; +const pluginDir = resolve("dist", "package", PACKAGE_DIR); +const providerJar = join(pluginDir, "lib", "lithe-tomcat-provider.jar"); +const BUILD_MS = 300_000; +const START_MS = 60_000; +const STOP_MS = 10_000; +const WINDOWS = process.platform === "win32"; + +if (!existsSync(providerJar)) { + console.error("✗ dist/package is missing; run node scripts/package.mjs first"); + process.exit(1); +} + +const homes = (process.env.LITHE_TEST_TOMCAT_HOMES + ? process.env.LITHE_TEST_TOMCAT_HOMES.split(delimiter) + : readdirSync(".artifacts/tomcat", { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && entry.name.startsWith("apache-tomcat-")) + .map((entry) => join(".artifacts/tomcat", entry.name))) + .filter(Boolean).map((home) => resolve(home)); +if (homes.length === 0) { + console.error("✗ no Tomcat installation: set LITHE_TEST_TOMCAT_HOMES or unpack one under .artifacts/tomcat"); + process.exit(1); +} + +function gradleHome() { + if (process.env.GRADLE_HOME) return process.env.GRADLE_HOME; + if (existsSync(".artifacts/gradle")) { + const local = readdirSync(".artifacts/gradle").find((name) => /^gradle-[0-9.]+$/.test(name)); + if (local) return resolve(".artifacts/gradle", local); + } + return undefined; +} + +const gradle = gradleHome(); +// Builds use their own Gradle user home, so the test neither reads nor leaves +// daemons in the user's ~/.gradle; stopGradle() ends the daemons it started. +const gradleEnvironment = { + GRADLE_USER_HOME: resolve(".artifacts", "test-work", "gradle-user-home"), + ...(gradle ? { GRADLE_HOME: gradle } : {}), +}; + +function stopGradle() { + const command = gradle ? join(gradle, "bin", WINDOWS ? "gradle.bat" : "gradle") : WINDOWS ? "gradle.bat" : "gradle"; + try { + execFileSync(WINDOWS ? process.env.ComSpec ?? "cmd.exe" : command, WINDOWS ? ["/d", "/c", command, "--stop", "-q"] : ["--stop", "-q"], { + env: { ...process.env, ...gradleEnvironment }, timeout: 60_000, stdio: "inherit", windowsHide: true, + }); + } catch (error) { + console.error(`cannot stop the test's Gradle daemons: ${error.message}`); + failed = true; + } +} + +const report = createReport("tomcat"); +let failed = false; +const check = async (name, body) => { + try { + await report.step(name, body); + } catch (error) { + failed = true; + console.error(error.stack); + } +}; + +/** A content hash of every file under `directory`, to prove nothing wrote there. */ +function treeHash(directory) { + const hash = createHash("sha256"); + const walk = (path) => { + for (const entry of readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { + const child = join(path, entry.name); + hash.update(relative(directory, child)); + if (entry.isDirectory()) walk(child); + else hash.update(readFileSync(child)); + } + }; + walk(directory); + return hash.digest("hex"); +} + +function freePort() { + return new Promise((resolvePort, reject) => { + const server = net.createServer(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const { port } = server.address(); + server.close(() => resolvePort(port)); + }); + }); +} + +function get(url) { + return new Promise((resolveBody, reject) => { + const request = http.get(url, (response) => { + let body = ""; + response.setEncoding("utf8"); + response.on("data", (chunk) => { body += chunk; }); + response.on("end", () => resolveBody({ status: response.statusCode, body })); + }); + request.setTimeout(5_000, () => request.destroy(new Error(`GET ${url} timed out`))); + request.once("error", reject); + }); +} + +/** Polls `probe` until it returns a value, for at most `timeoutMs`. */ +async function waitFor(description, timeoutMs, probe) { + const deadline = Date.now() + timeoutMs; + let last; + while (Date.now() < deadline) { + try { + const value = await probe(); + if (value !== undefined) return value; + } catch (error) { + last = error; + } + await new Promise((done) => setTimeout(done, 250)); + } + throw new Error(`timed out after ${timeoutMs} ms waiting for ${description}${last ? `: ${last.message}` : ""}`); +} + +/** The JDWP handshake: the debuggee answers the same 14 bytes. */ +function jdwpHandshake(port) { + return new Promise((resolveReply, reject) => { + const socket = net.connect(port, "127.0.0.1"); + let reply = ""; + socket.setTimeout(5_000, () => socket.destroy(new Error("JDWP handshake timed out"))); + socket.once("connect", () => socket.write("JDWP-Handshake")); + socket.on("data", (chunk) => { + reply += chunk.toString("latin1"); + if (reply.length >= 14) { + socket.destroy(); + resolveReply(reply.slice(0, 14)); + } + }); + socket.once("error", reject); + }); +} + +/** Starts a launch plan the way Lithe does and owns the process until `stop`. */ +class Server { + output = ""; + + constructor(workspace, plan) { + assert.deepEqual(plan.executable, { kind: "toolchain", value: "java" }); + this.child = spawn("java", plan.arguments, { + cwd: join(workspace, plan.workingDirectory), env: { ...process.env, ...plan.environment }, + stdio: ["ignore", "pipe", "pipe"], detached: !WINDOWS, windowsHide: true, + }); + const keep = (chunk) => { this.output = (this.output + chunk.toString("utf8")).slice(-64 * 1024); }; + this.child.stdout.on("data", keep); + this.child.stderr.on("data", keep); + this.exited = new Promise((done) => this.child.once("exit", done)); + } + + async stop() { + if (this.child.exitCode !== null || this.child.signalCode !== null || !this.child.pid) return; + if (WINDOWS) { + try { execFileSync("taskkill.exe", ["/PID", String(this.child.pid), "/T", "/F"], { timeout: STOP_MS, stdio: "ignore" }); } + catch (error) { if (error.status !== 128) throw error; } + } else { + try { process.kill(-this.child.pid, "SIGTERM"); } catch (error) { if (error.code !== "ESRCH") throw error; } + const stopped = await Promise.race([this.exited.then(() => true), new Promise((done) => setTimeout(() => done(false), STOP_MS))]); + if (!stopped) { + try { process.kill(-this.child.pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") throw error; } + } + } + await bounded(this.exited, "Tomcat to exit", STOP_MS); + } +} + +async function suite(home, signal) { + const version = /apache-tomcat-([0-9.]+)/.exec(home)?.[1] ?? "custom"; + const work = resolve(".artifacts", "test-work", version); + rmSync(work, { recursive: true, force: true }); + const workspace = join(work, "workspace"); + const state = join(work, "state"); + mkdirSync(state, { recursive: true }); + cpSync("test/fixtures/workspace", workspace, { recursive: true }); + // The Java plugin compiles an Eclipse project into its output folder; do it here. + mkdirSync(join(workspace, "wtp", "build", "classes"), { recursive: true }); + execFileSync("javac", ["-source", "8", "-target", "8", "-nowarn", "-d", join(workspace, "wtp", "build", "classes"), + join(workspace, "wtp", "src", "demo", "wtp", "Message.java")], { timeout: 60_000 }); + + const homeBefore = treeHash(home); + const port = await freePort(); + const environment = { ...process.env, ...gradleEnvironment }; + delete environment.CATALINA_HOME; + delete environment.CATALINA_BASE; + const client = new BackendClient({ jar: providerJar, state, env: environment, timeoutMs: BUILD_MS }); + const servers = []; + let operation = 0; + const prepare = (root, project, target, launchOptions = {}) => client.request("lithe/build/prepareRun", { + operationID: `run-${++operation}`, buildSystemID: "tomcat", root, options: {}, optionArguments: [], environment: {}, + run: "tomcat", project: { name: target.name, path: project }, target, userArguments: [], + launchOptions: { execution: "service", runtimeArguments: [], arguments: [], environment: {}, ...launchOptions }, + }); + const serve = async (plan) => { + const server = new Server(workspace, plan); + servers.push(server); + return server; + }; + const page = (server, path) => waitFor(`http://127.0.0.1:${port}${path}`, START_MS, async () => { + if (server.child.exitCode !== null) throw new Error(`Tomcat exited with ${server.child.exitCode}:\n${server.output}`); + const response = await get(`http://127.0.0.1:${port}${path}`); + return response.status === 200 ? response.body.trim() : undefined; + }).catch((error) => { throw new Error(`${error.message}\nTomcat output:\n${server.output}`); }); + + try { + signal.throwIfAborted(); + await report.step(`[${version}] start the build provider`, () => client.initialize(workspace, { + initializationOptions: { tomcatHome: home, httpPort: port }, locale: "en", + })); + const models = {}; + for (const root of ["maven", "wtp", "plain/web/WEB-INF", "gradle-app"]) { + models[root] = await report.step(`[${version}] model of ${root}`, () => client.request("lithe/build/model", { + buildSystemID: "tomcat", root, options: {}, optionArguments: [], environment: {}, + })); + } + const target = (root) => models[root].targets[0]; + await check(`[${version}] the model lists each Web module and nothing else`, () => { + const summary = Object.fromEntries(Object.entries(models).map(([root, model]) => [root, + model.targets.map(({ project, name, tags, properties }) => ({ project, name, tags, ...properties }))])); + assert.deepEqual(summary, { + maven: [{ project: "web", name: "shop", tags: ["web-application"], kind: "maven", contextPath: "/shop" }], + wtp: [{ project: ".", name: "wtp-demo", tags: ["web-application"], kind: "eclipse", contextPath: "/eclipse/demo", webRoot: "WebContent" }], + "plain/web/WEB-INF": [{ project: ".", name: "plain", tags: ["web-application"], kind: "plain", contextPath: "/plain", webRoot: ".." }], + "gradle-app": [{ project: ".", name: "gradle-app", tags: ["web-application"], kind: "gradle", contextPath: "/gradle-app" }], + }); + assert.deepEqual(models.maven.projects.map((project) => project.path), ["web"], "the jar modules are not Web modules"); + }); + await check(`[${version}] an unreadable build file is reported once as a degraded model, and model successes stay quiet`, () => { + const model = client.diagnostics.filter((fact) => fact.operation === "lithe/build/model"); + assert.deepEqual(model.filter((fact) => fact.kind === "degraded").map(({ code, count }) => ({ code, count })), + [{ code: "buildFileUnreadable", count: 1 }], JSON.stringify(model)); + assert.equal(model.filter((fact) => fact.kind === "operationFinished").length, 0, "model reads are routine"); + }); + + const maven = await report.step(`[${version}] prepare the Maven war module`, () => prepare("maven", "maven/web", target("maven"))); + await check(`[${version}] the Maven module builds with its reactor and serves the exploded WAR`, async () => { + assert.equal(maven.workingDirectory, "maven/web"); + assert.ok(maven.arguments.includes("org.apache.catalina.startup.Bootstrap")); + assert.match(maven.environment.JDK_JAVA_OPTIONS, /--add-opens=java.base\/java.lang=ALL-UNNAMED/); + const base = maven.arguments.find((argument) => argument.startsWith("-Dcatalina.base=")).slice("-Dcatalina.base=".length); + assert.ok(base.startsWith(state), "CATALINA_BASE lives in the workspace state directory"); + const context = readFileSync(join(base, "conf", "Catalina", "localhost", "shop.xml"), "utf8"); + assert.ok(context.includes(join(workspace, "maven", "web", "target", "shop-1.0")), context); + const server = await serve(maven); + assert.equal(await page(server, "/shop/"), "Hello from the Maven reactor"); + await server.stop(); + assert.match(server.output, /Server startup in/, "Tomcat logs to the console Lithe shows"); + assert.ok(!existsSync(join(base, "logs")) || readdirSync(join(base, "logs")).length === 0, "Tomcat writes no log files into the state"); + }); + + const wtp = await report.step(`[${version}] prepare the Eclipse Dynamic Web Project`, () => prepare("wtp", "wtp", target("wtp"))); + await check(`[${version}] the Eclipse project is served in place with its output folder, and a JSP edit needs no deployment`, async () => { + const server = await serve(wtp); + assert.equal(await page(server, "/eclipse/demo/"), "Hello from the Eclipse output folder"); + writeFileSync(join(workspace, "wtp", "WebContent", "index.jsp"), + '<%@ page contentType="text/plain; charset=UTF-8" %>edited <%= demo.wtp.Message.text() %>\n'); + await waitFor("the edited JSP", 30_000, async () => { + const response = await get(`http://127.0.0.1:${port}/eclipse/demo/`); + return response.body.trim().startsWith("edited ") ? true : undefined; + }); + await server.stop(); + }); + + const plain = await report.step(`[${version}] prepare the plain Web folder`, () => prepare("plain/web/WEB-INF", "plain/web/WEB-INF", target("plain/web/WEB-INF"))); + await check(`[${version}] a plain Web folder found by its web.xml is served in place`, async () => { + assert.equal(plain.workingDirectory, "plain/web/WEB-INF"); + const server = await serve(plain); + assert.equal(await page(server, "/plain/"), "Hello from a plain Web folder"); + await server.stop(); + }); + + await check(`[${version}] the Gradle war module builds with the war task and serves the WAR`, async () => { + const plan = await prepare("gradle-app", "gradle-app", target("gradle-app")); + const server = await serve(plan); + assert.equal(await page(server, "/gradle-app/"), "Hello from a Gradle WAR"); + await server.stop(); + }); + + await check(`[${version}] a debug run suspends Tomcat until a debugger attaches on the host's port`, async () => { + const debugPort = await freePort(); + const plan = await prepare("wtp", "wtp", target("wtp"), { + debug: { adapterID: "dev.example/java", configurationType: "java", target: { kind: "connection", host: "127.0.0.1", port: debugPort } }, + }); + const agent = plan.arguments.findIndex((argument) => argument.startsWith("-agentlib:jdwp=")); + assert.equal(plan.arguments[agent], `-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:${debugPort}`); + assert.ok(agent < plan.arguments.indexOf("org.apache.catalina.startup.Bootstrap")); + const server = await serve(plan); + const reply = await waitFor("the JDWP listener", START_MS, () => jdwpHandshake(debugPort)); + assert.equal(reply, "JDWP-Handshake"); + await assert.rejects(get(`http://127.0.0.1:${port}/eclipse/demo/`), "a suspended Tomcat serves nothing"); + await server.stop(); + }); + + await check(`[${version}] a busy HTTP port fails before anything is built`, async () => { + const blocker = net.createServer(); + await new Promise((done) => blocker.listen(port, "127.0.0.1", done)); + try { + await assert.rejects(prepare("maven", "maven/web", target("maven")), (error) => { + assert.match(error.message, new RegExp(`HTTP port ${port} is in use`)); + return true; + }); + } finally { + await new Promise((done) => blocker.close(done)); + } + }); + + await check(`[${version}] program arguments and stale targets are refused`, async () => { + await assert.rejects(prepare("wtp", "wtp", target("wtp"), { arguments: ["--debug"] }), /takes no program arguments/); + await assert.rejects(prepare("maven", "maven/library", { ...target("maven"), name: "library" }), /no longer a Web module/); + }); + + await check(`[${version}] each run preparation ends with exactly one terminal log fact`, () => { + const facts = client.diagnostics.filter((fact) => fact.operation === "lithe/build/prepareRun" + && (fact.kind === "operationFinished" || fact.kind === "operationFailed")); + assert.equal(facts.length, operation, JSON.stringify(facts)); + assert.deepEqual([...new Set(facts.filter((fact) => fact.kind === "operationFailed").map((fact) => fact.code))].sort(), + ["tomcat.run.notWebModule", "tomcat.run.portInUse", "tomcat.run.unsupportedArguments"]); + for (const fact of client.diagnostics) { + assert.ok(!JSON.stringify(fact).includes(workspace), "log facts carry no paths"); + } + }); + + await check(`[${version}] the provider stops cleanly`, async () => assert.equal(await client.close(), 0)); + } finally { + for (const server of servers) await server.stop().catch((error) => console.error(error.stack)); + client.kill(); + } + await check(`[${version}] the Tomcat installation is unchanged`, () => assert.equal(treeHash(home), homeBefore)); +} + +async function missingHome() { + const workspace = resolve(".artifacts", "test-work", "no-home"); + rmSync(workspace, { recursive: true, force: true }); + cpSync("test/fixtures/workspace/plain", workspace, { recursive: true }); + const environment = { ...process.env }; + delete environment.CATALINA_HOME; + const client = new BackendClient({ jar: providerJar, state: join(workspace, ".state"), env: environment }); + try { + await client.initialize(workspace, { initializationOptions: { tomcatHome: "", httpPort: 8080 }, locale: "zh-Hans" }); + const model = await client.request("lithe/build/model", { buildSystemID: "tomcat", root: "web/WEB-INF", options: {}, optionArguments: [], environment: {} }); + await assert.rejects(client.request("lithe/build/prepareRun", { + operationID: "run-1", buildSystemID: "tomcat", root: "web/WEB-INF", options: {}, optionArguments: [], environment: {}, + run: "tomcat", project: { name: "plain", path: "web/WEB-INF" }, target: model.targets[0], userArguments: [], + launchOptions: { execution: "service", runtimeArguments: [], arguments: [], environment: {} }, + }), /没有设置 Tomcat/); + assert.equal(await client.close(), 0); + } finally { + client.kill(); + } +} + +const packageBefore = treeHash(pluginDir); +await withInterrupts(async (signal) => { + try { + for (const home of homes) { + assert.ok(statSync(join(home, "bin", "bootstrap.jar")).isFile(), `${home} is not a Tomcat installation`); + await suite(home, signal); + } + await check("without a Tomcat home the run fails with the localized setup message", missingHome); + await check("the plugin package is unchanged", () => assert.equal(treeHash(pluginDir), packageBefore)); + } catch (error) { + failed = true; + report.failure("test lane failed", error); + console.error(error.stack); + } finally { + stopGradle(); + report.write(); + } +}); +if (failed) process.exitCode = 1; diff --git a/scripts/test/fetch-java-plugin.mjs b/scripts/test/fetch-java-plugin.mjs new file mode 100644 index 0000000..d9c484c --- /dev/null +++ b/scripts/test/fetch-java-plugin.mjs @@ -0,0 +1,72 @@ +#!/usr/bin/env node +// Downloads the test inputs test/java-plugin.json pins for the host end-to-end +// tests, checking each against its pinned SHA-256, and prints a path: +// +// node scripts/test/fetch-java-plugin.mjs [-] +// The Java Support package for this machine (or the named target), in +// .artifacts/java-plugin/. Its java tool launches Tomcat and its java +// adapter debugs it. +// node scripts/test/fetch-java-plugin.mjs --jdtls +// The Eclipse JDT Language Server Java Support runs, unpacked into +// .artifacts/jdtls//, for JDTLS_HOME. Java Support does not carry +// it; a user installs it. +// +// A download already present and matching is kept. These are test inputs only; +// this plugin never carries them. + +import { runCommand, withInterrupts } from "../process.mjs"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { basename, join, resolve } from "node:path"; + +const FETCH_TIMEOUT_MS = 300_000; +const pin = JSON.parse(readFileSync("test/java-plugin.json", "utf8")); +const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex"); + +/** Downloads url to file unless file already has the pinned digest. */ +async function download(url, digest, file, what, signal) { + if (existsSync(file) && sha256(readFileSync(file)) === digest) { + console.error(`✓ ${what} is already downloaded`); + return; + } + const timeout = AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]); + const response = await fetch(url, { signal: timeout }); + if (!response.ok) throw new Error(`GET ${url} answered ${response.status}`); + const bytes = Buffer.from(await response.arrayBuffer()); + const actual = sha256(bytes); + if (actual !== digest) throw new Error(`SHA-256 mismatch for ${what}: ${actual}`); + writeFileSync(`${file}.partial`, bytes); + renameSync(`${file}.partial`, file); + console.error(`✓ ${what} downloaded and verified`); +} + +await withInterrupts(async (signal) => { + if (process.argv[2] === "--jdtls") { + const { version, url, sha256: digest } = pin.jdtls; + const directory = resolve(".artifacts", "jdtls"); + const home = join(directory, version); + mkdirSync(directory, { recursive: true }); + if (!existsSync(join(home, "plugins"))) { + const archive = join(directory, basename(new URL(url).pathname)); + await download(url, digest, archive, `Eclipse JDT LS ${version}`, signal); + const partial = join(directory, `.unpack-${version}`); + rmSync(partial, { recursive: true, force: true }); + mkdirSync(partial); + await runCommand("tar", ["-xzf", archive, "-C", partial], { timeoutMs: FETCH_TIMEOUT_MS, signal }); + rmSync(home, { recursive: true, force: true }); + renameSync(partial, home); + } + console.log(home); + return; + } + const target = process.argv[2] ?? `${process.platform}-${process.arch}`; + const entry = pin.archives[target]; + if (!entry) { + throw new Error(`test/java-plugin.json pins no Java Support archive for ${target}; pinned: ${Object.keys(pin.archives).join(", ")}`); + } + const directory = resolve(".artifacts", "java-plugin"); + mkdirSync(directory, { recursive: true }); + const archive = join(directory, basename(new URL(entry.url).pathname)); + await download(entry.url, entry.sha256, archive, `Java Support ${pin.version} (${target})`, signal); + console.log(archive); +}); diff --git a/scripts/test/fetch-tomcat.mjs b/scripts/test/fetch-tomcat.mjs new file mode 100644 index 0000000..dd7e0f6 --- /dev/null +++ b/scripts/test/fetch-tomcat.mjs @@ -0,0 +1,43 @@ +#!/usr/bin/env node +// Downloads the Tomcat versions test/tomcat-versions.json pins into +// .artifacts/tomcat/apache-tomcat-/, checking each archive against +// its pinned SHA-512 before unpacking. A version already unpacked is kept. +// The downloads are test inputs only; the plugin package never carries Tomcat. +// +// Usage: node scripts/test/fetch-tomcat.mjs + +import { runCommand, withInterrupts } from "../process.mjs"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; + +const FETCH_TIMEOUT_MS = 180_000; +const directory = resolve(".artifacts", "tomcat"); +const { versions } = JSON.parse(readFileSync("test/tomcat-versions.json", "utf8")); +mkdirSync(directory, { recursive: true }); + +await withInterrupts(async (signal) => { + for (const { version, url, sha512 } of versions) { + const home = join(directory, `apache-tomcat-${version}`); + if (existsSync(join(home, "bin", "bootstrap.jar"))) { + console.log(`✓ Tomcat ${version} is already unpacked`); + continue; + } + const archive = join(directory, `apache-tomcat-${version}.tar.gz`); + const timeout = AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]); + const response = await fetch(url, { signal: timeout }); + if (!response.ok) throw new Error(`GET ${url} answered ${response.status}`); + const bytes = Buffer.from(await response.arrayBuffer()); + const digest = createHash("sha512").update(bytes).digest("hex"); + if (digest !== sha512) throw new Error(`SHA-512 mismatch for Tomcat ${version}: ${digest}`); + writeFileSync(archive, bytes); + const partial = join(directory, `.unpack-${version}`); + rmSync(partial, { recursive: true, force: true }); + mkdirSync(partial); + await runCommand("tar", ["-xzf", archive, "-C", partial], { timeoutMs: FETCH_TIMEOUT_MS, signal }); + rmSync(home, { recursive: true, force: true }); + renameSync(join(partial, `apache-tomcat-${version}`), home); + rmSync(partial, { recursive: true, force: true }); + console.log(`✓ Tomcat ${version} downloaded, verified and unpacked`); + } +}); diff --git a/sdk.lock.json b/sdk.lock.json new file mode 100644 index 0000000..8a55736 --- /dev/null +++ b/sdk.lock.json @@ -0,0 +1,89 @@ +{ + "schemaVersion": 1, + "source": { + "repository": "https://github.com/Lithe-IDEA/Lithe-core-rust", + "revision": "8b91b324f0e8140cb6ca3fed3dc26fa0b59a788c" + }, + "files": [ + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java", + "sha256": "a5f7ea6bc0cf5e78e663203d7cc65fb2522ebcf99462c24ebf0f6422bcb6d16c" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java", + "sha256": "eb25a8b572de751411eab4380d044907b8fe40acf33889fa759e3b6be325ef45" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java", + "sha256": "826c246360a607eb40ce950202db0988a465718082dc22be539f045139671db3" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java", + "sha256": "699c054b1857a0518fd244ff193bc87445495ae40cbf7cc34436ac92ba42973e" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java", + "sha256": "a1e6fa4b743c0702a4b7f462cbad9539da32a523e51d8bf8a6a054bec82d14df" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Framing.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java", + "sha256": "510a82f0c29e634d4235326ed9abccc2c618f795e9aca6c354d516c7dce278db" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java", + "sha256": "974c51e84638f5e708cab471100d9cfcc7f7ff9af568f309c8285bd4c5e9455d" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java", + "sha256": "7c3e15d5ea79f17374371cc32c4b983f1274289cc0741870f6cccc9c55ff5553" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java", + "sha256": "fc24c7ede0363c32c11b4bea6b879401524267b90f2db9930fda1338b32e4bf3" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Json.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java", + "sha256": "7ff4a54ab5003cd86046db3b35110b4906b97fc56b8d934f33e6f51eb96dd5ed" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java", + "sha256": "882485659c7e77833ebb383dd8175b7eede292596696f63678fbcd868c029806" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java", + "sha256": "ced28c084e0f0d1d5c42d29d1c85b6528e065b9a933f7a6ab0a4eae1bcd6a520" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Processes.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java", + "sha256": "a8ab4b1e5dc2d4eac2cbe90eb302517cab6f0283c210f8c64f2e01edaceb318d" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java", + "sha256": "c84c26121c2997826269c5503dbd11cf437acfa13c2ab3c4f2ea29652a096712" + }, + { + "upstream": "shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java", + "path": "vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java", + "sha256": "c56519730a9243d5ce9e8333025456bd934890bd7ad134de3b8e8fb9fd28bfe4" + }, + { + "upstream": "shared/plugins/LICENSE", + "path": "vendor/LICENSE", + "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" + } + ] +} diff --git a/test/fixtures/workspace/gradle-app/build.gradle b/test/fixtures/workspace/gradle-app/build.gradle new file mode 100644 index 0000000..a29da3b --- /dev/null +++ b/test/fixtures/workspace/gradle-app/build.gradle @@ -0,0 +1,4 @@ +plugins { + // id 'java' alone would not make this a Web module; the war plugin does. + id 'war' +} diff --git a/test/fixtures/workspace/gradle-app/settings.gradle b/test/fixtures/workspace/gradle-app/settings.gradle new file mode 100644 index 0000000..cfd4d7e --- /dev/null +++ b/test/fixtures/workspace/gradle-app/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'gradle-app' diff --git a/test/fixtures/workspace/gradle-app/src/main/webapp/index.html b/test/fixtures/workspace/gradle-app/src/main/webapp/index.html new file mode 100644 index 0000000..8653a3b --- /dev/null +++ b/test/fixtures/workspace/gradle-app/src/main/webapp/index.html @@ -0,0 +1 @@ +Hello from a Gradle WAR diff --git a/test/fixtures/workspace/maven/broken/pom.xml b/test/fixtures/workspace/maven/broken/pom.xml new file mode 100644 index 0000000..8b5ad73 --- /dev/null +++ b/test/fixtures/workspace/maven/broken/pom.xml @@ -0,0 +1,2 @@ + + broken diff --git a/test/fixtures/workspace/maven/core/pom.xml b/test/fixtures/workspace/maven/core/pom.xml new file mode 100644 index 0000000..00a7f82 --- /dev/null +++ b/test/fixtures/workspace/maven/core/pom.xml @@ -0,0 +1,6 @@ + + + 4.0.0 + demoreactor1.0 + core + diff --git a/test/fixtures/workspace/maven/core/src/main/java/demo/core/Greeter.java b/test/fixtures/workspace/maven/core/src/main/java/demo/core/Greeter.java new file mode 100644 index 0000000..b175aa7 --- /dev/null +++ b/test/fixtures/workspace/maven/core/src/main/java/demo/core/Greeter.java @@ -0,0 +1,7 @@ +package demo.core; + +public final class Greeter { + public static String greet() { + return "Hello from the Maven reactor"; + } +} diff --git a/test/fixtures/workspace/maven/library/pom.xml b/test/fixtures/workspace/maven/library/pom.xml new file mode 100644 index 0000000..201984e --- /dev/null +++ b/test/fixtures/workspace/maven/library/pom.xml @@ -0,0 +1,6 @@ + + + 4.0.0 + demoreactor1.0 + library + diff --git a/test/fixtures/workspace/maven/library/src/main/java/demo/library/Library.java b/test/fixtures/workspace/maven/library/src/main/java/demo/library/Library.java new file mode 100644 index 0000000..625aad1 --- /dev/null +++ b/test/fixtures/workspace/maven/library/src/main/java/demo/library/Library.java @@ -0,0 +1,5 @@ +package demo.library; + +/** A jar module: not a Web module, so the Tomcat model leaves it out. */ +public final class Library { +} diff --git a/test/fixtures/workspace/maven/pom.xml b/test/fixtures/workspace/maven/pom.xml new file mode 100644 index 0000000..d6e7766 --- /dev/null +++ b/test/fixtures/workspace/maven/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + demo + reactor + 1.0 + pom + + core + web + library + + + UTF-8 + 1.8 + 1.8 + + + + + maven-compiler-plugin3.13.0 + maven-jar-plugin3.4.2 + maven-war-plugin3.4.0 + maven-resources-plugin3.3.1 + maven-surefire-plugin3.5.2 + + + + diff --git a/test/fixtures/workspace/maven/web/pom.xml b/test/fixtures/workspace/maven/web/pom.xml new file mode 100644 index 0000000..316938d --- /dev/null +++ b/test/fixtures/workspace/maven/web/pom.xml @@ -0,0 +1,10 @@ + + + 4.0.0 + demoreactor1.0 + shop + war + + democore1.0 + + diff --git a/test/fixtures/workspace/maven/web/src/main/webapp/WEB-INF/web.xml b/test/fixtures/workspace/maven/web/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..5884822 --- /dev/null +++ b/test/fixtures/workspace/maven/web/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,4 @@ + + + shop + diff --git a/test/fixtures/workspace/maven/web/src/main/webapp/index.jsp b/test/fixtures/workspace/maven/web/src/main/webapp/index.jsp new file mode 100644 index 0000000..364053b --- /dev/null +++ b/test/fixtures/workspace/maven/web/src/main/webapp/index.jsp @@ -0,0 +1 @@ +<%@ page contentType="text/plain; charset=UTF-8" %><%= demo.core.Greeter.greet() %> diff --git a/test/fixtures/workspace/plain/web/WEB-INF/web.xml b/test/fixtures/workspace/plain/web/WEB-INF/web.xml new file mode 100644 index 0000000..85288a4 --- /dev/null +++ b/test/fixtures/workspace/plain/web/WEB-INF/web.xml @@ -0,0 +1,4 @@ + + + plain + diff --git a/test/fixtures/workspace/plain/web/index.html b/test/fixtures/workspace/plain/web/index.html new file mode 100644 index 0000000..9c62eb5 --- /dev/null +++ b/test/fixtures/workspace/plain/web/index.html @@ -0,0 +1 @@ +Hello from a plain Web folder diff --git a/test/fixtures/workspace/wtp/.classpath b/test/fixtures/workspace/wtp/.classpath new file mode 100644 index 0000000..dd6ef05 --- /dev/null +++ b/test/fixtures/workspace/wtp/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/test/fixtures/workspace/wtp/.project b/test/fixtures/workspace/wtp/.project new file mode 100644 index 0000000..d9031a6 --- /dev/null +++ b/test/fixtures/workspace/wtp/.project @@ -0,0 +1,9 @@ + + + wtp-demo + + org.eclipse.jdt.core.javanature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.wst.common.modulecore.ModuleCoreNature + + diff --git a/test/fixtures/workspace/wtp/.settings/org.eclipse.wst.common.component b/test/fixtures/workspace/wtp/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..2014284 --- /dev/null +++ b/test/fixtures/workspace/wtp/.settings/org.eclipse.wst.common.component @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/test/fixtures/workspace/wtp/WebContent/WEB-INF/web.xml b/test/fixtures/workspace/wtp/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000..64933a2 --- /dev/null +++ b/test/fixtures/workspace/wtp/WebContent/WEB-INF/web.xml @@ -0,0 +1,4 @@ + + + wtp-demo + diff --git a/test/fixtures/workspace/wtp/WebContent/index.jsp b/test/fixtures/workspace/wtp/WebContent/index.jsp new file mode 100644 index 0000000..5172776 --- /dev/null +++ b/test/fixtures/workspace/wtp/WebContent/index.jsp @@ -0,0 +1 @@ +<%@ page contentType="text/plain; charset=UTF-8" %><%= demo.wtp.Message.text() %> diff --git a/test/fixtures/workspace/wtp/src/demo/wtp/Message.java b/test/fixtures/workspace/wtp/src/demo/wtp/Message.java new file mode 100644 index 0000000..80a1726 --- /dev/null +++ b/test/fixtures/workspace/wtp/src/demo/wtp/Message.java @@ -0,0 +1,7 @@ +package demo.wtp; + +public final class Message { + public static String text() { + return "Hello from the Eclipse output folder"; + } +} diff --git a/test/java-plugin.json b/test/java-plugin.json new file mode 100644 index 0000000..8846254 --- /dev/null +++ b/test/java-plugin.json @@ -0,0 +1,22 @@ +{ + "schemaVersion": 1, + "plugin": "io.github.lithe-idea.java-support", + "repository": "https://github.com/Lithe-IDEA/lithe-plugin-java", + "version": "4.0.1", + "archives": { + "darwin-arm64": { + "url": "https://github.com/Lithe-IDEA/lithe-plugin-java/releases/download/v4.0.1/Lithe-Java-Support-4.0.1-darwin-arm64.zip", + "sha256": "ce5d127eef82263378a330f29932f14a6c3408a577b810f8a7422b39088bb435" + }, + "linux-x64": { + "url": "https://github.com/Lithe-IDEA/lithe-plugin-java/releases/download/v4.0.1/Lithe-Java-Support-4.0.1-linux-x64.zip", + "sha256": "42c4349c4b79b442cd04639bac32205c4dac730dbc2145ea9e39ec76ddcc0a7b" + } + }, + "jdtls": { + "version": "1.61.0", + "note": "Java Support finds the Eclipse JDT Language Server outside its package (JDTLS_HOME among others); the version and checksum are the ones lithe-plugin-java's CI pins in third_party/jdtls/manifest.json.", + "url": "https://download.eclipse.org/jdtls/milestones/1.61.0/jdt-language-server-1.61.0-202609031315.tar.gz", + "sha256": "338e7e73d61836651ba2453919a0d34fa763eb4e7c03342092309bffb8934c64" + } +} diff --git a/test/tomcat-versions.json b/test/tomcat-versions.json new file mode 100644 index 0000000..3775710 --- /dev/null +++ b/test/tomcat-versions.json @@ -0,0 +1,16 @@ +{ + "schemaVersion": 1, + "source": "https://archive.apache.org/dist/tomcat", + "versions": [ + { + "version": "9.0.124", + "url": "https://archive.apache.org/dist/tomcat/tomcat-9/v9.0.124/bin/apache-tomcat-9.0.124.tar.gz", + "sha512": "925e4fefe25b2ecccd032acd0b4cb1b506455037ed0f8b0e51824bed839c5e92bf5e58982b990d2fdcbc790bcda1a533db7faffb325f8a7baee939fc8ae871c1" + }, + { + "version": "10.1.62", + "url": "https://archive.apache.org/dist/tomcat/tomcat-10/v10.1.62/bin/apache-tomcat-10.1.62.tar.gz", + "sha512": "ca776bf4045d3eadc2ede1b9bb2c33fc52ce1d102b63ca635ec6c0e515140027c6be7a15b2c1e1d8d8692aeaf25a72de99ca0f14135c3e1d163eedaf3dac5a54" + } + ] +} diff --git a/vendor/LICENSE b/vendor/LICENSE new file mode 100644 index 0000000..69bef1d --- /dev/null +++ b/vendor/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and + for which the editorial revisions, annotations, elaborations, + or other modifications represent, as a whole, an original work + of authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely link + (or bind by name) to the interfaces of, the Work and Derivative Works + thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of + its distribution, then any Derivative Works that You + distribute must include a readable copy of the attribution + notices contained within such NOTICE file, excluding those + notices that do not pertain to any part of the Derivative + Works, in at least one of the following places: within a + NOTICE text file distributed as part of the Derivative Works; + within the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing + the origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as + a result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[ ]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java new file mode 100644 index 0000000..02aa4a6 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -0,0 +1,1573 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.Base64; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +/** + * The plugin backend session: one process the host starts from the plugin's + * manifest and talks to over stdio with the LSP base protocol. + * + *

The SDK owns everything Lithe manages uniformly -- the lifecycle, protocol + * negotiation, cancellation, error codes, and the {@code lithe/*} namespace -- + * and leaves the plugin free to decide what its handlers do. Declare handlers, + * then call {@link #listen()}. Handlers run on their own threads, so several + * calls can be in flight at once; shared plugin state needs its own locking. + * + *

Host services ({@code lithe/host/*}) are in {@link #host()}, or a + * handler's {@link CallContext#host()}. + * + *

Contract: {@code contract/v1/README.md} ("Build providers" + * and "Plugin functions"). Behaviour and error codes match the Node.js SDK. + */ +public final class Backend { + /** Answers a typed build request or a plugin function. */ + @FunctionalInterface + public interface Handler { + Object handle(Map params, CallContext context) throws Exception; + } + + /** Answers an independently negotiated shortcut import request. */ + @FunctionalInterface + public interface KeymapImportHandler { + Object handle(KeymapSnapshot snapshot, CallContext context) throws Exception; + } + + /** One file within the user's selected source; its path is a relative label. */ + public static final class KeymapSourceFile { + private final String id; + private final String path; + private final long byteCount; + KeymapSourceFile(String id, String path, long byteCount) { this.id = id; this.path = path; this.byteCount = byteCount; } + public String id() { return id; } + public String path() { return path; } + public long byteCount() { return byteCount; } + } + + /** Opaque selected source scoped to one import and backend session. */ + public static final class KeymapSnapshot { + private final String providerId; + private final String snapshotId; + private final Host host; + KeymapSnapshot(String providerId, String snapshotId, Host host) { + this.providerId = providerId; this.snapshotId = snapshotId; this.host = host; + } + public String providerId() { return providerId; } + public String snapshotId() { return snapshotId; } + private Map scope() { + Map result = singleton("providerID", providerId); + result.put("snapshotID", snapshotId); + return result; + } + public CompletableFuture> listInputs() { + return host.request("lithe/host/keymapImport/listInputs", scope()).thenApply(raw -> { + Object files = raw instanceof Map ? ((Map) raw).get("files") : null; + if (!(files instanceof List) || ((List) files).size() > 128) throw invalidKeymapResponse(); + List result = new ArrayList<>(); + for (Object item : (List) files) { + if (!(item instanceof Map)) throw invalidKeymapResponse(); + Map file = (Map) item; + Object id = file.get("id"), path = file.get("path"), count = file.get("byteCount"); + if (!(id instanceof String) || !validSnapshotToken((String) id) || !(path instanceof String) + || ((String) path).isEmpty() || ((String) path).getBytes(StandardCharsets.UTF_8).length > 4096 + || !(count instanceof Number) || ((Number) count).doubleValue() != ((Number) count).longValue() + || ((Number) count).longValue() < 0 || ((Number) count).longValue() > 1048576) throw invalidKeymapResponse(); + result.add(new KeymapSourceFile((String) id, (String) path, ((Number) count).longValue())); + } + return result; + }); + } + public CompletableFuture readChunk(String fileId, long offset, int maximumBytes) { + if (!validSnapshotToken(fileId) || offset < 0 || offset > 1048576 || maximumBytes < 1 || maximumBytes > 131072) { + throw invalidKeymapResponse(); + } + Map params = scope(); + params.put("fileID", fileId); params.put("offset", offset); params.put("maximumBytes", maximumBytes); + return host.request("lithe/host/keymapImport/readChunk", params).thenApply(raw -> { + Object encoded = raw instanceof Map ? ((Map) raw).get("data") : null; + if (!(encoded instanceof String) || ((String) encoded).length() > 174764) throw invalidKeymapResponse(); + final byte[] bytes; + try { bytes = Base64.getDecoder().decode((String) encoded); } + catch (IllegalArgumentException error) { throw invalidKeymapResponse(); } + if (bytes.length > maximumBytes || !Base64.getEncoder().encodeToString(bytes).equals(encoded)) throw invalidKeymapResponse(); + return bytes; + }); + } + } + + /** Answers a standard LSP request, for a backend that is also a language server. */ + @FunctionalInterface + public interface RequestHandler { + Object handle(Object params, CallContext context) throws Exception; + } + + /** Handles a standard LSP notification. */ + @FunctionalInterface + public interface NotificationHandler { + void handle(Object params) throws Exception; + } + + /** + * Handles {@code lithe/host/commands/didRun} for one of the plugin's + * commands. {@code workspaceContext} is the {@code { contextID, generation }} + * of the window the command ran in, or null. + */ + @FunctionalInterface + public interface CommandHandler { + void handle(String commandId, Map workspaceContext) throws Exception; + } + + /** Runs before the {@code initialize} answer. */ + @FunctionalInterface + public interface InitializeHook { + void run(Map params, Negotiated negotiated) throws Exception; + } + + /** Runs on {@code shutdown}, after running calls were cancelled. */ + @FunctionalInterface + public interface ShutdownHook { + void run() throws Exception; + } + + /** Protocols the host agreed to in {@code initialize}. */ + public static final class Negotiated { + static final Negotiated NONE = new Negotiated(false, false); + + private final boolean functions; + private final boolean build; + + Negotiated(boolean functions, boolean build) { + this.functions = functions; + this.build = build; + } + + /** + * Whether the host negotiated plugin functions ({@code litheFunctions}), + * which also carry the host services, the workspace contexts, the host + * notifications, and the calls to other plugins' functions. + */ + public boolean functions() { + return functions; + } + + /** Whether the host negotiated typed build requests and this backend declared a build handler. */ + public boolean build() { + return build; + } + } + + private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED } + + /** The {@code version} every build result document carries. */ + private static final long BUILD_DOCUMENT_VERSION = 0; + + /** Canonical result format of each typed build request. */ + private static final Map BUILD_FORMATS; + + static { + Map formats = new HashMap<>(); + formats.put(Protocol.BUILD_MODEL, "litheBuildModel"); + formats.put(Protocol.BUILD_DEPENDENCIES, "litheDependencies"); + formats.put(Protocol.BUILD_DISCOVER_TESTS, "litheTestDiscovery"); + formats.put(Protocol.BUILD_RUN_ENTRYPOINTS, "litheRunEntrypoints"); + BUILD_FORMATS = Collections.unmodifiableMap(formats); + } + + private volatile boolean logging; + /** The negotiated build protocol version, the newest the host offered; -1 before. */ + private volatile int buildVersion = -1; + private boolean loggingReady; + private final List> earlyDiagnostics = new ArrayList<>(); + private final java.util.Set quietSuccess = new java.util.HashSet<>(); + private final String name; + private final String version; + private final Map capabilities; + private final Object lock = new Object(); + private final Object writeLock = new Object(); + private final Map functions = new HashMap<>(); + private final Map keymapProviders = new HashMap<>(); + private final Set selectedKeymapProviders = new TreeSet<>(); + private final Map buildHandlers = new HashMap<>(); + private final Map requestHandlers = new HashMap<>(); + private final Map notificationHandlers = new HashMap<>(); + private final Map commandHandlers = new HashMap<>(); + private final Map hostNotificationHandlers = new HashMap<>(); + private NotificationHandler contextsHandler; + private final List initializeHooks = new ArrayList<>(); + private final List shutdownHooks = new ArrayList<>(); + /** Host requests being handled, by JSON-RPC ID. */ + private final Map incoming = new HashMap<>(); + /** Requests this backend sent to the host, by JSON-RPC ID. */ + private final Map outgoing = new HashMap<>(); + private final AtomicInteger nextRequestId = new AtomicInteger(1); + private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadNamer()); + private final HostChannel channel = new HostChannel(new Wire()); + private final Host host = new Host(channel, Collections.emptyList(), null); + /** Serializes register/unregister so the host sees them in call order. */ + private CompletableFuture registrations = CompletableFuture.completedFuture(null); + private volatile Phase phase = Phase.IDLE; + private volatile Negotiated negotiated = Negotiated.NONE; + private volatile Map initializeParams; + private volatile OutputStream output; + private volatile PrintStream errorOutput = System.err; + private int exitCode = 1; + + private Backend(String name, String version, Map capabilities) { + Object experimental = capabilities.get("experimental"); + if (experimental instanceof Map + && (((Map) experimental).containsKey("litheBuild") + || ((Map) experimental).containsKey("litheFunctions") + || ((Map) experimental).containsKey("litheKeymapImport") + || ((Map) experimental).containsKey("litheLogging"))) { + throw new PluginSdkError("sdk.capabilities.reserved", + "litheBuild, litheFunctions, litheKeymapImport and litheLogging are negotiated by the SDK; declare handlers instead."); + } + this.name = name == null ? "lithe-plugin-backend" : name; + this.version = version; + this.capabilities = new LinkedHashMap<>(capabilities); + } + + /** + * Creates a backend. + * + * @param name reported as {@code serverInfo.name} and used as the log prefix + * @param version reported as {@code serverInfo.version}; may be null + */ + public static Backend create(String name, String version) { + return new Backend(name, version, Collections.emptyMap()); + } + + /** + * Creates a backend that also declares standard LSP server capabilities. + * {@code experimental.litheBuild} and {@code experimental.litheFunctions} + * are negotiated by the SDK and cannot be set here. + */ + public static Backend create(String name, String version, Map capabilities) { + return new Backend(name, version, capabilities == null ? Collections.emptyMap() : capabilities); + } + + /** Protocols the host agreed to in {@code initialize}; both false before it. */ + public Negotiated negotiated() { + return negotiated; + } + + /** + * Host services, usable once the session is ready. Prefer a handler's {@link CallContext#host()}, whose + * requests end with the call; this one belongs to no call, so its calls to + * other plugins name no parent call unless the call says one. + */ + public Host host() { + return host; + } + + /** The host's {@code initialize} params, or null before it arrives. */ + public Map initializeParams() { + return initializeParams; + } + + /** IDs of the functions this backend currently serves, sorted. */ + public List functionIds() { + synchronized (lock) { + List ids = new ArrayList<>(functions.keySet()); + Collections.sort(ids); + return ids; + } + } + + /** Answers {@code lithe/build/model} with a {@code litheBuildModel} document. */ + public Backend onModel(Handler handler) { + return declareBuild(Protocol.BUILD_MODEL, handler); + } + + /** Answers {@code lithe/build/dependencies} with a {@code litheDependencies} document. */ + public Backend onDependencies(Handler handler) { + return declareBuild(Protocol.BUILD_DEPENDENCIES, handler); + } + + /** Executes a bounded provider task. */ + public Backend onExecute(Handler handler) { + return declareBuild(Protocol.BUILD_EXECUTE, handler); + } + + /** Runs exact test selectors. */ + public Backend onTest(Handler handler) { + return declareBuild(Protocol.BUILD_TEST, handler); + } + + /** Returns the upstream engine's runnable test selectors, with the format stamped. */ + public Backend onDiscoverTests(Handler handler) { + return declareBuild(Protocol.BUILD_DISCOVER_TESTS, handler); + } + + /** Prepares native executable target facts. */ + public Backend onPrepareDebug(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_DEBUG, handler); + } + + /** Prepares a portable application launch. */ + public Backend onPrepareRun(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_RUN, handler); + } + + /** + * Names the entrypoints of one source file that an entrypoint run starts + * ({@code buildProviders} 1), with the format stamped. + */ + public Backend onRunEntrypoints(Handler handler) { + return declareBuild(Protocol.BUILD_RUN_ENTRYPOINTS, handler); + } + + /** + * Declares a plugin function offered from the start, in the {@code initialize} + * answer. To add one later, use {@link #registerFunction}. + * + * @param id dot-separated lowerCamelCase segments, such as {@code snapshot.refresh} + */ + public Backend function(String id, Handler handler) { + synchronized (lock) { + if (!beforeAnswer()) { + throw new PluginSdkError("sdk.function.lateDeclaration", + "After initialize, add functions with registerFunction()."); + } + checkNewFunction(id, handler); + functions.put(id, handler); + } + return this; + } + + /** Declares a shortcut import provider before initialization. */ + public Backend keymapImportProvider(String id, KeymapImportHandler handler) { + synchronized (lock) { + if (!beforeAnswer() || !validKeymapProvider(id) || handler == null + || keymapProviders.containsKey(id) || keymapProviders.size() >= 8) { + throw new PluginSdkError("sdk.keymap.invalidRegistration", "Invalid or duplicate shortcut import provider."); + } + keymapProviders.put(id, handler); + } + return this; + } + + /** Handles a standard LSP request, for a backend that is also a language server. */ + public Backend onRequest(String method, RequestHandler handler) { + checkDeclared(method, handler); + synchronized (lock) { + requestHandlers.put(method, handler); + } + return this; + } + + /** Handles a standard LSP notification. */ + public Backend onNotification(String method, NotificationHandler handler) { + checkDeclared(method, handler); + synchronized (lock) { + notificationHandlers.put(method, handler); + } + return this; + } + + /** + * Handles {@code lithe/host/commands/didRun} for one of the plugin's + * commands. It is an event: the host waits for no result. + * + * @param commandId the command's ID from the manifest, 1-128 of {@code [a-z0-9.-]} + */ + public Backend onCommand(String commandId, CommandHandler handler) { + if (!Protocol.isCommandId(commandId)) { + throw new PluginSdkError("sdk.command.invalidID", "Command ID \"" + commandId + "\" must be 1-128 of [a-z0-9.-]."); + } + if (handler == null) { + throw new IllegalArgumentException("A command handler must not be null."); + } + synchronized (lock) { + commandHandlers.put(commandId, handler); + } + return this; + } + + /** + * Handles {@code lithe/host/workspace/didChangeContexts} with + * {@code { revision }}; call {@code host().workspace().listContexts()} for + * the contexts. + */ + public Backend onContextsChanged(NotificationHandler handler) { + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + synchronized (lock) { + contextsHandler = handler; + } + return this; + } + + /** + * Handles a {@code lithe/host/*} notification a later host adds. Commands, + * context changes, and subscription events have their own APIs. + */ + public Backend onHostNotification(String method, NotificationHandler handler) { + if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { + throw new PluginSdkError("sdk.method.invalid", method + " is not a host notification."); + } + if (method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) || method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY) + || method.equals(Protocol.HOST_COMMAND_DID_RUN)) { + throw new PluginSdkError("sdk.method.reserved", + method + " is routed by the SDK; use onCommand, onContextsChanged, or Host.subscribe."); + } + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + synchronized (lock) { + hostNotificationHandlers.put(method, handler); + } + return this; + } + + /** Runs before the {@code initialize} answer, with the host's params and the negotiation. */ + public Backend onInitialize(InitializeHook hook) { + synchronized (lock) { + initializeHooks.add(hook); + } + return this; + } + + /** Runs on {@code shutdown}, after running calls were cancelled. */ + public Backend onShutdown(ShutdownHook hook) { + synchronized (lock) { + shutdownHooks.add(hook); + } + return this; + } + + /** + * Adds a function. Before the {@code initialize} answer (including from an + * {@link #onInitialize} hook) it joins the initial list; afterwards the host + * must accept it first. The future completes once the function is served. + */ + public CompletableFuture registerFunction(String id, Handler handler) { + synchronized (lock) { + if (beforeAnswer()) { + try { + checkNewFunction(id, handler); + functions.put(id, handler); + return CompletableFuture.completedFuture(null); + } catch (RuntimeException error) { + return failed(error); + } + } + } + return queueRegistration(() -> { + synchronized (lock) { + requireFunctions(); + checkNewFunction(id, handler); + // Installed before the request: the host may invoke it as soon as + // its registry changed, before this backend reads the reply. + functions.put(id, handler); + } + Map entry = new LinkedHashMap<>(); + entry.put("id", id); + Map params = new LinkedHashMap<>(); + params.put("functions", Collections.singletonList(entry)); + return request(Protocol.FUNCTION_REGISTER, params).handle((result, error) -> { + if (error != null) { + synchronized (lock) { + functions.remove(id); + quietSuccess.remove(id); + } + throw new CompletionException(unwrap(error)); + } + return null; + }); + }); + } + + /** Withdraws a function. The host ends its running calls as revoked. */ + public CompletableFuture unregisterFunction(String id) { + synchronized (lock) { + if (beforeAnswer()) { + if (functions.remove(id) == null) { + return failed(unknownFunction(id)); + } + quietSuccess.remove(id); + return CompletableFuture.completedFuture(null); + } + } + return queueRegistration(() -> { + synchronized (lock) { + requireFunctions(); + if (!functions.containsKey(id)) { + throw unknownFunction(id); + } + } + Map params = new LinkedHashMap<>(); + params.put("ids", Collections.singletonList(id)); + return request(Protocol.FUNCTION_UNREGISTER, params).thenApply(result -> { + List running = new ArrayList<>(); + synchronized (lock) { + functions.remove(id); + quietSuccess.remove(id); + for (Call call : incoming.values()) { + if (id.equals(call.functionId)) { + running.add(call); + } + } + } + for (Call call : running) { + call.cancellation.cancel("The function was withdrawn."); + } + return null; + }); + }); + } + + /** Sends a standard LSP request to the host. {@code lithe/*} methods are reserved. */ + public CompletableFuture sendRequest(String method, Object params) { + checkOutgoing(method); + return request(method, params); + } + + /** Sends a standard LSP notification to the host. {@code lithe/*} methods are reserved. */ + public void sendNotification(String method, Object params) { + checkOutgoing(method); + Map message = message(null, method); + if (params != null) { + message.put("params", params); + } + write(message); + } + + public Diagnostics diagnostics() { return new Diagnostics(this, null); } + + public Backend suppressSuccessDiagnostics(String operation) { + if (!loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Suppress a registered operation."); + synchronized (lock) { quietSuccess.add(operation); } + return this; + } + + boolean loggingOperation(String operation) { + synchronized (lock) { return Diagnostics.OPERATIONS.contains(operation) || functions.containsKey(operation); } + } + + void logFact(Map params) { + synchronized (lock) { + if (!logging) return; + if (!loggingReady) { if (earlyDiagnostics.size() < 8) earlyDiagnostics.add(params); return; } + } + Map notification = message(null, "lithe/log"); + notification.put("params", params); + write(notification); + } + + /** + * Serves the host over stdio until it sends {@code exit} or closes stdin, + * then exits the process with the session's exit code: 0 after a + * {@code shutdown}, 1 otherwise. {@code System.out} is redirected to stderr + * first, because stdout carries the protocol and a stray line there would + * end the session. + */ + public void listen() { + OutputStream protocol = new FileOutputStream(FileDescriptor.out); + System.setOut(System.err); + int code = listen(System.in, protocol, System.err); + System.exit(code); + } + + /** + * Serves the host over the given streams and returns the exit code once the + * session ended, without exiting the process. Blocks the calling thread. + */ + public int listen(InputStream input, OutputStream output, PrintStream errorOutput) { + synchronized (lock) { + if (phase != Phase.IDLE) { + throw new PluginSdkError("sdk.listen.repeated", "A backend listens once."); + } + phase = Phase.LISTENING; + this.output = output; + this.errorOutput = errorOutput; + } + Framing.Decoder decoder = new Framing.Decoder(); + byte[] chunk = new byte[64 * 1024]; + try { + while (phase != Phase.EXITED) { + int count = input.read(chunk); + if (count < 0) { + finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); + break; + } + List messages; + try { + messages = decoder.push(chunk, 0, count); + } catch (Framing.FramingException error) { + diagnostics().terminal("notification", new IllegalStateException(), System.nanoTime()); + finish(1); + break; + } + for (Object message : messages) { + if (phase == Phase.EXITED) { + break; + } + dispatch(message); + } + } + } catch (IOException error) { + finish(1); + } + synchronized (lock) { + return exitCode; + } + } + + private void dispatch(Object message) { + if (message == Framing.MALFORMED) { + respond(null, null, error(Protocol.PARSE_ERROR, "The message is not valid JSON.")); + return; + } + // Valid JSON that is not a message object, such as `null` or a batch. + if (!(message instanceof Map)) { + respond(null, null, error(Protocol.INVALID_REQUEST, "The message is not a JSON-RPC object.")); + return; + } + Map object = Json.object(message); + Object id = object.get("id"); + Object method = object.get("method"); + if (!(method instanceof String)) { + if (id != null) { + settleOutgoing(object); + } + return; + } + if (id != null) { + handleRequest(id, (String) method, object.get("params")); + } else { + handleNotification((String) method, object.get("params")); + } + } + + private void handleRequest(Object id, String method, Object params) { + if (method.equals(Protocol.INITIALIZE)) { + initialize(id, params instanceof Map ? Json.object(params) : new LinkedHashMap<>()); + return; + } + if (method.equals(Protocol.SHUTDOWN)) { + shutdown(id); + return; + } + Phase current = phase; + if (current == Phase.LISTENING || current == Phase.INITIALIZING) { + respond(id, null, error(Protocol.SERVER_NOT_INITIALIZED, "The backend is not initialized.")); + return; + } + if (current != Phase.READY) { + respond(id, null, error(Protocol.INVALID_REQUEST, "The backend is shutting down.")); + return; + } + if (method.equals(Protocol.FUNCTION_INVOKE)) { + invokeFunction(id, params); + return; + } + if (method.equals("lithe/keymap/import")) { + invokeKeymap(id, params); + return; + } + Handler build; + RequestHandler handler; + synchronized (lock) { + build = negotiated.build() ? buildHandlers.get(method) : null; + handler = requestHandlers.get(method); + } + if (build != null) { + if (params != null && !(params instanceof Map)) { + respond(id, null, error(Protocol.INVALID_PARAMS, method + " params must be an object.")); + return; + } + Map arguments = Json.object(params); + invokeBuild(id, method, arguments, build); + return; + } + if (handler != null) { + run(id, null, null, context -> handler.handle(params, context), result -> result, null); + return; + } + respond(id, null, error(Protocol.METHOD_NOT_FOUND, "Unsupported method: " + method)); + } + + private void handleNotification(String method, Object params) { + if (method.equals(Protocol.EXIT)) { + finish(phase == Phase.SHUTTING_DOWN ? 0 : 1); + return; + } + if (method.equals(Protocol.CANCEL_REQUEST)) { + Object id = params instanceof Map ? ((Map) params).get("id") : null; + Call call; + synchronized (lock) { + call = incoming.get(requestKey(id)); + } + if (call != null) { + call.cancellation.cancel("The request was cancelled."); + } + return; + } + if (phase != Phase.READY || method.equals(Protocol.INITIALIZED)) { + return; + } + if (method.startsWith(Protocol.HOST_PREFIX)) { + hostNotification(method, params); + return; + } + NotificationHandler handler; + synchronized (lock) { + handler = notificationHandlers.get(method); + } + if (handler == null) { + return; + } + notifyHandler(method, () -> handler.handle(params)); + } + + /** + * Routes a host notification. Core checked its shape and the session's + * grant; one this SDK does not know is ignored, as the contract asks. + */ + private void hostNotification(String method, Object raw) { + if (!negotiated.functions() || !(raw instanceof Map)) { + return; + } + Map params = Json.object(raw); + if (method.equals(Protocol.HOST_SUBSCRIPTION_NOTIFY)) { + channel.deliver(params); + return; + } + if (method.equals(Protocol.HOST_COMMAND_DID_RUN)) { + Object commandId = params.get("commandID"); + CommandHandler handler; + synchronized (lock) { + handler = commandId instanceof String ? commandHandlers.get(commandId) : null; + } + if (handler == null) { + diagnostics().degraded("notification", "command_unhandled"); + return; + } + Map context = workspaceContext(params.get("context")); + notifyHandler(method, () -> handler.handle((String) commandId, context)); + return; + } + NotificationHandler handler; + synchronized (lock) { + handler = method.equals(Protocol.HOST_DID_CHANGE_CONTEXTS) ? contextsHandler : hostNotificationHandlers.get(method); + } + if (handler != null) { + notifyHandler(method, () -> handler.handle(params)); + } + } + + private interface Notified { + void run() throws Exception; + } + + /** Runs a notification handler off the reader thread; a failure is logged. */ + private void notifyHandler(String method, Notified handler) { + executor.execute(() -> { + try { + handler.run(); + } catch (Throwable error) { + diagnostics().terminal("notification", error, System.nanoTime()); + } + }); + } + + private void initialize(Object id, Map params) { + Negotiated agreed; + List hooks; + synchronized (lock) { + if (phase != Phase.LISTENING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "initialize was already received.")); + return; + } + phase = Phase.INITIALIZING; + initializeParams = params; + Map offered = experimental(params.get("capabilities")); + loggingReady = false; + earlyDiagnostics.clear(); + logging = offers(offered.get("litheLogging"), Protocol.LOGGING_VERSION); + if (!logging) { + phase = Phase.LISTENING; + respond(id, null, error(Protocol.INVALID_REQUEST, + "The backend requires litheLogging version " + Protocol.LOGGING_VERSION + ".")); + return; + } + buildVersion = -1; + for (int version = Protocol.BUILD_VERSION; version >= 0 && buildVersion < 0; version--) { + if (offers(offered.get("litheBuild"), version)) { + buildVersion = version; + } + } + agreed = new Negotiated( + offers(offered.get("litheFunctions"), Protocol.FUNCTIONS_VERSION), + !buildHandlers.isEmpty() && buildVersion >= 0); + negotiated = agreed; + hooks = new ArrayList<>(initializeHooks); + } + executor.execute(() -> { + try { + for (InitializeHook hook : hooks) { + hook.run(params, agreed); + } + } catch (Throwable failure) { + synchronized (lock) { + if (phase == Phase.INITIALIZING) { + phase = Phase.LISTENING; + } + } + respond(id, null, toResponseError(failure, null)); + return; + } + synchronized (lock) { + // A shutdown or exit that arrived while a hook ran ended the + // session; finishing initialize must not reopen it. + if (phase != Phase.INITIALIZING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "The session ended during initialize.")); + return; + } + if (!agreed.functions() && !functions.isEmpty()) { + diagnostics().degraded("initialize", "functions_unavailable"); + } + Map experimental = new LinkedHashMap<>(experimental(capabilities)); + experimental.put("litheLogging", singleton("version", Protocol.LOGGING_VERSION)); + Map offeredCapabilities = experimental(params.get("capabilities")); + Object keymap = offeredCapabilities.get("litheKeymapImport"); + if (offers(keymap, Protocol.KEYMAP_IMPORT_VERSION) && keymap instanceof Map) { + Object providers = ((Map) keymap).get("providers"); + if (providers instanceof List && ((List) providers).size() <= 8) { + selectedKeymapProviders.clear(); + for (Object provider : (List) providers) { + if (provider instanceof String && keymapProviders.containsKey(provider)) selectedKeymapProviders.add((String) provider); + } + if (!selectedKeymapProviders.isEmpty()) { + Map entry = singleton("version", Protocol.KEYMAP_IMPORT_VERSION); + entry.put("providers", new ArrayList<>(selectedKeymapProviders)); + experimental.put("litheKeymapImport", entry); + } + } + } + if (agreed.build()) { + experimental.put("litheBuild", singleton("version", buildVersion)); + } + if (agreed.functions()) { + List offered = new ArrayList<>(); + for (String functionId : functionIds()) { + offered.add(singleton("id", functionId)); + } + Map entry = singleton("version", Protocol.FUNCTIONS_VERSION); + entry.put("functions", offered); + experimental.put("litheFunctions", entry); + } + Map answered = new LinkedHashMap<>(capabilities); + answered.put("experimental", experimental); + Map serverInfo = singleton("name", name); + if (version != null) { + serverInfo.put("version", version); + } + Map result = singleton("capabilities", answered); + result.put("serverInfo", serverInfo); + phase = Phase.READY; + respond(id, result, null); + loggingReady = true; + List> early = new ArrayList<>(earlyDiagnostics); + earlyDiagnostics.clear(); + for (Map fact : early) logFact(fact); + } + }); + } + + private void shutdown(Object id) { + List hooks; + synchronized (lock) { + if (phase != Phase.READY && phase != Phase.LISTENING && phase != Phase.INITIALIZING) { + respond(id, null, error(Protocol.INVALID_REQUEST, "shutdown was already received.")); + return; + } + phase = Phase.SHUTTING_DOWN; + hooks = new ArrayList<>(shutdownHooks); + } + cancelAll("The backend is shutting down."); + executor.execute(() -> { + for (ShutdownHook hook : hooks) { + try { + hook.run(); + } catch (Throwable error) { + diagnostics().terminal("shutdown", error, System.nanoTime()); + } + } + Processes.killAll(); + respond(id, null, null); + }); + } + + private void invokeKeymap(Object id, Object raw) { + Map params = raw instanceof Map ? Json.object(raw) : new LinkedHashMap<>(); + Object provider = params.get("providerID"), snapshot = params.get("snapshotID"); + KeymapImportHandler handler; + synchronized (lock) { + handler = provider instanceof String && selectedKeymapProviders.contains(provider) ? keymapProviders.get(provider) : null; + } + if (params.size() != 2 || !(provider instanceof String) || !validKeymapProvider((String) provider) + || !(snapshot instanceof String) || !validSnapshotToken((String) snapshot) || handler == null) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Invalid shortcut import request.")); + return; + } + run(id, null, null, null, context -> handler.handle(new KeymapSnapshot((String) provider, (String) snapshot, context.host()), context), + Backend::functionResult, null, null, "lithe/keymap/import", null, null); + } + + private static boolean validKeymapProvider(String id) { + return id != null && id.matches("[a-z][a-z0-9-]{0,63}"); + } + + private static boolean validSnapshotToken(String id) { + return id != null && id.matches("[a-zA-Z0-9_-]{1,128}"); + } + + private static PluginSdkError invalidKeymapResponse() { + return new PluginSdkError("sdk.keymap.invalidResponse", "Invalid shortcut source response."); + } + + private void invokeFunction(Object id, Object raw) { + Map invocation = raw instanceof Map ? Json.object(raw) : new LinkedHashMap<>(); + Object functionId = invocation.get("functionID"); + Object operationId = invocation.get("operationID"); + Object params = invocation.get("params"); + Map workspaceContext = workspaceContext(invocation.get("context")); + Map caller = callerReference(invocation.get("caller")); + Handler handler; + synchronized (lock) { + handler = negotiated.functions() && functionId instanceof String ? functions.get(functionId) : null; + } + if (handler == null) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " is not registered.")); + return; + } + if (params != null && !(params instanceof Map)) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Function " + functionId + " params must be an object.")); + return; + } + String function = (String) functionId; + String operation = operationId instanceof String ? (String) operationId : null; + Map arguments = Json.object(params); + AtomicBoolean reporting = new AtomicBoolean(true); + CallContext.ProgressSink progress = (message, percentage) -> { + if (!reporting.get()) { + return; + } + Map report = new LinkedHashMap<>(); + report.put("operationID", operationId); + if (message != null) { + report.put("message", Protocol.boundedText(message)); + } + if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { + report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); + } + Map notification = message(null, Protocol.FUNCTION_PROGRESS); + notification.put("params", report); + write(notification); + }; + // The call's wire operation ID is the parent of the calls it makes to other plugins. + String parentOperationId = Protocol.isParentOperationId(operation) ? operation : null; + run(id, function, operation, workspaceContext, context -> handler.handle(arguments, context), + Backend::functionResult, () -> reporting.set(false), progress, function, caller, parentOperationId); + } + + private void invokeBuild(Object id, String method, Map arguments, Handler handler) { + if (!Protocol.buildProgress(method)) { + run(id, null, null, null, context -> handler.handle(arguments, context), result -> buildResult(method, result), null, null, method, + null, null); + return; + } + Object wireId = arguments.get("operationID"); + if (!(wireId instanceof String)) { + respond(id, null, error(Protocol.INVALID_PARAMS, "A build request needs its wire operationID.")); + return; + } + AtomicBoolean reporting = new AtomicBoolean(true); + CallContext.ProgressSink progress = new CallContext.ProgressSink() { + @Override + public void report(String message, Double percentage) { report(message, percentage, null); } + @Override + public void report(String text, Double percentage, String output) { + if (!reporting.get()) return; + Map report = singleton("operationID", wireId); + if (text != null) report.put("message", Protocol.boundedText(text, Protocol.MAX_BUILD_MESSAGE_BYTES)); + if (output != null) report.put("output", Protocol.boundedText(output, Protocol.MAX_BUILD_OUTPUT_BYTES)); + if (percentage != null && !percentage.isNaN() && !percentage.isInfinite()) { + report.put("percentage", Math.min(100L, Math.max(0L, Math.round(percentage)))); + } + Map notification = message(null, Protocol.BUILD_PROGRESS); + notification.put("params", report); + write(notification); + } + }; + run(id, null, (String) wireId, null, context -> handler.handle(arguments, context), + result -> buildResult(method, result), () -> reporting.set(false), progress, method, null, null); + } + + private interface Invocation { + Object invoke(CallContext context) throws Exception; + } + + private interface Shape { + Object apply(Object result); + } + + private void run(Object id, String functionId, String operationId, Invocation invoke, Shape shape, Runnable onSettled) { + run(id, functionId, operationId, null, invoke, shape, onSettled, null); + } + + /** Runs one handler with its own cancellation and answers exactly once. */ + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress) { + run(id, functionId, operationId, workspaceContext, invoke, shape, onSettled, progress, + functionId == null ? "function-call" : functionId, null, null); + } + + /** + * {@code caller} is the plugin that called a function through the relay and + * {@code parentOperationId} the wire operation ID calls to other plugins + * name as their parent; both are null for every call but a function call. + */ + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress, String diagnosticOperation, + Map caller, String parentOperationId) { + long started = System.nanoTime(); + String diagnosticOperationId = Diagnostics.requestOperationId(operationId, id); + Cancellation cancellation = new Cancellation(() -> diagnostics().degraded("notification", "cancellation_listener_failed")); + String key = requestKey(id); + synchronized (lock) { + incoming.put(key, new Call(cancellation, functionId)); + } + CallContext context = new CallContext(cancellation, this, functionId, diagnosticOperationId, progress, + new Host(channel, Collections.singletonList(cancellation), parentOperationId), workspaceContext, caller); + executor.execute(() -> { + Object result = null; + Map error = null; + try { + Object value = invoke.invoke(context); + cancellation.throwIfCancelled(); + result = shape.apply(value); + } catch (Throwable failure) { + if (!cancellation.isCancelled()) { + new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, failure, started); + } + error = toResponseError(failure, cancellation); + } + if (error == null && !cancellation.isCancelled()) { + boolean quiet; + synchronized (lock) { quiet = context.quietSuccess() || quietSuccess.contains(diagnosticOperation); } + if (!quiet) new Diagnostics(this, diagnosticOperationId).terminal(diagnosticOperation, null, started); + } + try { + if (onSettled != null) { + onSettled.run(); + } + } finally { + synchronized (lock) { + incoming.remove(key); + } + // Work belongs to its call: tools still running when the handler + // returned end now. Other calls have their own cancellation. + cancellation.cancel("The call ended."); + // Answered whatever the clean-up did, so Lithe never waits for + // its timeout. + respond(id, result, error); + } + }); + } + + private Backend declareBuild(String method, Handler handler) { + if (handler == null) { + throw new IllegalArgumentException("A build handler must not be null."); + } + synchronized (lock) { + if (phase != Phase.IDLE) { + throw new PluginSdkError("sdk.build.lateDeclaration", "Declare build handlers before listen()."); + } + buildHandlers.put(method, handler); + } + return this; + } + + private static void checkDeclared(String method, Object handler) { + if (method == null || Protocol.isReservedMethod(method)) { + throw new PluginSdkError("sdk.method.reserved", method + " is managed by the SDK and Lithe."); + } + if (handler == null) { + throw new IllegalArgumentException("A handler must not be null."); + } + } + + private void checkNewFunction(String id, Handler handler) { + if (!Protocol.isFunctionId(id)) { + throw new PluginSdkError("sdk.function.invalidID", "Function ID \"" + id + + "\" must be dot-separated lowerCamelCase segments of at most 128 bytes."); + } + if (handler == null) { + throw new IllegalArgumentException("A function handler must not be null."); + } + if (functions.containsKey(id)) { + throw new PluginSdkError("sdk.function.duplicate", "Function " + id + " is already declared."); + } + if (functions.size() >= Protocol.MAX_FUNCTIONS) { + throw new PluginSdkError("sdk.function.limit", + "A backend serves at most " + Protocol.MAX_FUNCTIONS + " functions."); + } + } + + /** True until the {@code initialize} answer fixes the initial function list. */ + private boolean beforeAnswer() { + return phase == Phase.IDLE || phase == Phase.LISTENING || phase == Phase.INITIALIZING; + } + + private void requireFunctions() { + if (phase != Phase.READY || !negotiated.functions()) { + throw new PluginSdkError("sdk.functions.unavailable", "The host has not negotiated plugin functions."); + } + } + + private static PluginSdkError unknownFunction(String id) { + return new PluginSdkError("sdk.function.unknown", "Function " + id + " is not registered."); + } + + private CompletableFuture queueRegistration(Supplier> change) { + synchronized (lock) { + CompletableFuture next = registrations.thenComposeAsync(ignored -> { + try { + return change.get(); + } catch (RuntimeException error) { + return failed(error); + } + }, executor); + registrations = next.handle((result, error) -> null); + return next; + } + } + + private void checkOutgoing(String method) { + if (method == null || Protocol.isReservedMethod(method)) { + throw new PluginSdkError("sdk.method.reserved", method + + " is reserved. A backend never asks the host to run a domain operation or a function."); + } + if (phase != Phase.READY) { + throw new PluginSdkError("sdk.session.notReady", "The session is not initialized."); + } + } + + private CompletableFuture request(String method, Object params) { + return send(method, params).response; + } + + /** Writes a request; params JSON cannot encode throw before anything is registered. */ + private HostChannel.Sent send(String method, Object params) { + String id = "sdk-" + nextRequestId.getAndIncrement(); + CompletableFuture future = new CompletableFuture<>(); + Map message = message(id, method); + if (params != null) { + message.put("params", params); + } + byte[] frame = Framing.encode(message); + synchronized (lock) { + if (phase == Phase.EXITED) { + future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); + return new HostChannel.Sent(id, future); + } + outgoing.put(id, new Pending(future, method)); + } + writeEncoded(frame); + return new HostChannel.Sent(id, future); + } + + private void settleOutgoing(Map message) { + Object id = message.get("id"); + Pending pending; + synchronized (lock) { + pending = id instanceof String ? outgoing.remove(id) : null; + } + if (pending == null) { + return; + } + Object error = message.get("error"); + // Completed on a handler thread: the reader thread never runs plugin code. + if (error instanceof Map) { + HostError rejection = HostError.fromResponse(pending.method, Json.object(error)); + executor.execute(() -> pending.future.completeExceptionally(rejection)); + } else { + Object result = message.get("result"); + executor.execute(() -> pending.future.complete(result)); + } + } + + private void cancelAll(String reason) { + List calls; + synchronized (lock) { + calls = new ArrayList<>(incoming.values()); + } + for (Call call : calls) { + call.cancellation.cancel(reason); + } + } + + private void finish(int code) { + List pending; + synchronized (lock) { + if (phase == Phase.EXITED) { + return; + } + phase = Phase.EXITED; + exitCode = code; + pending = new ArrayList<>(outgoing.values()); + outgoing.clear(); + } + channel.close(); + cancelAll("The session ended."); + Processes.killAll(); + for (Pending request : pending) { + request.future.completeExceptionally(new PluginSdkError("sdk.session.closed", "The session ended.")); + } + // Running handlers finish on their own threads; nothing new starts. + executor.shutdown(); + } + + private void respond(Object id, Object result, Map error) { + if (phase == Phase.EXITED) { + return; + } + Map message = message(id, null); + if (error != null) { + message.put("error", error); + } else { + message.put("result", result); + } + try { + writeEncoded(Framing.encode(message)); + } catch (Json.JsonException failure) { + // A result JSON cannot encode must not end the session. + diagnostics().terminal("result-encoding", failure, System.nanoTime()); + Map fallback = message(id, null); + fallback.put("error", toResponseError(failure, null)); + write(fallback); + } + } + + private void write(Map message) { + writeEncoded(Framing.encode(message)); + } + + private void writeEncoded(byte[] frame) { + synchronized (writeLock) { + OutputStream stream = output; + if (stream == null || phase == Phase.EXITED) { + return; + } + try { + stream.write(frame); + stream.flush(); + } catch (IOException error) { + // The host closed the pipe; the input side ends the session. + // The closed protocol pipe leaves the host owning the terminal process fact. + } + } + } + + /** + * The JSON-RPC error object for a handler failure. Only {@link PluginError} + * carries a plugin code; any other exception becomes a generic internal + * error so that stack traces and machine paths never reach the host's UI. + */ + static Map toResponseError(Throwable failure, Cancellation cancellation) { + Throwable error = unwrap(failure); + if (cancellation != null && cancellation.isCancelled() && error instanceof CancelledException) { + return error(Protocol.REQUEST_CANCELLED, "The request was cancelled."); + } + if (error instanceof PluginError) { + Map response = error(Protocol.REQUEST_FAILED, Protocol.boundedText(error.getMessage())); + response.put("data", singleton("code", ((PluginError) error).code())); + return response; + } + // Unexpected exceptions often embed absolute paths or internals; the + // caller logs only a fixed failure category to stderr. + return error(Protocol.INTERNAL_ERROR, "The plugin backend failed unexpectedly."); + } + + /** + * Stamps the canonical format on a build result, so a handler can return the + * plain document. A result in another format is a backend bug: Core would + * refuse it as {@code plugin.build.invalidOutput}, so it fails here with a log. + */ + static Object buildResult(String method, Object result) { + String expected = BUILD_FORMATS.get(method); + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " must return a reply object."); + } + Map document = new LinkedHashMap<>(Json.object(result)); + if (expected != null) { + Object format = document.get("format"); + if (format != null && !expected.equals(format)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " returned another format."); + } + Object version = document.get("version"); + if (version != null && !(version instanceof Number && ((Number) version).doubleValue() == BUILD_DOCUMENT_VERSION)) { + throw new PluginSdkError("sdk.build.invalidResult", + method + " returned a version other than " + BUILD_DOCUMENT_VERSION + "."); + } + document.put("format", expected); + document.put("version", BUILD_DOCUMENT_VERSION); + } + if (Protocol.BUILD_EXECUTE.equals(method) || Protocol.BUILD_TEST.equals(method)) { + Object exit = document.get("exitCode"); + Object output = document.get("output"); + if (!(exit instanceof Number) || ((Number) exit).doubleValue() < Integer.MIN_VALUE + || ((Number) exit).doubleValue() > Integer.MAX_VALUE + || ((Number) exit).doubleValue() != ((Number) exit).longValue() + || !(output instanceof String) || Protocol.utf8Length((String) output) > Protocol.MAX_BUILD_RESULT_BYTES) { + throw new PluginSdkError("sdk.build.invalidResult", method + " needs an int32 exitCode and bounded output."); + } + document.put("exitCode", ((Number) exit).longValue()); + } + if (Protocol.BUILD_PREPARE_DEBUG.equals(method)) { + if (!(document.get("program") instanceof String) || !(document.get("workingDirectory") instanceof String) + || !stringList(document.get("arguments")) || !stringMap(document.get("environment")) + || document.size() != 4) { + throw new PluginSdkError("sdk.build.invalidResult", "Native debug preparation needs program, arguments, workingDirectory and environment only."); + } + } + if (Protocol.BUILD_PREPARE_RUN.equals(method)) { + Map executable = Json.object(document.get("executable")); + if (!("toolchain".equals(executable.get("kind")) || "command".equals(executable.get("kind"))) + || !(executable.get("value") instanceof String) || !(document.get("workingDirectory") instanceof String) + || !stringList(document.get("arguments")) || !stringMap(document.get("environment"))) { + throw new PluginSdkError("sdk.build.invalidResult", method + " needs a portable launch plan."); + } + } + // Workspace containment and domain facts remain Core/provider responsibilities. + if (Protocol.utf8Length(Json.stringify(document)) > Protocol.MAX_BUILD_RESULT_BYTES) { + throw new PluginSdkError("sdk.build.invalidResult", method + " exceeds the build-result size limit."); + } + return document; + } + + private static boolean stringList(Object value) { + if (!(value instanceof List)) return false; + for (Object item : (List) value) if (!(item instanceof String)) return false; + return true; + } + + private static boolean stringMap(Object value) { + if (!(value instanceof Map)) return false; + for (Map.Entry item : ((Map) value).entrySet()) { + if (!(item.getKey() instanceof String) || !(item.getValue() instanceof String)) return false; + } + return true; + } + + /** + * A function result as the JSON value Core accepts. A value JSON cannot + * encode, or one over Core's 1 MiB limit, fails here as a backend bug with a + * log line, instead of breaking the response frame or being refused by Core. + */ + static Object functionResult(Object result) { + String encoded; + try { + encoded = Json.stringify(result); + } catch (Json.JsonException error) { + throw new PluginSdkError("sdk.function.invalidResult", "The result is not JSON: " + error.getMessage()); + } + if (encoded.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_RESULT_BYTES) { + throw new PluginSdkError("sdk.function.invalidResult", + "The result exceeds " + Protocol.MAX_RESULT_BYTES + " bytes."); + } + return result; + } + + private static boolean offers(Object entry, int version) { + if (!(entry instanceof Map)) { + return false; + } + Object versions = ((Map) entry).get("versions"); + if (!(versions instanceof List)) { + return false; + } + for (Object offered : (List) versions) { + if (offered instanceof Number && ((Number) offered).doubleValue() == version) { + return true; + } + } + return false; + } + + /** {@code capabilities.experimental}, or an empty map. */ + private static Map experimental(Object capabilities) { + Object experimental = capabilities instanceof Map ? ((Map) capabilities).get("experimental") : null; + return experimental instanceof Map ? Json.object(experimental) : Collections.emptyMap(); + } + + /** The JSON-RPC ID as a map key; numbers and strings never collide. */ + private static String requestKey(Object id) { + if (id instanceof Number) { + Number number = (Number) id; + return "number:" + (number.doubleValue() == number.longValue() ? Long.toString(number.longValue()) : number); + } + return (id instanceof String ? "string:" : "other:") + id; + } + + private static Map message(Object id, String method) { + Map message = new LinkedHashMap<>(); + message.put("jsonrpc", "2.0"); + if (id != null || method == null) { + message.put("id", id); + } + if (method != null) { + message.put("method", method); + } + return message; + } + + private static Map error(int code, String text) { + Map error = new LinkedHashMap<>(); + error.put("code", code); + error.put("message", text); + return error; + } + + private static Map singleton(String key, Object value) { + Map map = new LinkedHashMap<>(); + map.put(key, value); + return map; + } + + /** The failure inside {@code CompletableFuture}'s wrappers, from {@code join()} or {@code get()}. */ + static Throwable unwrap(Throwable error) { + Throwable current = error; + while ((current instanceof CompletionException || current instanceof ExecutionException) && current.getCause() != null) { + current = current.getCause(); + } + return current; + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } + + /** The {@code { contextID, generation }} the host sent, or null. */ + private static Map workspaceContext(Object value) { + return Protocol.isContextReference(value) ? Host.contextReference(Json.object(value)) : null; + } + + /** + * The {@code { pluginID }} of the plugin that called a function through the + * relay, or null. Core adds it only to a relayed call, and only as exactly + * {@code { pluginID }}; anything else is not a caller. + */ + private Map callerReference(Object value) { + if (!negotiated.functions() || !(value instanceof Map)) { + return null; + } + Map caller = (Map) value; + Object pluginId = caller.get("pluginID"); + if (caller.size() != 1 || !(pluginId instanceof String) || ((String) pluginId).isEmpty()) { + return null; + } + return Collections.singletonMap("pluginID", pluginId); + } + + /** The session's wire, for host services. */ + private final class Wire implements HostChannel.Transport { + @Override + public boolean negotiated() { + return negotiated.functions(); + } + + @Override + public boolean ready() { + return phase == Phase.READY; + } + + @Override + public HostChannel.Sent send(String method, Object params) { + return Backend.this.send(method, params); + } + + @Override + public void notify(String method, Object params) { + Map notification = message(null, method); + notification.put("params", params); + write(notification); + } + + @Override + public void log(String message) { + Backend.this.diagnostics().degraded("notification", "subscription_queue_full"); + } + + @Override + public void log(String message, Throwable error) { + Backend.this.diagnostics().terminal("notification", error, System.nanoTime()); + } + + @Override + public void execute(Runnable task) { + executor.execute(task); + } + } + + /** One host request being handled. */ + private static final class Call { + final Cancellation cancellation; + final String functionId; + + Call(Cancellation cancellation, String functionId) { + this.cancellation = cancellation; + this.functionId = functionId; + } + } + + /** One request this backend sent to the host. */ + private static final class Pending { + final CompletableFuture future; + final String method; + + Pending(CompletableFuture future, String method) { + this.future = future; + this.method = method; + } + } + + /** Daemon threads, so a handler still running never keeps the process alive after exit. */ + private static final class ThreadNamer implements java.util.concurrent.ThreadFactory { + private final AtomicInteger next = new AtomicInteger(1); + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "lithe-sdk-call-" + next.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java new file mode 100644 index 0000000..6eb8e01 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java @@ -0,0 +1,143 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * What a handler gets besides its params: the call's cancellation, tools and + * host requests that end with the call, the backend's log, and progress for + * plugin functions or bounded build operations. + */ +public final class CallContext { + /** Sends one progress report; absent for model, dependency and discovery requests. */ + interface ProgressSink { + void report(String message, Double percentage); + default void report(String message, Double percentage, String output) { report(message, percentage); } + } + + private final java.util.concurrent.atomic.AtomicBoolean quietSuccess = new java.util.concurrent.atomic.AtomicBoolean(); + private final Cancellation cancellation; + private final Backend backend; + private final String functionId; + private final String operationId; + private final ProgressSink progress; + private final Host host; + private final Map workspaceContext; + private final Map caller; + + CallContext(Cancellation cancellation, Backend backend, String functionId, String operationId, ProgressSink progress, + Host host, Map workspaceContext, Map caller) { + this.cancellation = cancellation; + this.backend = backend; + this.functionId = functionId; + this.operationId = operationId; + this.progress = progress; + this.host = host; + this.workspaceContext = workspaceContext; + this.caller = caller; + } + + /** + * Cancelled when the host cancels the call, the backend shuts down, or the + * call ends; work a handler leaves running after it returned is stopped. + */ + public Cancellation cancellation() { + return cancellation; + } + + public boolean isCancelled() { + return cancellation.isCancelled(); + } + + /** Throws {@link CancelledException} once the call was cancelled. */ + public void throwIfCancelled() { + cancellation.throwIfCancelled(); + } + + /** + * Runs a tool that belongs to this call: cancelling the call or ending it + * stops the tool, and the backend shutting down ends it. + */ + public Processes.Result run(List command, Processes.Options options) throws IOException { + Processes.Options settings = options == null ? new Processes.Options() : options.copy(); + settings.listenerFailure(() -> diagnostics().degraded("notification", "output_listener_failed")); + Cancellation own = settings.cancellation(); + settings.cancellation(own == null ? cancellation : cancellation.combinedWith(own)); + return Processes.run(command, settings); + } + + /** Runs a tool that belongs to this call with default options. */ + public Processes.Result run(List command) throws IOException { + return run(command, null); + } + + public void suppressSuccessDiagnostics() { quietSuccess.set(true); } + boolean quietSuccess() { return quietSuccess.get(); } + + public Diagnostics diagnostics() { return new Diagnostics(backend, operationId); } + + /** + * Reports progress of a function or bounded build call. Function messages + * are cut to 1024 bytes, build messages to 4096; percentages are rounded to + * 0-100. Reports after cancellation or completion are dropped. + */ + public void progress(String message, Double percentage) { progress(message, percentage, null); } + + /** Build calls may additionally stream up to 64 KiB of output per report. */ + public void progress(String message, Double percentage, String output) { + if (progress != null && !cancellation.isCancelled()) progress.report(message, percentage, output); + } + + /** The function this call runs, or null for a build or LSP request. */ + public String functionId() { + return functionId; + } + + /** + * The wire operation ID of a function or bounded build call, otherwise null. + * It identifies the call in diagnostics and, when the request has no usable + * operation ID, falls back to the JSON-RPC request ID: do not use it as a + * {@code parentOperationID}. {@link #host()} already sends the right one. + */ + public String operationId() { + return operationId; + } + + /** + * Host services that belong to this call: requests still unanswered when + * the call is cancelled or ends fail with {@link CancelledException} and + * are cancelled on the wire. A subscription created here outlives the call + * until it is disposed. + */ + public Host host() { + return host; + } + + /** + * The {@code { contextID, generation }} of the workspace a function was + * invoked for, or null: for other calls and for an invocation outside a + * workspace. Pass it to the + * {@link Host} methods that name a context. + */ + public Map workspaceContext() { + return workspaceContext; + } + + /** + * The plugin that called this function through the relay: an + * unmodifiable {@code { pluginID }}, written by Core from the calling + * session. Null when the host started the call, and for calls that are not + * function invocations. + * Decide by who asks from this, never from a plugin ID in the params, + * which any caller can write. + */ + public Map caller() { + return caller; + } + + /** The {@code pluginID} of {@link #caller()}, or null when there is no calling plugin. */ + public String callerPluginId() { + return caller == null ? null : (String) caller.get("pluginID"); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java new file mode 100644 index 0000000..d80cd7d --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java @@ -0,0 +1,112 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayList; +import java.util.List; + +/** + * Cancellation of one call, or of work a plugin manages itself. Listeners run + * once, on the thread that cancels; a listener added after cancellation runs + * immediately. A listener that throws is logged to stderr and does not keep + * the others, or the thread that cancelled, from running on. Cancelling never interrupts threads, because an interrupt + * closes NIO channels a handler may be writing state through; long work checks + * {@link #isCancelled()} or {@link #throwIfCancelled()} instead. + */ +public final class Cancellation { + private final Object lock = new Object(); + private final List listeners = new ArrayList<>(); + private String reason; + private final Runnable listenerFailure; + public Cancellation() { this(() -> {}); } + Cancellation(Runnable listenerFailure) { this.listenerFailure = listenerFailure; } + + /** Cancels with {@code reason}; later calls have no effect. */ + public void cancel(String reason) { + List pending; + synchronized (lock) { + if (this.reason != null) { + return; + } + this.reason = reason == null ? "The request was cancelled." : reason; + pending = new ArrayList<>(listeners); + listeners.clear(); + } + for (Runnable listener : pending) { + runIsolated(listener); + } + } + + public boolean isCancelled() { + synchronized (lock) { + return reason != null; + } + } + + /** Throws {@link CancelledException} once cancelled. */ + public void throwIfCancelled() { + String current; + synchronized (lock) { + current = reason; + } + if (current != null) { + throw new CancelledException(current); + } + } + + /** + * Runs {@code listener} on cancellation. The returned handle removes it, + * for work that finished first. + */ + public Registration onCancel(Runnable listener) { + synchronized (lock) { + if (reason == null) { + listeners.add(listener); + return () -> { + synchronized (lock) { + listeners.remove(listener); + } + }; + } + } + runIsolated(listener); + return () -> {}; + } + + /** + * A token cancelled when either this one or {@code other} is; for work that + * a plugin may also stop for its own reasons. + */ + public Cancellation combinedWith(Cancellation other) { + Cancellation combined = new Cancellation(listenerFailure); + Registration first = onCancel(() -> combined.cancel(reasonOrDefault())); + Registration second = other.onCancel(() -> combined.cancel(other.reasonOrDefault())); + combined.onCancel(() -> { + first.remove(); + second.remove(); + }); + return combined; + } + + private void runIsolated(Runnable listener) { + try { + listener.run(); + } catch (RuntimeException error) { + listenerFailure.run(); + } + } + + /** The reason it was cancelled with, or the default text before that. */ + String reason() { + return reasonOrDefault(); + } + + private String reasonOrDefault() { + synchronized (lock) { + return reason == null ? "The request was cancelled." : reason; + } + } + + /** Removes a cancellation listener. */ + public interface Registration { + void remove(); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java new file mode 100644 index 0000000..dd01676 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java @@ -0,0 +1,14 @@ +package io.github.litheidea.plugin.sdk; + +/** + * Thrown when the call a piece of work belongs to was cancelled or ended. + * A handler normally lets it propagate; the SDK then answers the host with + * {@code RequestCancelled}. + */ +public class CancelledException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public CancelledException(String message) { + super(message); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java new file mode 100644 index 0000000..77f422a --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java @@ -0,0 +1,73 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** Typed facts for the host's litheLogging 1 catalog; never accepts message or payload text. */ +public final class Diagnostics { + static final long MAX_INTEGER = 9007199254740991L; + static final Set OPERATIONS = new HashSet<>(Arrays.asList( + "initialize", "shutdown", "notification", "function-call", "result-encoding", + "lithe/build/model", "lithe/build/dependencies", "lithe/build/execute", "lithe/build/test", + "lithe/build/discoverTests", "lithe/build/prepareRun", "lithe/build/prepareDebug", + "lithe/build/runEntrypoints", + "lithe/vcs/status", "lithe/vcs/baseContent", "lithe/vcs/history", "lithe/vcs/fileHistory", + "lithe/vcs/annotate", "lithe/vcs/checkin", "lithe/vcs/rollback", "lithe/vcs/update", + "lithe/vcs/fileOperation", "lithe/vcs/resolve", "lithe/vcs/cleanup", + "lithe/keymap/import")); + private final Backend backend; + private final String operationId; + + Diagnostics(Backend backend, String operationId) { + this.backend = backend; + this.operationId = operationId; + } + + public void degraded(String operation, String code, Long count) { record("degraded", operation, code, count, null); } + public void recovered(String operation, String code, Long count) { record("recovered", operation, code, count, null); } + public void degraded(String operation, String code) { degraded(operation, code, null); } + public void recovered(String operation, String code) { recovered(operation, code, null); } + + static boolean token(String value, int maximum) { + return value != null && value.length() > 0 && value.length() <= maximum && value.matches("[A-Za-z0-9._:/\\-$]+"); + } + + static String requestOperationId(String operationId, Object requestId) { + if (token(operationId, 128)) return operationId; + String fallback = requestId instanceof String ? (String) requestId : null; + if (requestId instanceof Number) { + double number = ((Number) requestId).doubleValue(); + if (Double.isFinite(number) && Math.abs(number) <= MAX_INTEGER && number == Math.rint(number)) { + fallback = Long.toString(((Number) requestId).longValue()); + } + } + return token(fallback, 128) ? fallback : null; + } + + void terminal(String operation, Throwable failure, long started) { + String code = null; + if (failure != null) { + Throwable error = Backend.unwrap(failure); + code = error instanceof PluginError ? ((PluginError) error).code() : "internal_error"; + } + record(failure == null ? "operationFinished" : "operationFailed", operation, code, null, + Math.min(MAX_INTEGER, Math.max(0, (System.nanoTime() - started) / 1000000))); + } + + private void record(String kind, String operation, String code, Long count, Long duration) { + if (!backend.loggingOperation(operation)) throw new PluginSdkError("sdk.logging.invalidOperation", "Diagnostics need a registered operation."); + if (code != null && !token(code, 64)) throw new PluginSdkError("sdk.logging.invalidCode", "Diagnostics need a controlled code."); + if (count != null && (count < 0 || count > MAX_INTEGER)) throw new PluginSdkError("sdk.logging.invalidCount", "Diagnostics need a nonnegative safe count."); + Map params = new LinkedHashMap<>(); + params.put("kind", kind); + params.put("operation", operation.length() <= 64 ? operation : "function-call"); + if (code != null) params.put("code", code); + if (count != null) params.put("count", count); + if (duration != null) params.put("durationMs", duration); + if (token(operationId, 128)) params.put("operationId", operationId); + backend.logFact(params); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java new file mode 100644 index 0000000..36f76f6 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java @@ -0,0 +1,138 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * LSP base-protocol framing: {@code Content-Length} headers followed by a UTF-8 + * JSON body. Lithe talks to every plugin backend this way, so the SDK owns the + * framing and plugin code never writes to stdout itself. + */ +public final class Framing { + /** Largest header block accepted from the host. */ + static final int MAX_HEADER_BYTES = 8192; + + /** Largest body accepted from the host. Larger frames end the session. */ + public static final int MAX_FRAME_BYTES = 64 * 1024 * 1024; + + /** Stands for a body that is not JSON; compared by identity, so no host message can mimic it. */ + public static final Object MALFORMED = new Object() { + @Override + public String toString() { + return "MALFORMED"; + } + }; + + private static final byte[] HEADER_END = {'\r', '\n', '\r', '\n'}; + + private Framing() {} + + /** A framing error the session cannot recover from. */ + public static final class FramingException extends RuntimeException { + private static final long serialVersionUID = 1L; + + FramingException(String message) { + super(message); + } + } + + /** Encodes one JSON-RPC message as a complete frame. */ + public static byte[] encode(Object message) { + byte[] body = Json.stringify(message).getBytes(StandardCharsets.UTF_8); + byte[] header = ("Content-Length: " + body.length + "\r\n\r\n").getBytes(StandardCharsets.US_ASCII); + byte[] frame = Arrays.copyOf(header, header.length + body.length); + System.arraycopy(body, 0, frame, header.length, body.length); + return frame; + } + + /** Incrementally splits a byte stream into decoded JSON-RPC messages. */ + public static final class Decoder { + private byte[] buffer = new byte[8192]; + private int length; + + /** + * Appends {@code count} bytes of {@code chunk} and returns every complete + * message they finished. A body that is not JSON is returned as + * {@link #MALFORMED} so the caller can report it without losing the + * framing position. + */ + public List push(byte[] chunk, int offset, int count) { + ensureCapacity(length + count); + System.arraycopy(chunk, offset, buffer, length, count); + length += count; + List messages = new ArrayList<>(); + int start = 0; + for (;;) { + int headerEnd = indexOfHeaderEnd(start); + int available = length - start; + // The same bound whether the header arrived whole or in pieces. + if ((headerEnd >= 0 && headerEnd - start > MAX_HEADER_BYTES) + || (headerEnd < 0 && available > MAX_HEADER_BYTES)) { + throw new FramingException("The message header is too long."); + } + if (headerEnd < 0) { + break; + } + int bodyLength = contentLength(new String(buffer, start, headerEnd - start, StandardCharsets.US_ASCII)); + int bodyStart = headerEnd + HEADER_END.length; + if ((long) length < (long) bodyStart + bodyLength) { + break; + } + String body = new String(buffer, bodyStart, bodyLength, StandardCharsets.UTF_8); + start = bodyStart + bodyLength; + try { + messages.add(Json.parse(body)); + } catch (Json.JsonException error) { + messages.add(MALFORMED); + } + } + if (start > 0) { + System.arraycopy(buffer, start, buffer, 0, length - start); + length -= start; + } + return messages; + } + + private int indexOfHeaderEnd(int from) { + for (int index = from; index + HEADER_END.length <= length; index++) { + if (buffer[index] == '\r' && buffer[index + 1] == '\n' + && buffer[index + 2] == '\r' && buffer[index + 3] == '\n') { + return index; + } + } + return -1; + } + + private void ensureCapacity(int required) { + if (required > buffer.length) { + buffer = Arrays.copyOf(buffer, Math.max(required, buffer.length * 2)); + } + } + } + + private static int contentLength(String header) { + for (String line : header.split("\r\n")) { + int separator = line.indexOf(':'); + if (separator < 0) { + continue; + } + if (!line.substring(0, separator).trim().equalsIgnoreCase("content-length")) { + continue; + } + String value = line.substring(separator + 1).trim(); + if (!value.matches("[0-9]+")) { + break; + } + // More than ten digits exceeds the limit whatever they are. + long length = value.length() > 10 ? Long.MAX_VALUE : Long.parseLong(value); + if (length > MAX_FRAME_BYTES) { + throw new FramingException("A message of " + value + " bytes exceeds the " + + MAX_FRAME_BYTES + "-byte limit."); + } + return (int) length; + } + throw new FramingException("A message has no valid Content-Length header."); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java new file mode 100644 index 0000000..fb0e988 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -0,0 +1,637 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.BooleanSupplier; + +/** + * Host services ({@code lithe/host/*}): credentials; workspace contexts, + * files, documents, the editor, previews, the browser, messages, and + * capability discovery; calls to other plugins' functions. Every method + * answers with a future and never blocks; failures the host reports arrive as + * {@link HostError}. + * + *

{@link Backend#host()} is usable once the session is ready. A handler's + * {@link CallContext#host()} belongs to its call: requests still unanswered + * when the call is cancelled or ends fail with {@link CancelledException} and + * are cancelled on the wire. At most 16 requests are on the wire at once; the + * rest wait their turn. + * + *

Contract: {@code contract/v1/README.md}, "Host services". + */ +public final class Host { + /** Receives a subscription's events, one at a time and in order. */ + @FunctionalInterface + public interface Listener { + void onEvent(Event event) throws Exception; + } + + /** One {@code lithe/host/subscriptions/notify}. */ + public static final class Event { + private final String subscriptionId; + private final long sequence; + private final boolean gap; + private final Object event; + + Event(String subscriptionId, long sequence, boolean gap, Object event) { + this.subscriptionId = subscriptionId; + this.sequence = sequence; + this.gap = gap; + this.event = event; + } + + public String subscriptionId() { + return subscriptionId; + } + + /** Starts at 1 and grows by one per event of the subscription. */ + public long sequence() { + return sequence; + } + + /** + * True when events before this one were lost, so state built from + * earlier events should be refreshed, for example by rescanning. + */ + public boolean gap() { + return gap; + } + + /** The event, usually an object. */ + public Object event() { + return event; + } + } + + /** A host subscription, such as a file watch or registered editor actions. */ + public static final class Subscription { + private final String id; + private final BooleanSupplier live; + private final HostChannel channel; + + Subscription(String id, BooleanSupplier live, HostChannel channel) { + this.id = id; + this.live = live; + this.channel = channel; + } + + public String id() { + return id; + } + + /** True once disposed here or the session ended. */ + public boolean isDisposed() { + return !live.getAsBoolean(); + } + + /** Stops routing events at once and asks the host to dispose the subscription. */ + public CompletableFuture dispose() { + return channel.dispose(id); + } + } + + private final HostChannel channel; + private final List scope; + /** The wire operation ID of the function call this Host belongs to, or null; the default parent of {@link Functions#invoke}. */ + private final String parentOperationId; + private final Credentials credentials = new Credentials(); + private final Subscriptions subscriptions = new Subscriptions(); + private final Workspace workspace = new Workspace(); + private final Documents documents = new Documents(); + private final Editor editor = new Editor(); + private final Preview preview = new Preview(); + private final Browser browser = new Browser(); + private final Window window = new Window(); + private final Functions functions = new Functions(); + + Host(HostChannel channel, List scope, String parentOperationId) { + this.channel = channel; + this.scope = Collections.unmodifiableList(new ArrayList<>(scope)); + this.parentOperationId = parentOperationId; + } + + /** Whether the host offered plugin functions ({@code litheFunctions}); false before {@code initialize}. */ + public boolean negotiated() { + return channel.negotiated(); + } + + /** + * The same services, with requests also cancelled by {@code cancellation}, + * for work a plugin may stop for its own reasons. Calls to other plugins + * keep the parent call of this Host. + */ + public Host withCancellation(Cancellation cancellation) { + if (cancellation == null) { + throw new IllegalArgumentException("A cancellation must not be null."); + } + List combined = new ArrayList<>(scope); + combined.add(cancellation); + return new Host(channel, combined, parentOperationId); + } + + /** + * Sends any {@code lithe/host/*} request, including methods a later host + * adds; {@link #supports} says whether the session may call it. + */ + public CompletableFuture request(String method, Object params) { + return channel.request(method, params, scope); + } + + /** + * Sends a request that answers {@code { subscriptionID }} and routes the + * subscription's events to {@code listener}. + */ + public CompletableFuture subscribe(String method, Object params, Listener listener) { + return channel.subscribe(method, params, listener, scope); + } + + /** + * {@code { protocolVersion, backendAuthority, services, limits }}, asked + * once per session. + */ + public CompletableFuture> capabilities() { + return channel.capabilities(); + } + + /** Whether this session may call {@code method}, as {@link #capabilities} lists it. */ + public CompletableFuture supports(String method) { + return channel.supports(method); + } + + public Credentials credentials() { + return credentials; + } + + public Subscriptions subscriptions() { + return subscriptions; + } + + public Workspace workspace() { + return workspace; + } + + public Documents documents() { + return documents; + } + + public Editor editor() { + return editor; + } + + public Preview preview() { + return preview; + } + + public Browser browser() { + return browser; + } + + public Terminal terminal() { + return new Terminal(); + } + + public Window window() { + return window; + } + + /** Calls to functions other plugins export. */ + public Functions functions() { + return functions; + } + + /** + * {@code { contextID, generation }} of a context reference or of a full + * context from {@code listContexts} or {@code getContext}, so either can be + * passed on. + * + * @throws PluginSdkError {@code sdk.host.invalidContext} for anything else + */ + public static Map contextReference(Map context) { + Object id = context == null ? null : context.get("contextID"); + Object generation = context == null ? null : context.get("generation"); + if (!(id instanceof String) || !Protocol.isCredentialKey((String) id) || !Protocol.isGeneration(generation)) { + throw new PluginSdkError("sdk.host.invalidContext", + "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\", and a positive generation."); + } + Map reference = new LinkedHashMap<>(); + reference.put("contextID", id); + reference.put("generation", ((Number) generation).longValue()); + return Collections.unmodifiableMap(reference); + } + + /** Secrets in the operating system's credential store, scoped to the plugin. */ + public final class Credentials { + private Credentials() {} + + /** The stored secret, or null when nothing is stored under {@code key}. */ + public CompletableFuture get(String key) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + return channel.request(Protocol.HOST_CREDENTIALS_GET, params("key", key), scope).thenApply(result -> { + if (result == null) { + return null; + } + Object secret = result instanceof Map ? ((Map) result).get("secret") : null; + if (!(secret instanceof String)) { + throw new PluginSdkError("sdk.host.invalidResult", "The host answered credentials/get without a secret."); + } + return (String) secret; + }); + } + + public CompletableFuture set(String key, String secret) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + if (secret == null || secret.getBytes(StandardCharsets.UTF_8).length > Protocol.MAX_CREDENTIAL_SECRET_BYTES) { + return failed(new PluginSdkError("sdk.credentials.invalidSecret", "A secret is a string of at most 16 KiB.")); + } + Map params = params("key", key); + params.put("secret", secret); + return channel.request(Protocol.HOST_CREDENTIALS_SET, params, scope).thenApply(result -> null); + } + + /** Deletes the secret; also succeeds when nothing was stored. */ + public CompletableFuture delete(String key) { + if (!Protocol.isCredentialKey(key)) { + return failed(invalidKey()); + } + return channel.request(Protocol.HOST_CREDENTIALS_DELETE, params("key", key), scope).thenApply(result -> null); + } + } + + public final class Subscriptions { + private Subscriptions() {} + + /** Disposes a subscription by ID; also succeeds for an unknown or disposed one. */ + public CompletableFuture dispose(String subscriptionId) { + return channel.dispose(subscriptionId); + } + } + + /** + * Workspace contexts and files. Every method but + * {@link #listContexts} names a context: a reference from + * {@link CallContext#workspaceContext()}, or a context from + * {@link #listContexts}. + */ + public final class Workspace { + private Workspace() {} + + /** {@code { revision, contexts }}. */ + public CompletableFuture> listContexts() { + return object(Protocol.HOST_WORKSPACE_LIST_CONTEXTS, channel.request( + Protocol.HOST_WORKSPACE_LIST_CONTEXTS, new LinkedHashMap(), scope)); + } + + public CompletableFuture> getContext(Map context) { + return scoped(Protocol.HOST_WORKSPACE_GET_CONTEXT, context, null); + } + + /** {@code { folders }}. */ + public CompletableFuture> getFolders(Map context) { + return scoped(Protocol.HOST_WORKSPACE_GET_FOLDERS, context, null); + } + + /** {@code params}: {@code resource, cursor?, limit?}. */ + public CompletableFuture> readDirectory(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_READ_DIRECTORY, context, params); + } + + /** {@code params}: {@code resource}. */ + public CompletableFuture> stat(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_STAT, context, params); + } + + /** {@code params}: {@code resource, maximumBytes?}. */ + public CompletableFuture> readFile(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_READ_FILE, context, params); + } + + /** + * Watches {@code resource, recursive?}; events are + * {@code { rootID, changedPaths, requiresRescan }}. + */ + public CompletableFuture watch(Map context, Map params, Listener listener) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.subscribe(Protocol.HOST_WORKSPACE_WATCH, message, listener, scope); + } + + /** {@code params}: root {@code resource, query, fileMask?, cursor?, limit?}. */ + public CompletableFuture> findFiles(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_FIND_FILES, context, params); + } + + /** {@code params}: root {@code resource, pattern}, and optional search options. */ + public CompletableFuture> findText(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_FIND_TEXT, context, params); + } + } + + /** Open documents, read from their live buffers. */ + public final class Documents { + private Documents() {} + + /** {@code { documents }}. */ + public CompletableFuture> list(Map context) { + return scoped(Protocol.HOST_DOCUMENTS_LIST, context, null); + } + + /** {@code params}: {@code documentID}; answers {@code { document, text }}. */ + public CompletableFuture> getSnapshot(Map context, Map params) { + return scoped(Protocol.HOST_DOCUMENTS_GET_SNAPSHOT, context, params); + } + } + + /** The text editor. */ + public final class Editor { + private Editor() {} + + /** The foreground text tab's document summary, or null. */ + public CompletableFuture> getActive(Map context) { + return scoped(Protocol.HOST_EDITOR_GET_ACTIVE, context, null); + } + + /** {@code params}: {@code documentID}. */ + public CompletableFuture> getSelections(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_GET_SELECTIONS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, edits}. */ + public CompletableFuture> applyEdits(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_APPLY_EDITS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, selections, replacements}. */ + public CompletableFuture> replaceSelections(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_REPLACE_SELECTIONS, context, params); + } + + /** {@code params}: {@code documentID, expectedVersion, at, text}. */ + public CompletableFuture> insertText(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_INSERT_TEXT, context, params); + } + + /** {@code params}: {@code resource, activation?, range?, tab?}. */ + public CompletableFuture> open(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_OPEN, context, params); + } + + /** {@code params}: {@code resource, activation?, range?, tab?}. */ + public CompletableFuture> reveal(Map context, Map params) { + return scoped(Protocol.HOST_EDITOR_REVEAL, context, params); + } + + /** + * Registers editor actions ({@code id, function, selector}) that invoke + * one of the backend's functions; disposing the subscription removes them. + */ + public CompletableFuture registerActions(Map context, Map params) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return channel.subscribe(Protocol.HOST_EDITOR_REGISTER_ACTIONS, message, null, scope); + } + } + + /** HTML previews. */ + public final class Preview { + private Preview() {} + + /** {@code params}: HTML {@code resource, presentation?, range?}. */ + public CompletableFuture> openHtml(Map context, Map params) { + return scoped(Protocol.HOST_PREVIEW_OPEN_HTML, context, params); + } + } + + /** The system browser. */ + public final class Browser { + private Browser() {} + + /** {@code params}: exactly one of an HTTP(S) {@code url} or an HTML {@code resource}. */ + public CompletableFuture> openExternal(Map context, Map params) { + return scoped(Protocol.HOST_BROWSER_OPEN_EXTERNAL, context, params); + } + } + + /** Native terminals private to the backend session and workspace. */ + public final class Terminal { + private Terminal() {} + /** Params: executable, arguments?, title?, cwd?, environment?, show?. */ + public CompletableFuture> create(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_CREATE, context, params); + } + public CompletableFuture> show(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_SHOW, context, params); + } + public CompletableFuture> close(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_CLOSE, context, params); + } + /** Restarts the saved argv, restoring only the chosen plain display suffix. */ + public CompletableFuture> reopen(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_REOPEN, context, params); + } + /** Forgets the handle and its retained display history. */ + public CompletableFuture> dispose(Map context, Map params) { + return scoped(Protocol.HOST_TERMINAL_DISPOSE, context, params); + } + /** Params: terminalID; disposing the subscription does not close the terminal. */ + public CompletableFuture onExit(Map context, Map params) { + Map message; + try { message = withContext(context, params); } + catch (PluginSdkError error) { return failed(error); } + return channel.subscribe(Protocol.HOST_TERMINAL_ON_EXIT, message, null, scope); + } + } + + /** + * Messages in the window. {@code params}: {@code text, + * actions?}; answers {@code { selectedIndex }}, null on dismissal. + */ + public final class Window { + private Window() {} + + public CompletableFuture> showInformation(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_INFORMATION, context, params); + } + + public CompletableFuture> showWarning(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_WARNING, context, params); + } + + public CompletableFuture> showError(Map context, Map params) { + return scoped(Protocol.HOST_WINDOW_SHOW_ERROR, context, params); + } + } + + /** + * Calls to functions other plugins export, relayed by Core. The plugin's + * manifest must declare each function it calls. Both methods fail with a + * {@link HostError} {@code plugin.host.unavailable} when the host did not + * offer plugin functions, without sending anything, and a malformed + * argument fails with {@code sdk.functions.invalidCall} (a malformed + * context with {@code sdk.host.invalidContext}), also without sending + * anything. + * + *

A provider's own failure arrives as a {@link HostError} with code + * {@code plugin.function.failed}; {@link HostError#pluginErrorCode()} is + * its error code. Other relay failures have their own + * {@code plugin.function.*} codes, see {@link HostError#CODES}. + */ + public final class Functions { + private Functions() {} + + /** + * {@code { providers: [{ pluginID, version }] }}: the enabled plugins + * other than this one that export {@code functionId}, sorted by plugin + * ID. A listed provider's backend need not be running. + */ + public CompletableFuture> providers(String functionId) { + if (!Protocol.isFunctionId(functionId)) { + return failed(invalidCall("A functionID is dot-separated lowerCamelCase segments of at most 128 bytes.")); + } + return object(Protocol.HOST_FUNCTIONS_PROVIDERS, channel.request( + Protocol.HOST_FUNCTIONS_PROVIDERS, params("functionID", functionId), scope)); + } + + /** + * Calls one provider's exported function in the workspace {@code context} + * (a reference from {@link CallContext#workspaceContext()}, or a context + * from {@code workspace().listContexts()}) and answers {@code { value }}, + * the provider's result, where {@code value} may be null. Only the + * fields listed here are sent. {@code call}: + *

    + *
  • {@code pluginID}: the provider, a non-empty string; required;
  • + *
  • {@code functionID}: the exported function; required;
  • + *
  • {@code params}: an object, omitted when absent;
  • + *
  • {@code timeoutMilliseconds}: a positive integer; Core defaults to + * 60 000 and caps it at 600 000;
  • + *
  • {@code parentOperationID}: a string of 1-128 bytes. When absent + * and this Host belongs to a function call, that call's wire operation + * ID is sent, so Core knows the new call belongs to it; otherwise the + * field is omitted and Core counts the new call as a child of every + * relayed call this backend is serving.
  • + *
+ * When the call this Host belongs to is cancelled or ends, the relayed + * call is cancelled on the wire and the future fails with + * {@link CancelledException}. + */ + public CompletableFuture> invoke(Map context, Map call) { + Map message; + try { + message = relayParams(context, call); + } catch (PluginSdkError error) { + return failed(error); + } + return object(Protocol.HOST_FUNCTIONS_INVOKE, channel.request(Protocol.HOST_FUNCTIONS_INVOKE, message, scope)); + } + } + + /** The wire params of a relayed call: the listed fields of {@code call}, never another one. */ + private Map relayParams(Map context, Map call) { + if (call == null) { + throw invalidCall("A call is { pluginID, functionID, params?, timeoutMilliseconds?, parentOperationID? }."); + } + Object pluginId = call.get("pluginID"); + if (!(pluginId instanceof String) || ((String) pluginId).isEmpty()) { + throw invalidCall("A call's pluginID is a non-empty string."); + } + Object functionId = call.get("functionID"); + if (!(functionId instanceof String) || !Protocol.isFunctionId((String) functionId)) { + throw invalidCall("A functionID is dot-separated lowerCamelCase segments of at most 128 bytes."); + } + Map message = new LinkedHashMap<>(); + message.put("pluginID", pluginId); + message.put("functionID", functionId); + message.put("context", contextReference(context)); + Object params = call.get("params"); + if (params != null) { + if (!(params instanceof Map)) { + throw invalidCall("A call's params is an object."); + } + message.put("params", params); + } + Object timeout = call.get("timeoutMilliseconds"); + if (timeout != null) { + if (!Protocol.isGeneration(timeout)) { + throw invalidCall("A call's timeoutMilliseconds is a positive integer."); + } + message.put("timeoutMilliseconds", ((Number) timeout).longValue()); + } + Object parent = call.get("parentOperationID"); + if (parent == null) { + parent = parentOperationId; + } else if (!Protocol.isParentOperationId(parent)) { + throw invalidCall("A call's parentOperationID is a string of 1-128 bytes."); + } + if (parent != null) { + message.put("parentOperationID", parent); + } + return message; + } + + private static PluginSdkError invalidCall(String message) { + return new PluginSdkError("sdk.functions.invalidCall", message); + } + + /** A method whose params name a workspace context. */ + private CompletableFuture> scoped(String method, Map context, Map params) { + Map message; + try { + message = withContext(context, params); + } catch (PluginSdkError error) { + return failed(error); + } + return object(method, channel.request(method, message, scope)); + } + + private static Map withContext(Map context, Map params) { + Map message = params == null ? new LinkedHashMap() : new LinkedHashMap(params); + message.put("context", contextReference(context)); + return message; + } + + /** The result as an object, or null; anything else is a host bug. */ + private static CompletableFuture> object(String method, CompletableFuture response) { + return response.thenApply(result -> { + if (result == null) { + return null; + } + if (!(result instanceof Map)) { + throw new PluginSdkError("sdk.host.invalidResult", method + " answered with something other than an object."); + } + return Json.object(result); + }); + } + + private static Map params(String key, Object value) { + Map params = new LinkedHashMap<>(); + params.put(key, value); + return params; + } + + private static PluginSdkError invalidKey() { + return new PluginSdkError("sdk.credentials.invalidKey", + "A credential key is 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\"."); + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java new file mode 100644 index 0000000..995e7e4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java @@ -0,0 +1,495 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.RejectedExecutionException; + +/** + * The session's host-request state. The backend owns the wire; this class + * owns what Core expects of a well-behaved client -- at most 16 unanswered + * host requests, cancellation through {@code $/cancelRequest}, and + * subscription events routed by ID, in order, off the reader thread. + * + *

Contract: {@code contract/v1/README.md}, "Host services". + */ +final class HostChannel { + /** Events kept for a subscription whose creating request is still unanswered. */ + static final int MAX_EARLY_EVENTS = 128; + + /** The backend's wire. */ + interface Transport { + /** Whether the host offered plugin functions ({@code litheFunctions}); false before {@code initialize}. */ + boolean negotiated(); + + boolean ready(); + + /** Writes a request; its response settles when the host answers or the session ends. */ + Sent send(String method, Object params); + + void notify(String method, Object params); + + void log(String message); + + void log(String message, Throwable error); + + /** Runs plugin code off the reader thread. */ + void execute(Runnable task); + } + + /** A request on the wire. */ + static final class Sent { + final String id; + final CompletableFuture response; + + Sent(String id, CompletableFuture response) { + this.id = id; + this.response = response; + } + } + + private enum State { QUEUED, SENDING, SENT } + + /** One host request; settles for its caller once. */ + private static final class Entry { + final String method; + final Object params; + final CompletableFuture future = new CompletableFuture<>(); + final List registrations = new ArrayList<>(); + State state = State.QUEUED; + boolean settled; + /** Cancelled while being written: {@code $/cancelRequest} follows the write. */ + boolean cancelAfterWrite; + String id; + + Entry(String method, Object params) { + this.method = method; + this.params = params; + } + } + + /** A live subscription. */ + private static final class Route { + final String id; + final Host.Listener listener; + final ArrayDeque pending = new ArrayDeque<>(); + volatile boolean live = true; + long lastSequence; + boolean draining; + + Route(String id, Host.Listener listener) { + this.id = id; + this.listener = listener; + } + + boolean isLive() { + return live; + } + } + + private static final class Early { + final String subscriptionId; + final long sequence; + final Object event; + + Early(String subscriptionId, long sequence, Object event) { + this.subscriptionId = subscriptionId; + this.sequence = sequence; + this.event = event; + } + } + + private final Transport transport; + private final Object lock = new Object(); + private final ArrayDeque queue = new ArrayDeque<>(); + private final Map routes = new HashMap<>(); + private final List early = new ArrayList<>(); + private int inFlight; + /** Subscribing requests not yet answered; early events wait only while there are some. */ + private int subscribing; + private CompletableFuture> capabilities; + private boolean closed; + + HostChannel(Transport transport) { + this.transport = transport; + } + + boolean negotiated() { + return transport.negotiated(); + } + + /** + * Sends {@code method} once a slot is free. Cancelling any of + * {@code scope} rejects the caller at once with {@link CancelledException}; + * a request already sent is cancelled on the wire, and never sent again, + * because a cancelled mutation may already have taken effect. + */ + CompletableFuture request(String method, Object params, List scope) { + if (method == null || !method.startsWith(Protocol.HOST_PREFIX)) { + return failed(new PluginSdkError("sdk.host.method", + method + " is not a host method; host requests are lithe/host/*.")); + } + if (!open()) { + return failed(notReady()); + } + if (!transport.negotiated()) { + // The answer Core would give, without the round trip. + return failed(unavailable(method, + "The host did not negotiate plugin functions (litheFunctions), which offer host services.")); + } + for (Cancellation cancellation : scope) { + try { + cancellation.throwIfCancelled(); + } catch (CancelledException error) { + return failed(error); + } + } + Entry entry = new Entry(method, params); + synchronized (lock) { + if (closed || !transport.ready()) { + return failed(notReady()); + } + queue.add(entry); + } + for (Cancellation cancellation : scope) { + Cancellation.Registration registration = cancellation.onCancel(() -> cancel(entry, cancellation)); + boolean settled; + synchronized (lock) { + settled = entry.settled; + if (!settled) { + entry.registrations.add(registration); + } + } + if (settled) { + registration.remove(); + } + } + drain(); + return entry.future; + } + + /** + * Sends a request whose result is {@code { subscriptionID }} and routes + * that subscription's events to {@code listener}, one at a time and in the + * order the host sent them. + */ + CompletableFuture subscribe(String method, Object params, Host.Listener listener, + List scope) { + synchronized (lock) { + subscribing++; + } + return request(method, params, scope).handle((result, error) -> { + try { + if (error != null) { + throw new CompletionException(Backend.unwrap(error)); + } + Object id = result instanceof Map ? ((Map) result).get("subscriptionID") : null; + if (!(id instanceof String) || !Protocol.isCredentialKey((String) id)) { + throw new PluginSdkError("sdk.host.invalidResult", method + " answered without a subscriptionID."); + } + String subscriptionId = (String) id; + Route route = new Route(subscriptionId, listener); + synchronized (lock) { + if (closed) { + throw new PluginSdkError("sdk.session.closed", "The session ended."); + } + routes.put(subscriptionId, route); + // Events the host sent before this answer was read. + for (Iterator events = early.iterator(); events.hasNext();) { + Early event = events.next(); + if (event.subscriptionId.equals(subscriptionId)) { + events.remove(); + emit(route, event.sequence, event.event); + } + } + } + return new Host.Subscription(subscriptionId, route::isLive, this); + } finally { + synchronized (lock) { + subscribing--; + if (subscribing == 0) { + early.clear(); + } + } + } + }); + } + + /** Stops routing a subscription's events at once and asks the host to dispose it. */ + CompletableFuture dispose(String subscriptionId) { + synchronized (lock) { + Route route = routes.remove(subscriptionId); + if (route != null) { + route.live = false; + route.pending.clear(); + } + if (closed || !transport.ready()) { + return CompletableFuture.completedFuture(null); + } + } + Map params = new LinkedHashMap<>(); + params.put("subscriptionID", subscriptionId); + return request(Protocol.HOST_SUBSCRIPTIONS_DISPOSE, params, Collections.emptyList()) + .thenApply(result -> null); + } + + /** Routes one {@code lithe/host/subscriptions/notify}. */ + void deliver(Map params) { + Object id = params.get("subscriptionID"); + if (!(id instanceof String)) { + return; + } + Object number = params.get("sequence"); + long sequence = number instanceof Number ? ((Number) number).longValue() : 0; + synchronized (lock) { + Route route = routes.get(id); + if (route != null) { + emit(route, sequence, params.get("event")); + } else if (subscribing > 0) { + if (early.size() < MAX_EARLY_EVENTS) { + early.add(new Early((String) id, sequence, params.get("event"))); + } else { + transport.log("Dropped an early subscription event: queue_full"); + } + } + // Otherwise the subscription was disposed; nothing follows a disposal. + } + } + + /** The cached {@code getCapabilities} answer; Core answers it itself. */ + CompletableFuture> capabilities() { + if (!transport.negotiated()) { + return failed(unavailable(Protocol.HOST_GET_CAPABILITIES, + "The host did not negotiate plugin functions (litheFunctions), which offer capability discovery.")); + } + CompletableFuture> answer; + synchronized (lock) { + if (capabilities != null) { + return capabilities.thenApply(result -> result); + } + answer = new CompletableFuture<>(); + capabilities = answer; + } + request(Protocol.HOST_GET_CAPABILITIES, null, Collections.emptyList()).whenComplete((result, error) -> { + if (error == null && result instanceof Map) { + answer.complete(Collections.unmodifiableMap(Json.object(result))); + return; + } + synchronized (lock) { + if (capabilities == answer) { + capabilities = null; + } + } + answer.completeExceptionally(error != null ? Backend.unwrap(error) + : new PluginSdkError("sdk.host.invalidResult", "getCapabilities answered without an object.")); + }); + return answer.thenApply(result -> result); + } + + /** + * Whether this session may call {@code method}, from + * {@code getCapabilities}; false when the host offered no plugin functions. + * A missing grant still fails the request. + */ + CompletableFuture supports(String method) { + if (!transport.negotiated()) { + return CompletableFuture.completedFuture(false); + } + return capabilities().thenApply(answer -> { + Object services = answer.get("services"); + if (!(services instanceof Map)) { + return false; + } + for (Object service : ((Map) services).values()) { + Object methods = service instanceof Map ? ((Map) service).get("methods") : null; + if (methods instanceof List && ((List) methods).contains(method)) { + return true; + } + } + return false; + }); + } + + /** Ends the channel with the session: queued requests fail, subscriptions end. */ + void close() { + List queued; + synchronized (lock) { + closed = true; + queued = new ArrayList<>(queue); + queue.clear(); + for (Route route : routes.values()) { + route.live = false; + route.pending.clear(); + } + routes.clear(); + early.clear(); + capabilities = null; + } + for (Entry entry : queued) { + settle(entry, null, new PluginSdkError("sdk.session.closed", "The session ended.")); + } + } + + private void drain() { + List starting = new ArrayList<>(); + synchronized (lock) { + while (!closed && inFlight < Protocol.MAX_PENDING_HOST_REQUESTS && !queue.isEmpty()) { + Entry entry = queue.poll(); + entry.state = State.SENDING; + inFlight++; + starting.add(entry); + } + } + for (Entry entry : starting) { + start(entry); + } + } + + /** Writes outside the lock, so a full pipe never blocks the reader thread's routing. */ + private void start(Entry entry) { + Sent sent; + try { + sent = transport.send(entry.method, entry.params); + } catch (RuntimeException error) { + // Params JSON cannot encode never reached the wire. + synchronized (lock) { + inFlight--; + } + settle(entry, null, error); + drain(); + return; + } + boolean cancelNow; + synchronized (lock) { + entry.id = sent.id; + entry.state = State.SENT; + cancelNow = entry.cancelAfterWrite; + } + if (cancelNow) { + transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", sent.id)); + } + sent.response.whenComplete((result, error) -> { + synchronized (lock) { + // The slot frees when Core answers, also after a cancellation: + // Core answers a cancelled request at once. + inFlight--; + } + settle(entry, result, error == null ? null : Backend.unwrap(error)); + drain(); + }); + } + + private void cancel(Entry entry, Cancellation cancellation) { + String id = null; + synchronized (lock) { + if (entry.settled) { + return; + } + if (entry.state == State.QUEUED) { + queue.remove(entry); + } else if (entry.state == State.SENDING) { + entry.cancelAfterWrite = true; + } else { + id = entry.id; + } + } + if (id != null) { + transport.notify(Protocol.CANCEL_REQUEST, Collections.singletonMap("id", id)); + } + settle(entry, null, new CancelledException(cancellation.reason())); + } + + /** Completes the caller's future once, on a handler thread. */ + private void settle(Entry entry, Object result, Throwable error) { + List registrations; + synchronized (lock) { + if (entry.settled) { + return; + } + entry.settled = true; + registrations = new ArrayList<>(entry.registrations); + entry.registrations.clear(); + } + for (Cancellation.Registration registration : registrations) { + registration.remove(); + } + Runnable complete = () -> { + if (error != null) { + entry.future.completeExceptionally(error); + } else { + entry.future.complete(result); + } + }; + try { + transport.execute(complete); + } catch (RejectedExecutionException ended) { + complete.run(); + } + } + + /** Queues one event; called with the lock held. */ + private void emit(Route route, long sequence, Object event) { + boolean gap = sequence != route.lastSequence + 1; + route.lastSequence = sequence; + route.pending.add(new Host.Event(route.id, sequence, gap, event)); + if (route.draining) { + return; + } + route.draining = true; + try { + transport.execute(() -> run(route)); + } catch (RejectedExecutionException ended) { + route.draining = false; + route.pending.clear(); + } + } + + /** Hands a subscription's events to its listener one at a time. */ + private void run(Route route) { + while (true) { + Host.Event event; + synchronized (lock) { + event = route.live ? route.pending.poll() : null; + if (event == null) { + route.draining = false; + route.pending.clear(); + return; + } + } + try { + if (route.listener != null) { + route.listener.onEvent(event); + } + } catch (Throwable error) { + transport.log("A subscription listener failed:", error); + } + } + } + + private boolean open() { + synchronized (lock) { + return !closed && transport.ready(); + } + } + + private static PluginSdkError notReady() { + return new PluginSdkError("sdk.session.notReady", "The session is not initialized."); + } + + private static HostError unavailable(String method, String message) { + return new HostError("plugin.host.unavailable", message, Protocol.METHOD_NOT_FOUND, null, method); + } + + private static CompletableFuture failed(Throwable error) { + CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(error); + return future; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java new file mode 100644 index 0000000..3730a02 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java @@ -0,0 +1,126 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The host refused or failed a request this backend sent. {@link #code()} is + * the stable {@code error.data.code}, such as {@code plugin.host.contextExpired}; + * {@link #rpcCode()} the JSON-RPC number; {@link #details()} the object a + * host may add, such as {@code { option }} or + * {@code { retryAfterMilliseconds }}. + */ +public final class HostError extends PluginSdkError { + private static final long serialVersionUID = 1L; + + /** + * Stable host failure codes and their JSON-RPC numbers, including the + * {@code plugin.function.*} codes of cross-plugin calls. A later host adds + * codes after the highest number here. + */ + public static final Map CODES; + private static final Map BY_RPC_CODE; + + static { + Map codes = new LinkedHashMap<>(); + codes.put("plugin.host.unavailable", -32601); + codes.put("plugin.host.invalidParams", -32602); + codes.put("plugin.host.failed", -32603); + codes.put("plugin.host.cancelled", -32800); + codes.put("plugin.host.permissionDenied", -32010); + codes.put("plugin.host.contextExpired", -32011); + codes.put("plugin.host.authorityUnsupported", -32012); + codes.put("plugin.host.versionConflict", -32013); + codes.put("plugin.host.limitExceeded", -32014); + codes.put("plugin.host.timeout", -32015); + codes.put("plugin.host.notFound", -32016); + codes.put("plugin.host.readOnly", -32017); + codes.put("plugin.host.unsupportedOption", -32018); + codes.put("plugin.host.preconditionFailed", -32019); + codes.put("plugin.host.busy", -32020); + codes.put("plugin.host.rateLimited", -32021); + codes.put("plugin.host.languageServerUnavailable", -32022); + codes.put("plugin.host.languageServerError", -32023); + codes.put("plugin.host.methodNotDeclared", -32024); + codes.put("plugin.host.toolUnresolved", -32025); + codes.put("plugin.host.foreignContribution", -32026); + codes.put("plugin.function.notDeclared", -32027); + codes.put("plugin.function.notExported", -32028); + codes.put("plugin.function.providerDisabled", -32029); + codes.put("plugin.function.versionMismatch", -32030); + codes.put("plugin.function.callCycle", -32065); + codes.put("plugin.function.depthExceeded", -32066); + codes.put("plugin.function.tooManyCalls", -32067); + codes.put("plugin.function.payloadTooLarge", -32068); + codes.put("plugin.function.providerUnavailable", -32069); + codes.put("plugin.function.failed", -32070); + codes.put("plugin.function.invalidResult", -32071); + CODES = Collections.unmodifiableMap(codes); + Map byNumber = new HashMap<>(); + for (Map.Entry entry : codes.entrySet()) { + byNumber.put(entry.getValue(), entry.getKey()); + } + BY_RPC_CODE = Collections.unmodifiableMap(byNumber); + } + + private final transient Map details; + private final String method; + + public HostError(String code, String message, Integer rpcCode, Map details, String method) { + super(code, message, rpcCode); + this.details = details == null ? null : Collections.unmodifiableMap(new LinkedHashMap<>(details)); + this.method = method; + } + + /** The failure's {@code error.data.details}, or null when the host sent none. */ + public Map details() { + return details; + } + + /** The request that failed. */ + public String method() { + return method; + } + + /** + * For {@code plugin.function.failed}, the provider's own + * {@code error.data.code} (from {@code details.pluginErrorCode}); null for + * any other failure or when the provider named none. + */ + public String pluginErrorCode() { + if (!"plugin.function.failed".equals(code()) || details == null) { + return null; + } + Object pluginErrorCode = details.get("pluginErrorCode"); + return pluginErrorCode instanceof String ? (String) pluginErrorCode : null; + } + + /** + * The failure for a JSON-RPC error answer. A host method without a known + * code is a host failure: a number names one code, and an unknown number + * is {@code plugin.host.failed}. + */ + static HostError fromResponse(String method, Map error) { + Object data = error.get("data"); + Map fields = data instanceof Map ? Json.object(data) : Collections.emptyMap(); + Object rpcCode = error.get("code"); + Integer number = rpcCode instanceof Number && ((Number) rpcCode).doubleValue() == ((Number) rpcCode).intValue() + ? ((Number) rpcCode).intValue() + : null; + String code = Json.string(fields, "code"); + if (code == null) { + if (method.startsWith(Protocol.HOST_PREFIX)) { + String known = number == null ? null : BY_RPC_CODE.get(number); + code = known == null ? "plugin.host.failed" : known; + } else { + code = "sdk.host.error"; + } + } + Object details = fields.get("details"); + String text = Json.string(error, "message"); + return new HostError(code, text == null ? method + " failed." : text, number, + details instanceof Map ? Json.object(details) : null, method); + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java new file mode 100644 index 0000000..64ff3f5 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java @@ -0,0 +1,426 @@ +package io.github.litheidea.plugin.sdk; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Minimal JSON reader and writer for protocol messages and stored state. + * + *

The SDK carries its own codec so that a plugin can shade it next to any + * JSON library without version conflicts. Values map to plain Java types: + * objects to {@code Map} (insertion-ordered), arrays to + * {@code List}, strings to {@code String}, booleans to + * {@code Boolean}, {@code null} to {@code null}, integers to {@code Long} (or + * {@code BigInteger} beyond its range), and other numbers to {@code Double}. + */ +public final class Json { + /** Deeper input is refused instead of overflowing the reader's stack. */ + private static final int MAX_DEPTH = 512; + + private Json() {} + + /** A value that is not JSON, or one JSON cannot represent. */ + public static final class JsonException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public JsonException(String message) { + super(message); + } + } + + /** Parses one JSON document; trailing content other than whitespace is an error. */ + public static Object parse(String text) { + Reader reader = new Reader(text); + reader.skipWhitespace(); + Object value = reader.value(0); + reader.skipWhitespace(); + if (reader.position != text.length()) { + throw reader.error("Unexpected content after the value"); + } + return value; + } + + /** + * Encodes {@code value}. Maps need string keys; numbers must be finite. + * Arrays of objects and any {@link Collection} encode as JSON arrays. + */ + public static String stringify(Object value) { + StringBuilder output = new StringBuilder(); + write(output, value, 0); + return output.toString(); + } + + /** {@code value} as an object, or an empty map when it is {@code null}. */ + @SuppressWarnings("unchecked") + public static Map object(Object value) { + if (value == null) { + return new LinkedHashMap<>(); + } + if (value instanceof Map) { + return (Map) value; + } + throw new JsonException("Expected a JSON object."); + } + + /** The string at {@code key}, or {@code null} when it is missing or not a string. */ + public static String string(Map object, String key) { + Object value = object.get(key); + return value instanceof String ? (String) value : null; + } + + private static void write(StringBuilder output, Object value, int depth) { + if (depth > MAX_DEPTH) { + throw new JsonException("The value is nested too deeply, or contains itself."); + } + if (value == null) { + output.append("null"); + } else if (value instanceof String || value instanceof Character) { + quote(output, value.toString()); + } else if (value instanceof Boolean) { + output.append(value.toString()); + } else if (value instanceof Double || value instanceof Float) { + output.append(decimal(((Number) value).doubleValue())); + } else if (value instanceof Long || value instanceof Integer || value instanceof Short + || value instanceof Byte || value instanceof BigInteger) { + output.append(value.toString()); + } else if (value instanceof BigDecimal) { + output.append(((BigDecimal) value).toString()); + } else if (value instanceof Map) { + output.append('{'); + boolean first = true; + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!(entry.getKey() instanceof String)) { + throw new JsonException("Object keys must be strings."); + } + if (!first) { + output.append(','); + } + first = false; + quote(output, (String) entry.getKey()); + output.append(':'); + write(output, entry.getValue(), depth + 1); + } + output.append('}'); + } else if (value instanceof Collection) { + writeArray(output, ((Collection) value).toArray(), depth); + } else if (value instanceof Object[]) { + writeArray(output, (Object[]) value, depth); + } else { + throw new JsonException("A " + value.getClass().getName() + " is not a JSON value."); + } + } + + private static void writeArray(StringBuilder output, Object[] values, int depth) { + output.append('['); + for (int index = 0; index < values.length; index++) { + if (index > 0) { + output.append(','); + } + write(output, values[index], depth + 1); + } + output.append(']'); + } + + private static String decimal(double value) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + throw new JsonException("JSON has no representation for " + value + "."); + } + // Integral values print without a fraction, as JavaScript prints them. + if (value == Math.rint(value) && Math.abs(value) < 1e15) { + return Long.toString((long) value); + } + return Double.toString(value); + } + + private static void quote(StringBuilder output, String text) { + output.append('"'); + for (int index = 0; index < text.length(); index++) { + char character = text.charAt(index); + switch (character) { + case '"': + output.append("\\\""); + break; + case '\\': + output.append("\\\\"); + break; + case '\n': + output.append("\\n"); + break; + case '\r': + output.append("\\r"); + break; + case '\t': + output.append("\\t"); + break; + case '\b': + output.append("\\b"); + break; + case '\f': + output.append("\\f"); + break; + default: + if (character < 0x20 || isLoneSurrogate(text, index)) { + // A lone surrogate has no UTF-8 encoding; escaping it + // keeps the frame valid, as JSON.stringify does. + output.append(String.format("\\u%04x", (int) character)); + } else { + output.append(character); + } + } + } + output.append('"'); + } + + private static boolean isLoneSurrogate(String text, int index) { + char character = text.charAt(index); + if (Character.isHighSurrogate(character)) { + return index + 1 >= text.length() || !Character.isLowSurrogate(text.charAt(index + 1)); + } + if (Character.isLowSurrogate(character)) { + return index == 0 || !Character.isHighSurrogate(text.charAt(index - 1)); + } + return false; + } + + private static final class Reader { + private final String text; + private int position; + + Reader(String text) { + this.text = text; + } + + Object value(int depth) { + if (depth > MAX_DEPTH) { + throw error("The document is nested too deeply"); + } + if (position >= text.length()) { + throw error("Unexpected end of input"); + } + char character = text.charAt(position); + switch (character) { + case '{': + return object(depth); + case '[': + return array(depth); + case '"': + return string(); + case 't': + return literal("true", Boolean.TRUE); + case 'f': + return literal("false", Boolean.FALSE); + case 'n': + return literal("null", null); + default: + if (character == '-' || (character >= '0' && character <= '9')) { + return number(); + } + throw error("Unexpected character"); + } + } + + private Map object(int depth) { + Map result = new LinkedHashMap<>(); + position++; + skipWhitespace(); + if (peek() == '}') { + position++; + return result; + } + for (;;) { + skipWhitespace(); + if (peek() != '"') { + throw error("Expected a property name"); + } + String key = string(); + skipWhitespace(); + expect(':'); + skipWhitespace(); + result.put(key, value(depth + 1)); + skipWhitespace(); + char next = peek(); + position++; + if (next == '}') { + return result; + } + if (next != ',') { + throw error("Expected ',' or '}'"); + } + } + } + + private List array(int depth) { + List result = new ArrayList<>(); + position++; + skipWhitespace(); + if (peek() == ']') { + position++; + return result; + } + for (;;) { + skipWhitespace(); + result.add(value(depth + 1)); + skipWhitespace(); + char next = peek(); + position++; + if (next == ']') { + return result; + } + if (next != ',') { + throw error("Expected ',' or ']'"); + } + } + } + + private String string() { + position++; + StringBuilder result = new StringBuilder(); + for (;;) { + if (position >= text.length()) { + throw error("Unterminated string"); + } + char character = text.charAt(position++); + if (character == '"') { + return result.toString(); + } + if (character < 0x20) { + throw error("Control character in string"); + } + if (character != '\\') { + result.append(character); + continue; + } + if (position >= text.length()) { + throw error("Unterminated escape"); + } + char escape = text.charAt(position++); + switch (escape) { + case '"': + case '\\': + case '/': + result.append(escape); + break; + case 'b': + result.append('\b'); + break; + case 'f': + result.append('\f'); + break; + case 'n': + result.append('\n'); + break; + case 'r': + result.append('\r'); + break; + case 't': + result.append('\t'); + break; + case 'u': + if (position + 4 > text.length()) { + throw error("Incomplete unicode escape"); + } + int code = 0; + for (int index = 0; index < 4; index++) { + int digit = Character.digit(text.charAt(position++), 16); + if (digit < 0) { + throw error("Invalid unicode escape"); + } + code = code * 16 + digit; + } + result.append((char) code); + break; + default: + throw error("Invalid escape"); + } + } + } + + private Object number() { + int start = position; + if (peek() == '-') { + position++; + } + if (peek() == '0') { + position++; + } else if (isDigit(peek())) { + digits(); + } else { + throw error("Invalid number"); + } + boolean integral = true; + if (peek() == '.') { + integral = false; + position++; + if (!isDigit(peek())) { + throw error("Invalid number"); + } + digits(); + } + if (peek() == 'e' || peek() == 'E') { + integral = false; + position++; + if (peek() == '+' || peek() == '-') { + position++; + } + if (!isDigit(peek())) { + throw error("Invalid number"); + } + digits(); + } + String literal = text.substring(start, position); + if (integral) { + BigInteger value = new BigInteger(literal); + return value.bitLength() < 64 ? (Object) value.longValue() : value; + } + return Double.parseDouble(literal); + } + + private void digits() { + while (isDigit(peek())) { + position++; + } + } + + private Object literal(String word, Object value) { + if (!text.startsWith(word, position)) { + throw error("Unexpected literal"); + } + position += word.length(); + return value; + } + + private void expect(char character) { + if (peek() != character) { + throw error("Expected '" + character + "'"); + } + position++; + } + + private char peek() { + return position < text.length() ? text.charAt(position) : '\0'; + } + + void skipWhitespace() { + while (position < text.length()) { + char character = text.charAt(position); + if (character != ' ' && character != '\t' && character != '\n' && character != '\r') { + return; + } + position++; + } + } + + JsonException error(String message) { + return new JsonException(message + " at offset " + position + "."); + } + + private static boolean isDigit(char character) { + return character >= '0' && character <= '9'; + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java new file mode 100644 index 0000000..c7e83b3 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java @@ -0,0 +1,38 @@ +package io.github.litheidea.plugin.sdk; + +/** + * A failure a handler reports on purpose. Core ends the call with the stable + * {@code plugin.function.failed} code and forwards {@link #code()} as + * {@code pluginErrorCode}, so the plugin's own UI can tell its failures apart. + * Lithe never branches on it. + * + *

The message is shown to the user as written (Core keeps its first 1024 + * bytes), so it must not contain stack traces or machine paths. + */ +public class PluginError extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + + /** + * @param code identifier of at most 64 bytes, such as {@code maven.snapshotLocked} + * @param message user-facing text + */ + public PluginError(String code, String message) { + this(code, message, null); + } + + /** As {@link #PluginError(String, String)}; {@code cause} stays in memory, outside automatic diagnostics. */ + public PluginError(String code, String message, Throwable cause) { + super(message, cause); + if (!Protocol.isPluginErrorCode(code)) { + throw new IllegalArgumentException("Plugin error code \"" + code + + "\" must start with a letter, use letters, digits, \".\", \"_\" or \"-\", and be at most 64 bytes."); + } + this.code = code; + } + + public String code() { + return code; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java new file mode 100644 index 0000000..043ba52 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java @@ -0,0 +1,32 @@ +package io.github.litheidea.plugin.sdk; + +/** + * An SDK usage error raised to the plugin author, or a failure the host + * reported for a request this backend sent. {@link #rpcCode()} carries the + * host's JSON-RPC error code in the latter case. + */ +public class PluginSdkError extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final String code; + private final Integer rpcCode; + + public PluginSdkError(String code, String message) { + this(code, message, null); + } + + public PluginSdkError(String code, String message, Integer rpcCode) { + super(message); + this.code = code; + this.rpcCode = rpcCode; + } + + public String code() { + return code; + } + + /** The host's JSON-RPC error code, or {@code null} for a local usage error. */ + public Integer rpcCode() { + return rpcCode; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java new file mode 100644 index 0000000..39e9a7a --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java @@ -0,0 +1,629 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Child processes a backend starts for one call. + * + *

Lithe's host offers no process capability, so a + * backend runs its tools itself; this helper makes sure that the call ending, + * cancelling it, or the backend shutting down also ends the tools it started. + * + *

Process trees: on macOS and Linux every tool leads its own process group, + * as in the Node SDK, on every Java version. Java has no API for that, so the + * tool starts through the system {@code perl}, which calls {@code setpgrp} and + * then replaces itself with the tool, keeping its PID. A stop signals the whole + * group, and once the tool exits on its own the members it left behind, such + * as a background worker, are killed too; descendants that leave the group + * with {@code setsid} are out of reach. Windows, and a system without + * {@code perl}, fall back to {@code ProcessHandle} on Java 9 and newer, found + * by reflection so the SDK still loads on Java 8; it reaches only the + * descendants still attached to the tool. Lithe starts every backend inside + * its own process scope ({@code LITHE_PLUGIN_BACKEND_SCOPE}) and ends whatever + * is left of it when the session ends; that remains the final boundary. + */ +public final class Processes { + /** + * Variables Lithe sets on the backend so it can find and end every process + * the backend started, even one that left its parent. A tool always + * inherits them, also when the plugin replaces the environment. + */ + static final String[] HOST_MARKERS = {"LITHE_PROCESS_SCOPE", "LITHE_PLUGIN_BACKEND_SCOPE"}; + + /** Every tool started through {@link #run} that has not exited or been stopped. */ + private static final Set RUNNING = Collections.newSetFromMap(new ConcurrentHashMap<>()); + + private static final ScheduledExecutorService TIMERS = Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "lithe-sdk-process-timer"); + thread.setDaemon(true); + return thread; + }); + + private static final ProcessTree TREE = ProcessTree.load(); + + private static final ProcessGroups GROUPS = ProcessGroups.load(); + + private Processes() {} + + /** Options of one {@link #run}; every setter returns this object. */ + public static final class Options { + private Path directory; + private Map environment; + private Cancellation cancellation; + private int maxOutputBytes = 1 << 20; + private long killGraceMillis = 2000; + private Consumer onStdout; + private Consumer onStderr; + private Runnable listenerFailure = () -> {}; + + /** Working directory; defaults to the backend's. */ + public Options directory(Path value) { + directory = value; + return this; + } + + /** Replaces the environment; the host's process markers are carried over regardless. */ + public Options environment(Map value) { + environment = value; + return this; + } + + /** Cancelling it stops the tool and makes {@link #run} throw {@link CancelledException}. */ + public Options cancellation(Cancellation value) { + cancellation = value; + return this; + } + + /** Captured bytes per stream; default 1 MiB. Listeners still see everything. */ + public Options maxOutputBytes(int value) { + maxOutputBytes = value; + return this; + } + + /** Delay between the polite and the forced stop; default 2000. */ + public Options killGraceMillis(long value) { + killGraceMillis = value; + return this; + } + + /** Receives stdout as it arrives, decoded as UTF-8 without splitting characters. */ + public Options onStdout(Consumer value) { + onStdout = value; + return this; + } + + /** Receives stderr as it arrives, decoded as UTF-8 without splitting characters. */ + public Options onStderr(Consumer value) { + onStderr = value; + return this; + } + + Options listenerFailure(Runnable value) { listenerFailure = value; return this; } + + Cancellation cancellation() { + return cancellation; + } + + Options copy() { + Options copy = new Options(); + copy.directory = directory; + copy.environment = environment; + copy.cancellation = cancellation; + copy.maxOutputBytes = maxOutputBytes; + copy.killGraceMillis = killGraceMillis; + copy.onStdout = onStdout; + copy.onStderr = onStderr; + copy.listenerFailure = listenerFailure; + return copy; + } + } + + /** Exit status and captured output of a tool. */ + public static final class Result { + private final int exitCode; + private final String stdout; + private final String stderr; + private final boolean truncated; + + Result(int exitCode, String stdout, String stderr, boolean truncated) { + this.exitCode = exitCode; + this.stdout = stdout; + this.stderr = stderr; + this.truncated = truncated; + } + + /** The exit code; on POSIX a tool ended by signal N reports 128 + N. */ + public int exitCode() { + return exitCode; + } + + public String stdout() { + return stdout; + } + + public String stderr() { + return stderr; + } + + /** True when either stream exceeded {@code maxOutputBytes}. */ + public boolean truncated() { + return truncated; + } + } + + /** + * Runs {@code command} without a shell and returns its exit status and + * captured output. A non-zero exit returns normally; the caller decides + * what it means for its tool. Cancellation stops the tool and throws + * {@link CancelledException} once it ended. + */ + public static Result run(List command, Options options) throws IOException { + Options settings = options == null ? new Options() : options; + Cancellation cancellation = settings.cancellation; + if (cancellation != null) { + cancellation.throwIfCancelled(); + } + if (command.isEmpty()) { + throw new IllegalArgumentException("A command needs an executable."); + } + ProcessBuilder builder = new ProcessBuilder(new ArrayList<>(command)); + if (settings.directory != null) { + builder.directory(settings.directory.toFile()); + } + if (settings.environment != null) { + Map environment = builder.environment(); + environment.clear(); + environment.putAll(settings.environment); + for (String name : HOST_MARKERS) { + String value = System.getenv(name); + if (value == null) { + environment.remove(name); + } else { + environment.put(name, value); + } + } + } + boolean grouped = GROUPS.available(); + if (grouped) { + builder.command(GROUPS.launcher(command, builder.environment())); + } + Process process = builder.start(); + // Tools get no input; an open pipe would let one wait on it forever. + process.getOutputStream().close(); + Running entry = new Running(process, grouped ? GROUPS.leader(process) : 0); + RUNNING.add(entry); + Capture stdout = new Capture(process.getInputStream(), settings.maxOutputBytes, settings.onStdout, "stdout", settings.listenerFailure); + Capture stderr = new Capture(process.getErrorStream(), settings.maxOutputBytes, settings.onStderr, "stderr", settings.listenerFailure); + Cancellation.Registration registration = cancellation == null + ? () -> {} + : cancellation.onCancel(() -> entry.stop(settings.killGraceMillis)); + int exitCode; + try { + exitCode = waitFor(process, entry); + registration.remove(); + // The tool ended on its own; what it left running, such as a + // background worker, ends with it. A stopped tool stays registered + // until its forced stop, which reaches the same members. + entry.endLeftovers(); + // A descendant out of reach can keep the inherited pipes open after + // the tool exited; the output then ends at the grace period. + stdout.join(settings.killGraceMillis); + stderr.join(settings.killGraceMillis); + } finally { + registration.remove(); + if (!entry.stopping()) { + RUNNING.remove(entry); + } + } + if (cancellation != null) { + cancellation.throwIfCancelled(); + } + String errors = stderr.text(); + if (grouped && exitCode == ProcessGroups.EXEC_FAILED && errors.startsWith(ProcessGroups.EXEC_FAILURE)) { + // The launcher could not start the tool; report it as ProcessBuilder would. + throw new IOException("Cannot run program \"" + command.get(0) + "\": " + + errors.substring(ProcessGroups.EXEC_FAILURE.length()).trim()); + } + return new Result(exitCode, stdout.text(), errors, stdout.truncated() || stderr.truncated()); + } + + /** Runs {@code command} with default options. */ + public static Result run(List command) throws IOException { + return run(command, null); + } + + /** + * Forcibly ends every tool still running. The backend calls it on shutdown, + * on {@code exit}, and when the host closes stdin, so no tool outlives the + * session that started it. + */ + public static void killAll() { + for (Running entry : new ArrayList<>(RUNNING)) { + entry.forceStop(); + } + RUNNING.clear(); + } + + /** Number of tools still running or being stopped, for tests and diagnostics. */ + public static int runningCount() { + return RUNNING.size(); + } + + private static int waitFor(Process process, Running entry) { + boolean interrupted = false; + try { + for (;;) { + try { + return process.waitFor(); + } catch (InterruptedException error) { + // The tool still belongs to this call; end it before giving + // the interrupt back to the caller. + interrupted = true; + entry.forceStop(); + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + /** One started tool and its stop state. */ + private static final class Running { + private final Process process; + /** The tool's process group, or 0 when it has none of its own. */ + private final long group; + private final Object lock = new Object(); + private boolean stopping; + private List tree = Collections.emptyList(); + private ScheduledFuture forceTimer; + + Running(Process process, long group) { + this.process = process; + this.group = group; + } + + /** Kills what the tool left after exiting on its own, unless a stop owns that. */ + void endLeftovers() { + synchronized (lock) { + if (stopping) { + return; + } + } + if (group > 0) { + // While any member lives the group ID cannot be reused, so this + // reaches only what this tool started; an empty group is ignored. + GROUPS.signal(group, true); + } else { + // Windows keeps the parent link of an exited tool, so its + // descendants are still found there. + TREE.destroy(TREE.descendants(process), true); + } + } + + boolean stopping() { + synchronized (lock) { + return stopping; + } + } + + /** Asks the tree to stop, then forces it after {@code graceMillis}. */ + void stop(long graceMillis) { + synchronized (lock) { + if (stopping) { + return; + } + stopping = true; + if (group > 0) { + GROUPS.signal(group, false); + } else { + // Descendants are listed before the tool is signalled: once + // it exits they are reparented and no longer reachable from it. + tree = TREE.descendants(process); + TREE.destroy(tree, false); + } + // Also covers a tool that has not formed its group yet. + process.destroy(); + forceTimer = TIMERS.schedule(this::forceStop, graceMillis, TimeUnit.MILLISECONDS); + } + } + + void forceStop() { + List known; + synchronized (lock) { + stopping = true; + if (forceTimer != null) { + forceTimer.cancel(false); + } + known = new ArrayList<>(tree); + if (group <= 0) { + known.addAll(TREE.descendants(process)); + } + } + if (group > 0) { + GROUPS.signal(group, true); + } + TREE.destroy(known, true); + process.destroyForcibly(); + RUNNING.remove(this); + } + } + + /** Reads one output stream on its own thread, keeping at most {@code limit} bytes. */ + private static final class Capture { + private final ByteArrayOutputStream kept = new ByteArrayOutputStream(); + private final InputStream input; + private final int limit; + private final Consumer listener; + private final Runnable listenerFailure; + private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPLACE) + .onUnmappableCharacter(CodingErrorAction.REPLACE); + private final Thread thread; + private volatile boolean truncated; + + Capture(InputStream input, int limit, Consumer listener, String name, Runnable listenerFailure) { + this.listenerFailure = listenerFailure; + this.input = input; + this.limit = limit; + this.listener = listener; + thread = new Thread(this::read, "lithe-sdk-" + name); + thread.setDaemon(true); + thread.start(); + } + + private void read() { + byte[] chunk = new byte[8192]; + // Holds a multi-byte character split across reads until it is whole. + ByteBuffer pending = ByteBuffer.allocate(chunk.length + 8); + try { + int count; + while ((count = input.read(chunk)) >= 0) { + synchronized (kept) { + int room = Math.max(0, limit - kept.size()); + kept.write(chunk, 0, Math.min(room, count)); + if (count > room) { + truncated = true; + } + } + if (listener != null) { + pending.put(chunk, 0, count); + pending.flip(); + deliver(pending, false); + pending.compact(); + } + } + if (listener != null) { + pending.flip(); + deliver(pending, true); + } + } catch (IOException error) { + // The stream was closed after the grace period; what was read is kept. + } + } + + private void deliver(ByteBuffer bytes, boolean end) { + CharBuffer characters = CharBuffer.allocate(bytes.remaining() + 1); + decoder.decode(bytes, characters, end); + if (end) { + decoder.flush(characters); + } + characters.flip(); + if (characters.hasRemaining()) { + try { + listener.accept(characters.toString()); + } catch (RuntimeException error) { + listenerFailure.run(); + } + } + } + + void join(long millis) { + try { + thread.join(Math.max(1, millis)); + if (thread.isAlive()) { + input.close(); + thread.join(millis); + } + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } catch (IOException error) { + // Closing an output pipe that already failed changes nothing. + } + } + + String text() { + synchronized (kept) { + return new String(kept.toByteArray(), StandardCharsets.UTF_8); + } + } + + boolean truncated() { + return truncated; + } + } + + /** + * A process group per tool on macOS and Linux. The launcher is + * {@code perl -e SCRIPT -- command...}: it calls + * {@code setpgrp(0, 0)} and replaces itself with the tool, so the PID Java + * reports is the tool's and also its group ID. {@code PERL5OPT} would make + * perl load modules before the script runs, so it is withheld from perl and + * handed back to the tool. Signals go through {@code /bin/kill}, which + * Java 8 needs for a negative PID. + */ + private static final class ProcessGroups { + /** Exit code and stderr prefix of a launcher that could not start the tool. */ + static final int EXEC_FAILED = 127; + static final String EXEC_FAILURE = "lithe-sdk-exec-failed: "; + + private static final String SCRIPT = "my $has = shift; my $opt = shift;" + + " $ENV{PERL5OPT} = $opt if $has;" + + " setpgrp(0, 0);" + + " exec { $ARGV[0] } @ARGV;" + + " print STDERR '" + EXEC_FAILURE + "', \"$!\\n\"; exit " + EXEC_FAILED + ";"; + + /** A signal that has not run after this long is abandoned; the host scope remains. */ + private static final long SIGNAL_TIMEOUT_MILLIS = 2000; + + private final String perl; + private final String kill; + private final Method pid; + + private ProcessGroups(String perl, String kill, Method pid) { + this.perl = perl; + this.kill = kill; + this.pid = pid; + } + + static ProcessGroups load() { + if (System.getProperty("os.name", "").startsWith("Windows")) { + return new ProcessGroups(null, null, null); + } + Method pid; + try { + pid = Process.class.getMethod("pid"); + } catch (NoSuchMethodException error) { + // Java 8 keeps the PID in a private field of UNIXProcess. + pid = null; + } + return new ProcessGroups(executable("/usr/bin/perl", "/bin/perl"), + executable("/bin/kill", "/usr/bin/kill"), pid); + } + + private static String executable(String... candidates) { + for (String candidate : candidates) { + if (new File(candidate).canExecute()) { + return candidate; + } + } + return null; + } + + boolean available() { + return perl != null && kill != null; + } + + List launcher(List command, Map environment) { + String option = environment.remove("PERL5OPT"); + List launcher = new ArrayList<>(Arrays.asList(perl, "-e", SCRIPT, "--", + option == null ? "0" : "1", option == null ? "" : option)); + launcher.addAll(command); + return launcher; + } + + /** The tool's PID, which is its group ID; 0 when it cannot be read. */ + long leader(Process process) { + try { + if (pid != null) { + return ((Number) pid.invoke(process)).longValue(); + } + Field field = process.getClass().getDeclaredField("pid"); + field.setAccessible(true); + return field.getInt(process); + } catch (ReflectiveOperationException | RuntimeException error) { + return 0; + } + } + + /** Signals every member of {@code group}; an empty group is ignored. */ + void signal(long group, boolean forcibly) { + ProcessBuilder builder = new ProcessBuilder(kill, "-s", forcibly ? "KILL" : "TERM", "--", "-" + group); + File discard = new File("/dev/null"); + builder.redirectOutput(discard).redirectError(discard); + try { + Process signal = builder.start(); + signal.getOutputStream().close(); + if (!signal.waitFor(SIGNAL_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { + signal.destroyForcibly(); + } + } catch (IOException error) { + // The host's process scope ends what this could not reach. + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + } + } + } + + /** + * {@code ProcessHandle} through reflection: present from Java 9, absent on + * Java 8, where only the direct child can be stopped. + */ + private static final class ProcessTree { + private final Method descendants; + private final Method destroy; + private final Method destroyForcibly; + + private ProcessTree(Method descendants, Method destroy, Method destroyForcibly) { + this.descendants = descendants; + this.destroy = destroy; + this.destroyForcibly = destroyForcibly; + } + + static ProcessTree load() { + try { + Class handle = Class.forName("java.lang.ProcessHandle"); + return new ProcessTree( + Process.class.getMethod("descendants"), + handle.getMethod("destroy"), + handle.getMethod("destroyForcibly")); + } catch (ReflectiveOperationException error) { + return new ProcessTree(null, null, null); + } + } + + List descendants(Process process) { + if (descendants == null) { + return Collections.emptyList(); + } + try { + @SuppressWarnings("unchecked") + Stream stream = (Stream) descendants.invoke(process); + return stream.collect(Collectors.toList()); + } catch (ReflectiveOperationException | RuntimeException error) { + return Collections.emptyList(); + } + } + + void destroy(List handles, boolean forcibly) { + Method method = forcibly ? destroyForcibly : destroy; + if (method == null) { + return; + } + for (Object handle : handles) { + try { + method.invoke(handle); + } catch (ReflectiveOperationException | RuntimeException error) { + // The process already exited, or the platform refused; the + // host's process scope ends what is left. + } + } + } + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java new file mode 100644 index 0000000..66f57ca --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -0,0 +1,240 @@ +package io.github.litheidea.plugin.sdk; + +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Wire constants and validation shared with Lithe's Rust Core + * ({@code rust/crates/plugin-rpc/src/} in the Lithe + * repository) and the Node.js + * SDK. The SDK checks the same rules locally so a plugin author sees a mistake + * when registering a handler instead of as a refused session at runtime. + */ +public final class Protocol { + /** The version of each protocol this SDK speaks; the host offers it in {@code initialize}. */ + public static final int FUNCTIONS_VERSION = 0; + /** + * The newest build protocol version ({@code buildProviders} 1 adds + * {@code lithe/build/runEntrypoints}). The SDK also speaks every earlier + * version and answers the newest one the host offers. + */ + public static final int BUILD_VERSION = 1; + public static final int LOGGING_VERSION = 0; + public static final int KEYMAP_IMPORT_VERSION = 0; + + public static final String INITIALIZE = "initialize"; + public static final String INITIALIZED = "initialized"; + public static final String SHUTDOWN = "shutdown"; + public static final String EXIT = "exit"; + public static final String CANCEL_REQUEST = "$/cancelRequest"; + public static final String FUNCTION_INVOKE = "lithe/function/invoke"; + public static final String FUNCTION_REGISTER = "lithe/function/register"; + public static final String FUNCTION_UNREGISTER = "lithe/function/unregister"; + public static final String FUNCTION_PROGRESS = "lithe/function/progress"; + public static final String BUILD_MODEL = "lithe/build/model"; + public static final String BUILD_DEPENDENCIES = "lithe/build/dependencies"; + public static final String BUILD_EXECUTE = "lithe/build/execute"; + public static final String BUILD_TEST = "lithe/build/test"; + public static final String BUILD_DISCOVER_TESTS = "lithe/build/discoverTests"; + public static final String BUILD_PREPARE_DEBUG = "lithe/build/prepareDebug"; + public static final String BUILD_PREPARE_RUN = "lithe/build/prepareRun"; + public static final String BUILD_RUN_ENTRYPOINTS = "lithe/build/runEntrypoints"; + public static final String BUILD_PROGRESS = "lithe/build/progress"; + + /** + * Backend-to-host requests. The host may add methods; + * {@link Host#request} sends any {@code lithe/host/*} method, and + * {@code getCapabilities} says which ones the session may call. + */ + public static final String HOST_TERMINAL_CREATE = "lithe/host/terminal/create"; + public static final String HOST_TERMINAL_SHOW = "lithe/host/terminal/show"; + public static final String HOST_TERMINAL_CLOSE = "lithe/host/terminal/close"; + public static final String HOST_TERMINAL_REOPEN = "lithe/host/terminal/reopen"; + public static final String HOST_TERMINAL_DISPOSE = "lithe/host/terminal/dispose"; + public static final String HOST_TERMINAL_ON_EXIT = "lithe/host/terminal/onExit"; + public static final String HOST_PREFIX = "lithe/host/"; + public static final String HOST_CREDENTIALS_GET = "lithe/host/credentials/get"; + public static final String HOST_CREDENTIALS_SET = "lithe/host/credentials/set"; + public static final String HOST_CREDENTIALS_DELETE = "lithe/host/credentials/delete"; + public static final String HOST_GET_CAPABILITIES = "lithe/host/getCapabilities"; + public static final String HOST_SUBSCRIPTIONS_DISPOSE = "lithe/host/subscriptions/dispose"; + public static final String HOST_WORKSPACE_LIST_CONTEXTS = "lithe/host/workspace/listContexts"; + public static final String HOST_WORKSPACE_GET_CONTEXT = "lithe/host/workspace/getContext"; + public static final String HOST_WORKSPACE_GET_FOLDERS = "lithe/host/workspace/getFolders"; + public static final String HOST_WORKSPACE_READ_DIRECTORY = "lithe/host/workspace/readDirectory"; + public static final String HOST_WORKSPACE_STAT = "lithe/host/workspace/stat"; + public static final String HOST_WORKSPACE_READ_FILE = "lithe/host/workspace/readFile"; + public static final String HOST_WORKSPACE_WATCH = "lithe/host/workspace/watch"; + public static final String HOST_WORKSPACE_FIND_FILES = "lithe/host/workspace/findFiles"; + public static final String HOST_WORKSPACE_FIND_TEXT = "lithe/host/workspace/findText"; + public static final String HOST_DOCUMENTS_LIST = "lithe/host/documents/list"; + public static final String HOST_DOCUMENTS_GET_SNAPSHOT = "lithe/host/documents/getSnapshot"; + public static final String HOST_EDITOR_REGISTER_ACTIONS = "lithe/host/editor/registerActions"; + public static final String HOST_EDITOR_GET_ACTIVE = "lithe/host/editor/getActive"; + public static final String HOST_EDITOR_GET_SELECTIONS = "lithe/host/editor/getSelections"; + public static final String HOST_EDITOR_APPLY_EDITS = "lithe/host/editor/applyEdits"; + public static final String HOST_EDITOR_REPLACE_SELECTIONS = "lithe/host/editor/replaceSelections"; + public static final String HOST_EDITOR_INSERT_TEXT = "lithe/host/editor/insertText"; + public static final String HOST_EDITOR_OPEN = "lithe/host/editor/open"; + public static final String HOST_EDITOR_REVEAL = "lithe/host/editor/reveal"; + public static final String HOST_PREVIEW_OPEN_HTML = "lithe/host/preview/openHTML"; + public static final String HOST_BROWSER_OPEN_EXTERNAL = "lithe/host/browser/openExternal"; + public static final String HOST_WINDOW_SHOW_INFORMATION = "lithe/host/window/showInformation"; + public static final String HOST_WINDOW_SHOW_WARNING = "lithe/host/window/showWarning"; + public static final String HOST_WINDOW_SHOW_ERROR = "lithe/host/window/showError"; + + /** Cross-plugin calls Core relays. */ + public static final String HOST_FUNCTIONS_PROVIDERS = "lithe/host/functions/providers"; + public static final String HOST_FUNCTIONS_INVOKE = "lithe/host/functions/invoke"; + + /** Host-to-backend notifications. */ + public static final String HOST_DID_CHANGE_CONTEXTS = "lithe/host/workspace/didChangeContexts"; + public static final String HOST_SUBSCRIPTION_NOTIFY = "lithe/host/subscriptions/notify"; + public static final String HOST_COMMAND_DID_RUN = "lithe/host/commands/didRun"; + + /** JSON-RPC and LSP error codes the SDK answers with. */ + public static final int PARSE_ERROR = -32700; + public static final int INVALID_REQUEST = -32600; + public static final int METHOD_NOT_FOUND = -32601; + public static final int INVALID_PARAMS = -32602; + public static final int INTERNAL_ERROR = -32603; + public static final int SERVER_NOT_INITIALIZED = -32002; + public static final int REQUEST_FAILED = -32000; + public static final int REQUEST_CANCELLED = -32800; + + public static final int MAX_FUNCTIONS = 256; + public static final int MAX_FUNCTION_ID_BYTES = 128; + public static final int MAX_PLUGIN_ERROR_CODE_BYTES = 64; + public static final int MAX_MESSAGE_BYTES = 1024; + public static final int MAX_RESULT_BYTES = 1 << 20; + public static final int MAX_BUILD_RESULT_BYTES = 32 * 1024 * 1024; + public static final int MAX_BUILD_MESSAGE_BYTES = 4096; + public static final int MAX_BUILD_OUTPUT_BYTES = 65536; + /** Unanswered host requests Core allows a session; the SDK queues the rest. */ + public static final int MAX_PENDING_HOST_REQUESTS = 16; + public static final int MAX_CREDENTIAL_SECRET_BYTES = 16 * 1024; + /** Timeout Core gives a relayed call that names none. */ + public static final int RELAY_DEFAULT_TIMEOUT_MILLISECONDS = 60000; + /** Longest timeout of a relayed call; the SDK sends a longer one unchanged and leaves the cap to Core. */ + public static final int RELAY_MAX_TIMEOUT_MILLISECONDS = 600000; + public static final int MAX_PARENT_OPERATION_ID_BYTES = 128; + + static boolean buildProgress(String method) { + return BUILD_EXECUTE.equals(method) || BUILD_TEST.equals(method) || BUILD_PREPARE_RUN.equals(method) || BUILD_PREPARE_DEBUG.equals(method); + } + + private static final Pattern FUNCTION_SEGMENT = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern PLUGIN_ERROR_CODE = Pattern.compile("[A-Za-z][A-Za-z0-9._-]*"); + private static final Pattern KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}"); + private static final Pattern COMMAND_ID = Pattern.compile("[a-z0-9.-]{1,128}"); + private static final long MAX_SAFE_INTEGER = 9007199254740991L; + + private Protocol() {} + + /** Dot-separated lowerCamelCase segments, for example {@code snapshot.refresh}. */ + public static boolean isFunctionId(String value) { + if (value == null || value.isEmpty() || utf8Length(value) > MAX_FUNCTION_ID_BYTES) { + return false; + } + for (String segment : value.split("\\.", -1)) { + if (!FUNCTION_SEGMENT.matcher(segment).matches()) { + return false; + } + } + return true; + } + + /** The plugin error code alphabet Core forwards as {@code pluginErrorCode}. */ + public static boolean isPluginErrorCode(String value) { + return value != null + && utf8Length(value) <= MAX_PLUGIN_ERROR_CODE_BYTES + && PLUGIN_ERROR_CODE.matcher(value).matches(); + } + + /** + * The key alphabet of host services: 1-128 ASCII letters, digits, + * {@code .}, {@code _}, {@code :}, or {@code -}. Credential keys, context + * IDs, and subscription IDs use it. + */ + public static boolean isCredentialKey(String value) { + return value != null && KEY.matcher(value).matches(); + } + + /** {@code { contextID, generation }}, exactly, naming one generation of one workspace context. */ + public static boolean isContextReference(Object value) { + if (!(value instanceof Map) || ((Map) value).size() != 2) { + return false; + } + Map reference = (Map) value; + Object id = reference.get("contextID"); + return id instanceof String && isCredentialKey((String) id) && isGeneration(reference.get("generation")); + } + + /** A {@code parentOperationID}: a string of 1-128 UTF-8 bytes. */ + static boolean isParentOperationId(Object value) { + if (!(value instanceof String)) { + return false; + } + int bytes = utf8Length((String) value); + return bytes >= 1 && bytes <= MAX_PARENT_OPERATION_ID_BYTES; + } + + /** A command ID from the plugin's manifest: 1-128 of {@code [a-z0-9.-]}. */ + public static boolean isCommandId(String value) { + return value != null && COMMAND_ID.matcher(value).matches(); + } + + /** A positive integer JSON can carry exactly. */ + static boolean isGeneration(Object value) { + if (value instanceof Long || value instanceof Integer || value instanceof Short || value instanceof Byte) { + long number = ((Number) value).longValue(); + return number >= 1 && number <= MAX_SAFE_INTEGER; + } + if (value instanceof Double || value instanceof Float) { + double number = ((Number) value).doubleValue(); + return number >= 1 && number <= MAX_SAFE_INTEGER && number == Math.rint(number); + } + return false; + } + + /** Cuts {@code value} to {@link #MAX_MESSAGE_BYTES} UTF-8 bytes without splitting a character. */ + public static String boundedText(String value) { + return boundedText(value, MAX_MESSAGE_BYTES); + } + + /** Cuts {@code value} to {@code limit} UTF-8 bytes without splitting a character. */ + public static String boundedText(String value, int limit) { + String text = value == null ? "" : value; + int used = 0; + int index = 0; + while (index < text.length()) { + int codePoint = text.codePointAt(index); + int size = codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4; + if (used + size > limit) { + return text.substring(0, index); + } + used += size; + index += Character.charCount(codePoint); + } + return text; + } + + /** + * Methods reserved for the SDK. A plugin cannot install its own handler for + * these, or send them to the host: the lifecycle belongs to the host's + * session management, and {@code lithe/*} belongs to Lithe's typed contracts. + */ + public static boolean isReservedMethod(String method) { + return method.equals(INITIALIZE) + || method.equals(INITIALIZED) + || method.equals(SHUTDOWN) + || method.equals(EXIT) + || method.equals(CANCEL_REQUEST) + || method.startsWith("lithe/"); + } + + static int utf8Length(String value) { + return value.getBytes(StandardCharsets.UTF_8).length; + } +} diff --git a/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java new file mode 100644 index 0000000..24761e2 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java @@ -0,0 +1,198 @@ +package io.github.litheidea.plugin.sdk; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.CodeSource; +import java.security.SecureRandom; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Durable plugin state, in a directory the host gives the backend. + * + *

The host passes writable directories through the {@code ${stateDir}} and + * {@code ${workspaceStateDir}} launch variables; the installed package and the + * host's installation are read-only, because signatures and delta updates are + * computed over their exact bytes. Values are JSON; each key is one file + * replaced atomically, so a crash leaves either the old or the new value, + * never half of one. The envelope matches the Node.js SDK's, so either SDK + * reads what the other wrote. + */ +public final class StateStore { + /** Version of the envelope each value is stored in. */ + private static final int STORE_FORMAT = 1; + private static final Pattern KEY = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._-]{0,127}"); + private static final SecureRandom RANDOM = new SecureRandom(); + + private final Path root; + + private StateStore(Path root) { + this.root = root; + } + + /** + * Opens a store in {@code directory}, creating the directory. Refuses a + * directory inside the plugin package, found as the nearest directory with + * a {@code plugin.json} above the JAR this class was loaded from. + * + * @param directory absolute path, normally the value of {@code ${workspaceStateDir}} + */ + public static StateStore open(Path directory) throws IOException { + return open(directory, findPackageDirectory()); + } + + /** + * Opens a store in {@code directory}, refusing one inside + * {@code packageDirectory}; null skips that check. + */ + public static StateStore open(Path directory, Path packageDirectory) throws IOException { + if (directory == null || !directory.isAbsolute()) { + throw new PluginSdkError("sdk.state.invalidDirectory", + "The state directory must be an absolute path passed by the host."); + } + // Checked before creating anything, so a refused path leaves the package untouched. + Path resolved = canonical(directory); + if (packageDirectory != null && resolved.startsWith(canonical(packageDirectory))) { + throw new PluginSdkError("sdk.state.readOnlyPackage", + "The state directory is inside the plugin package, which is read-only. Use ${stateDir} or ${workspaceStateDir}."); + } + Files.createDirectories(resolved); + return new StateStore(resolved); + } + + /** The resolved directory, for a backend that keeps its own files next to the store. */ + public Path directory() { + return root; + } + + /** The stored value, or {@code fallback} when the key is missing or unreadable. */ + public Object read(String key, Object fallback) { + Path path = path(key); + if (!Files.isRegularFile(path)) { + return fallback; + } + try { + Object envelope = Json.parse(new String(Files.readAllBytes(path), StandardCharsets.UTF_8)); + if (!(envelope instanceof Map)) { + return fallback; + } + Map fields = (Map) envelope; + Object format = fields.get("litheStateStore"); + if (!(format instanceof Number) || ((Number) format).doubleValue() != STORE_FORMAT + || !fields.containsKey("value")) { + return fallback; + } + return fields.get("value"); + } catch (IOException | RuntimeException error) { + return fallback; + } + } + + /** Stores {@code value}, which must be JSON-encodable, replacing the previous one. */ + public void write(String key, Object value) throws IOException { + Path path = path(key); + Map envelope = new LinkedHashMap<>(); + envelope.put("litheStateStore", STORE_FORMAT); + envelope.put("value", value); + byte[] body; + try { + body = Json.stringify(envelope).getBytes(StandardCharsets.UTF_8); + } catch (Json.JsonException error) { + // Refused before touching the file, so the stored value stays. + throw new PluginSdkError("sdk.state.invalidValue", "The value for " + key + " is not JSON-encodable."); + } + Path temporary = root.resolve(key + ".json." + Long.toHexString(RANDOM.nextLong()) + ".tmp"); + try { + createPrivate(temporary); + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + ByteBuffer buffer = ByteBuffer.wrap(body); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + try { + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException error) { + Files.move(temporary, path, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException | RuntimeException error) { + Files.deleteIfExists(temporary); + throw error; + } + } + + /** Removes the key; a missing key is not an error. */ + public void delete(String key) throws IOException { + Files.deleteIfExists(path(key)); + } + + private Path path(String key) { + if (key == null || !KEY.matcher(key).matches() || key.endsWith(".tmp")) { + throw new PluginSdkError("sdk.state.invalidKey", "State key \"" + key + + "\" must be 1-128 letters, digits, \".\", \"_\" or \"-\", start with a letter or digit, and not end with \".tmp\"."); + } + return root.resolve(key + ".json"); + } + + /** Creates an empty file only the user can read, where the platform supports it. */ + private static void createPrivate(Path file) throws IOException { + try { + Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); + } catch (UnsupportedOperationException error) { + Files.createFile(file); + } catch (FileAlreadyExistsException error) { + throw new IOException("A temporary state file already exists: " + file.getFileName(), error); + } + } + + /** Resolves symbolic links of the longest existing prefix of {@code path}. */ + static Path canonical(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + Path existing = absolute; + while (existing != null && !Files.exists(existing)) { + existing = existing.getParent(); + } + if (existing == null) { + return absolute; + } + return existing.toRealPath().resolve(existing.relativize(absolute)); + } + + /** The nearest directory with a {@code plugin.json} above the JAR this class came from. */ + static Path findPackageDirectory() { + try { + CodeSource source = StateStore.class.getProtectionDomain().getCodeSource(); + URL location = source == null ? null : source.getLocation(); + if (location == null) { + return null; + } + Path current = Paths.get(location.toURI()).toAbsolutePath(); + if (Files.isRegularFile(current)) { + current = current.getParent(); + } + while (current != null) { + if (Files.isRegularFile(current.resolve("plugin.json"))) { + return current; + } + current = current.getParent(); + } + return null; + } catch (URISyntaxException | RuntimeException error) { + return null; + } + } +}