From 74cc46edb891fe77388e4e60dd2c79888977699d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 4 Nov 2026 10:54:16 +0800 Subject: [PATCH] =?UTF-8?q?feat(logging):=20=E6=8E=A5=E5=85=A5=20litheLogg?= =?UTF-8?q?ing=201=20=E7=BB=93=E6=9E=84=E5=8C=96=E8=AF=8A=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 后端改为直接编译 vendor/ 下官方 Java SDK 的生产源码(基线 lithe-plugin-docs 29b245c 加本轮日志改动),去掉远程 SDK JAR 下载、LITHE_SDK_JAR 覆盖和 shade - 新增 scripts/sdk/verify-sdk.mjs,按逐文件 SHA-256 拒绝漂移、遗漏或额外文件, CI 与打包都会先跑;安装包附带 SDK-LICENSE - backend.log 改为受控事实:无 --state 目录、快照保存失败、读取中项目变化 各记 WARN degraded;Maven 失败不再额外打印构建输出,只由 SDK 记录一次 ERROR - README 与 NOTICE 补充诊断日志和 SDK 来源说明 --- .github/workflows/ci.yml | 2 + NOTICE | 5 + README.md | 35 +- backend/pom.xml | 74 +- .../litheidea/maven/backend/MavenBackend.java | 2 +- .../litheidea/maven/backend/MavenRuns.java | 5 +- .../litheidea/maven/backend/Snapshots.java | 2 +- scripts/backend-client.mjs | 7 +- scripts/package.mjs | 55 +- scripts/sdk/verify-sdk.mjs | 42 + scripts/test-backend.mjs | 6 + scripts/test.mjs | 9 + scripts/verify-scripts.mjs | 2 +- sdk.lock.json | 106 +- vendor/LICENSE | 203 +++ .../github/litheidea/plugin/sdk/Backend.java | 1417 +++++++++++++++++ .../litheidea/plugin/sdk/CallContext.java | 119 ++ .../litheidea/plugin/sdk/Cancellation.java | 112 ++ .../plugin/sdk/CancelledException.java | 14 + .../litheidea/plugin/sdk/Diagnostics.java | 71 + .../github/litheidea/plugin/sdk/Framing.java | 138 ++ .../io/github/litheidea/plugin/sdk/Host.java | 520 ++++++ .../litheidea/plugin/sdk/HostChannel.java | 504 ++++++ .../litheidea/plugin/sdk/HostError.java | 96 ++ .../io/github/litheidea/plugin/sdk/Json.java | 426 +++++ .../litheidea/plugin/sdk/PluginError.java | 38 + .../litheidea/plugin/sdk/PluginSdkError.java | 32 + .../litheidea/plugin/sdk/Processes.java | 629 ++++++++ .../github/litheidea/plugin/sdk/Protocol.java | 230 +++ .../litheidea/plugin/sdk/StateStore.java | 198 +++ 30 files changed, 4975 insertions(+), 124 deletions(-) create mode 100644 scripts/sdk/verify-sdk.mjs create mode 100644 vendor/LICENSE create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Cancellation.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CancelledException.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Framing.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Json.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginError.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/PluginSdkError.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Processes.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java create mode 100644 vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/StateStore.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 46842a9..7e57a6e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,8 @@ jobs: 17 - name: Check script process deadlines and cleanup run: node scripts/test-process.mjs + - name: Verify vendored Java SDK sources + run: node scripts/sdk/verify-sdk.mjs - name: Check manifest and build the archive run: node scripts/package.mjs - name: Test the build provider's snapshot with a fake Maven (Java 17) diff --git a/NOTICE b/NOTICE index e6c612a..a81ec60 100644 --- a/NOTICE +++ b/NOTICE @@ -12,3 +12,8 @@ Version 2.0, at revision 158b854d47ac9af2bbd99c0d7c354a5875cb6f81: skipTests.svg platform/icons/src/expui/run/showIgnored.svg Copyright 2000-2024 JetBrains s.r.o. and contributors. + +The backend includes the Apache-2.0 licensed official Lithe Java plugin SDK +from Lithe-IDEA/lithe-plugin-docs. Its production sources and LICENSE are +vendored in vendor/, with upstream base revision, local structured logging +changes and exact SHA-256 per input recorded in sdk.lock.json. diff --git a/README.md b/README.md index be9662b..3fe174f 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,23 @@ Lithe 已预置 Lithe Store 社区插件源;如果你之前移除了它,先 一个包同时支持 Apple Silicon 和 Intel Mac;Lithe for Windows 支持插件市场后会增加 Windows 包。 +## 诊断日志 + +本分支要求宿主提供 `litheLogging: 1`。SDK 通过类型化的 `lithe/log` 通知,把 Maven provider +操作交给宿主 v2 目录和统一 writer,写入当前会话的 `plugins/io.github.lithe-idea.maven-build/host` 通道。 +关键成功终态为 INFO、失败终态为 ERROR,包含单调耗时和稳定分类;取消不记失败。 +缓存保存失败或读取中项目变化属于可恢复降级,使用 WARN `degraded`,不记录异常正文、路径或环境值。 +模型快照继续属于 `${workspaceStateDir}`,不会搬到会话日志目录。 + +Maven 失败由 SDK 的请求边界记录一次,provider 不再重复打印构建输出。 +完整构建输出仍属于 Build Output,模型/依赖树 JSON 属于工作流数据。 +后端从 `vendor/` 直接编译官方 Java SDK 的结构化日志实现,使用 `lithe/log` 发送稳定分类、 +单调耗时和操作身份;原始异常与构建 tail 不进入日志。`sdk.lock.json` 记录真实上游基线、 +本轮尚未发布的源代码改动及每个文件的 SHA-256,没有沿用或伪造旧发版 JAR 的校验值。 + +排障时使用 Lithe 的独立日志窗口和诊断导出;不要开启输出源码、凭据、环境变量或协议正文的日志。 +Windows 的日志实现仍为 v1,未声明 Windows v2 已完成验收。 + ## 开发 ```text @@ -76,7 +93,9 @@ io.github.lithe-idea.maven-build/plugin.json # 插件描述,目录名必须 io.github.lithe-idea.maven-build/icons/ # 工具窗口和工具栏图标(来源见 NOTICE) extension/ # Maven 核心扩展,导出模型和依赖树 backend/ # 构建后端(Java 8,Lithe 插件 SDK),快照和 Maven 运行 -sdk.lock.json # 打进后端的 Lithe Java 插件 SDK:版本、下载地址、SHA-256 +vendor/ # 官方 Java SDK 生产源码和许可证(不带测试、JAR、target) +sdk.lock.json # SDK 上游基线、本轮改动身份、逐文件 SHA-256 +scripts/sdk/verify-sdk.mjs # 编译前拒绝漂移、遗漏或额外 SDK 文件 test/fixtures/reactor/ # 三个模块的示例反应堆,供集成测试使用 scripts/package.mjs # 构建扩展并打包成 dist/maven-build-<版本>-darwin.zip scripts/test.mjs # 用真实 Maven 经后端读取项目、运行清单里的命令并检查输出 @@ -87,13 +106,11 @@ scripts/test-backend.mjs # 用假 Maven 计数,检查快 本地需要 Node.js 22+、JDK(CI 用 17;扩展和后端都按 Java 8 编译,后端运行只需 Java 8)和 Maven(还需要 `zip`)。 -后端打进 Lithe 的 Java 插件 SDK。打包脚本按 `sdk.lock.json` 下载正式发布的 SDK JAR 到 `.cache/sdk/`,SHA-256 不符就拒绝。 - -如需本地调试,可用 `LITHE_SDK_JAR` 指向一个 JAR;正式锁定的 SHA-256 仍会校验该文件,发布(`--expect-tag`)不接受这个覆盖变量: - -```bash -LITHE_SDK_JAR=/path/to/lithe-plugin-sdk-java-0.1.0.jar node scripts/package.mjs -``` +后端把固定在 `vendor/lithe-plugin-sdk-java/src/main/java/` 的 SDK 生产源码一同按 Java 8 编译。 +打包前先校验 `sdk.lock.json`,缺失、改动或额外未登记文件都会拒绝;只读源码不共享可变构建状态。 +不再从网络下载 SDK JAR,也不接受 `LITHE_SDK_JAR` 替换构建输入。 +SDK 以 Apache-2.0 分发,源码许可证位于 `vendor/LICENSE`,安装包附带 `SDK-LICENSE`。 +如需更新,先从官方 SDK 仓库取真实生产源码,审查变更并更新基线和逐文件摘要,再执行验证。 开发或发布时直接运行: @@ -144,7 +161,7 @@ node scripts/verify-scripts.mjs --host-bundle /Applications/Lithe.app ## 发布新版本 1. 同时修改 `plugin.json`、`extension/pom.xml` 和 `backend/pom.xml` 的版本(例如 `0.2.0`;打包脚本会检查三者一致), - 确认 `sdk.lock.json` 已填入正式发布的 SDK 地址和 SHA-256,合入 `main`。 + 确认 `sdk.lock.json` 已登记所用 SDK 源码、上游基线与全部 SHA-256,合入 `main`。 2. 推送同名标签: ```bash diff --git a/backend/pom.xml b/backend/pom.xml index c28bcd8..135d439 100644 --- a/backend/pom.xml +++ b/backend/pom.xml @@ -5,11 +5,8 @@ persistent snapshot, and runs Maven (with the extension in ../extension) only when the snapshot is missing, stale or a refresh was asked for. - Lithe's Java plugin SDK is not published to a Maven repository. - scripts/package.mjs downloads the JAR pinned in sdk.lock.json, checks its - SHA-256 and passes it as -Dlithe.sdk.jar. It compiles against that file and - shade's extraJars merges it into lithe-maven-backend.jar, so the package - carries one self-contained JAR and nothing is installed into ~/.m2. + The official SDK production sources are vendored with per-file hashes in + sdk.lock.json, verified by scripts/package.mjs, and compiled into this JAR. --> 8 2026-10-20T00:00:00Z - - ${project.basedir}/missing-lithe-sdk.jar - - - io.github.lithe-idea - lithe-plugin-sdk-java - 0.1.0 - system - ${lithe.sdk.jar} - - - + ${project.basedir}/.. lithe-maven-backend + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.0 + + + backend/src/main/java/**/*.java + vendor/lithe-plugin-sdk-java/src/main/java/**/*.java + + + org.apache.maven.plugins maven-jar-plugin + + io.github.litheidea.maven.backend.MavenBackend + ${project.version} - - org.apache.maven.plugins - maven-shade-plugin - - - package - - shade - - - false - - - ${lithe.sdk.jar} - - - - *:* - - META-INF/MANIFEST.MF - - - - - - io.github.litheidea.maven.backend.MavenBackend - - ${project.version} - - - - - - - @@ -120,11 +85,6 @@ maven-jar-plugin 3.4.2 - - org.apache.maven.plugins - maven-shade-plugin - 3.6.0 - org.apache.maven.plugins maven-install-plugin diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java index 353a817..1075485 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenBackend.java @@ -55,7 +55,7 @@ private void serve() { snapshots = new Snapshots(store, backend); state = store.directory(); } else { - backend.log("No --state directory: Maven results are not kept across restarts."); + backend.diagnostics().degraded("initialize", "maven.stateUnavailable"); } runs = new MavenRuns(snapshots, backend, state); }); diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java index 7dc04b6..63624b1 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/MavenRuns.java @@ -152,7 +152,7 @@ private void fly(Flight flight, Inputs inputs, String before) { if (before.equals(Fingerprint.of(inputs))) { snapshots.write(inputs.root, before, loaded); } else { - backend.log("The Maven project changed while it was read; the result is not saved."); + backend.diagnostics().degraded("lithe/build/model", "maven.inputsChanged"); } } flight.result.complete(loaded); @@ -192,7 +192,8 @@ private Loaded run(Inputs inputs, Cancellation cancellation) throws IOException .onStderr(tail)); if (result.exitCode() != 0) { String output = tail.errors(); - backend.log("Maven exited with status " + result.exitCode() + ":\n" + output); + // The SDK records this failed request once. Build output belongs + // to the response, never to the diagnostic stderr stream. throw new PluginError("maven.loadFailed", "Maven could not read the project (exit status " + result.exitCode() + ")." + (output.isEmpty() ? "" : "\n" + output)); } diff --git a/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java b/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java index b818be7..c3ca261 100644 --- a/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java +++ b/backend/src/main/java/io/github/litheidea/maven/backend/Snapshots.java @@ -67,7 +67,7 @@ synchronized void write(Path root, String fingerprint, MavenRuns.Loaded loaded) store.write(KEY, snapshot); } catch (IOException | RuntimeException error) { // The result is still answered; only the next start runs Maven again. - backend.log("Could not save the Maven snapshot: " + error.getMessage()); + backend.diagnostics().degraded("lithe/build/model", "maven.snapshotSaveFailed"); } } diff --git a/scripts/backend-client.mjs b/scripts/backend-client.mjs index 139c47f..b679d19 100644 --- a/scripts/backend-client.mjs +++ b/scripts/backend-client.mjs @@ -12,6 +12,7 @@ export class BackendClient { #pending = new Map(); #nextId = 1; stderr = ""; + diagnostics = []; /** Starts `java -jar --state `; `javaOptions` go before `-jar`. */ constructor({ java = "java", jar, state, env = process.env, javaOptions = [], timeoutMs = WAIT_MS }) { @@ -70,7 +71,7 @@ export class BackendClient { const result = await this.request("initialize", { processId: process.pid, rootUri: pathToFileURL(root).href, - capabilities: { experimental: { litheBuild: { versions: [1] } } }, + capabilities: { experimental: { litheBuild: { versions: [1] }, litheLogging: { versions: [1] } } }, }); this.notify("initialized", {}); return result; @@ -118,7 +119,9 @@ export class BackendClient { 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.id !== undefined && message.method === undefined) { + if (message.method === "lithe/log") { + this.diagnostics.push(message.params); + } else if (message.id !== undefined && message.method === undefined) { this.#pending.get(message.id)?.(message); this.#pending.delete(message.id); } diff --git a/scripts/package.mjs b/scripts/package.mjs index 423bc68..18e958b 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -9,18 +9,17 @@ // every Mac. The unpacked package stays in dist/package/ for installing a // local development copy into Lithe. // -// The backend shades Lithe's Java plugin SDK pinned in sdk.lock.json: the -// JAR is downloaded once into .cache/sdk/ and refused unless its SHA-256 -// matches. LITHE_SDK_JAR= uses a local JAR instead; while the lock has -// no SHA-256 (the SDK is not released yet) that is the only way, and a -// release (--expect-tag) refuses it. +// The backend compiles the official SDK sources pinned by sdk.lock.json into +// the same JAR. Every input is verified before Maven runs; build outputs and +// plugin runtime state never become part of the source lock. // // Usage: node scripts/package.mjs [--expect-tag ] import { mavenTimeout, runCommand, withInterrupts, ZIP_TIMEOUT_MS } from "./process.mjs"; import { createReport } from "./report.mjs"; +import { verifySdk } from "./sdk/verify-sdk.mjs"; import { createHash } from "node:crypto"; -import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs"; import { join, resolve } from "node:path"; const PACKAGE_DIR = "io.github.lithe-idea.maven-build"; @@ -28,7 +27,6 @@ const ASSET_PREFIX = "maven-build"; const PLATFORM = "darwin"; const EXTENSION_JAR = "extension/target/lithe-maven-extension.jar"; const BACKEND_JAR = "backend/target/lithe-maven-backend.jar"; -const SDK_DOWNLOAD_TIMEOUT_MS = 60_000; const PACKAGE_ROOT = join("dist", "package"); const manifest = JSON.parse(readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8")); @@ -38,8 +36,6 @@ const pomVersion = (pom, artifact) => new RegExp(`${artifact}lithe-plugin-sdk-java<\/artifactId>\s*([^<]+)<\/version>/.exec(backendPom)?.[1]; 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`); @@ -51,17 +47,11 @@ if (extensionVersion !== manifest.version) { if (backendVersion !== manifest.version) { problems.push(`backend/pom.xml version ${backendVersion} must equal plugin.json version ${manifest.version}`); } -if (backendSdkVersion !== sdkLock.version) { - problems.push(`backend/pom.xml SDK version ${backendSdkVersion} must equal sdk.lock.json version ${sdkLock.version}`); -} -if (sdkLock.sha256 !== null && !/^[0-9a-f]{64}$/.test(sdkLock.sha256)) problems.push("sdk.lock.json sha256 must be 64 lowercase hex digits or null"); 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} (expected v${manifest.version})`); - if (sdkLock.sha256 === null) problems.push("a release needs a released SDK: pin its url and sha256 in sdk.lock.json"); - if (process.env.LITHE_SDK_JAR) problems.push("a release uses the SDK pinned in sdk.lock.json; unset LITHE_SDK_JAR"); } if (problems.length > 0) { for (const problem of problems) console.error(`✗ ${problem}`); @@ -70,36 +60,6 @@ if (problems.length > 0) { const sha256 = (path) => createHash("sha256").update(readFileSync(path)).digest("hex"); -/** The SDK JAR to shade, checked against sdk.lock.json. */ -async function sdkJar(signal) { - const local = process.env.LITHE_SDK_JAR; - if (local) { - const path = resolve(local); - if (!existsSync(path)) throw new Error(`LITHE_SDK_JAR ${path} does not exist`); - const actual = sha256(path); - if (sdkLock.sha256 !== null && actual !== sdkLock.sha256) { - throw new Error(`LITHE_SDK_JAR ${path} has SHA-256 ${actual}, but sdk.lock.json pins ${sdkLock.sha256}`); - } - if (sdkLock.sha256 === null) console.warn(`! using the unreleased SDK ${path} (SHA-256 ${actual}); sdk.lock.json pins no release yet`); - return path; - } - if (sdkLock.sha256 === null) { - throw new Error(`SDK ${sdkLock.version} is not released yet (sdk.lock.json has no sha256). ` - + `Build it from ${sdkLock.source.repository} ${sdkLock.source.ref} and set LITHE_SDK_JAR to ${sdkLock.source.jar}.`); - } - const cached = resolve(".cache", "sdk", `lithe-plugin-sdk-java-${sdkLock.version}.jar`); - if (existsSync(cached) && sha256(cached) === sdkLock.sha256) return cached; - const response = await fetch(sdkLock.url, { signal: AbortSignal.any([signal, AbortSignal.timeout(SDK_DOWNLOAD_TIMEOUT_MS)]) }); - if (!response.ok) throw new Error(`downloading ${sdkLock.url} failed with HTTP ${response.status}`); - const bytes = Buffer.from(await response.arrayBuffer()); - const actual = createHash("sha256").update(bytes).digest("hex"); - if (actual !== sdkLock.sha256) throw new Error(`${sdkLock.url} has SHA-256 ${actual}, but sdk.lock.json pins ${sdkLock.sha256}`); - mkdirSync(resolve(".cache", "sdk"), { recursive: true }); - writeFileSync(`${cached}.partial`, bytes); - renameSync(`${cached}.partial`, cached); - return cached; -} - /** Lithe refuses packages with symbolic links, so refuse them before zipping. */ function assertNoLinks(directory) { for (const name of readdirSync(directory)) { @@ -114,15 +74,15 @@ const report = createReport("package"); const timeoutMs = mavenTimeout(); await withInterrupts(async (signal) => { try { + await report.step("verify the vendored plugin SDK", verifySdk); await report.step("build the Maven extension", async () => { await runCommand(process.env.MVN ?? "mvn", ["-B", "-ntp", "-q", "-f", "extension/pom.xml", "clean", "package"], { timeoutMs, signal }); if (!existsSync(EXTENSION_JAR)) throw new Error(`${EXTENSION_JAR} was not built`); }); - const sdk = await report.step("check the plugin SDK", () => sdkJar(signal)); await report.step("build the Maven backend", async () => { await runCommand(process.env.MVN ?? "mvn", [ - "-B", "-ntp", "-q", "-f", "backend/pom.xml", `-Dlithe.sdk.jar=${sdk}`, "clean", "package", + "-B", "-ntp", "-q", "-f", "backend/pom.xml", "clean", "package", ], { timeoutMs, signal }); if (!existsSync(BACKEND_JAR)) throw new Error(`${BACKEND_JAR} was not built`); }); @@ -137,6 +97,7 @@ await withInterrupts(async (signal) => { cpSync(BACKEND_JAR, join(packageRoot, "lib", "lithe-maven-backend.jar")); cpSync("LICENSE", join(packageRoot, "LICENSE")); cpSync("NOTICE", join(packageRoot, "NOTICE")); + cpSync("vendor/LICENSE", join(packageRoot, "SDK-LICENSE")); assertNoLinks(packageRoot); }); diff --git a/scripts/sdk/verify-sdk.mjs b/scripts/sdk/verify-sdk.mjs new file mode 100644 index 0000000..b352bb4 --- /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-plugin-docs') { + 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) + || (entry.localChanges === true && (!Object.hasOwn(entry, 'upstreamSha256') || (entry.upstreamSha256 !== null && !/^[0-9a-f]{64}$/.test(entry.upstreamSha256))))) { + 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-backend.mjs b/scripts/test-backend.mjs index aaa7cfa..ccf5a22 100644 --- a/scripts/test-backend.mjs +++ b/scripts/test-backend.mjs @@ -252,6 +252,12 @@ async function test() { assert.match(error.message, /\[ERROR\] fake failure for the backend test/); assert.doesNotMatch(error.message, /Scanning for projects/); assert.equal(readFileSync(snapshotFile, "utf8"), saved); + const terminal = client.diagnostics.at(-1); + assert.equal(terminal.kind, "operationFailed"); + assert.equal(terminal.operation, "lithe/build/model"); + assert.equal(terminal.code, "maven.loadFailed"); + assert.ok(!JSON.stringify(client.diagnostics).includes("fake failure for the backend test")); + assert.equal(client.stderr, "", "Maven output and exceptions never cross the SDK stderr boundary"); control({}); }); diff --git a/scripts/test.mjs b/scripts/test.mjs index a14fee1..7779679 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -122,6 +122,15 @@ async function test(signal) { }); const model = await report.step("read the reactor model", () => backend.request("lithe/build/model", params())); capture("model.json", model); + await check("model diagnostics use one typed terminal without Maven output", async () => { + const terminals = backend.diagnostics.filter((entry) => entry.operation === "lithe/build/model"); + assert.equal(terminals.length, 1); + assert.equal(terminals[0].kind, "operationFinished"); + assert.ok(Number.isSafeInteger(terminals[0].durationMs) && terminals[0].durationMs >= 0); + assert.deepEqual(Object.keys(terminals[0]).sort(), ["durationMs", "kind", "operation", "operationId"]); + assert.equal(terminals[0].operationId, "2"); + assert.equal(backend.stderr, ""); + }); const byName = (name) => model.projects.find((project) => project.name === name); await check("the model lists the reactor and its aggregator tree", () => { diff --git a/scripts/verify-scripts.mjs b/scripts/verify-scripts.mjs index 9e9e380..268ae65 100644 --- a/scripts/verify-scripts.mjs +++ b/scripts/verify-scripts.mjs @@ -39,7 +39,7 @@ const unchanged = (name) => { await withInterrupts(async (signal) => { try { - for (const path of [packageId, "scripts", "extension", "backend", "sdk.lock.json", "test", "LICENSE", "NOTICE"]) { + for (const path of [packageId, "scripts", "extension", "backend", "vendor", "sdk.lock.json", "test", "LICENSE", "NOTICE"]) { cpSync(resolve(path), join(scratch, path), { recursive: true, filter: (source) => source !== resolve("extension/target") && source !== resolve("backend/target"), diff --git a/sdk.lock.json b/sdk.lock.json index 8ed6fa6..453b59b 100644 --- a/sdk.lock.json +++ b/sdk.lock.json @@ -1,6 +1,104 @@ { - "comment": "Lithe Java plugin SDK shaded into lib/lithe-maven-backend.jar. scripts/package.mjs downloads the official release URL and refuses a JAR whose SHA-256 differs.", - "version": "0.1.0", - "url": "https://github.com/1lck/Lithe-IDEA/releases/download/sdk-java-v0.1.0/lithe-plugin-sdk-java-0.1.0.jar", - "sha256": "8343df7541390b7b0cc337743bb4fd301aab8aa0faa96d5e512a913eebd0db5e" + "schemaVersion": 1, + "source": { + "repository": "https://github.com/Lithe-IDEA/lithe-plugin-docs", + "revision": "29b245c0e1d77c761d9032a3144a301d1818bfc7", + "localChanges": "Structured logging lithe/log implementation from the accompanying SDK working tree. Per-file hashes identify these reviewed inputs; no published release is claimed." + }, + "files": [ + { + "upstream": "LICENSE", + "path": "vendor/LICENSE", + "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" + }, + { + "upstream": "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": "c5430ea55f5ee73a88b8c6c3517cf6bc2237827b009ae1844c105254b7f48a24", + "localChanges": true, + "upstreamSha256": "c1943d63121ce20dfadf24dfcac50581da4371356fb5f7ee30962b41b2fd04a2" + }, + { + "upstream": "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": "c41fcc2cbc6533215ee9034409292ddeb6237d6c3defdd65b2cdfb8fb848dde8", + "localChanges": true, + "upstreamSha256": "8157d980a585b85ed31b96ad974fe980e167b6c0b7701b2636328ba84c0b62af" + }, + { + "upstream": "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", + "localChanges": true, + "upstreamSha256": "87eb1a9b673f59774ac1688393f62f8aa5379ead1ed2464b50ab64a0d6ad80d9" + }, + { + "upstream": "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": "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": "e6b70f167f1b030509fccf399745bc7693023eabeff1201696e866340d546ec9", + "localChanges": true, + "upstreamSha256": null + }, + { + "upstream": "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": "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": "ff2cc8830645722173a257aec66adec94cfae7d5a91501b1024e2843954dc8f1" + }, + { + "upstream": "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": "79e337d8fc495c1c993d33205f70d79a0baa5fe49c054ef7032f02ce500f147c", + "localChanges": true, + "upstreamSha256": "1830ac36651759f3b4f77bda5fb23fd4b478a2c153671fc01920af38faefd09f" + }, + { + "upstream": "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": "8072d652209042f578c3eaf49600f8797ed19662b8119581772f60a3b972fa96" + }, + { + "upstream": "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": "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", + "localChanges": true, + "upstreamSha256": "33dec00015fc1611084bd99063e90dbce3c306e99b83faed1cd6a2f8cab24de7" + }, + { + "upstream": "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": "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": "86b50e196fb23ccd28e576b524a8da2d8928ac3113bbcd105180ceaef9981319", + "localChanges": true, + "upstreamSha256": "e1a499d9fc526179c624be1084188e2a394e46f5d5c512cc5c3e3b3d39661aeb" + }, + { + "upstream": "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": "b491ba1a55f869bf29ba337684fe0a1c42c00b9ae8887dac508cc508748d419d" + }, + { + "upstream": "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" + } + ] } 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..b71b683 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -0,0 +1,1417 @@ +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.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/*}) of plugin-function protocols 2 and 3 + * 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 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(0, 0); + + private final int functionsVersion; + private final int buildVersion; + + Negotiated(int functionsVersion, int buildVersion) { + this.functionsVersion = functionsVersion; + this.buildVersion = buildVersion; + } + + /** Whether the host negotiated plugin functions ({@code litheFunctions}). */ + public boolean functions() { + return functionsVersion > 0; + } + + /** + * Selected plugin-function version (1-3), or zero when unavailable. + * Version 2 adds host credentials; version 3 workspace contexts, the + * other host services, and host notifications. + */ + public int functionsVersion() { + return functionsVersion; + } + + /** Whether the host negotiated typed build requests. */ + public boolean build() { + return buildVersion > 0; + } + + /** Selected build protocol version, or zero when unavailable. */ + public int buildVersion() { + return buildVersion; + } + } + + private enum Phase { IDLE, LISTENING, INITIALIZING, READY, SHUTTING_DOWN, EXITED } + + /** 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"); + BUILD_FORMATS = Collections.unmodifiableMap(formats); + } + + private volatile boolean logging; + 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 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()); + /** 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("litheLogging"))) { + throw new PluginSdkError("sdk.capabilities.reserved", + "litheBuild and litheFunctions 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 of plugin-function protocols 2 and 3, usable once the + * session is ready. Prefer a handler's {@link CallContext#host()}, whose + * requests end with the call. + */ + 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; requires build protocol 2 or newer. */ + public Backend onExecute(Handler handler) { + return declareBuild(Protocol.BUILD_EXECUTE, handler); + } + + /** Runs exact test selectors; requires build protocol 3 or newer. */ + 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; requires build protocol 5. */ + public Backend onPrepareDebug(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_DEBUG, handler); + } + + /** Prepares a portable application launch with build protocol 4 or newer. */ + public Backend onPrepareRun(Handler handler) { + return declareBuild(Protocol.BUILD_PREPARE_RUN, 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; + } + + /** 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 (protocol 3). 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} (protocol 3) 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; + } + Handler build; + RequestHandler handler; + synchronized (lock) { + build = negotiated.buildVersion() >= Protocol.buildMethodVersion(method) ? 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.functionsVersion() < Protocol.CONTEXT_VERSION || !(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"), 1); + if (!logging) { + phase = Phase.LISTENING; + respond(id, null, error(Protocol.INVALID_REQUEST, "The backend requires litheLogging version 1.")); + return; + } + int buildVersion = 0; + if (!buildHandlers.isEmpty()) { + for (int version = Protocol.BUILD_VERSION; version > 0; version--) { + if (offers(offered.get("litheBuild"), version)) { + buildVersion = version; + break; + } + } + } + int functionsVersion = 0; + for (int version = Protocol.FUNCTIONS_VERSION; version > 0; version--) { + if (offers(offered.get("litheFunctions"), version)) { + functionsVersion = version; + break; + } + } + agreed = new Negotiated(functionsVersion, buildVersion); + 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", 1)); + if (agreed.build()) { + experimental.put("litheBuild", singleton("version", agreed.buildVersion())); + } + if (agreed.functions()) { + List offered = new ArrayList<>(); + for (String functionId : functionIds()) { + offered.add(singleton("id", functionId)); + } + Map entry = singleton("version", agreed.functionsVersion()); + 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 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")); + 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); + }; + run(id, function, operation, workspaceContext, context -> handler.handle(arguments, context), + Backend::functionResult, () -> reporting.set(false), progress); + } + + private void invokeBuild(Object id, String method, Map arguments, Handler handler) { + if (arguments.containsKey("modelInputs") && negotiated.buildVersion() < 6) { + respond(id, null, error(Protocol.INVALID_PARAMS, "Model inputs require build protocol 6.")); + return; + } + if (!Protocol.buildProgress(method)) { + run(id, null, null, null, context -> handler.handle(arguments, context), result -> buildResult(method, result), null, null, method); + 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); + } + + 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); + } + + private void run(Object id, String functionId, String operationId, Map workspaceContext, + Invocation invoke, Shape shape, Runnable onSettled, CallContext.ProgressSink progress, String diagnosticOperation) { + 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)), workspaceContext); + 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() == 1)) { + throw new PluginSdkError("sdk.build.invalidResult", method + " returned a version other than 1."); + } + document.put("format", expected); + document.put("version", 1); + } + 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 session's wire, for host services. */ + private final class Wire implements HostChannel.Transport { + @Override + public int version() { + return negotiated.functionsVersion(); + } + + @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..ceffda4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/CallContext.java @@ -0,0 +1,119 @@ +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; + + CallContext(Cancellation cancellation, Backend backend, String functionId, String operationId, ProgressSink progress, + Host host, Map workspaceContext) { + this.cancellation = cancellation; + this.backend = backend; + this.functionId = functionId; + this.operationId = operationId; + this.progress = progress; + this.host = host; + this.workspaceContext = workspaceContext; + } + + /** + * 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. */ + 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, + * from protocol 3, 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 (protocol 3), or null: for other calls, before protocol 3, + * and for an invocation outside a workspace. Pass it to the + * {@link Host} methods that name a context. + */ + public Map workspaceContext() { + return workspaceContext; + } +} 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..6912594 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Diagnostics.java @@ -0,0 +1,71 @@ +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/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")); + 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..5e67d63 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -0,0 +1,520 @@ +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/*}) of plugin-function protocols 2 and 3: + * credentials from version 2; workspace contexts, files, documents, the + * editor, previews, the browser, messages, and capability discovery from + * version 3. 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, + * from version 3, 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; + 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(); + + Host(HostChannel channel, List scope) { + this.channel = channel; + this.scope = Collections.unmodifiableList(new ArrayList<>(scope)); + } + + /** The negotiated plugin-function version, or 0 before or without one. */ + public int version() { + return channel.version(); + } + + /** + * The same services, with requests also cancelled by {@code cancellation}, + * for work a plugin may stop for its own reasons. + */ + 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); + } + + /** + * 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; needs protocol 3. + */ + public CompletableFuture> capabilities() { + return channel.capabilities(); + } + + /** + * Whether this session may call {@code method}: from {@link #capabilities} + * on protocol 3, the credential methods on protocol 2. + */ + 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; + } + + /** + * {@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 (protocol 2). */ + 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 (protocol 3). 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 (protocol 3). */ + 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 (protocol 3). */ + 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 (protocol 3). */ + 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 (protocol 3). */ + 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 (protocol 3). */ + 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 (protocol 3). {@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); + } + } + + /** 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..274fbd4 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostChannel.java @@ -0,0 +1,504 @@ +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 for plugin-function protocols 2 and 3. 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} from version 3, and subscription events routed by + * ID, in order, off the reader thread. + * + *

