diff --git a/.agents/notes/implemented/architecture/2026-10-20-plugin-function-contract.md b/.agents/notes/implemented/architecture/2026-10-20-plugin-function-contract.md index 48cb831555..56c22bb06e 100644 --- a/.agents/notes/implemented/architecture/2026-10-20-plugin-function-contract.md +++ b/.agents/notes/implemented/architecture/2026-10-20-plugin-function-contract.md @@ -10,6 +10,8 @@ Rust Core 负责校验、路由、协商和测试(`lsp/interface/plugin_function.rs`、`lsp.functionRequest`)。macOS 宿主的调用入口见[宿主调用插件函数的入口](2026-10-20-host-plugin-function-invocation.md):只有插件自己的网页、只对插件自己的构建 Provider 进程。版本 1 不提供任何宿主能力。旧插件包和旧后端不受影响。 +函数默认仍然私有。协议 4(见决策 8)新增了一条经过 Core 中转的跨插件通道:插件在清单里用 `pluginFunctions.exports` 明确选择导出函数、用 `calls` 声明要调用的函数,协商到协议 4 的后端用 `lithe/host/functions/providers` 与 `lithe/host/functions/invoke` 发现并调用。这条通道只放宽“私有”这一条,不放宽下面的递归、归属和信任规则。 + ## 问题 Issue #1351 要把 Maven、Gradle 这类插件从“只给声明”推进到“插件自带逻辑”。动手前盘点了已有的几条通道,发现它们各自解决一部分,但没有一条同时具备回复、进度、取消和归属: @@ -37,11 +39,11 @@ Issue #1351 要把 Maven、Gradle 这类插件从“只给声明”推进到“ ### 2. 禁止回调自己 -后端向宿主请求 `lithe/function/invoke` 或任何 `lithe/build/*`,Core 直接回 JSON-RPC `-32601`,`data.code` 是 `plugin.function.recursiveCall`。宿主能力只开放进程运行、输出、存储这类原语,不开放“再进入某个领域注册表”的入口:Maven 处理器需要跑 Maven,应当请求宿主的进程能力,而不是请求宿主“执行 Maven 任务”。版本 1 一个宿主能力都没有开放,`lithe/host/*` 一律是 `plugin.host.unavailable`;协议 2 和 3 的宿主能力都随新的协议版本开放,每个都带着参数、权限和所属操作;从协议 3 起,新的宿主能力改为在协议 3 内新增,后端用 `getCapabilities` 发现,见[插件后端的工作区上下文](2026-10-30-plugin-backend-workspace-context.md)的“协议 3 内只增不改”。 +后端向宿主请求 `lithe/function/invoke` 或任何 `lithe/build/*`,Core 直接回 JSON-RPC `-32601`,`data.code` 是 `plugin.function.recursiveCall`。宿主能力只开放进程运行、输出、存储这类原语,不开放“再进入某个领域注册表”的入口:Maven 处理器需要跑 Maven,应当请求宿主的进程能力,而不是请求宿主“执行 Maven 任务”。版本 1 一个宿主能力都没有开放,`lithe/host/*` 一律是 `plugin.host.unavailable`;协议 2 和 3 的宿主能力都随新的协议版本开放,每个都带着参数、权限和所属操作;协议 4 的 `lithe/host/functions/*` 是跨插件中转,它调用的是另一个插件的导出函数,不会“再进入”本插件或领域注册表,且由调用链检查保证不绕回自己(决策 8);从协议 3 起,新的宿主能力改为在协议 3 内新增,后端用 `getCapabilities` 发现,见[插件后端的工作区上下文](2026-10-30-plugin-backend-workspace-context.md)的“协议 3 内只增不改”。 ### 3. 引用、注册与撤回 -- 函数引用是 `{pluginID, functionID}`。Core 先按插件路由:只有 `lsp.startServer` 时带同一个 `pluginId` 的会话才提供该插件的函数;宿主自己的语言服务器没有 `pluginId`,不发送或接受函数协议协商,不保留函数注册表,也不发布函数发现事件,增删请求一律以 `-32601` 拒绝。所以一个插件拿不到另一个插件的函数,也不需要在宿主里按插件名判断。 +- 函数引用是 `{pluginID, functionID}`。Core 先按插件路由:只有 `lsp.startServer` 时带同一个 `pluginId` 的会话才提供该插件的函数;宿主自己的语言服务器没有 `pluginId`,不发送或接受函数协议协商,不保留函数注册表,也不发布函数发现事件,增删请求一律以 `-32601` 拒绝。所以一个插件拿不到另一个插件的**私有**函数,也不需要在宿主里按插件名判断;引用别人的私有函数仍是 `plugin.function.wrongPlugin`,该检查不因跨插件调用而删除。只有被调方在清单里导出、运行时又注册过的函数,才能由另一个插件通过协议 4 的中转调用(决策 8),那条路径由 Core 自己的中转检查把关(清单没导出的函数在那里是 `plugin.function.notExported`),不会把别人的私有函数变成可以用 `lsp.functionRequest` 引用的函数。 - 函数 ID 是点分的 lowerCamelCase 段(`snapshot.refresh`),最长 128 字节,每个会话最多 256 个。 - 后端在 `initialize` 回答里给出初始函数,之后用 `lithe/function/register`、`lithe/function/unregister` 增删。每个请求要么全部生效,要么整体拒绝(`plugin.function.invalidRegistration`),不会留下半个注册表;初始回答里有坏 ID 时整个协议不算协商成功,原因相同。插件会话成功完成 `initialize` 函数协议协商后发布一次 `functionsChanged`,带排序后的初始列表与空 `removed`,即使列表为空也发布;宿主因此只订阅事件就能发现初始函数,不必先尝试调用。 - 撤回一个正在执行的函数时,调用立即以 `plugin.function.revoked` 结束,Core 同时发 `$/cancelRequest`。 @@ -67,9 +69,39 @@ Issue #1351 要把 Maven、Gradle 这类插件从“只给声明”推进到“ ### 7. 旧包兼容 -- 所有 API 级别的旧插件包不变:函数没有新增清单字段。 +- 所有 API 级别的旧插件包不变:私有函数没有新增清单字段;跨插件调用用的 `pluginFunctions` 是新能力键(`requires.pluginFunctions: 1`),只有声明它的插件会被不支持中转的宿主拒绝。 - 不认识 `litheFunctions` 的后端照常服务语言和 `litheBuild`,不会收到函数调用;它发来的函数请求得到 `-32601`。 -- 对方不能忽略的新字段,只能放进新的协议版本,与旧版本一起提供。宿主能力从协议 3 起在版本内新增,靠 `getCapabilities` 发现,不再单独升版本。 +- 对方不能忽略的新字段,只能放进新的协议版本,与旧版本一起提供:协议 4 只新增中转方法和中转调用里的 `caller` 字段,协商到 3 及以下的后端既不能调用前者,也收不到后者。宿主能力从协议 3 起在版本内新增,靠 `getCapabilities` 发现,不再单独升版本。 + +### 8. 跨插件调用:协议 4 的中转(第一阶段) + +这是[插件依赖、导出与跨包授权](../../proposed/architecture/2026-10-25-plugin-dependencies-and-exports.md)里第一阶段的落地部分(对应计划 API-35 的第一阶段,不新增 API 编号)。它只解决“已安装、已启用的两个插件之间调用一个被明确导出的函数”,不做安装依赖解析、版本冲突或依赖闭包。 + +**清单。** 新能力键 `requires.pluginFunctions: 1` 加顶层 `pluginFunctions {exports, calls}`(需要 `pluginAPIVersion` 3、`backend` 和 `serverProcess`)。导出是对象 `{id, version, context}`,`context` 是封闭集合,第一阶段只有 `"workspace"`;缺失或未知的 `context` 让整个清单以 `plugin.manifest.invalid` 失败,所以没写明调用上下文的导出一律不能被调用。调用方声明 `{id, version}`,只写函数 ID,不写被调方的插件 ID:被调方由运行时发现。导出只是选择加入,后端仍要用 `lithe/function/register` 注册;清单没导出的函数不管后端注册什么都仍是私有。 + +**协议。** `litheFunctions` 的版本集合从 1、2、3 增加到 4。只有协商到 4 的后端、并且插件声明了至少一个调用时,才能用两个宿主请求:`lithe/host/functions/providers {functionID}` 返回 `{providers: [{pluginID, version}]}`(不含调用方,按插件 ID 排序),`lithe/host/functions/invoke {pluginID, functionID, context, params?, timeoutMilliseconds?, parentOperationID?}` 返回 `{value}`。协议 3 及以下调用得到 `plugin.host.unavailable`,未声明调用的插件得到 `plugin.host.permissionDenied`。 + +**Core 的检查与顺序。** 所有逻辑在 Rust Core(`lsp/interface/function_relay.rs`、`engine_function_relay.rs`),写入被调方进程之前先同步检查,第一个失败的赢:调用方已声明 → 被调方已安装且启用 → 被调方导出 → 版本相等 → 上下文有效 → 本地工作区 → 参数不超过 256 KiB → `parentOperationID` 指向的调用仍在运行 → 调用链无环 → 深度不超过 4 → 每个调用方最多 8 个并发中转。结果同样限 256 KiB,默认超时 60 秒、最多 10 分钟。每个新拒绝都有自己的字符串码和数值码,一个码只表示一个含义;超时、取消、上下文过期和远程工作区复用已有的宿主错误码,因为含义相同。 + +**调用链和取消。** Core 记录调用链。被调方在服务一个中转调用时再发出新调用,要在 `parentOperationID`(可选,1 到 128 字节的字符串)里填它正在服务的那个调用的 `operationID`,也就是 Core 转发 `lithe/function/invoke` 时写进去的编号。新调用只是那个调用的子调用:调用链是那个调用的链再加上发起方;那个调用被取消、超时或结束,新调用随之取消。调用到链上已有的插件(包括自己调自己)是 `plugin.function.callCycle`。因此“Maven 通知 Java 配置变了”这类调用里,Java 不能在处理时再回调 Maven,要先记下新值,或等调用结束后再调。三种特殊情况: + +- 填的是宿主直接发起(不是中转)的调用:新调用开始一条新链。 +- 填的是这个后端并不在服务的调用(已经结束,或根本不存在):以 `plugin.host.cancelled` 拒绝,消息是 “The call this request belongs to is not running.”。这一项排在参数大小检查之后、成环和深度检查之前。 +- 不填:沿用旧规则,新调用算作后端当前正在服务的每一个中转调用的子调用,只为兼容旧后端保留,SDK 应当总是填。之所以要加这个字段,是因为后端同时服务多个中转调用时,Core 无法知道新调用属于哪一个,只能把它挂在全部调用下面,取消和成环、深度检查就会牵连无关的调用。 + +取消一个调用、它超时或结束,或调用方会话结束,会沿链向下给每个子调用的被调方发 `$/cancelRequest`。 + +**运行中的调用。** 一个正在运行的中转调用,正常情况下由被调方会话自己的超时结束。如果被调方一直不回答,中转在截止时间之后再宽限 2 秒,就以 `plugin.host.timeout` 结束该调用,并取消被调方的这个操作。 + +**信任不传递。** 被调方用自己的权限、状态目录和凭据运行;调用方的权限不会借给它,被调方的权限也不属于调用方。Core 不把调用方的插件 ID 写进被调方的会话身份,只在转发的 `lithe/function/invoke` 里加一个由 Core 填写的顶层 `caller: {pluginID}`,仅在被调方协商到协议 4 时出现,宿主自己发起的调用没有这个字段(没有即宿主);调用方在宿主请求里自带的同名顶层字段会被 `plugin.host.unsupportedOption` 拒绝,所以按调用方区分的状态可以放心以它为键。导出函数不得接受调用方传来的可执行文件路径或命令并据此启动进程,这条写进契约 README,由被调方自己负责。没有新增权限项:调用方的 `calls` 声明加被调方的 `exports` 就是双方的同意。 + +**被调方没在运行。** Core 只发出运行时事件 `functionProviderStartRequired {pluginID}`;宿主(Swift)把它当作 I/O,按普通的插件启动流程启动那个后端,Core 等被调方协商并注册函数后再派发,最多等 30 秒,超时按 `plugin.function.providerUnavailable` 失败。Core 从不替宿主启动后端,也不自动重试。 + +**热激活。** 宿主用 Core 命令 `lsp.configureFunctionRelay` 发布插件与工作区上下文的快照,Core 据此更新发现结果,并让快照已不允许的进行中调用立刻以明确的错误结束:被调方被禁用、卸载、更新后不再导出或改了版本是 `providerDisabled`,被调方后端退出或撤回函数是 `providerUnavailable`,调用方更新后不再声明是 `notDeclared`。工作区上下文被宿主关闭,或 generation 被替换成更新的值时,携带该上下文的中转调用以 `plugin.host.contextExpired` 结束,既包括还在等被调方启动的调用,也包括已经在运行的调用,运行中的被调方同时收到取消。禁用、启用、替换和卸载对中转即时生效,不需要重启。但只在启动时注册带后端插件的宿主(目前是 macOS),要重启后才会在发现结果里列出新安装或更新的带后端插件。 + +**远程工作区。** 中转只用于本地工作区(计划 API-40);远程工作区的上下文得到 `plugin.host.authorityUnsupported`。 + +**不动的旧规则。** 后端发 `lithe/function/invoke` 或任何 `lithe/build/*` 仍是 `plugin.function.recursiveCall`;引用别人的私有函数仍是 `plugin.function.wrongPlugin`。新的跨插件通道没有删除任何检查。 ### 正确做法 @@ -115,6 +147,22 @@ Maven 插件窗口的“刷新快照”按钮 后端直接回显宿主 ID 虽少一次映射,但函数 A 已结束、宿主用同一 ID 调用函数 B 时,A 的迟到进度仍会被误认成 B。永久保存已用 ID 并拒绝复用也能隔离,却会引入随会话历史增长的墓碑集合,并改变宿主调用习惯。采用每次调用唯一的后端 ID:只保留正在执行的关联,后端原样回显,宿主接口继续允许在终止后复用 ID;代价是 Core 必须在全部终止路径删除关联并在事件出口转换 ID。 +### 让调用方直接连被调方的进程,或由宿主在 Swift 里中转 + +让两个后端互相知道对方的管道,或在 macOS 层按插件名转发。被否:调用方会看到被调方的进程细节,清单声明、调用链、取消和限额无处统一执行,Windows 也要再写一份。所有检查放在 Rust Core,宿主只做“启动被调方后端”这一步 I/O。 + +### 导出时带上调用方的权限,或在被调方会话里写入调用方身份 + +被否:信任会沿调用链传递,社区插件调用官方插件就借到官方权限,或被调方的存储和凭据被按调用方分叉。被调方始终以自己的权限运行,调用方身份只在一个由 Core 填写的 `caller` 字段里出现,不进入会话身份。 + +### 清单只写函数 ID 的导出,不写版本和调用上下文 + +被否:不兼容的参数变更无法发现,也没有“这个函数在什么上下文里可以被别人调用”的明确声明。导出要有整数版本和封闭的 `context`,调用方声明期望的版本,不相等就是 `plugin.function.versionMismatch`。 + +### 给中转新增一个权限项 + +被否:调用方的 `calls` 与被调方的 `exports` 已经是双方各自写在清单里的同意,再加一个权限只会让安装确认多一层不能表达差别的开关。以后如果导出需要额外授权,随新的 `context` 值一起设计。 + ### 复用 LSP 的 `workspace/executeCommand` 被否:它没有插件归属、没有稳定错误码和进度约定,命令名也和语言服务器自己的命令混在一起;JDT LS 这类共享进程会收到本不属于它的调用。 @@ -126,18 +174,28 @@ Maven 插件窗口的“刷新快照”按钮 - 代价:函数不进清单,安装审查看不到插件会提供哪些函数;如果以后函数需要额外权限,必须随新协议版本补审查。 - 代价:本 Note 只覆盖 Core 一侧;宿主入口另见[宿主调用插件函数的入口](2026-10-20-host-plugin-function-invocation.md),宿主能力仍未开放。 - 后续:后端一侧的官方实现见 [官方插件后端 SDK(Node)](2026-10-20-plugin-backend-sdk.md),它只实现本契约,不新增线上字段。 +- 收益:跨插件调用的所有判断(声明、导出、版本、调用链、深度、并发、字节上限、超时、取消)都在 Rust Core,macOS 与 Windows 以后共用;macOS 宿主只发布快照和启动被调方后端。 +- 收益:每个后端会话有自己的一条写入队列。某个后端不读它的 stdin(标准输入),只会拖慢发给它自己的调用和回复,其他插件的中转调用照常进行。 +- 代价:如果对某个后端的写入卡住超过请求超时,Core 会把这个会话按传输失败结束(`transportFailed`,阶段 `relayWrite`),它的调用和任何会话失败一样结束,不会再继续等。 +- 代价:macOS 对带后端的插件仍只在启动时注册,所以新安装或更新的后端插件要重启后才会出现在发现结果里;禁用、启用、替换和卸载是即时的。让带后端的插件免重启激活属于 #1515 的后续工作。 - 代价:没有操作系统级沙盒,隔离仍只到进程和通信通道。 ## 验证 - `cargo test -p lithe-core --lib plugin_function`:`function-protocol.json` 的协商、注册、调用、结果、进度和后端请求全部标准答案,以及消息截断、超大结果和注册上限。 - `cargo test -p lithe-core --lib lsp::interface::engine`:用脚本化后端覆盖路由与结果、失败与插件错误码、初始函数列表(包括空列表)只靠事件发现、取消/超时/成功/失败/撤回后复用宿主 ID 的迟到进度隔离、函数结束后复用 ID 发构建请求不受旧函数撤回影响、会话停止/失败后清空注册表且迟到注册不能恢复能力、自身超时、只支持 `litheBuild` 的旧后端照常工作、宿主自有会话不提供函数、后端请求回调自己被拒绝。 +- `cargo test -p lithe-core plugins::plugin_functions`、`cargo test -p lithe-core lsp::interface::function_relay`、`cargo test -p lithe-core lsp::interface::engine`:`pluginFunctions` 清单校验,纯逻辑的深度与并发限额,以及用脚本化后端覆盖发现与调用、每一个拒绝码及其顺序、调用链、取消沿链传播、被调方未运行时的启动请求与超时、热激活后的进行中调用、`caller` 字段只在协议 4 出现且伪造被拒、旧后端不受影响。示例用一个 Python 插件调用一个 Go 插件的导出。 +- `scripts/macos/test/test-macos.sh --filter "MacPluginBackendSessionsTests|PluginHostServiceDispatchTests|PluginPublicHostAPITests"`:快照发布、启动被调方后端的 I/O、`functions` 服务授权。 - `./scripts/architecture/verify-shared-contracts.sh`:`function-protocol.json` 的 schema 版本、协议名、用例名唯一、错误码都在 README 里有文档、不含机器路径。 - `./scripts/rust-core/verify-rust-core.sh` 与 `./scripts/rust-core/verify-rust-core-comments.sh`:Core 编译、测试和注释规范。 ## 适用范围 - `rust/lithe-core/src/lsp/interface/plugin_function.rs` +- `rust/lithe-core/src/lsp/interface/function_relay.rs` +- `rust/lithe-core/src/lsp/interface/engine_function_relay.rs` +- `rust/lithe-core/src/plugins/plugin_functions.rs` +- `macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift` - `rust/lithe-core/src/lsp/interface/client.rs` - `rust/lithe-core/src/lsp/interface/engine.rs` - `rust/lithe-core/src/protocol/command.rs` diff --git a/.agents/notes/proposed/architecture/2026-10-25-plugin-dependencies-and-exports.md b/.agents/notes/proposed/architecture/2026-10-25-plugin-dependencies-and-exports.md index f4aee158ab..a182f74ddf 100644 --- a/.agents/notes/proposed/architecture/2026-10-25-plugin-dependencies-and-exports.md +++ b/.agents/notes/proposed/architecture/2026-10-25-plugin-dependencies-and-exports.md @@ -6,7 +6,7 @@ 插件之间复用运行时、JSON 声明和计算能力属于整个插件平台,不应由某个 Debug 格式顺带定义。本提案从 [Debug #1210](https://github.com/1lck/Lithe-IDEA/issues/1210) 拆出依赖、导出和授权,挂在[公共扩展契约](2026-10-13-public-extension-contract-and-provider-api.md)下;Debug 的 Registry 与第三方 DAP 接入不依赖它。 -方向仍是插件好写、共享逻辑尽量复用,但安装闭包(某个插件及其全部间接依赖)、版本冲突和信任必须先有明确规则。以下只是待单独实施的决策边界,不开放 `pluginDependencies`、`exports`、跨包函数或工作流字段,也不更改现有私有函数契约。 +方向仍是插件好写、共享逻辑尽量复用,但安装闭包(某个插件及其全部间接依赖)、版本冲突和信任必须先有明确规则。其中**第一阶段已经落地**:两个已安装、已启用的插件之间,可以经 Rust Core 中转调用被明确导出的函数(见提案第 5 节)。其余仍只是待单独实施的决策边界:安装依赖、版本范围解析、依赖闭包、跨包资源租约和工作流字段都没有开放,`pluginDependencies` 也不存在。 ## 问题 @@ -45,16 +45,29 @@ 若需要跨包资源引用,正式契约使用显式带标签的类型,例如专门的 backend/lease 变体;不靠普通参数恰好叫 `backendRef` 来识别。宿主签发的租约记录资源所有者、调用链、操作与失效代次,跨包只传受限引用;`${pluginDir}` 永远按声明资源的包解析。用户参数里的同名字符串和对象仍然只是数据。 -跨包操作只能由宿主在已授权的导出边界调度到资源所属会话,不能将调用方 pluginID 写入目标会话。后端回调宿主重新进入注册表的禁止规则保留;否则等待中的处理器可能等待自己。如何将新授权模型加入函数路由、如何区分私有与公开调用,需要单独版本化,不能删除旧 `wrongPlugin` 或 `recursiveCall` 检查来实现。 +跨包操作只能在已授权的导出边界调度到资源所属会话,不能将调用方 pluginID 写入目标会话。(第一阶段由 Rust Core 在导出边界中转,宿主只负责启动被调方后端;调用方 ID 只出现在 Core 填写的 `caller` 请求字段里。)后端回调宿主重新进入注册表的禁止规则保留;否则等待中的处理器可能等待自己。如何将新授权模型加入函数路由、如何区分私有与公开调用,需要单独版本化,不能删除旧 `wrongPlugin` 或 `recursiveCall` 检查来实现。 ### 4. 不在此处偷改已实现决策 -[插件函数契约](../../implemented/architecture/2026-10-20-plugin-function-contract.md)仍是当前行为真源:函数私有,领域结果走类型化契约。此提案没有修改它。若以后采用函数传输领域结果或依赖导出,先在实现 PR 中修订对应决策,给出输入/结果、授权、错误优先级与兼容 fixtures,再改 Core 和双端宿主。 +[插件函数契约](../../implemented/architecture/2026-10-20-plugin-function-contract.md)仍是当前行为真源:函数默认私有,领域结果走类型化契约。第一阶段在它的决策 8 里增加了“明确导出的函数可经 Core 中转被另一个插件调用”,同一 PR 给出了输入/结果、错误优先级与兼容 fixtures;私有、递归和领域结果走类型化契约的规则没有改动。以后若采用函数传输领域结果,或让导出带上依赖闭包、资源租约,仍须先在实现 PR 中修订对应决策,再改 Core 和双端宿主。 新的字段属于统一 `plugin.json` 的能力演进;基础权限或身份语义变化需要新的基础 API。没有 Debug draftVersion,也不要求现有 Build/VCS/UI/语言插件迁移。现有 `backend: 1` 的全局、网页触发行为不变;新的进程共享方式另行版本化。 通用 workflow 尚无证明必要的真实输入,不在这个依赖提案里重新引入 steps 或取值语言。先通过实际导出契约完成复用,再判断是否有需要由宿主解释的公共流程。 +### 5. 第一阶段已落地的部分 + +对应计划 API-35 的第一阶段,不新增 API 编号,决策正文写在[插件函数契约](../../implemented/architecture/2026-10-20-plugin-function-contract.md)的决策 8,契约写在 `shared/contracts/plugins/v1/README.md` 的 “Cross-plugin calls (protocol version 4)”。它只落地了本提案里不依赖安装解析的那一部分: + +- 清单新能力键 `requires.pluginFunctions: 1` 与顶层 `pluginFunctions {exports, calls}`。导出是 `{id, version, context}`,`context` 是封闭集合,第一阶段只有 `"workspace"`,缺失或未知就拒绝整个清单:这兑现了第 2 节“没有定义可接受调用上下文的导出,不允许跨包调用”。调用方只声明 `{id, version}`,版本必须相等,不相等是 `plugin.function.versionMismatch`。 +- 协议 `litheFunctions` 增加版本 4,只有协商到 4 的后端能用 `lithe/host/functions/providers` 与 `lithe/host/functions/invoke`。运行时发现被调方,清单里不写被调方的插件 ID。 +- 所有检查在 Rust Core:声明、导出、双方启用、版本、调用链(拒绝 A→B→A 和自己调自己)、深度、每个调用方的并发、参数与结果大小、超时、沿链取消,远程工作区拒绝(API-40)。被调方未运行时 Core 只发 `functionProviderStartRequired`,宿主把它当作 I/O 去启动后端,超时即失败。 +- 信任不传递:被调方用自己的权限运行,Core 不把调用方的插件 ID 写进被调方的会话身份,只在转发的请求里加一个由 Core 填写的 `caller: {pluginID}` 字段;契约要求导出函数不得接受调用方传来的可执行路径或命令。没有新增权限项,`calls` 声明加 `exports` 选择加入就是双方的同意。 +- 安装、更新、卸载、启用、禁用即时更新发现结果,进行中的调用以明确的错误结束;带后端的插件在 macOS 上仍只在启动时注册,新安装或更新的后端插件要重启后才出现在发现结果里(属于 #1515 的后续工作)。 +- 旧的 `plugin.function.wrongPlugin` 与 `plugin.function.recursiveCall` 检查一个都没有删除。 + +**没有落地**:安装时解析依赖、版本范围与冲突报告、依赖闭包和事务恢复、卸载或禁用时的反向依赖提示、启动时发现缺失依赖并标记阻塞、跨包资源租约和带标签的资源引用类型、会启动程序的导出、弱依赖和多版本并存。这些仍按本提案的待办和验收标准单独实施;第一阶段也不引入任何安装期的依赖声明,被调方是否已安装完全由运行时发现。 + ### 正确做法与反例 正确做法:两个插件依赖同一个运行时,安装器先求兼容版本并展示共同资源的来源与权限,宿主只对获准导出执行调用。 @@ -73,7 +86,7 @@ - 独立任务/PR 完成安装解析、版本冲突、来源固定、哈希校验、事务恢复及并发安装规则,之后才公布新能力。 - 有共同兼容版本与不兼容菱形两组标准用例,冲突报告带确定排序的两条依赖路径;失败不修改原安装闭包。 - 禁用/卸载、启动时依赖缺失、升级失效及恢复分别验证反向依赖与资源清理;任何失败不误停不相关插件。 -- 社区依赖官方、同名包来自不同来源、签名变化和导出撤回均有拒绝输入;旧私有函数的归属和递归拒绝语义不变。 +- 社区依赖官方、同名包来自不同来源、签名变化和导出撤回均有拒绝输入;旧私有函数的归属和递归拒绝语义不变。(第一阶段已覆盖导出撤回、禁用与卸载的进行中调用,以及旧 `wrongPlugin`、`recursiveCall` 不变;来源与签名相关的输入属于安装解析,尚未覆盖。) - 如涉及函数协议,在 `lithe-plugin-docs` 验证 Node/Java SDK;正式契约与 Core 一起落地后再同步副本。 - #1210 的基础 Registry 和第三方 DAP 验收可以完全不安装依赖包而完成。 @@ -83,12 +96,13 @@ ## 验证 -本次只运行 `./scripts/agent-notes/verify-agent-notes.sh` 和文档检查,没有依赖解析器或跨包调用实现,不能声称安装或授权用例通过。实施时使用 `write-stable-tests`、`./scripts/architecture/verify-shared-contracts.sh`、`./scripts/rust-core/verify-rust-core.sh`,并分别验证两个宿主和函数 SDK;新增资源时遵守工作树复用与安装目录只读要求。 +第一阶段的跨插件调用由 Core 测试(`plugins::plugin_functions`、`lsp::interface::function_relay`、`lsp::interface::engine`)和 macOS 单测(`MacPluginBackendSessionsTests`、`PluginHostServiceDispatchTests`、`PluginPublicHostAPITests`)覆盖,细节见实现 Note 的“验证”。依赖解析器和安装期规则仍没有实现,不能声称安装、版本冲突或依赖授权用例通过。实施时使用 `write-stable-tests`、`./scripts/architecture/verify-shared-contracts.sh`、`./scripts/rust-core/verify-rust-core.sh`,并分别验证两个宿主和函数 SDK;新增资源时遵守工作树复用与安装目录只读要求。 ## 适用范围 - `rust/lithe-core/src/plugins/` - `rust/lithe-core/src/lsp/interface/plugin_function.rs` +- `rust/lithe-core/src/lsp/interface/function_relay.rs` - `shared/contracts/plugins/v1/` - `macos/Sources/Lithe/Platform/MacOS/` - `windows/tauri/src-tauri/src/plugin_host/` diff --git a/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift b/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift index 02d2e604a0..731bd7d4ae 100644 --- a/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift +++ b/macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift @@ -260,8 +260,14 @@ final class PluginHostServiceDispatcher { Array(Set(uniqueHandlers.map(\.service))).sorted() } + /// Services Core answers itself. The host has no handler for them, but + /// the plugin is still granted them: a call between two plugins runs + /// inside Core, and the host only starts the callee's backend. + static let coreServedGrants: Set = ["functions"] + func supportedGrants(_ requested: [String]) -> [String] { requested.filter { grant in + if Self.coreServedGrants.contains(grant) { return true } if handlers[grant] != nil { return true } let legacy: [String] switch grant { diff --git a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift index 9cd7e1fdfc..9ea15a6138 100644 --- a/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift +++ b/macos/Sources/Lithe/Core/Rust/RustCoreBridge.swift @@ -4289,6 +4289,37 @@ struct RustCoreBridge: Sendable, IncrementalLanguageServerRuntimeCore { ).map { (response: LspHostNotifyResponse) in response.delivered } } + private struct LspConfigureFunctionRelayRequest: Encodable { + struct Plugin: Encodable { + let pluginID: String + let exports: [ToolingJSONValue] + let calls: [ToolingJSONValue] + } + + struct Context: Encodable { + let contextID: String + let generation: Int + let authority: String + } + + let plugins: [Plugin] + let contexts: [Context] + } + + /// Replaces the enabled plugins and live workspace contexts that Core's + /// relay between plugin backends works from. + func lspConfigureFunctionRelay(_ snapshot: PluginFunctionRelaySnapshot) -> Result { + executeVoid( + command: "lsp.configureFunctionRelay", + payload: LspConfigureFunctionRelayRequest( + plugins: snapshot.plugins.map { .init(pluginID: $0.pluginID, exports: $0.exports, calls: $0.calls) }, + contexts: snapshot.contexts.map { + .init(contextID: $0.contextID, generation: $0.generation, authority: $0.isRemote ? "remote" : "local") + } + ) + ) + } + /// Cancels a pending operation. Its completion event still arrives, carrying /// a cancellation error, so callers never leak a continuation. func lspCancelOperation(sessionID: String, operationID: String) { diff --git a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift index 9f9288d14a..528279d05d 100644 --- a/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift +++ b/macos/Sources/Lithe/Core/Rust/RustLanguageServerRuntimeAdapter.swift @@ -459,6 +459,12 @@ extension RustCoreBridge: LanguageServerRuntimeCore { .mapError(Self.runtimeFailure) } + func configurePluginFunctionRelay( + _ snapshot: PluginFunctionRelaySnapshot + ) -> Result { + lspConfigureFunctionRelay(snapshot).mapError(Self.runtimeFailure) + } + func updateWorkspaceConfiguration( sessionID: String, configuration: ToolingJSONValue diff --git a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift index e16fe90007..ee4bfe2e50 100644 --- a/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift +++ b/macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift @@ -98,6 +98,10 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi private var backgroundQueue: [String] = [] private var backgroundStarts: [String: Task] = [:] private var commandStarts: [String: Task] = [:] + /// Starts a call between plugins waits for, one per plugin. + private var providerStarts: [String: Task] = [:] + /// The last snapshot Core's relay accepted; an unchanged one is not sent again. + private var publishedRelaySnapshot: PluginFunctionRelaySnapshot? private var pendingCommands: [String: [ToolingJSONValue]] = [:] private var packages: [String: Package] = [:] /// Disabled plugins start again once enabled. @@ -193,6 +197,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi ) added.insert(id) } + publishFunctionRelay() activateForOpenWorkspaces(added) } @@ -475,6 +480,7 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi /// Tells every running backend granted `workspace` that the contexts /// changed; it asks `listContexts` for them. private func contextsDidChange(revision: Int) { + publishFunctionRelay() for (pluginID, entry) in running where entry.hostServices.contains("workspace") { notify(pluginID: pluginID, method: "lithe/host/workspace/didChangeContexts", params: .object(["revision": .integer(revision)])) @@ -528,16 +534,84 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi )) } + // MARK: Calls between plugins + + /// Reports to Core's relay which plugins are enabled and which workspace + /// contexts are live. Core decides from these what a call may do; this + /// side only states the facts, and states them again whenever one of + /// them changes, so calls in flight see the change. + private func publishFunctionRelay() { + let snapshot = functionRelaySnapshot() + guard snapshot != publishedRelaySnapshot else { return } + // A snapshot Core did not accept stays unpublished, so the next + // change sends it again. + guard case .success = core.configurePluginFunctionRelay(snapshot) else { return } + publishedRelaySnapshot = snapshot + } + + private func functionRelaySnapshot() -> PluginFunctionRelaySnapshot { + let plugins = packages.compactMap { pluginID, package -> PluginFunctionRelaySnapshot.Plugin? in + guard !disabledPluginIDs.contains(pluginID), !replacedPluginIDs.contains(pluginID), canStart(pluginID), + let declaration = Self.pluginFunctionDeclaration(ofManifest: package.manifest) else { return nil } + return .init(pluginID: pluginID, exports: declaration.exports ?? [], calls: declaration.calls ?? []) + } + let contexts = hostDispatcher.contexts.contexts.map { context -> PluginFunctionRelaySnapshot.Context in + let isRemote: Bool + if case .remote = context.authority { isRemote = true } else { isRemote = false } + return .init(contextID: context.contextID, generation: context.generation, isRemote: isRemote) + } + return PluginFunctionRelaySnapshot( + plugins: plugins.sorted { $0.pluginID < $1.pluginID }, + contexts: contexts.sorted { $0.contextID < $1.contextID } + ) + } + + /// The `pluginFunctions` section of a normalized manifest, left as Core + /// wrote it: Core validated it once and reads it again in the relay. + private struct PluginFunctionDeclaration: Decodable { + let exports: [ToolingJSONValue]? + let calls: [ToolingJSONValue]? + } + + private struct PluginFunctionsManifest: Decodable { + let pluginFunctions: PluginFunctionDeclaration? + } + + private static func pluginFunctionDeclaration(ofManifest manifest: Data) -> PluginFunctionDeclaration? { + // log-exempt: Core 已校验过清单;解码失败只会让该插件不进中转快照 + try? JSONDecoder().decode(PluginFunctionsManifest.self, from: manifest).pluginFunctions + } + + /// Starts the backend a call between plugins waits for. This is the + /// host's whole part in the call: Core checks and relays it. The start + /// is bounded like every other one, by the `initialize` time limit, and + /// a failure is reported here while Core ends the waiting call with its + /// own error once its wait runs out. + private func startProviderBackend(_ pluginID: String) { + guard providerStarts[pluginID] == nil else { return } + providerStarts[pluginID] = Task { @MainActor [weak self] in + guard let self else { return } + defer { if !Task.isCancelled { self.providerStarts[pluginID] = nil } } + do { + _ = try await self.session(for: pluginID) + } catch { + if !Task.isCancelled, !(error is CancellationError) { self.onActivationFailure?(pluginID, error) } + } + } + } + /// Stops the backend until `enable` is called. func disable(_ pluginID: String) { disabledPluginIDs.insert(pluginID) stop(pluginID) + publishFunctionRelay() } /// The backend may start again; with a workspace open, one that starts /// on `onWorkspaceOpen` starts now instead of with the next workspace. func enable(_ pluginID: String) { disabledPluginIDs.remove(pluginID) + publishFunctionRelay() activateForOpenWorkspaces([pluginID]) } @@ -547,12 +621,14 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi replacedPluginIDs.insert(pluginID) packages[pluginID] = nil stop(pluginID) + publishFunctionRelay() } private func stop(_ pluginID: String) { backgroundQueue.removeAll { $0 == pluginID } backgroundStarts.removeValue(forKey: pluginID)?.cancel() commandStarts.removeValue(forKey: pluginID)?.cancel() + providerStarts.removeValue(forKey: pluginID)?.cancel() pendingCommands[pluginID] = nil hostDispatcher.endSession(pluginID: pluginID) guard let entry = running.removeValue(forKey: pluginID) else { return } @@ -685,6 +761,9 @@ final class MacPluginBackendSessions: PluginBackendRequesting, PluginBackendActi session.onHostRequestCancelled = { hostRequestID in hostDispatcher.cancel(hostRequestID: hostRequestID, pluginID: pluginID, sessionID: sessionToken) } + session.onFunctionProviderStartRequired = { [weak self] providerID in + self?.startProviderBackend(providerID) + } entry.session = session try await waitUntilReady(session, rootURL: backend.stateDirectory) try Task.checkCancellation() diff --git a/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift b/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift index ea487b223b..6ebecd959f 100644 --- a/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift +++ b/macos/Sources/LitheCoreContracts/Language/LanguageServerRuntimeContracts.swift @@ -615,6 +615,12 @@ package protocol LanguageServerRuntimeCore: Sendable { method: String, params: ToolingJSONValue ) -> Result + /// Replaces what Core's relay between plugin backends knows about the + /// enabled plugins and the live workspace contexts. Calls in flight that + /// the new snapshot no longer allows end with an explicit error. + func configurePluginFunctionRelay( + _ snapshot: PluginFunctionRelaySnapshot + ) -> Result /// Replaces the configuration a running plugin server reads and tells it /// through `workspace/didChangeConfiguration`. func updateWorkspaceConfiguration( @@ -962,6 +968,13 @@ package extension LanguageServerRuntimeCore { )) } + /// A runtime without the relay has no calls between plugins to configure. + func configurePluginFunctionRelay( + _: PluginFunctionRelaySnapshot + ) -> Result { + .success(()) + } + func updateWorkspaceConfiguration( sessionID _: String, configuration _: ToolingJSONValue @@ -1048,6 +1061,47 @@ package struct PluginWorkspaceContextReference: Hashable, Sendable { } } +/// What Core's relay between plugin backends needs from the host: which +/// plugins are enabled, and which workspace contexts are live. The host +/// reports facts only; Core decides what each call may do with them. +package struct PluginFunctionRelaySnapshot: Equatable, Sendable { + package struct Plugin: Equatable, Sendable { + package let pluginID: String + /// The manifest's `pluginFunctions.exports`, as Core normalized them. + package let exports: [ToolingJSONValue] + /// The manifest's `pluginFunctions.calls`, as Core normalized them. + package let calls: [ToolingJSONValue] + + package init(pluginID: String, exports: [ToolingJSONValue], calls: [ToolingJSONValue]) { + self.pluginID = pluginID + self.exports = exports + self.calls = calls + } + } + + package struct Context: Equatable, Sendable { + package let contextID: String + package let generation: Int + /// Whether the workspace is on an SSH host; Core refuses relayed + /// calls in it. + package let isRemote: Bool + + package init(contextID: String, generation: Int, isRemote: Bool) { + self.contextID = contextID + self.generation = generation + self.isRemote = isRemote + } + } + + package let plugins: [Plugin] + package let contexts: [Context] + + package init(plugins: [Plugin], contexts: [Context]) { + self.plugins = plugins + self.contexts = contexts + } +} + /// One progress report of a running plugin function, as Core normalized it. package struct PluginFunctionProgress: Equatable, Sendable { package let message: String? diff --git a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift index 8b1840d8f8..3a1badf21e 100644 --- a/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift +++ b/macos/Sources/LitheLanguageIntelligenceModule/Runtime/LanguageServerSession.swift @@ -149,6 +149,11 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { /// `$/cancelRequest` (function protocol 3). Core has already answered /// the backend; the owner stops the work and sends no answer. package var onHostRequestCancelled: ((String) -> Void)? + /// Receives the ID of a plugin whose backend a call from this plugin + /// waits for (function protocol 4). The owner starts that backend if it + /// can; Core ends the call with an error when the backend does not + /// register the function in time. + package var onFunctionProviderStartRequired: ((String) -> Void)? /// The VCS provider the process negotiated in `initialize`, as Core's /// `vcsProvider` event reported it; nil for every other session. package private(set) var vcsNegotiation: VcsProviderNegotiation? @@ -1651,6 +1656,11 @@ package final class LanguageServerRuntimeSession: LanguageServerSession { respond(to: id, with: .failure(PluginHostRequestFailure(message: "The host serves no requests of this process."))) } return false + case "functionProviderStartRequired": + if case .object(let object)? = event.result, case .string(let pluginID)? = object["pluginID"] { + onFunctionProviderStartRequired?(pluginID) + } + return false case "hostRequestCancelled": if case .object(let object)? = event.result, case .string(let id)? = object["hostRequestID"] { onHostRequestCancelled?(id) diff --git a/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift b/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift index 9c873e18b1..661b721e05 100644 --- a/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift +++ b/macos/Sources/LitheModuleAPI/Plugins/PluginTypes.swift @@ -521,6 +521,7 @@ public struct PluginManifest: Equatable, Codable, Sendable { public static let hostCapabilities: [String: [Int]] = [ "keymapImportProviders": [1], "packageTrust": [1], + "pluginFunctions": [1], "backend": [1, 2], "buildProviders": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "buildModelInputs": [1], "buildSystems": [1, 2, 3, 4], "debugAdapters": [1, 2], "executableResolution": [1, 2], diff --git a/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift b/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift index 465c8d6388..2956bd245a 100644 --- a/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift +++ b/macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift @@ -237,6 +237,99 @@ struct MacPluginBackendSessionsTests { #expect(stopped.core.notifications.isEmpty) } + /// The relay between plugins works from the host's facts: which plugins + /// are enabled, with the functions they export and call as Core + /// normalized them, and which workspace contexts are live. Every change + /// of those facts reaches Core again; a repeat of the same facts does not. + @Test + func theRelayIsToldWhichPluginsAreEnabledAndWhichContextsAreLive() throws { + let contexts = PluginWorkspaceContexts() + let fixture = try BackendFixture(hostDispatcher: PluginHostServiceDispatcher(contexts: contexts)) + defer { fixture.remove() } + try fixture.installFunctionPlugin("plugin-functions-exporter") + try fixture.installFunctionPlugin("plugin-functions-caller") + + // The fixture's own backend declares no plugin functions, so it is not listed. + let plugins = try #require(fixture.core.relaySnapshots.last).plugins + #expect(plugins.map(\.pluginID) == [FunctionPlugins.caller, FunctionPlugins.exporter]) + #expect(plugins[0].exports.isEmpty) + #expect(plugins[0].calls == [FunctionPlugins.declaration("document.format", version: 1)]) + #expect(Set(plugins[1].exports) == [ + FunctionPlugins.declaration("document.format", version: 1, context: "workspace"), + FunctionPlugins.declaration("symbols.list", version: 2, context: "workspace"), + ]) + #expect(plugins[1].calls.isEmpty) + + fixture.sessions.disable(FunctionPlugins.exporter) + #expect(fixture.core.relaySnapshots.last?.plugins.map(\.pluginID) == [FunctionPlugins.caller]) + fixture.sessions.enable(FunctionPlugins.exporter) + #expect(fixture.core.relaySnapshots.last?.plugins.map(\.pluginID) == [FunctionPlugins.caller, FunctionPlugins.exporter]) + let published = fixture.core.relaySnapshots.count + fixture.sessions.enable(FunctionPlugins.exporter) + #expect(fixture.core.relaySnapshots.count == published) + fixture.sessions.packageWillChange(FunctionPlugins.exporter) + #expect(fixture.core.relaySnapshots.last?.plugins.map(\.pluginID) == [FunctionPlugins.caller]) + + let localWindow = NSObject() + let local = contexts.open(owner: localWindow, rootURL: URL(fileURLWithPath: "/fixture/project"), remote: nil) + defer { contexts.close(owner: localWindow) } + let remoteWindow = NSObject() + let remote = contexts.open( + owner: remoteWindow, rootURL: URL(fileURLWithPath: "/fixture/remote"), + remote: (connectionID: "ssh-fixture", remoteRoot: "/srv/app") + ) + defer { contexts.close(owner: remoteWindow) } + let liveContexts = try #require(fixture.core.relaySnapshots.last).contexts + #expect(liveContexts.first { $0.contextID == local.contextID }?.isRemote == false) + #expect(liveContexts.first { $0.contextID == local.contextID }?.generation == local.generation) + #expect(liveContexts.first { $0.contextID == remote.contextID }?.isRemote == true) + + contexts.close(owner: localWindow) + #expect(fixture.core.relaySnapshots.last?.contexts.map(\.contextID) == [remote.contextID]) + } + + /// A plugin whose call waits for another plugin's backend gets that + /// backend started. The caller is granted the `functions` service Core + /// answers itself, and the callee, which declares no calls, is not. + @Test + func aCallWaitingForABackendStartsIt() async throws { + let fixture = try BackendFixture(hostDispatcher: PluginHostServiceDispatcher(contexts: PluginWorkspaceContexts())) + defer { fixture.remove() } + try fixture.installFunctionPlugin("plugin-functions-exporter") + try fixture.installFunctionPlugin("plugin-functions-caller") + _ = try await fixture.sessions.pluginFunctions(ofPlugin: FunctionPlugins.caller) + #expect(fixture.core.starts.map(\.pluginID) == [FunctionPlugins.caller]) + #expect(fixture.core.starts.first?.hostServices == ["functions"]) + + fixture.core.sendProviderStartRequired(pluginID: FunctionPlugins.exporter) + try #require(await fixture.core.startGate(for: FunctionPlugins.exporter).waitUntilOpen(timeout: .seconds(5))) + #expect(fixture.core.starts.map(\.pluginID) == [FunctionPlugins.caller, FunctionPlugins.exporter]) + #expect(fixture.core.starts.last?.hostServices == []) + } + + /// The host starts only a backend that may run: a disabled plugin stays + /// stopped, and the failure is reported while Core ends the call. + @Test + func aCallCannotStartABackendThatIsDisabled() async throws { + let fixture = try BackendFixture(hostDispatcher: PluginHostServiceDispatcher(contexts: PluginWorkspaceContexts())) + defer { fixture.remove() } + try fixture.installFunctionPlugin("plugin-functions-exporter") + try fixture.installFunctionPlugin("plugin-functions-caller") + _ = try await fixture.sessions.pluginFunctions(ofPlugin: FunctionPlugins.caller) + fixture.sessions.disable(FunctionPlugins.exporter) + let reported = TestGate() + var failedPlugins: [String] = [] + fixture.sessions.onActivationFailure = { pluginID, _ in + failedPlugins.append(pluginID) + reported.open() + } + + fixture.core.sendProviderStartRequired(pluginID: FunctionPlugins.exporter) + try #require(await reported.waitUntilOpen(timeout: .seconds(5))) + #expect(failedPlugins == [FunctionPlugins.exporter]) + #expect(fixture.core.starts.map(\.pluginID) == [FunctionPlugins.caller]) + } + /// The answer never echoes a secret, and a request outside the /// credentials service is refused even if Core forwarded it. @Test @@ -299,10 +392,12 @@ private struct BackendFixture { let credentials = MemoryPluginCredentialStore() let core = ScriptedBackendCore() let sessions: MacPluginBackendSessions + private let installedFunctionPlugins = InstalledFunctionPlugins() init( backendVersion: Int = 1, commandActivation: Bool = false, + hostDispatcher: PluginHostServiceDispatcher? = nil, prepareState: @escaping @Sendable (_ installation: PluginInstallationRecord, _ stateDirectory: URL) -> Void = { _, _ in } ) throws { root = FileManager.default.temporaryDirectory @@ -349,6 +444,7 @@ private struct BackendFixture { credentials: credentials, prepareState: prepareState, stuckSendGrace: .milliseconds(20), + hostDispatcher: hostDispatcher, endBackendProcesses: { [core] _, immediately in if immediately { core.forcedStop.open(); core.releaseWrite.open() } } @@ -362,12 +458,61 @@ private struct BackendFixture { )]) } + /// Installs a plugin of the shared `pluginFunctions` fixtures beside the + /// fixture's own, with a placeholder backend executable. + func installFunctionPlugin(_ fixtureName: String) throws { + let fixtureURL = DeclarativePluginTestSupport.repositoryRoot + .appendingPathComponent("shared/contracts/plugins/v1/fixtures/backend/\(fixtureName).plugin.json") + let manifest = try #require( + try JSONSerialization.jsonObject(with: Data(contentsOf: fixtureURL)) as? [String: Any] + ) + let pluginID = try #require(manifest["id"] as? String) + let directory = root.appendingPathComponent(pluginID, isDirectory: true) + _ = try DeclarativePluginTestSupport.writePackage(at: directory, manifest: manifest) + let executable = directory.appendingPathComponent("bin/backend") + try FileManager.default.createDirectory(at: executable.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("#!/bin/sh\n".utf8).write(to: executable) + try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: executable.path) + let descriptor = try DeclarativePluginTestSupport.operations.validate( + manifest: Data(contentsOf: directory.appendingPathComponent("plugin.json")) + ) + sessions.register([InstalledPluginPackage( + descriptor: descriptor, + installation: PluginInstallationRecord( + pluginID: descriptor.id, activeVersion: descriptor.pluginManifest.version, origin: .localDevelopment + ), + packageURL: directory + )]) + installedFunctionPlugins.ids.append(pluginID) + } + func remove() { sessions.packageWillChange(Self.pluginID) + installedFunctionPlugins.ids.forEach { sessions.packageWillChange($0) } try? FileManager.default.removeItem(at: root) } } +/// The plugins of the shared `pluginFunctions` fixtures, and how their +/// declarations look in the relay snapshot. +private enum FunctionPlugins { + static let exporter = "dev.lithe.fixture.functionexporter" + static let caller = "dev.lithe.fixture.functioncaller" + + /// An export (with `context`) or a call (without) as Core normalizes it. + static func declaration(_ id: String, version: Int, context: String? = nil) -> ToolingJSONValue { + var fields: [String: ToolingJSONValue] = ["id": .string(id), "version": .integer(version)] + if let context { fields["context"] = .string(context) } + return .object(fields) + } +} + +/// The IDs of the function plugins a fixture installed, so `remove` can +/// stop them; a class because the fixture is a value. +private final class InstalledFunctionPlugins { + var ids: [String] = [] +} + /// Starts ready plugin backends, queues host requests on demand, and /// records how the host answered them. private final class ScriptedBackendCore: LanguageServerRuntimeCore, @unchecked Sendable { @@ -405,6 +550,8 @@ private final class ScriptedBackendCore: LanguageServerRuntimeCore, @unchecked S private var _notifications: [Notification] = [] private var waiters: [UUID: (count: Int, continuation: CheckedContinuation)] = [:] private var notificationWaiters: [UUID: (count: Int, continuation: CheckedContinuation)] = [:] + private var _relaySnapshots: [PluginFunctionRelaySnapshot] = [] + private var startGates: [String: TestGate] = [:] private var _delayReady = false private var _blockNotification = false private var _notificationSupported = true @@ -426,6 +573,34 @@ private final class ScriptedBackendCore: LanguageServerRuntimeCore, @unchecked S } var starts: [Start] { lock.withLock { _starts } } + var relaySnapshots: [PluginFunctionRelaySnapshot] { lock.withLock { _relaySnapshots } } + + /// Opens once a backend of `pluginID` has started. + func startGate(for pluginID: String) -> TestGate { + lock.withLock { startGateLocked(for: pluginID) } + } + + private func startGateLocked(for pluginID: String) -> TestGate { + if let gate = startGates[pluginID] { return gate } + let gate = TestGate() + startGates[pluginID] = gate + return gate + } + + func configurePluginFunctionRelay(_ snapshot: PluginFunctionRelaySnapshot) -> Result { + lock.withLock { _relaySnapshots.append(snapshot) } + return .success(()) + } + + /// Queues Core's request to start `pluginID`'s backend on the newest session. + func sendProviderStartRequired(pluginID: String) { + lock.withLock { + events["backend-\(nextSession)", default: []].append(LanguageServerRuntimeEvent( + type: "functionProviderStartRequired", + result: .object(["pluginID": .string(pluginID)]) + )) + } + } var stops: [String] { lock.withLock { _stops } } var responses: [Response] { lock.withLock { _responses } } var notifications: [Notification] { lock.withLock { _notifications } } @@ -448,6 +623,7 @@ private final class ScriptedBackendCore: LanguageServerRuntimeCore, @unchecked S ] if !_delayReady { events[sessionID, default: []].append(LanguageServerRuntimeEvent(type: "stateChanged", state: "ready")) } started.open() + startGateLocked(for: pluginID).open() return .success(LanguageServerRuntimeStart(sessionID: sessionID, state: "initializing", processID: nil)) } } diff --git a/macos/Tests/LitheTests/PluginPublicHostAPITests.swift b/macos/Tests/LitheTests/PluginPublicHostAPITests.swift index 242bc9e939..cdffb3c31e 100644 --- a/macos/Tests/LitheTests/PluginPublicHostAPITests.swift +++ b/macos/Tests/LitheTests/PluginPublicHostAPITests.swift @@ -57,6 +57,14 @@ struct PluginPublicHostAPITests { #expect(dispatcher.supportedGrants(["lithe/host/editor/applyEdits", "lithe/host/editor/missing"]) == ["lithe/host/editor/applyEdits"]) } + /// Core answers `functions` (calls between plugins) itself, so the host + /// has no handler for it; a plugin that declares calls is still granted it. + @Test + func theFunctionsServiceIsGrantedThoughCoreAnswersIt() { + let dispatcher = PluginHostServiceDispatcher(contexts: PluginWorkspaceContexts()) + #expect(dispatcher.supportedGrants(["functions", "lithe/host/functions/missing"]) == ["functions"]) + } + @Test func closingContextCancelsAnInflightRequestExactlyOnce() async throws { let contexts = PluginWorkspaceContexts() diff --git a/rust/lithe-core/src/lsp/interface/client.rs b/rust/lithe-core/src/lsp/interface/client.rs index 3f1bd61ce3..77f7199f3d 100644 --- a/rust/lithe-core/src/lsp/interface/client.rs +++ b/rust/lithe-core/src/lsp/interface/client.rs @@ -569,6 +569,22 @@ pub(super) fn client_apply_server_message_for_plugin( error: None, }) } + // Another plugin's function: the engine's relay checks the + // call against the plugins' manifests and answers the + // backend itself, so the reducer only names the request. + Ok(plugin_function::HostRoute::Relay) => events.push(LspClientEvent { + kind: "functionRelayRequest".to_string(), + request_id: None, + method: Some(method.to_string()), + uri: None, + version: None, + diagnostics: None, + result: Some(json!({ + "id": id, + "params": message.get("params").cloned().unwrap_or(Value::Null), + })), + error: None, + }), Err(refusal) => { let mut data = json!({ "code": refusal.code }); if let Some(details) = refusal.details { diff --git a/rust/lithe-core/src/lsp/interface/engine.rs b/rust/lithe-core/src/lsp/interface/engine.rs index b539c7b752..991350a99b 100644 --- a/rust/lithe-core/src/lsp/interface/engine.rs +++ b/rust/lithe-core/src/lsp/interface/engine.rs @@ -87,6 +87,10 @@ const JAVA_BUILD_METHOD: &str = "workspace/executeCommand"; static ENGINE: OnceLock = OnceLock::new(); +#[path = "engine_function_relay.rs"] +mod relay_hub; +use relay_hub::RelayHub; + #[derive(Debug, Clone, Copy, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] /// Observable lifecycle of one managed language-server session. @@ -899,6 +903,9 @@ struct SessionState { deadline_cancellations: Vec, /// Bounds an outbound maintenance write independently of caller deadlines. maintenance_write_deadline: Option, + /// Bounds one write the function relay's lane makes to this session, so a + /// backend that stops reading its stdin cannot hold the lane forever. + relay_write_deadline: Option, /// Backend requests for a host service awaiting `lsp.hostResponse`, by /// the opaque ID the host sees, with the backend's own JSON-RPC ID. host_requests: BTreeMap, @@ -964,6 +971,8 @@ struct RuntimeSession { event_signal: Condvar, process: Arc, active: AtomicBool, + /// The engine's cross-plugin function relay; see `engine_function_relay`. + relay: Arc, } /// The engine is a process-owning singleton in production, but it holds no @@ -972,7 +981,10 @@ struct RuntimeSession { pub(super) struct LspEngine { next_session_id: AtomicU64, next_operation_id: AtomicU64, - sessions: Mutex>>, + /// Shared with the relay's worker, which reaches sessions by ID. + sessions: Arc>>>, + /// Cross-plugin function calls; every session of this engine uses it. + relay: Arc, /// Failed wire starts have no returned identity. Retain their cleanup /// responsibility here and retry disposal before another process starts. failed_starts: Mutex>, @@ -1731,10 +1743,19 @@ pub fn plugin_function_request( .unwrap_or_else(|| engine().next_operation_id()); engine() .session(&request.session_id)? - .function_request(request, operation_id.clone())?; + .function_request(request, operation_id.clone(), None)?; Ok(OperationResponse { operation_id }) } +/// Replaces the host's view of the enabled plugins and live workspace +/// contexts that the cross-plugin function relay checks calls against. Calls +/// in flight that the new view forbids end with an error. +pub fn configure_function_relay( + snapshot: super::function_relay::RelaySnapshot, +) -> Result<(), CoreError> { + engine().relay.configure(snapshot) +} + /// Cancels a pending semantic request in both client state and the server. pub fn cancel_operation(request: CancelOperationRequest) -> Result<(), CoreError> { engine() @@ -1868,10 +1889,12 @@ impl LspEngine { } fn with_launcher(launcher: Arc) -> Self { + let sessions = Arc::new(Mutex::new(BTreeMap::new())); Self { next_session_id: AtomicU64::new(1), next_operation_id: AtomicU64::new(1), - sessions: Mutex::new(BTreeMap::new()), + relay: RelayHub::start(&sessions), + sessions, failed_starts: Mutex::new(BTreeSet::new()), launcher, } @@ -2262,6 +2285,7 @@ impl LspEngine { java_build_timeout, deadline_cancellations: Vec::new(), maintenance_write_deadline: None, + relay_write_deadline: None, host_requests: BTreeMap::new(), next_host_request_id: 1, detailed_diagnostics: false, @@ -2273,6 +2297,7 @@ impl LspEngine { event_signal: Condvar::new(), process: process.handle, active: AtomicBool::new(true), + relay: Arc::clone(&self.relay), }); session.transition(LspLifecycleState::Created, None)?; session.transition(LspLifecycleState::ProcessStarting, None)?; @@ -3323,11 +3348,22 @@ impl RuntimeSession { /// Writes a `lithe/function/invoke` request. The plan comes from /// `plugin_function::plan_invocation`, so plugin identity, negotiation, /// and registration are checked before anything reaches the process. + /// + /// `caller` is the plugin whose call the relay forwards, and `None` for a + /// call the host starts. Only the relay passes `Some`, so a host cannot + /// name a plugin as the caller and a plugin cannot choose its own name. fn function_request( &self, request: PluginFunctionRequest, operation_id: String, + caller: Option<&str>, ) -> Result<(), CoreError> { + if caller.is_none() && relay_hub::is_relay_operation_id(&operation_id) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "This language-server operation ID is reserved for relayed plugin calls.", + )); + } let outbound_order = self.lock_outbound_order()?; let (messages, request_id) = { let mut state = self.lock_state()?; @@ -3367,11 +3403,9 @@ impl RuntimeSession { &request.params, )?; let mut params = params; - super::plugin_function::attach_context( - &mut params, - state.client.plugin_function_version.unwrap_or(0), - request.context.as_ref(), - )?; + let version = state.client.plugin_function_version.unwrap_or(0); + super::plugin_function::attach_context(&mut params, version, request.context.as_ref())?; + super::plugin_function::attach_caller(&mut params, version, caller); let timeout = request .timeout_milliseconds .map(|milliseconds| { @@ -5211,6 +5245,14 @@ impl RuntimeSession { .collect(); outbound.extend(revoke_function_calls_locked(self, &mut state, &removed)); push_functions_event(self, &mut state, result); + relay_hub::observe_functions_changed(self); + } else if event.kind == "functionRelayRequest" { + outbound.extend(self.relay.answer_request( + self, + &state, + event.method.as_deref().unwrap_or_default(), + &event.result.unwrap_or_default(), + )?); } else if event.kind == "functionProgress" { push_function_progress_locked(self, &mut state, event.result); } else if event.kind == "buildProgress" { @@ -6021,12 +6063,15 @@ impl RuntimeSession { } fn expire_deadlines_at(&self, now: Instant) { + // Relayed calls that no callee runs yet have no session deadline. + self.relay.expire(now); let mut cancellations = Vec::new(); let mut initialize_timeout = false; let mut service_ready_timeout = None; let mut maven_context_timeout = false; let mut shutdown_timeout = false; let mut maintenance_write_timeout = false; + let mut relay_write_timeout = false; if let Ok(mut state) = self.lock_state() { maintenance_write_timeout = state .maintenance_write_deadline @@ -6034,6 +6079,12 @@ impl RuntimeSession { if maintenance_write_timeout { state.maintenance_write_deadline = None; } + relay_write_timeout = state + .relay_write_deadline + .is_some_and(|deadline| now >= deadline); + if relay_write_timeout { + state.relay_write_deadline = None; + } if state.lifecycle == LspLifecycleState::Initializing && state .initialize_deadline @@ -6298,6 +6349,16 @@ impl RuntimeSession { None, ); self.kill_process(); + } else if relay_write_timeout { + // Killing the process releases the relay lane's blocked stdin write. + self.fail( + "transportFailed", + "relayWrite", + "Language-server stdin write timed out.", + None, + None, + ); + self.kill_process(); } else if initialize_timeout { // Timeout termination must not wait behind a blocked stdin write; // killing the process is what releases that write. @@ -7243,6 +7304,7 @@ fn transition_locked( error: Option, ) { state.lifecycle = lifecycle; + relay_hub::observe_lifecycle(session, lifecycle); let (id, fields) = EngineLog::SessionUpdated.fact( &session.log_identity, &json!({"state": lifecycle}), @@ -7290,6 +7352,16 @@ fn push_request_event( result: Option, error: Option, ) { + // No host operation waits for a relayed call: the relay answers the + // calling plugin, so the event never reaches the host. + if relay_hub::is_relayed_operation(operation_id, method) { + session.relay.callee_finished( + &session.id, + operation_id, + relay_hub::callee_outcome(result, error), + ); + return; + } let (result, error) = if let Some(mut preparation) = state.java_launches.remove(operation_id) { match preparation.advance(result, error) { Ok(JavaLaunchAction::Build(command)) => { @@ -7701,7 +7773,9 @@ fn cancel_host_request_locked( .find(|(_, pending)| *pending == backend_id) .map(|(host_request_id, _)| host_request_id.clone()) else { - return Ok(false); + // Not a host request: it may name a call the backend relayed to + // another plugin. + return Ok(session.relay.cancel_from_caller(&session.id, backend_id)); }; let backend_id = state .host_requests @@ -8591,6 +8665,7 @@ fn clear_runtime_state(session: &RuntimeSession, state: &mut SessionState) { state.java_launch_messages.clear(); state.deadline_cancellations.clear(); state.maintenance_write_deadline = None; + state.relay_write_deadline = None; state.pending_workspace_file_changes.clear(); state.maven_profile_update_pending = false; state.maven_project_reload_pending = false; @@ -8670,6 +8745,10 @@ fn workspace_file_changes_notification( .to_string() } +#[cfg(test)] +#[path = "engine_function_relay_tests.rs"] +mod function_relay_tests; + #[cfg(test)] #[path = "engine_real_jdt_tests.rs"] mod real_jdt_tests; @@ -8702,7 +8781,7 @@ mod tests { configuration } - fn start_request(server: &ScriptedServer) -> StartServerRequest { + pub(super) fn start_request(server: &ScriptedServer) -> StartServerRequest { let _ = server; StartServerRequest { // A non-Java provider keeps JDT argument adaptation out of the way; @@ -16694,6 +16773,7 @@ public class Main { context: None, }, operation_id.clone(), + None, ) .map(|()| operation_id) } @@ -16797,7 +16877,7 @@ public class Main { initialize["params"]["capabilities"]["experimental"], json!({ "litheBuild": { "versions": [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] }, - "litheFunctions": { "versions": [1, 2, 3] }, + "litheFunctions": { "versions": [1, 2, 3, 4] }, "litheLogging": { "versions": [1] }, "litheVcs": { "versions": [1] } }) @@ -17991,6 +18071,7 @@ public class Main { context: Some(context), }, operation_id, + None, ) }; let error = call(json!({ "contextID": "w/1", "generation": 1 })) diff --git a/rust/lithe-core/src/lsp/interface/engine_function_relay.rs b/rust/lithe-core/src/lsp/interface/engine_function_relay.rs new file mode 100644 index 0000000000..95d242ce0d --- /dev/null +++ b/rust/lithe-core/src/lsp/interface/engine_function_relay.rs @@ -0,0 +1,697 @@ +//! Engine side of the cross-plugin function relay: it owns the relay's +//! state, carries out the actions `function_relay` returns, and connects the +//! relay to live sessions. +//! +//! Two sessions are involved in every call (the caller's and the callee's), +//! and a callee may call back into another plugin while serving, so a session +//! thread must never write to a second session itself: two sessions doing that +//! to each other would each wait for the other's write lock. Every effect on +//! a session therefore goes through the relay's threads, which hold no session +//! lock while they wait. The relay's own lock is a leaf: sessions may take it +//! while holding their locks, and it never takes a session lock while held. +//! +//! The main worker only plans: it decides which action comes next and which +//! session it concerns, but it never writes. Each session has its own lane, a +//! thread that performs the writes to that session in order. A backend that +//! stops reading its stdin therefore stalls only its own lane, and the write +//! is bounded by the session's request timeout (`bounded_relay_write`), after +//! which the session fails and its process is killed. One such backend cannot +//! hold up the calls of other plugins. + +use super::super::function_relay::{ + CallParent, CalleeOutcome, DispatchPlan, FunctionRelay, RelayAction, RelayFailure, + RelayRequest, RelaySnapshot, OPERATION_PREFIX, +}; +use super::super::plugin_function::{ + bounded_host_message, codes, host_rpc_code, FunctionReference, FUNCTIONS_INVOKE, + FUNCTIONS_PROVIDERS, INVOKE_METHOD, +}; +use super::{ + json_rpc_error_with_data, json_rpc_result, push_negotiated_provider_event, LspLifecycleState, + LspRuntimeError, PluginFunctionRequest, RuntimeSession, SessionState, +}; +use crate::protocol::{CoreError, ErrorCode}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::sync::{mpsc, Arc, Mutex, MutexGuard, PoisonError, Weak}; +use std::thread; +use std::time::{Duration, Instant}; + +type SessionMap = Mutex>>; + +/// The relay's state plus the queue of work for its worker thread. +pub(super) struct RelayHub { + relay: Mutex, + actions: Mutex>, +} + +impl RelayHub { + /// Creates the hub and its worker. The worker holds only weak references, + /// so it ends once the engine and its sessions are gone. + pub(super) fn start(sessions: &Arc) -> Arc { + let (sender, receiver) = mpsc::channel(); + let hub = Arc::new(Self { + relay: Mutex::new(FunctionRelay::default()), + actions: Mutex::new(sender), + }); + let worker_hub = Arc::downgrade(&hub); + let worker_sessions = Arc::downgrade(sessions); + thread::spawn(move || run_worker(worker_hub, worker_sessions, receiver)); + hub + } + + /// Replaces the plugin and workspace-context snapshot. Calls the new + /// snapshot no longer allows end at once. + pub(super) fn configure(&self, snapshot: RelaySnapshot) -> Result<(), CoreError> { + let actions = self + .lock() + .configure(snapshot) + .map_err(|message| CoreError::new(ErrorCode::InvalidRequest, message))?; + self.send(actions); + Ok(()) + } + + /// Answers one request a plugin backend made with `lithe/host/functions/*`. + /// Returns the messages to write to that backend now; an admitted call + /// has none, because its answer comes when the callee finishes. + /// + /// `state` is that backend's session state, which the caller already holds + /// locked: it is how a call that names its parent is checked against the + /// calls this backend is serving, without locking the session again. + pub(super) fn answer_request( + &self, + session: &RuntimeSession, + state: &SessionState, + method: &str, + request: &Value, + ) -> Result, CoreError> { + let rpc_id = request.get("id").cloned().unwrap_or(Value::Null); + let params = request.get("params").unwrap_or(&Value::Null); + // Only a plugin's own session can negotiate the protocol, so a + // session without a plugin should never get here. + let Some(caller_plugin) = session.plugin_id.as_deref() else { + let failure = RelayFailure::new( + codes::HOST_UNAVAILABLE, + "The host does not offer this method.", + ); + return Ok(vec![reply_message(&rpc_id, &Err(failure))?]); + }; + let outcome = match method { + FUNCTIONS_PROVIDERS => self.providers(caller_plugin, params), + FUNCTIONS_INVOKE => match self.admit(session, state, caller_plugin, &rpc_id, params) { + Ok(()) => return Ok(Vec::new()), + Err(failure) => Err(failure), + }, + _ => Err(RelayFailure::new( + codes::HOST_UNAVAILABLE, + "The host does not offer this method.", + )), + }; + Ok(vec![reply_message(&rpc_id, &outcome)?]) + } + + fn providers(&self, caller_plugin: &str, params: &Value) -> Result { + let function_id = string_param(params, "functionID")?; + self.lock().providers(caller_plugin, function_id) + } + + fn admit( + &self, + session: &RuntimeSession, + state: &SessionState, + caller_plugin: &str, + rpc_id: &Value, + params: &Value, + ) -> Result<(), RelayFailure> { + let request = RelayRequest { + caller_session: session.id.clone(), + caller_plugin: caller_plugin.to_string(), + rpc_id: rpc_id.clone(), + callee_plugin: string_param(params, "pluginID")?.to_string(), + function_id: string_param(params, "functionID")?.to_string(), + params: params.get("params").cloned().unwrap_or_else(|| json!({})), + context: params.get("context").cloned().unwrap_or(Value::Null), + timeout: params + .get("timeoutMilliseconds") + .and_then(Value::as_u64) + .map(Duration::from_millis), + parent: call_parent(state, params), + }; + let actions = self.lock().admit(request, Instant::now())?; + self.send(actions); + Ok(()) + } + + /// A callee session finished an operation. Calls that are not relayed + /// are ignored. + pub(super) fn callee_finished( + &self, + session_id: &str, + operation_id: &str, + outcome: CalleeOutcome, + ) { + let actions = self + .lock() + .callee_finished(session_id, operation_id, outcome); + self.send(actions); + } + + /// The calling plugin sent `$/cancelRequest`. Returns whether the request + /// named a relayed call. + pub(super) fn cancel_from_caller(&self, session_id: &str, rpc_id: &Value) -> bool { + let Some(actions) = self.lock().cancel_from_caller(session_id, rpc_id) else { + return false; + }; + self.send(actions); + true + } + + /// A session stopped or failed. + pub(super) fn session_ended(&self, session_id: &str) { + let actions = self.lock().session_ended(session_id); + self.send(actions); + } + + /// A backend of the plugin became ready or registered functions. + pub(super) fn provider_changed(&self, plugin_id: &str) { + let actions = self.lock().provider_changed(plugin_id); + self.send(actions); + } + + /// Ends the calls that ran out of time without a running callee. + pub(super) fn expire(&self, now: Instant) { + let actions = self.lock().expire(now); + self.send(actions); + } + + fn lock(&self) -> MutexGuard<'_, FunctionRelay> { + // The tables are plain data that every method leaves consistent + // before it returns, so a panic elsewhere does not invalidate them. + self.relay.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn send(&self, actions: Vec) { + if actions.is_empty() { + return; + } + let sender = self.actions.lock().unwrap_or_else(PoisonError::into_inner); + for action in actions { + // log-exempt: A closed queue means the worker ended with the engine, so nothing is left to carry out the action. + let _ = sender.send(action); + } + } + + /// Ends a call the relay admitted but could not write to its provider. + fn dispatch_failed(&self, call_id: u64, failure: RelayFailure) { + let actions = self.lock().dispatch_failed(call_id, failure); + self.send(actions); + } + + /// Carries out one action on the main worker. It plans only: every write + /// to a session is handed to that session's lane, so this thread never + /// waits on a backend's stdin. + fn perform(&self, sessions: &SessionMap, lanes: &mut Lanes, action: RelayAction) { + match action { + RelayAction::Reply { + session_id, + rpc_id, + outcome, + } => { + // The caller may have stopped meanwhile; the lane drops the + // answer when nobody is left to receive it. + lanes.post(sessions, &session_id, LaneWork::Reply { rpc_id, outcome }); + } + RelayAction::CancelCallee { + session_id, + operation_id, + } => { + // The callee may already have finished the operation; the lane + // ignores a cancel that finds nothing to cancel. + lanes.post(sessions, &session_id, LaneWork::Cancel { operation_id }); + } + RelayAction::Dispatch { call_id } => self.dispatch(sessions, lanes, call_id), + } + } + + /// Picks a ready backend of the callee plugin for one admitted call and + /// hands the invoke to that backend's lane, or records that no backend + /// exists yet. + fn dispatch(&self, sessions: &SessionMap, lanes: &mut Lanes, call_id: u64) { + let Some(plan) = self.lock().dispatch_plan(call_id, Instant::now()) else { + return; + }; + let Some(provider) = find_provider( + sessions, + &plan.caller_session, + &plan.callee_plugin, + &plan.function_id, + ) else { + self.wait_for_provider(sessions, call_id, &plan); + return; + }; + let operation_id = format!("{OPERATION_PREFIX}{call_id}"); + // Recorded before the request is posted, so an answer that arrives + // at once still finds its call. + if !self.lock().started(call_id, &provider.id, &operation_id) { + return; + } + let milliseconds = u64::try_from(plan.remaining.as_millis()).unwrap_or(u64::MAX); + let request = PluginFunctionRequest { + session_id: provider.id.clone(), + operation_id: Some(operation_id.clone()), + function: FunctionReference { + plugin_id: plan.callee_plugin, + function_id: plan.function_id, + }, + params: plan.params, + timeout_milliseconds: Some(milliseconds), + context: Some(plan.context), + }; + // The provider's lane writes the request. If that write fails, the + // lane ends the call. + let work = LaneWork::Invoke { + call_id, + request, + operation_id, + caller_plugin: plan.caller_plugin, + }; + lanes.post(sessions, &provider.id, work); + } + + /// Parks the call until a backend is ready, and asks the host to start + /// one the first time the call waits. Starting a process is the host's + /// I/O; Core only says it is needed. + fn wait_for_provider(&self, sessions: &SessionMap, call_id: u64, plan: &DispatchPlan) { + let notice = self.lock().wait_for_provider(call_id, Instant::now()); + if let Some(notice) = notice { + if let Some(session) = find_session(sessions, ¬ice.caller_session) { + session.announce_provider_start_required(¬ice.callee_plugin); + } + } + // A backend may have become ready between the search and the wait, + // and its announcement found no waiting call. Look once more. + let provider_appeared = find_provider( + sessions, + &plan.caller_session, + &plan.callee_plugin, + &plan.function_id, + ) + .is_some(); + if provider_appeared { + self.provider_changed(&plan.callee_plugin); + } + } +} + +/// Plans relay actions in order until the engine is gone. The worker owns the +/// lanes, so its own thread is never the one that writes to a backend. +fn run_worker( + hub: Weak, + sessions: Weak, + actions: mpsc::Receiver, +) { + let mut lanes = Lanes::new(hub.clone(), sessions.clone()); + for action in actions { + let (Some(hub), Some(sessions)) = (hub.upgrade(), sessions.upgrade()) else { + return; + }; + hub.perform(&sessions, &mut lanes, action); + } +} + +/// Work the main relay worker hands to one session's lane. The lane performs +/// it in the order it arrived, because later work may depend on earlier work: +/// a cancel follows the invoke it cancels. +enum LaneWork { + /// Answer a `lithe/host/functions/*` request that this session's plugin + /// backend made. + Reply { + rpc_id: Value, + outcome: Result, + }, + /// Cancel one relayed call this session is serving. + Cancel { operation_id: String }, + /// Write one admitted call to this session, the provider that serves it. + Invoke { + /// The relay's ID of the call, to end it if the write fails. + call_id: u64, + request: PluginFunctionRequest, + /// The callee-side operation ID the relay recorded for the call. + operation_id: String, + /// The plugin whose call this is, which the provider sees as the caller. + caller_plugin: String, + }, +} + +impl LaneWork { + /// Drops work whose session is gone. A reply or cancel has nobody left to + /// tell, but an invoke has a caller waiting, so its call ends. + fn abandon(self, hub: &RelayHub) { + if let Self::Invoke { call_id, .. } = self { + hub.dispatch_failed(call_id, provider_unavailable()); + } + } +} + +/// The lanes the main worker owns, keyed by session ID. A lane ends after it +/// drains its queue once its sender is dropped here. +struct Lanes { + /// What a new lane needs to reach the hub and the sessions. Lanes hold + /// only weak references, so they end with the engine. + hub: Weak, + sessions: Weak, + senders: BTreeMap>, +} + +impl Lanes { + fn new(hub: Weak, sessions: Weak) -> Self { + Self { + hub, + sessions, + senders: BTreeMap::new(), + } + } + + /// Queues `work` on the lane of `session_id`, starting the lane the first + /// time the session needs one. Lanes of sessions that have left the + /// session map are released first, so their threads end. + fn post(&mut self, sessions: &SessionMap, session_id: &str, work: LaneWork) { + let session_present = { + let sessions = sessions.lock().unwrap_or_else(PoisonError::into_inner); + self.senders.retain(|id, _| sessions.contains_key(id)); + sessions.contains_key(session_id) + }; + if !session_present { + self.abandon(work); + return; + } + let (hub, lane_sessions) = (&self.hub, &self.sessions); + let sender = self + .senders + .entry(session_id.to_string()) + .or_insert_with(|| { + let (sender, receiver) = mpsc::channel(); + let (hub, sessions) = (hub.clone(), lane_sessions.clone()); + let session_id = session_id.to_string(); + thread::spawn(move || run_lane(hub, sessions, session_id, receiver)); + sender + }); + if let Err(mpsc::SendError(work)) = sender.send(work) { + // The lane ended without its sender being dropped. Forget it, so + // the next post starts a new lane. + self.senders.remove(session_id); + self.abandon(work); + } + } + + /// Handles work that cannot reach its session; see `LaneWork::abandon`. + fn abandon(&self, work: LaneWork) { + if let Some(hub) = self.hub.upgrade() { + work.abandon(&hub); + } + } +} + +/// Performs the writes to one session in order. This thread alone waits on +/// the session's stdin, and each write is bounded by `bounded_relay_write`. +/// It ends once the engine is gone or the main worker released the lane. +fn run_lane( + hub: Weak, + sessions: Weak, + session_id: String, + queue: mpsc::Receiver, +) { + for work in queue { + let (Some(hub), Some(sessions)) = (hub.upgrade(), sessions.upgrade()) else { + return; + }; + let Some(session) = find_session(&sessions, &session_id) else { + work.abandon(&hub); + continue; + }; + match work { + LaneWork::Invoke { + call_id, + request, + operation_id, + caller_plugin, + } => { + // The call may have ended while it waited behind earlier work. + if !hub.lock().is_running(call_id) { + continue; + } + let written = session.bounded_relay_write(|| { + session.function_request(request, operation_id, Some(caller_plugin.as_str())) + }); + if let Err(error) = written { + hub.dispatch_failed(call_id, dispatch_failure(&error)); + } + } + LaneWork::Reply { rpc_id, outcome } => { + // log-exempt: A write failure is already recorded by send_messages_or_fail; any other failure means the caller session is unusable and nobody is left to answer. + let _ = session.bounded_relay_write(|| session.relay_reply(&rpc_id, &outcome)); + } + LaneWork::Cancel { operation_id } => { + // log-exempt: The operation may already have finished; nothing is left to cancel. + let _ = session.bounded_relay_write(|| session.cancel_operation(&operation_id)); + } + } + } +} + +fn find_session(sessions: &SessionMap, session_id: &str) -> Option> { + let sessions = sessions.lock().unwrap_or_else(PoisonError::into_inner); + sessions.get(session_id).cloned() +} + +/// A ready backend of `plugin_id` that registered `function_id`. A backend +/// of the caller's own workspace wins, so a call stays inside the workspace +/// it was made for when several windows run the same plugin. +fn find_provider( + sessions: &SessionMap, + caller_session: &str, + plugin_id: &str, + function_id: &str, +) -> Option> { + let (candidates, caller_root) = { + let sessions = sessions.lock().unwrap_or_else(PoisonError::into_inner); + let candidates: Vec> = sessions + .values() + .filter(|session| session.plugin_id.as_deref() == Some(plugin_id)) + .cloned() + .collect(); + let caller_root = sessions + .get(caller_session) + .map(|session| session.root_uri.clone()); + (candidates, caller_root) + }; + let mut serving: Vec> = candidates + .into_iter() + .filter(|session| session.serves_function(function_id)) + .collect(); + let same_workspace = serving + .iter() + .position(|session| Some(&session.root_uri) == caller_root.as_ref()); + match same_workspace { + Some(index) => Some(serving.swap_remove(index)), + None => serving.into_iter().next(), + } +} + +/// Why `function_request` refused a call the relay had admitted. +fn dispatch_failure(error: &CoreError) -> RelayFailure { + match error.details.as_deref() { + Some(codes::UNKNOWN) => RelayFailure::new( + codes::NOT_EXPORTED, + "The plugin has not registered this function.", + ), + _ => provider_unavailable(), + } +} + +/// The failure of a call whose provider's session cannot take it, because the +/// session is gone, not ready, or refused the write. +fn provider_unavailable() -> RelayFailure { + RelayFailure::new( + codes::PROVIDER_UNAVAILABLE, + "The plugin could not take the call.", + ) +} + +/// Which call a new `lithe/host/functions/invoke` was made while serving, as +/// the request's `parentOperationID` names it. The backend sends the wire +/// `operationID` of the `lithe/function/invoke` the engine wrote to it. That +/// ID is also the key of the invoke in `state.pending`, so the session's own +/// table proves both that the call is still running and that this backend is +/// the one serving it. +fn call_parent(state: &SessionState, params: &Value) -> CallParent { + let Some(named) = params.get("parentOperationID") else { + return CallParent::Unstated; + }; + // The request's shape was checked before it reached the relay, so a value + // that is not a string cannot name a call that is running. + let Some(wire_id) = named.as_str() else { + return CallParent::Ended; + }; + let Some(pending) = state + .pending + .get(wire_id) + .filter(|pending| pending.method == INVOKE_METHOD) + else { + return CallParent::Ended; + }; + match pending.operation_id.as_deref() { + // A relayed call: its operation ID carries the relay's call ID. + Some(operation_id) if is_relay_operation_id(operation_id) => operation_id + .strip_prefix(OPERATION_PREFIX) + .and_then(|call_id| call_id.parse::().ok()) + .map_or(CallParent::Ended, CallParent::Relay), + // A call the host started, which is not part of a relay chain. + _ => CallParent::Root, + } +} + +fn string_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, RelayFailure> { + params.get(key).and_then(Value::as_str).ok_or_else(|| { + RelayFailure::new( + codes::HOST_INVALID_PARAMS, + "The request params are malformed.", + ) + }) +} + +/// The JSON-RPC message that answers the calling plugin's request. A failure +/// carries its stable code in `error.data.code`, and the callee's own error +/// code, if any, in `error.data.details.pluginErrorCode`. +fn reply_message( + rpc_id: &Value, + outcome: &Result, +) -> Result { + match outcome { + Ok(result) => json_rpc_result(rpc_id, result.clone()), + Err(failure) => { + let mut data = json!({ "code": failure.code }); + if let Some(plugin_error_code) = &failure.plugin_error_code { + data["details"] = json!({ "pluginErrorCode": plugin_error_code }); + } + json_rpc_error_with_data( + rpc_id, + host_rpc_code(failure.code), + &bounded_host_message(&failure.message), + data, + ) + } + } +} + +/// The relay's view of how a function call ended on the callee's session. +/// `result` is the engine's wrapped `{ value }`. +pub(super) fn callee_outcome( + result: Option, + error: Option, +) -> CalleeOutcome { + match error { + Some(error) => CalleeOutcome::Failed { + code: error.code, + message: error.message, + plugin_error_code: error.plugin_error_code, + }, + None => CalleeOutcome::Succeeded( + result + .and_then(|wrapped| wrapped.get("value").cloned()) + .unwrap_or(Value::Null), + ), + } +} + +/// Whether the host may not use this operation ID, because the relay does. +pub(super) fn is_relay_operation_id(operation_id: &str) -> bool { + operation_id.starts_with(OPERATION_PREFIX) +} + +/// Whether an operation of the callee's session belongs to the relay. +pub(super) fn is_relayed_operation(operation_id: &str, method: &str) -> bool { + method == INVOKE_METHOD && is_relay_operation_id(operation_id) +} + +/// Tells the relay about a lifecycle change of `session`. A backend that +/// became ready may serve a call that waited for it; a session that is +/// ending takes its calls with it, in both roles. +pub(super) fn observe_lifecycle(session: &RuntimeSession, lifecycle: LspLifecycleState) { + match lifecycle { + LspLifecycleState::Ready => observe_functions_changed(session), + LspLifecycleState::Stopping | LspLifecycleState::Stopped | LspLifecycleState::Failed => { + session.relay.session_ended(&session.id) + } + LspLifecycleState::Created + | LspLifecycleState::ProcessStarting + | LspLifecycleState::Initializing => {} + } +} + +/// Tells the relay that `session` may now serve functions it did not before. +pub(super) fn observe_functions_changed(session: &RuntimeSession) { + if let Some(plugin_id) = session.plugin_id.as_deref() { + session.relay.provider_changed(plugin_id); + } +} + +impl RuntimeSession { + /// Whether a call to `function_id` can be written to this session now. + fn serves_function(&self, function_id: &str) -> bool { + let Ok(state) = self.lock_state() else { + return false; + }; + state.lifecycle == LspLifecycleState::Ready + && state.client.initialized + && state.client.plugin_functions.contains(function_id) + } + + /// Runs one write the relay's lane makes to this session, and bounds how + /// long it may take. The session monitor fails the session and kills its + /// process when the write is still running after the session's request + /// timeout, which releases a write blocked on a backend that stopped + /// reading its stdin. `write` runs with no session lock held. + fn bounded_relay_write(&self, write: impl FnOnce() -> T) -> T { + if let Ok(mut state) = self.lock_state() { + state.relay_write_deadline = Some(Instant::now() + state.request_timeout); + } + let result = write(); + if let Ok(mut state) = self.lock_state() { + state.relay_write_deadline = None; + } + result + } + + /// Writes the answer to a `lithe/host/functions/*` request this plugin + /// backend made earlier. + fn relay_reply( + &self, + rpc_id: &Value, + outcome: &Result, + ) -> Result<(), CoreError> { + let outbound_order = self.lock_outbound_order()?; + let message = reply_message(rpc_id, outcome)?; + self.send_messages_or_fail(&outbound_order, vec![message], "relayReply") + } + + /// Tells the host that a call waits for a backend of `plugin_id` that is + /// not running, so the host can start it. + fn announce_provider_start_required(&self, plugin_id: &str) { + if let Ok(mut state) = self.lock_state() { + push_provider_start_event(self, &mut state, plugin_id); + } + } +} + +/// The `functionProviderStartRequired` event: a call waits for the plugin's +/// backend, and the host should start it if it can. Like the provider events +/// it carries only its kind and a result, so it shares their builder. +fn push_provider_start_event(session: &RuntimeSession, state: &mut SessionState, plugin_id: &str) { + push_negotiated_provider_event( + session, + state, + json!({ "pluginID": plugin_id }), + "functionProviderStartRequired", + ); +} diff --git a/rust/lithe-core/src/lsp/interface/engine_function_relay_tests.rs b/rust/lithe-core/src/lsp/interface/engine_function_relay_tests.rs new file mode 100644 index 0000000000..7998d22bf6 --- /dev/null +++ b/rust/lithe-core/src/lsp/interface/engine_function_relay_tests.rs @@ -0,0 +1,1339 @@ +//! Engine-level tests of the cross-plugin function relay. +//! +//! Each plugin backend is a scripted server, so a test plays every plugin +//! process: the Python plugin that asks the host to call a function, the Go +//! plugin that exports it, and a third plugin further down the chain. The +//! relay's own rules (limits, nesting, state transitions) have unit tests in +//! `function_relay`; these tests check that the engine carries them out on +//! real sessions: what each backend receives on the wire, and what it is told +//! when a call is refused, fails, is cancelled, or loses a participant. +//! +//! Nothing here sleeps to coordinate. A test waits on the scripted servers' +//! bounded readers or on a bounded poll of the session events, and time-based +//! outcomes use synthetic instants passed to `expire_deadlines_at`. + +use super::super::function_relay::RelaySnapshot; +use super::super::plugin_function::FunctionReference; +use super::super::process::{LspProcessLauncher, LspProcessSpec, LspProcessStreams}; +use super::super::scripted::ScriptedServer; +use super::tests::start_request; +use super::*; + +const PYTHON: &str = "dev.lithe.fixture.python"; +const GO: &str = "dev.lithe.fixture.go"; +const RUST: &str = "dev.lithe.fixture.rust"; +const ALPHA: &str = "dev.lithe.fixture.alpha"; + +const FORMAT: &str = "document.format"; +const LINT: &str = "lint.run"; +const SYMBOLS: &str = "symbols.list"; + +const CONTEXT_ID: &str = "workspace-1"; + +const INVOKE: &str = "lithe/host/functions/invoke"; +const PROVIDERS: &str = "lithe/host/functions/providers"; + +/// A payload the relay refuses: it is above the relay's 256 KiB limit but +/// below every limit of the session itself. +const OVERSIZED_BYTES: usize = 300 * 1024; + +/// Hands every started session its own scripted server, in the order the +/// test queued them. The engine has one launcher for all its sessions. +#[derive(Default)] +struct HandoffLauncher { + queued: Mutex>>, +} + +impl HandoffLauncher { + fn queue(&self, launcher: Arc) { + self.queued.lock().unwrap().push_back(launcher); + } +} + +impl LspProcessLauncher for HandoffLauncher { + fn launch(&self, spec: LspProcessSpec) -> Result { + let next = self.queued.lock().unwrap().pop_front(); + match next { + Some(launcher) => launcher.launch(spec), + None => Err(CoreError::new( + ErrorCode::ProcessStartFailed, + "No scripted server was queued for this start.", + )), + } + } +} + +/// Polls `condition` until it holds. The wait is bounded, so a failure is +/// reported as what was missing instead of hanging the run. +fn await_until(description: &str, mut condition: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if condition() { + return; + } + thread::sleep(Duration::from_millis(2)); + } + panic!("timed out waiting for {description}"); +} + +/// One engine with several plugin backends that share its relay. +struct Fixture { + engine: LspEngine, + launcher: Arc, +} + +impl Fixture { + fn new() -> Self { + let launcher = Arc::new(HandoffLauncher::default()); + Self { + engine: LspEngine::with_launcher(launcher.clone()), + launcher, + } + } + + /// Starts a plugin backend and waits until it is ready to take calls. + fn start(&self, launch: Launch) -> Backend { + let server = ScriptedServer::new(); + self.launcher.queue(server.launcher()); + let mut request = start_request(&server); + request.plugin_id = Some(launch.plugin_id.to_string()); + request.root_uri = launch.root_uri.to_string(); + request.host_services = launch.host_services.clone(); + let started = self + .engine + .start_server(request) + .expect("the plugin backend should start"); + server.complete_initialize(launch.capabilities()); + let session = self + .engine + .session(&started.session_id) + .expect("the session should be registered"); + let backend = Backend { + server, + session, + events: Vec::new(), + }; + backend.await_ready(); + backend + } + + /// Publishes the host's view of the enabled plugins and workspace. + fn configure(&self, snapshot: Value) { + let snapshot: RelaySnapshot = + serde_json::from_value(snapshot).expect("the snapshot has the documented shape"); + self.engine + .relay + .configure(snapshot) + .expect("the snapshot is valid"); + } +} + +/// How a plugin backend starts: what it negotiated and which functions it +/// registered. +struct Launch { + plugin_id: &'static str, + root_uri: &'static str, + protocol_version: u64, + functions: Vec<&'static str>, + host_services: Vec, +} + +impl Launch { + /// A backend that negotiated the relay protocol and holds the grant for + /// it, in the standard workspace. + fn new(plugin_id: &'static str) -> Self { + Self { + plugin_id, + root_uri: "file:///workspace", + protocol_version: 4, + functions: Vec::new(), + host_services: vec!["functions".to_string()], + } + } + + fn serving(mut self, functions: &[&'static str]) -> Self { + self.functions = functions.to_vec(); + self + } + + fn at(mut self, root_uri: &'static str) -> Self { + self.root_uri = root_uri; + self + } + + fn speaking(mut self, protocol_version: u64) -> Self { + self.protocol_version = protocol_version; + self + } + + fn without_grant(mut self) -> Self { + self.host_services.clear(); + self + } + + fn capabilities(&self) -> Value { + let functions: Vec = self + .functions + .iter() + .map(|id| json!({ "id": id })) + .collect(); + json!({ + "experimental": { + "litheFunctions": { "version": self.protocol_version, "functions": functions } + } + }) + } +} + +/// A started plugin backend: the scripted server that plays its process and +/// the engine session that talks to it. +struct Backend { + server: ScriptedServer, + session: Arc, + /// Events are drained by every poll, so the backend accumulates them. + events: Vec, +} + +impl Drop for Backend { + fn drop(&mut self) { + // Ends the session's reader thread instead of leaving it to the run. + self.server.exit(Some(0)); + } +} + +/// Kills a session's process when the test ends. A write held at the scripted +/// server's barrier is released by the kill, so a failed assertion cannot leave +/// an engine thread waiting on it. +struct KillOnDrop(Arc); + +impl Drop for KillOnDrop { + fn drop(&mut self) { + self.0.kill_process(); + } +} + +impl Backend { + fn await_ready(&self) { + await_until("the backend to become ready", || { + self.session + .snapshot() + .is_ok_and(|snapshot| snapshot.state == LspLifecycleState::Ready) + }); + } + + fn poll(&mut self) { + let events = self.session.poll_events().expect("polling should succeed"); + self.events.extend(events); + } + + fn await_event( + &mut self, + description: &str, + matches: impl Fn(&LspRuntimeEvent) -> bool, + ) -> LspRuntimeEvent { + await_until(description, || { + self.poll(); + self.events.iter().any(&matches) + }); + self.events + .iter() + .find(|&event| matches(event)) + .cloned() + .expect("the event was observed") + } + + // The plugin's side: requests the backend sends to the host. + + /// Sends one request to the host, as the plugin process would. + fn ask(&self, id: &str, method: &str, params: Value) { + self.server.send(json!({ + "jsonrpc": "2.0", "id": id, "method": method, "params": params + })); + } + + /// Asks the host to call `function` of `plugin` in the standard context. + fn call(&self, id: &str, plugin: &str, function: &str) { + self.ask(id, INVOKE, call_params(plugin, function)); + } + + /// Asks the host to call `function` of `plugin` while serving the relayed + /// call whose wire operation ID is `parent`, as a plugin that serves + /// several calls at once names the one this request belongs to. + fn call_within(&self, id: &str, parent: &str, plugin: &str, function: &str) { + let mut params = call_params(plugin, function); + params["parentOperationID"] = json!(parent); + self.ask(id, INVOKE, params); + } + + /// The plugin process cancels a request it sent earlier. + fn cancel(&self, id: &str) { + self.server.send(json!({ + "jsonrpc": "2.0", "method": "$/cancelRequest", "params": { "id": id } + })); + } + + /// The host's answer to a request this backend sent. + fn reply(&self, id: &str) -> Value { + self.server + .await_response(id) + .unwrap_or_else(|| panic!("the host never answered request {id}")) + } + + // The callee's side: calls the engine writes to the backend. + + /// The first relayed call as this backend received it: its wire ID and + /// params. + fn await_invoke(&self) -> (String, Value) { + self.await_invoke_at(0) + } + + /// The `index`-th relayed call this backend received, counted in the order + /// the engine wrote them. + fn await_invoke_at(&self, index: usize) -> (String, Value) { + let wire_id = self + .server + .await_request_at("lithe/function/invoke", index) + .expect("the call should reach the callee"); + let request = self + .server + .messages() + .into_iter() + .find(|message| { + message["id"] == wire_id.as_str() && message["method"] == "lithe/function/invoke" + }) + .expect("the request was written"); + (wire_id, request["params"].clone()) + } + + fn answer(&self, wire_id: &str, result: Value) { + self.server + .send(json!({ "jsonrpc": "2.0", "id": wire_id, "result": result })); + } + + fn fail(&self, wire_id: &str, message: &str, plugin_error_code: &str) { + self.server.send(json!({ + "jsonrpc": "2.0", "id": wire_id, + "error": { "code": -32000, "message": message, "data": { "code": plugin_error_code } } + })); + } + + /// Nothing has been written to this backend as a function call. A call the + /// relay refuses never reaches the callee, so this holds without waiting. + fn assert_not_invoked(&self) { + assert!(self + .server + .messages() + .iter() + .all(|message| message["method"] != "lithe/function/invoke")); + } + + /// The IDs of the requests the engine has cancelled on this backend, in + /// the order it wrote the cancellations. + fn cancelled_request_ids(&self) -> Vec { + self.server + .messages() + .into_iter() + .filter(|message| message["method"] == "$/cancelRequest") + .map(|message| message["params"]["id"].clone()) + .collect() + } + + /// A call the host itself starts, as a host feature would. + fn host_call(&self, operation_id: &str, plugin: &str, function: &str) -> Result<(), CoreError> { + self.session.function_request( + PluginFunctionRequest { + session_id: self.session.id.clone(), + operation_id: Some(operation_id.to_string()), + function: FunctionReference { + plugin_id: plugin.to_string(), + function_id: function.to_string(), + }, + params: json!({}), + timeout_milliseconds: None, + context: None, + }, + operation_id.to_string(), + None, + ) + } +} + +fn workspace_context() -> Value { + json!({ "contextID": CONTEXT_ID, "generation": 1 }) +} + +/// The params of `lithe/host/functions/invoke` for a plain call. +fn call_params(plugin: &str, function: &str) -> Value { + json!({ + "pluginID": plugin, + "functionID": function, + "context": workspace_context(), + "params": { "uri": "file:///workspace/main.go" } + }) +} + +/// One plugin as the host reports it: the functions it exports and the +/// functions it declared calling, with their contract versions. +fn plugin(id: &str, exports: &[(&str, u32)], calls: &[(&str, u32)]) -> Value { + let exports: Vec = exports + .iter() + .map(|(function, version)| { + json!({ "id": function, "version": version, "context": "workspace" }) + }) + .collect(); + let calls: Vec = calls + .iter() + .map(|(function, version)| json!({ "id": function, "version": version })) + .collect(); + json!({ "pluginID": id, "exports": exports, "calls": calls }) +} + +fn snapshot(plugins: Vec, authority: &str) -> Value { + json!({ + "plugins": plugins, + "contexts": [{ "contextID": CONTEXT_ID, "generation": 1, "authority": authority }] + }) +} + +/// Python declares calling `document.format`, Go exports it, locally. +fn standard_snapshot() -> Value { + snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[]), + ], + "local", + ) +} + +/// Python calls Go, Go calls Rust, and Rust exports `symbols.list`: the +/// plugins of a chain of two hops. +fn chain_snapshot() -> Value { + snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[(SYMBOLS, 1)]), + plugin(RUST, &[(SYMBOLS, 1)], &[]), + ], + "local", + ) +} + +/// The standard plugins with the workspace context as the host reports it +/// after a change: `Some(generation)` is the generation it serves now, `None` +/// means the context is closed. +fn standard_snapshot_with_context(generation: Option) -> Value { + let contexts: Vec = generation + .map(|generation| { + json!({ "contextID": CONTEXT_ID, "generation": generation, "authority": "local" }) + }) + .into_iter() + .collect(); + json!({ + "plugins": [ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[]), + ], + "contexts": contexts + }) +} + +/// The failure a backend sees: the stable code in `error.data.code` and the +/// JSON-RPC number, which is unique to that code. +fn assert_error(reply: &Value, code: &str, rpc_code: i64) { + assert_eq!(reply["error"]["data"]["code"], code, "{reply}"); + assert_eq!(reply["error"]["code"], rpc_code, "{reply}"); +} + +// The call path. + +#[test] +fn a_declared_exported_call_reaches_the_callee_and_returns_its_value() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let mut go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + // The function's own params may carry a `caller` of their own. Only the + // field Core writes beside them names the caller. + let mut params = call_params(GO, FORMAT); + params["params"]["caller"] = json!({ "pluginID": "dev.lithe.forged" }); + python.ask("call-1", INVOKE, params); + + let (wire_id, received) = go.await_invoke(); + assert_eq!(received["functionID"], FORMAT); + assert_eq!(received["context"], workspace_context()); + assert_eq!(received["caller"], json!({ "pluginID": PYTHON })); + assert_eq!( + received["params"]["caller"], + json!({ "pluginID": "dev.lithe.forged" }) + ); + go.answer(&wire_id, json!({ "edits": 2 })); + + assert_eq!( + python.reply("call-1")["result"], + json!({ "value": { "edits": 2 } }) + ); + // The callee keeps its own identity; the caller is only request context. + assert_eq!(go.session.plugin_id.as_deref(), Some(GO)); + // The relay answers the calling plugin, so the host never sees the call. + go.poll(); + assert!(go.events.iter().all(|event| !event + .operation_id + .as_deref() + .is_some_and(|id| id.starts_with("relay-call-")))); + await_until("the callee to forget the call", || { + go.session + .snapshot() + .is_ok_and(|snapshot| snapshot.pending_operation_ids.is_empty()) + }); +} + +#[test] +fn a_caller_field_in_the_host_request_is_refused() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + let mut params = call_params(GO, FORMAT); + params["caller"] = json!({ "pluginID": "dev.lithe.forged" }); + python.ask("call-1", INVOKE, params); + + assert_error( + &python.reply("call-1"), + "plugin.host.unsupportedOption", + -32018, + ); + go.assert_not_invoked(); +} + +#[test] +fn a_call_the_host_starts_carries_no_caller() { + let fixture = Fixture::new(); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + + go.host_call("host-call-1", GO, FORMAT) + .expect("the host call is sent"); + + let (_, received) = go.await_invoke(); + assert!(received.get("caller").is_none(), "{received}"); +} + +#[test] +fn a_callee_on_an_older_protocol_version_gets_no_caller() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).speaking(3).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + + let (wire_id, received) = go.await_invoke(); + assert!(received.get("caller").is_none(), "{received}"); + // The rest of the call is unchanged for that callee. + assert_eq!(received["context"], workspace_context()); + go.answer(&wire_id, json!({})); + assert_eq!(python.reply("call-1")["result"], json!({ "value": {} })); +} + +#[test] +fn a_failing_callee_keeps_its_own_error_code() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + let (wire_id, _) = go.await_invoke(); + go.fail(&wire_id, "Parse failed.", "go.parseFailed"); + + let reply = python.reply("call-1"); + assert_error(&reply, "plugin.function.failed", -32070); + assert_eq!(reply["error"]["message"], "Parse failed."); + assert_eq!( + reply["error"]["data"]["details"]["pluginErrorCode"], + "go.parseFailed" + ); +} + +#[test] +fn a_result_above_the_relay_limit_is_refused() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + let (wire_id, _) = go.await_invoke(); + // Within the session's own result limit, above the relay's. + go.answer(&wire_id, json!({ "text": "x".repeat(OVERSIZED_BYTES) })); + + assert_error( + &python.reply("call-1"), + "plugin.function.payloadTooLarge", + -32068, + ); +} + +// Discovery. + +#[test] +fn discovery_follows_the_enabled_plugins() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + fixture.configure(standard_snapshot()); + + python.ask("first", PROVIDERS, json!({ "functionID": FORMAT })); + assert_eq!( + python.reply("first")["result"], + json!({ "providers": [{ "pluginID": GO, "version": 1 }] }) + ); + + // A plugin is installed: providers are listed by plugin ID. + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[]), + plugin(ALPHA, &[(FORMAT, 1)], &[]), + ], + "local", + )); + python.ask("second", PROVIDERS, json!({ "functionID": FORMAT })); + assert_eq!( + python.reply("second")["result"], + json!({ "providers": [ + { "pluginID": ALPHA, "version": 1 }, + { "pluginID": GO, "version": 1 } + ] }) + ); + + // A plugin is uninstalled or disabled: it is gone at once. + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(ALPHA, &[(FORMAT, 1)], &[]), + ], + "local", + )); + python.ask("third", PROVIDERS, json!({ "functionID": FORMAT })); + assert_eq!( + python.reply("third")["result"], + json!({ "providers": [{ "pluginID": ALPHA, "version": 1 }] }) + ); + + // A caller that did not declare the function learns nothing about it. + fixture.configure(snapshot(vec![plugin(PYTHON, &[], &[])], "local")); + python.ask("fourth", PROVIDERS, json!({ "functionID": FORMAT })); + assert_error( + &python.reply("fourth"), + "plugin.function.notDeclared", + -32027, + ); +} + +// Refusals. + +struct Refusal { + name: &'static str, + snapshot: Value, + params: Value, + code: &'static str, + rpc_code: i64, +} + +fn refusals() -> Vec { + let mut stale_generation = call_params(GO, FORMAT); + stale_generation["context"]["generation"] = json!(2); + let mut oversized_params = call_params(GO, FORMAT); + oversized_params["params"] = json!({ "text": "x".repeat(OVERSIZED_BYTES) }); + vec![ + Refusal { + name: "the caller did not declare the call", + snapshot: snapshot( + vec![plugin(PYTHON, &[], &[]), plugin(GO, &[(FORMAT, 1)], &[])], + "local", + ), + params: call_params(GO, FORMAT), + code: "plugin.function.notDeclared", + rpc_code: -32027, + }, + Refusal { + name: "the plugin does not export the function", + snapshot: snapshot( + vec![plugin(PYTHON, &[], &[(FORMAT, 1)]), plugin(GO, &[], &[])], + "local", + ), + params: call_params(GO, FORMAT), + code: "plugin.function.notExported", + rpc_code: -32028, + }, + Refusal { + name: "the plugin is not enabled", + snapshot: snapshot(vec![plugin(PYTHON, &[], &[(FORMAT, 1)])], "local"), + params: call_params(GO, FORMAT), + code: "plugin.function.providerDisabled", + rpc_code: -32029, + }, + Refusal { + name: "the contract versions differ", + snapshot: snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 2)]), + plugin(GO, &[(FORMAT, 1)], &[]), + ], + "local", + ), + params: call_params(GO, FORMAT), + code: "plugin.function.versionMismatch", + rpc_code: -32030, + }, + Refusal { + name: "the workspace context is stale", + snapshot: standard_snapshot(), + params: stale_generation, + code: "plugin.host.contextExpired", + rpc_code: -32011, + }, + Refusal { + name: "the workspace is remote", + snapshot: snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[]), + ], + "remote", + ), + params: call_params(GO, FORMAT), + code: "plugin.host.authorityUnsupported", + rpc_code: -32012, + }, + Refusal { + name: "the params are above the relay limit", + snapshot: standard_snapshot(), + params: oversized_params, + code: "plugin.function.payloadTooLarge", + rpc_code: -32068, + }, + ] +} + +#[test] +fn a_refused_call_never_reaches_the_callee() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + + for (index, refusal) in refusals().into_iter().enumerate() { + fixture.configure(refusal.snapshot); + let id = format!("call-{index}"); + python.ask(&id, INVOKE, refusal.params); + let reply = python.reply(&id); + assert_eq!( + reply["error"]["data"]["code"], refusal.code, + "{}: {reply}", + refusal.name + ); + assert_eq!( + reply["error"]["code"], refusal.rpc_code, + "{}: {reply}", + refusal.name + ); + } + go.assert_not_invoked(); +} + +#[test] +fn relay_methods_need_protocol_version_4_and_the_functions_grant() { + let fixture = Fixture::new(); + let old_protocol = fixture.start(Launch::new(PYTHON).speaking(3)); + old_protocol.call("call-1", GO, FORMAT); + assert_error( + &old_protocol.reply("call-1"), + "plugin.host.unavailable", + -32601, + ); + old_protocol.ask("providers-1", PROVIDERS, json!({ "functionID": FORMAT })); + assert_error( + &old_protocol.reply("providers-1"), + "plugin.host.unavailable", + -32601, + ); + + let ungranted = fixture.start(Launch::new(ALPHA).without_grant()); + ungranted.call("call-2", GO, FORMAT); + assert_error( + &ungranted.reply("call-2"), + "plugin.host.permissionDenied", + -32010, + ); +} + +#[test] +fn the_old_refusals_still_hold_with_the_relay() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON).serving(&[LINT])); + fixture.configure(standard_snapshot()); + + // A backend still cannot ask the host to run a function or a domain + // operation, which could route back into the backend itself. + for (id, method) in [ + ("invoke", "lithe/function/invoke"), + ("model", "lithe/build/model"), + ] { + python.ask(id, method, json!({})); + assert_eq!( + python.reply(id)["error"]["data"]["code"], + "plugin.function.recursiveCall", + "{method}" + ); + } + + // The host still cannot call another plugin's function through a session. + let error = python + .host_call("host-call-1", GO, FORMAT) + .expect_err("another plugin's function stays private"); + assert!(matches!(error.code, ErrorCode::PermissionDenied)); + assert_eq!( + error.details.as_deref(), + Some("plugin.function.wrongPlugin") + ); + + // The host cannot take an operation ID the relay hands out. + let error = python + .host_call("relay-call-1", PYTHON, LINT) + .expect_err("the operation ID is reserved"); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); +} + +// Chains. + +#[test] +fn a_plugin_cannot_call_itself_or_back_into_its_own_chain() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON).serving(&[LINT])); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[(LINT, 1)], &[(FORMAT, 1), (LINT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[(LINT, 1)]), + ], + "local", + )); + + python.call("self", PYTHON, LINT); + assert_error(&python.reply("self"), "plugin.function.callCycle", -32065); + + // Python -> Go -> Python: Go's call lands on a plugin that is already + // waiting for Go's answer. + python.call("forward", GO, FORMAT); + let (wire_id, _) = go.await_invoke(); + go.call("back", PYTHON, LINT); + assert_error(&go.reply("back"), "plugin.function.callCycle", -32065); + python.assert_not_invoked(); + + go.answer(&wire_id, json!({})); + assert_eq!(python.reply("forward")["result"], json!({ "value": {} })); +} + +#[test] +fn cancelling_a_call_cancels_the_calls_made_while_serving_it() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + let rust = fixture.start(Launch::new(RUST).serving(&[SYMBOLS])); + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[(SYMBOLS, 1)]), + plugin(RUST, &[(SYMBOLS, 1)], &[]), + ], + "local", + )); + + python.call("outer", GO, FORMAT); + go.await_invoke(); + go.call("inner", RUST, SYMBOLS); + let (_, nested) = rust.await_invoke(); + // The innermost callee sees the plugin that called it, not the origin. + assert_eq!(nested["caller"], json!({ "pluginID": GO })); + + python.cancel("outer"); + + assert_error(&python.reply("outer"), "plugin.host.cancelled", -32800); + assert!(go.server.await_notification("$/cancelRequest")); + assert!(rust.server.await_notification("$/cancelRequest")); + assert_error(&go.reply("inner"), "plugin.host.cancelled", -32800); +} + +// A plugin that serves several calls at once says which one it is serving. + +/// A plugin serving two calls names the call a new request belongs to, so +/// cancelling one call cancels only the calls made for it. +#[test] +fn a_named_parent_scopes_cancellation_to_its_own_children() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let alpha = fixture.start(Launch::new(ALPHA)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + let rust = fixture.start(Launch::new(RUST).serving(&[SYMBOLS])); + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(ALPHA, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[(SYMBOLS, 1)]), + plugin(RUST, &[(SYMBOLS, 1)], &[]), + ], + "local", + )); + + // Go serves two calls at once. Each is awaited before the next is made, so + // the order Go received them in is known. + python.call("from-python", GO, FORMAT); + let (python_wire_id, python_call) = go.await_invoke_at(0); + alpha.call("from-alpha", GO, FORMAT); + let (alpha_wire_id, alpha_call) = go.await_invoke_at(1); + assert_eq!(python_call["caller"], json!({ "pluginID": PYTHON })); + assert_eq!(alpha_call["caller"], json!({ "pluginID": ALPHA })); + + // While serving each call Go calls Rust, naming the call it serves. + let python_operation = python_call["operationID"] + .as_str() + .expect("the call carries its wire operation ID"); + let alpha_operation = alpha_call["operationID"] + .as_str() + .expect("the call carries its wire operation ID"); + go.call_within("for-python", python_operation, RUST, SYMBOLS); + let (for_python_wire_id, for_python) = rust.await_invoke_at(0); + assert_eq!(for_python["caller"], json!({ "pluginID": GO })); + go.call_within("for-alpha", alpha_operation, RUST, SYMBOLS); + let (for_alpha_wire_id, for_alpha) = rust.await_invoke_at(1); + assert_eq!(for_alpha["caller"], json!({ "pluginID": GO })); + + python.cancel("from-python"); + + // Python's call ends, and so does the call Go made for it. + assert_error( + &python.reply("from-python"), + "plugin.host.cancelled", + -32800, + ); + assert_error(&go.reply("for-python"), "plugin.host.cancelled", -32800); + assert!(go + .server + .await_notification_at("$/cancelRequest", 0) + .is_some()); + assert!(rust + .server + .await_notification_at("$/cancelRequest", 0) + .is_some()); + + // Alpha's call, and the call Go made for it, run to their answers. + rust.answer(&for_alpha_wire_id, json!({ "symbols": 2 })); + assert_eq!( + go.reply("for-alpha")["result"], + json!({ "value": { "symbols": 2 } }) + ); + go.answer(&alpha_wire_id, json!({ "edits": 5 })); + assert_eq!( + alpha.reply("from-alpha")["result"], + json!({ "value": { "edits": 5 } }) + ); + // Only the two calls that belonged to Python's call were cancelled. + assert_eq!(go.cancelled_request_ids(), vec![json!(python_wire_id)]); + assert_eq!( + rust.cancelled_request_ids(), + vec![json!(for_python_wire_id)] + ); +} + +/// A parent operation ID that names no running relayed call is refused, so a +/// call cannot be attached to a call that was never there. +#[test] +fn an_unknown_parent_operation_is_refused() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + // The longest ID the host accepts is still an unknown call. + let longest = "1".repeat(128); + for (index, parent) in ["999999", longest.as_str()].into_iter().enumerate() { + let mut params = call_params(GO, FORMAT); + params["parentOperationID"] = json!(parent); + let id = format!("call-{index}"); + python.ask(&id, INVOKE, params); + assert_error(&python.reply(&id), "plugin.host.cancelled", -32800); + } + go.assert_not_invoked(); +} + +/// A parent operation ID of the wrong type or length is a malformed request, +/// not an unknown call. +#[test] +fn a_malformed_parent_operation_id_is_refused() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + let malformed = [ + ("a number", json!(17)), + ("an empty string", json!("")), + ("a string above 128 bytes", json!("1".repeat(129))), + ]; + for (index, (name, parent)) in malformed.into_iter().enumerate() { + let mut params = call_params(GO, FORMAT); + params["parentOperationID"] = parent; + let id = format!("call-{index}"); + python.ask(&id, INVOKE, params); + let reply = python.reply(&id); + assert_eq!( + reply["error"]["data"]["code"], "plugin.host.invalidParams", + "{name}: {reply}" + ); + assert_eq!(reply["error"]["code"], -32602, "{name}: {reply}"); + } + go.assert_not_invoked(); +} + +/// Once the call a plugin was serving has ended, a late request that names it +/// is refused instead of becoming a call nobody waits for. +#[test] +fn a_finished_parent_operation_is_refused() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + let rust = fixture.start(Launch::new(RUST).serving(&[SYMBOLS])); + fixture.configure(chain_snapshot()); + + python.call("outer", GO, FORMAT); + let (wire_id, received) = go.await_invoke(); + let operation = received["operationID"] + .as_str() + .expect("the call carries its wire operation ID") + .to_string(); + go.answer(&wire_id, json!({})); + // The caller's answer is written after the relay forgot the call. + assert_eq!(python.reply("outer")["result"], json!({ "value": {} })); + + go.call_within("late", &operation, RUST, SYMBOLS); + + assert_error(&go.reply("late"), "plugin.host.cancelled", -32800); + rust.assert_not_invoked(); +} + +// Time, loss of a participant, hot activation. + +#[test] +fn a_callee_that_runs_out_of_time_fails_the_call() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + let mut params = call_params(GO, FORMAT); + params["timeoutMilliseconds"] = json!(1_000); + python.ask("call-1", INVOKE, params); + go.await_invoke(); + + // A synthetic instant past the callee session's deadline for the call. + go.session + .expire_deadlines_at(Instant::now() + Duration::from_secs(120)); + + assert_error(&python.reply("call-1"), "plugin.host.timeout", -32015); +} + +#[test] +fn a_caller_that_stops_cancels_its_callee() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + go.await_invoke(); + python.server.exit(Some(1)); + + // Nobody is left to answer; the callee is told to stop working. + assert!(go.server.await_notification("$/cancelRequest")); +} + +#[test] +fn a_callee_that_stops_fails_the_call_for_its_caller() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + go.await_invoke(); + go.server.exit(Some(1)); + + assert_error( + &python.reply("call-1"), + "plugin.function.providerUnavailable", + -32069, + ); +} + +#[test] +fn disabling_the_provider_ends_calls_in_flight() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + go.await_invoke(); + fixture.configure(snapshot(vec![plugin(PYTHON, &[], &[(FORMAT, 1)])], "local")); + + assert_error( + &python.reply("call-1"), + "plugin.function.providerDisabled", + -32029, + ); + assert!(go.server.await_notification("$/cancelRequest")); + python.call("call-2", GO, FORMAT); + assert_error( + &python.reply("call-2"), + "plugin.function.providerDisabled", + -32029, + ); +} + +// A callee whose backend is not running. + +#[test] +fn a_call_waits_for_a_provider_the_host_starts() { + let fixture = Fixture::new(); + let mut python = fixture.start(Launch::new(PYTHON)); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + // Core only says that a backend is needed; starting it is the host's job. + let notice = python.await_event("the start request", |event| { + event.kind == "functionProviderStartRequired" + }); + assert_eq!(notice.result, Some(json!({ "pluginID": GO }))); + + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + let (wire_id, received) = go.await_invoke(); + assert_eq!(received["caller"], json!({ "pluginID": PYTHON })); + go.answer(&wire_id, json!({ "edits": 0 })); + + assert_eq!( + python.reply("call-1")["result"], + json!({ "value": { "edits": 0 } }) + ); + python.poll(); + let notices = python + .events + .iter() + .filter(|event| event.kind == "functionProviderStartRequired") + .count(); + assert_eq!(notices, 1, "one waiting call asks for one start"); +} + +#[test] +fn a_provider_that_registers_the_function_later_serves_the_waiting_call() { + let fixture = Fixture::new(); + let mut python = fixture.start(Launch::new(PYTHON)); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + python.await_event("the start request", |event| { + event.kind == "functionProviderStartRequired" + }); + // The backend is ready but has not registered the function yet. + let go = fixture.start(Launch::new(GO)); + go.assert_not_invoked(); + + go.ask( + "register", + "lithe/function/register", + json!({ "functions": [{ "id": FORMAT }] }), + ); + assert_eq!(go.reply("register")["result"], Value::Null); + + let (wire_id, _) = go.await_invoke(); + go.answer(&wire_id, json!({})); + assert_eq!(python.reply("call-1")["result"], json!({ "value": {} })); +} + +#[test] +fn a_provider_that_never_starts_ends_the_call() { + let fixture = Fixture::new(); + let mut python = fixture.start(Launch::new(PYTHON)); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + python.await_event("the start request", |event| { + event.kind == "functionProviderStartRequired" + }); + // Synthetic instant past the 30 second start limit, within the call's own + // 60 second limit. + python + .session + .expire_deadlines_at(Instant::now() + Duration::from_secs(31)); + + assert_error( + &python.reply("call-1"), + "plugin.function.providerUnavailable", + -32069, + ); +} + +#[test] +fn a_call_that_runs_out_of_time_while_waiting_times_out() { + let fixture = Fixture::new(); + let mut python = fixture.start(Launch::new(PYTHON)); + fixture.configure(standard_snapshot()); + + let mut params = call_params(GO, FORMAT); + params["timeoutMilliseconds"] = json!(5_000); + python.ask("call-1", INVOKE, params); + python.await_event("the start request", |event| { + event.kind == "functionProviderStartRequired" + }); + python + .session + .expire_deadlines_at(Instant::now() + Duration::from_secs(10)); + + assert_error(&python.reply("call-1"), "plugin.host.timeout", -32015); +} + +#[test] +fn a_call_goes_to_the_provider_of_the_callers_workspace() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON).at("file:///workspace-b")); + // Started first, so it would win on session order alone. + let other_workspace = + fixture.start(Launch::new(GO).serving(&[FORMAT]).at("file:///workspace-a")); + let same_workspace = + fixture.start(Launch::new(GO).serving(&[FORMAT]).at("file:///workspace-b")); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + let (wire_id, _) = same_workspace.await_invoke(); + same_workspace.answer(&wire_id, json!({})); + + assert_eq!(python.reply("call-1")["result"], json!({ "value": {} })); + other_workspace.assert_not_invoked(); +} + +// A workspace context that closes or moves on. + +/// A call that waits for its provider's backend, then the host reports a +/// different state of the workspace context the call was made in. +fn assert_waiting_call_ends_when_context_changes(reconfigured: Value) { + let fixture = Fixture::new(); + let mut python = fixture.start(Launch::new(PYTHON)); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + python.await_event("the start request", |event| { + event.kind == "functionProviderStartRequired" + }); + fixture.configure(reconfigured); + + assert_error( + &python.reply("call-1"), + "plugin.host.contextExpired", + -32011, + ); +} + +/// A call still waiting for its provider ends as soon as the host closes the +/// workspace context it was made in, instead of lasting until its deadline. +#[test] +fn a_closed_context_ends_a_call_waiting_for_its_provider() { + assert_waiting_call_ends_when_context_changes(standard_snapshot_with_context(None)); +} + +/// A new generation of the context is a different context: a call made in the +/// old generation and still waiting for its provider ends. +#[test] +fn a_newer_context_generation_ends_a_call_waiting_for_its_provider() { + assert_waiting_call_ends_when_context_changes(standard_snapshot_with_context(Some(2))); +} + +/// A call that the callee is already running ends when its context closes, and +/// the callee is told to stop working on it. +#[test] +fn a_closed_context_ends_a_running_call_and_cancels_its_callee() { + let fixture = Fixture::new(); + let python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + fixture.configure(standard_snapshot()); + + python.call("call-1", GO, FORMAT); + let (wire_id, _) = go.await_invoke(); + fixture.configure(standard_snapshot_with_context(None)); + + assert_error( + &python.reply("call-1"), + "plugin.host.contextExpired", + -32011, + ); + assert!(go.server.await_notification("$/cancelRequest")); + assert_eq!(go.cancelled_request_ids(), vec![json!(wire_id)]); +} + +// A backend that stops reading its input. + +/// A backend that stops reading holds up only the writes to its own process. +/// Its answer waits at the blocked write while another pair of plugins +/// completes a call, and the blocked write fails its session once it has +/// outlasted its own deadline. +#[test] +fn a_backend_that_stops_reading_does_not_hold_up_other_calls() { + let fixture = Fixture::new(); + let mut python = fixture.start(Launch::new(PYTHON)); + let go = fixture.start(Launch::new(GO).serving(&[FORMAT])); + let alpha = fixture.start(Launch::new(ALPHA)); + let rust = fixture.start(Launch::new(RUST).serving(&[SYMBOLS])); + fixture.configure(snapshot( + vec![ + plugin(PYTHON, &[], &[(FORMAT, 1)]), + plugin(GO, &[(FORMAT, 1)], &[]), + plugin(ALPHA, &[], &[(SYMBOLS, 1)]), + plugin(RUST, &[(SYMBOLS, 1)], &[]), + ], + "local", + )); + let _release = KillOnDrop(python.session.clone()); + + // Python's process stops reading. The one write left for it is the answer + // to its own call, so that is the write held at the barrier. + python.server.pause_input(); + python.call("call-1", GO, FORMAT); + let (wire_id, _) = go.await_invoke(); + go.answer(&wire_id, json!({})); + assert!( + python.server.await_input_pause(), + "the answer should reach the blocked write" + ); + + // The other pair is not held up behind it. + alpha.call("call-2", RUST, SYMBOLS); + let (other_wire_id, received) = rust.await_invoke(); + assert_eq!(received["caller"], json!({ "pluginID": ALPHA })); + rust.answer(&other_wire_id, json!({ "symbols": 3 })); + assert_eq!( + alpha.reply("call-2")["result"], + json!({ "value": { "symbols": 3 } }) + ); + + // The blocked write outlasts its deadline: the session fails, and killing + // the process releases the write. + python.session.lock_state().unwrap().relay_write_deadline = Some(Instant::now()); + python.session.expire_deadlines_at(Instant::now()); + let failed = python.await_event("python's session to fail", |event| { + event.kind == "stateChanged" && event.state == Some(LspLifecycleState::Failed) + }); + let error = failed.error.expect("the failure carries its reason"); + assert_eq!(error.code, "transportFailed"); + assert_eq!(error.stage, "relayWrite"); + assert!(python.server.await_input_resumed()); +} diff --git a/rust/lithe-core/src/lsp/interface/function_relay.rs b/rust/lithe-core/src/lsp/interface/function_relay.rs new file mode 100644 index 0000000000..d92576f368 --- /dev/null +++ b/rust/lithe-core/src/lsp/interface/function_relay.rs @@ -0,0 +1,2007 @@ +//! Cross-plugin function relay: the rules that decide whether one plugin may +//! call a function another plugin exports, and the bookkeeping of the calls in +//! flight. +//! +//! This module is a pure state machine. It never touches a session, a thread +//! or the clock: every method takes what it needs, changes only its own +//! tables, and returns the `RelayAction`s the engine must carry out. The +//! engine (`engine_function_relay`) owns the I/O, so these rules can be tested +//! with plain values and synthetic `Instant`s. +//! +//! A call has two sides and both must have agreed in their manifests: the +//! callee lists the function under `pluginFunctions.exports` and the caller +//! lists it under `pluginFunctions.calls`, with the same contract version. +//! The host supplies the list of enabled plugins as a snapshot; presence in +//! the snapshot means the plugin is enabled. +//! +//! Trust never follows a call. The callee runs with its own permissions, and +//! the caller's plugin ID travels only as the `caller` field of the request +//! the callee receives, never as the callee session's identity. +//! +//! The rules live in the plugin contract +//! (`shared/contracts/plugins/v1/README.md`, "Plugin functions"). + +use super::plugin_function::{codes, is_function_id, is_plugin_id}; +use crate::plugins::plugin_functions::KNOWN_CONTEXTS; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::time::{Duration, Instant}; + +/// Most plugins in one hop chain. A chain A -> B -> C is depth 2 for the call +/// C receives; the limit keeps a mistaken fan-out from growing without bound. +pub(crate) const MAX_CALL_DEPTH: usize = 4; + +/// Most relayed calls one plugin may have in flight at once, counted over +/// every session and window the plugin runs in. +pub(crate) const MAX_CALLS_PER_CALLER: usize = 8; + +/// Largest serialized `params` a relayed call carries. +pub(crate) const MAX_PARAMS_BYTES: usize = 256 * 1024; + +/// Largest serialized function result a relayed call returns. +pub(crate) const MAX_RESULT_BYTES: usize = 256 * 1024; + +/// Deadline of a call that names none. +pub(crate) const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); + +/// Longest deadline a call may ask for. +pub(crate) const MAX_TIMEOUT: Duration = Duration::from_secs(10 * 60); + +/// How long a call waits for the callee's backend to start and register the +/// function before it fails with `plugin.function.providerUnavailable`. +pub(crate) const PROVIDER_START_TIMEOUT: Duration = Duration::from_secs(30); + +/// How long after its deadline a running call may still wait for the callee's +/// own timeout reply before the relay ends it. The callee session enforces the +/// same deadline and normally answers first; this only ends calls whose callee +/// never answers. +pub(crate) const RUNNING_GRACE: Duration = Duration::from_secs(2); + +/// Operation IDs of relayed calls start with this. The engine keeps them out +/// of the callee session's host events, because no host operation waits for +/// them: the answer goes to the calling plugin. +pub(crate) const OPERATION_PREFIX: &str = "relay-call-"; + +/// Most plugins one snapshot may list. Guards the table, not the product. +const MAX_SNAPSHOT_PLUGINS: usize = 4096; + +/// Where a workspace context runs, as the host reports it. +#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum ContextAuthority { + Local, + Remote, +} + +/// One workspace context generation the host currently serves. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RelayContext { + #[serde(rename = "contextID")] + pub context_id: String, + pub generation: u64, + pub authority: ContextAuthority, +} + +/// A function an enabled plugin exports. +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RelayExport { + pub id: String, + pub version: u32, + pub context: String, +} + +/// A function an enabled plugin declared it calls. +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RelayCall { + pub id: String, + pub version: u32, +} + +/// What the relay needs to know about one enabled plugin. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RelayPlugin { + #[serde(rename = "pluginID")] + pub plugin_id: String, + #[serde(default)] + pub exports: Vec, + #[serde(default)] + pub calls: Vec, +} + +/// The host's complete view: the enabled plugins and the live workspace +/// contexts. Each configuration replaces the previous one, which is how +/// installing, updating, disabling and uninstalling a plugin reaches calls +/// already in flight. +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RelaySnapshot { + #[serde(default)] + pub plugins: Vec, + #[serde(default)] + pub contexts: Vec, +} + +/// Why a relayed call (or a discovery) did not succeed. `code` is the stable +/// `plugin.function.*` or `plugin.host.*` code the calling plugin branches on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct RelayFailure { + pub code: &'static str, + pub message: String, + /// The callee's own code (`error.data.code`) when its function failed. + pub plugin_error_code: Option, +} + +impl RelayFailure { + pub(crate) fn new(code: &'static str, message: &str) -> Self { + Self { + code, + message: message.to_string(), + plugin_error_code: None, + } + } +} + +/// Which call a new request was made while serving, as the engine resolved +/// the request's `parentOperationID`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CallParent { + /// The request named no parent: every relayed call the caller's session + /// is running counts as one. + Unstated, + /// The named operation is one the host started, not a relayed call, so + /// the new call starts a chain. + Root, + /// The named operation is this relayed call. + Relay(u64), + /// The named operation is not running in the caller's session. + Ended, +} + +/// One request of a plugin to call an exported function. +pub(crate) struct RelayRequest { + pub caller_session: String, + pub caller_plugin: String, + /// JSON-RPC ID of the request, echoed in the answer. + pub rpc_id: Value, + pub callee_plugin: String, + pub function_id: String, + /// A JSON object. + pub params: Value, + /// `{ contextID, generation }`. + pub context: Value, + pub timeout: Option, + /// The call this request was made while serving; decides the new call's + /// plugin chain and which ended call cancels it. + pub parent: CallParent, +} + +/// How the callee's side of a call ended. +pub(crate) enum CalleeOutcome { + /// The function returned this value. + Succeeded(Value), + /// The call ended without a value; `code` is the engine's request code, + /// such as `plugin.function.failed` or `requestTimeout`. + Failed { + code: String, + message: String, + plugin_error_code: Option, + }, +} + +/// Work the engine must do after a state change. Every action runs outside +/// all session locks. +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum RelayAction { + /// Answer the calling plugin's request. + Reply { + session_id: String, + rpc_id: Value, + outcome: Result, + }, + /// Tell the callee session to stop one running call. + CancelCallee { + session_id: String, + operation_id: String, + }, + /// Find the callee's backend and send it the call. + Dispatch { call_id: u64 }, +} + +/// Everything the engine needs to send one call to the callee's backend. +pub(crate) struct DispatchPlan { + pub caller_session: String, + pub caller_plugin: String, + pub callee_plugin: String, + pub function_id: String, + pub params: Value, + pub context: Value, + pub remaining: Duration, +} + +/// Tells the caller's session that the callee's backend must be started. +pub(crate) struct StartNotice { + pub caller_session: String, + pub callee_plugin: String, +} + +enum Phase { + /// Admitted; the engine is looking for the callee's backend. + Dispatching, + /// No ready backend yet; the host was asked to start one. + WaitingForProvider, + /// The callee's session has the call. + Running { + session_id: String, + operation_id: String, + }, +} + +struct Call { + id: u64, + caller_session: String, + caller_plugin: String, + rpc_id: Value, + callee_plugin: String, + function_id: String, + params: Value, + context: Value, + deadline: Instant, + /// Set when the call first waits for a backend, never moved afterwards, so + /// retries cannot extend the wait. + give_up_at: Option, + /// Plugins from the root call down to the caller, without repeats. + chain: Vec, + /// Calls the caller's session was serving when it made this one: the one + /// the request named, or every one when it named none. When all of them + /// end this call is cancelled; a root call has none. + parents: BTreeSet, + phase: Phase, +} + +/// The relay's tables. See the module comment. +#[derive(Default)] +pub(crate) struct FunctionRelay { + plugins: BTreeMap, + contexts: BTreeMap, + calls: BTreeMap, + next_call_id: u64, +} + +impl FunctionRelay { + /// Replaces the snapshot and ends the calls it no longer allows. + pub(crate) fn configure( + &mut self, + snapshot: RelaySnapshot, + ) -> Result, &'static str> { + check_snapshot(&snapshot)?; + self.plugins = snapshot + .plugins + .into_iter() + .map(|mut plugin| { + // An export without a context this Core knows is not callable. + plugin + .exports + .retain(|export| KNOWN_CONTEXTS.contains(&export.context.as_str())); + (plugin.plugin_id.clone(), plugin) + }) + .collect(); + self.contexts = snapshot + .contexts + .into_iter() + .map(|context| (context.context_id.clone(), context)) + .collect(); + Ok(self.end_calls_the_snapshot_forbids()) + } + + /// Answers `lithe/host/functions/providers`: the enabled plugins that + /// export `function_id`, sorted by plugin ID, with the contract version + /// each exports so a mismatch with the caller's declaration is visible. + pub(crate) fn providers( + &self, + caller_plugin: &str, + function_id: &str, + ) -> Result { + self.declared_version(caller_plugin, function_id)?; + let providers: Vec = self + .plugins + .values() + .filter(|plugin| plugin.plugin_id != caller_plugin) + .filter_map(|plugin| { + let export = exported(plugin, function_id)?; + Some(json!({ "pluginID": plugin.plugin_id, "version": export.version })) + }) + .collect(); + Ok(json!({ "providers": providers })) + } + + /// Checks one call request. The checks run in a fixed order, so the same + /// request always reports the same reason. On success the call is + /// recorded and the returned actions ask the engine to dispatch it. + pub(crate) fn admit( + &mut self, + request: RelayRequest, + now: Instant, + ) -> Result, RelayFailure> { + let declared_version = + self.declared_version(&request.caller_plugin, &request.function_id)?; + let provider = self.plugins.get(&request.callee_plugin).ok_or_else(|| { + RelayFailure::new( + codes::PROVIDER_DISABLED, + "The plugin that exports this function is not enabled.", + ) + })?; + let export = exported(provider, &request.function_id).ok_or_else(|| { + RelayFailure::new( + codes::NOT_EXPORTED, + "The plugin does not export this function.", + ) + })?; + if export.version != declared_version { + return Err(RelayFailure::new( + codes::VERSION_MISMATCH, + "The function's contract version differs from the version this plugin declared.", + )); + } + self.check_context(&request.context)?; + if request.params.to_string().len() > MAX_PARAMS_BYTES { + return Err(RelayFailure::new( + codes::PAYLOAD_TOO_LARGE, + "The call's params exceed the relay limit.", + )); + } + let (chain, parents) = self.ancestry( + &request.caller_session, + &request.caller_plugin, + request.parent, + )?; + if chain.contains(&request.callee_plugin) { + return Err(RelayFailure::new( + codes::CALL_CYCLE, + "The call would re-enter a plugin that is already part of this call chain.", + )); + } + if chain.len() > MAX_CALL_DEPTH { + return Err(RelayFailure::new( + codes::DEPTH_EXCEEDED, + "Plugin calls are nested too deeply.", + )); + } + let in_flight = self + .calls + .values() + .filter(|call| call.caller_plugin == request.caller_plugin) + .count(); + if in_flight >= MAX_CALLS_PER_CALLER { + return Err(RelayFailure::new( + codes::TOO_MANY_CALLS, + "This plugin has too many plugin calls in flight.", + )); + } + + let timeout = request.timeout.unwrap_or(DEFAULT_TIMEOUT).min(MAX_TIMEOUT); + self.next_call_id += 1; + let call_id = self.next_call_id; + self.calls.insert( + call_id, + Call { + id: call_id, + caller_session: request.caller_session, + caller_plugin: request.caller_plugin, + rpc_id: request.rpc_id, + callee_plugin: request.callee_plugin, + function_id: request.function_id, + params: request.params, + context: request.context, + deadline: now + timeout, + give_up_at: None, + chain, + parents, + phase: Phase::Dispatching, + }, + ); + Ok(vec![RelayAction::Dispatch { call_id }]) + } + + /// What the engine needs to send the call, or `None` when it already + /// ended. + pub(crate) fn dispatch_plan(&self, call_id: u64, now: Instant) -> Option { + let call = self.calls.get(&call_id)?; + Some(DispatchPlan { + caller_session: call.caller_session.clone(), + caller_plugin: call.caller_plugin.clone(), + callee_plugin: call.callee_plugin.clone(), + function_id: call.function_id.clone(), + params: call.params.clone(), + context: call.context.clone(), + remaining: call.deadline.saturating_duration_since(now), + }) + } + + /// Records that no ready backend serves the call yet. Returns the notice + /// for the host to start one, only the first time the call waits. + pub(crate) fn wait_for_provider(&mut self, call_id: u64, now: Instant) -> Option { + let call = self.calls.get_mut(&call_id)?; + call.phase = Phase::WaitingForProvider; + if call.give_up_at.is_some() { + return None; + } + call.give_up_at = Some(now + PROVIDER_START_TIMEOUT); + Some(StartNotice { + caller_session: call.caller_session.clone(), + callee_plugin: call.callee_plugin.clone(), + }) + } + + /// Records the callee session and operation that now own the call, before + /// the request is written, so an answer that beats the caller of this + /// method still finds its call. Returns false when the call already + /// ended. + pub(crate) fn started(&mut self, call_id: u64, session_id: &str, operation_id: &str) -> bool { + let Some(call) = self.calls.get_mut(&call_id) else { + return false; + }; + call.phase = Phase::Running { + session_id: session_id.to_string(), + operation_id: operation_id.to_string(), + }; + true + } + + /// Whether the call exists and its callee session has it. The engine asks + /// before writing the request, to skip a call that ended while it queued. + pub(crate) fn is_running(&self, call_id: u64) -> bool { + self.calls + .get(&call_id) + .is_some_and(|call| matches!(call.phase, Phase::Running { .. })) + } + + /// The call could not be sent to the callee's backend. + pub(crate) fn dispatch_failed( + &mut self, + call_id: u64, + failure: RelayFailure, + ) -> Vec { + self.end_call(call_id, Some(Err(failure)), false) + } + + /// The callee's session finished an operation. Anything that is not a + /// running relayed call returns no actions. + pub(crate) fn callee_finished( + &mut self, + session_id: &str, + operation_id: &str, + outcome: CalleeOutcome, + ) -> Vec { + let Some(call_id) = self.running_call(session_id, operation_id) else { + return Vec::new(); + }; + self.end_call(call_id, Some(answer_for(outcome)), false) + } + + /// The calling plugin withdrew its request with `$/cancelRequest`. + /// Returns `None` when the request names no relayed call. + pub(crate) fn cancel_from_caller( + &mut self, + session_id: &str, + rpc_id: &Value, + ) -> Option> { + let call_id = self + .calls + .values() + .find(|call| call.caller_session == session_id && &call.rpc_id == rpc_id)? + .id; + let cancelled = RelayFailure::new( + codes::HOST_CANCELLED, + "The plugin process cancelled this call.", + ); + Some(self.end_call(call_id, Some(Err(cancelled)), true)) + } + + /// A session stopped or failed. Calls it made end silently, because + /// nobody is left to answer, and their callees are cancelled. Calls it + /// was serving fail for their callers. + pub(crate) fn session_ended(&mut self, session_id: &str) -> Vec { + let made: Vec = self + .calls + .values() + .filter(|call| call.caller_session == session_id) + .map(|call| call.id) + .collect(); + let mut actions = Vec::new(); + for call_id in made { + actions.extend(self.end_call(call_id, None, true)); + } + let served: Vec = self + .calls + .values() + .filter(|call| { + matches!(&call.phase, Phase::Running { session_id: owner, .. } if owner == session_id) + }) + .map(|call| call.id) + .collect(); + for call_id in served { + let ended = RelayFailure::new( + codes::PROVIDER_UNAVAILABLE, + "The plugin's process ended before it answered.", + ); + actions.extend(self.end_call(call_id, Some(Err(ended)), false)); + } + actions + } + + /// A backend of `plugin_id` became ready or registered functions: calls + /// that waited for it are dispatched again. + pub(crate) fn provider_changed(&mut self, plugin_id: &str) -> Vec { + self.calls + .values_mut() + .filter(|call| { + call.callee_plugin == plugin_id && matches!(call.phase, Phase::WaitingForProvider) + }) + .map(|call| { + call.phase = Phase::Dispatching; + RelayAction::Dispatch { call_id: call.id } + }) + .collect() + } + + /// Ends calls that are out of time. A call with no running callee ends at + /// its deadline, or when its provider did not start in time. A running + /// call carries its remaining time to the callee session, whose own + /// timeout normally answers first; the relay ends it only `RUNNING_GRACE` + /// after the deadline, so a callee that never answers cannot leave the + /// call open, and it cancels the callee. + pub(crate) fn expire(&mut self, now: Instant) -> Vec { + let mut due = Vec::new(); + for call in self.calls.values() { + let running = matches!(call.phase, Phase::Running { .. }); + let out_of_time = if running { + call.deadline + RUNNING_GRACE + } else { + call.deadline + }; + if now >= out_of_time { + // Only a running call has a callee to cancel. + due.push(( + call.id, + RelayFailure::new(codes::HOST_TIMEOUT, "The plugin call timed out."), + running, + )); + } else if !running && call.give_up_at.is_some_and(|limit| now >= limit) { + due.push(( + call.id, + RelayFailure::new( + codes::PROVIDER_UNAVAILABLE, + "The plugin did not start in time.", + ), + false, + )); + } + } + let mut actions = Vec::new(); + for (call_id, failure, cancel_callee) in due { + actions.extend(self.end_call(call_id, Some(Err(failure)), cancel_callee)); + } + actions + } + + /// The version the caller declared for `function_id`, or `notDeclared`. + fn declared_version( + &self, + caller_plugin: &str, + function_id: &str, + ) -> Result { + self.plugins + .get(caller_plugin) + .and_then(|plugin| plugin.calls.iter().find(|call| call.id == function_id)) + .map(|call| call.version) + .ok_or_else(|| { + RelayFailure::new( + codes::NOT_DECLARED, + "The plugin did not declare calling this function.", + ) + }) + } + + fn check_context(&self, reference: &Value) -> Result<(), RelayFailure> { + let current = reference + .get("contextID") + .and_then(Value::as_str) + .and_then(|context_id| self.contexts.get(context_id)) + .filter(|context| Some(context.generation) == reference["generation"].as_u64()); + match current { + None => Err(RelayFailure::new( + codes::HOST_CONTEXT_EXPIRED, + "The workspace context is no longer current.", + )), + Some(context) if context.authority == ContextAuthority::Remote => { + Err(RelayFailure::new( + codes::HOST_AUTHORITY_UNSUPPORTED, + "Plugin functions do not run for remote workspaces.", + )) + } + Some(_) => Ok(()), + } + } + + /// The plugin chain and the parent calls of a new call made from + /// `caller_session`, according to what the request said about its parent. + /// + /// A named relayed call must be running in `caller_session`; the new call + /// continues that call's chain and is cancelled with it. A named call that + /// is not running there is refused with `cancelled`. A host operation + /// starts a new chain. When the request names no parent, the parents are + /// every relayed call that session is running: the request does not say + /// which of them caused it, so the chain is their union. That can reject + /// a call that is not really cyclic, never accept one that is. + fn ancestry( + &self, + caller_session: &str, + caller_plugin: &str, + parent: CallParent, + ) -> Result<(Vec, BTreeSet), RelayFailure> { + let not_running = || { + RelayFailure::new( + codes::HOST_CANCELLED, + "The call this request belongs to is not running.", + ) + }; + let served_here = |call: &Call| matches!(&call.phase, Phase::Running { session_id, .. } if session_id == caller_session); + let mut chain: Vec = Vec::new(); + let mut parents = BTreeSet::new(); + match parent { + CallParent::Root => {} + CallParent::Ended => return Err(not_running()), + CallParent::Relay(call_id) => { + let named = self + .calls + .get(&call_id) + .filter(|call| served_here(*call)) + .ok_or_else(not_running)?; + parents.insert(named.id); + chain.extend(named.chain.iter().cloned()); + } + CallParent::Unstated => { + for served in self.calls.values().filter(|call| served_here(*call)) { + parents.insert(served.id); + for plugin in &served.chain { + if !chain.contains(plugin) { + chain.push(plugin.clone()); + } + } + } + } + } + if !chain.iter().any(|plugin| plugin == caller_plugin) { + chain.push(caller_plugin.to_string()); + } + Ok((chain, parents)) + } + + fn running_call(&self, session_id: &str, operation_id: &str) -> Option { + self.calls + .values() + .find(|call| { + matches!( + &call.phase, + Phase::Running { session_id: owner, operation_id: operation } + if owner == session_id && operation == operation_id + ) + }) + .map(|call| call.id) + } + + /// Removes a call, optionally cancelling its callee and answering its + /// caller, then cancels every call that only existed because of it. + fn end_call( + &mut self, + call_id: u64, + reply: Option>, + cancel_callee: bool, + ) -> Vec { + let Some(call) = self.calls.remove(&call_id) else { + return Vec::new(); + }; + let mut actions = Vec::new(); + if let ( + true, + Phase::Running { + session_id, + operation_id, + }, + ) = (cancel_callee, &call.phase) + { + actions.push(RelayAction::CancelCallee { + session_id: session_id.clone(), + operation_id: operation_id.clone(), + }); + } + if let Some(outcome) = reply { + actions.push(RelayAction::Reply { + session_id: call.caller_session, + rpc_id: call.rpc_id, + outcome, + }); + } + actions.extend(self.cancel_orphans_of(call_id)); + actions + } + + /// Cancels the calls whose every parent has ended. The plugin that made + /// them was serving the ended call, so nobody wants their result. + fn cancel_orphans_of(&mut self, ended_call: u64) -> Vec { + let mut orphans = Vec::new(); + for child in self.calls.values_mut() { + if child.parents.remove(&ended_call) && child.parents.is_empty() { + orphans.push(child.id); + } + } + let mut actions = Vec::new(); + for orphan in orphans { + let cancelled = RelayFailure::new( + codes::HOST_CANCELLED, + "The call this request belonged to ended.", + ); + actions.extend(self.end_call(orphan, Some(Err(cancelled)), true)); + } + actions + } + + /// After a new snapshot: calls whose callee left, stopped exporting the + /// function or changed its version end with `providerDisabled`; calls + /// whose caller no longer declares them end with `notDeclared`; calls + /// whose workspace context closed, moved to a new generation or became + /// remote end with the context's failure. + fn end_calls_the_snapshot_forbids(&mut self) -> Vec { + let mut doomed = Vec::new(); + for call in self.calls.values() { + let declared = self.declared_version(&call.caller_plugin, &call.function_id); + let exported_version = self + .plugins + .get(&call.callee_plugin) + .and_then(|plugin| exported(plugin, &call.function_id)) + .map(|export| export.version); + if declared.is_err() { + doomed.push(( + call.id, + RelayFailure::new( + codes::NOT_DECLARED, + "The plugin no longer declares calling this function.", + ), + )); + } else if exported_version.is_none() || exported_version != declared.ok() { + doomed.push(( + call.id, + RelayFailure::new( + codes::PROVIDER_DISABLED, + "The plugin that exports this function changed or was disabled.", + ), + )); + } else if let Err(failure) = self.check_context(&call.context) { + // Workspace contexts change only through `configure`, so + // checking here covers closed contexts and generation bumps. + doomed.push((call.id, failure)); + } + } + let mut actions = Vec::new(); + for (call_id, failure) in doomed { + actions.extend(self.end_call(call_id, Some(Err(failure)), true)); + } + actions + } +} + +fn exported<'a>(plugin: &'a RelayPlugin, function_id: &str) -> Option<&'a RelayExport> { + plugin + .exports + .iter() + .find(|export| export.id == function_id) +} + +/// The answer the calling plugin gets for how the callee's side ended. +fn answer_for(outcome: CalleeOutcome) -> Result { + match outcome { + CalleeOutcome::Succeeded(value) => { + if value.to_string().len() > MAX_RESULT_BYTES { + return Err(RelayFailure::new( + codes::PAYLOAD_TOO_LARGE, + "The function's result exceeds the relay limit.", + )); + } + Ok(json!({ "value": value })) + } + CalleeOutcome::Failed { + code, + message, + plugin_error_code, + } => Err(match code.as_str() { + codes::FAILED => RelayFailure { + code: codes::FAILED, + message, + plugin_error_code, + }, + // No result, or one over the engine's own bound: the provider + // answered, but not with a value Core can pass on. + codes::INVALID_RESULT => RelayFailure { + code: codes::INVALID_RESULT, + message, + plugin_error_code: None, + }, + "requestTimeout" => { + RelayFailure::new(codes::HOST_TIMEOUT, "The plugin call timed out.") + } + // Revoked, cancelled by the callee's own shutdown, or a process + // that exited: the provider cannot finish the call. + _ => RelayFailure::new( + codes::PROVIDER_UNAVAILABLE, + "The plugin stopped before it answered.", + ), + }), + } +} + +/// Rejects a snapshot that is malformed rather than merely restrictive. +fn check_snapshot(snapshot: &RelaySnapshot) -> Result<(), &'static str> { + if snapshot.plugins.len() > MAX_SNAPSHOT_PLUGINS { + return Err("The function-relay snapshot lists too many plugins."); + } + let mut seen = BTreeSet::new(); + for plugin in &snapshot.plugins { + if !is_plugin_id(&plugin.plugin_id) || !seen.insert(plugin.plugin_id.as_str()) { + return Err("A snapshot plugin ID is malformed or listed twice."); + } + let ids_are_valid = plugin + .exports + .iter() + .map(|export| export.id.as_str()) + .chain(plugin.calls.iter().map(|call| call.id.as_str())) + .all(is_function_id); + if !ids_are_valid { + return Err("A snapshot function ID is malformed."); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PYTHON: &str = "dev.lithe.python"; + const GO: &str = "dev.lithe.go"; + const ZIG: &str = "dev.lithe.zig"; + /// A second plugin that calls Go, so Go can serve two callers at once. + const RUBY: &str = "dev.lithe.ruby"; + const FUNCTION: &str = "project.describe"; + + fn plugin(id: &str, exports: &[(&str, u32)], calls: &[(&str, u32)]) -> RelayPlugin { + RelayPlugin { + plugin_id: id.to_string(), + exports: exports + .iter() + .map(|(function, version)| RelayExport { + id: function.to_string(), + version: *version, + context: "workspace".to_string(), + }) + .collect(), + calls: calls + .iter() + .map(|(function, version)| RelayCall { + id: function.to_string(), + version: *version, + }) + .collect(), + } + } + + fn local_context() -> RelayContext { + RelayContext { + context_id: "workspace-1".to_string(), + generation: 3, + authority: ContextAuthority::Local, + } + } + + /// The snapshot of `relay()` with a different set of live contexts. + fn snapshot_with_contexts(contexts: Vec) -> RelaySnapshot { + RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 1)], &[]), + ], + contexts, + } + } + + /// Python calls `project.describe` (version 1), Go exports it. + fn relay() -> FunctionRelay { + let mut relay = FunctionRelay::default(); + relay + .configure(snapshot_with_contexts(vec![local_context()])) + .expect("the snapshot is valid"); + relay + } + + /// Python and Ruby call Go; Go calls Zig, which exports the function too. + /// Go can serve a call from each caller at once and call Zig for both. + fn relay_with_two_callers_of_go() -> FunctionRelay { + let mut relay = FunctionRelay::default(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(RUBY, &[], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 1)], &[(FUNCTION, 1)]), + plugin(ZIG, &[(FUNCTION, 1)], &[]), + ], + contexts: vec![local_context()], + }) + .expect("the snapshot is valid"); + relay + } + + /// Six plugins in a line, each exporting and calling the function, with + /// `MAX_CALL_DEPTH` hops running. Hop `i` (call ID `i + 1`) is plugin `i` + /// calling plugin `i + 1` from `session-i` with RPC ID `i`; the session + /// `session-(i + 1)` serves it. One more hop, made by the last served + /// plugin `names[MAX_CALL_DEPTH]`, would be too deep. + fn relay_with_calls_down_a_line(now: Instant) -> (FunctionRelay, Vec) { + let names: Vec = (1..=6).map(|index| format!("dev.lithe.p{index}")).collect(); + let mut relay = FunctionRelay::default(); + relay + .configure(RelaySnapshot { + plugins: names + .iter() + .map(|name| plugin(name, &[(FUNCTION, 1)], &[(FUNCTION, 1)])) + .collect(), + contexts: vec![local_context()], + }) + .expect("the snapshot is valid"); + for hop in 0..MAX_CALL_DEPTH { + running_call( + &mut relay, + request( + &format!("session-{hop}"), + &names[hop], + &names[hop + 1], + hop as i64, + ), + &format!("session-{}", hop + 1), + now, + ); + } + (relay, names) + } + + fn request(caller_session: &str, caller: &str, callee: &str, rpc_id: i64) -> RelayRequest { + RelayRequest { + caller_session: caller_session.to_string(), + caller_plugin: caller.to_string(), + rpc_id: json!(rpc_id), + callee_plugin: callee.to_string(), + function_id: FUNCTION.to_string(), + params: json!({ "project": "app" }), + context: json!({ "contextID": "workspace-1", "generation": 3 }), + timeout: None, + parent: CallParent::Unstated, + } + } + + /// `request`, made while serving the call `parent` names. + fn request_from( + parent: CallParent, + caller_session: &str, + caller: &str, + callee: &str, + rpc_id: i64, + ) -> RelayRequest { + RelayRequest { + parent, + ..request(caller_session, caller, callee, rpc_id) + } + } + + /// The action that cancels the call `call_id` in its callee session. + fn cancel_of(callee_session: &str, call_id: u64) -> RelayAction { + RelayAction::CancelCallee { + session_id: callee_session.to_string(), + operation_id: format!("{OPERATION_PREFIX}{call_id}"), + } + } + + /// The codes of the failed replies among `actions`, in order. + fn failed_reply_codes(actions: &[RelayAction]) -> Vec<&'static str> { + actions + .iter() + .filter_map(|action| match action { + RelayAction::Reply { + outcome: Err(failure), + .. + } => Some(failure.code), + _ => None, + }) + .collect() + } + + fn admitted_call(relay: &mut FunctionRelay, request: RelayRequest, now: Instant) -> u64 { + match relay + .admit(request, now) + .expect("the call is admitted") + .as_slice() + { + [RelayAction::Dispatch { call_id }] => *call_id, + other => panic!("expected one dispatch, got {other:?}"), + } + } + + fn refusal(relay: &mut FunctionRelay, request: RelayRequest) -> &'static str { + relay + .admit(request, Instant::now()) + .expect_err("the call is refused") + .code + } + + /// Admits a call and records its callee session, like the engine does. + fn running_call( + relay: &mut FunctionRelay, + request: RelayRequest, + callee_session: &str, + now: Instant, + ) -> u64 { + let call_id = admitted_call(relay, request, now); + assert!(relay.started( + call_id, + callee_session, + &format!("{OPERATION_PREFIX}{call_id}") + )); + call_id + } + + #[test] + fn a_declared_exported_call_is_admitted_and_dispatched() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + let plan = relay.dispatch_plan(call_id, now).expect("the call is live"); + assert_eq!(plan.callee_plugin, GO); + assert_eq!(plan.caller_plugin, PYTHON); + assert_eq!(plan.function_id, FUNCTION); + assert_eq!(plan.remaining, DEFAULT_TIMEOUT); + } + + #[test] + fn a_requested_timeout_is_capped() { + let mut relay = relay(); + let now = Instant::now(); + let mut long = request("py", PYTHON, GO, 7); + long.timeout = Some(Duration::from_secs(24 * 3600)); + let call_id = admitted_call(&mut relay, long, now); + assert_eq!( + relay.dispatch_plan(call_id, now).unwrap().remaining, + MAX_TIMEOUT + ); + } + + #[test] + fn discovery_lists_exporters_sorted_with_their_versions() { + let mut relay = relay(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin("dev.lithe.zig", &[(FUNCTION, 2)], &[]), + plugin(GO, &[(FUNCTION, 1)], &[]), + plugin("dev.lithe.rust", &[("other.run", 1)], &[]), + ], + contexts: vec![], + }) + .unwrap(); + assert_eq!( + relay.providers(PYTHON, FUNCTION).unwrap(), + json!({ "providers": [ + { "pluginID": GO, "version": 1 }, + { "pluginID": "dev.lithe.zig", "version": 2 } + ] }) + ); + } + + #[test] + fn discovery_requires_the_caller_to_declare_the_function() { + let relay = relay(); + assert_eq!( + relay.providers(GO, FUNCTION).unwrap_err().code, + codes::NOT_DECLARED + ); + assert_eq!( + relay + .providers("dev.lithe.unknown", FUNCTION) + .unwrap_err() + .code, + codes::NOT_DECLARED + ); + } + + #[test] + fn an_undeclared_call_is_refused_before_anything_about_the_callee() { + let mut relay = relay(); + let mut undeclared = request("go", GO, PYTHON, 1); + undeclared.function_id = "other.run".to_string(); + assert_eq!(refusal(&mut relay, undeclared), codes::NOT_DECLARED); + } + + #[test] + fn a_disabled_provider_is_refused() { + let mut relay = relay(); + assert_eq!( + refusal(&mut relay, request("py", PYTHON, "dev.lithe.gone", 1)), + codes::PROVIDER_DISABLED + ); + } + + #[test] + fn a_function_the_provider_does_not_export_is_refused() { + let mut relay = relay(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(GO, &[("other.run", 1)], &[]), + ], + contexts: vec![local_context()], + }) + .unwrap(); + assert_eq!( + refusal(&mut relay, request("py", PYTHON, GO, 1)), + codes::NOT_EXPORTED + ); + } + + #[test] + fn an_export_with_an_unknown_context_is_not_callable() { + let mut relay = relay(); + let mut provider = plugin(GO, &[(FUNCTION, 1)], &[]); + provider.exports[0].context = "everywhere".to_string(); + relay + .configure(RelaySnapshot { + plugins: vec![plugin(PYTHON, &[], &[(FUNCTION, 1)]), provider], + contexts: vec![local_context()], + }) + .unwrap(); + assert_eq!( + refusal(&mut relay, request("py", PYTHON, GO, 1)), + codes::NOT_EXPORTED + ); + } + + #[test] + fn different_contract_versions_are_refused() { + let mut relay = relay(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 2)], &[]), + ], + contexts: vec![local_context()], + }) + .unwrap(); + assert_eq!( + refusal(&mut relay, request("py", PYTHON, GO, 1)), + codes::VERSION_MISMATCH + ); + } + + #[test] + fn a_stale_or_unknown_context_is_refused() { + let mut relay = relay(); + let mut stale = request("py", PYTHON, GO, 1); + stale.context = json!({ "contextID": "workspace-1", "generation": 2 }); + assert_eq!(refusal(&mut relay, stale), codes::HOST_CONTEXT_EXPIRED); + let mut unknown = request("py", PYTHON, GO, 2); + unknown.context = json!({ "contextID": "workspace-9", "generation": 3 }); + assert_eq!(refusal(&mut relay, unknown), codes::HOST_CONTEXT_EXPIRED); + } + + #[test] + fn a_remote_workspace_is_refused() { + let mut relay = relay(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 1)], &[]), + ], + contexts: vec![RelayContext { + authority: ContextAuthority::Remote, + ..local_context() + }], + }) + .unwrap(); + assert_eq!( + refusal(&mut relay, request("py", PYTHON, GO, 1)), + codes::HOST_AUTHORITY_UNSUPPORTED + ); + } + + #[test] + fn oversized_params_are_refused() { + let mut relay = relay(); + let mut big = request("py", PYTHON, GO, 1); + big.params = json!({ "text": "x".repeat(MAX_PARAMS_BYTES) }); + assert_eq!(refusal(&mut relay, big), codes::PAYLOAD_TOO_LARGE); + } + + #[test] + fn a_plugin_cannot_call_itself() { + let mut relay = relay(); + relay + .configure(RelaySnapshot { + plugins: vec![plugin(GO, &[(FUNCTION, 1)], &[(FUNCTION, 1)])], + contexts: vec![local_context()], + }) + .unwrap(); + assert_eq!( + refusal(&mut relay, request("go", GO, GO, 1)), + codes::CALL_CYCLE + ); + } + + /// Python calls Go; while Go serves that call it calls Python back. + #[test] + fn a_call_back_into_the_chain_is_a_cycle() { + let mut relay = FunctionRelay::default(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[(FUNCTION, 1)], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 1)], &[(FUNCTION, 1)]), + ], + contexts: vec![local_context()], + }) + .unwrap(); + let now = Instant::now(); + running_call(&mut relay, request("py", PYTHON, GO, 1), "go-session", now); + assert_eq!( + refusal(&mut relay, request("go-session", GO, PYTHON, 2)), + codes::CALL_CYCLE + ); + } + + /// Six plugins in a line, each calling the next: the fifth hop is one too + /// many. + #[test] + fn nesting_is_limited() { + let (mut relay, names) = relay_with_calls_down_a_line(Instant::now()); + let last = MAX_CALL_DEPTH; + assert_eq!( + refusal( + &mut relay, + request( + &format!("session-{last}"), + &names[last], + &names[last + 1], + 99 + ) + ), + codes::DEPTH_EXCEEDED + ); + } + + /// A call made while serving a host operation starts a new chain, so the + /// calls the session is serving for other plugins neither make it a cycle + /// nor make it too deep, and ending them does not cancel it. + #[test] + fn a_call_made_for_a_host_operation_starts_a_new_chain() { + let now = Instant::now(); + let (mut relay, names) = relay_with_calls_down_a_line(now); + let last = MAX_CALL_DEPTH; + let last_session = format!("session-{last}"); + + // With no named parent this is the depth error of `nesting_is_limited`. + let deeper = running_call( + &mut relay, + request_from( + CallParent::Root, + &last_session, + &names[last], + &names[last + 1], + 98, + ), + "session-deeper", + now, + ); + assert_eq!(relay.calls[&deeper].chain, [names[last].as_str()]); + assert!(relay.calls[&deeper].parents.is_empty()); + + // With no named parent this would re-enter the first plugin: a cycle. + let back = running_call( + &mut relay, + request_from(CallParent::Root, &last_session, &names[last], &names[0], 99), + "session-back", + now, + ); + assert_eq!(relay.calls[&back].chain, [names[last].as_str()]); + + // Ending the first hop (call 1) of the line cancels the hops made + // while serving it (call 4 is the last), but not the two calls that + // started their own chain. + let actions = relay.cancel_from_caller("session-0", &json!(0)).unwrap(); + assert!(actions.contains(&cancel_of("session-1", 1))); + assert!(actions.contains(&cancel_of("session-4", 4))); + assert!(!actions.contains(&cancel_of("session-deeper", deeper))); + assert!(!actions.contains(&cancel_of("session-back", back))); + assert!(relay.is_running(deeper)); + assert!(relay.is_running(back)); + } + + #[test] + fn a_caller_has_a_limited_number_of_calls_in_flight() { + let mut relay = relay(); + let now = Instant::now(); + for rpc_id in 0..MAX_CALLS_PER_CALLER { + admitted_call(&mut relay, request("py", PYTHON, GO, rpc_id as i64), now); + } + assert_eq!( + refusal(&mut relay, request("py-2", PYTHON, GO, 100)), + codes::TOO_MANY_CALLS + ); + } + + #[test] + fn a_finished_call_frees_its_slot() { + let mut relay = relay(); + let now = Instant::now(); + let mut calls = Vec::new(); + for rpc_id in 0..MAX_CALLS_PER_CALLER { + calls.push(running_call( + &mut relay, + request("py", PYTHON, GO, rpc_id as i64), + "go", + now, + )); + } + relay.callee_finished( + "go", + &format!("{OPERATION_PREFIX}{}", calls[0]), + CalleeOutcome::Succeeded(json!(1)), + ); + admitted_call(&mut relay, request("py", PYTHON, GO, 100), now); + } + + #[test] + fn a_result_is_wrapped_for_the_caller() { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay.callee_finished( + "go", + &format!("{OPERATION_PREFIX}{call_id}"), + CalleeOutcome::Succeeded(json!({ "name": "app" })), + ); + assert_eq!( + actions, + vec![RelayAction::Reply { + session_id: "py".to_string(), + rpc_id: json!(7), + outcome: Ok(json!({ "value": { "name": "app" } })), + }] + ); + } + + #[test] + fn an_oversized_result_is_refused() { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay.callee_finished( + "go", + &format!("{OPERATION_PREFIX}{call_id}"), + CalleeOutcome::Succeeded(json!("x".repeat(MAX_RESULT_BYTES))), + ); + match actions.as_slice() { + [RelayAction::Reply { + outcome: Err(failure), + .. + }] => { + assert_eq!(failure.code, codes::PAYLOAD_TOO_LARGE) + } + other => panic!("expected one failed reply, got {other:?}"), + } + } + + #[test] + fn callee_failures_map_to_distinct_codes() { + let cases = [ + ("plugin.function.failed", codes::FAILED), + ("plugin.function.invalidResult", codes::INVALID_RESULT), + ("requestTimeout", codes::HOST_TIMEOUT), + ("plugin.function.revoked", codes::PROVIDER_UNAVAILABLE), + ("requestCancelled", codes::PROVIDER_UNAVAILABLE), + ("serverExited", codes::PROVIDER_UNAVAILABLE), + ]; + for (engine_code, expected) in cases { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay.callee_finished( + "go", + &format!("{OPERATION_PREFIX}{call_id}"), + CalleeOutcome::Failed { + code: engine_code.to_string(), + message: "no".to_string(), + plugin_error_code: Some("go.locked".to_string()), + }, + ); + match actions.as_slice() { + [RelayAction::Reply { + outcome: Err(failure), + .. + }] => { + assert_eq!(failure.code, expected, "{engine_code}") + } + other => panic!("expected one failed reply, got {other:?}"), + } + } + } + + #[test] + fn a_failed_function_keeps_its_message_and_plugin_code() { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay.callee_finished( + "go", + &format!("{OPERATION_PREFIX}{call_id}"), + CalleeOutcome::Failed { + code: codes::FAILED.to_string(), + message: "Index is locked.".to_string(), + plugin_error_code: Some("go.locked".to_string()), + }, + ); + match actions.as_slice() { + [RelayAction::Reply { + outcome: Err(failure), + .. + }] => { + assert_eq!(failure.message, "Index is locked."); + assert_eq!(failure.plugin_error_code.as_deref(), Some("go.locked")); + } + other => panic!("expected one failed reply, got {other:?}"), + } + } + + #[test] + fn an_unrelated_finish_changes_nothing() { + let mut relay = relay(); + running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = + relay.callee_finished("go", "lsp-operation-1", CalleeOutcome::Succeeded(json!(1))); + assert!(actions.is_empty()); + } + + #[test] + fn the_caller_cancelling_cancels_the_callee_and_is_answered() { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay + .cancel_from_caller("py", &json!(7)) + .expect("the request names a relayed call"); + assert_eq!( + actions[0], + RelayAction::CancelCallee { + session_id: "go".to_string(), + operation_id: format!("{OPERATION_PREFIX}{call_id}"), + } + ); + match &actions[1] { + RelayAction::Reply { + outcome: Err(failure), + .. + } => { + assert_eq!(failure.code, codes::HOST_CANCELLED) + } + other => panic!("expected a cancelled reply, got {other:?}"), + } + assert!(relay.cancel_from_caller("py", &json!(7)).is_none()); + } + + #[test] + fn a_cancelled_call_cancels_the_calls_made_while_serving_it() { + let mut relay = FunctionRelay::default(); + relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 1)], &[(FUNCTION, 1)]), + plugin("dev.lithe.zig", &[(FUNCTION, 1)], &[]), + ], + contexts: vec![local_context()], + }) + .unwrap(); + let now = Instant::now(); + let parent = running_call(&mut relay, request("py", PYTHON, GO, 1), "go", now); + let child = running_call( + &mut relay, + request("go", GO, "dev.lithe.zig", 2), + "zig", + now, + ); + let actions = relay.cancel_from_caller("py", &json!(1)).unwrap(); + assert!(actions.contains(&RelayAction::CancelCallee { + session_id: "go".to_string(), + operation_id: format!("{OPERATION_PREFIX}{parent}"), + })); + assert!(actions.contains(&RelayAction::CancelCallee { + session_id: "zig".to_string(), + operation_id: format!("{OPERATION_PREFIX}{child}"), + })); + // Both ends were answered once. + let replies = actions + .iter() + .filter(|action| matches!(action, RelayAction::Reply { .. })) + .count(); + assert_eq!(replies, 2); + } + + /// Go serves a call from Python and one from Ruby at once and calls Zig + /// while serving each. Because each request names its parent, ending the + /// Python call must not cancel the Zig call made for the Ruby call. + #[test] + fn a_named_parent_scopes_the_chain_and_the_cancellation_to_that_call() { + let mut relay = relay_with_two_callers_of_go(); + let now = Instant::now(); + let from_python = running_call(&mut relay, request("py", PYTHON, GO, 1), "go", now); + let from_ruby = running_call(&mut relay, request("rb", RUBY, GO, 2), "go", now); + let zig_for_python = running_call( + &mut relay, + request_from(CallParent::Relay(from_python), "go", GO, ZIG, 3), + "zig-1", + now, + ); + let zig_for_ruby = running_call( + &mut relay, + request_from(CallParent::Relay(from_ruby), "go", GO, ZIG, 4), + "zig-2", + now, + ); + + // Each chain is the named call's chain plus the caller, nothing from + // the sibling call. + assert_eq!(relay.calls[&zig_for_python].chain, [PYTHON, GO]); + assert_eq!( + relay.calls[&zig_for_python].parents, + BTreeSet::from([from_python]) + ); + assert_eq!(relay.calls[&zig_for_ruby].chain, [RUBY, GO]); + assert_eq!( + relay.calls[&zig_for_ruby].parents, + BTreeSet::from([from_ruby]) + ); + + let actions = relay.cancel_from_caller("py", &json!(1)).unwrap(); + assert!(actions.contains(&cancel_of("go", from_python))); + assert!(actions.contains(&cancel_of("zig-1", zig_for_python))); + assert!(!actions.contains(&cancel_of("zig-2", zig_for_ruby))); + // Python and Go were each answered once; Ruby's side saw nothing. + assert_eq!( + failed_reply_codes(&actions), + [codes::HOST_CANCELLED, codes::HOST_CANCELLED] + ); + assert!(relay.is_running(from_ruby)); + assert!(relay.is_running(zig_for_ruby)); + assert!(!relay.is_running(zig_for_python)); + } + + /// Without a named parent a call belongs to every call its session serves, + /// so it ends only when all of them have ended. + #[test] + fn a_request_naming_no_parent_belongs_to_every_call_its_session_serves() { + let mut relay = relay_with_two_callers_of_go(); + let now = Instant::now(); + let from_python = running_call(&mut relay, request("py", PYTHON, GO, 1), "go", now); + let from_ruby = running_call(&mut relay, request("rb", RUBY, GO, 2), "go", now); + let zig = running_call(&mut relay, request("go", GO, ZIG, 3), "zig", now); + + assert_eq!(relay.calls[&zig].chain, [PYTHON, RUBY, GO]); + assert_eq!( + relay.calls[&zig].parents, + BTreeSet::from([from_python, from_ruby]) + ); + let first = relay.cancel_from_caller("py", &json!(1)).unwrap(); + assert!(!first.contains(&cancel_of("zig", zig))); + let second = relay.cancel_from_caller("rb", &json!(2)).unwrap(); + assert!(second.contains(&cancel_of("zig", zig))); + } + + /// A parent the caller's session is not running can no longer be what the + /// request belongs to: the request is refused instead of being tied to + /// some other call. + #[test] + fn a_parent_that_is_not_running_in_the_callers_session_is_refused() { + let mut relay = relay_with_two_callers_of_go(); + let now = Instant::now(); + let waiting = admitted_call(&mut relay, request("py", PYTHON, GO, 1), now); + relay.wait_for_provider(waiting, now); + let served = running_call(&mut relay, request("rb", RUBY, GO, 2), "go", now); + + let ended = request_from(CallParent::Ended, "go", GO, ZIG, 3); + assert_eq!(refusal(&mut relay, ended), codes::HOST_CANCELLED); + let unknown = request_from(CallParent::Relay(99), "go", GO, ZIG, 4); + assert_eq!(refusal(&mut relay, unknown), codes::HOST_CANCELLED); + // The call is served by the session "go", not by another session of Go. + let elsewhere = request_from(CallParent::Relay(served), "go-2", GO, ZIG, 5); + assert_eq!(refusal(&mut relay, elsewhere), codes::HOST_CANCELLED); + // No session serves a call that still waits for its provider. + let not_started = request_from(CallParent::Relay(waiting), "go", GO, ZIG, 6); + assert_eq!(refusal(&mut relay, not_started), codes::HOST_CANCELLED); + // Refused requests leave no call behind. + assert_eq!(relay.calls.len(), 2); + + // The same request from the session that serves the call is admitted. + admitted_call( + &mut relay, + request_from(CallParent::Relay(served), "go", GO, ZIG, 7), + now, + ); + } + + #[test] + fn a_caller_session_ending_cancels_its_callee_without_a_reply() { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay.session_ended("py"); + assert_eq!( + actions, + vec![RelayAction::CancelCallee { + session_id: "go".to_string(), + operation_id: format!("{OPERATION_PREFIX}{call_id}"), + }] + ); + } + + #[test] + fn a_callee_session_ending_fails_the_call_for_its_caller() { + let mut relay = relay(); + running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay.session_ended("go"); + match actions.as_slice() { + [RelayAction::Reply { + session_id, + outcome: Err(failure), + .. + }] => { + assert_eq!(session_id, "py"); + assert_eq!(failure.code, codes::PROVIDER_UNAVAILABLE); + } + other => panic!("expected one failed reply, got {other:?}"), + } + } + + #[test] + fn a_call_waits_for_a_provider_and_is_dispatched_when_one_appears() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + let notice = relay + .wait_for_provider(call_id, now) + .expect("first wait asks for a start"); + assert_eq!(notice.caller_session, "py"); + assert_eq!(notice.callee_plugin, GO); + assert!(relay.wait_for_provider(call_id, now).is_none()); + assert!(relay.provider_changed("dev.lithe.other").is_empty()); + assert_eq!( + relay.provider_changed(GO), + vec![RelayAction::Dispatch { call_id }] + ); + } + + #[test] + fn a_provider_that_never_starts_ends_the_call() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + relay.wait_for_provider(call_id, now); + assert!(relay + .expire(now + PROVIDER_START_TIMEOUT - Duration::from_secs(1)) + .is_empty()); + match relay.expire(now + PROVIDER_START_TIMEOUT).as_slice() { + [RelayAction::Reply { + outcome: Err(failure), + .. + }] => { + assert_eq!(failure.code, codes::PROVIDER_UNAVAILABLE) + } + other => panic!("expected one failed reply, got {other:?}"), + } + } + + #[test] + fn retrying_a_wait_does_not_extend_it() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + relay.wait_for_provider(call_id, now); + relay.provider_changed(GO); + relay.wait_for_provider(call_id, now + Duration::from_secs(20)); + assert_eq!(relay.expire(now + PROVIDER_START_TIMEOUT).len(), 1); + } + + #[test] + fn a_call_out_of_time_before_it_started_times_out() { + let mut relay = relay(); + let now = Instant::now(); + let mut short = request("py", PYTHON, GO, 7); + short.timeout = Some(Duration::from_secs(10)); + let call_id = admitted_call(&mut relay, short, now); + relay.wait_for_provider(call_id, now); + assert!(relay.expire(now + Duration::from_secs(9)).is_empty()); + match relay.expire(now + Duration::from_secs(10)).as_slice() { + [RelayAction::Reply { + outcome: Err(failure), + .. + }] => { + assert_eq!(failure.code, codes::HOST_TIMEOUT) + } + other => panic!("expected one failed reply, got {other:?}"), + } + } + + /// The callee session enforces the same deadline and answers with its own + /// timeout, so the relay must not end a running call before `RUNNING_GRACE` + /// after the deadline has passed. + #[test] + fn a_running_call_is_left_to_its_session_until_the_grace_ends() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = running_call(&mut relay, request("py", PYTHON, GO, 7), "go", now); + let deadline = now + DEFAULT_TIMEOUT; + assert!(relay.expire(deadline - Duration::from_secs(1)).is_empty()); + assert!(relay.expire(deadline).is_empty()); + assert!(relay + .expire(deadline + RUNNING_GRACE - Duration::from_millis(1)) + .is_empty()); + assert!(relay.is_running(call_id)); + } + + /// A callee that never answers, even with its own timeout, must not leave + /// the call open: the relay ends it and cancels the callee. + #[test] + fn a_running_call_whose_callee_never_answers_times_out_after_the_grace() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = running_call(&mut relay, request("py", PYTHON, GO, 7), "go", now); + let actions = relay.expire(now + DEFAULT_TIMEOUT + RUNNING_GRACE); + assert_eq!(actions.len(), 2); + assert_eq!(actions[0], cancel_of("go", call_id)); + assert_eq!(failed_reply_codes(&actions), [codes::HOST_TIMEOUT]); + assert!(!relay.is_running(call_id)); + // The call is gone, so a later sweep has nothing left to end. + assert!(relay.expire(now + MAX_TIMEOUT).is_empty()); + } + + /// The provider-start limit only applies while the call waits for a + /// backend; once the callee runs it, that older limit must not end it. + #[test] + fn a_call_that_waited_for_its_provider_is_not_ended_by_that_wait_once_running() { + let mut relay = relay(); + let now = Instant::now(); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + relay.wait_for_provider(call_id, now); + assert!(relay.started(call_id, "go", &format!("{OPERATION_PREFIX}{call_id}"))); + assert!(relay.expire(now + PROVIDER_START_TIMEOUT).is_empty()); + assert!(relay.is_running(call_id)); + } + + #[test] + fn a_call_is_running_only_while_its_callee_session_has_it() { + let mut relay = relay(); + let now = Instant::now(); + assert!(!relay.is_running(1)); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + assert!(!relay.is_running(call_id)); + relay.wait_for_provider(call_id, now); + assert!(!relay.is_running(call_id)); + let operation_id = format!("{OPERATION_PREFIX}{call_id}"); + assert!(relay.started(call_id, "go", &operation_id)); + assert!(relay.is_running(call_id)); + relay.callee_finished("go", &operation_id, CalleeOutcome::Succeeded(json!(1))); + assert!(!relay.is_running(call_id)); + } + + #[test] + fn disabling_the_provider_ends_calls_in_flight() { + let mut relay = relay(); + let call_id = running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay + .configure(RelaySnapshot { + plugins: vec![plugin(PYTHON, &[], &[(FUNCTION, 1)])], + contexts: vec![local_context()], + }) + .unwrap(); + assert!(actions.contains(&RelayAction::CancelCallee { + session_id: "go".to_string(), + operation_id: format!("{OPERATION_PREFIX}{call_id}"), + })); + match actions.last() { + Some(RelayAction::Reply { + outcome: Err(failure), + .. + }) => { + assert_eq!(failure.code, codes::PROVIDER_DISABLED) + } + other => panic!("expected a failed reply, got {other:?}"), + } + } + + #[test] + fn a_caller_that_stops_declaring_ends_its_calls() { + let mut relay = relay(); + running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay + .configure(RelaySnapshot { + plugins: vec![plugin(PYTHON, &[], &[]), plugin(GO, &[(FUNCTION, 1)], &[])], + contexts: vec![local_context()], + }) + .unwrap(); + match actions.last() { + Some(RelayAction::Reply { + outcome: Err(failure), + .. + }) => { + assert_eq!(failure.code, codes::NOT_DECLARED) + } + other => panic!("expected a failed reply, got {other:?}"), + } + } + + #[test] + fn an_unchanged_snapshot_keeps_calls_running() { + let mut relay = relay(); + running_call( + &mut relay, + request("py", PYTHON, GO, 7), + "go", + Instant::now(), + ); + let actions = relay + .configure(RelaySnapshot { + plugins: vec![ + plugin(PYTHON, &[], &[(FUNCTION, 1)]), + plugin(GO, &[(FUNCTION, 1)], &[]), + ], + contexts: vec![local_context()], + }) + .unwrap(); + assert!(actions.is_empty()); + } + + /// A snapshot that drops a workspace context, or replaces it with a newer + /// generation, ends the calls made in it even while they wait for a + /// backend, so they cannot be dispatched into a context that is gone. + #[test] + fn a_waiting_call_ends_when_its_context_closes_or_changes_generation() { + let new_contexts = [ + ("closed", vec![]), + ( + "new generation", + vec![RelayContext { + generation: 4, + ..local_context() + }], + ), + ]; + for (label, contexts) in new_contexts { + let mut relay = relay(); + let now = Instant::now(); + let call_id = admitted_call(&mut relay, request("py", PYTHON, GO, 7), now); + relay.wait_for_provider(call_id, now); + let actions = relay.configure(snapshot_with_contexts(contexts)).unwrap(); + // The callee never had the call, so there is nothing to cancel. + assert_eq!(actions.len(), 1, "{label}"); + assert_eq!( + failed_reply_codes(&actions), + [codes::HOST_CONTEXT_EXPIRED], + "{label}" + ); + assert!(relay.dispatch_plan(call_id, now).is_none(), "{label}"); + assert!(relay.provider_changed(GO).is_empty(), "{label}"); + } + } + + /// The same snapshot also stops a call its callee is already running. + #[test] + fn a_running_call_ends_when_its_context_closes_or_changes_generation() { + let new_contexts = [ + ("closed", vec![]), + ( + "new generation", + vec![RelayContext { + generation: 4, + ..local_context() + }], + ), + ]; + for (label, contexts) in new_contexts { + let mut relay = relay(); + let now = Instant::now(); + let call_id = running_call(&mut relay, request("py", PYTHON, GO, 7), "go", now); + let actions = relay.configure(snapshot_with_contexts(contexts)).unwrap(); + assert_eq!(actions.len(), 2, "{label}"); + assert_eq!(actions[0], cancel_of("go", call_id), "{label}"); + assert_eq!( + failed_reply_codes(&actions), + [codes::HOST_CONTEXT_EXPIRED], + "{label}" + ); + assert!(!relay.is_running(call_id), "{label}"); + } + } + + #[test] + fn a_malformed_snapshot_is_rejected_and_changes_nothing() { + let mut relay = relay(); + let duplicate = RelaySnapshot { + plugins: vec![plugin(GO, &[], &[]), plugin(GO, &[], &[])], + contexts: vec![], + }; + assert!(relay.configure(duplicate).is_err()); + let bad_function = RelaySnapshot { + plugins: vec![plugin(GO, &[("Not A Function", 1)], &[])], + contexts: vec![], + }; + assert!(relay.configure(bad_function).is_err()); + // The earlier snapshot still stands. + assert!(relay.providers(PYTHON, FUNCTION).is_ok()); + } +} diff --git a/rust/lithe-core/src/lsp/interface/mod.rs b/rust/lithe-core/src/lsp/interface/mod.rs index 5d7e297940..93ddd99f41 100644 --- a/rust/lithe-core/src/lsp/interface/mod.rs +++ b/rust/lithe-core/src/lsp/interface/mod.rs @@ -5,6 +5,7 @@ mod client; mod document_uri; mod engine; mod engine_logging; +mod function_relay; mod keymap_provider; pub(crate) mod plugin_function; mod plugin_logging; @@ -23,5 +24,6 @@ pub(crate) use document_uri::{ }; pub(crate) use engine::*; pub(crate) use engine_logging::{resolve_engine_log_subject, ResolveEngineLogSubjectRequest}; +pub(crate) use function_relay::RelaySnapshot; pub(crate) use transport::*; pub(crate) use types::*; diff --git a/rust/lithe-core/src/lsp/interface/plugin_function.rs b/rust/lithe-core/src/lsp/interface/plugin_function.rs index f80c177344..57a31f428f 100644 --- a/rust/lithe-core/src/lsp/interface/plugin_function.rs +++ b/rust/lithe-core/src/lsp/interface/plugin_function.rs @@ -25,12 +25,17 @@ const EXPERIMENTAL_KEY: &str = "litheFunctions"; /// Version 3 keeps version 2 and adds `lithe/host/getCapabilities`, /// subscription disposal, workspace contexts, a workspace context on /// invocations, and typed host failure codes. -const SUPPORTED_VERSIONS: [u64; 3] = [1, 2, 3]; +/// Version 4 keeps version 3 and adds the cross-plugin function relay +/// (`lithe/host/functions/*`) and the Core-written `caller` of an invocation. +const SUPPORTED_VERSIONS: [u64; 4] = [1, 2, 3, 4]; /// First protocol version that offers host services. const HOST_SERVICES_VERSION: u64 = 2; /// First protocol version whose invocations may carry a workspace context /// and whose host offers capability discovery and workspace contexts. pub(crate) const CONTEXT_VERSION: u64 = 3; +/// First protocol version whose backend may call the functions other plugins +/// export, and whose invocations carry the Core-written `caller`. +pub(crate) const RELAY_VERSION: u64 = 4; /// Feature name recorded in the session's server capabilities once a backend /// answered a supported version with a valid function list. @@ -70,10 +75,18 @@ const HOST_SERVICE_HOST: &str = "host"; /// of version 3 has it, because only the session that holds a subscription /// can name it. const HOST_SERVICE_SUBSCRIPTIONS: &str = "subscriptions"; +/// Calls into the functions other plugins export. The grant comes from the +/// manifest's `requires.pluginFunctions.calls`, not from a permission: the +/// caller's declaration plus the provider's `exports` is the consent, and +/// Core's relay checks both on every call. +pub(crate) const HOST_SERVICE_FUNCTIONS: &str = "functions"; /// Legacy aggregate grants. New methods are granted individually so adding a /// method to `workspace` or `editor` never widens an existing permission. -pub(crate) const GRANTABLE_HOST_SERVICES: &[&str] = - &[HOST_SERVICE_CREDENTIALS, HOST_SERVICE_WORKSPACE]; +pub(crate) const GRANTABLE_HOST_SERVICES: &[&str] = &[ + HOST_SERVICE_CREDENTIALS, + HOST_SERVICE_WORKSPACE, + HOST_SERVICE_FUNCTIONS, +]; /// Whether a launch grant names an implemented legacy service or host method. pub(crate) fn is_host_grant(grant: &str) -> bool { @@ -118,6 +131,10 @@ const SUBSCRIPTIONS_DISPOSE: &str = "lithe/host/subscriptions/dispose"; const WORKSPACE_LIST_CONTEXTS: &str = "lithe/host/workspace/listContexts"; const WORKSPACE_GET_CONTEXT: &str = "lithe/host/workspace/getContext"; const WORKSPACE_GET_FOLDERS: &str = "lithe/host/workspace/getFolders"; +/// Backend request listing the plugins that export a function it may call. +pub(crate) const FUNCTIONS_PROVIDERS: &str = "lithe/host/functions/providers"; +/// Backend request calling a function another plugin exports. +pub(crate) const FUNCTIONS_INVOKE: &str = "lithe/host/functions/invoke"; const MAX_CREDENTIAL_KEY_BYTES: usize = 128; /// Bound of one stored secret, in UTF-8 bytes; enough for a password, a /// token, or a private key, not for documents. @@ -205,6 +222,34 @@ pub(crate) mod codes { /// A page's call or a host operation ended because the backend process /// exited. Reported by hosts to pages, never sent to a backend. pub const BACKEND_EXITED: &str = "plugin.backend.exited"; + + // Cross-plugin relay (`lithe/host/functions/*`, protocol version 4). Each + // refusal has its own code and number, so a caller can branch on either. + + /// The caller's manifest does not declare a call to this function. + pub const NOT_DECLARED: &str = "plugin.function.notDeclared"; + /// The plugin that should provide the function does not export it, or + /// has not registered it with its running backend. + pub const NOT_EXPORTED: &str = "plugin.function.notExported"; + /// The providing plugin is not installed or not enabled, or was disabled + /// or removed while the call was running. + pub const PROVIDER_DISABLED: &str = "plugin.function.providerDisabled"; + /// The caller declared another contract version than the provider exports. + pub const VERSION_MISMATCH: &str = "plugin.function.versionMismatch"; + /// The provider is already on the call chain, so the call would come + /// back to a plugin that is waiting for it (including a plugin calling + /// itself). + pub const CALL_CYCLE: &str = "plugin.function.callCycle"; + /// The call chain is longer than the depth limit. + pub const DEPTH_EXCEEDED: &str = "plugin.function.depthExceeded"; + /// The calling plugin already has the most relayed calls it may have + /// running at once. + pub const TOO_MANY_CALLS: &str = "plugin.function.tooManyCalls"; + /// The relayed params or result exceed the relay's byte limit. + pub const PAYLOAD_TOO_LARGE: &str = "plugin.function.payloadTooLarge"; + /// The provider's backend could not serve the call: it did not start in + /// time, exited, or withdrew the function while the call ran. + pub const PROVIDER_UNAVAILABLE: &str = "plugin.function.providerUnavailable"; } #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] @@ -464,6 +509,10 @@ pub(crate) enum HostRoute { Forward(&'static str), /// Answered by Core with this result; the host never sees the request. Answer(Value), + /// Another plugin's function: Core's relay checks, dispatches, and + /// answers it. The host sees only the start request for a provider whose + /// backend is not running. + Relay, } /// How Core checks the params of one host method before the host sees them. @@ -479,6 +528,10 @@ pub(crate) enum HostParams { Context, /// Snapshot source listing or one bounded chunk from a selected source. KeymapSnapshot { chunk: bool }, + /// Exactly `{ functionID }`, a well-formed function ID. + FunctionProviders, + /// `{ pluginID, functionID, context, params?, timeoutMilliseconds? }`. + FunctionInvoke, /// Any object whose `context`, when present, is a well-formed /// reference. The service checks the rest and answers /// `plugin.host.invalidParams` or, for a field it does not know, @@ -507,6 +560,20 @@ pub(crate) struct HostMethod { /// service adds its rows here, its grant to `GRANTABLE_HOST_SERVICES` and /// the manifest permission, and its handler to the host's dispatcher. pub(crate) const HOST_METHODS: &[HostMethod] = &[ + HostMethod { + method: FUNCTIONS_PROVIDERS, + service: HOST_SERVICE_FUNCTIONS, + permission: None, + since: RELAY_VERSION, + params: HostParams::FunctionProviders, + }, + HostMethod { + method: FUNCTIONS_INVOKE, + service: HOST_SERVICE_FUNCTIONS, + permission: None, + since: RELAY_VERSION, + params: HostParams::FunctionInvoke, + }, HostMethod { method: "lithe/host/keymapImport/listInputs", service: "keymapImport", @@ -841,6 +908,9 @@ pub(crate) fn host_request( if entry.method == GET_CAPABILITIES { return Ok(HostRoute::Answer(capabilities_answer(version, granted))); } + if entry.service == HOST_SERVICE_FUNCTIONS { + return Ok(HostRoute::Relay); + } Ok(HostRoute::Forward(entry.service)) } @@ -1062,6 +1132,15 @@ fn check_host_params( HostParams::Credential { with_secret: false } => &["key"], HostParams::Subscription => &["subscriptionID"], HostParams::Context => &["context"], + HostParams::FunctionProviders => &["functionID"], + HostParams::FunctionInvoke => &[ + "pluginID", + "functionID", + "context", + "params", + "timeoutMilliseconds", + "parentOperationID", + ], HostParams::KeymapSnapshot { chunk: false } => &["snapshotID", "providerID"], HostParams::KeymapSnapshot { chunk: true } => &[ "snapshotID", @@ -1127,6 +1206,16 @@ fn check_host_params( return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); } } + HostParams::FunctionProviders => { + if !params + .get("functionID") + .and_then(Value::as_str) + .is_some_and(is_function_id) + { + return Err(invalid(FUNCTION_ID_MESSAGE)); + } + } + HostParams::FunctionInvoke => check_function_invoke_params(params)?, HostParams::KeymapSnapshot { chunk } => { let opaque_id = |key: &str| { params.get(key).and_then(Value::as_str).is_some_and(|id| { @@ -1168,6 +1257,63 @@ fn check_host_params( Ok(()) } +const FUNCTION_ID_MESSAGE: &str = + "A function ID is dot-separated lowerCamelCase segments of at most 128 bytes."; + +/// The shape of a `lithe/host/functions/invoke` request. Whether the caller +/// declared the call and the provider exports it is the relay's check, which +/// needs the plugin snapshot. +fn check_function_invoke_params( + params: &serde_json::Map, +) -> Result<(), HostRequestRefusal> { + let invalid = |message| HostRequestRefusal { + rpc_code: -32602, + code: codes::HOST_INVALID_PARAMS, + message, + details: None, + }; + if !params + .get("pluginID") + .and_then(Value::as_str) + .is_some_and(is_plugin_id) + { + return Err(invalid( + "A plugin ID is lowercase letters, digits, '.' and '-'.", + )); + } + if !params + .get("functionID") + .and_then(Value::as_str) + .is_some_and(is_function_id) + { + return Err(invalid(FUNCTION_ID_MESSAGE)); + } + if !params.get("context").is_some_and(is_context_reference) { + return Err(invalid(CONTEXT_REFERENCE_MESSAGE)); + } + if params.get("params").is_some_and(|value| !value.is_object()) { + return Err(invalid("Function params must be a JSON object.")); + } + if params + .get("timeoutMilliseconds") + .is_some_and(|value| !value.as_u64().is_some_and(|milliseconds| milliseconds >= 1)) + { + return Err(invalid("A timeout is a positive number of milliseconds.")); + } + // Only the shape is checked here. Whether the ID names a call this backend + // is serving needs the session's pending requests, so the relay decides. + if params.get("parentOperationID").is_some_and(|value| { + !value + .as_str() + .is_some_and(|id| (1..=128).contains(&id.len())) + }) { + return Err(invalid( + "A parent operation ID is the operationID of a call this backend is serving, 1-128 bytes.", + )); + } + Ok(()) +} + const CONTEXT_REFERENCE_MESSAGE: &str = "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, '.', '_', ':' or '-', and a positive generation."; @@ -1216,6 +1362,26 @@ pub(crate) fn attach_context( Ok(()) } +/// Writes the calling plugin into the params of a relayed +/// `lithe/function/invoke` as `caller: { "pluginID": ... }`, a sibling of +/// `functionID`, `operationID`, `params` and `context`. Only Core writes it, +/// from the identity of the session that made the request, so a callee can +/// key state by caller without trusting anything in the params. A callee that +/// negotiated a version before the relay never receives it, and a call the +/// host itself starts (`caller` is `None`) never carries one: its absence +/// means the host. +pub(crate) fn attach_caller(invoke_params: &mut Value, version: u64, caller: Option<&str>) { + let Some(caller) = caller else { + return; + }; + if version < RELAY_VERSION { + return; + } + if let Some(params) = invoke_params.as_object_mut() { + params.insert("caller".to_string(), json!({ "pluginID": caller })); + } +} + /// The JSON-RPC error code of a host-service code from version 3 on. Each /// code has its own number, so a backend can branch on the number alone: /// codes with a standard meaning keep the JSON-RPC or LSP number, and the @@ -1239,6 +1405,19 @@ pub(crate) fn host_rpc_code(code: &str) -> i64 { codes::HOST_PRECONDITION_FAILED => -32019, codes::HOST_BUSY => -32020, codes::HOST_RATE_LIMITED => -32021, + codes::NOT_DECLARED => -32027, + codes::NOT_EXPORTED => -32028, + codes::PROVIDER_DISABLED => -32029, + codes::VERSION_MISMATCH => -32030, + codes::CALL_CYCLE => -32065, + codes::DEPTH_EXCEEDED => -32066, + codes::TOO_MANY_CALLS => -32067, + codes::PAYLOAD_TOO_LARGE => -32068, + codes::PROVIDER_UNAVAILABLE => -32069, + // A relayed call's own failure is not a host failure: the caller + // must tell the provider's error from Core's by the number alone. + codes::FAILED => -32070, + codes::INVALID_RESULT => -32071, _ => -32603, } } @@ -1342,7 +1521,7 @@ pub(crate) fn is_function_id(value: &str) -> bool { } /// The manifest's plugin ID alphabet: lowercase letters, digits, `.` and `-`. -fn is_plugin_id(value: &str) -> bool { +pub(crate) fn is_plugin_id(value: &str) -> bool { !value.is_empty() && value.len() <= MAX_PLUGIN_ID_BYTES && value.chars().all(|character| { @@ -1582,6 +1761,10 @@ mod tests { &granted, ); let expected = &case["expected"]; + if expected["relay"].as_bool() == Some(true) { + assert_eq!(outcome, Ok(HostRoute::Relay), "{}", name(&case)); + continue; + } if let Some(service) = expected["forward"].as_str() { assert_eq!( outcome, @@ -1646,6 +1829,63 @@ mod tests { } } + #[test] + fn invocation_callers_follow_the_fixture() { + for case in cases("invocationCallers") { + let mut params = case["params"].clone(); + attach_caller( + &mut params, + case["version"].as_u64().unwrap(), + case["caller"].as_str(), + ); + assert_eq!(params, case["expected"]["params"], "{}", name(&case)); + } + } + + #[test] + fn relay_errors_follow_the_fixture() { + for case in cases("relayErrors") { + let code = case["code"].as_str().unwrap(); + assert_eq!(host_rpc_code(code), case["rpcCode"], "{}", name(&case)); + } + } + + /// Every failure a relayed call can end with has its own number, so a + /// caller can branch on either the string or the number. + #[test] + fn relay_refusals_have_distinct_numbers() { + let relay_codes = [ + codes::FAILED, + codes::INVALID_RESULT, + codes::NOT_DECLARED, + codes::NOT_EXPORTED, + codes::PROVIDER_DISABLED, + codes::VERSION_MISMATCH, + codes::CALL_CYCLE, + codes::DEPTH_EXCEEDED, + codes::TOO_MANY_CALLS, + codes::PAYLOAD_TOO_LARGE, + codes::PROVIDER_UNAVAILABLE, + ]; + let numbers: BTreeSet = relay_codes.iter().map(|code| host_rpc_code(code)).collect(); + assert_eq!(numbers.len(), relay_codes.len()); + assert!(!numbers.contains(&-32603)); + } + + /// The relay's discovery and invocation requests are not the old + /// recursive call: the backend still cannot send `lithe/function/invoke`. + #[test] + fn relay_methods_do_not_weaken_the_recursive_call_refusal() { + assert_eq!( + refused_backend_request(INVOKE_METHOD), + Some(codes::RECURSIVE_CALL) + ); + assert_eq!( + refused_backend_request("lithe/build/model"), + Some(codes::RECURSIVE_CALL) + ); + } + #[test] fn host_failures_follow_the_fixture() { for case in cases("hostFailures") { diff --git a/rust/lithe-core/src/plugins/capabilities.rs b/rust/lithe-core/src/plugins/capabilities.rs index 0748637b61..8131621584 100644 --- a/rust/lithe-core/src/plugins/capabilities.rs +++ b/rust/lithe-core/src/plugins/capabilities.rs @@ -73,6 +73,9 @@ pub(crate) const DEBUG_ADAPTERS_API_VERSION: u32 = 4; pub(crate) const EXECUTABLE_RESOLUTION: &str = "executableResolution"; /// Independent providers that translate external shortcut settings. pub(crate) const KEYMAP_IMPORT_PROVIDERS: &str = "keymapImportProviders"; +/// `pluginFunctions`: functions exported to, and called from, other plugins; +/// see `super::plugin_functions`. +pub(crate) const PLUGIN_FUNCTIONS: &str = "pluginFunctions"; /// Plugin-owned tool identities, discovery policy and executable candidates. pub(crate) const TOOL_DEFINITIONS: &str = "toolDefinitions"; /// Backend facts that can influence the executable selected for a defined tool. @@ -92,6 +95,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (LANGUAGE_SERVERS, &[1, 2]), (LANGUAGES, &[1, 2]), (PACKAGE_TRUST, &[1]), + (PLUGIN_FUNCTIONS, &[1]), (PROJECT_GENERATORS, &[1, 2]), (SERVER_PROCESS, &[1, 2]), (SETTINGS, &[1, 2]), diff --git a/rust/lithe-core/src/plugins/declarative.rs b/rust/lithe-core/src/plugins/declarative.rs index 4a7b7613d9..31ad1199ce 100644 --- a/rust/lithe-core/src/plugins/declarative.rs +++ b/rust/lithe-core/src/plugins/declarative.rs @@ -225,6 +225,10 @@ pub struct DeclarativePluginManifest { /// Independent shortcut importers implemented by this plugin's backend. #[serde(default, skip_serializing_if = "Vec::is_empty")] keymap_import_providers: Vec, + /// Functions this plugin exports to other plugins and the exported + /// functions it calls. `pluginFunctions` 1; see `super::plugin_functions`. + #[serde(default, skip_serializing_if = "Option::is_none")] + plugin_functions: Option, } /// UI supplied by plugins. The host owns every window shell: docking, title, @@ -1103,6 +1107,7 @@ impl DeclarativePluginManifest { super::keymap_import::validate_declarations(&mut self.keymap_import_providers)?; self.validate_packaged_provider_backend()?; } + self.validate_plugin_functions()?; if let Some(backend) = &self.backend { backend.validate(&super::backend::DeclarationContext { plugin_api_version: self.plugin_api_version, @@ -1117,8 +1122,13 @@ impl DeclarativePluginManifest { .activation_events .iter() .any(|event| event == super::backend::ON_WORKSPACE_OPEN), + // An exported function starts the backend when another plugin + // calls it, so it needs no page, command or workspace event. provider_query_trigger: !self.toolchain_providers.is_empty() - || !self.keymap_import_providers.is_empty(), + || !self.keymap_import_providers.is_empty() + || self.plugin_functions.as_ref().is_some_and( + super::plugin_functions::PluginFunctionsDeclaration::exports_any, + ), })?; } self.validate_permissions()?; @@ -1212,6 +1222,10 @@ impl DeclarativePluginManifest { capabilities::KEYMAP_IMPORT_PROVIDERS, !self.keymap_import_providers.is_empty(), ), + ( + capabilities::PLUGIN_FUNCTIONS, + self.plugin_functions.is_some(), + ), ]; sections .into_iter() @@ -1331,6 +1345,28 @@ impl DeclarativePluginManifest { Ok(()) } + /// Checks `pluginFunctions`: only a backend 2 of a level 3 or newer + /// manifest registers functions for the protocol that relays calls. + fn validate_plugin_functions(&mut self) -> Validation<()> { + let version = self.backend_version(); + let Some(section) = self.plugin_functions.as_mut() else { + return Ok(()); + }; + if self.plugin_api_version < CAPABILITIES_API_VERSION { + return Err(invalid( + "pluginFunctions", + "Plugin functions require plugin API level 3.", + )); + } + if self.backend.is_none() { + return Err(invalid( + "pluginFunctions", + "Exported and called plugin functions need the plugin backend.", + )); + } + super::plugin_functions::validate(section, version) + } + /// Host-queried providers must start without relying on the discovery they provide. fn validate_packaged_provider_backend(&self) -> Validation<()> { if self.plugin_api_version < CAPABILITIES_API_VERSION || self.backend_version() != 2 { @@ -1794,6 +1830,16 @@ impl DeclarativePluginManifest { services .extend(crate::lsp::interface::plugin_function::methods_for_permission(permission)); } + // Calling another plugin's exported function takes no permission: the + // declaration, and the receiver's own export, are the consent. The + // service lets the backend ask Core to find and call a provider. + if self + .plugin_functions + .as_ref() + .is_some_and(super::plugin_functions::PluginFunctionsDeclaration::calls_any) + { + services.push(crate::lsp::interface::plugin_function::HOST_SERVICE_FUNCTIONS); + } services.sort_unstable(); services.dedup(); services diff --git a/rust/lithe-core/src/plugins/mod.rs b/rust/lithe-core/src/plugins/mod.rs index f97ed37c39..666690582c 100644 --- a/rust/lithe-core/src/plugins/mod.rs +++ b/rust/lithe-core/src/plugins/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod grammar; pub(crate) mod keymap_import; pub mod marketplace; pub(crate) mod native_ui; +pub(crate) mod plugin_functions; pub(crate) mod settings; use serde::Deserialize; diff --git a/rust/lithe-core/src/plugins/plugin_functions.rs b/rust/lithe-core/src/plugins/plugin_functions.rs new file mode 100644 index 0000000000..998d891436 --- /dev/null +++ b/rust/lithe-core/src/plugins/plugin_functions.rs @@ -0,0 +1,270 @@ +//! `pluginFunctions` of a plugin manifest: the functions a plugin exports to +//! other plugins and the exported functions it calls. +//! +//! A plugin function is private to the plugin that registered it. Calling one +//! from another plugin is therefore an explicit contract with two sides. The +//! receiving plugin lists `exports`: each entry names one function ID, the +//! version of the input/result contract that function exchanges, and the one +//! calling context it accepts. The calling plugin lists `calls`: the function +//! IDs and contract versions it will call, never the receiving plugin's ID, +//! because the host discovers the providers. Without both declarations, and +//! the receiver registering the function at runtime, no call is routed. +//! +//! Trust never follows the call. The receiving function runs with the +//! receiving plugin's own permissions and the caller gains none of them. +//! `context` is a closed set; version 1 of the capability has one value, +//! `workspace`: a local trusted workspace scheduled by the host. An export +//! without a context the host knows is rejected, so a function that nobody +//! described the acceptable context of is never callable across plugins. +//! +//! The relay itself lives in `crate::lsp::interface::function_relay`. +//! +//! Note: the decision is recorded in .agents/notes/implemented/architecture/2026-10-20-plugin-function-contract.md +//! and .agents/notes/proposed/architecture/2026-10-25-plugin-dependencies-and-exports.md + +use super::declarative::{invalid, Validation}; +use crate::lsp::interface::plugin_function::is_function_id; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Most functions one plugin may export, and most it may declare calling. +pub(crate) const MAX_ENTRIES: usize = 32; + +/// Largest export or call contract version. A version names an incompatible +/// contract, so a plugin does not need many. +pub(crate) const MAX_CONTRACT_VERSION: u32 = 1000; + +/// The calling context of a function that runs inside the local trusted +/// workspace, scheduled by the host. +pub(crate) const CONTEXT_WORKSPACE: &str = "workspace"; + +/// Every calling context this Core build knows. +pub(crate) const KNOWN_CONTEXTS: &[&str] = &[CONTEXT_WORKSPACE]; + +/// A function this plugin offers to other plugins. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ExportDeclaration { + pub(crate) id: String, + /// Version of the input and result contract. An incompatible change uses + /// a new version, and callers declare the version they were written for. + pub(crate) version: u32, + /// The only calling context the function accepts. Kept optional while + /// decoding so a missing or unknown value is a precise manifest error. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) context: Option, +} + +/// An exported function this plugin calls. +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct CallDeclaration { + pub(crate) id: String, + pub(crate) version: u32, +} + +/// The `pluginFunctions` section. +#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct PluginFunctionsDeclaration { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) exports: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) calls: Vec, +} + +impl PluginFunctionsDeclaration { + /// Whether the plugin exports at least one function, which lets the host + /// start its backend when another plugin calls it. + pub(crate) fn exports_any(&self) -> bool { + !self.exports.is_empty() + } + + /// Whether the plugin may call exported functions of other plugins. + pub(crate) fn calls_any(&self) -> bool { + !self.calls.is_empty() + } +} + +/// Checks a section and sorts both lists by function ID, so the same +/// declaration always plans the same way. `backend_version` is the plugin's +/// `requires.backend`, 0 without a backend: only a backend 2 process can +/// register functions for the protocol that carries relayed calls. +pub(crate) fn validate( + section: &mut PluginFunctionsDeclaration, + backend_version: u32, +) -> Validation<()> { + if section.exports.is_empty() && section.calls.is_empty() { + return Err(invalid( + "pluginFunctions", + "pluginFunctions declares no exports and no calls.", + )); + } + if backend_version < super::backend::WORKSPACE_CONTEXT_VERSION { + return Err(invalid( + "requires.backend", + "Exported and called plugin functions require backend 2.", + )); + } + if section.exports.len() > MAX_ENTRIES { + return Err(invalid( + "pluginFunctions.exports", + "The plugin exports too many functions.", + )); + } + if section.calls.len() > MAX_ENTRIES { + return Err(invalid( + "pluginFunctions.calls", + "The plugin declares too many called functions.", + )); + } + let mut exported = BTreeSet::new(); + for (index, export) in section.exports.iter().enumerate() { + let field = format!("pluginFunctions.exports[{index}]"); + if !is_function_id(&export.id) { + return Err(invalid( + format!("{field}.id"), + "An exported function ID is dot-separated lowerCamelCase segments.", + )); + } + if !exported.insert(export.id.as_str()) { + return Err(invalid( + format!("{field}.id"), + "A function is exported more than once.", + )); + } + check_version(export.version, &field)?; + match export.context.as_deref() { + Some(context) if KNOWN_CONTEXTS.contains(&context) => {} + Some(_) => { + return Err(invalid( + format!("{field}.context"), + "This version of Lithe does not know the export's calling context.", + )) + } + None => { + return Err(invalid( + format!("{field}.context"), + "An exported function states the calling context it accepts.", + )) + } + } + } + let mut called = BTreeSet::new(); + for (index, call) in section.calls.iter().enumerate() { + let field = format!("pluginFunctions.calls[{index}]"); + if !is_function_id(&call.id) { + return Err(invalid( + format!("{field}.id"), + "A called function ID is dot-separated lowerCamelCase segments.", + )); + } + if !called.insert(call.id.as_str()) { + return Err(invalid( + format!("{field}.id"), + "A function is declared as called more than once.", + )); + } + check_version(call.version, &field)?; + } + section + .exports + .sort_by(|left, right| left.id.cmp(&right.id)); + section.calls.sort_by(|left, right| left.id.cmp(&right.id)); + Ok(()) +} + +fn check_version(version: u32, field: &str) -> Validation<()> { + if version == 0 || version > MAX_CONTRACT_VERSION { + return Err(invalid( + format!("{field}.version"), + "A function contract version is a positive integer within the supported range.", + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn export(id: &str, version: u32, context: Option<&str>) -> ExportDeclaration { + ExportDeclaration { + id: id.to_string(), + version, + context: context.map(str::to_string), + } + } + + fn section() -> PluginFunctionsDeclaration { + PluginFunctionsDeclaration { + exports: vec![export("project.describe", 1, Some("workspace"))], + calls: vec![CallDeclaration { + id: "tool.resolve".to_string(), + version: 2, + }], + } + } + + #[test] + fn a_valid_section_is_sorted_by_function_id() { + let mut section = section(); + section + .exports + .insert(0, export("zeta.run", 1, Some("workspace"))); + validate(&mut section, 2).expect("section is valid"); + assert_eq!(section.exports[0].id, "project.describe"); + assert_eq!(section.exports[1].id, "zeta.run"); + } + + #[test] + fn an_export_must_name_a_known_context() { + for context in [None, Some("remote"), Some(""), Some("Workspace")] { + let mut section = section(); + section.exports[0].context = context.map(str::to_string); + let rejection = validate(&mut section, 2).expect_err("context is rejected"); + assert_eq!(rejection.code, "plugin.manifest.invalid"); + assert_eq!( + rejection.field.as_deref(), + Some("pluginFunctions.exports[0].context") + ); + } + } + + #[test] + fn ids_versions_and_counts_are_bounded() { + let mut bad_id = section(); + bad_id.exports[0].id = "Project.Describe".to_string(); + assert!(validate(&mut bad_id, 2).is_err()); + + let mut zero = section(); + zero.calls[0].version = 0; + assert!(validate(&mut zero, 2).is_err()); + + let mut huge = section(); + huge.exports[0].version = MAX_CONTRACT_VERSION + 1; + assert!(validate(&mut huge, 2).is_err()); + + let mut duplicate = section(); + duplicate + .exports + .push(export("project.describe", 2, Some("workspace"))); + assert!(validate(&mut duplicate, 2).is_err()); + + let mut many = section(); + many.calls = (0..=MAX_ENTRIES) + .map(|index| CallDeclaration { + id: format!("tool.run{index}"), + version: 1, + }) + .collect(); + assert!(validate(&mut many, 2).is_err()); + } + + #[test] + fn the_section_needs_backend_two_and_some_entry() { + assert!(validate(&mut section(), 1).is_err()); + assert!(validate(&mut section(), 0).is_err()); + assert!(validate(&mut PluginFunctionsDeclaration::default(), 2).is_err()); + } +} diff --git a/rust/lithe-core/src/protocol/command.rs b/rust/lithe-core/src/protocol/command.rs index 035ee14266..49867208d8 100644 --- a/rust/lithe-core/src/protocol/command.rs +++ b/rust/lithe-core/src/protocol/command.rs @@ -445,6 +445,9 @@ pub enum CoreCommand { LspKeymapImportRequest, /// Invokes one plugin function (`lsp.functionRequest`). LspFunctionRequest, + /// Replaces the plugins and workspace contexts the cross-plugin function + /// relay checks calls against (`lsp.configureFunctionRelay`). + LspConfigureFunctionRelay, /// Answers a plugin backend's host-service request (`lsp.hostResponse`). LspHostResponse, /// Sends a plugin backend one host notification (`lsp.hostNotify`). @@ -924,6 +927,7 @@ impl CoreCommand { "lsp.toolchainRequest" => Some(Self::LspToolchainRequest), "lsp.keymapImportRequest" => Some(Self::LspKeymapImportRequest), "lsp.functionRequest" => Some(Self::LspFunctionRequest), + "lsp.configureFunctionRelay" => Some(Self::LspConfigureFunctionRelay), "lsp.hostResponse" => Some(Self::LspHostResponse), "lsp.hostNotify" => Some(Self::LspHostNotify), "java.resolveNavigation" => Some(Self::JavaResolveNavigation), @@ -1088,6 +1092,7 @@ mod tests { "lsp.toolchainRequest", "lsp.keymapImportRequest", "lsp.functionRequest", + "lsp.configureFunctionRelay", "lsp.hostResponse", "lsp.hostNotify", "lsp.cancelOperation", diff --git a/rust/lithe-core/src/runtime/dispatcher.rs b/rust/lithe-core/src/runtime/dispatcher.rs index d32fbebcf5..42f8c647dd 100644 --- a/rust/lithe-core/src/runtime/dispatcher.rs +++ b/rust/lithe-core/src/runtime/dispatcher.rs @@ -2299,6 +2299,18 @@ fn execute_parsed(mut parsed: CoreRequest) -> CoreResponse { Err(error) => CoreResponse::failure(id, error), } } + CoreCommand::LspConfigureFunctionRelay => { + match serde_json::from_value::(parsed.payload) + .map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid function relay snapshot") + .with_details(error.to_string()) + }) + .and_then(crate::lsp::configure_function_relay) + { + Ok(()) => CoreResponse::success(id, json!({})), + Err(error) => CoreResponse::failure(id, error), + } + } CoreCommand::LspHostResponse => { match serde_json::from_value::(parsed.payload) .map_err(|error| { diff --git a/rust/lithe-core/src/tests/declarative_plugins.rs b/rust/lithe-core/src/tests/declarative_plugins.rs index 15d3c5e645..4cc1172897 100644 --- a/rust/lithe-core/src/tests/declarative_plugins.rs +++ b/rust/lithe-core/src/tests/declarative_plugins.rs @@ -40,6 +40,10 @@ const SETTINGS_V2_FIXTURE: &str = contract_file!("fixtures/settings/settings-v2. const BACKEND_FIXTURE: &str = contract_file!("fixtures/backend/backend.plugin.json"); const WORKSPACE_BACKEND_FIXTURE: &str = contract_file!("fixtures/backend/backend-workspace.plugin.json"); +const FUNCTION_EXPORTER_FIXTURE: &str = + contract_file!("fixtures/backend/plugin-functions-exporter.plugin.json"); +const FUNCTION_CALLER_FIXTURE: &str = + contract_file!("fixtures/backend/plugin-functions-caller.plugin.json"); const DEBUG_ADAPTER_FIXTURE: &str = contract_file!("fixtures/debug-adapters/debug-adapter.plugin.json"); const DEBUG_ADAPTER_LANGUAGE_SERVER_FIXTURE: &str = @@ -81,6 +85,8 @@ fn fixture(name: &str) -> Value { "settings-v2.plugin.json" => SETTINGS_V2_FIXTURE, "backend.plugin.json" => BACKEND_FIXTURE, "backend-workspace.plugin.json" => WORKSPACE_BACKEND_FIXTURE, + "plugin-functions-exporter.plugin.json" => FUNCTION_EXPORTER_FIXTURE, + "plugin-functions-caller.plugin.json" => FUNCTION_CALLER_FIXTURE, "debug-adapter.plugin.json" => DEBUG_ADAPTER_FIXTURE, "debug-adapter-language-server.plugin.json" => DEBUG_ADAPTER_LANGUAGE_SERVER_FIXTURE, "debug-adapter-remote-attach.plugin.json" => DEBUG_ADAPTER_REMOTE_ATTACH_FIXTURE, @@ -109,6 +115,8 @@ fn contract_fixtures_and_official_plugins_validate() { PUBLISHER_BUNDLED_FIXTURE, BACKEND_FIXTURE, WORKSPACE_BACKEND_FIXTURE, + FUNCTION_EXPORTER_FIXTURE, + FUNCTION_CALLER_FIXTURE, DEBUG_ADAPTER_FIXTURE, DEBUG_ADAPTER_REMOTE_ATTACH_FIXTURE, GRAMMAR_FIXTURE, @@ -841,6 +849,73 @@ fn workspace_backend_is_planned_with_its_version_and_workspace_service() { assert_eq!(validate(manifest)["status"], "ok"); } +/// An exporting plugin is sorted by function ID and starts for a call without +/// a page or an event. Only a plugin that declares calls is granted the host +/// service that finds providers: exporting grants nothing, and a call needs +/// no permission because both declarations are the consent. +#[test] +fn plugin_functions_are_normalized_and_granted_only_to_callers() { + let mut exporter = fixture("plugin-functions-exporter.plugin.json"); + exporter["pluginFunctions"]["exports"] + .as_array_mut() + .unwrap() + .reverse(); + let outcome = validate(exporter); + assert_eq!(outcome["status"], "ok", "{outcome}"); + assert_eq!( + outcome["plugin"]["pluginFunctions"]["exports"], + json!([ + { "id": "document.format", "version": 1, "context": "workspace" }, + { "id": "symbols.list", "version": 2, "context": "workspace" } + ]) + ); + + let backend_plan = |name: &str| { + language_server_launch_plan_command(json!({ + "manifest": fixture(name), + "backend": true, + "request": { + "pluginDirectory": "/plugins/functions", + "stateDirectory": "/state/functions", + "architecture": "arm64" + }, + })) + .expect("payload is well formed") + }; + let exporter_plan = backend_plan("plugin-functions-exporter.plugin.json"); + assert_eq!(exporter_plan["status"], "ok", "{exporter_plan}"); + assert_eq!( + exporter_plan["plan"]["backend"], + json!({ "hostServices": [], "version": 2 }) + ); + let caller_plan = backend_plan("plugin-functions-caller.plugin.json"); + assert_eq!(caller_plan["status"], "ok", "{caller_plan}"); + assert_eq!( + caller_plan["plan"]["backend"], + json!({ "hostServices": ["functions"], "version": 2 }) + ); +} + +/// A host that does not know `pluginFunctions` never runs a plugin that uses +/// it, so a plugin cannot export a function nobody will route. +#[test] +fn plugin_functions_need_a_host_that_hosts_them() { + let hosted = |host: Value| { + validate_command(json!({ + "manifest": fixture("plugin-functions-caller.plugin.json"), + "hostCapabilities": host, + })) + .expect("payload is well formed") + }; + let old_host = hosted(json!({ "backend": [1, 2], "serverProcess": [1] })); + assert_eq!(old_host["error"]["code"], "plugin.api.unsupported"); + assert_eq!(old_host["error"]["field"], "requires.pluginFunctions"); + let host = hosted(json!({ + "backend": [1, 2], "serverProcess": [1], "pluginFunctions": [1] + })); + assert_eq!(host["status"], "ok", "{host}"); +} + /// Icon trust boundaries are shared; native decoding remains with the macOS host. #[test] fn ui_icon_declarations_validate_and_preserve_theme_resources() { diff --git a/scripts/architecture/verify-shared-contracts.sh b/scripts/architecture/verify-shared-contracts.sh index 060f099c3c..187ebc51fc 100755 --- a/scripts/architecture/verify-shared-contracts.sh +++ b/scripts/architecture/verify-shared-contracts.sh @@ -239,7 +239,7 @@ done functions = JSON.parse(File.read(File.join(fixtures, "backend", "function-protocol.json"))) abort "function protocol fixture schema must be 1" unless functions.fetch("schemaVersion") == 1 abort "function protocol fixture must describe litheFunctions" unless functions.fetch("protocol") == "litheFunctions" - function_sections = %w[negotiation registration invocations outcomes progress backendRequests hostRequests] + function_sections = %w[negotiation registration invocations outcomes progress backendRequests hostRequests invocationCallers relayErrors] function_names = function_sections.flat_map { |section| functions.fetch(section).map { |item| item.fetch("name") } } abort "function protocol case names must be unique" unless function_names.uniq.length == function_names.length function_codes = [] @@ -251,6 +251,11 @@ done functions.fetch("outcomes").each { |item| function_codes << item.fetch("expected").fetch("error", {})["code"] } functions.fetch("backendRequests").each { |item| function_codes << item.fetch("expected")["code"] } functions.fetch("hostRequests").each { |item| function_codes << item.fetch("expected")["code"] } + functions.fetch("relayErrors").each { |item| function_codes << item.fetch("code") } + relay_numbers = functions.fetch("relayErrors").map { |item| [item.fetch("code"), item.fetch("rpcCode")] }.uniq + abort "relay error codes must each have one number" unless relay_numbers.map(&:first).uniq.length == relay_numbers.length + new_relay_numbers = relay_numbers.select { |code, _| code.start_with?("plugin.function.") && code != "plugin.function.failed" }.map(&:last) + abort "each new plugin.function relay code needs its own number" unless new_relay_numbers.uniq.length == new_relay_numbers.length function_codes.compact.uniq.each do |code| abort "function protocol fixture uses an undocumented code #{code}" unless documented.include?(code) end diff --git a/shared/contracts/plugins/v1/README.md b/shared/contracts/plugins/v1/README.md index 08a03e7b99..6b7e235d8c 100644 --- a/shared/contracts/plugins/v1/README.md +++ b/shared/contracts/plugins/v1/README.md @@ -20,7 +20,7 @@ This directory is the cross-platform source of truth: | --- | --- | | `fixtures/manifest/` | `hello-lithe.plugin.json`, the smallest UI plugin, and `invalid-manifests.json`: edits to a valid manifest and the rejection code every host must report | | `fixtures/languages/` | Language support: packaged, system-command, and host-integration language servers, `node-runtime` for a discovered runtime, and `language-grammar` with `grammars/`; `command-plans.json` holds golden run/test command expansions and language-server launch plans, `runtime-versions.json` the golden outcomes of the launch runtime version check | -| `fixtures/backend/` | Plugin backends (`backend`, `backend-workspace`, `command-backend`, `terminal-backend`); `function-protocol.json` holds golden plugin-function negotiation, registration, invocation, outcome, progress, and refusal cases, `plugin-logging.json` the golden `litheLogging` negotiation and notifications | +| `fixtures/backend/` | Plugin backends (`backend`, `backend-workspace`, `command-backend`, `terminal-backend`); cross-plugin calls (`plugin-functions-exporter`, `plugin-functions-caller`); `function-protocol.json` holds golden plugin-function negotiation, registration, invocation, outcome, progress, and refusal cases, `plugin-logging.json` the golden `litheLogging` negotiation and notifications | | `fixtures/editor/` | Editor actions served by a backend: `editor-actions.plugin.json`, version 2 icons, alternatives and click results in `editor-actions-v2.json`; editor providers in `editor-providers.plugin.json` with registration and result cases in `editor-providers.json` | | `fixtures/ui/` | Native controls, forms, and panels, and a web panel | | `fixtures/settings/` | Plugin settings declared with `settings: 2` | @@ -175,6 +175,7 @@ symbolic links. A host treats an installed package as read-only. | `toolDefinitions` | Plugin-owned tool policy ([Core foundation](toolchains/README.md)); requires `toolDefinitions: 1` and `executableResolution: 2`; macOS hosts read-only discovery and resolves Build and run tools. | | `toolchainProviders` | Backend fact-provider declarations ([Core foundation](toolchains/README.md)); requires `toolchainProviders: 1`, backend/server-process capabilities and `toolchains.provide`. | | `keymapImportProviders` | Independent shortcut import providers; requires `keymapImportProviders: 1`, `backend: 2`, `serverProcess: 1` and `keymaps.provide`. macOS provides access to explicitly selected sources; Windows does not yet advertise this capability. | +| `pluginFunctions` | [Functions the plugin exports to, and calls from, other plugins](#cross-plugin-calls-protocol-version-4); requires `pluginFunctions: 1`, `backend: 2` and `serverProcess: 1`, and grants no permission. macOS relays the calls; Windows does not advertise this capability. | Unknown fields are refused (`plugin.manifest.invalid`) so an older host rejects a package instead of ignoring part of it. At levels 1 and 2 a new @@ -676,6 +677,7 @@ hosts. Level 3 versions each section on its own. A level 3 manifest lists in | `backend` | [`backend`](#plugin-backend): the plugin's own long-lived process | `1`, `2` (adds [start without a page and workspace contexts](#backend-2-workspace-contexts)) | | `toolDefinitions` | [Tool identities, layouts, discovery and four-layer candidates](toolchains/README.md) | `1` (Core; macOS settings pages, Build and run tools) | | `toolchainProviders` | [Provider declarations and permission-bound answer validation](toolchains/README.md) | `1` (Core; macOS settings pages, Build and run tools) | +| `pluginFunctions` | [`pluginFunctions`](#cross-plugin-calls-protocol-version-4): exported functions and declared calls between plugins | `1` (Core; macOS relays calls) | | `executableResolution` | [Shared executable candidates](#shared-executable-candidates-executableresolution-12): candidate ordering and strict selection; v2 adds tool-definition candidates and canonical project/subproject toolchain registry bindings without changing existing Build candidate sets | `1`, `2` (v2 Core; macOS settings pages, Build and run tools) | | `keymapImportProviders` | `keymapImportProviders[]`: independent shortcut import providers | `1` (macOS; Windows does not advertise it yet) | @@ -2221,11 +2223,15 @@ removes the staging directory and leaves nothing behind A plugin backend (a language server, build provider, or [plugin backend](#plugin-backend) process the plugin starts) can offer -**plugin functions**: plugin-private actions with -serializable params and results, which the host invokes on behalf of the same -plugin, for example from that plugin's own window. Functions complement the -typed domain protocols; they never replace them. Versions 1 to 3 of the protocol are -implemented in Rust Core (`rust/lithe-core/src/lsp/interface/plugin_function.rs`). +**plugin functions**: actions with +serializable params and results. A function is private to its plugin unless +the manifest exports it: the host invokes a private function on behalf of the +same plugin, for example from that plugin's own window, and another plugin +can call only an [exported function](#cross-plugin-calls-protocol-version-4). +Functions complement the +typed domain protocols; they never replace them. Versions 1 to 4 of the protocol are +implemented in Rust Core (`rust/lithe-core/src/lsp/interface/plugin_function.rs`, +`function_relay.rs`). macOS starts every build provider process as a session of the plugin that owns it and invokes its functions from that plugin's web pages (the `functions.*` bridge methods below). A provider served by a shared language @@ -2242,6 +2248,7 @@ Every capability has one owner, who defines its contract, and one direction: | Plugin provides a domain capability | Lithe: the typed domain contract | The plugin, declaratively or by its backend | A manifest `source`, Core plans and decodes, a typed `lithe/build/*` request | Build model, dependency tree; later task execution | | Plugin provides a plugin function | The plugin: its own params and results | The plugin's backend | `lithe/function/invoke` | Refresh a private snapshot, a step behind a button of the plugin's own UI | | Plugin calls a host capability | The host | The host | `lithe/host/*` requests, offered per protocol version | Run a process through the host's runner, write output, store state | +| Plugin calls another plugin's exported function | The exporting plugin: its own params and results, under an exported version | The exporting plugin's backend | `lithe/host/functions/invoke`, relayed by Core as `lithe/function/invoke` | A language plugin asks a build plugin for the options it contributes | Two rules keep these directions from forming a loop: @@ -2250,7 +2257,11 @@ Two rules keep these directions from forming a loop: then wait for itself. A backend request for `lithe/function/invoke` or any `lithe/build/*` method is refused with `plugin.function.recursiveCall`. A handler that needs, say, a Maven run asks for the host's process - capability, never for the task that its own plugin implements. + capability, never for the task that its own plugin implements. The + [relay methods](#cross-plugin-calls-protocol-version-4) are a different + request: they name another plugin's exported function, Core refuses a call + that would come back to a plugin already waiting on the call chain, and + the old refusals above stay in force. - Host capabilities are primitive host services, never another entry into a domain registry. Each is added to a protocol version together with its params, permission, and the operation it must belong to. Version 1 offers @@ -2266,10 +2277,12 @@ Two rules keep these directions from forming a loop: - A backend implements a domain operation through its typed method and Core's plan and decode commands, never through a plugin function, so IDE workflows, presentation, and other hosts keep a single contract. -- Plugin functions need no manifest field. What a running process can answer - is negotiated, as for [build providers](#build-providers); so declaring, - adding, or removing functions changes neither `pluginAPIVersion` nor any - `requires` version. +- A plugin-private function needs no manifest field. What a running process + can answer is negotiated, as for [build providers](#build-providers); so + declaring, adding, or removing private functions changes neither + `pluginAPIVersion` nor any `requires` version. Only a function that + another plugin may call, and a call to such a function, are declared, in + [`pluginFunctions`](#cross-plugin-calls-protocol-version-4). - A new kind of domain implementation, such as a provider for tasks, is a new version of the capability that owns it (`buildProviders`), so only plugins that use it are filtered from hosts that cannot run it. @@ -2277,7 +2290,7 @@ Two rules keep these directions from forming a loop: ### Negotiation For a session owned by a plugin (`lsp.startServer.pluginId`), the host offers -`capabilities.experimental.litheFunctions: { "versions": [1, 2, 3] }` in +`capabilities.experimental.litheFunctions: { "versions": [1, 2, 3, 4] }` in `initialize`, next to and independent of `litheBuild`. Host-owned sessions do not offer or accept this protocol, retain no plugin-function registry, and reject register/unregister with `-32601`. A plugin backend that offers @@ -2894,9 +2907,270 @@ per workspace context: package requiring `editor.providers` is refused by an older host that does not recognize the permission. +### Cross-plugin calls (protocol version 4) + +A plugin function is private to its plugin unless the plugin exports it. An +exported function can be called by another enabled plugin whose manifest +declares that call. Core relays every call: the calling backend never +reaches the provider's process, the provider's backend never learns more than +the call it serves, and the host takes part only by starting a provider's +backend that is not running (see below). The relay is Rust Core logic, the same +on every platform that runs plugin backends. +`fixtures/backend/plugin-functions-exporter.plugin.json` and +`fixtures/backend/plugin-functions-caller.plugin.json` are the examples. + +#### Declaring exports and calls + +```json +"requires": { "pluginFunctions": 1, "backend": 2, "serverProcess": 1 }, +"pluginFunctions": { + "exports": [{ "id": "document.format", "version": 1, "context": "workspace" }], + "calls": [{ "id": "project.describe", "version": 2 }] +} +``` + +- `pluginFunctions` needs `pluginAPIVersion` 3 or later, a `backend`, and + `requires.pluginFunctions: 1`, `backend: 2` and `serverProcess: 1`. The + section holds at least one of `exports` and `calls`, each at most 32 + entries sorted by `id`, with no `id` twice. Anything else, including an + unknown field, is `plugin.manifest.invalid`. `requires` lists + `pluginFunctions` exactly when the section exists. +- An export is an object, never a bare function ID. `id` is a function ID + as in [References and IDs](#references-and-ids). `version` is the + exported contract version, an integer from 1 to 1000; an incompatible + change to the params or result takes a new version. `context` is a closed + set; version 1 knows only `"workspace"`: the function runs only for a + local workspace context, on a call Core relays. A missing or unknown + `context` refuses the whole manifest with `plugin.manifest.invalid`, so a + function whose context is unstated is never callable. +- A call is `{ id, version }`. It names a function ID and the version the + caller was written against, never the providing plugin's ID: the caller + discovers providers at run time. Core requires the versions to be equal; + otherwise the call fails with `plugin.function.versionMismatch`. +- Declaring an export does not register it. The provider's backend still + registers the function with `lithe/function/register`, and a function it + has not registered, or has withdrawn, is `plugin.function.notExported`. + A function the manifest does not export is private whatever the backend + registers, and a reference to it keeps answering + `plugin.function.wrongPlugin`. +- A plugin that exports needs no page, command or `onWorkspaceOpen` to start + its backend: a call starts it. A plugin that only calls needs one of + those, as every [`backend` 2](#backend-2-workspace-contexts) does. +- `pluginFunctions` grants no manifest permission. The caller's `calls` + and the provider's `exports` are the two sides' consent, and the host + grants a plugin that declares `calls` the `functions` host service, + through `backend.hostServices` of its launch plan, like every other + service. A host without `pluginFunctions` in `hostCapabilities` refuses + such a manifest with `plugin.api.unsupported`. + +#### What an exported function must and must not do + +- **Trust is not transitive.** The provider runs with its own permissions, + its own state directory and its own credentials. The caller gains none of + them, and the provider gains none of the caller's. Core never writes the + caller's plugin ID into the provider's session; it appears only in the + `caller` field of one request, below. +- **The provider owns its resources and processes.** An exported function + must not accept an executable path, command line or script from its caller + and start a process with it, nor read or write a path the caller chose + without checking it against what the provider itself may access. If a + caller needs the provider to run something, the function takes a request + the provider interprets (a task name, a document) and the provider decides + the executable. +- A function that decides by who asks reads the `caller` field below, never + a plugin ID in `params`, which any caller can write. + +#### Discovery and invocation + +A backend that negotiated protocol version 4, and whose plugin declares at +least one call, may send two requests. A backend on version 3 or earlier gets +`-32601`, `plugin.host.unavailable`; a plugin that declares no call gets +`-32010`, `plugin.host.permissionDenied`. `getCapabilities` lists the +methods the session may call under the `functions` service. + +| Request | Params | Result | +| --- | --- | --- | +| `lithe/host/functions/providers` | `{ functionID }` | `{ providers: [{ pluginID, version }] }` | +| `lithe/host/functions/invoke` | `{ pluginID, functionID, context: { contextID, generation }, params?, timeoutMilliseconds?, parentOperationID? }` | `{ value }` | + +- `providers` lists the enabled plugins other than the caller that export + `functionID`, sorted by plugin ID, each with its exported `version`. + Disabling, enabling, replacing and uninstalling a plugin take effect for + the list at once; a host that registers backend plugins only when it + launches (macOS today) lists a newly installed or updated backend plugin + only after a restart of Lithe (see [Hot activation](#hot-activation)). The + caller must have declared the function, otherwise + `plugin.function.notDeclared`. A listed provider's backend need not be + running. +- `invoke` calls one provider. `context` is required: a workspace context + the caller learned from the [workspace service](#workspace-contexts-and-capability-discovery-protocol-version-3), + checked like every call context. `params` is a JSON object and defaults + to `{}`. `timeoutMilliseconds` is a positive integer, defaults to 60 000 + and is capped at 600 000. A field the method does not define is `-32018`, + `plugin.host.unsupportedOption`. The reply is `{ value }`, where `value` + is the provider's result (`null` is a result). +- `parentOperationID` is optional: a string of 1 to 128 bytes, otherwise + `-32602`, `plugin.host.invalidParams`. A backend that makes a nested call + while it serves a relayed call sets it to the `operationID` of the + `lithe/function/invoke` it is serving (the field shown in + [The caller field](#the-caller-field)), so Core knows which call the new + one belongs to. Its effects are described in + [The call chain](#the-call-chain). A backend should always set it: without + it Core treats the new call as a child of every relayed call the backend is + serving. +- The caller cancels a call with `$/cancelRequest` for its `invoke` request + id; it fails with `plugin.host.cancelled`. + +Core checks, in this order, and refuses a call before anything is written to +the provider; the first failing check wins: + +| Check | Code | +| --- | --- | +| The caller declared the function | `plugin.function.notDeclared` | +| The provider is installed and enabled | `plugin.function.providerDisabled` | +| The provider exports the function | `plugin.function.notExported` | +| The declared and exported versions are equal | `plugin.function.versionMismatch` | +| The context is open, and has this generation | `plugin.host.contextExpired` | +| The context is a local workspace | `plugin.host.authorityUnsupported` | +| The params are at most 256 KiB | `plugin.function.payloadTooLarge` | +| The call named by `parentOperationID` is still running | `plugin.host.cancelled` | +| The provider is not on the call chain, the caller included | `plugin.function.callCycle` | +| The chain has at most 4 calls | `plugin.function.depthExceeded` | +| The caller has at most 8 relayed calls running | `plugin.function.tooManyCalls` | + +A provider's own failure keeps its meaning. The reply is a JSON-RPC error +with `data: { "code", "details" }`; when the provider's function answered with +an error, `code` is `plugin.function.failed` (`-32070`), `message` is the +provider's message cut to 1024 bytes, and `details.pluginErrorCode` is the +provider's own `error.data.code`. A reply with no `result`, or with one over +1 MiB serialized, is `plugin.function.invalidResult` (`-32071`); any other +result over 256 KiB is `plugin.function.payloadTooLarge`. Neither number is +`-32603`, which stays `plugin.host.failed`, a failure inside Core. The relay's deadline passing is +`plugin.host.timeout`. A call that is running normally ends through the +provider session's own timeout; if the provider has still not answered 2 +seconds after the deadline, the relay ends the call with +`plugin.host.timeout` itself and cancels the provider's operation. A +provider whose backend exits, or that withdraws +the function, while the call runs ends it with +`plugin.function.providerUnavailable`; a provider that is disabled or +uninstalled, or whose update stops exporting the function or changes its +version, ends it with `plugin.function.providerDisabled`. A caller whose +update stops declaring the call ends it with `plugin.function.notDeclared`. +A workspace context that the host closes, or replaces with a newer +generation, ends the relayed calls that carry it with +`plugin.host.contextExpired`: both the calls still waiting for a provider and +the calls already running, whose provider also receives `$/cancelRequest`. +Core never restarts a backend or retries a call to finish one. + +`fixtures/backend/function-protocol.json` holds the cases: the host requests +(`hostRequests`), the numbers of every failure (`relayErrors`) and the +`caller` field (`invocationCallers`). + +#### The call chain + +Core records the chain a call belongs to. A provider that makes a call while it +serves a relayed call names that call in `parentOperationID`. The new call is +then a child of that call only: + +- Its chain is the chain of that call plus the caller. +- Cancelling that call, its timing out, or its ending cancels the new call. + +A call to a plugin already on the chain, including a plugin calling itself, is +`plugin.function.callCycle`: the plugin on the chain is waiting for the call +that would reach it. A chain has at most 4 calls. So a provider that is asked +to apply values must not call back the plugin that asked inside that call; it +records the values, or calls after the call ends. + +- If `parentOperationID` names a call the host started directly, not a relayed + one, the new call starts a new chain. +- If it names a call this backend is not serving (one that has finished, or + one that never existed), the call is refused with `plugin.host.cancelled` + and the message "The call this request belongs to is not running." +- If it is omitted, the call counts as a child of every relayed call the + backend is serving at that moment. This is kept for compatibility with + backends written before the field; SDKs should always fill it in. + +Cancelling a call, its timing out or ending, or the end of its caller's +session, cancels the calls made as its children, down the chain, and each +provider receives `$/cancelRequest`. The relay never retries a call. + +#### Isolation between backends + +Core writes to each backend session through a queue of its own. A backend +that stops reading its standard +input only delays the calls and replies sent to it; the relayed calls of other +plugins continue. If a write to a backend stays blocked past the request +timeout, Core ends that backend's session as a transport failure +(`transportFailed`, stage `relayWrite`), and the calls of that session end like +those of any session failure. + +#### The caller field + +For every relayed call Core forwards `lithe/function/invoke` to the provider +as for any call (see [Invocation](#invocation)) and adds one top-level field: + +```json +{ + "functionID": "project.describe", + "operationID": "7", + "context": { "contextID": "w1", "generation": 1 }, + "params": { "project": "app" }, + "caller": { "pluginID": "dev.lithe.fixture.python" } +} +``` + +- `caller.pluginID` is written by Core from the identity of the calling + session. It is a sibling of `functionID`, `operationID`, `params` and + `context`, never inside `params`, and the caller cannot supply it: a + `lithe/host/functions/invoke` request carrying a top-level `caller` is + refused with `-32018`, `plugin.host.unsupportedOption`. A `caller` key + inside the caller's own `params` is ordinary data and is passed unchanged. +- A call the host itself started has no `caller` field. Absent means the + host. +- A provider that negotiated version 3 or earlier never receives the field. + A provider that relies on it must negotiate version 4; a provider that + keeps per-caller state (for example a slot per calling plugin) keys it by + this ID, which cannot be forged. + +#### Providers that are not running + +If the provider's backend is not running, Core waits for it and emits the +runtime event `functionProviderStartRequired` with +`result: { "pluginID" }` on the calling session, once per waiting provider. +The host starts that plugin's backend as an ordinary plugin start, and Core +dispatches the call when the provider has negotiated the protocol and registered +the function. If that takes longer than 30 seconds the call fails with +`plugin.function.providerUnavailable`; the relay's deadline still applies. +A host that cannot start the backend ignores the event, and the call ends the +same way. + +#### Remote workspaces + +The relay is a local-workspace feature. A call whose context is a remote +workspace is refused with `plugin.host.authorityUnsupported`, and the +exported `context` value `"workspace"` means a local workspace only. Backends +still run on the machine that runs Lithe. + +#### Hot activation + +Disabling, enabling, replacing and uninstalling a plugin take effect for the +relay at once and need no restart of Lithe or of any other plugin. +The host sends the plugin and workspace-context snapshot with the Core +command `lsp.configureFunctionRelay` +([Rust Core API](https://github.com/1lck/Lithe-IDEA/blob/preview/shared/contracts/rust-core-api.md)), +and calls the new snapshot no longer allows end at once with the errors above. + +Installing or updating a plugin that has a backend is different on a host that +registers backend plugins only when it launches (macOS today): that host lists +a newly installed or updated backend plugin in `providers` only after a +restart of Lithe. + ### Compatibility -- Packages of every API level are unchanged: functions add no manifest field. +- Packages of every API level are unchanged: private functions add no + manifest field. `pluginFunctions` is a new capability + (`requires.pluginFunctions: 1`), so only a plugin that exports or calls + functions is refused by a host that cannot relay them. - A backend written before this protocol does not answer `litheFunctions`. It keeps serving its language and its `litheBuild` requests, receives no function calls, and its function requests are answered with `-32601`. @@ -2908,13 +3182,17 @@ per workspace context: - A backend that answers `version: 1` keeps working unchanged: version 2 only adds host services. A backend that answers `version: 2` keeps working unchanged: version 3 only adds methods, notifications, the call - context, and failure codes and details, all of which it never sees. + context, and failure codes and details, all of which it never sees. A + backend that answers `version: 3` keeps working unchanged: version 4 only + adds the relay methods, which it must not call, and the `caller` field + of a relayed call, which it never receives. - `requires.backend: 1` packages keep their meaning; a new behavior of the backend capability is `backend` 2, never a silent change of version 1. - `fixtures/backend/function-protocol.json` holds the golden cases, including the - host requests (`hostRequests`), call contexts (`invocationContexts`), host - failure codes (`hostFailures`), and host notifications - (`hostNotifications`). Rust Core tests run them, and a scripted backend covers routing, result, failure, cancellation, + host requests (`hostRequests`), call contexts (`invocationContexts`), the + caller of a relayed call (`invocationCallers`), host + failure codes (`hostFailures`), relay failure codes (`relayErrors`), and + host notifications (`hostNotifications`). Rust Core tests run them, and a scripted backend covers routing, result, failure, cancellation, deadline, late reply, revocation, and compatibility with a build-only backend. @@ -3012,6 +3290,9 @@ command payload is a Core `invalid_request` failure instead. | `plugin.function.invalidReference`, `plugin.function.invalidParams`, `plugin.function.unavailable`, `plugin.function.wrongPlugin`, `plugin.function.unknown` | Core | A [plugin-function](#plugin-functions) call is refused before it reaches the backend | | `plugin.function.failed`, `plugin.function.invalidResult`, `plugin.function.revoked` | Core | A plugin-function call ended without a usable result | | `plugin.function.invalidRegistration` | Core | A backend's register or unregister request was refused as a whole | +| `plugin.function.notDeclared`, `plugin.function.notExported`, `plugin.function.providerDisabled`, `plugin.function.versionMismatch` | Core | A [relayed call](#cross-plugin-calls-protocol-version-4) is refused: the caller did not declare it, the provider does not export (or has not registered) the function, the provider is not enabled, or the declared and exported versions differ | +| `plugin.function.callCycle`, `plugin.function.depthExceeded`, `plugin.function.tooManyCalls`, `plugin.function.payloadTooLarge` | Core | A relayed call is refused by a bound: the provider is already on the call chain, the chain is too long, the caller has too many relayed calls running, or the params or result are too large | +| `plugin.function.providerUnavailable` | Core | The provider's backend did not start in time, exited, or withdrew the function while a relayed call waited for it | | `plugin.project.unavailable` | Core | The plugin declares no such project generator | | `plugin.project.invalidInput` | Core | The project name or a field value is not accepted; `field` is `projectName` or `values.`, or a step whose expanded path leaves the project | | `plugin.project.templateInvalid` | Core | A template directory is missing, too large, contains a symbolic link or non-UTF-8 file, or uses an unknown variable | diff --git a/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json b/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json index 89cf0f6cf5..e77c105f5d 100644 --- a/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json +++ b/shared/contracts/plugins/v1/fixtures/backend/function-protocol.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "protocol": "litheFunctions", - "offer": { "versions": [1, 2, 3] }, + "offer": { "versions": [1, 2, 3, 4] }, "negotiation": [ { "name": "no answer leaves the protocol off", @@ -46,9 +46,14 @@ "capabilities": { "experimental": { "litheFunctions": { "version": 3, "functions": [{ "id": "query.run" }] } } }, "expected": { "functions": ["query.run"], "version": 3 } }, + { + "name": "version 4 negotiates the same registry and adds the cross-plugin relay", + "capabilities": { "experimental": { "litheFunctions": { "version": 4, "functions": [{ "id": "query.run" }] } } }, + "expected": { "functions": ["query.run"], "version": 4 } + }, { "name": "a version the host never offered is not negotiated", - "capabilities": { "experimental": { "litheFunctions": { "version": 4 } } }, + "capabilities": { "experimental": { "litheFunctions": { "version": 5 } } }, "expected": { "functions": null } }, { @@ -543,7 +548,78 @@ {"name": "terminal aggregate grant cannot authorize terminal creation", "version": 3, "hostServices": ["terminal"], "method": "lithe/host/terminal/create", "params": {}, "expected": {"code": "plugin.host.permissionDenied", "rpcCode": -32010}}, {"name": "an older protocol cannot create a native terminal", "version": 2, "hostServices": ["lithe/host/terminal/create"], "method": "lithe/host/terminal/create", "params": {}, "expected": {"code": "plugin.host.unavailable", "rpcCode": -32601}}, {"name": "terminal reopen is granted on protocol 3", "version": 3, "hostServices": ["lithe/host/terminal/reopen"], "method": "lithe/host/terminal/reopen", "params": {"context": {"contextID": "w-terminal", "generation": 1}, "terminalID": "owned"}, "expected": {"forward": "terminal"}}, - {"name": "terminal dispose is granted on protocol 3", "version": 3, "hostServices": ["lithe/host/terminal/dispose"], "method": "lithe/host/terminal/dispose", "params": {"context": {"contextID": "w-terminal", "generation": 1}, "terminalID": "owned"}, "expected": {"forward": "terminal"}} + {"name": "terminal dispose is granted on protocol 3", "version": 3, "hostServices": ["lithe/host/terminal/dispose"], "method": "lithe/host/terminal/dispose", "params": {"context": {"contextID": "w-terminal", "generation": 1}, "terminalID": "owned"}, "expected": {"forward": "terminal"}}, + {"name": "a declared caller lists the providers of a function", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/providers", "params": {"functionID": "languageImport.settings"}, "expected": {"relay": true}}, + {"name": "a declared caller invokes another plugin's function through the relay", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000}, "expected": {"relay": true}}, + {"name": "a nested invocation names the relayed call it belongs to", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000, "parentOperationID": "17"}, "expected": {"relay": true}}, + {"name": "an invocation's parent operation ID is a string", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000, "parentOperationID": 17}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "the relay needs protocol version 4", "version": 3, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}}, "expected": {"rpcCode": -32601, "code": "plugin.host.unavailable"}}, + {"name": "the relay needs the manifest's pluginFunctions calls", "version": 4, "hostServices": [], "method": "lithe/host/functions/providers", "params": {"functionID": "languageImport.settings"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "an invocation names the workspace context it runs in", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "an invocation's function ID is well formed", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "Not-Valid", "context": {"contextID": "w1", "generation": 1}}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "an invocation's params are an object", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": [1]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "an invocation's timeout is positive", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "timeoutMilliseconds": 0}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a caller cannot choose who the callee thinks called", "version": 4, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "caller": {"pluginID": "dev.lithe.fixture.other"}}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "caller"}}} + ], + "invocationCallers": [ + { + "name": "a version 4 callee receives the plugin that called it", + "version": 4, + "params": { "functionID": "languageImport.settings", "operationID": "7", "params": {} }, + "caller": "dev.lithe.fixture.python", + "expected": { + "params": { + "functionID": "languageImport.settings", + "operationID": "7", + "params": {}, + "caller": { "pluginID": "dev.lithe.fixture.python" } + } + } + }, + { + "name": "an older callee never receives a caller", + "version": 3, + "params": { "functionID": "languageImport.settings", "operationID": "7", "params": {} }, + "caller": "dev.lithe.fixture.python", + "expected": { "params": { "functionID": "languageImport.settings", "operationID": "7", "params": {} } } + }, + { + "name": "a call the host started has no caller, which means the host", + "version": 4, + "params": { "functionID": "languageImport.settings", "operationID": "7", "params": {} }, + "expected": { "params": { "functionID": "languageImport.settings", "operationID": "7", "params": {} } } + }, + { + "name": "Core's caller replaces any field the params already carried", + "version": 4, + "params": { "functionID": "languageImport.settings", "operationID": "7", "params": {}, "caller": { "pluginID": "dev.lithe.fixture.other" } }, + "caller": "dev.lithe.fixture.python", + "expected": { + "params": { + "functionID": "languageImport.settings", + "operationID": "7", + "params": {}, + "caller": { "pluginID": "dev.lithe.fixture.python" } + } + } + } + ], + "relayErrors": [ + { "name": "the caller did not declare the call", "code": "plugin.function.notDeclared", "rpcCode": -32027 }, + { "name": "the provider does not export the function", "code": "plugin.function.notExported", "rpcCode": -32028 }, + { "name": "the provider is not enabled", "code": "plugin.function.providerDisabled", "rpcCode": -32029 }, + { "name": "the declared and exported contract versions differ", "code": "plugin.function.versionMismatch", "rpcCode": -32030 }, + { "name": "the provider is already on the call chain", "code": "plugin.function.callCycle", "rpcCode": -32065 }, + { "name": "the call chain is too long", "code": "plugin.function.depthExceeded", "rpcCode": -32066 }, + { "name": "the caller has too many relayed calls running", "code": "plugin.function.tooManyCalls", "rpcCode": -32067 }, + { "name": "the params or result exceed the relay's bound", "code": "plugin.function.payloadTooLarge", "rpcCode": -32068 }, + { "name": "the provider's backend could not serve the call", "code": "plugin.function.providerUnavailable", "rpcCode": -32069 }, + { "name": "the provider's function answered with an error", "code": "plugin.function.failed", "rpcCode": -32070 }, + { "name": "the provider answered without a result Core can pass on", "code": "plugin.function.invalidResult", "rpcCode": -32071 }, + { "name": "the relay's own deadline passed", "code": "plugin.host.timeout", "rpcCode": -32015 }, + { "name": "the caller or an upstream caller cancelled", "code": "plugin.host.cancelled", "rpcCode": -32800 }, + { "name": "the workspace context is unknown or replaced", "code": "plugin.host.contextExpired", "rpcCode": -32011 }, + { "name": "the workspace is remote", "code": "plugin.host.authorityUnsupported", "rpcCode": -32012 } ], "invocationContexts": [ { diff --git a/shared/contracts/plugins/v1/fixtures/backend/plugin-functions-caller.plugin.json b/shared/contracts/plugins/v1/fixtures/backend/plugin-functions-caller.plugin.json new file mode 100644 index 0000000000..301571b76f --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/backend/plugin-functions-caller.plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 2, + "id": "dev.lithe.fixture.functioncaller", + "displayName": "Plugin function caller fixture", + "version": "1.0.0", + "pluginAPIVersion": 3, + "requires": {"pluginFunctions": 1, "backend": 2, "serverProcess": 1}, + "vendor": {"id": "org.example", "displayName": "Fixture publisher", "signatureRequirement": "publisherPackage"}, + "permissions": ["backend.launch"], + "activationEvents": ["onWorkspaceOpen"], + "pluginFunctions": { + "calls": [ + {"id": "document.format", "version": 1} + ] + }, + "backend": {"launch": {"kind": "packaged", "path": "bin/backend"}, "arguments": ["--stdio"]} +} diff --git a/shared/contracts/plugins/v1/fixtures/backend/plugin-functions-exporter.plugin.json b/shared/contracts/plugins/v1/fixtures/backend/plugin-functions-exporter.plugin.json new file mode 100644 index 0000000000..dedf1e4ca6 --- /dev/null +++ b/shared/contracts/plugins/v1/fixtures/backend/plugin-functions-exporter.plugin.json @@ -0,0 +1,17 @@ +{ + "schemaVersion": 2, + "id": "dev.lithe.fixture.functionexporter", + "displayName": "Plugin function exporter fixture", + "version": "1.0.0", + "pluginAPIVersion": 3, + "requires": {"pluginFunctions": 1, "backend": 2, "serverProcess": 1}, + "vendor": {"id": "org.example", "displayName": "Fixture publisher", "signatureRequirement": "publisherPackage"}, + "permissions": ["backend.launch"], + "pluginFunctions": { + "exports": [ + {"id": "document.format", "version": 1, "context": "workspace"}, + {"id": "symbols.list", "version": 2, "context": "workspace"} + ] + }, + "backend": {"launch": {"kind": "packaged", "path": "bin/backend"}, "arguments": ["--stdio"]} +} diff --git a/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json b/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json index ea6647ec3f..6e2c416541 100644 --- a/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/contracts/plugins/v1/fixtures/manifest/invalid-manifests.json @@ -1055,6 +1055,18 @@ {"name": "a grammar names a known engine", "base": "language-grammar.plugin.json", "edits": [{"op": "set", "path": "/languages/0/grammar/kind", "value": "textmate"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a grammar file stays in the package", "base": "language-grammar.plugin.json", "edits": [{"op": "set", "path": "/languages/0/grammar/path", "value": "../http.monarch.json"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a comment delimiter is one short line", "base": "language-grammar.plugin.json", "edits": [{"op": "set", "path": "/languages/0/configuration/lineComment", "value": "#\n"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an export states its calling context", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "remove", "path": "/pluginFunctions/exports/0/context"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an export names a context Lithe knows", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0/context", "value": "remote"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an export is an object, not a bare function ID", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0", "value": "document.format"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an export version is a positive integer", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0/version", "value": 0}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a function is exported once", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/1/id", "value": "document.format"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "an exported function ID is lowerCamelCase segments", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/exports/0/id", "value": "Document.Format"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a call states the contract version it was written for", "base": "plugin-functions-caller.plugin.json", "edits": [{"op": "remove", "path": "/pluginFunctions/calls/0/version"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "a call never names the provider plugin", "base": "plugin-functions-caller.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions/calls/0/pluginID", "value": "dev.lithe.fixture.functionexporter"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "exported and called functions need backend 2", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/requires/backend", "value": 1}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "pluginFunctions lists an export or a call", "base": "plugin-functions-exporter.plugin.json", "edits": [{"op": "set", "path": "/pluginFunctions", "value": {}}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "pluginFunctions is listed in requires", "base": "plugin-functions-caller.plugin.json", "edits": [{"op": "remove", "path": "/requires/pluginFunctions"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "requires lists pluginFunctions only when the manifest uses it", "base": "plugin-functions-caller.plugin.json", "edits": [{"op": "remove", "path": "/pluginFunctions"}], "expectedCode": "plugin.manifest.invalid"}, {"name": "editor providers read the documents they answer for", "base": "editor-providers.plugin.json", "edits": [{"op": "set", "path": "/permissions", "value": ["backend.launch", "editor.providers", "workspace.metadata"]}], "expectedCode": "plugin.manifest.invalid"}, {"name": "a tool field needs projectGenerators 2", "base": "project-generator.plugin.json", "edits": [{"op": "set", "path": "/projectGenerators/0/fields/1", "value": {"id": "sdk", "type": "tool", "title": "SDK", "tool": "python"}}], "expectedCode": "plugin.manifest.invalid"}, {"name": "projectGenerators 2 has no runtime field", "base": "project-generator.plugin.json", "edits": [{"op": "set", "path": "/requires/projectGenerators", "value": 2}], "expectedCode": "plugin.manifest.invalid"}, diff --git a/shared/contracts/plugins/v1/plugin-manifest.schema.json b/shared/contracts/plugins/v1/plugin-manifest.schema.json index dfb7ef9292..2e2baff2d5 100644 --- a/shared/contracts/plugins/v1/plugin-manifest.schema.json +++ b/shared/contracts/plugins/v1/plugin-manifest.schema.json @@ -20,6 +20,7 @@ }, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"pluginAPIVersion": {"minimum": 3}, "requires": {"required": ["toolDefinitions", "executableResolution"], "properties": {"executableResolution": {"const": 2}}}}}}, {"if": {"required": ["toolchainProviders"]}, "then": {"required": ["backend"], "properties": {"pluginAPIVersion": {"minimum": 3}, "requires": {"required": ["toolchainProviders", "backend", "serverProcess"], "properties": {"backend": {"const": 2}}}, "permissions": {"allOf": [{"contains": {"const": "toolchains.provide"}}, {"contains": {"const": "backend.launch"}}]}}}}, + {"if": {"required": ["pluginFunctions"]}, "then": {"required": ["backend"], "properties": {"pluginAPIVersion": {"minimum": 3}, "requires": {"required": ["pluginFunctions", "backend", "serverProcess"], "properties": {"backend": {"const": 2}}}}}}, {"if": {"required": ["keymapImportProviders"]}, "then": {"required": ["backend", "permissions"], "properties": {"pluginAPIVersion": {"minimum": 3}, "requires": {"required": ["keymapImportProviders", "backend", "serverProcess"], "properties": {"backend": {"const": 2}}}, "permissions": {"allOf": [{"contains": {"const": "keymaps.provide"}}, {"contains": {"const": "keymaps.readSelectedSources"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["requires"], "properties": {"requires": {"required": ["settings"], "properties": {"settings": {"const": 2}}}}}, "else": {"properties": {"settings": {"items": {"$ref": "#/$defs/settingVersion1"}}, "settingActions": {"maxItems": 0}}}}, {"if": {"required": ["requires"], "properties": {"requires": {"required": ["languageServers"], "properties": {"languageServers": {"const": 2}}}}}, "else": {"properties": {"languageServers": {"items": {"properties": {"workspaceConfiguration": false}}}}}} @@ -52,6 +53,7 @@ "toolDefinitions": { "const": 1 }, "toolchainProviders": { "const": 1 }, "keymapImportProviders": { "const": 1 }, + "pluginFunctions": { "description": "Required exactly when pluginFunctions is present: functions this plugin's backend exports to other plugins, and exported functions it calls. Needs backend 2 (litheFunctions protocol 4).", "const": 1 }, "ui": { "description": "Version 2 adds web content; version 3 adds native controls; version 4 adds backend-only commands.", "enum": [1, 2, 3, 4] }, "vcsProviders": { "description": "Required exactly when vcsProviders is non-empty. The provider protocol itself is negotiated in initialize (shared/contracts/vcs-provider-v1.md).", "enum": [1] } } @@ -100,6 +102,7 @@ "toolDefinitions": { "type": "array", "minItems": 1, "maxItems": 32, "items": { "$ref": "#/$defs/toolchainToolDefinition" } }, "toolchainProviders": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "$ref": "#/$defs/toolchainProvider" } }, "keymapImportProviders": { "type": "array", "minItems": 1, "maxItems": 8, "items": { "$ref": "#/$defs/keymapImportProvider" } }, + "pluginFunctions": { "$ref": "#/$defs/pluginFunctions" }, "languages": { "type": "array", "minItems": 0, @@ -269,6 +272,41 @@ } }, "$defs": { + "pluginFunctionID": { + "description": "Dot-separated lowerCamelCase segments, for example document.format.", + "type": "string", + "maxLength": 128, + "pattern": "^[a-z][a-zA-Z0-9]*(\\.[a-z][a-zA-Z0-9]*)*$" + }, + "pluginFunctions": { + "description": "Functions this plugin exports to other plugins and exported functions it calls. A function is private to its plugin unless it is exported here and registered at runtime with lithe/function/register; calling it takes no permission, because the receiver's export and the caller's declaration are the consent. The called function runs with the receiver's own permissions.", + "type": "object", + "additionalProperties": false, + "minProperties": 1, + "properties": { + "exports": { "type": "array", "minItems": 1, "maxItems": 32, "items": { "$ref": "#/$defs/pluginFunctionExport" } }, + "calls": { "type": "array", "minItems": 1, "maxItems": 32, "items": { "$ref": "#/$defs/pluginFunctionCall" } } + } + }, + "pluginFunctionExport": { + "type": "object", + "additionalProperties": false, + "required": ["id", "version", "context"], + "properties": { + "id": { "$ref": "#/$defs/pluginFunctionID" }, + "version": { "description": "Version of the function's input and result contract; an incompatible change uses a new version.", "type": "integer", "minimum": 1, "maximum": 1000 }, + "context": { "description": "The one calling context the function accepts. workspace: a local trusted workspace, scheduled by the host. An export without a context Lithe knows is refused.", "enum": ["workspace"] } + } + }, + "pluginFunctionCall": { + "type": "object", + "additionalProperties": false, + "required": ["id", "version"], + "properties": { + "id": { "$ref": "#/$defs/pluginFunctionID" }, + "version": { "description": "The export contract version this plugin was written for; Core refuses a provider that exports another version.", "type": "integer", "minimum": 1, "maximum": 1000 } + } + }, "keymapImportProvider": { "type": "object", "additionalProperties": false, diff --git a/shared/contracts/rust-core-api.md b/shared/contracts/rust-core-api.md index f199c5a805..8aa74f381f 100644 --- a/shared/contracts/rust-core-api.md +++ b/shared/contracts/rust-core-api.md @@ -1236,6 +1236,7 @@ package manager owns the download and Lithe does not infer bytes from logs. | `lsp.functionRequest` | Invoke one registered plugin function on a session its plugin started | | `lsp.hostResponse` | Answer one host-service request a plugin backend sent | | `lsp.hostNotify` | Send one host notification to a plugin backend that negotiated it | +| `lsp.configureFunctionRelay` | Replace the enabled plugins and live workspace contexts Core's plugin-to-plugin function relay checks calls against | | `lsp.toolchainRequest` | Send one `toolchains/query` to a plugin backend that negotiated the provider | | `lsp.keymapImportRequest` | Send one shortcut import request to a negotiated plugin provider | | `lsp.vcsRequest` | Send one VCS operation, planned by Core, to a session that negotiated the VCS-provider protocol | @@ -3512,6 +3513,42 @@ ungranted service, malformed or oversized params, a session that is not plugin-owned, or one that is not ready is `invalid_request` with the `plugin.host.*` code in `details`. +A session that negotiated `litheFunctions` version 4 and holds the `functions` +grant may call another plugin's exported function through the +[plugin-to-plugin relay](plugins/v1/README.md#cross-plugin-calls-protocol-version-4). +Core runs the whole relay: it checks the declarations, keeps the call chain, +writes the forwarded request, and answers the caller. `lsp.configureFunctionRelay` +accepts the host's complete view and returns `{}`; every call replaces the +previous view, and a call in flight that the new view forbids ends with an +explicit `plugin.function.*` error. + +```json +{ + "plugins": [ + { + "pluginID": "dev.example.formatter", + "exports": [{ "id": "document.format", "version": 1, "context": "workspace" }], + "calls": [] + } + ], + "contexts": [{ "contextID": "w-1", "generation": 1, "authority": "local" }] +} +``` + +- `plugins` lists the enabled plugins that declare `pluginFunctions`, and each + `exports` and `calls` is the normalized manifest's own list. The host + copies them and does not interpret them. A plugin that is disabled, + replaced, or removed is left out, which ends its calls. +- `contexts` lists the live workspace contexts; `authority` is `local` or + `remote`, and a call in a remote workspace is refused. +- A malformed snapshot (an unknown field, a bad plugin or function ID, a + duplicate plugin, more than 4096 plugins) is `invalid_request`. +- Core publishes the runtime event `functionProviderStartRequired` with + `result: { pluginID }` on the calling plugin's session when a call waits for + a callee whose backend is not running. The host starts that backend as plain + I/O; Core ends the call with `plugin.function.providerUnavailable` if the + callee does not register the function within 30 seconds. + `lsp.request` accepts a semantic `operation` plus the operation-specific URI, position, range, diagnostics, item, action, or command fields, and returns `{ operationId }`. Supported operations include diff --git a/shared/platform-feature-matrix/features/plugin-cross-plugin-function-calls.json b/shared/platform-feature-matrix/features/plugin-cross-plugin-function-calls.json new file mode 100644 index 0000000000..c1140d1cf7 --- /dev/null +++ b/shared/platform-feature-matrix/features/plugin-cross-plugin-function-calls.json @@ -0,0 +1,33 @@ +{ + "id": "plugin-cross-plugin-function-calls", + "area": "扩展", + "group": "插件与主题", + "capability": "插件函数的跨插件调用(API-35 第一阶段):插件在清单 pluginFunctions 里导出 {id, version, context} 函数、声明要调用的 {id, version}(requires.pluginFunctions 1);协商到 litheFunctions 4 的后端经 lithe/host/functions/providers 发现、经 lithe/host/functions/invoke 调用,全部由 Rust Core 中转:声明、导出、双方启用、版本相等、调用链无环、深度、并发、参数与结果大小、超时、沿链取消、远程工作区拒绝;被调方不运行时 Core 只发 functionProviderStartRequired,由宿主启动其后端;被调方信任不传递,Core 在转发请求里写入 caller.pluginID;旧的 wrongPlugin 与 recursiveCall 检查不变", + "macos": { + "implementationStatus": "partial", + "verificationStatus": "pending", + "evidence": [ + "rust/lithe-core/src/lsp/interface/function_relay.rs", + "rust/lithe-core/src/lsp/interface/engine_function_relay.rs", + "rust/lithe-core/src/plugins/plugin_functions.rs", + "shared/contracts/plugins/v1/README.md", + "shared/contracts/plugins/v1/fixtures/backend/function-protocol.json", + "shared/contracts/plugins/v1/fixtures/backend/plugin-functions-exporter.plugin.json", + "shared/contracts/plugins/v1/fixtures/backend/plugin-functions-caller.plugin.json", + "macos/Sources/Lithe/Platform/MacOS/Plugins/MacPluginBackendSessions.swift", + "macos/Sources/Lithe/Application/Features/PluginHostServiceDispatch.swift", + "macos/Tests/LitheTests/MacPluginBackendSessionsTests.swift", + "macos/Tests/LitheTests/PluginPublicHostAPITests.swift" + ] + }, + "windows": { + "implementationStatus": "missing", + "verificationStatus": "not-applicable", + "evidence": [ + "shared/contracts/plugins/v1/README.md" + ] + }, + "owner": "Extensions", + "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core plugins::plugin_functions、lsp::interface::function_relay、lsp::interface::engine、declarative_plugins,核对 function-protocol.json 的 hostRequests/relayErrors/invocationCallers 与 plugin-functions-exporter/caller 夹具(含 context 缺失或未知、重复导出、requires 与 pluginFunctions 不一致的无效清单);用脚本化后端以一个 Python 插件调用一个 Go 插件的导出,覆盖发现与调用、每个拒绝码及其先后顺序、旧的 wrongPlugin 与 recursiveCall 仍然成立、调用链(自调与回环被拒)、沿链取消、被调方超时与退出、被调方未运行时的启动请求与 30 秒上限、禁用被调方后进行中调用以明确错误结束、caller 字段只给协议 4 的被调方且调用方伪造被拒、协议 3 后端与未声明调用的插件被拒。深度上限与每个调用方的并发上限只由纯逻辑单测覆盖。macOS 宿主:scripts/macos/test/test-macos.sh --filter \"MacPluginBackendSessionsTests|PluginHostServiceDispatchTests|PluginPublicHostAPITests\",覆盖快照发布、functionProviderStartRequired 到后端启动的 I/O 接线与 functions 服务授权。契约:./scripts/architecture/verify-shared-contracts.sh。官方 SDK 回归:在 lithe-plugin-docs 运行 node scripts/sdk-e2e.mjs --source <本仓库路径> --ref <分支>。macOS 原生验收:debug 应用安装两个声明了 pluginFunctions 的示例插件(一个导出、一个调用,各带 backend 2),打开本地工作区,调用方经 providers 发现被调方并 invoke,核对结果与 caller.pluginID;被调方后端未运行时由调用触发启动;禁用被调方后进行中调用以 plugin.function.providerDisabled 结束;打开远程工作区应得到 plugin.host.authorityUnsupported;结束后用 pgrep 确认两个后端不残留。", + "notes": "本条是 API-35 的第一阶段,只解决两个已安装、已启用的插件之间调用被明确导出的函数;不含安装期依赖解析、版本冲突、依赖闭包、跨包资源租约或会启动程序的导出,见提议 Note 2026-10-25-plugin-dependencies-and-exports。没有新增权限项:调用方的 calls 与被调方的 exports 是双方的同意。macOS 尚未做原生验收,所以验证状态为待验证。带后端的插件在 macOS 上仍只在启动时注册,新安装或更新的后端插件要重启后才出现在发现结果里,禁用、启用、替换和卸载是即时的,免重启激活属于 #1515 的后续工作。中转使用单个工作线程,被调方管道被写满时后续中转调用会排队等到各自截止。Windows/Tauri 尚无插件后端宿主,不广告 pluginFunctions,所以声明它的插件在 Windows 上会被拒绝,Windows 行为不变;Core 中转逻辑与平台无关,以后接入后端宿主即可复用。" +} diff --git a/shared/platform-feature-matrix/features/plugin-functions.json b/shared/platform-feature-matrix/features/plugin-functions.json index 3e672db009..e4b6a72efd 100644 --- a/shared/platform-feature-matrix/features/plugin-functions.json +++ b/shared/platform-feature-matrix/features/plugin-functions.json @@ -28,5 +28,5 @@ }, "owner": "Extensions", "verification": "共享 Core:cargo test --manifest-path rust/Cargo.toml -p lithe-core --lib plugin_function 及 --lib lsp::interface::engine,核对共享 fixture、初始化发现事件、动态增删、归属拒绝、结果与插件错误码、超时取消撤回。插件会话成功完成 initialize 函数协议协商后发布初始 functionsChanged(含空注册表),无 pluginId 的宿主会话不协商、不保留或广播函数。每次后端调用使用唯一且不透明的 operationID,进度转换回宿主 operationId,所有终止路径清除关联;复用宿主 ID 后,旧进度与撤回不得影响新函数或构建请求。后端请求 lithe/function/invoke 或 lithe/build/* 时拒绝递归派发,lithe/host/* 在 v1 全部拒绝。平台验收:宿主接入后,从同一插件的界面发现并调用函数,验证另一插件无法调用、终止后的旧进度不污染新调用,关闭项目和停用插件后不残留进程;分别在 macOS 和 Windows 完成原生验收后才标记 verified。 macOS 宿主:scripts/macos/test/test-macos.sh --filter \"PluginWebBridgeTests|MacBuildProviderSessionsTests\",覆盖插件网页只能访问本插件实例并经同意、结果/进度/pluginErrorCode 到达页面、取消与关闭页面取消函数、构建 Provider 以插件会话启动并带 pluginId、Core 拒绝码原样保留、停用插件停止 Provider。 macOS 原生验收:debug 应用安装带网页窗口的 sample-build(PR #1365)与另一个带构建系统的插件,在示例工作区的页面上依次调用 functions.list、functions.invoke(带 call 观察 functions.progress)、functions.cancel,核对结果与 pluginErrorCode;从另一插件页面访问该实例应得到 plugin.web.forbidden;调用进行中关闭项目、停用插件后用 pgrep 确认 Provider 与构建子进程不残留。 官方 SDK(在 lithe-plugin-docs 仓库中运行):node --test sdk/node/test/*.test.mjs;mvn -B -f sdk/java/pom.xml verify(CI 以 -Djvm 指向 Java 8 运行测试);cargo +1.87 test --locked --manifest-path sdk/rust/Cargo.toml;node scripts/sdk-e2e.mjs 把 sdk/e2e 复制进契约副本锁定的主仓库 commit 并运行 plugin_sdk_node、plugin_sdk_java、plugin_sdk_rust:Node 与 Java 示例插件经真实 Core 会话完成构建模型/依赖、函数结果/进度/失败/取消、重启恢复状态,Java 示例按插件打包形态(plugin.json + shade 后的 JAR)运行;Rust 示例后端按 packaged 启动计划运行,完成函数结果/进度/失败/取消、宿主请求(测试扮演宿主应答 hostRequest:凭据,以及协议 3 的工作区、文件监视订阅与窗口消息,过期上下文与取消转发的 $/cancelRequest)、命令与工作区变化通知、重启恢复状态与未授权时的拒绝;三者插件包文件清单都不变;CI 每周再以 --ref HEAD 对主仓库最新 Core 运行一次。", - "notes": "macOS 已接入宿主入口:插件网页通过 functions.list / functions.invoke / functions.cancel 调用自己构建 Provider 进程的函数,共享语言服务器不提供函数;2026-10-20 已在 macOS debug 应用中用 Node SDK 的示例插件 sample-build(PR #1365,当时在主仓库 sdk/node/examples,加一个只用于验收的网页窗口)完成原生验收:functions.list/invoke 的结果、functions.progress、动态注册的 snapshot.clear、pluginErrorCode(sample.buildFailed)、取消后的 requestCancelled 都到达页面,取消会结束构建子进程;另一插件的页面访问该实例得到 plugin.web.forbidden;调用进行中关闭项目或停用插件后 Provider 及其子进程均不残留。Windows 尚无插件后端宿主;不能以共享测试通过替代平台功能验收。函数不新增清单字段,不改变 pluginAPIVersion 或 requires;litheBuild v1 与旧后端继续独立工作,lithe/host/* 暂不开放,协议不提供操作系统级沙盒。 官方 Node SDK(lithe-plugin-docs 的 sdk/node)只实现契约、不新增线上字段,进程树清理在 POSIX 由端到端测试覆盖,Windows 的 taskkill 路径尚未在 Windows 上验证。 官方 Java SDK(lithe-plugin-docs 的 sdk/java)同样只实现契约;Java 9+ 取消时结束整棵进程树,Java 8 只结束直接子进程,其余由宿主的后端进程标记兜底;目前只经共享 Core 端到端验证,macOS 原生验收随 Maven 插件的 Java 后端一起完成。运行时启动计划的 java 版本探测改用 -version,Java 8 后端不再被误判为不可用。 官方 Rust SDK(lithe-plugin-docs 的 sdk/rust)同样只实现契约,用于 packaged 插件后端:实现函数协议及其宿主服务,不含构建与 VCS Provider;目前只经共享 Core 端到端验证。" + "notes": "macOS 已接入宿主入口:插件网页通过 functions.list / functions.invoke / functions.cancel 调用自己构建 Provider 进程的函数,共享语言服务器不提供函数;2026-10-20 已在 macOS debug 应用中用 Node SDK 的示例插件 sample-build(PR #1365,当时在主仓库 sdk/node/examples,加一个只用于验收的网页窗口)完成原生验收:functions.list/invoke 的结果、functions.progress、动态注册的 snapshot.clear、pluginErrorCode(sample.buildFailed)、取消后的 requestCancelled 都到达页面,取消会结束构建子进程;另一插件的页面访问该实例得到 plugin.web.forbidden;调用进行中关闭项目或停用插件后 Provider 及其子进程均不残留。Windows 尚无插件后端宿主;不能以共享测试通过替代平台功能验收。函数不新增清单字段,不改变 pluginAPIVersion 或 requires;litheBuild v1 与旧后端继续独立工作,lithe/host/* 暂不开放,协议不提供操作系统级沙盒。 官方 Node SDK(lithe-plugin-docs 的 sdk/node)只实现契约、不新增线上字段,进程树清理在 POSIX 由端到端测试覆盖,Windows 的 taskkill 路径尚未在 Windows 上验证。 官方 Java SDK(lithe-plugin-docs 的 sdk/java)同样只实现契约;Java 9+ 取消时结束整棵进程树,Java 8 只结束直接子进程,其余由宿主的后端进程标记兜底;目前只经共享 Core 端到端验证,macOS 原生验收随 Maven 插件的 Java 后端一起完成。运行时启动计划的 java 版本探测改用 -version,Java 8 后端不再被误判为不可用。 官方 Rust SDK(lithe-plugin-docs 的 sdk/rust)同样只实现契约,用于 packaged 插件后端:实现函数协议及其宿主服务,不含构建与 VCS Provider;目前只经共享 Core 端到端验证。 跨插件调用(litheFunctions 4、pluginFunctions 清单、lithe/host/functions/*)单独记录在 plugin-cross-plugin-function-calls;本条描述的私有函数、lithe/host/* 在协议 1 全部拒绝等行为不变。" }