Contract: {@code contract/v1/README.md}, "Host services (protocol + * version 2)" and the version 3 sections after it. + */ +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 { + /** The negotiated plugin-function version, or 0 before or without one. */ + int version(); + + 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; + } + + int version() { + return transport.version(); + } + + /** + * 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 from version 3, 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.version() < Protocol.HOST_SERVICES_VERSION) { + // The answer Core would give, without the round trip. + return failed(unavailable(method, + "The host did not negotiate plugin-function protocol 2 or later, which offers 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, from version 3. */ + CompletableFuture> capabilities() { + if (transport.version() < Protocol.CONTEXT_VERSION) { + return failed(unavailable(Protocol.HOST_GET_CAPABILITIES, + "Capability discovery needs plugin-function protocol 3.")); + } + 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 version 3 the answer + * comes from {@code getCapabilities}; version 2 has no discovery, so it + * reports the methods version 2 defines, and a missing grant still fails + * the request. + */ + CompletableFuture supports(String method) { + if (transport.version() >= Protocol.CONTEXT_VERSION) { + 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; + }); + } + return CompletableFuture.completedFuture(transport.version() >= Protocol.HOST_SERVICES_VERSION + && (Protocol.HOST_CREDENTIALS_GET.equals(method) + || Protocol.HOST_CREDENTIALS_SET.equals(method) + || Protocol.HOST_CREDENTIALS_DELETE.equals(method))); + } + + /** 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: + // from version 3 Core answers it at once, before version 3 the + // host still finishes the request. + 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 (transport.version() >= Protocol.CONTEXT_VERSION) { + 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..dbd452c --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/HostError.java @@ -0,0 +1,96 @@ +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 + * version 3 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 of plugin-function protocol 3 and their + * JSON-RPC numbers. A later host adds codes after {@code -32021}. + */ + 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 = 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; + } + + /** + * The failure for a JSON-RPC error answer. A host method without a known + * code is a host failure: from version 3 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..6764cca --- /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 in protocol version 1, 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..c4e2ff8 --- /dev/null +++ b/vendor/lithe-plugin-sdk-java/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -0,0 +1,230 @@ +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/lithe-core/src/lsp/interface/plugin_function.rs} 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 { + /** Protocol versions this SDK can answer: the highest of each. */ + public static final int FUNCTIONS_VERSION = 3; + public static final int BUILD_VERSION = 6; + + /** First plugin-function version with host services (credentials). */ + public static final int HOST_SERVICES_VERSION = 2; + /** First plugin-function version with workspace contexts, discovery, and host notifications. */ + public static final int CONTEXT_VERSION = 3; + + 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_PROGRESS = "lithe/build/progress"; + + /** + * Backend-to-host requests of plugin-function protocols 2 and 3. From + * version 3 the host adds methods without a new version; + * {@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"; + + /** Host-to-backend notifications of plugin-function protocol 3. */ + 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; + + /** Minimum negotiated version; unknown methods can never pass admission. */ + static int buildMethodVersion(String method) { + if (BUILD_MODEL.equals(method) || BUILD_DEPENDENCIES.equals(method)) return 1; + if (BUILD_EXECUTE.equals(method)) return 2; + if (BUILD_TEST.equals(method) || BUILD_DISCOVER_TESTS.equals(method)) return 3; + if (BUILD_PREPARE_DEBUG.equals(method)) return 5; + if (BUILD_PREPARE_RUN.equals(method)) return 4; + return Integer.MAX_VALUE; + } + + 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 protocols 2 and 3: 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 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; + } + } +}