From 1e7fdf3a134a764017a03fa873d7ad9a2b788b82 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 10:38:58 +0530 Subject: [PATCH 01/32] Add a nix flake, remove default.nix Pin streamly-core-0.3.3 and streamly-0.11.1 (Hackage revision 3, which allows streamly-core < 0.3.4). --- default.nix | 207 --------------------------------------------------- flake.lock | 88 ++++++++++++++++++++++ flake.nix | 17 +++++ packages.nix | 8 ++ sources.nix | 20 +++++ 5 files changed, 133 insertions(+), 207 deletions(-) delete mode 100644 default.nix create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 packages.nix create mode 100644 sources.nix diff --git a/default.nix b/default.nix deleted file mode 100644 index c89a385..0000000 --- a/default.nix +++ /dev/null @@ -1,207 +0,0 @@ -# CAUTION! a spelling mistake in arg string is ignored silently. -# -# nix-build --arg static true -# vector takes too much memory in compiling tests. We need to disable tests to -# build it. -# nix-build --arg static true --arg nixpkgs 'import ~/third-party/nixpkgs {}' - -{ - nixpkgs ? - import - (builtins.fetchTarball - https://github.com/composewell/nixpkgs/archive/refs/tags/22.05-composewell.tar.gz - ) - {} -, compiler ? "ghc922" -, c2nix ? "" # cabal2nix CLI options -, static ? false -}: -let - # we can possibly avoid adding our package to HaskellPackages like - # in the case of nix-shell for a single package? - mkPackage = super: pkg: path: opts: inShell: - let orig = super.callCabal2nixWithOptions pkg path opts {}; - in if inShell - # When in shell, avoid copying the source directory - # to nix store by using src = null. - then orig.overrideAttrs (oldAttrs: { src = null; }) - else orig; - - flags = "--benchmark --flag fusion-plugin" + " " + c2nix; - - mkHaskellPackages = pkgs: hpkgs: inShell: - hpkgs.override { - overrides = self: super: - with pkgs.haskell.lib; - { - simple-rpc-setup = - pkgs.haskell.lib.overrideCabal - (mkPackage super "simple-rpc-setup" ./setup/. flags inShell) - (old: - { enableLibraryProfiling = false; - doHaddock = false; - }); - - simple-rpc-generate = - pkgs.haskell.lib.overrideCabal - (mkPackage super "simple-rpc-generate" ./generate/. flags inShell) - (old: - { enableLibraryProfiling = false; - doHaddock = false; - }); - - simple-rpc = - pkgs.haskell.lib.overrideCabal - (mkPackage super "simple-rpc" ./rpc/. flags inShell) - (old: - { enableLibraryProfiling = false; - doHaddock = false; - }); - - example = - pkgs.haskell.lib.overrideCabal - (mkPackage super "example" ./example/. flags inShell) - (old: - { enableLibraryProfiling = false; - doHaddock = false; - }); - - streamly = - pkgs.haskell.lib.overrideCabal - (super.callHackageDirect - { pkg = "streamly"; - ver = "0.9.0"; - sha256 = "sha256-eOxVb8qQjZDo1+S7CStqYSExOg2QHWkMY+zlOYqwZak="; - } {}) - #(let src = fetchGit { - # url = "git@github.com:composewell/streamly.git"; - # rev = "d33bb110ab5ed6a8cbd8f49e23517df2dbcf3c3b"; - #}; in super.callCabal2nix "streamly" src {}) - (old: - { librarySystemDepends = - if builtins.currentSystem == "x86_64-darwin" - then [pkgs.darwin.apple_sdk.frameworks.Cocoa] - else []; - enableLibraryProfiling = false; - doHaddock = false; - }); - - streamly-core = - pkgs.haskell.lib.overrideCabal - (super.callHackageDirect - { pkg = "streamly-core"; - ver = "0.1.0"; - sha256 = "sha256-hoSV6Q2+X5a7hFnJAArqNPjcMaCVyX9Vz4FcxeJ+jgI="; - } {}) - #pkgs.haskell.lib.overrideCabal - # (let src = fetchGit { - # url = "git@github.com:composewell/streamly.git"; - # rev = "d33bb110ab5ed6a8cbd8f49e23517df2dbcf3c3b"; - # }; in super.callCabal2nix "streamly-core" "${src}/core" {}) - (old: - { librarySystemDepends = - if builtins.currentSystem == "x86_64-darwin" - then [pkgs.darwin.apple_sdk.frameworks.Cocoa] - else []; - enableLibraryProfiling = false; - doHaddock = false; - }); - - streamly-coreutils = - pkgs.haskell.lib.overrideCabal - (let src = fetchGit { - url = "git@github.com:composewell/streamly-coreutils.git"; - rev = "d36e0810b9f091eafaadc183a02de9c0cce6eada"; - }; in super.callCabal2nix "streamly-coreutils" src {}) - (old: - { enableLibraryProfiling = false; - doHaddock = false; - doCheck = false; - }); - - streamly-process = - pkgs.haskell.lib.overrideCabal - (super.callHackageDirect - { pkg = "streamly-process"; - ver = "0.3.0"; - sha256 = "sha256-h0BN+L0nFQqhgnlOk8bbivteqxS7ljhckHA51RLyibk="; - } {}) - #pkgs.haskell.lib.overrideCabal - # (let src = fetchGit { - # url = "git@github.com:composewell/streamly-process.git"; - # rev = "7ef84bddc869c6a7c46fd5e4ef9c1b4a22c301db"; - # }; in super.callCabal2nix "streamly-process" src {}) - (old: - { enableLibraryProfiling = false; - doHaddock = false; - doCheck = false; - }); - - lockfree-queue = - super.callHackageDirect - { pkg = "lockfree-queue"; - ver = "0.2.4"; - sha256 = "1bj9agy3x0yjbscpjgn96gpnj4lvkh39spjvy3jnrr3a42v3ynw7"; - } {}; - - }; - }; - - shell = pkgs: hpkgs: - hpkgs.shellFor { - packages = p: - [ p.simple-rpc - p.simple-rpc-setup - p.simple-rpc-generate - p.example - ]; - doBenchmark = true; - # Use a better prompt - shellHook = '' - export CABAL_DIR="$(pwd)/.cabal.nix" - if test -n "$PS_SHELL" - then - export PS1="$PS_SHELL\[$bldred\](nix)\[$txtrst\] " - fi - ''; - }; - - getHaskellPackages = pkgs: - let h = - if compiler == "default" - then pkgs.haskellPackages - else pkgs.haskell.packages.${compiler}; - in mkHaskellPackages pkgs h false; - - drvBuild = - if static - then - let pkgs = nixpkgs.pkgsMusl; - hpkgs = getHaskellPackages pkgs; - in pkgs.haskell.lib.overrideCabal hpkgs.simple-rpc - (old: - { configureFlags = - [ - "--ghc-option=-optl=-static" - "--extra-lib-dirs=${pkgs.gmp6.override { withStatic = true; }}/lib" - "--extra-lib-dirs=${pkgs.zlib.static}/lib" - "--extra-lib-dirs=${pkgs.libffi.overrideAttrs (old: { dontDisableStatic = true; })}/lib" - "--extra-lib-dirs=${pkgs.ncurses.override { enableStatic = true; }}/lib" - ]; - enableSharedExecutables = false; - enableSharedLibraries = false; - enableLibraryProfiling = false; - doHaddock = false; - }) - else (getHaskellPackages nixpkgs).simple-rpc; - - drvShell = - if static - then - let pkgs = nixpkgs.pkgsMusl; - hpkgs = getHaskellPackages pkgs; - in shell pkgs (getHaskellPackages pkgs) - else shell nixpkgs (getHaskellPackages nixpkgs); -in if nixpkgs.lib.inNixShell - then drvShell - else drvBuild diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..114d59a --- /dev/null +++ b/flake.lock @@ -0,0 +1,88 @@ +{ + "nodes": { + "basepkgs": { + "inputs": { + "basepkgs": "basepkgs_2", + "nixpkgs": "nixpkgs", + "nixpkgs-darwin": "nixpkgs-darwin" + }, + "locked": { + "lastModified": 1776414440, + "narHash": "sha256-Be67u+Qea2sEuI+3BVjkc+o4fYgRT/fOANGNAp2OuFk=", + "ref": "refs/heads/master", + "rev": "69728978adc44f53b3dd907acb2eb5bd2415fd60", + "revCount": 125, + "type": "git", + "url": "ssh://git@github.com/composewell/streamly-packages" + }, + "original": { + "rev": "69728978adc44f53b3dd907acb2eb5bd2415fd60", + "type": "git", + "url": "ssh://git@github.com/composewell/streamly-packages" + } + }, + "basepkgs_2": { + "locked": { + "lastModified": 1776376172, + "narHash": "sha256-tVn1PuKG+kJGH2PUnV3weRHDnbtgUDlwwSC0K3A45aM=", + "owner": "composewell", + "repo": "nixpack", + "rev": "f50a0b2aaaab434f46847bc171240957b508b901", + "type": "github" + }, + "original": { + "owner": "composewell", + "repo": "nixpack", + "rev": "f50a0b2aaaab434f46847bc171240957b508b901", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1774106199, + "narHash": "sha256-US5Tda2sKmjrg2lNHQL3jRQ6p96cgfWh3J1QBliQ8Ws=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6c9a78c09ff4d6c21d0319114873508a6ec01655", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6c9a78c09ff4d6c21d0319114873508a6ec01655", + "type": "github" + } + }, + "nixpkgs-darwin": { + "locked": { + "lastModified": 1774106199, + "narHash": "sha256-US5Tda2sKmjrg2lNHQL3jRQ6p96cgfWh3J1QBliQ8Ws=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6c9a78c09ff4d6c21d0319114873508a6ec01655", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "6c9a78c09ff4d6c21d0319114873508a6ec01655", + "type": "github" + } + }, + "root": { + "inputs": { + "basepkgs": "basepkgs", + "nixpkgs": [ + "basepkgs", + "nixpkgs" + ], + "nixpkgs-darwin": [ + "basepkgs", + "nixpkgs-darwin" + ] + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..c0cefca --- /dev/null +++ b/flake.nix @@ -0,0 +1,17 @@ +{ + description = "simple-rpc"; + + inputs = { + basepkgs.url = "git+ssh://git@github.com/composewell/streamly-packages?rev=69728978adc44f53b3dd907acb2eb5bd2415fd60"; + nixpkgs.follows = "basepkgs/nixpkgs"; + nixpkgs-darwin.follows = "basepkgs/nixpkgs-darwin"; + }; + + outputs = { self, nixpkgs, nixpkgs-darwin, basepkgs }: + basepkgs.nixpack.mkOutputs { + inherit nixpkgs nixpkgs-darwin basepkgs; + name = "simple-rpc"; + sources = import ./sources.nix; + packages = import ./packages.nix; + }; +} diff --git a/packages.nix b/packages.nix new file mode 100644 index 0000000..017cea5 --- /dev/null +++ b/packages.nix @@ -0,0 +1,8 @@ +{ nixpkgs }: +{ +# Haskell dev packages. Install only dependencies of these in the shell, +# do not build the packages themselves. +dev-packages = + with nixpkgs.haskellPackages; + [ simple-rpc simple-rpc-generate example ]; +} diff --git a/sources.nix b/sources.nix new file mode 100644 index 0000000..a5bbccb --- /dev/null +++ b/sources.nix @@ -0,0 +1,20 @@ +{nixpack}: +# Package sources to override the streamly-packages set. +with nixpack.mkSources; +{ +layers = [ +{ + streamly-core = hackage "0.3.3" + "0rrgbk1jmhyzgg39wd2wdli6xqdcb36xmqkqmvix7qy6rjfykicz"; + # Hackage revision 3 allows streamly-core < 0.3.4 + streamly = hackage "0.11.1" + "1dxyhq8m9fr3ghpmxkh6bc37fd4f1048xckjrlpp6ybvlg0lq7g2" + // { rev = "3"; + cabalSha256 = "0xvx6vacr9vlss67qs5v25gbj6xvxjzx4f7w5ck9lr845g57k9ay"; + }; + simple-rpc = local ./rpc; + simple-rpc-generate = local ./generate; + example = local ./example; +} +]; +} From 2251fbadaacd694eac6ff679c768832475f740e6 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 10:56:47 +0530 Subject: [PATCH 02/32] Fix the example to work with the current API Port the example to run/runAt and the RunningConfig setters, use the generated RpcMap in the server, and update the generator config and READMEs to the current config format. --- README.md | 10 ++++++++-- example/app/Main.hs | 28 ++++------------------------ example/app/RpcMap.hs | 26 ++++++++++++++++++++++++++ example/example.cabal | 12 +++--------- example/lib/Module0.hs | 3 ++- example/lib/Module1.hs | 2 +- example/lib/Module2.hs | 2 +- example/lib/Module3.hs | 15 +++++++-------- example/lib/Module4.hs | 17 ++++++++++------- example/plan.json | 2 +- example/rpcConfig.json | 11 ++++------- generate/README.md | 38 ++++++++++++++++---------------------- 12 files changed, 83 insertions(+), 83 deletions(-) create mode 100644 example/app/RpcMap.hs diff --git a/README.md b/README.md index 7b53db5..fefaf83 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,12 @@ # README -Look at `app` for an example application. +See `example` for an example application. `example/app/RpcMap.hs` is +generated by `simple-rpc-generate` from `example/rpcConfig.json`: + +``` +cabal build lib:example +cd example && cabal run simple-rpc-generate -- rpcConfig.json +``` ## Pre-requisites @@ -16,5 +22,5 @@ Look at `app` for an example application. ## Usage as a CLI ``` -echo '[22, "Test", true]' | cabal run example -- "Module1.printFromModule1" +echo '[22, "Test", true]' | cabal run example-server -- "Module1.printFromModule1" ``` diff --git a/example/app/Main.hs b/example/app/Main.hs index b895b5a..587ebde 100644 --- a/example/app/Main.hs +++ b/example/app/Main.hs @@ -1,28 +1,8 @@ --- Warning: This file is generated via CLI. Do not edit this directly. - module Main (main) where --------------------------------------------------------------------------------- --- Imports --------------------------------------------------------------------------------- - -import Simple.RPC.Types -import Simple.RPC.Server -import qualified Module4 as Module0 -import qualified Module3 as Module1 -import qualified Module2 as Module2 -import qualified Module1 as Module3 - --------------------------------------------------------------------------------- --- Main --------------------------------------------------------------------------------- +import Module0 (exeVersion) +import RpcMap (rpcMap) +import Simple.RPC (mainWith) main :: IO () -main = - mainWith "0.0.0" $ createRpcMap - [ evaluator Module0.top - , evaluator Module1.helloWorld - , evaluator Module1.bottom - , evaluator Module2.printFromModule2 - , evaluator Module3.printFromModule1 - ] +main = mainWith exeVersion rpcMap diff --git a/example/app/RpcMap.hs b/example/app/RpcMap.hs new file mode 100644 index 0000000..36b328f --- /dev/null +++ b/example/app/RpcMap.hs @@ -0,0 +1,26 @@ +-- Warning: This file is generated via CLI. Do not edit this directly. + +module RpcMap (rpcMap) where + +-------------------------------------------------------------------------------- +-- Imports +-------------------------------------------------------------------------------- + +import Simple.RPC +import qualified Module3 as Module0 +import qualified Module4 as Module1 +import qualified Module2 as Module2 +import qualified Module1 as Module3 + +-------------------------------------------------------------------------------- +-- Main +-------------------------------------------------------------------------------- + +rpcMap :: RpcMap IntermediateRep +rpcMap = createRpcMap + [ evaluator Module0.helloWorld + , evaluator Module0.bottom + , evaluator Module1.top + , evaluator Module2.printFromModule2 + , evaluator Module3.printFromModule1 + ] diff --git a/example/example.cabal b/example/example.cabal index f3a5fe2..05de2dd 100644 --- a/example/example.cabal +++ b/example/example.cabal @@ -46,19 +46,13 @@ library , simple-rpc hs-source-dirs: lib --- --- Warning: The section between and is managed by the rpc --- generator. Do not edit this by hand. - executable example-server - import: - lib-options + import: lib-options main-is: Main.hs + -- RpcMap is generated by simple-rpc-generate, see rpcConfig.json + other-modules: RpcMap build-depends: base , simple-rpc , example hs-source-dirs: app - default-language: Haskell2010 - --- diff --git a/example/lib/Module0.hs b/example/lib/Module0.hs index 4186552..6d5b33f 100644 --- a/example/lib/Module0.hs +++ b/example/lib/Module0.hs @@ -8,5 +8,6 @@ exeVersion = "0.1.1" remoteExe :: Executable remoteExe = Executable "/opt/ssh-rpc/test" exeVersion -localhost :: SSHConfig +-- | (user@host, port) +localhost :: (String, String) localhost = ("user@localhost", "22") diff --git a/example/lib/Module1.hs b/example/lib/Module1.hs index 7469d69..099407a 100644 --- a/example/lib/Module1.hs +++ b/example/lib/Module1.hs @@ -2,7 +2,7 @@ module Module1 ( printFromModule1 ) where -import Simple.RPC.Server +import Simple.RPC raw_printFromModule1 :: Int -> String -> Bool -> IO (Int, String, Bool) raw_printFromModule1 val1 val2 val3 = do diff --git a/example/lib/Module2.hs b/example/lib/Module2.hs index 506fdf6..e47606a 100644 --- a/example/lib/Module2.hs +++ b/example/lib/Module2.hs @@ -2,7 +2,7 @@ module Module2 ( printFromModule2 ) where -import Simple.RPC.Server +import Simple.RPC import qualified Module1 as Module1 raw_printFromModule2 :: String -> IO () diff --git a/example/lib/Module3.hs b/example/lib/Module3.hs index 11bd598..cbcdc29 100644 --- a/example/lib/Module3.hs +++ b/example/lib/Module3.hs @@ -10,8 +10,7 @@ import qualified Module1 as Module1 import qualified Module2 as Module2 import Module0 -import Simple.RPC.Client -import Simple.RPC.Server +import Simple.RPC helloWorld' :: IO () helloWorld' = do @@ -23,11 +22,11 @@ raw_bottom = do exePath <- getExecutablePath let exe = Executable exePath exeVersion val <- - call - Module1.printFromModule1 - (with (exec exe & asUser "user")) 5 "Hello" False + runAt + (defaultConfig exe & setUser "user") + Module1.printFromModule1 5 "Hello" False print val - call - Module2.printFromModule2 - (with (exec remoteExe & onSSH localhost)) "World" + runAt + (defaultConfig remoteExe & setRemote localhost) + Module2.printFromModule2 "World" $(rpcExport "raw_bottom" "bottom") diff --git a/example/lib/Module4.hs b/example/lib/Module4.hs index 044eaa8..9eaca6f 100644 --- a/example/lib/Module4.hs +++ b/example/lib/Module4.hs @@ -9,17 +9,20 @@ import qualified Module2 as Module2 import qualified Module3 as Module3 import Module0 -import Simple.RPC.Client -import Simple.RPC.Server +import Simple.RPC top' :: IO () top' = do exePath <- getExecutablePath let exe = Executable exePath exeVersion run Module3.bottom - call Module3.helloWorld (with (exec exe & asUser "user")) - call Module2.printFromModule2 (with (exec exe & asUser "user")) "Hello" - call Module2.printFromModule2 - (with (exec remoteExe & onSSH localhost & asUser "cw-portal")) - "World" + runAt (defaultConfig exe & setUser "user") Module3.helloWorld + runAt + (defaultConfig exe & setUser "user") + Module2.printFromModule2 "Hello" + runAt + (defaultConfig remoteExe + & setRemote localhost + & setUser "cw-portal") + Module2.printFromModule2 "World" $(rpcify 'top') diff --git a/example/plan.json b/example/plan.json index 3cb5c4e..a065366 100644 --- a/example/plan.json +++ b/example/plan.json @@ -3,7 +3,7 @@ "config": { "executable": { "path": "./example-server", - "version": "0.0.0" + "version": "0.1.1" } }, "actions": [ diff --git a/example/rpcConfig.json b/example/rpcConfig.json index 9dfa981..ba61a3b 100644 --- a/example/rpcConfig.json +++ b/example/rpcConfig.json @@ -1,10 +1,7 @@ { - "distBuildDir": "../dist-newstyle/build/x86_64-linux/ghc-9.2.2/example-0.1.0.0/build/", + "distBuildDir": "../dist-newstyle/build/x86_64-linux/ghc-9.10.3/example-0.1.0.0/build/", "sourceDirectories": ["lib"], - "cabalFile": "example.cabal", - "libraryName": "example", - "serverDirectory": "app", - "serverExecutableName": "example-server", - "serverConfigImportList": ["lib-options"], - "serverVersion": "0.0.0" + "rpcModulePath": "app/RpcMap.hs", + "rpcModuleName": "RpcMap", + "compilationMode": "Normal" } diff --git a/generate/README.md b/generate/README.md index 505f69f..e02c4c7 100644 --- a/generate/README.md +++ b/generate/README.md @@ -11,40 +11,34 @@ Add the following ghc-options to your library sections **Step 2:** -Add the following comments in your cabal file where you want the executable code -to be generated. - -``` --- --- -``` - -The code generated inside this is handled by the `generate` executable. - -**Step 3:** - Create a rpc configuration file: Example: ``` { - "distBuildDir": "../dist-newstyle/build/x86_64-linux/ghc-9.2.2/example-0.1.0.0/build/", + "distBuildDir": "../dist-newstyle/build/x86_64-linux/ghc-9.10.3/example-0.1.0.0/build/", "sourceDirectories": ["lib"], - "cabalFile": "example.cabal", - "libraryName": "example", - "serverDirectory": "app", - "serverExecutableName": "example-server", - "serverConfigImportList": ["lib-options"], - "serverVersion": "0.0.0" + "rpcModulePath": "app/RpcMap.hs", + "rpcModuleName": "RpcMap", + "compilationMode": "Normal" } ``` -**Step 4** +`compilationMode` is one of `Normal`, `Dynamic` or `Threaded`; it selects +the `.th.hs`, `.dyn.th.hs` or `.thr.th.hs` dump files respectively. + +**Step 3:** Run the generator: - Run the `cabal build ` - Run the ` ` -This should populate the `` block and generate the executable -itself. +This generates the module `rpcModuleName` at `rpcModulePath`, exporting +`rpcMap :: RpcMap IntermediateRep`. Add it to `other-modules` of the server +executable and use it in `main`: + +```haskell +main :: IO () +main = mainWith "0.1.1" rpcMap +``` From b1dc375b7a7342a91ddac2b249c07075a05b98fe Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:08:19 +0530 Subject: [PATCH 03/32] Add a limit-build-mem flag to cap the GHC heap The flag adds +RTS -M2G -RTS to the GHC options. cabal.project enables it so that a local build does not exhaust the machine memory. --- cabal.project | 3 +++ example/example.cabal | 8 ++++++++ generate/simple-rpc-generate.cabal | 8 ++++++++ rpc/simple-rpc.cabal | 8 ++++++++ 4 files changed, 27 insertions(+) diff --git a/cabal.project b/cabal.project index 41b57b6..65854b3 100644 --- a/cabal.project +++ b/cabal.project @@ -1,5 +1,8 @@ packages: rpc, example, generate +-- Cap GHC heap usage so that builds do not exhaust the machine memory +flags: +limit-build-mem + -- source-repository-package -- type: git -- location: https://github.com/composewell/streamly-coreutils.git diff --git a/example/example.cabal b/example/example.cabal index 05de2dd..28e6153 100644 --- a/example/example.cabal +++ b/example/example.cabal @@ -2,6 +2,11 @@ cabal-version: 2.4 name: example version: 0.1.0.0 +flag limit-build-mem + description: Limits the GHC heap when building + manual: True + default: False + common compile-options default-language: Haskell2010 ghc-options: -Weverything @@ -24,6 +29,9 @@ common compile-options -Wno-redundant-bang-patterns -Wno-operator-whitespace + if flag(limit-build-mem) + ghc-options: +RTS -M2G -RTS + common default-extensions default-extensions: TemplateHaskell , QuasiQuotes diff --git a/generate/simple-rpc-generate.cabal b/generate/simple-rpc-generate.cabal index 5e72aad..2b88ac0 100644 --- a/generate/simple-rpc-generate.cabal +++ b/generate/simple-rpc-generate.cabal @@ -2,6 +2,11 @@ cabal-version: 2.4 name: simple-rpc-generate version: 0.1.0.0 +flag limit-build-mem + description: Limits the GHC heap when building + manual: True + default: False + common compile-options default-language: Haskell2010 ghc-options: -Weverything @@ -24,6 +29,9 @@ common compile-options -Wno-redundant-bang-patterns -Wno-operator-whitespace + if flag(limit-build-mem) + ghc-options: +RTS -M2G -RTS + common default-extensions default-extensions: TemplateHaskell , QuasiQuotes diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index df03442..7cb6c87 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -4,6 +4,11 @@ version: 0.1.0.0 extra-source-files: CHANGELOG.md +flag limit-build-mem + description: Limits the GHC heap when building + manual: True + default: False + common compile-options default-language: Haskell2010 ghc-options: -Weverything @@ -26,6 +31,9 @@ common compile-options -Wno-redundant-bang-patterns -Wno-operator-whitespace + if flag(limit-build-mem) + ghc-options: +RTS -M2G -RTS + common default-extensions default-extensions: TemplateHaskell , QuasiQuotes From 61b4ee8d5c1f280ae03b0e747a64813c04a45629 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:12:03 +0530 Subject: [PATCH 04/32] Add a test suite The test executable is also the RPC server for the endpoints in test/TestFunctions.hs. Fake ssh, scp, sudo and su first in PATH run the remote and privileged commands locally. test/Harness.hs provides assertions and QuickCheck properties. The heap is limited to 1G. --- rpc/simple-rpc.cabal | 23 +++ rpc/test/Harness.hs | 137 ++++++++++++++++ rpc/test/Main.hs | 332 ++++++++++++++++++++++++++++++++++++++ rpc/test/TestFunctions.hs | 87 ++++++++++ rpc/test/TestUtil.hs | 231 ++++++++++++++++++++++++++ 5 files changed, 810 insertions(+) create mode 100644 rpc/test/Harness.hs create mode 100644 rpc/test/Main.hs create mode 100644 rpc/test/TestFunctions.hs create mode 100644 rpc/test/TestUtil.hs diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 7cb6c87..d6f0d92 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -61,3 +61,26 @@ library , filepath , unordered-containers hs-source-dirs: lib + +test-suite simple-rpc-test + import: lib-options + type: exitcode-stdio-1.0 + main-is: Main.hs + other-modules: Harness + , TestFunctions + , TestUtil + hs-source-dirs: test + -- The test executable also runs as the RPC server for the tests. + ghc-options: -threaded -rtsopts -with-rtsopts=-M1G + build-depends: base + , simple-rpc + , QuickCheck + , aeson + , bytestring + , directory + , filepath + , process + , streamly-core + , streamly-process + , unix + , unordered-containers diff --git a/rpc/test/Harness.hs b/rpc/test/Harness.hs new file mode 100644 index 0000000..ae740a5 --- /dev/null +++ b/rpc/test/Harness.hs @@ -0,0 +1,137 @@ +-- | A minimal test harness: named test cases, assertions and QuickCheck +-- properties with a configurable seed. +-- +module Harness + ( Test + , test + , runTests + , assertEqual + , assertBool + , assertThrows + , property + ) where + +-------------------------------------------------------------------------------- +-- Imports +-------------------------------------------------------------------------------- + +import Control.Exception + (Exception, SomeException, displayException, evaluate, throwIO, try) +import Control.Monad (unless, when) +import Data.IORef (IORef, newIORef, readIORef, writeIORef) +import System.Exit (exitFailure) +import System.IO (hFlush, stdout) +import System.IO.Unsafe (unsafePerformIO) +import System.Timeout (timeout) +import Test.QuickCheck (Args(..), Result, Testable, isSuccess, stdArgs) +import Test.QuickCheck.Random (mkQCGen) + +import qualified Test.QuickCheck as QC + +-------------------------------------------------------------------------------- +-- Assertions +-------------------------------------------------------------------------------- + +newtype TestFailure = TestFailure String deriving Show + +instance Exception TestFailure where + displayException (TestFailure msg) = msg + +-- | Raise a 'TestFailure' exception with the message if the condition is +-- false. +assertBool :: String -> Bool -> IO () +assertBool msg cond = unless cond $ throwIO (TestFailure msg) + +-- | @assertEqual msg expected actual@. +assertEqual :: (Eq a, Show a) => String -> a -> a -> IO () +assertEqual msg expected actual = + unless (expected == actual) + $ throwIO + $ TestFailure + $ msg ++ "\n expected: " ++ show expected + ++ "\n actual: " ++ show actual + +-- | @assertThrows msg p action@ runs @action@, forces its result to WHNF and +-- checks that it raises an exception of type @e@ satisfying @p@. +assertThrows :: (Exception e, Show a) => String -> (e -> Bool) -> IO a -> IO () +assertThrows msg p action = do + r <- try (action >>= evaluate) + case r of + Left e -> + unless (p e) + $ throwIO + $ TestFailure + $ msg ++ "\n unexpected exception: " ++ show e + Right v -> + throwIO + $ TestFailure + $ msg ++ "\n no exception, result: " ++ show v + +-------------------------------------------------------------------------------- +-- QuickCheck +-------------------------------------------------------------------------------- + +{-# NOINLINE seedRef #-} +seedRef :: IORef Int +seedRef = unsafePerformIO (newIORef 0) + +-- | Check a QuickCheck property with the seed given to 'runTests', raise a +-- 'TestFailure' exception if it fails. +property :: Testable p => p -> IO () +property p = do + seed <- readIORef seedRef + let args = + stdArgs + { replay = Just (mkQCGen seed, 0) + , chatty = False + , maxSuccess = 100 + } + r :: Result <- QC.quickCheckWithResult args p + unless (isSuccess r) $ throwIO $ TestFailure (QC.output r) + +-------------------------------------------------------------------------------- +-- Running +-------------------------------------------------------------------------------- + +data Test = Test String (IO ()) + +-- | A named test case. +test :: String -> IO () -> Test +test = Test + +-- | Seconds after which a test is reported as failed. +testTimeout :: Int +testTimeout = 120 + +-- | Run the tests with the QuickCheck seed, print the result of each test and +-- exit with a failure exit code if any test failed. +runTests :: Int -> [Test] -> IO () +runTests seed tests = do + writeIORef seedRef seed + putStrLn $ "QuickCheck seed: " ++ show seed + results <- mapM runOne tests + let failed = [name | (name, False) <- results] + putStrLn "" + putStrLn + $ show (length tests - length failed) ++ " passed, " + ++ show (length failed) ++ " failed" + mapM_ (putStrLn . ("FAILED: " ++)) failed + when (not (null failed)) exitFailure + + where + + runOne (Test name action) = do + putStr (name ++ " ... ") + hFlush stdout + r <- try (timeout (testTimeout * 1000000) action) + case r of + Right (Just ()) -> putStrLn "OK" >> pure (name, True) + Right Nothing -> do + putStrLn "FAIL" + putStrLn + $ " timed out after " ++ show testTimeout ++ " seconds" + pure (name, False) + Left (e :: SomeException) -> do + putStrLn "FAIL" + putStrLn $ " " ++ displayException e + pure (name, False) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs new file mode 100644 index 0000000..ae789ba --- /dev/null +++ b/rpc/test/Main.hs @@ -0,0 +1,332 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Main (main) where + +-------------------------------------------------------------------------------- +-- Imports +-------------------------------------------------------------------------------- + +import Control.Exception (SomeException, finally) +import Data.Function ((&)) +import Data.Functor.Identity (runIdentity) +import Data.IORef (modifyIORef, newIORef, readIORef) +import Data.List (isPrefixOf, sort) +import Streamly.Internal.System.Process (ProcessFailure(..)) +import System.Directory (doesFileExist, executable, getPermissions) +import System.Environment (getArgs, lookupEnv) +import System.Exit (ExitCode(..)) +import System.FilePath (()) +import Test.QuickCheck (forAll, ioProperty, withMaxSuccess) + +import qualified Data.Aeson as Json +import qualified Data.ByteString as BS +import qualified Data.ByteString.Char8 as BSC +import qualified Data.ByteString.Lazy as BSL +import qualified Data.HashMap.Strict as HM +import qualified Streamly.Data.Stream as Stream +import qualified Test.QuickCheck as QC + +import Harness +import Simple.RPC +import TestFunctions +import TestUtil + +-------------------------------------------------------------------------------- +-- Helpers +-------------------------------------------------------------------------------- + +-- | A config for the test server that does not log. +serverConfig :: Env -> RunningConfig +serverConfig env = + defaultConfig (Executable (envExe env) testVersion) + & setLogger (const (pure ())) + +-- | A config for the test server that logs to the returned action. +loggingConfig :: Env -> IO (RunningConfig, IO [String]) +loggingConfig env = do + ref <- newIORef [] + let cfg = serverConfig env & setLogger (\s -> modifyIORef ref (s:)) + pure (cfg, reverse <$> readIORef ref) + +-- | Print-able ASCII characters and the control characters. +asciiString :: QC.Gen String +asciiString = QC.listOf (QC.choose ('\0', '\127')) + +-------------------------------------------------------------------------------- +-- Simple.RPC.Common +-------------------------------------------------------------------------------- + +commonTests :: [Test] +commonTests = + [ test "toIntermediateRep is toJSON" $ do + property $ \(x :: Int) -> toIntermediateRep x == Json.toJSON x + property $ \(x :: String) -> toIntermediateRep x == Json.toJSON x + property $ \(x :: [(Bool, Maybe Int)]) -> + toIntermediateRep x == Json.toJSON x + + , test "toBinStream is the JSON encoding" $ + property $ forAll genValue $ \v -> + let bytes = runIdentity (Stream.toList (toBinStream v)) + in bytes == BSL.unpack (Json.encode v) + && Json.decode (BSL.pack bytes) == Just v + + , test "rpcName is the module qualified endpoint name" $ do + assertEqual "echoInt" "TestFunctions.echoInt" (rpcName echoInt) + assertEqual "constant" "TestFunctions.constant" (rpcName constant) + + , test "rpcExport run calls the original function" $ do + r1 <- run add 2 3 + assertEqual "add" 5 r1 + r2 <- run constant + assertEqual "constant" 42 r2 + r3 <- run three 1 "x" True + assertEqual "three" (1, "x", True) r3 + ] + +-------------------------------------------------------------------------------- +-- Simple.RPC.Server +-------------------------------------------------------------------------------- + +serverTests :: Env -> [Test] +serverTests env = + [ test "createRpcMap maps endpoint names" $ + assertEqual "keys" + (sort + [ "TestFunctions.add", "TestFunctions.constant" + , "TestFunctions.echoInt", "TestFunctions.echoString" + , "TestFunctions.failing", "TestFunctions.printPartial" + , "TestFunctions.replicateChar", "TestFunctions.three" + , "TestFunctions.writeMarker" + ]) + (sort (HM.keys rpcMap)) + + , test "mainWith without arguments prints the version" $ do + (code, out, _) <- runServerRaw env [] [] "" + assertEqual "exit code" ExitSuccess code + assertEqual "stdout" (BSC.pack testVersion) out + + , test "mainWith with two arguments fails" $ do + (code, _, _) <- runServerRaw env [] ["a", "b"] "" + assertEqual "exit code" (ExitFailure 1) code + + , test "invokeFunction output protocol" $ do + (code, out, _) <- + runServerRaw env [] ["TestFunctions.add"] "[2,3]" + assertEqual "exit code" ExitSuccess code + assertEqual "stdout" + (BSC.pack "[SERVER] TestFunctions.add [2,3]\n\n5") out + + , test "invokeFunction prints the endpoint output before the result" $ do + (code, out, err) <- + runServerRaw env [] ["TestFunctions.printPartial"] "[\"abc\"]" + assertEqual "exit code" ExitSuccess code + assertEqual "stdout" + (BSC.pack + "[SERVER] TestFunctions.printPartial [\"abc\"]\nabc\n\"abc\"") + out + assertEqual "stderr" (BSC.pack "printPartial on stderr\n") err + + , test "invokeFunction reads the input up to the first newline" $ do + (code, out, _) <- + runServerRaw env [] ["TestFunctions.add"] "[2,3]\ngarbage" + assertEqual "exit code" ExitSuccess code + assertEqual "last line" "5" (last (BSC.lines out)) + + , test "invokeFunction with a zero argument endpoint" $ do + (code, out, _) <- + runServerRaw env [] ["TestFunctions.constant"] "[]" + assertEqual "exit code" ExitSuccess code + assertEqual "last line" "42" (last (BSC.lines out)) + (code1, _, _) <- + runServerRaw env [] ["TestFunctions.constant"] "[1]" + assertEqual "non-empty input" (ExitFailure 1) code1 + + , test "invokeFunction with an unknown endpoint fails" $ do + (code, _, err) <- runServerRaw env [] ["TestFunctions.nope"] "[]" + assertEqual "exit code" (ExitFailure 1) code + assertBool "stderr names the endpoint" + (BSC.pack "TestFunctions.nope" `BS.isInfixOf` err) + + , test "invokeFunction with an argument of a wrong type fails" $ do + (code, _, _) <- + runServerRaw env [] ["TestFunctions.add"] "[2,\"x\"]" + assertEqual "exit code" (ExitFailure 1) code + ] + +-------------------------------------------------------------------------------- +-- Simple.RPC.Client +-------------------------------------------------------------------------------- + +configTests :: [Test] +configTests = + [ test "defaultConfig fields" $ do + let exe = Executable "/x/server" "1.2" + cfg = defaultConfig exe + assertEqual "rcRemote" Nothing (rcRemote cfg) + assertEqual "rcUser" Nothing (rcUser cfg) + assertEqual "rcSudo" False (rcSudo cfg) + assertEqual "rcImageFlags" "" (rcImageFlags cfg) + assertEqual "executablePath" "/x/server" + (executablePath (rcImage cfg)) + assertEqual "executableVersion" "1.2" + (executableVersion (rcImage cfg)) + + , test "config setters set their fields" $ do + ref <- newIORef [] + let cfg = + defaultConfig (Executable "/x/server" "1.2") + & setImage (Executable "/y/server" "3") + & setImageFlags "+RTS -N -RTS" + & setRemote ("u@h", "2222") + & setUser "alice" + & useSudo True + & setLogger (\s -> modifyIORef ref (s:)) + assertEqual "setImage" "/y/server" (executablePath (rcImage cfg)) + assertEqual "setImage version" "3" (executableVersion (rcImage cfg)) + assertEqual "setImageFlags" "+RTS -N -RTS" (rcImageFlags cfg) + assertEqual "setRemote" (Just ("u@h", "2222")) (rcRemote cfg) + assertEqual "setUser" (Just "alice") (rcUser cfg) + assertEqual "useSudo" True (rcSudo cfg) + assertEqual "useSudo False" False (rcSudo (useSudo False cfg)) + rcLogger cfg "hello" + logged <- readIORef ref + assertEqual "setLogger" ["hello"] logged + + , test "showPair formats a tag and a value" $ do + assertEqual "CMD" "[CMD] ls -l" (showPair "CMD" "ls -l") + assertEqual "empty" "[] " (showPair "" "") + ] + +clientTests :: Env -> [Test] +clientTests env = + [ test "runAt calls a local endpoint" $ do + let cfg = serverConfig env + r1 <- runAt cfg add 2 3 + assertEqual "add" 5 r1 + r2 <- runAt cfg constant + assertEqual "constant" 42 r2 + r3 <- runAt cfg three (-7) "x y" False + assertEqual "three" (-7, "x y", False) r3 + + , test "runAt round trips Int and ASCII String arguments" $ do + let cfg = serverConfig env + property $ withMaxSuccess 20 $ \(x :: Int) -> + ioProperty $ (== x) <$> runAt cfg echoInt x + property $ withMaxSuccess 20 $ forAll asciiString $ \s -> + ioProperty $ (== s) <$> runAt cfg echoString s + + , test "runAt returns the result after partial endpoint output" $ do + r <- runAt (serverConfig env) printPartial "no newline" + assertEqual "printPartial" "no newline" r + + , test "runAt logs the command, input, stdout and stderr" $ do + (cfg, getLog) <- loggingConfig env + _ <- runAt cfg printPartial "abc" + logged <- getLog + let has p = any p logged + assertBool ("CMD: " ++ show logged) + (has ("[CMD] " `isPrefixOf`)) + assertBool ("ACT: " ++ show logged) + (has (== "[ACT] TestFunctions.printPartial")) + assertBool ("input: " ++ show logged) (has (== "[\"abc\"]")) + assertBool ("STDOUT: " ++ show logged) + (has (== "[STDOUT] \"abc\"")) + assertBool ("STDERR: " ++ show logged) + (has (== "[STDERR] printPartial on stderr")) + + , test "runAt raises ProcessFailure when the endpoint fails" $ + assertThrows "failing" (\(ProcessFailure n) -> n == 1) + (runAt (serverConfig env) failing 1) + + , test "runAt raises an exception on a version mismatch" $ + assertThrows "version" (\(_ :: SomeException) -> True) + (runAt + (defaultConfig (Executable (envExe env) "other") + & setLogger (const (pure ()))) + add 1 2) + + , test "runAt with setUser runs the endpoint through sudo su" $ do + clearFakeLog env + r <- runAt (serverConfig env & setUser "rpcuser") add 2 3 + assertEqual "add" 5 r + logged <- readFakeLog env + assertBool ("su: " ++ show logged) + (any ("su [rpcuser] [-c] " `isPrefixOf`) logged) + + , test "runAt with useSudo runs the endpoint through sudo" $ do + clearFakeLog env + r <- runAt (serverConfig env & useSudo True) add 2 3 + assertEqual "add" 5 r + logged <- readFakeLog env + assertBool ("sudo: " ++ show logged) + (any ("sudo [" `isPrefixOf`) logged) + + , test "runAt with setRemote runs the endpoint through ssh" $ do + clearFakeLog env + r <- runAt (serverConfig env & setRemote ("u@h", "2222")) add 2 3 + assertEqual "add" 5 r + logged <- readFakeLog env + let sshPrefix = + "ssh [-T] [-p] [2222] [-o] [StrictHostKeyChecking off] [u@h] " + assertBool ("ssh: " ++ show logged) + (length (filter (sshPrefix `isPrefixOf`) logged) == 2) + + , test "runAt with setRemote and setUser" $ do + clearFakeLog env + let cfg = + serverConfig env + & setRemote ("u@h", "22") + & setUser "rpcuser" + r <- runAt cfg three 1 "a" True + assertEqual "three" (1, "a", True) r + logged <- readFakeLog env + assertBool ("su: " ++ show logged) + (any ("su [rpcuser] [-c] " `isPrefixOf`) logged) + ] + +installTests :: Env -> [Test] +installTests env = + [ test "installOnRemote copies the executable" $ do + let destDir = envDir env "install1" "bin" + dest = destDir "server" + installOnRemote + (Executable (envExe env) testVersion) ("u@h", "22") dest + exists <- doesFileExist dest + assertBool "destination exists" exists + perms <- getPermissions dest + assertBool "destination is executable" (executable perms) + orig <- BS.readFile (envExe env) + copy <- BS.readFile dest + assertBool "same content" (orig == copy) + logged <- readFakeLog env + assertBool ("scp: " ++ show logged) + (any ("scp [-P] [22] " `isPrefixOf`) logged) + ] + +-------------------------------------------------------------------------------- +-- Main +-------------------------------------------------------------------------------- + +-- | Parse @--seed N@ from the arguments, default 0. +parseSeed :: [String] -> Int +parseSeed args = + case args of + ("--seed" : n : _) -> read n + (_ : rest) -> parseSeed rest + [] -> 0 + +main :: IO () +main = do + mode <- lookupEnv (fst serverMode) + if mode == Just (snd serverMode) + then mainWith testVersion rpcMap + else do + seed <- parseSeed <$> getArgs + env <- setupEnv + let tests = + commonTests + ++ serverTests env + ++ configTests + ++ clientTests env + ++ installTests env + runTests seed tests `finally` cleanupEnv env diff --git a/rpc/test/TestFunctions.hs b/rpc/test/TestFunctions.hs new file mode 100644 index 0000000..49b692c --- /dev/null +++ b/rpc/test/TestFunctions.hs @@ -0,0 +1,87 @@ +-- | Functions exported as RPC endpoints for the tests. The test executable +-- serves these endpoints when the environment variable +-- @SIMPLE_RPC_TEST_MODE@ is @server@. +-- +module TestFunctions + ( testVersion + , rpcMap + + -- * Endpoints + , echoInt + , echoString + , add + , constant + , three + , printPartial + , writeMarker + , failing + , replicateChar + ) where + +import Control.Exception (ErrorCall(..), throwIO) +import System.IO (hPutStrLn, stderr) + +import Simple.RPC + +-- | The version reported by the test server. +testVersion :: String +testVersion = "test-1.0" + +raw_echoInt :: Int -> IO Int +raw_echoInt = pure +$(rpcExport "raw_echoInt" "echoInt") + +raw_echoString :: String -> IO String +raw_echoString = pure +$(rpcExport "raw_echoString" "echoString") + +raw_add :: Int -> Int -> IO Int +raw_add x y = pure (x + y) +$(rpcExport "raw_add" "add") + +raw_constant :: IO Int +raw_constant = pure 42 +$(rpcExport "raw_constant" "constant") + +raw_three :: Int -> String -> Bool -> IO (Int, String, Bool) +raw_three x y z = pure (x, y, z) +$(rpcExport "raw_three" "three") + +-- | Print the argument to stdout without a trailing newline and a line to +-- stderr, return the argument. +raw_printPartial :: String -> IO String +raw_printPartial x = do + putStr x + hPutStrLn stderr "printPartial on stderr" + pure x +$(rpcExport "raw_printPartial" "printPartial") + +-- | Write the second argument to the file in the first argument. +raw_writeMarker :: FilePath -> Int -> IO Int +raw_writeMarker path x = do + writeFile path "marker" + pure x +$(rpcExport "raw_writeMarker" "writeMarker") + +raw_failing :: Int -> IO Int +raw_failing _ = throwIO (ErrorCall "failing endpoint") +$(rpcExport "raw_failing" "failing") + +raw_replicateChar :: Int -> Char -> IO String +raw_replicateChar n c = pure (replicate n c) +$(rpcExport "raw_replicateChar" "replicateChar") + +-- | The endpoints served by the test server. +rpcMap :: RpcMap IntermediateRep +rpcMap = + createRpcMap + [ evaluator echoInt + , evaluator echoString + , evaluator add + , evaluator constant + , evaluator three + , evaluator printPartial + , evaluator writeMarker + , evaluator failing + , evaluator replicateChar + ] diff --git a/rpc/test/TestUtil.hs b/rpc/test/TestUtil.hs new file mode 100644 index 0000000..66e0925 --- /dev/null +++ b/rpc/test/TestUtil.hs @@ -0,0 +1,231 @@ +-- | Test environment: a temporary directory, fake @ssh@, @scp@, @sudo@ and +-- @su@ commands, and a runner for the test server process. +-- +module TestUtil + ( Env(..) + , setupEnv + , cleanupEnv + , serverMode + , readFakeLog + , clearFakeLog + , writeScript + , runServerRaw + , genValue + ) where + +-------------------------------------------------------------------------------- +-- Imports +-------------------------------------------------------------------------------- + +import Control.Concurrent (forkIO) +import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) +import Control.Exception (IOException, catch, evaluate) +import Data.Aeson (Value, toJSON) +import System.Directory + ( Permissions, createDirectory, getPermissions, getTemporaryDirectory + , removeDirectoryRecursive, setOwnerExecutable, setPermissions ) +import System.Environment + (getEnvironment, getExecutablePath, lookupEnv, setEnv) +import System.Exit (ExitCode) +import System.FilePath (()) +import System.IO (hClose, hSetBinaryMode) +import System.Posix.Process (getProcessID) +import System.Process + ( CreateProcess(..), StdStream(..), createProcess, proc + , waitForProcess ) +import Test.QuickCheck (Gen) + +import qualified Data.Aeson as Json +import qualified Data.Aeson.Key as Key +import qualified Data.ByteString as BS +import qualified Test.QuickCheck as QC + +-------------------------------------------------------------------------------- +-- Environment +-------------------------------------------------------------------------------- + +-- | The name and value of the environment variable that runs the test +-- executable as the RPC server. +serverMode :: (String, String) +serverMode = ("SIMPLE_RPC_TEST_MODE", "server") + +data Env = + Env + { envDir :: FilePath -- ^ temporary directory for the tests + , envExe :: FilePath -- ^ path of the test executable + , envFakeLog :: FilePath -- ^ invocations of the fake commands + } + +fakeSsh :: String +fakeSsh = unlines + [ "#!/bin/sh" + , "# Run the remote command with sh in $SIMPLE_RPC_FAKE_HOME." + , logArgs "ssh" + , "while [ $# -gt 0 ]; do" + , " case \"$1\" in" + , " -T) shift ;;" + , " -p|-o) shift 2 ;;" + , " -*) echo \"fake ssh: unsupported option $1\" >&2; exit 255 ;;" + , " *) break ;;" + , " esac" + , "done" + , "shift" + , "cd \"$SIMPLE_RPC_FAKE_HOME\" || exit 255" + , "exec sh -c \"$*\"" + ] + +fakeScp :: String +fakeScp = unlines + [ "#!/bin/sh" + , "# scp -P PORT SRC HOST:DST, copy locally." + , logArgs "scp" + , "[ \"$1\" = \"-P\" ] && shift 2" + , "src=$1" + , "dst=${2#*:}" + , "case \"$dst\" in" + , " /*) ;;" + , " *) dst=\"$SIMPLE_RPC_FAKE_HOME/$dst\" ;;" + , "esac" + , "exec cp \"$src\" \"$dst\"" + ] + +fakeSudo :: String +fakeSudo = unlines + [ "#!/bin/sh" + , logArgs "sudo" + , "[ \"$1\" = \"--\" ] && shift" + , "exec \"$@\"" + ] + +fakeSu :: String +fakeSu = unlines + [ "#!/bin/sh" + , "# su USER -c CMD" + , logArgs "su" + , "[ \"$2\" = \"-c\" ] || { echo \"fake su: usage\" >&2; exit 1; }" + , "exec sh -c \"$3\"" + ] + +-- | Shell code to append the command name and its arguments, each in +-- brackets, as a line to the fake log. +logArgs :: String -> String +logArgs name = + "{ printf '" ++ name ++ "'; for a in \"$@\"; do printf ' [%s]' \"$a\"; \ + \done; echo; } >> \"$SIMPLE_RPC_FAKE_LOG\"" + +-- | Write an executable script. +writeScript :: FilePath -> String -> IO () +writeScript path content = do + writeFile path content + p :: Permissions <- getPermissions path + setPermissions path (setOwnerExecutable True p) + +-- | Create the temporary directory and the fake commands, put the fake +-- commands first in @PATH@ and make the child processes of the test +-- executable run as the RPC server. +setupEnv :: IO Env +setupEnv = do + tmp <- getTemporaryDirectory + pid <- getProcessID + exe <- getExecutablePath + let dir = tmp ("simple-rpc-test-" ++ show pid) + bin = dir "bin" + home = dir "home" + logFile = dir "fake.log" + createDirectory dir + createDirectory bin + createDirectory home + writeFile logFile "" + writeScript (bin "ssh") fakeSsh + writeScript (bin "scp") fakeScp + writeScript (bin "sudo") fakeSudo + writeScript (bin "su") fakeSu + path <- maybe "" id <$> lookupEnv "PATH" + setEnv "PATH" (bin ++ ":" ++ path) + setEnv "SIMPLE_RPC_FAKE_HOME" home + setEnv "SIMPLE_RPC_FAKE_LOG" logFile + uncurry setEnv serverMode + pure $ Env dir exe logFile + +cleanupEnv :: Env -> IO () +cleanupEnv env = removeDirectoryRecursive (envDir env) + +-- | The lines of the fake command log. +readFakeLog :: Env -> IO [String] +readFakeLog env = do + s <- readFile (envFakeLog env) + _ <- evaluate (length s) + pure (lines s) + +clearFakeLog :: Env -> IO () +clearFakeLog env = writeFile (envFakeLog env) "" + +-------------------------------------------------------------------------------- +-- Server process +-------------------------------------------------------------------------------- + +-- | @runServerRaw env extraEnv args input@ runs the test executable as the +-- RPC server with @args@, the environment variables @extraEnv@ added, and +-- @input@ as stdin. Returns the exit code, stdout and stderr. +runServerRaw + :: Env + -> [(String, String)] + -> [String] + -> BS.ByteString + -> IO (ExitCode, BS.ByteString, BS.ByteString) +runServerRaw env extraEnv args input = do + env0 <- getEnvironment + let vars = serverMode : extraEnv + env1 = vars ++ [kv | kv@(k, _) <- env0, k `notElem` map fst vars] + cp = + (proc (envExe env) args) + { std_in = CreatePipe + , std_out = CreatePipe + , std_err = CreatePipe + , env = Just env1 + } + (mIn, mOut, mErr, ph) <- createProcess cp + case (mIn, mOut, mErr) of + (Just hin, Just hout, Just herr) -> do + mapM_ (`hSetBinaryMode` True) [hin, hout, herr] + outVar <- newEmptyMVar + errVar <- newEmptyMVar + _ <- forkIO $ BS.hGetContents hout >>= putMVar outVar + _ <- forkIO $ BS.hGetContents herr >>= putMVar errVar + BS.hPut hin input `catch` \(_ :: IOException) -> pure () + hClose hin `catch` \(_ :: IOException) -> pure () + out <- takeMVar outVar + err <- takeMVar errVar + code <- waitForProcess ph + pure (code, out, err) + _ -> error "runServerRaw: createProcess did not create pipes" + +-------------------------------------------------------------------------------- +-- Generators +-------------------------------------------------------------------------------- + +-- | Generate a JSON value with integral numbers, so that a value survives +-- an encode and decode round trip. +genValue :: Gen Value +genValue = QC.sized go + + where + + go :: Int -> Gen Value + go n + | n <= 1 = QC.oneof leaves + | otherwise = + let m = n `div` 4 + pair = (,) . Key.fromString <$> QC.arbitrary <*> go m + in QC.oneof + $ leaves + ++ [ toJSON <$> QC.resize m (QC.listOf (go m)) + , Json.object <$> QC.resize m (QC.listOf pair) + ] + + leaves = + [ pure Json.Null + , Json.Bool <$> QC.arbitrary + , (\x -> Json.Number (fromIntegral x)) <$> (QC.arbitrary :: Gen Integer) + , toJSON <$> (QC.arbitrary :: Gen String) + ] From 7dd30b1bb59e2d2c7e1ed36a4fe7bcb17abd5b77 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:14:46 +0530 Subject: [PATCH 05/32] Decode the JSON input and output as UTF-8 bytes The input and output were decoded to a String and packed one Char per byte, so any non-ASCII character in an argument or result made the call fail. The server and the client now pass byte arrays to aeson and decode UTF-8 only for logging. --- rpc/lib/Simple/RPC/Client.hs | 15 ++++++--- rpc/lib/Simple/RPC/Internal/Types.hs | 42 ++++++++++++++++++------- rpc/lib/Simple/RPC/Server.hs | 17 +++++----- rpc/simple-rpc.cabal | 1 + rpc/test/Harness.hs | 6 ++-- rpc/test/Main.hs | 35 +++++++++++++++++++++ rpc/test/TestUtil.hs | 47 ++++++++++++++++++++++++++-- 7 files changed, 135 insertions(+), 28 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 3e2a40d..964f3a9 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -40,6 +40,7 @@ import System.FilePath (takeDirectory) import qualified Data.IORef as IORef import qualified Streamly.Data.Array as Array +import qualified Streamly.Internal.Data.Array as Array (compactEndByLn_) import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream import qualified Streamly.Internal.System.Command as Cmd @@ -87,6 +88,9 @@ versionGuard send mSshConf exe = do tracing :: (String -> IO ()) -> String -> String -> IO String tracing send tag val = send (showPair tag val) >> pure val +traceLine :: (String -> IO ()) -> String -> Array Word8 -> IO (Array Word8) +traceLine send tag val = send (showPair tag (decodeUtf8Array val)) >> pure val + bufferLefts :: IORef.IORef [a] -> Stream.Stream IO (Either a b) -> Stream.Stream IO b bufferLefts ref inp = @@ -127,9 +131,8 @@ pipe send using cmd input = do toChunkStream input & using cmd & bufferLefts errRef - & Unicode.decodeUtf8Chunks - & Stream.foldMany (Fold.takeEndBy_ (== '\n') Fold.toList) - & Stream.fold (Fold.lmapM (tracing send "STDOUT") Fold.latest) + & Array.compactEndByLn_ + & Stream.fold (Fold.lmapM (traceLine send "STDOUT") Fold.latest) chunkBufferReversed <- IORef.readIORef errRef let errBuffer = reverse chunkBufferReversed @@ -141,7 +144,11 @@ pipe send using cmd input = do case actionRes of Left (err :: SomeException) -> throwIO err Right Nothing -> throwIO EmptyOutput - Right (Just val) -> pure $ irFromString val + Right (Just val) -> do + r <- irFromArray val + case r of + Left err -> error $ "Unable to decode the output: " ++ err + Right x -> pure x -- XXX the remote call should be more seamless. We should be able to wrap any -- arbitrary code in runAt as long as its input and output are serializable. diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index f19b097..a7b7c35 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -24,8 +24,9 @@ module Simple.RPC.Internal.Types , toBinStream , toChunkStream , fromBinStream - , irFromString + , irFromArray , irToString + , decodeUtf8Array -- * Symbols , RpcEval(..) @@ -62,20 +63,28 @@ module Simple.RPC.Internal.Types import Data.Aeson (ToJSON, FromJSON, toJSON, fromJSON) import Data.Function ((&)) +import Data.Functor.Identity (runIdentity) import Data.Vector ((!?)) import Data.Word (Word8) +import Foreign.Ptr (castPtr) +import Streamly.Data.Array (Array) import Streamly.Data.Stream (Stream) import qualified Data.Aeson as Json import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Bifunctor +import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL -import qualified Data.ByteString.Lazy.Char8 as BSLC import qualified Data.HashMap.Strict as HM +import qualified Data.Text.Encoding.Error as Text +import qualified Data.Text.Lazy as TextL +import qualified Data.Text.Lazy.Encoding as TextL import qualified Data.Vector as Vector import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream +import qualified Streamly.Internal.Data.Array as Array (unsafePinnedAsPtr) +import qualified Streamly.Unicode.Stream as Unicode -------------------------------------------------------------------------------- -- Running Config @@ -352,14 +361,23 @@ fromBinStream input = do Nothing -> error "Unable to decode" Just x -> pure x --- | Convert the Latin1 Char String representation of IR (i.e. Json) to --- its Haskell representation. -irFromString :: String -> IntermediateRep -irFromString input = do - case Json.decode $ BSLC.pack input of - Nothing -> error $ "Unable to decode: " ++ input - Just x -> x - --- | Convert the Haskell representation of IR (i.e. Json) to String. +-- | Decode a UTF-8 encoded byte array to a String, replacing invalid bytes +-- with the Unicode replacement character. Used for logging. +decodeUtf8Array :: Array Word8 -> String +decodeUtf8Array arr = + runIdentity $ Stream.toList $ Unicode.decodeUtf8 $ Array.read arr + +-- | Decode the UTF-8 encoded JSON representation of IR in a byte array. +-- Returns the decoding error message on failure. +irFromArray :: Array Word8 -> IO (Either String IntermediateRep) +irFromArray arr = do + bs <- + Array.unsafePinnedAsPtr arr + $ \p n -> BS.packCStringLen (castPtr p, n) + pure $ Json.eitherDecodeStrict' bs + +-- | Convert the Haskell representation of IR (i.e. Json) to String. Used for +-- logging. irToString :: IntermediateRep -> String -irToString input = BSLC.unpack $ Json.encode input +irToString input = + TextL.unpack $ TextL.decodeUtf8With Text.lenientDecode $ Json.encode input diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index 23abff6..8d696de 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -17,11 +17,10 @@ import Streamly.Internal.Unicode.String (str) import System.Environment (getArgs) import System.IO (stdout, stdin) +import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream -import qualified Streamly.FileSystem.Handle as FH hiding (read) -import qualified Streamly.Internal.FileSystem.Handle as FH (read) -import qualified Streamly.Unicode.Stream as Unicode +import qualified Streamly.FileSystem.Handle as FH import Simple.RPC.Internal.Types @@ -43,12 +42,16 @@ invokeFunction actions actionName = -- XXX we should not buffer the input, it should be directly -- streamed to the function, otherwise we cannot support -- infinite or large input. - inputString <- + inputBytes <- FH.read stdin - & Unicode.decodeUtf8' - & Stream.fold (Fold.takeEndBy_ (== '\n') Fold.toList) - let input = irFromString inputString + & Stream.fold (Fold.takeEndBy_ (== 10) Array.create) + let inputString = decodeUtf8Array inputBytes putStrLn $ showPair "SERVER" [str|#{actionName} #{inputString}|] + r <- irFromArray inputBytes + input <- + case r of + Left err -> error $ "Unable to decode the input: " ++ err + Right x -> pure x output <- actFun input putStrLn "" toBinStream output & Stream.fold (FH.write stdout) diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index d6f0d92..8fd1678 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -59,6 +59,7 @@ library , bytestring , vector , filepath + , text , unordered-containers hs-source-dirs: lib diff --git a/rpc/test/Harness.hs b/rpc/test/Harness.hs index ae740a5..ca341d4 100644 --- a/rpc/test/Harness.hs +++ b/rpc/test/Harness.hs @@ -16,7 +16,8 @@ module Harness -------------------------------------------------------------------------------- import Control.Exception - (Exception, SomeException, displayException, evaluate, throwIO, try) + ( Exception, SomeException(..), displayException, evaluate, throwIO + , try ) import Control.Monad (unless, when) import Data.IORef (IORef, newIORef, readIORef, writeIORef) import System.Exit (exitFailure) @@ -131,7 +132,8 @@ runTests seed tests = do putStrLn $ " timed out after " ++ show testTimeout ++ " seconds" pure (name, False) - Left (e :: SomeException) -> do + Left (SomeException e) -> do + -- displayException of SomeException adds the backtrace putStrLn "FAIL" putStrLn $ " " ++ displayException e pure (name, False) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index ae789ba..c23d7ed 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -303,6 +303,40 @@ installTests env = (any ("scp [-P] [22] " `isPrefixOf`) logged) ] +-------------------------------------------------------------------------------- +-- Unicode +-------------------------------------------------------------------------------- + +unicodeTests :: Env -> [Test] +unicodeTests env = + [ test "invokeFunction decodes UTF-8 input" $ do + (code, out, err) <- + runServerRaw env [] ["TestFunctions.echoString"] + (utf8 "[\"T\233st\8594\"]") + assertEqual ("exit code, stderr: " ++ show err) ExitSuccess code + assertEqual "last line" + (utf8 "\"T\233st\8594\"") (last (BSC.lines out)) + + , test "runAt decodes a UTF-8 result" $ do + path <- fakeServer env "utf8-server" "1" (utf8 "\"T\233st\8594\"") + r <- + runAt + (serverConfig env & setImage (Executable path "1")) + echoString "x" + assertEqual "result" "T\233st\8594" r + + , test "runAt round trips Unicode String arguments" $ do + let cfg = serverConfig env + property $ withMaxSuccess 20 $ forAll genUnicodeString $ \s -> + ioProperty $ (== s) <$> runAt cfg echoString s + + , test "runAt logs the input as UTF-8 decoded text" $ do + (cfg, getLog) <- loggingConfig env + _ <- runAt cfg echoString "\233" + logged <- getLog + assertBool ("input: " ++ show logged) ("[\"\233\"]" `elem` logged) + ] + -------------------------------------------------------------------------------- -- Main -------------------------------------------------------------------------------- @@ -329,4 +363,5 @@ main = do ++ configTests ++ clientTests env ++ installTests env + ++ unicodeTests env runTests seed tests `finally` cleanupEnv env diff --git a/rpc/test/TestUtil.hs b/rpc/test/TestUtil.hs index 66e0925..9b8699e 100644 --- a/rpc/test/TestUtil.hs +++ b/rpc/test/TestUtil.hs @@ -9,8 +9,11 @@ module TestUtil , readFakeLog , clearFakeLog , writeScript + , utf8 + , fakeServer , runServerRaw , genValue + , genUnicodeString ) where -------------------------------------------------------------------------------- @@ -31,13 +34,16 @@ import System.FilePath (()) import System.IO (hClose, hSetBinaryMode) import System.Posix.Process (getProcessID) import System.Process - ( CreateProcess(..), StdStream(..), createProcess, proc - , waitForProcess ) + ( CreateProcess(std_err, std_in, std_out), StdStream(..), createProcess + , proc, waitForProcess ) import Test.QuickCheck (Gen) import qualified Data.Aeson as Json import qualified Data.Aeson.Key as Key import qualified Data.ByteString as BS +import qualified Data.ByteString.Builder as BSB +import qualified Data.ByteString.Lazy as BSL +import qualified System.Process as Process import qualified Test.QuickCheck as QC -------------------------------------------------------------------------------- @@ -120,6 +126,27 @@ writeScript path content = do p :: Permissions <- getPermissions path setPermissions path (setOwnerExecutable True p) +-- | Encode a String as UTF-8. +utf8 :: String -> BS.ByteString +utf8 = BSL.toStrict . BSB.toLazyByteString . BSB.stringUtf8 + +-- | @fakeServer env name version output@ creates a fake RPC server script +-- named @name@ that prints @version@ when called without arguments. +-- Otherwise it reads stdin and prints @output@ without a trailing newline. +-- Returns the path of the script. +fakeServer :: Env -> String -> String -> BS.ByteString -> IO FilePath +fakeServer env name version output = do + let path = envDir env name + outFile = path ++ ".out" + BS.writeFile outFile output + writeScript path $ unlines + [ "#!/bin/sh" + , "if [ $# -eq 0 ]; then printf '%s' '" ++ version ++ "'; exit 0; fi" + , "cat > /dev/null" + , "cat '" ++ outFile ++ "'" + ] + pure path + -- | Create the temporary directory and the fake commands, put the fake -- commands first in @PATH@ and make the child processes of the test -- executable run as the RPC server. @@ -182,7 +209,7 @@ runServerRaw env extraEnv args input = do { std_in = CreatePipe , std_out = CreatePipe , std_err = CreatePipe - , env = Just env1 + , Process.env = Just env1 } (mIn, mOut, mErr, ph) <- createProcess cp case (mIn, mOut, mErr) of @@ -229,3 +256,17 @@ genValue = QC.sized go , (\x -> Json.Number (fromIntegral x)) <$> (QC.arbitrary :: Gen Integer) , toJSON <$> (QC.arbitrary :: Gen String) ] + +-- | A Unicode string without the surrogate code points, which 'toJSON' +-- replaces with U+FFFD. +genUnicodeString :: Gen String +genUnicodeString = + QC.listOf + $ QC.oneof + [ QC.arbitrary `QC.suchThat` notSurrogate + , QC.elements "\233\8594\128512\0\n\"\\" + ] + + where + + notSurrogate c = c < '\xD800' || c > '\xDFFF' From 54dd9c4c4a9aa22653bd68a3e71ab54b0242b444 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:15:40 +0530 Subject: [PATCH 06/32] Write the server stdout as UTF-8 in any locale In a non-UTF-8 locale, e.g. LC_ALL=C in a non-interactive ssh session, printing a non-ASCII input, result or version raised an exception. invokeFunction and mainWith now set the stdout encoding to UTF-8, which the client expects. --- rpc/lib/Simple/RPC/Server.hs | 11 +++++-- rpc/test/Harness.hs | 16 ++++----- rpc/test/Main.hs | 63 +++++++++++++++++++++++++++--------- rpc/test/TestUtil.hs | 16 ++++----- 4 files changed, 72 insertions(+), 34 deletions(-) diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index 8d696de..f01aeca 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -15,7 +15,7 @@ module Simple.RPC.Server import Data.Function ((&)) import Streamly.Internal.Unicode.String (str) import System.Environment (getArgs) -import System.IO (stdout, stdin) +import System.IO (hSetEncoding, stdin, stdout, utf8) import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Fold as Fold @@ -34,11 +34,15 @@ import Simple.RPC.Internal.Types -- | Given a RpcMap and a function name invoke the function. The function input -- is supplied in serialized form on the stdin and the output is streamed in -- serialized form to stdout. +-- +-- The encoding of stdout is set to UTF-8, the client decodes the output as +-- UTF-8 independent of the locale of the server. invokeFunction :: RpcMap IntermediateRep -> String -> IO () invokeFunction actions actionName = case lookupRpcSymbol actionName actions of Nothing -> error [str|#{actionName} not found|] Just actFun -> do + hSetEncoding stdout utf8 -- XXX we should not buffer the input, it should be directly -- streamed to the function, otherwise we cannot support -- infinite or large input. @@ -60,7 +64,8 @@ invokeFunction actions actionName = -- the version number. The behavior of the main function in the executable is -- as follows: -- --- * If no arguments are provided, it prints the version number. +-- * If no arguments are provided, it prints the version number in UTF-8 +-- encoding, without a newline. -- * If more than one argument is provided, it is an error. -- * If exactly one argument is provided, the argument is treated as the name -- of the endpoint to be executed. @@ -76,6 +81,6 @@ mainWith :: String -> RpcMap IntermediateRep -> IO () mainWith version actions = do args <- getArgs case args of - [] -> putStr version + [] -> hSetEncoding stdout utf8 >> putStr version [actName] -> invokeFunction actions actName _ -> error [str|Usage: []|] diff --git a/rpc/test/Harness.hs b/rpc/test/Harness.hs index ca341d4..718a50d 100644 --- a/rpc/test/Harness.hs +++ b/rpc/test/Harness.hs @@ -11,9 +11,9 @@ module Harness , property ) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Control.Exception ( Exception, SomeException(..), displayException, evaluate, throwIO @@ -29,9 +29,9 @@ import Test.QuickCheck.Random (mkQCGen) import qualified Test.QuickCheck as QC --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Assertions --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- newtype TestFailure = TestFailure String deriving Show @@ -68,9 +68,9 @@ assertThrows msg p action = do $ TestFailure $ msg ++ "\n no exception, result: " ++ show v --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- QuickCheck --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- {-# NOINLINE seedRef #-} seedRef :: IORef Int @@ -90,9 +90,9 @@ property p = do r :: Result <- QC.quickCheckWithResult args p unless (isSuccess r) $ throwIO $ TestFailure (QC.output r) --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Running --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- data Test = Test String (IO ()) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index c23d7ed..c0dfb8b 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -2,9 +2,9 @@ module Main (main) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Control.Exception (SomeException, finally) import Data.Function ((&)) @@ -31,9 +31,9 @@ import Simple.RPC import TestFunctions import TestUtil --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Helpers --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | A config for the test server that does not log. serverConfig :: Env -> RunningConfig @@ -52,9 +52,9 @@ loggingConfig env = do asciiString :: QC.Gen String asciiString = QC.listOf (QC.choose ('\0', '\127')) --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Simple.RPC.Common --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- commonTests :: [Test] commonTests = @@ -83,9 +83,9 @@ commonTests = assertEqual "three" (1, "x", True) r3 ] --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Simple.RPC.Server --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- serverTests :: Env -> [Test] serverTests env = @@ -105,6 +105,15 @@ serverTests env = assertEqual "exit code" ExitSuccess code assertEqual "stdout" (BSC.pack testVersion) out + , test "mainWith prints a non-ASCII version in the C locale" $ do + let vars = + [ ("LC_ALL", "C"), ("LANG", "C") + , ("SIMPLE_RPC_TEST_VERSION", "unicode") + ] + (code, out, err) <- runServerRaw env vars [] "" + assertEqual ("exit code, stderr: " ++ show err) ExitSuccess code + assertEqual "stdout" (utf8 "1.0-\233") out + , test "mainWith with two arguments fails" $ do (code, _, _) <- runServerRaw env [] ["a", "b"] "" assertEqual "exit code" (ExitFailure 1) code @@ -153,9 +162,9 @@ serverTests env = assertEqual "exit code" (ExitFailure 1) code ] --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Simple.RPC.Client --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- configTests :: [Test] configTests = @@ -303,9 +312,9 @@ installTests env = (any ("scp [-P] [22] " `isPrefixOf`) logged) ] --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Unicode --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- unicodeTests :: Env -> [Test] unicodeTests env = @@ -317,6 +326,27 @@ unicodeTests env = assertEqual "last line" (utf8 "\"T\233st\8594\"") (last (BSC.lines out)) + , test "invokeFunction writes UTF-8 output in the C locale" $ do + let cLocale = [("LC_ALL", "C"), ("LANG", "C")] + (code, out, err) <- + runServerRaw env cLocale ["TestFunctions.echoString"] + (utf8 "[\"\233\"]") + assertEqual ("echoString, stderr: " ++ show err) ExitSuccess code + assertEqual "echoString stdout" + (utf8 + $ "[SERVER] TestFunctions.echoString [\"\233\"]\n" + ++ "\n\"\233\"") + out + (code1, out1, err1) <- + runServerRaw env cLocale ["TestFunctions.printPartial"] + (utf8 "[\"\8594\"]") + assertEqual ("printPartial, stderr: " ++ show err1) ExitSuccess code1 + assertEqual "printPartial stdout" + (utf8 + $ "[SERVER] TestFunctions.printPartial [\"\8594\"]\n" + ++ "\8594\n\"\8594\"") + out1 + , test "runAt decodes a UTF-8 result" $ do path <- fakeServer env "utf8-server" "1" (utf8 "\"T\233st\8594\"") r <- @@ -337,9 +367,9 @@ unicodeTests env = assertBool ("input: " ++ show logged) ("[\"\233\"]" `elem` logged) ] --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Main --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | Parse @--seed N@ from the arguments, default 0. parseSeed :: [String] -> Int @@ -353,7 +383,10 @@ main :: IO () main = do mode <- lookupEnv (fst serverMode) if mode == Just (snd serverMode) - then mainWith testVersion rpcMap + then do + v <- lookupEnv "SIMPLE_RPC_TEST_VERSION" + let version = if v == Just "unicode" then "1.0-\233" else testVersion + mainWith version rpcMap else do seed <- parseSeed <$> getArgs env <- setupEnv diff --git a/rpc/test/TestUtil.hs b/rpc/test/TestUtil.hs index 9b8699e..e159ea7 100644 --- a/rpc/test/TestUtil.hs +++ b/rpc/test/TestUtil.hs @@ -16,9 +16,9 @@ module TestUtil , genUnicodeString ) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) @@ -46,9 +46,9 @@ import qualified Data.ByteString.Lazy as BSL import qualified System.Process as Process import qualified Test.QuickCheck as QC --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Environment --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | The name and value of the environment variable that runs the test -- executable as the RPC server. @@ -187,9 +187,9 @@ readFakeLog env = do clearFakeLog :: Env -> IO () clearFakeLog env = writeFile (envFakeLog env) "" --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Server process --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | @runServerRaw env extraEnv args input@ runs the test executable as the -- RPC server with @args@, the environment variables @extraEnv@ added, and @@ -227,9 +227,9 @@ runServerRaw env extraEnv args input = do pure (code, out, err) _ -> error "runServerRaw: createProcess did not create pipes" --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Generators --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | Generate a JSON value with integral numbers, so that a value survives -- an encode and decode round trip. From 39418aa3d194aeec5ee1134f00fc99267467775c Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:17:32 +0530 Subject: [PATCH 07/32] Raise a named exception for every RPC error Most errors were raised with error, so a caller could not match on the kind of error. Export RpcException from Simple.RPC.Common with a constructor for each error. Decode an invalid output line in IO before runAt returns. --- rpc/lib/Simple/RPC/Client.hs | 23 +++++++++----- rpc/lib/Simple/RPC/Common.hs | 3 ++ rpc/lib/Simple/RPC/Internal/Types.hs | 42 ++++++++++++++++++++++++++ rpc/lib/Simple/RPC/Server.hs | 15 ++++++---- rpc/test/Main.hs | 45 +++++++++++++++++++++++----- 5 files changed, 108 insertions(+), 20 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 964f3a9..668ac5b 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -29,7 +29,7 @@ module Simple.RPC.Client -- Imports -------------------------------------------------------------------------------- -import Control.Exception (SomeException, throwIO, try, Exception) +import Control.Exception (SomeException, throwIO, try) import Control.Monad (when) import Data.Function ((&)) import Data.Word (Word8) @@ -83,7 +83,9 @@ versionGuard send mSshConf exe = do send $ showPair "ERR" [str|Version mismatch for #{prefix}#{exePath}|] send $ showPair "ERR" [str|Expected: #{exeVersionExpected}|] send $ showPair "ERR" [str|Got: #{exeVersion}|] - error "VersionMismatch" + throwIO + $ VersionMismatch + [str|#{prefix}#{exePath}|] exeVersionExpected exeVersion tracing :: (String -> IO ()) -> String -> String -> IO String tracing send tag val = send (showPair tag val) >> pure val @@ -99,11 +101,6 @@ bufferLefts ref inp = f (Left a) = IORef.modifyIORef ref (a:) >> pure Nothing f (Right b) = pure $ Just b -data RpcException = EmptyOutput - deriving (Show) - -instance Exception RpcException - -- XXX We should allow the input to be a stream instead of being finite. -- XXX We should not buffer the output, it should be returned as a stream. -- XXX We should be able to use websockets instead of ssh. @@ -147,7 +144,7 @@ pipe send using cmd input = do Right (Just val) -> do r <- irFromArray val case r of - Left err -> error $ "Unable to decode the output: " ++ err + Left err -> throwIO (InvalidOutput err) Right x -> pure x -- XXX the remote call should be more seamless. We should be able to wrap any @@ -194,6 +191,16 @@ with (RunningConfig{..}) actionName input = do in [str|#{ePath} #{actionName}|] -- | Make a RPC call at the remote host specified by the first argument. +-- +-- The call raises: +-- +-- * a 'VersionMismatch' exception if the server executable prints a version +-- other than 'executableVersion', +-- * a 'Streamly.Internal.System.Process.ProcessFailure' exception if the +-- server process exits with a non-zero exit code, +-- * an 'EmptyOutput' exception if the server does not print an output line, +-- * an 'InvalidOutput' exception if the last output line of the server is not +-- the JSON encoding of the result type. runAt :: RunningConfig -> RpcSymbol IntermediateRep typ -> typ runAt cfg sym = call sym (with cfg) diff --git a/rpc/lib/Simple/RPC/Common.hs b/rpc/lib/Simple/RPC/Common.hs index 4911607..d09b8f2 100644 --- a/rpc/lib/Simple/RPC/Common.hs +++ b/rpc/lib/Simple/RPC/Common.hs @@ -15,6 +15,9 @@ module Simple.RPC.Common , toIntermediateRep , toBinStream + -- * Exceptions + , RpcException(..) + -- * Deprecated , rpcify ) where diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index a7b7c35..74d485f 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -55,12 +55,15 @@ module Simple.RPC.Internal.Types -- * RPC , Runner + -- * Exceptions + , RpcException(..) ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- +import Control.Exception (Exception(..)) import Data.Aeson (ToJSON, FromJSON, toJSON, fromJSON) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) @@ -86,6 +89,45 @@ import qualified Streamly.Data.Stream as Stream import qualified Streamly.Internal.Data.Array as Array (unsafePinnedAsPtr) import qualified Streamly.Unicode.Stream as Unicode +-------------------------------------------------------------------------------- +-- Exceptions +-------------------------------------------------------------------------------- + +-- | Exceptions raised by the RPC client and the RPC server. +data RpcException + = EndpointNotFound String + -- ^ The server does not have an endpoint with this name. + | InvalidInput String + -- ^ The server could not decode the input of the endpoint, the + -- argument is the error message. + | InvalidOutput String + -- ^ The client could not decode the last output line of the server, + -- the argument is the error message. + | EmptyOutput + -- ^ The server did not print any output line. + | VersionMismatch String String String + -- ^ @VersionMismatch executable expected actual@: the server + -- executable printed the version @actual@ instead of @expected@. + | InvalidUsage [String] + -- ^ The server executable was called with these arguments, it accepts + -- at most one argument. + deriving (Eq, Show) + +instance Exception RpcException where + displayException e = + case e of + EndpointNotFound name -> "RPC endpoint not found: " ++ name + InvalidInput msg -> "Invalid RPC input: " ++ msg + InvalidOutput msg -> "Invalid RPC output: " ++ msg + EmptyOutput -> "The RPC server did not print an output line" + VersionMismatch exe expected actual -> + "Version mismatch for " ++ exe + ++ ", expected: " ++ show expected + ++ ", got: " ++ show actual + InvalidUsage args -> + "Usage: [], got the arguments: " + ++ show args + -------------------------------------------------------------------------------- -- Running Config -------------------------------------------------------------------------------- diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index f01aeca..2ce0802 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -12,6 +12,7 @@ module Simple.RPC.Server -- Imports -------------------------------------------------------------------------------- +import Control.Exception (throwIO) import Data.Function ((&)) import Streamly.Internal.Unicode.String (str) import System.Environment (getArgs) @@ -37,10 +38,13 @@ import Simple.RPC.Internal.Types -- -- The encoding of stdout is set to UTF-8, the client decodes the output as -- UTF-8 independent of the locale of the server. +-- +-- Raise an 'EndpointNotFound' exception if the map does not have the +-- function, and an 'InvalidInput' exception if the input is not valid JSON. invokeFunction :: RpcMap IntermediateRep -> String -> IO () invokeFunction actions actionName = case lookupRpcSymbol actionName actions of - Nothing -> error [str|#{actionName} not found|] + Nothing -> throwIO (EndpointNotFound actionName) Just actFun -> do hSetEncoding stdout utf8 -- XXX we should not buffer the input, it should be directly @@ -54,7 +58,7 @@ invokeFunction actions actionName = r <- irFromArray inputBytes input <- case r of - Left err -> error $ "Unable to decode the input: " ++ err + Left err -> throwIO (InvalidInput err) Right x -> pure x output <- actFun input putStrLn "" @@ -66,13 +70,14 @@ invokeFunction actions actionName = -- -- * If no arguments are provided, it prints the version number in UTF-8 -- encoding, without a newline. --- * If more than one argument is provided, it is an error. +-- * If more than one argument is provided, it raises an 'InvalidUsage' +-- exception. -- * If exactly one argument is provided, the argument is treated as the name -- of the endpoint to be executed. -- -- The RPC server executable implements several endpoints, it has a map of the -- endpoint name to the function that implements the endpoint. If the endpoint --- is not found in the map then it is an error. If the endpoint is found then +-- is not found in the map then it raises an 'EndpointNotFound' exception. If the endpoint is found then -- the stdin of the RPC executable is supplied as input to the corresponding -- function. The input is a serialized form (JSON) of the 'IntermediateRep'. -- The output of the endpoint is emitted on stdout as serialized form of @@ -83,4 +88,4 @@ mainWith version actions = do case args of [] -> hSetEncoding stdout utf8 >> putStr version [actName] -> invokeFunction actions actName - _ -> error [str|Usage: []|] + _ -> throwIO (InvalidUsage args) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index c0dfb8b..456c3a1 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -6,7 +6,7 @@ module Main (main) where -- Imports ------------------------------------------------------------------------------- -import Control.Exception (SomeException, finally) +import Control.Exception (displayException, finally) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.IORef (modifyIORef, newIORef, readIORef) @@ -48,6 +48,12 @@ loggingConfig env = do let cfg = serverConfig env & setLogger (\s -> modifyIORef ref (s:)) pure (cfg, reverse <$> readIORef ref) +-- | Check that the stderr of the server has the message of the exception. +assertStderr :: BS.ByteString -> RpcException -> IO () +assertStderr err e = + assertBool ("stderr: " ++ show err) + (utf8 (displayException e) `BS.isInfixOf` err) + -- | Print-able ASCII characters and the control characters. asciiString :: QC.Gen String asciiString = QC.listOf (QC.choose ('\0', '\127')) @@ -114,9 +120,10 @@ serverTests env = assertEqual ("exit code, stderr: " ++ show err) ExitSuccess code assertEqual "stdout" (utf8 "1.0-\233") out - , test "mainWith with two arguments fails" $ do - (code, _, _) <- runServerRaw env [] ["a", "b"] "" + , test "mainWith with two arguments raises InvalidUsage" $ do + (code, _, err) <- runServerRaw env [] ["a", "b"] "" assertEqual "exit code" (ExitFailure 1) code + assertStderr err (InvalidUsage ["a", "b"]) , test "invokeFunction output protocol" $ do (code, out, _) <- @@ -153,8 +160,14 @@ serverTests env = , test "invokeFunction with an unknown endpoint fails" $ do (code, _, err) <- runServerRaw env [] ["TestFunctions.nope"] "[]" assertEqual "exit code" (ExitFailure 1) code - assertBool "stderr names the endpoint" - (BSC.pack "TestFunctions.nope" `BS.isInfixOf` err) + assertStderr err (EndpointNotFound "TestFunctions.nope") + + , test "invokeFunction with invalid JSON input raises InvalidInput" $ do + (code, _, err) <- + runServerRaw env [] ["TestFunctions.add"] "not json" + assertEqual "exit code" (ExitFailure 1) code + assertBool ("stderr: " ++ show err) + (utf8 "Invalid RPC input: " `BS.isInfixOf` err) , test "invokeFunction with an argument of a wrong type fails" $ do (code, _, _) <- @@ -247,13 +260,31 @@ clientTests env = assertThrows "failing" (\(ProcessFailure n) -> n == 1) (runAt (serverConfig env) failing 1) - , test "runAt raises an exception on a version mismatch" $ - assertThrows "version" (\(_ :: SomeException) -> True) + , test "runAt raises VersionMismatch on a version mismatch" $ + assertThrows "version" + (== VersionMismatch (envExe env) "other" testVersion) (runAt (defaultConfig (Executable (envExe env) "other") & setLogger (const (pure ()))) add 1 2) + , test "runAt raises EmptyOutput when the server prints nothing" $ do + path <- fakeServer env "empty-server" "1" "" + assertThrows "empty" (== EmptyOutput) + (runAt + (serverConfig env & setImage (Executable path "1")) + echoInt 1) + + , test "runAt raises InvalidOutput when the output is not JSON" $ do + path <- fakeServer env "garbage-server" "1" "garbage" + assertThrows "garbage" + (\e -> case e of + InvalidOutput _ -> True + _ -> False) + (runAt + (serverConfig env & setImage (Executable path "1")) + echoInt 1) + , test "runAt with setUser runs the endpoint through sudo su" $ do clearFakeLog env r <- runAt (serverConfig env & setUser "rpcuser") add 2 3 From e8a452ef8d72f6edc7a7778cfaf1a379b02b1e68 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:19:47 +0530 Subject: [PATCH 08/32] Decode all endpoint arguments before calling the endpoint Arguments were decoded lazily, so a bad argument failed only after the function's earlier effects, an unforced one was never checked, and extra arguments were ignored. The wrapper now checks the argument count and decodes every argument first, raising InvalidInput. Use newName for the generated local names, so that exporting a function named val compiles. --- rpc/lib/Simple/RPC/Internal/TH.hs | 47 ++++++++++++++++------------ rpc/lib/Simple/RPC/Internal/Types.hs | 45 +++++++++++++++----------- rpc/test/Main.hs | 47 +++++++++++++++++++++++++--- rpc/test/TestFunctions.hs | 8 +++++ 4 files changed, 103 insertions(+), 44 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/TH.hs b/rpc/lib/Simple/RPC/Internal/TH.hs index d983ce3..7c91cdd 100644 --- a/rpc/lib/Simple/RPC/Internal/TH.hs +++ b/rpc/lib/Simple/RPC/Internal/TH.hs @@ -40,34 +40,41 @@ rpcExport oldFuncName newFuncName = do let endpoint = newFuncName endpointWithMod = modName ++ "." ++ endpoint - n_raw = mkName oldFuncName n_endpoint = mkName endpoint - n_runner = mkName "runner" - n_val = mkName "val" appEArgs = foldl appE + -- Resolve the name, a name made by mkName would be captured by a local + -- variable of the same name in the generated code. + mRaw <- lookupValueName oldFuncName + n_raw <- + case mRaw of + Just n -> pure n + Nothing -> fail $ "rpcExport: not in scope: " ++ oldFuncName typ <- getFunctionType n_raw let numArgs = getNumArgs typ enumArgs = [0..(numArgs - 1)] - strArgs = ('x':) . show <$> enumArgs - patArgs = varP . mkName <$> strArgs - varArgs = varE . mkName <$> strArgs - arrIndexTH i = - [|arrIndex $(varE n_val) $(litE (integerL (fromIntegral i)))|] - parsedArgs = map arrIndexTH enumArgs - - - let evalExp1 = - lamE - [(varP n_val)] - [|toIntermediateRep <$> $(appEArgs (varE n_raw) parsedArgs)|] - evalExp0 = - [|\x -> ensureNullArray x (toIntermediateRep <$> $(varE n_raw))|] + n_runner <- newName "runner" + n_val <- newName "val" + n_args <- newName "args" + argNames <- mapM (\i -> newName ('x' : show i)) enumArgs + let patArgs = map varP argNames + varArgs = map varE argNames + + -- Decode all the arguments before calling the function, so that an + -- invalid input raises an exception before any effect of the function. + let intE i = litE (integerL (fromIntegral i)) + bindArg i n = bindS (varP n) [|irArg $(varE n_args) $(intE i)|] + argsPat = if numArgs == 0 then wildP else varP n_args evalExp = - if numArgs == 0 - then evalExp0 - else evalExp1 + lamE [varP n_val] + $ doE + $ bindS argsPat [|irArgs $(intE numArgs) $(varE n_val)|] + : zipWith bindArg enumArgs argNames + ++ [ noBindS + [|toIntermediateRep + <$> $(appEArgs (varE n_raw) varArgs)|] + ] let toIntermediateRepTH k = [|toIntermediateRep $(k)|] encodedInput = [| createArr $(listE (map toIntermediateRepTH varArgs))|] diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 74d485f..7e604be 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -13,8 +13,8 @@ module Simple.RPC.Internal.Types -- ** IR Arrays , createArr - , arrIndex - , ensureNullArray + , irArgs + , irArg -- ** IR Maps , createObj @@ -63,7 +63,7 @@ module Simple.RPC.Internal.Types -- Imports -------------------------------------------------------------------------------- -import Control.Exception (Exception(..)) +import Control.Exception (Exception(..), throwIO) import Data.Aeson (ToJSON, FromJSON, toJSON, fromJSON) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) @@ -332,22 +332,29 @@ fromIntermediateRep val = -- Arrays in IR -------------------------------------------------------------------------------- --- | Decode a null array in IR as the supplied value. If the array is --- not null then it is an error. -ensureNullArray :: IntermediateRep -> a -> a -ensureNullArray (Json.Array vec) act = - if Vector.length vec == 0 - then act - else error "Input is not an empty" -ensureNullArray _ _ = error "Value is not an array type" - --- | Retrieve the value at the given index in an IR array. -arrIndex :: FromJSON a => IntermediateRep -> Int -> a -arrIndex (Json.Array vec) i = - case vec !? i of - Nothing -> error $ "Could not find arg at position: " ++ show i - Just val -> fromIntermediateRep val -arrIndex _ _ = error "Value is not an array type" +-- | @irArgs n ir@ returns the elements of the IR array @ir@. Raise an +-- 'InvalidInput' exception if @ir@ is not an array of @n@ elements. +irArgs :: Int -> IntermediateRep -> IO (Vector.Vector IntermediateRep) +irArgs n (Json.Array vec) + | Vector.length vec == n = pure vec +irArgs n ir = + throwIO + $ InvalidInput + $ "expected an array of " ++ show n ++ " arguments, got: " + ++ irToString ir + +-- | @irArg args i@ decodes the element at index @i@ of the arguments returned +-- by 'irArgs'. Raise an 'InvalidInput' exception if the index is out of +-- bounds or the element cannot be decoded to the required type. +irArg :: FromJSON a => Vector.Vector IntermediateRep -> Int -> IO a +irArg args i = + case args !? i of + Nothing -> throwIO $ InvalidInput $ "missing argument " ++ show i + Just v -> + case fromJSON v of + Json.Error err -> + throwIO $ InvalidInput $ "argument " ++ show i ++ ": " ++ err + Json.Success a -> pure a -- | Create an array in IR from a list of IR Haskell values. createArr :: [IntermediateRep] -> IntermediateRep diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 456c3a1..0ca0ec4 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -54,6 +54,12 @@ assertStderr err e = assertBool ("stderr: " ++ show err) (utf8 (displayException e) `BS.isInfixOf` err) +-- | Check that the stderr of the server has an 'InvalidInput' message. +assertInvalidInput :: BS.ByteString -> IO () +assertInvalidInput err = + assertBool ("stderr: " ++ show err) + (utf8 "Invalid RPC input: " `BS.isInfixOf` err) + -- | Print-able ASCII characters and the control characters. asciiString :: QC.Gen String asciiString = QC.listOf (QC.choose ('\0', '\127')) @@ -102,7 +108,7 @@ serverTests env = , "TestFunctions.echoInt", "TestFunctions.echoString" , "TestFunctions.failing", "TestFunctions.printPartial" , "TestFunctions.replicateChar", "TestFunctions.three" - , "TestFunctions.writeMarker" + , "TestFunctions.valRpc", "TestFunctions.writeMarker" ]) (sort (HM.keys rpcMap)) @@ -153,9 +159,10 @@ serverTests env = runServerRaw env [] ["TestFunctions.constant"] "[]" assertEqual "exit code" ExitSuccess code assertEqual "last line" "42" (last (BSC.lines out)) - (code1, _, _) <- + (code1, _, err1) <- runServerRaw env [] ["TestFunctions.constant"] "[1]" assertEqual "non-empty input" (ExitFailure 1) code1 + assertInvalidInput err1 , test "invokeFunction with an unknown endpoint fails" $ do (code, _, err) <- runServerRaw env [] ["TestFunctions.nope"] "[]" @@ -166,13 +173,43 @@ serverTests env = (code, _, err) <- runServerRaw env [] ["TestFunctions.add"] "not json" assertEqual "exit code" (ExitFailure 1) code - assertBool ("stderr: " ++ show err) - (utf8 "Invalid RPC input: " `BS.isInfixOf` err) + assertInvalidInput err , test "invokeFunction with an argument of a wrong type fails" $ do - (code, _, _) <- + (code, _, err) <- runServerRaw env [] ["TestFunctions.add"] "[2,\"x\"]" assertEqual "exit code" (ExitFailure 1) code + assertInvalidInput err + + , test "invokeFunction decodes all arguments before the call" $ do + let marker = envDir env "marker" + input = Json.encode (marker, "not an Int" :: String) + (code, _, err) <- + runServerRaw env [] ["TestFunctions.writeMarker"] + (BSL.toStrict input) + assertEqual "exit code" (ExitFailure 1) code + assertInvalidInput err + exists <- doesFileExist marker + assertBool "the endpoint was not called" (not exists) + + , test "invokeFunction rejects a wrong number of arguments" $ do + let call input = do + (code, _, err) <- + runServerRaw env [] ["TestFunctions.add"] input + assertEqual ("exit code " ++ show input) (ExitFailure 1) code + assertInvalidInput err + call "[1,2,3]" + call "[1]" + call "[]" + call "{}" + call "1" + + , test "rpcExport of a function named val" $ do + r <- run valRpc 4 + assertEqual "run" 8 r + (code, out, _) <- runServerRaw env [] ["TestFunctions.valRpc"] "[4]" + assertEqual "exit code" ExitSuccess code + assertEqual "last line" "8" (last (BSC.lines out)) ] ------------------------------------------------------------------------------- diff --git a/rpc/test/TestFunctions.hs b/rpc/test/TestFunctions.hs index 49b692c..0852656 100644 --- a/rpc/test/TestFunctions.hs +++ b/rpc/test/TestFunctions.hs @@ -16,6 +16,7 @@ module TestFunctions , writeMarker , failing , replicateChar + , valRpc ) where import Control.Exception (ErrorCall(..), throwIO) @@ -71,6 +72,12 @@ raw_replicateChar :: Int -> Char -> IO String raw_replicateChar n c = pure (replicate n c) $(rpcExport "raw_replicateChar" "replicateChar") +-- | A function with the name of a variable used in the code generated by +-- 'rpcExport'. +val :: Int -> IO Int +val x = pure (x * 2) +$(rpcExport "val" "valRpc") + -- | The endpoints served by the test server. rpcMap :: RpcMap IntermediateRep rpcMap = @@ -84,4 +91,5 @@ rpcMap = , evaluator writeMarker , evaluator failing , evaluator replicateChar + , evaluator valRpc ] From 98beb61405d47bc946280cf4e2a83c91c85a5d77 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:20:48 +0530 Subject: [PATCH 09/32] Decode the runAt result before runAt returns runAt returned a thunk, so a decoding error was raised where the caller forced the result, outside any handler around runAt. The result is now decoded in IO and an invalid one raises InvalidOutput. --- rpc/lib/Simple/RPC/Internal/TH.hs | 6 +++--- rpc/lib/Simple/RPC/Internal/Types.hs | 17 +++++++++++------ rpc/test/Main.hs | 15 ++++++++++++++- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/TH.hs b/rpc/lib/Simple/RPC/Internal/TH.hs index 7c91cdd..ba5afbe 100644 --- a/rpc/lib/Simple/RPC/Internal/TH.hs +++ b/rpc/lib/Simple/RPC/Internal/TH.hs @@ -82,9 +82,9 @@ rpcExport oldFuncName newFuncName = do runningExp = lamE (varP n_runner:patArgs) - [|fromIntermediateRep - <$> $(varE n_runner) - $(stringE endpointWithMod) $(encodedInput)|] + [|$(varE n_runner) + $(stringE endpointWithMod) $(encodedInput) + >>= resultFromIR|] let rpcSymbolExp = [|RpcSymbol diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 7e604be..52af9e4 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -9,7 +9,7 @@ module Simple.RPC.Internal.Types ( -- * Intermediate Representation (IR) IntermediateRep , toIntermediateRep - , fromIntermediateRep + , resultFromIR -- ** IR Arrays , createArr @@ -322,11 +322,13 @@ type IntermediateRep = Json.Value toIntermediateRep :: ToJSON a => a -> IntermediateRep toIntermediateRep = toJSON -fromIntermediateRep :: FromJSON a => IntermediateRep -> a -fromIntermediateRep val = +-- | Decode the result of an endpoint from IR. Raise an 'InvalidOutput' +-- exception if the IR cannot be decoded to the required type. +resultFromIR :: FromJSON a => IntermediateRep -> IO a +resultFromIR val = case fromJSON val of - Json.Error err -> error err - Json.Success a -> a + Json.Error err -> throwIO $ InvalidOutput err + Json.Success a -> pure a -------------------------------------------------------------------------------- -- Arrays in IR @@ -371,7 +373,10 @@ createArr = Json.Array . Vector.fromList objLookup :: FromJSON a => IntermediateRep -> String -> a objLookup (Json.Object obj) kStr = case KeyMap.lookup (Key.fromString kStr) obj of - Just val -> fromIntermediateRep val + Just val -> + case fromJSON val of + Json.Error err -> error err + Json.Success a -> a Nothing -> error $ "Could not find: " ++ kStr objLookup _ _ = error "Value is not an object type" diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 0ca0ec4..f4dc37f 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -6,7 +6,7 @@ module Main (main) where -- Imports ------------------------------------------------------------------------------- -import Control.Exception (displayException, finally) +import Control.Exception (displayException, finally, try) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.IORef (modifyIORef, newIORef, readIORef) @@ -322,6 +322,19 @@ clientTests env = (serverConfig env & setImage (Executable path "1")) echoInt 1) + , test "runAt decodes the result before it returns" $ do + path <- fakeServer env "string-server" "1" "\"not an Int\"" + r <- + try + $ runAt + (serverConfig env & setImage (Executable path "1")) + echoInt 1 + case r of + Left (InvalidOutput _) -> pure () + Left e -> assertBool ("unexpected exception: " ++ show e) False + -- Do not force the result + Right _ -> assertBool "runAt returned without an exception" False + , test "runAt with setUser runs the endpoint through sudo su" $ do clearFakeLog env r <- runAt (serverConfig env & setUser "rpcuser") add 2 3 From cc79edea4a47f9cb8c6d65291e94a474812b4258 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:22:43 +0530 Subject: [PATCH 10/32] Quote the server command for the shell The command was quoted with show, which does not quote for a shell, so paths with spaces or shell characters broke. Run the command as an argument list, and quote the commands given to su -c and ssh with single quotes. --- rpc/lib/Simple/RPC/Client.hs | 106 ++++++++++++++++++++--------------- rpc/test/Main.hs | 75 ++++++++++++++++++++++++- rpc/test/TestUtil.hs | 38 ++++++++++--- 3 files changed, 165 insertions(+), 54 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 668ac5b..267668c 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -31,15 +31,14 @@ module Simple.RPC.Client import Control.Exception (SomeException, throwIO, try) import Control.Monad (when) +import Data.Char (isAsciiLower, isAsciiUpper, isDigit) import Data.Function ((&)) import Data.Word (Word8) import Streamly.Data.Array (Array) -import Streamly.Data.Stream (Stream) import Streamly.Internal.Unicode.String (str) import System.FilePath (takeDirectory) import qualified Data.IORef as IORef -import qualified Streamly.Data.Array as Array import qualified Streamly.Internal.Data.Array as Array (compactEndByLn_) import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream @@ -53,28 +52,47 @@ import Simple.RPC.Internal.Types -- Utils -------------------------------------------------------------------------------- -type Pipe = - String -> - Stream IO (Array.Array Word8) -> - Stream IO (Either (Array.Array Word8) (Array.Array Word8)) +-- streamly-coreutils (Streamly.Coreutils.Sh) has the maintained definitions +-- of shellQuote and shellCommand; these are copies. Make changes there and +-- copy them here. -pipeChunksEither - :: String - -> Stream.Stream IO (Array Word8) - -> Stream.Stream IO (Either (Array Word8) (Array Word8)) -pipeChunksEither = Cmd.pipeWith Proc.pipeChunksEither +-- | Quote a string for a POSIX shell. A non-empty string of characters that +-- the shell does not interpret is returned unchanged. +shellQuote :: String -> String +shellQuote x + | not (null x) && all safe x = x + | otherwise = '\'' : concatMap escape x ++ "'" + + where + + escape '\'' = "'\\''" + escape c = [c] + + safe c = + isAsciiUpper c || isAsciiLower c || isDigit c || c `elem` "-_./=:,+@%" + +-- | A command line for a POSIX shell, running the executable with the +-- arguments. +shellCommand :: FilePath -> [String] -> String +shellCommand exe args = unwords (map shellQuote (exe : args)) + +-- | @sshCommand remote (exe, args)@ runs @exe args@ on the @remote@ (address, +-- port) using ssh. ssh passes the command to the shell of the remote user. +sshCommand :: (String, String) -> (FilePath, [String]) -> (FilePath, [String]) +sshCommand (addr, port) (exe, args) = + ( "ssh" + , [ "-T", "-p", port, "-o", "StrictHostKeyChecking off", addr + , shellCommand exe args + ] + ) versionGuard :: (String -> IO ()) -> Maybe (String, String) -> Executable -> IO () versionGuard send mSshConf exe = do let exePath = executablePath exe exeVersionExpected = executableVersion exe - let cmdVersionCheck = - case mSshConf of - Nothing -> [str|#{exePath}|] - Just (addr, port) -> - [str|ssh -T -p #{port} -o "StrictHostKeyChecking off" #{addr} #{exePath}|] - send $ showPair "CMD" cmdVersionCheck - exeVersion <- Cmd.toString cmdVersionCheck + let (cmd, args) = maybe id sshCommand mSshConf (exePath, []) + send $ showPair "CMD" (shellCommand cmd args) + exeVersion <- Proc.toString cmd args let prefix = case mSshConf of Nothing -> "" @@ -105,19 +123,24 @@ bufferLefts ref inp = -- XXX We should not buffer the output, it should be returned as a stream. -- XXX We should be able to use websockets instead of ssh. --- | @pipe send using cmd input@ - execute @cmd@ (the @ssh@ command) as a --- process providing @input@ on its stdin and returning the last line of its --- output as result. i.e. it takes input from stdin and provides output on --- stdout. +-- | @pipe send exe args input@ - run the executable @exe@ with arguments +-- @args@ as a process providing @input@ on its stdin and returning the last +-- line of its output as result. i.e. it takes input from stdin and provides +-- output on stdout. -- -- BUGs: the output JSON from the remote call must not have a newline '\n' -- character. It will cause unexpected behavior. Also, the output must be -- finite as it is collected in a buffer. -- -- @send@ is a function for logging a String for debug and tracing. -pipe :: (String -> IO ()) -> Pipe -> Runner IntermediateRep -pipe send using cmd input = do - send $ showPair "CMD" cmd +pipe + :: (String -> IO ()) + -> FilePath + -> [String] + -> IntermediateRep + -> IO IntermediateRep +pipe send exe args input = do + send $ showPair "CMD" (shellCommand exe args) send $ showPair "INP" "" send $ irToString input send "" @@ -126,7 +149,7 @@ pipe send using cmd input = do actionRes <- try $ toChunkStream input - & using cmd + & Proc.pipeChunksEither exe args & bufferLefts errRef & Array.compactEndByLn_ & Stream.fold (Fold.lmapM (traceLine send "STDOUT") Fold.latest) @@ -158,37 +181,28 @@ with :: RunningConfig -> Runner IntermediateRep with (RunningConfig{..}) actionName input = do let send = rcLogger versionGuard send rcRemote rcImage - let cmd = - sshWrapper rcRemote + let (exe, args) = + maybe id sshCommand rcRemote $ userWrapper rcUser $ sudoWrapper rcSudo - $ exeAction rcImage + (executablePath rcImage, [actionName]) send $ showPair "ACT" actionName - pipe send pipeChunksEither cmd input + pipe send exe args input where - sshWrapper Nothing val = val - sshWrapper (Just (addr, port)) val = - let quotedVal = show val - in [str|ssh -T -p #{port} -o "StrictHostKeyChecking off" #{addr} #{quotedVal}|] - -- XXX we should use either user wrapper or sudo wrapper, not both. If we -- are using userWrapper then we know we are sudo capable and can use sudo -- directly. - -- Does not run the shell profile but runs the rc file - userWrapper Nothing val = val - userWrapper (Just username) val = - let quotedVal = show val - in [str|sudo su #{username} -c #{quotedVal}|] - - sudoWrapper False val = val - sudoWrapper True val = [str|sudo #{val}|] + -- Does not run the shell profile but runs the rc file. su passes the + -- command to the shell of the user. + userWrapper Nothing cmd = cmd + userWrapper (Just username) (cmd, args) = + ("sudo", ["su", username, "-c", shellCommand cmd args]) - exeAction exeObj = - let ePath = executablePath exeObj - in [str|#{ePath} #{actionName}|] + sudoWrapper False cmd = cmd + sudoWrapper True (cmd, args) = ("sudo", cmd : args) -- | Make a RPC call at the remote host specified by the first argument. -- diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index f4dc37f..72aa31f 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -7,12 +7,15 @@ module Main (main) where ------------------------------------------------------------------------------- import Control.Exception (displayException, finally, try) +import Control.Monad (unless) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.IORef (modifyIORef, newIORef, readIORef) import Data.List (isPrefixOf, sort) import Streamly.Internal.System.Process (ProcessFailure(..)) -import System.Directory (doesFileExist, executable, getPermissions) +import System.Directory + ( createDirectory, createFileLink, doesFileExist, executable + , getPermissions ) import System.Environment (getArgs, lookupEnv) import System.Exit (ExitCode(..)) import System.FilePath (()) @@ -393,6 +396,75 @@ installTests env = (any ("scp [-P] [22] " `isPrefixOf`) logged) ] +------------------------------------------------------------------------------- +-- Command quoting +------------------------------------------------------------------------------- + +-- | A directory name with characters that a shell interprets. +-- +-- If a command is not quoted correctly, the shell expands the variable to +-- an empty string and the glob to the files of the working directory, which +-- 'setupEnv' sets to the temporary directory. Do not use a variable that is +-- set, such as @HOME@: a wrongly quoted @chmod@ on this path once changed +-- the mode of the home directory to 777. +specialDirName :: String +specialDirName = "dir with 'sq' \"dq\" $SIMPLE_RPC_UNSET `id` \\ * \233" + +quotingTests :: Env -> [Test] +quotingTests env = + [ test "runAt with special characters in the executable path" $ do + exe <- specialExe + r <- runAt (cfgFor exe) add 2 3 + assertEqual "add" 5 r + + , test "runAt with useSudo and special characters in the path" $ do + exe <- specialExe + r <- runAt (cfgFor exe & useSudo True) add 2 3 + assertEqual "add" 5 r + + , test "runAt with setUser and special characters in the path" $ do + exe <- specialExe + clearFakeLog env + r <- runAt (cfgFor exe & setUser "rpc 'user'") add 2 3 + assertEqual "add" 5 r + logged <- readFakeLog env + assertBool ("su: " ++ show logged) + (any ("su [rpc 'user'] [-c] " `isPrefixOf`) logged) + + , test "runAt with setRemote and special characters in the path" $ do + exe <- specialExe + r <- runAt (cfgFor exe & setRemote ("u@h", "22")) add 2 3 + assertEqual "add" 5 r + + , test "runAt with setRemote, setUser, useSudo and a special path" $ do + exe <- specialExe + clearFakeLog env + let cfg = + cfgFor exe + & setRemote ("u@h", "22") + & setUser "rpc 'user'" + & useSudo True + r <- runAt cfg three 1 "a 'b' $c" True + assertEqual "three" (1, "a 'b' $c", True) r + logged <- readFakeLog env + assertBool ("su: " ++ show logged) + (any ("su [rpc 'user'] [-c] " `isPrefixOf`) logged) + ] + + where + + cfgFor exe = serverConfig env & setImage (Executable exe testVersion) + + -- A symbolic link to the test executable in specialDirName + specialExe = do + let dir = envDir env specialDirName + exe = dir "server" + exists <- doesFileExist exe + unless exists $ do + createDirectory dir + createFileLink (envExe env) exe + pure exe + ------------------------------------------------------------------------------- -- Unicode ------------------------------------------------------------------------------- @@ -478,4 +550,5 @@ main = do ++ clientTests env ++ installTests env ++ unicodeTests env + ++ quotingTests env runTests seed tests `finally` cleanupEnv env diff --git a/rpc/test/TestUtil.hs b/rpc/test/TestUtil.hs index e159ea7..43dd6a0 100644 --- a/rpc/test/TestUtil.hs +++ b/rpc/test/TestUtil.hs @@ -23,12 +23,14 @@ module TestUtil import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Exception (IOException, catch, evaluate) +import Control.Monad (forM_, when) import Data.Aeson (Value, toJSON) import System.Directory - ( Permissions, createDirectory, getPermissions, getTemporaryDirectory - , removeDirectoryRecursive, setOwnerExecutable, setPermissions ) + ( Permissions, createDirectory, findExecutable, getCurrentDirectory + , getPermissions, getTemporaryDirectory, removeDirectoryRecursive + , setCurrentDirectory, setOwnerExecutable, setPermissions ) import System.Environment - (getEnvironment, getExecutablePath, lookupEnv, setEnv) + (getEnvironment, getExecutablePath, lookupEnv, setEnv, unsetEnv) import System.Exit (ExitCode) import System.FilePath (()) import System.IO (hClose, hSetBinaryMode) @@ -58,6 +60,7 @@ serverMode = ("SIMPLE_RPC_TEST_MODE", "server") data Env = Env { envDir :: FilePath -- ^ temporary directory for the tests + , envOrigDir :: FilePath -- ^ working directory before 'setupEnv' , envExe :: FilePath -- ^ path of the test executable , envFakeLog :: FilePath -- ^ invocations of the fake commands } @@ -148,10 +151,20 @@ fakeServer env name version output = do pure path -- | Create the temporary directory and the fake commands, put the fake --- commands first in @PATH@ and make the child processes of the test --- executable run as the RPC server. +-- commands first in @PATH@, make the temporary directory the working +-- directory and make the child processes of the test executable run as the +-- RPC server. +-- +-- The tests run @sudo@, @su@, @ssh@ and @scp@ commands. Raise an exception +-- if @PATH@ does not find the fake command for any of them, so that a test +-- never runs the real one. +-- +-- With the temporary directory as the working directory, a relative path or +-- a glob in a wrongly quoted command refers to the files of the temporary +-- directory only. setupEnv :: IO Env setupEnv = do + origDir <- getCurrentDirectory tmp <- getTemporaryDirectory pid <- getProcessID exe <- getExecutablePath @@ -172,10 +185,21 @@ setupEnv = do setEnv "SIMPLE_RPC_FAKE_HOME" home setEnv "SIMPLE_RPC_FAKE_LOG" logFile uncurry setEnv serverMode - pure $ Env dir exe logFile + -- Used in a test path, must expand to an empty string + unsetEnv "SIMPLE_RPC_UNSET" + forM_ ["ssh", "scp", "sudo", "su"] $ \cmd -> do + found <- findExecutable cmd + when (found /= Just (bin cmd)) + $ ioError $ userError + $ "setupEnv: PATH finds " ++ show found ++ " for " ++ cmd + ++ ", not the fake " ++ show (bin cmd) + setCurrentDirectory dir + pure $ Env dir origDir exe logFile cleanupEnv :: Env -> IO () -cleanupEnv env = removeDirectoryRecursive (envDir env) +cleanupEnv env = do + setCurrentDirectory (envOrigDir env) + removeDirectoryRecursive (envDir env) -- | The lines of the fake command log. readFakeLog :: Env -> IO [String] From bd3a7173c944d5de41363785b3efb134a8967e7c Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:24:16 +0530 Subject: [PATCH 11/32] Pass the setImageFlags flags to the server executable runAt ignored rcImageFlags. It now passes the flags, split at white space, before the endpoint name. --- rpc/lib/Simple/RPC/Client.hs | 2 +- rpc/lib/Simple/RPC/Internal/Types.hs | 8 +++++++- rpc/test/Main.hs | 23 +++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 267668c..67c3868 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -185,7 +185,7 @@ with (RunningConfig{..}) actionName input = do maybe id sshCommand rcRemote $ userWrapper rcUser $ sudoWrapper rcSudo - (executablePath rcImage, [actionName]) + (executablePath rcImage, words rcImageFlags ++ [actionName]) send $ showPair "ACT" actionName pipe send exe args input diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 52af9e4..c840807 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -184,7 +184,13 @@ defaultConfig exe = setImage :: Executable -> RunningConfig -> RunningConfig setImage x rc = rc { rcImage = x } --- | Use these flags when invoking the RPC server image. +-- | Use these flags when invoking the RPC server image for an endpoint call. +-- The flags are split into words at white space, a word cannot contain white +-- space or quotes. The version check invokes the image without the flags. +-- +-- The server accepts one argument, the endpoint name, therefore the flags +-- can only be options that the server program does not see, e.g. GHC RTS +-- options @+RTS -N -RTS@ if the server is linked with @-rtsopts@. -- -- Default is "" i.e. no flags. setImageFlags :: String -> RunningConfig -> RunningConfig diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 72aa31f..fbc4ab5 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -338,6 +338,29 @@ clientTests env = -- Do not force the result Right _ -> assertBool "runAt returned without an exception" False + , test "runAt passes the setImageFlags flags to the executable" $ do + let wrapper = envDir env "flags-server" + argsFile = envDir env "flags-server.args" + writeScript wrapper $ unlines + [ "#!/bin/sh" + , "{ echo call; printf '%s\\n' \"$@\"; } >> '" ++ argsFile ++ "'" + , "exec '" ++ envExe env ++ "' \"$@\"" + ] + let cfg = + serverConfig env + & setImage (Executable wrapper testVersion) + & setImageFlags "+RTS -A2m\t-RTS " + r <- runAt cfg add 2 3 + assertEqual "add" 5 r + calls <- lines <$> readFile argsFile + -- printf prints an empty line for the version check, which has + -- no arguments. + assertEqual "arguments" + [ "call", "" + , "call", "+RTS", "-A2m", "-RTS", "TestFunctions.add" + ] + calls + , test "runAt with setUser runs the endpoint through sudo su" $ do clearFakeLog env r <- runAt (serverConfig env & setUser "rpcuser") add 2 3 From 7609cf612f9f680b5d8c2802f81d74e407671836 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:26:24 +0530 Subject: [PATCH 12/32] Do not make the installOnRemote directory world-writable installOnRemote ran chmod a+rw on the target directory and left it so. It also overwrote a running executable in place and quoted paths with show. It now copies to a mktemp file, installs it with sudo install -m 755, and quotes the remote commands for the shell. --- rpc/lib/Simple/RPC/Client.hs | 82 ++++++++++++++++++++++++------------ rpc/test/Main.hs | 52 +++++++++++++++++++++++ 2 files changed, 108 insertions(+), 26 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 67c3868..2fb1360 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -29,7 +29,7 @@ module Simple.RPC.Client -- Imports -------------------------------------------------------------------------------- -import Control.Exception (SomeException, throwIO, try) +import Control.Exception (SomeException, onException, throwIO, try) import Control.Monad (when) import Data.Char (isAsciiLower, isAsciiUpper, isDigit) import Data.Function ((&)) @@ -42,7 +42,6 @@ import qualified Data.IORef as IORef import qualified Streamly.Internal.Data.Array as Array (compactEndByLn_) import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream -import qualified Streamly.Internal.System.Command as Cmd import qualified Streamly.Internal.System.Process as Proc import qualified Streamly.Internal.Unicode.Stream as Unicode @@ -76,17 +75,20 @@ shellQuote x shellCommand :: FilePath -> [String] -> String shellCommand exe args = unwords (map shellQuote (exe : args)) +-- | @sshShell remote cmd@ runs the shell command line @cmd@ on the @remote@ +-- (address, port) using ssh. ssh passes the command to the shell of the +-- remote user. +sshShell :: (String, String) -> String -> (FilePath, [String]) +sshShell (addr, port) cmd = + ("ssh", ["-T", "-p", port, "-o", "StrictHostKeyChecking off", addr, cmd]) + -- | @sshCommand remote (exe, args)@ runs @exe args@ on the @remote@ (address, --- port) using ssh. ssh passes the command to the shell of the remote user. +-- port) using ssh. sshCommand :: (String, String) -> (FilePath, [String]) -> (FilePath, [String]) -sshCommand (addr, port) (exe, args) = - ( "ssh" - , [ "-T", "-p", port, "-o", "StrictHostKeyChecking off", addr - , shellCommand exe args - ] - ) - -versionGuard :: (String -> IO ()) -> Maybe (String, String) -> Executable -> IO () +sshCommand remote (exe, args) = sshShell remote (shellCommand exe args) + +versionGuard + :: (String -> IO ()) -> Maybe (String, String) -> Executable -> IO () versionGuard send mSshConf exe = do let exePath = executablePath exe exeVersionExpected = executableVersion exe @@ -234,26 +236,54 @@ run = direct -- XXX scpRpcImage --- | @installOnRemote localPath sshEndpoint remotePath@. Install the RPC --- endpoint server executable on a remote machine using @scp@. Requires @sudo@ --- access to create the directory if it does not exist. +-- | @installOnRemote localExe sshEndpoint remotePath@. Install the RPC +-- endpoint server executable on a remote machine: +-- +-- * check the version of the local executable, +-- * copy it with @scp@ to a temporary file created by @mktemp@ on the remote +-- machine, +-- * create the directory of @remotePath@ with @sudo mkdir -p@, if it does not +-- exist, and copy the temporary file to @remotePath@ with +-- @sudo install -m 755@, the file is owned by root and is readable and +-- executable by all users, +-- * remove the temporary file. +-- +-- The permissions of an existing directory are not changed. @install@ +-- creates a new file, therefore an instance of the executable that is +-- running is not affected. Requires @sudo@ access, @mktemp@ and @install@ +-- on the remote machine. +-- +-- Raise a 'VersionMismatch' exception if the local executable prints a +-- version other than 'executableVersion', and a +-- 'Streamly.Internal.System.Process.ProcessFailure' exception if a command +-- fails. installOnRemote :: Executable -> (String, String) -> FilePath -> IO () installOnRemote localExe sshConf@(addr, port) remoteExePath = do let exePath = executablePath localExe remoteExeDir = takeDirectory remoteExePath versionGuard putStrLn Nothing localExe - Cmd.toStdout $ mkSSHCmd sshConf [str|sudo mkdir -p #{remoteExeDir}|] - - -- XXX this is unsafe, gives write access to anyone. - Cmd.toStdout $ mkSSHCmd sshConf [str|sudo chmod a+rw #{remoteExeDir}|] - Cmd.toStdout [str|scp -P #{port} #{exePath} #{addr}:#{remoteExePath}|] - -- XXX nned chmod o-w - Cmd.toStdout $ mkSSHCmd sshConf [str|sudo chmod a+r #{remoteExeDir}|] - -- XXX we do not need sudo for this. - Cmd.toStdout $ mkSSHCmd sshConf [str|sudo chmod a+x #{remoteExePath}|] + tmpOut <- uncurry Proc.toString $ sshCommand sshConf ("mktemp", []) + let tmp = takeWhile (/= '\n') tmpOut + removeTmp = + uncurry Proc.toStdout $ sshCommand sshConf ("rm", ["-f", tmp]) + flip onException removeTmp + $ Proc.toStdout "scp" + ["-P", port, scpLocalPath exePath, addr ++ ":" ++ tmp] + let qTmp = shellQuote tmp + install = + shellCommand "sudo" ["mkdir", "-p", remoteExeDir] + ++ " && " + ++ shellCommand "sudo" + ["install", "-m", "755", tmp, remoteExePath] + ++ "; r=$?; rm -f " ++ qTmp ++ "; exit $r" + uncurry Proc.toStdout $ sshShell sshConf install where - mkSSHCmd (a, p) cmd = - let qCmd = show cmd - in [str|ssh -T -p #{p} -o "StrictHostKeyChecking off" #{a} #{qCmd}|] + -- scp takes a path with a colon before any slash as a remote path, and a + -- path that starts with a dash as an option. + scpLocalPath p = + case break (\c -> c == ':' || c == '/') p of + (_, ':' : _) -> "./" ++ p + ('-' : _, _) -> "./" ++ p + _ -> p diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index fbc4ab5..7f35e67 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -8,10 +8,12 @@ module Main (main) where import Control.Exception (displayException, finally, try) import Control.Monad (unless) +import Data.Bits ((.&.)) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.IORef (modifyIORef, newIORef, readIORef) import Data.List (isPrefixOf, sort) +import Numeric (showOct) import Streamly.Internal.System.Process (ProcessFailure(..)) import System.Directory ( createDirectory, createFileLink, doesFileExist, executable @@ -19,6 +21,11 @@ import System.Directory import System.Environment (getArgs, lookupEnv) import System.Exit (ExitCode(..)) import System.FilePath (()) +import System.IO (hClose, hPutStr) +import System.Posix.Files (fileMode, getFileStatus, setFileMode) +import System.Process + ( CreateProcess(std_in, std_out), StdStream(..), createProcess, proc + , waitForProcess ) import Test.QuickCheck (forAll, ioProperty, withMaxSuccess) import qualified Data.Aeson as Json @@ -417,6 +424,51 @@ installTests env = logged <- readFakeLog env assertBool ("scp: " ++ show logged) (any ("scp [-P] [22] " `isPrefixOf`) logged) + + , test "installOnRemote keeps the permissions of the directory" $ do + let destDir = envDir env "install2" + dest = destDir "server" + createDirectory destDir + setFileMode destDir 0o755 + clearFakeLog env + installOnRemote + (Executable (envExe env) testVersion) ("u@h", "22") dest + -- The last scp argument is "u@h:" + logged <- readFakeLog env + case filter ("scp " `isPrefixOf`) logged of + [line] -> do + let tmp = drop (length ("[u@h:" :: String)) + $ init $ last $ words line + tmpExists <- doesFileExist tmp + assertBool ("temporary file removed: " ++ tmp) (not tmpExists) + other -> assertBool ("one scp call: " ++ show other) False + dirMode <- fileMode <$> getFileStatus destDir + assertEqual "directory mode" "755" (showOct (dirMode .&. 0o777) "") + exeMode <- fileMode <$> getFileStatus dest + assertEqual "executable mode" "755" (showOct (exeMode .&. 0o777) "") + + , test "installOnRemote with special characters in the path" $ do + let dest = envDir env "install3" specialDirName "srv" + installOnRemote + (Executable (envExe env) testVersion) ("u@h", "22") dest + r <- runAt (serverConfig env & setImage (Executable dest testVersion)) + add 2 3 + assertEqual "installed server" 5 r + + , test "installOnRemote replaces a running executable" $ do + let dest = envDir env "install4" "server" + exe = Executable (envExe env) testVersion + installOnRemote exe ("u@h", "22") dest + -- The server waits for its input on stdin + (Just hin, _, _, ph) <- + createProcess + (proc dest ["TestFunctions.add"]) + { std_in = CreatePipe, std_out = CreatePipe } + installOnRemote exe ("u@h", "22") dest + `finally` do + hPutStr hin "[1,2]" + hClose hin + waitForProcess ph ] ------------------------------------------------------------------------------- From 0670fc9874d9bb7684c7e36b2dc6f4ac978c35c3 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:29:15 +0530 Subject: [PATCH 13/32] Add a benchmark suite Time toBinStream on large JSON values, and runAt with a large argument and a large result. The heap is limited to 1G. --- rpc/benchmark/Main.hs | 110 ++++++++++++++++++++++++++++++++++++++++++ rpc/simple-rpc.cabal | 12 +++++ 2 files changed, 122 insertions(+) create mode 100644 rpc/benchmark/Main.hs diff --git a/rpc/benchmark/Main.hs b/rpc/benchmark/Main.hs new file mode 100644 index 0000000..1807e2c --- /dev/null +++ b/rpc/benchmark/Main.hs @@ -0,0 +1,110 @@ +-- | Benchmarks of the IR serialization and of local RPC calls. The benchmark +-- executable runs as the RPC server when the environment variable +-- @SIMPLE_RPC_BENCH_MODE@ is @server@. +-- +-- Usage: simple-rpc-bench [ITERATIONS] +-- +module Main (main) where + +------------------------------------------------------------------------------- +-- Imports +------------------------------------------------------------------------------- + +import Control.Exception (evaluate) +import Control.Monad (forM, forM_, void) +import Data.Function ((&)) +import GHC.Clock (getMonotonicTime) +import System.Environment (getArgs, getExecutablePath, lookupEnv, setEnv) +import Text.Printf (printf) + +import qualified Data.Aeson as Json +import qualified Streamly.Data.Fold as Fold +import qualified Streamly.Data.Stream as Stream + +import Simple.RPC + +------------------------------------------------------------------------------- +-- Endpoints +------------------------------------------------------------------------------- + +benchVersion :: String +benchVersion = "bench-1.0" + +raw_replicateChar :: Int -> Char -> IO String +raw_replicateChar n c = pure (replicate n c) +$(rpcExport "raw_replicateChar" "replicateChar") + +raw_stringLength :: String -> IO Int +raw_stringLength = pure . length +$(rpcExport "raw_stringLength" "stringLength") + +rpcMap :: RpcMap IntermediateRep +rpcMap = + createRpcMap [evaluator replicateChar, evaluator stringLength] + +------------------------------------------------------------------------------- +-- Measurement +------------------------------------------------------------------------------- + +-- | @bench iterations name action@ runs the action, prints the minimum and +-- the mean time in milliseconds. +bench :: Int -> String -> IO () -> IO () +bench iterations name action = do + times <- forM [1 .. iterations] $ \_ -> do + t0 <- getMonotonicTime + action + t1 <- getMonotonicTime + pure (t1 - t0) + let ms x = x * 1000 :: Double + mean = sum times / fromIntegral (length times) + printf "%-40s min %9.2f ms mean %9.2f ms\n" + name (ms (minimum times)) (ms mean) + +-- | A JSON string of @n@ characters. +jsonString :: Int -> IntermediateRep +jsonString n = toIntermediateRep (replicate n 'x') + +------------------------------------------------------------------------------- +-- Main +------------------------------------------------------------------------------- + +main :: IO () +main = do + mode <- lookupEnv "SIMPLE_RPC_BENCH_MODE" + if mode == Just "server" + then mainWith benchVersion rpcMap + else do + args <- getArgs + let iterations = case args of + [n] -> read n + _ -> 5 + setEnv "SIMPLE_RPC_BENCH_MODE" "server" + exe <- getExecutablePath + let cfg = + defaultConfig (Executable exe benchVersion) + & setLogger (const (pure ())) + forM_ [1, 4] $ \mb -> do + let n = mb * 1000000 + v = jsonString n + _ <- evaluate (Json.encode v) + bench iterations (printf "toBinStream string %d MB" mb) + $ toBinStream v & Stream.fold Fold.sum >>= void . evaluate + -- An array of n numbers is about 8n bytes of JSON + forM_ [125000, 500000] $ \n -> do + let v = toIntermediateRep [1 .. n :: Int] + name = printf "toBinStream [Int] %d MB" (n `div` 125000) + _ <- evaluate (Json.encode v) + bench iterations name + $ toBinStream v & Stream.fold Fold.sum >>= void . evaluate + forM_ [1, 4] $ \mb -> do + let n = mb * 1000000 + s = replicate n 'x' + _ <- evaluate (length s) + bench iterations (printf "runAt input %d MB" mb) $ do + r <- runAt cfg stringLength s + _ <- evaluate r + pure () + bench iterations (printf "runAt output %d MB" mb) $ do + r <- runAt cfg replicateChar n 'x' + _ <- evaluate (length r) + pure () diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 8fd1678..347043f 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -85,3 +85,15 @@ test-suite simple-rpc-test , streamly-process , unix , unordered-containers + +benchmark simple-rpc-bench + import: lib-options + type: exitcode-stdio-1.0 + main-is: Main.hs + hs-source-dirs: benchmark + -- The benchmark executable also runs as the RPC server. + ghc-options: -threaded -rtsopts -with-rtsopts=-M1G + build-depends: base + , simple-rpc + , aeson + , streamly-core From fa970f6cae8e97bc8b5a111401da5891c88490e9 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:33:18 +0530 Subject: [PATCH 14/32] Make toBinStream linear in the size of the encoding toBinStream used BSL.index, which walks the chunk list from the start for every byte. It now unfolds the bytes of each chunk, and is inlined to fuse with the consumer. toChunkStream copies whole chunks. --- rpc/lib/Simple/RPC/Internal/Types.hs | 34 +++++++++++++++++----------- rpc/lib/Simple/RPC/Server.hs | 2 +- rpc/test/Main.hs | 20 +++++++++++++++- 3 files changed, 41 insertions(+), 15 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index c840807..12e2878 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -78,6 +78,7 @@ import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Bifunctor import qualified Data.ByteString as BS +import qualified Data.ByteString.Unsafe as BS.Unsafe import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM import qualified Data.Text.Encoding.Error as Text @@ -86,7 +87,9 @@ import qualified Data.Text.Lazy.Encoding as TextL import qualified Data.Vector as Vector import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream -import qualified Streamly.Internal.Data.Array as Array (unsafePinnedAsPtr) +import qualified Streamly.Data.Unfold as Unfold +import qualified Streamly.Internal.Data.Array as Array + (fromPtrN, unsafePinnedAsPtr) import qualified Streamly.Unicode.Stream as Unicode -------------------------------------------------------------------------------- @@ -394,24 +397,29 @@ createObj kv = Json.object $ map (Data.Bifunctor.first Key.fromString) kv -- Conversions of IR -------------------------------------------------------------------------------- --- | Convert the Haskell representation of IR (i.e. Json) to a byte stream. +-- | Convert the Haskell representation of IR (i.e. Json) to a byte stream of +-- its JSON encoding. +-- +-- The stream is generated from the chunks of the lazy encoding, the time is +-- linear in the size of the encoding. +{-# INLINE toBinStream #-} toBinStream :: Monad m => IntermediateRep -> Stream m Word8 toBinStream input = - Stream.enumerateFromTo 0 (len - 1) - & fmap (BSL.index bsl) - - where - bsl = Json.encode input - len = BSL.length bsl + Stream.fromList (BSL.toChunks (Json.encode input)) + & Stream.unfoldEach (Unfold.lmap BS.unpack Unfold.fromList) --- TODO: Convert Bytestring to Array directly +-- | Copy a ByteString to an array. +byteStringToArray :: BS.ByteString -> IO (Array Word8) +byteStringToArray c = + BS.Unsafe.unsafeUseAsCStringLen c + $ \(p, n) -> Array.fromPtrN n (castPtr p) -- | Convert the Haskell representation of IR (i.e. Json) to a stream of --- arrays. -toChunkStream :: IntermediateRep -> Stream IO (Array.Array Word8) +-- arrays of its JSON encoding, one array for each chunk of the lazy encoding. +toChunkStream :: IntermediateRep -> Stream IO (Array Word8) toChunkStream input = - toBinStream input - & Array.chunksOf 1024 + Stream.fromList (BSL.toChunks (Json.encode input)) + & Stream.mapM byteStringToArray -- | Convert a byte stream of IR (i.e. Json) to its Haskell representation. fromBinStream :: Stream IO Word8 -> IO IntermediateRep diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index 2ce0802..97c9990 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -62,7 +62,7 @@ invokeFunction actions actionName = Right x -> pure x output <- actFun input putStrLn "" - toBinStream output & Stream.fold (FH.write stdout) + toChunkStream output & Stream.fold (FH.writeChunks stdout) -- | The main function for the RPC endpoint executable. The first argument is -- the version number. The behavior of the main function in the executable is diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 7f35e67..5cad2c0 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -6,13 +6,15 @@ module Main (main) where -- Imports ------------------------------------------------------------------------------- -import Control.Exception (displayException, finally, try) +import Control.Exception (displayException, evaluate, finally, try) import Control.Monad (unless) import Data.Bits ((.&.)) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) +import Data.Int (Int64) import Data.IORef (modifyIORef, newIORef, readIORef) import Data.List (isPrefixOf, sort) +import GHC.Clock (getMonotonicTime) import Numeric (showOct) import Streamly.Internal.System.Process (ProcessFailure(..)) import System.Directory @@ -33,6 +35,7 @@ import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM +import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream import qualified Test.QuickCheck as QC @@ -92,6 +95,21 @@ commonTests = in bytes == BSL.unpack (Json.encode v) && Json.decode (BSL.pack bytes) == Just v + , test "toBinStream time is linear in the size" $ do + -- About 24 MB of JSON in about 750 chunks. A time quadratic in the + -- number of chunks takes more than 30 seconds. + let v = toIntermediateRep [1 .. 3000000 :: Int] + len = BSL.length (Json.encode v) + _ <- evaluate len + t0 <- getMonotonicTime + -- Force each byte, the stream may have lazy elements + let count n w = w `seq` n + 1 + total <- + toBinStream v & Stream.fold (Fold.foldl' count (0 :: Int64)) + t1 <- getMonotonicTime + assertEqual "length" len total + assertBool ("took " ++ show (t1 - t0) ++ " seconds") (t1 - t0 < 5) + , test "rpcName is the module qualified endpoint name" $ do assertEqual "echoInt" "TestFunctions.echoInt" (rpcName echoInt) assertEqual "constant" "TestFunctions.constant" (rpcName constant) From 2f645f2ce053079e18014ea7f0f7cd5d4c9f76fd Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:36:20 +0530 Subject: [PATCH 15/32] Read the server input before raising EndpointNotFound streamly-process 0.4.1 keeps writing the input after the server exits, so an unknown endpoint with a large input gave a broken pipe error instead of the server error. invokeFunction now reads the input first. Add expected failure support to the test harness. --- rpc/lib/Simple/RPC/Client.hs | 6 +++++ rpc/lib/Simple/RPC/Server.hs | 16 +++++++------ rpc/test/Harness.hs | 45 ++++++++++++++++++++++++++++-------- rpc/test/Main.hs | 37 ++++++++++++++++++++++++++++- rpc/test/TestUtil.hs | 2 +- 5 files changed, 87 insertions(+), 19 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 2fb1360..f9db1ac 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -217,6 +217,12 @@ with (RunningConfig{..}) actionName input = do -- * an 'EmptyOutput' exception if the server does not print an output line, -- * an 'InvalidOutput' exception if the last output line of the server is not -- the JSON encoding of the result type. +-- +-- With streamly-process 0.4.1, if the server process exits before it reads +-- all of the input and the input is larger than the pipe buffer, the call +-- raises an 'IOError' for the broken pipe instead of the +-- 'Streamly.Internal.System.Process.ProcessFailure' exception. The server reads the whole input before it raises an exception +-- for an unknown endpoint. runAt :: RunningConfig -> RpcSymbol IntermediateRep typ -> typ runAt cfg sym = call sym (with cfg) diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index 97c9990..e7d52a3 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -42,17 +42,19 @@ import Simple.RPC.Internal.Types -- Raise an 'EndpointNotFound' exception if the map does not have the -- function, and an 'InvalidInput' exception if the input is not valid JSON. invokeFunction :: RpcMap IntermediateRep -> String -> IO () -invokeFunction actions actionName = +invokeFunction actions actionName = do + -- XXX we should not buffer the input, it should be directly streamed to + -- the function, otherwise we cannot support infinite or large input. + + -- Read the input before raising an exception for an unknown endpoint. A + -- client writing the input to a process that has exited gets a broken + -- pipe error instead of the exit code of the process. + inputBytes <- + FH.read stdin & Stream.fold (Fold.takeEndBy_ (== 10) Array.create) case lookupRpcSymbol actionName actions of Nothing -> throwIO (EndpointNotFound actionName) Just actFun -> do hSetEncoding stdout utf8 - -- XXX we should not buffer the input, it should be directly - -- streamed to the function, otherwise we cannot support - -- infinite or large input. - inputBytes <- - FH.read stdin - & Stream.fold (Fold.takeEndBy_ (== 10) Array.create) let inputString = decodeUtf8Array inputBytes putStrLn $ showPair "SERVER" [str|#{actionName} #{inputString}|] r <- irFromArray inputBytes diff --git a/rpc/test/Harness.hs b/rpc/test/Harness.hs index 718a50d..67f60b2 100644 --- a/rpc/test/Harness.hs +++ b/rpc/test/Harness.hs @@ -4,6 +4,7 @@ module Harness ( Test , test + , expectFailure , runTests , assertEqual , assertBool @@ -94,12 +95,20 @@ property p = do -- Running ------------------------------------------------------------------------------- -data Test = Test String (IO ()) +data Test + = Test String (IO ()) + | ExpectFailure String String (IO ()) -- | A named test case. test :: String -> IO () -> Test test = Test +-- | @expectFailure reason name action@ is a test case that fails because of +-- a known defect described by @reason@. It is reported as XFAIL when it +-- fails, and fails as XPASS when it passes, the defect is then fixed. +expectFailure :: String -> String -> IO () -> Test +expectFailure reason name = ExpectFailure name reason + -- | Seconds after which a test is reported as failed. testTimeout :: Int testTimeout = 120 @@ -121,19 +130,35 @@ runTests seed tests = do where - runOne (Test name action) = do + run name action = do putStr (name ++ " ... ") hFlush stdout r <- try (timeout (testTimeout * 1000000) action) + pure $ case r of + Right (Just ()) -> Nothing + Right Nothing -> + Just $ "timed out after " ++ show testTimeout ++ " seconds" + -- displayException of SomeException adds the backtrace + Left (SomeException e) -> Just (displayException e) + + runOne (Test name action) = do + r <- run name action case r of - Right (Just ()) -> putStrLn "OK" >> pure (name, True) - Right Nothing -> do + Nothing -> putStrLn "OK" >> pure (name, True) + Just err -> do putStrLn "FAIL" - putStrLn - $ " timed out after " ++ show testTimeout ++ " seconds" + putStrLn $ " " ++ err pure (name, False) - Left (SomeException e) -> do - -- displayException of SomeException adds the backtrace - putStrLn "FAIL" - putStrLn $ " " ++ displayException e + + runOne (ExpectFailure name reason action) = do + r <- run name action + case r of + Nothing -> do + putStrLn "XPASS" + putStrLn $ " expected to fail: " ++ reason pure (name, False) + Just err -> do + putStrLn "XFAIL" + putStrLn $ " " ++ reason + putStrLn $ " " ++ err + pure (name, True) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 5cad2c0..51747be 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -13,7 +13,7 @@ import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.Int (Int64) import Data.IORef (modifyIORef, newIORef, readIORef) -import Data.List (isPrefixOf, sort) +import Data.List (isInfixOf, isPrefixOf, sort) import GHC.Clock (getMonotonicTime) import Numeric (showOct) import Streamly.Internal.System.Process (ProcessFailure(..)) @@ -325,6 +325,41 @@ clientTests env = assertThrows "failing" (\(ProcessFailure n) -> n == 1) (runAt (serverConfig env) failing 1) + , expectFailure + "streamly-process 0.4.1 writes stdin after the process exits" + "runAt raises ProcessFailure when the server ignores the input" $ do + -- The input is larger than the pipe buffer + let path = envDir env "exit3-server" + writeScript path $ unlines + [ "#!/bin/sh" + , "if [ $# -eq 0 ]; then printf 1; exit 0; fi" + , "exit 3" + ] + assertThrows "exit 3" (\(ProcessFailure n) -> n == 3) + (runAt + (serverConfig env & setImage (Executable path "1")) + echoString (replicate 1000000 'x')) + + , test "runAt raises ProcessFailure for an unknown endpoint" $ do + -- A server that does not have the endpoint, the input is larger + -- than the pipe buffer. + let path = envDir env "unknown-endpoint-server" + writeScript path $ unlines + [ "#!/bin/sh" + , "[ $# -eq 0 ] && exec '" ++ envExe env ++ "'" + , "exec '" ++ envExe env ++ "' TestFunctions.nope" + ] + (cfg, getLog) <- loggingConfig env + assertThrows "unknown" (\(ProcessFailure n) -> n == 1) + (runAt + (cfg & setImage (Executable path testVersion)) + echoString (replicate 1000000 'x')) + logged <- getLog + let msg = displayException (EndpointNotFound "TestFunctions.nope") + isErr l = "[STDERR]" `isPrefixOf` l + assertBool ("stderr logged: " ++ show (filter isErr logged)) + (any (\l -> isErr l && msg `isInfixOf` l) logged) + , test "runAt raises VersionMismatch on a version mismatch" $ assertThrows "version" (== VersionMismatch (envExe env) "other" testVersion) diff --git a/rpc/test/TestUtil.hs b/rpc/test/TestUtil.hs index 43dd6a0..10130e8 100644 --- a/rpc/test/TestUtil.hs +++ b/rpc/test/TestUtil.hs @@ -277,7 +277,7 @@ genValue = QC.sized go leaves = [ pure Json.Null , Json.Bool <$> QC.arbitrary - , (\x -> Json.Number (fromIntegral x)) <$> (QC.arbitrary :: Gen Integer) + , Json.Number . fromIntegral <$> (QC.arbitrary :: Gen Integer) , toJSON <$> (QC.arbitrary :: Gen String) ] From 929e5bd185ffba3d838c513712bd009c39e509dc Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:38:31 +0530 Subject: [PATCH 16/32] Test evaluator directly and invalid UTF-8 server output Call an endpoint evaluator from createRpcMap in process, and check that runAt logs an invalid UTF-8 output line and still decodes the result. --- rpc/test/Main.hs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 51747be..f0549e5 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -140,6 +140,24 @@ serverTests env = ]) (sort (HM.keys rpcMap)) + , test "evaluator in createRpcMap calls the function with IR" $ do + let m = createRpcMap [evaluator add, evaluator constant] + case HM.lookup "TestFunctions.add" m of + Nothing -> assertBool "add not found" False + Just f -> do + r <- f (toIntermediateRep [2, 3 :: Int]) + assertEqual "add" (toIntermediateRep (5 :: Int)) r + assertThrows "add [1]" + (\e -> case e of + InvalidInput _ -> True + _ -> False) + (f (toIntermediateRep [1 :: Int])) + case HM.lookup "TestFunctions.constant" m of + Nothing -> assertBool "constant not found" False + Just f -> do + r <- f (toIntermediateRep ([] :: [Int])) + assertEqual "constant" (toIntermediateRep (42 :: Int)) r + , test "mainWith without arguments prints the version" $ do (code, out, _) <- runServerRaw env [] [] "" assertEqual "exit code" ExitSuccess code @@ -636,6 +654,15 @@ unicodeTests env = echoString "x" assertEqual "result" "T\233st\8594" r + , test "runAt logs invalid UTF-8 output with replacement characters" $ do + path <- fakeServer env "invalid-utf8-server" "1" "\xff\xfe\n7" + (cfg, getLog) <- loggingConfig env + r <- runAt (cfg & setImage (Executable path "1")) echoInt 1 + assertEqual "result" 7 r + logged <- getLog + assertBool ("log: " ++ show logged) + ("[STDOUT] \65533\65533" `elem` logged) + , test "runAt round trips Unicode String arguments" $ do let cfg = serverConfig env property $ withMaxSuccess 20 $ forAll genUnicodeString $ \s -> From 856503311893d5232fdf8e2c86291e7b86376e9f Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:41:00 +0530 Subject: [PATCH 17/32] Correct and complete the documentation Correct the setRemote, setUser, defaultConfig and RpcSymbol docs, and document the version check, the output protocol, the steps of runAt and the requirements of rpcExport. Add module headers. --- rpc/lib/Simple/RPC.hs | 4 ++ rpc/lib/Simple/RPC/Client.hs | 13 ++++++ rpc/lib/Simple/RPC/Internal/TH.hs | 22 ++++++++- rpc/lib/Simple/RPC/Internal/Types.hs | 69 ++++++++++++++++++++++------ rpc/lib/Simple/RPC/Server.hs | 22 ++++++++- 5 files changed, 113 insertions(+), 17 deletions(-) diff --git a/rpc/lib/Simple/RPC.hs b/rpc/lib/Simple/RPC.hs index 0bcc192..0f3b392 100644 --- a/rpc/lib/Simple/RPC.hs +++ b/rpc/lib/Simple/RPC.hs @@ -1,3 +1,7 @@ +-- | Make RPC calls to Haskell functions in an executable on a local or a +-- remote host. This module re-exports "Simple.RPC.Client", +-- "Simple.RPC.Server" and "Simple.RPC.Common". +-- module Simple.RPC ( module Simple.RPC.Client diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index f9db1ac..de3e3f7 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -1,6 +1,9 @@ {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE RecordWildCards #-} +-- | Call the RPC endpoints of a server executable on the local host or, using +-- ssh, on a remote host. +-- module Simple.RPC.Client ( -- * RPC call @@ -208,6 +211,16 @@ with (RunningConfig{..}) actionName input = do -- | Make a RPC call at the remote host specified by the first argument. -- +-- The call runs the executable twice, without arguments to check its version, +-- and with the endpoint name to call the endpoint. The arguments are written +-- to the stdin of the server as a JSON array, the last line of the stdout of +-- the server is decoded as the result. The stderr of the server is buffered +-- in memory and logged after the server exits. The result is decoded before +-- the call returns. +-- +-- On a remote host, the output of the shell startup files of the ssh user, +-- if any, is part of the version check output and causes a version mismatch. +-- -- The call raises: -- -- * a 'VersionMismatch' exception if the server executable prints a version diff --git a/rpc/lib/Simple/RPC/Internal/TH.hs b/rpc/lib/Simple/RPC/Internal/TH.hs index ba5afbe..f793358 100644 --- a/rpc/lib/Simple/RPC/Internal/TH.hs +++ b/rpc/lib/Simple/RPC/Internal/TH.hs @@ -31,9 +31,27 @@ getNumArgs :: Type -> Int getNumArgs typ = length (breakTypeOnArrow typ) - 1 -- | @rpcExport origName rpcName@, creates a toplevel value definition with --- the name @rpcName@, of type 'RpcSymbol' representing an RPC endpoint. +-- the name @rpcName@, of type t'RpcSymbol' representing an RPC endpoint. +-- The endpoint name is @Module.rpcName@, where @Module@ is the current +-- module. -- --- See the details under the docs of 'RpcSymbol'. +-- For example: +-- +-- > add :: Int -> Int -> IO Int +-- > add x y = pure (x + y) +-- > $(rpcExport "add" "addRpc") +-- +-- @origName@ must be a function in scope with a monomorphic type of the form +-- @a1 -> ... -> an -> IO r@, @n >= 0@, where every argument type and @r@ +-- have 'Data.Aeson.ToJSON' and 'Data.Aeson.FromJSON' instances. A type +-- synonym for a function type, in the whole type or in the result type, is +-- not expanded and does not compile. +-- +-- The server side wrapper raises an 'InvalidInput' exception if the input is +-- not an array of @n@ values that decode to the argument types, before it +-- calls the function. +-- +-- See the details under the docs of t'RpcSymbol'. rpcExport :: String -> String -> Q [Dec] rpcExport oldFuncName newFuncName = do modName <- loc_module <$> location diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 12e2878..81a581d 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -135,7 +135,12 @@ instance Exception RpcException where -- Running Config -------------------------------------------------------------------------------- --- | RPC server executable name and version. +-- | RPC server executable path and version. +-- +-- Before each call, the client runs the executable without arguments and +-- compares its stdout with 'executableVersion'. The executable must print +-- exactly this string, 'Simple.RPC.Server.mainWith' prints it without a +-- trailing newline. data Executable = Executable { executablePath :: FilePath @@ -147,7 +152,8 @@ data Executable = -- need to have a single mechanism. -- | RPC server specification: server, port, username, executable location, --- privileges to use etc. +-- privileges to use etc. See 'defaultConfig' and the setters for the meaning +-- of the fields. data RunningConfig = RunningConfig { rcRemote :: Maybe (String, String) @@ -164,8 +170,15 @@ data RunningConfig = -- match with the sha256 of local image. Image can be named with a platform -- suffix so that we can have cross platform access. --- | Note we can use rpc to local host as well for executing a function as some --- other user on the same host without using sudo. +-- | A config that runs the executable on the local host as the current user, +-- without flags, and logs with 'putStrLn': +-- +-- * 'rcRemote' is 'Nothing', the executable is run without ssh, +-- * 'rcUser' is 'Nothing', +-- * 'rcSudo' is 'False', +-- * 'rcImage' is the argument, +-- * 'rcImageFlags' is @""@, +-- * 'rcLogger' is 'putStrLn'. defaultConfig :: Executable -> RunningConfig defaultConfig exe = RunningConfig @@ -199,25 +212,40 @@ setImage x rc = rc { rcImage = x } setImageFlags :: String -> RunningConfig -> RunningConfig setImageFlags x rc = rc { rcImageFlags = x } --- | Modify the server name to use for ssh access. +-- | @setRemote (address, port)@ sets the config to run the executable on a +-- remote host. An endpoint call then runs +-- @ssh -T -p port -o "StrictHostKeyChecking off" address command@. The +-- address is passed to ssh as it is, e.g. @user\@host@. +-- +-- The remote command is run by the shell of the ssh user, the client quotes +-- it for a POSIX shell. -- --- Default is local host IP address "127.0.0.1". +-- Default is 'Nothing', the executable is run on the local host without ssh. setRemote :: (String, String) -> RunningConfig -> RunningConfig setRemote x rc = rc { rcRemote = Just x } --- | Modify the ssh username to use for running the endpoint. +-- | Set the config to run the endpoint as this user. An endpoint call then +-- runs @sudo su user -c command@. The current user, or the ssh user if +-- 'setRemote' is used, must be allowed to run @sudo su@. @su@ runs the +-- command with the shell of the user, the client quotes it for a POSIX +-- shell. The version check is run as the current user. -- --- Default is the current user. +-- Default is 'Nothing', the endpoint is run as the current user. setUser :: String -> RunningConfig -> RunningConfig setUser x rc = rc { rcUser = Just x } --- | Use root privileges for running the endpoint. +-- | Set the config to run the endpoint with @sudo@. An endpoint call then +-- runs @sudo executable ...@. When 'setUser' is also used, @sudo +-- executable ...@ is the command run by @su@, the user must be allowed to +-- run @sudo@. -- -- Default is 'False'. useSudo :: Bool -> RunningConfig -> RunningConfig useSudo x rc = rc { rcSudo = x } --- | Use the supplied logger to for log and trace. +-- | Use the supplied logger for log and trace. The client logs the commands, +-- the input, each output line of the server and each stderr line of the +-- server. -- -- Default is 'putStrLn'. setLogger :: (String -> IO ()) -> RunningConfig -> RunningConfig @@ -258,7 +286,7 @@ data RpcEval ir = -- | Represents an RPC endpoint consisting of: -- --- * @run@ is the same as the original function +-- * @direct@ is the same as the original function -- * @call@ takes a 'Runner' and converts it into a local function call. The -- arguments from the local call are converted to IR and supplied to the -- Runner, similarly the result from the Runner is converted to Haskell type @@ -275,7 +303,9 @@ data RpcSymbol ir typ = , evaluator :: RpcEval ir -- server side generic (using IR) call } --- | Get the name of the RPC endpoint. +-- | Get the name of the RPC endpoint, @Module.name@, where @Module@ is the +-- module that has the 'Simple.RPC.Common.rpcExport' splice and @name@ is the +-- name given to 'Simple.RPC.Common.rpcExport'. rpcName :: RpcSymbol ir typ -> String rpcName = symbol . evaluator @@ -295,12 +325,14 @@ rpcCallUsing = call -- XXX Map instead of HashMap? -- XXX rename to ServiceMap --- | A map of symbol names and corresponding evals. +-- | A map of endpoint names and the corresponding server side wrappers. type RpcMap ir = HM.HashMap String (ir -> IO ir) -- XXX serviceMapFromList --- | Create a map from a list of symbol name, eval pairs. +-- | Create a map from a list of server side wrappers, use 'evaluator' to get +-- the wrapper of an t'RpcSymbol'. If two wrappers have the same endpoint name, +-- the map has the one later in the list. createRpcMap :: [RpcEval ir] -> RpcMap ir createRpcMap = HM.fromList . map (\x -> (symbol x, eval x)) @@ -315,6 +347,9 @@ lookupRpcSymbol = HM.lookup -------------------------------------------------------------------------------- -- | Format a tag and its value for pretty printing. +-- +-- >>> showPair "CMD" "ls -l" +-- "[CMD] ls -l" showPair :: String -> String -> String showPair tag val = "[" ++ tag ++ "] " ++ val @@ -322,12 +357,18 @@ showPair tag val = "[" ++ tag ++ "] " ++ val -- Serialized values -------------------------------------------------------------------------------- +-- | The intermediate representation of the arguments and the results, a JSON +-- value. type IntermediateRep = Json.Value -------------------------------------------------------------------------------- -- Conerting Haskell values to/from IR -------------------------------------------------------------------------------- +-- | Convert a Haskell value to IR, the same as 'toJSON'. +-- +-- >>> toIntermediateRep (1 :: Int, "a") +-- Array [Number 1.0,String "a"] toIntermediateRep :: ToJSON a => a -> IntermediateRep toIntermediateRep = toJSON diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index e7d52a3..71f3f6a 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -1,6 +1,9 @@ {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE RecordWildCards #-} +-- | The main function of an RPC server executable, it calls the endpoint +-- named by the command line argument. +-- module Simple.RPC.Server ( mainWith , RpcMap @@ -36,11 +39,24 @@ import Simple.RPC.Internal.Types -- is supplied in serialized form on the stdin and the output is streamed in -- serialized form to stdout. -- +-- The input is the JSON array of the arguments, read from stdin up to the +-- first newline or the end of the input. The function must not read stdin: +-- the server reads stdin in blocks, and the bytes after the newline in the +-- block that holds the newline are discarded. The output on stdout is: +-- +-- * the line @[SERVER] endpoint input@, +-- * the output of the function, +-- * a newline, +-- * the JSON encoding of the result, without a newline. +-- +-- The client takes the last line of the output as the result. +-- -- The encoding of stdout is set to UTF-8, the client decodes the output as -- UTF-8 independent of the locale of the server. -- -- Raise an 'EndpointNotFound' exception if the map does not have the --- function, and an 'InvalidInput' exception if the input is not valid JSON. +-- function, and an 'InvalidInput' exception if the input is not valid JSON or +-- does not match the arguments of the function. invokeFunction :: RpcMap IntermediateRep -> String -> IO () invokeFunction actions actionName = do -- XXX we should not buffer the input, it should be directly streamed to @@ -49,6 +65,10 @@ invokeFunction actions actionName = do -- Read the input before raising an exception for an unknown endpoint. A -- client writing the input to a process that has exited gets a broken -- pipe error instead of the exit code of the process. + -- + -- TODO takeEndBy_ discards the bytes after the newline in the block that + -- holds the newline. Pass them to the function when the input is + -- streamed to it. inputBytes <- FH.read stdin & Stream.fold (Fold.takeEndBy_ (== 10) Array.create) case lookupRpcSymbol actionName actions of From 939a2a28ae4a7bc324b340417e43d52d4a2c40d5 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:42:35 +0530 Subject: [PATCH 18/32] Fix the line lengths and the role annotation warnings Wrap lines to 79 columns. Disable the missing role annotation warning of GHC 9.8, the inferred roles are intended. --- rpc/lib/Simple/RPC/Client.hs | 19 +++++++----- rpc/lib/Simple/RPC/Internal/TH.hs | 11 +++---- rpc/lib/Simple/RPC/Internal/Types.hs | 44 +++++++++++++++------------- rpc/lib/Simple/RPC/Server.hs | 18 ++++++------ rpc/simple-rpc.cabal | 3 ++ 5 files changed, 52 insertions(+), 43 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index de3e3f7..63e3cad 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -28,9 +28,9 @@ module Simple.RPC.Client , installOnRemote ) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Control.Exception (SomeException, onException, throwIO, try) import Control.Monad (when) @@ -50,9 +50,9 @@ import qualified Streamly.Internal.Unicode.Stream as Unicode import Simple.RPC.Internal.Types --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Utils --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- streamly-coreutils (Streamly.Coreutils.Sh) has the maintained definitions -- of shellQuote and shellCommand; these are copies. Make changes there and @@ -120,7 +120,9 @@ bufferLefts :: IORef.IORef [a] -> Stream.Stream IO (Either a b) -> Stream.Stream IO b bufferLefts ref inp = Stream.mapM f inp & Stream.catMaybes + where + f (Left a) = IORef.modifyIORef ref (a:) >> pure Nothing f (Right b) = pure $ Just b @@ -234,8 +236,9 @@ with (RunningConfig{..}) actionName input = do -- With streamly-process 0.4.1, if the server process exits before it reads -- all of the input and the input is larger than the pipe buffer, the call -- raises an 'IOError' for the broken pipe instead of the --- 'Streamly.Internal.System.Process.ProcessFailure' exception. The server reads the whole input before it raises an exception --- for an unknown endpoint. +-- 'Streamly.Internal.System.Process.ProcessFailure' exception. The server +-- reads the whole input before it raises an exception for an unknown +-- endpoint. runAt :: RunningConfig -> RpcSymbol IntermediateRep typ -> typ runAt cfg sym = call sym (with cfg) @@ -245,9 +248,9 @@ runAt cfg sym = call sym (with cfg) run :: RpcSymbol IntermediateRep typ -> typ run = direct --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Backward compatibility --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- NOTE: This should be removed from here. Leave the installation to the user. -- XXX We can avoid sudo access or have a separate API which does not require diff --git a/rpc/lib/Simple/RPC/Internal/TH.hs b/rpc/lib/Simple/RPC/Internal/TH.hs index f793358..e9f8488 100644 --- a/rpc/lib/Simple/RPC/Internal/TH.hs +++ b/rpc/lib/Simple/RPC/Internal/TH.hs @@ -5,16 +5,16 @@ module Simple.RPC.Internal.TH , rpcify ) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Language.Haskell.TH import Simple.RPC.Internal.Types --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Functions --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- getFunctionType :: Name -> Q Type getFunctionType _func = do @@ -95,7 +95,8 @@ rpcExport oldFuncName newFuncName = do ] let toIntermediateRepTH k = [|toIntermediateRep $(k)|] - encodedInput = [| createArr $(listE (map toIntermediateRepTH varArgs))|] + encodedInput = + [|createArr $(listE (map toIntermediateRepTH varArgs))|] runningExp = lamE diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 81a581d..034336e 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -59,9 +59,9 @@ module Simple.RPC.Internal.Types , RpcException(..) ) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Control.Exception (Exception(..), throwIO) import Data.Aeson (ToJSON, FromJSON, toJSON, fromJSON) @@ -92,9 +92,9 @@ import qualified Streamly.Internal.Data.Array as Array (fromPtrN, unsafePinnedAsPtr) import qualified Streamly.Unicode.Stream as Unicode --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Exceptions --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | Exceptions raised by the RPC client and the RPC server. data RpcException @@ -131,9 +131,9 @@ instance Exception RpcException where "Usage: [], got the arguments: " ++ show args --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Running Config --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | RPC server executable path and version. -- @@ -251,9 +251,9 @@ useSudo x rc = rc { rcSudo = x } setLogger :: (String -> IO ()) -> RunningConfig -> RunningConfig setLogger x rc = rc { rcLogger = x } --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Symbols --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- XXX Call? @@ -342,9 +342,9 @@ createRpcMap = HM.fromList . map (\x -> (symbol x, eval x)) lookupRpcSymbol :: String -> RpcMap ir -> Maybe (ir -> IO ir) lookupRpcSymbol = HM.lookup --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Pretty printing --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | Format a tag and its value for pretty printing. -- @@ -353,17 +353,17 @@ lookupRpcSymbol = HM.lookup showPair :: String -> String -> String showPair tag val = "[" ++ tag ++ "] " ++ val --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Serialized values --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | The intermediate representation of the arguments and the results, a JSON -- value. type IntermediateRep = Json.Value --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Conerting Haskell values to/from IR --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | Convert a Haskell value to IR, the same as 'toJSON'. -- @@ -380,9 +380,9 @@ resultFromIR val = Json.Error err -> throwIO $ InvalidOutput err Json.Success a -> pure a --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Arrays in IR --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | @irArgs n ir@ returns the elements of the IR array @ir@. Raise an -- 'InvalidInput' exception if @ir@ is not an array of @n@ elements. @@ -405,16 +405,18 @@ irArg args i = Just v -> case fromJSON v of Json.Error err -> - throwIO $ InvalidInput $ "argument " ++ show i ++ ": " ++ err + throwIO + $ InvalidInput + $ "argument " ++ show i ++ ": " ++ err Json.Success a -> pure a -- | Create an array in IR from a list of IR Haskell values. createArr :: [IntermediateRep] -> IntermediateRep createArr = Json.Array . Vector.fromList --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Key-value maps in IR --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- XXX swap the arguments? @@ -434,9 +436,9 @@ objLookup _ _ = error "Value is not an object type" createObj :: [(String, IntermediateRep)] -> IntermediateRep createObj kv = Json.object $ map (Data.Bifunctor.first Key.fromString) kv --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Conversions of IR --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- | Convert the Haskell representation of IR (i.e. Json) to a byte stream of -- its JSON encoding. diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index 71f3f6a..be94dbe 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -11,9 +11,9 @@ module Simple.RPC.Server , invokeFunction ) where --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Imports --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- import Control.Exception (throwIO) import Data.Function ((&)) @@ -28,9 +28,9 @@ import qualified Streamly.FileSystem.Handle as FH import Simple.RPC.Internal.Types --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Utils --------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- XXX To reduce execution delays we should have this running as a server. Or -- at least make sure the executable is not swapped out. @@ -99,11 +99,11 @@ invokeFunction actions actionName = do -- -- The RPC server executable implements several endpoints, it has a map of the -- endpoint name to the function that implements the endpoint. If the endpoint --- is not found in the map then it raises an 'EndpointNotFound' exception. If the endpoint is found then --- the stdin of the RPC executable is supplied as input to the corresponding --- function. The input is a serialized form (JSON) of the 'IntermediateRep'. --- The output of the endpoint is emitted on stdout as serialized form of --- 'IntermediateRep'. +-- is not found in the map then it raises an 'EndpointNotFound' exception. If +-- the endpoint is found then the stdin of the RPC executable is supplied as +-- input to the corresponding function. The input is a serialized form (JSON) +-- of the 'IntermediateRep'. The output of the endpoint is emitted on stdout as +-- serialized form of 'IntermediateRep', see 'invokeFunction'. mainWith :: String -> RpcMap IntermediateRep -> IO () mainWith version actions = do args <- getArgs diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 347043f..2f222b8 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -31,6 +31,9 @@ common compile-options -Wno-redundant-bang-patterns -Wno-operator-whitespace + if impl(ghc >= 9.8) + ghc-options: -Wno-missing-role-annotations + if flag(limit-build-mem) ghc-options: +RTS -M2G -RTS From 088dbe27f28dda9bb8a5bfa44d691df6b0ba6eaa Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:43:05 +0530 Subject: [PATCH 19/32] Define the IR conversions before their use Move the IR conversion section after IntermediateRep. The code is unchanged. --- rpc/lib/Simple/RPC/Internal/Types.hs | 114 +++++++++++++-------------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 034336e..03315e3 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -361,6 +361,63 @@ showPair tag val = "[" ++ tag ++ "] " ++ val -- value. type IntermediateRep = Json.Value +------------------------------------------------------------------------------- +-- Conversions of IR +------------------------------------------------------------------------------- + +-- | Convert the Haskell representation of IR (i.e. Json) to a byte stream of +-- its JSON encoding. +-- +-- The stream is generated from the chunks of the lazy encoding, the time is +-- linear in the size of the encoding. +{-# INLINE toBinStream #-} +toBinStream :: Monad m => IntermediateRep -> Stream m Word8 +toBinStream input = + Stream.fromList (BSL.toChunks (Json.encode input)) + & Stream.unfoldEach (Unfold.lmap BS.unpack Unfold.fromList) + +-- | Copy a ByteString to an array. +byteStringToArray :: BS.ByteString -> IO (Array Word8) +byteStringToArray c = + BS.Unsafe.unsafeUseAsCStringLen c + $ \(p, n) -> Array.fromPtrN n (castPtr p) + +-- | Convert the Haskell representation of IR (i.e. Json) to a stream of +-- arrays of its JSON encoding, one array for each chunk of the lazy encoding. +toChunkStream :: IntermediateRep -> Stream IO (Array Word8) +toChunkStream input = + Stream.fromList (BSL.toChunks (Json.encode input)) + & Stream.mapM byteStringToArray + +-- | Convert a byte stream of IR (i.e. Json) to its Haskell representation. +fromBinStream :: Stream IO Word8 -> IO IntermediateRep +fromBinStream input = do + res <- Stream.toList input + case Json.decode $ BSL.pack res of + Nothing -> error "Unable to decode" + Just x -> pure x + +-- | Decode a UTF-8 encoded byte array to a String, replacing invalid bytes +-- with the Unicode replacement character. Used for logging. +decodeUtf8Array :: Array Word8 -> String +decodeUtf8Array arr = + runIdentity $ Stream.toList $ Unicode.decodeUtf8 $ Array.read arr + +-- | Decode the UTF-8 encoded JSON representation of IR in a byte array. +-- Returns the decoding error message on failure. +irFromArray :: Array Word8 -> IO (Either String IntermediateRep) +irFromArray arr = do + bs <- + Array.unsafePinnedAsPtr arr + $ \p n -> BS.packCStringLen (castPtr p, n) + pure $ Json.eitherDecodeStrict' bs + +-- | Convert the Haskell representation of IR (i.e. Json) to String. Used for +-- logging. +irToString :: IntermediateRep -> String +irToString input = + TextL.unpack $ TextL.decodeUtf8With Text.lenientDecode $ Json.encode input + ------------------------------------------------------------------------------- -- Conerting Haskell values to/from IR ------------------------------------------------------------------------------- @@ -435,60 +492,3 @@ objLookup _ _ = error "Value is not an object type" -- | Convert (String, IR) key-value pairs to a map in IR. createObj :: [(String, IntermediateRep)] -> IntermediateRep createObj kv = Json.object $ map (Data.Bifunctor.first Key.fromString) kv - -------------------------------------------------------------------------------- --- Conversions of IR -------------------------------------------------------------------------------- - --- | Convert the Haskell representation of IR (i.e. Json) to a byte stream of --- its JSON encoding. --- --- The stream is generated from the chunks of the lazy encoding, the time is --- linear in the size of the encoding. -{-# INLINE toBinStream #-} -toBinStream :: Monad m => IntermediateRep -> Stream m Word8 -toBinStream input = - Stream.fromList (BSL.toChunks (Json.encode input)) - & Stream.unfoldEach (Unfold.lmap BS.unpack Unfold.fromList) - --- | Copy a ByteString to an array. -byteStringToArray :: BS.ByteString -> IO (Array Word8) -byteStringToArray c = - BS.Unsafe.unsafeUseAsCStringLen c - $ \(p, n) -> Array.fromPtrN n (castPtr p) - --- | Convert the Haskell representation of IR (i.e. Json) to a stream of --- arrays of its JSON encoding, one array for each chunk of the lazy encoding. -toChunkStream :: IntermediateRep -> Stream IO (Array Word8) -toChunkStream input = - Stream.fromList (BSL.toChunks (Json.encode input)) - & Stream.mapM byteStringToArray - --- | Convert a byte stream of IR (i.e. Json) to its Haskell representation. -fromBinStream :: Stream IO Word8 -> IO IntermediateRep -fromBinStream input = do - res <- Stream.toList input - case Json.decode $ BSL.pack res of - Nothing -> error "Unable to decode" - Just x -> pure x - --- | Decode a UTF-8 encoded byte array to a String, replacing invalid bytes --- with the Unicode replacement character. Used for logging. -decodeUtf8Array :: Array Word8 -> String -decodeUtf8Array arr = - runIdentity $ Stream.toList $ Unicode.decodeUtf8 $ Array.read arr - --- | Decode the UTF-8 encoded JSON representation of IR in a byte array. --- Returns the decoding error message on failure. -irFromArray :: Array Word8 -> IO (Either String IntermediateRep) -irFromArray arr = do - bs <- - Array.unsafePinnedAsPtr arr - $ \p n -> BS.packCStringLen (castPtr p, n) - pure $ Json.eitherDecodeStrict' bs - --- | Convert the Haskell representation of IR (i.e. Json) to String. Used for --- logging. -irToString :: IntermediateRep -> String -irToString input = - TextL.unpack $ TextL.decodeUtf8With Text.lenientDecode $ Json.encode input From e4b11da0596098867e25c091d02324aeebacfab5 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Wed, 4 Nov 2026 11:44:34 +0530 Subject: [PATCH 20/32] Update the changelog --- rpc/CHANGELOG.md | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/rpc/CHANGELOG.md b/rpc/CHANGELOG.md index 6fb74bc..7adcb9e 100644 --- a/rpc/CHANGELOG.md +++ b/rpc/CHANGELOG.md @@ -1,5 +1,61 @@ # Revision history for simple-rpc +## Unreleased + +### Breaking changes + +No exported type signature has changed. The following behavior changes +can break existing callers: + +* Errors are raised as an `RpcException` instead of an `ErrorCall`: an + unknown endpoint (`EndpointNotFound`), an invalid server input + (`InvalidInput`), an invalid client output line (`InvalidOutput`), a + version mismatch (`VersionMismatch`) and more than one argument to the + server (`InvalidUsage`). `EmptyOutput` is unchanged. +* The server rejects an input array with more or fewer elements than the + arguments of the endpoint. Before, extra elements were ignored. +* The server decodes all arguments before it calls the endpoint. Before, + an argument was decoded when the endpoint used it, an invalid argument + that the endpoint did not use was accepted. +* `runAt` decodes the result before it returns, a decoding error is raised + by `runAt`. Before, it was raised when the caller used the result. +* `setImageFlags` flags are passed to the server executable. Before, they + were ignored. +* `installOnRemote` installs the executable with `sudo install -m 755`, the + file is owned by root. It no longer changes the permissions of the + directory. Before, the directory was made writable by all users and the + file was owned by the ssh user. It needs `mktemp` and `install` on the + remote host. +* The server sets the encoding of stdout to UTF-8. + +### Additions + +* `RpcException` is exported from `Simple.RPC.Common`. + +### Bug fixes + +* A non-ASCII character in a `String` argument or result made the call + fail. +* The server failed in a non-UTF-8 locale, e.g. `LC_ALL=C`, when the + input, the endpoint output or the version had a non-ASCII character. +* An executable path, a user name or an argument with a space, a quote, + `$`, a backtick, a backslash or a non-ASCII character was not quoted + correctly for the local command, `su -c` and ssh. +* `installOnRemote` left the remote directory writable by all users, and + failed when the executable was running or the path had a space. +* `rpcExport` of a function named `val` did not compile. +* For an unknown endpoint and an input larger than the pipe buffer, `runAt` + raised a broken pipe error instead of `ProcessFailure`. +* `toBinStream` took time proportional to the size times the number of + chunks of the encoding, 24 MB of JSON took 20 seconds. The client and + the server serialization use the chunks of the encoding directly. + +### Documentation + +* Corrected the defaults of `setRemote` and `setUser` and documented the + protocol, the exceptions and the limits of `runAt`, `invokeFunction`, + `mainWith`, `rpcExport` and `installOnRemote`. + ## 0.1.0.0 -- YYYY-mm-dd * First version. Released on an unsuspecting world. From 28a2ab35e1d04595d093784b3f6b51fdd9c1e8a4 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 02:42:38 +0530 Subject: [PATCH 21/32] Replace the fake command scripts with test executable copies Windows cannot run the /bin/sh scripts. Each fake is now a copy of the test executable with a config file. Remove the unix dependency and skip the installOnRemote tests on Windows. --- rpc/simple-rpc.cabal | 6 +- rpc/test/Fake.hs | 254 +++++++++++++++++++++++++++++++++++++++++++ rpc/test/Harness.hs | 33 ++++-- rpc/test/Main.hs | 114 +++++++++++-------- rpc/test/TestUtil.hs | 121 ++++----------------- 5 files changed, 375 insertions(+), 153 deletions(-) create mode 100644 rpc/test/Fake.hs diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 2f222b8..7942138 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -70,7 +70,8 @@ test-suite simple-rpc-test import: lib-options type: exitcode-stdio-1.0 main-is: Main.hs - other-modules: Harness + other-modules: Fake + , Harness , TestFunctions , TestUtil hs-source-dirs: test @@ -83,10 +84,9 @@ test-suite simple-rpc-test , bytestring , directory , filepath - , process + , process >= 1.6.12 , streamly-core , streamly-process - , unix , unordered-containers benchmark simple-rpc-bench diff --git a/rpc/test/Fake.hs b/rpc/test/Fake.hs new file mode 100644 index 0000000..abb352f --- /dev/null +++ b/rpc/test/Fake.hs @@ -0,0 +1,254 @@ +-- | Fake commands for the tests: @ssh@, @scp@, @sudo@, @su@ and RPC +-- servers with a given behaviour. +-- +-- A fake command is a copy of the test executable with a config file next +-- to it. When the test executable starts, 'lookupFake' finds the config +-- file of the running copy, and 'runFake' runs the fake command instead of +-- the tests. A copy is used instead of a script because Windows runs only +-- executables, and instead of a link because a link reports the path of +-- the linked file as the executable path. +-- +-- The fake @ssh@ runs the remote command with @sh -c@, the same as the +-- shell of the remote user, so that the tests check the shell quoting of +-- the commands. The fake @scp@ writes the remote file through @sh@ for the +-- same view of the remote file system. +-- +module Fake + ( Fake(..) + , installFake + , lookupFake + , runFake + , writeFileFs + , appendFileFs + , readFileFs + ) where + +------------------------------------------------------------------------------- +-- Imports +------------------------------------------------------------------------------- + +import Control.Exception (evaluate) +import GHC.Environment (getFullArgs) +import System.Directory + (copyFile, doesFileExist, exeExtension, getPermissions, setOwnerExecutable + , setPermissions) +import System.Environment (getEnv, getExecutablePath) +import System.Exit (ExitCode(..), exitWith) +import System.FilePath (dropExtension, takeExtension, (<.>)) +import System.IO + ( Handle, IOMode(..), hGetContents, hPutStr, hSetBinaryMode, hSetEncoding + , hSetNewlineMode, noNewlineTranslation, stderr, stdin, stdout + , withFile ) +import System.Process + ( CreateProcess(cwd, std_in), StdStream(..), createProcess, proc + , rawSystem, waitForProcess ) + +import qualified Data.ByteString as BS +import qualified GHC.IO.Encoding as Encoding + +------------------------------------------------------------------------------- +-- Files in the file system encoding +------------------------------------------------------------------------------- + +-- | Set the file system encoding and no newline translation, so that a +-- 'String' from 'getArgs' is written as the bytes of the argument, in any +-- locale and on Windows. +setFsMode :: Handle -> IO () +setFsMode h = do + enc <- Encoding.getFileSystemEncoding + hSetEncoding h enc + hSetNewlineMode h noNewlineTranslation + +withFileFs :: FilePath -> IOMode -> (Handle -> IO a) -> IO a +withFileFs path mode f = withFile path mode (\h -> setFsMode h >> f h) + +writeFileFs :: FilePath -> String -> IO () +writeFileFs path s = withFileFs path WriteMode (`hPutStr` s) + +appendFileFs :: FilePath -> String -> IO () +appendFileFs path s = withFileFs path AppendMode (`hPutStr` s) + +readFileFs :: FilePath -> IO String +readFileFs path = + withFileFs path ReadMode $ \h -> do + s <- hGetContents h + _ <- evaluate (length s) + pure s + +------------------------------------------------------------------------------- +-- Fake config +------------------------------------------------------------------------------- + +data Fake + = FakeSsh + | FakeScp + | FakeSudo + | FakeSu + -- | @FakeServer version output@ prints @version@ when called without + -- arguments. Otherwise it reads stdin and prints the contents of the + -- file @output@. + | FakeServer String FilePath + -- | @ExitServer version code@ prints @version@ when called without + -- arguments. Otherwise it exits with @code@ without reading stdin. + | ExitServer String Int + -- | @ArgsServer exe args@ runs @exe@ without arguments when called + -- without arguments. Otherwise it runs @exe args@, ignoring its own + -- arguments. + | ArgsServer FilePath [String] + -- | @RecordServer exe file@ appends a line @call@ and a line for each + -- of its arguments to @file@, then runs @exe@ with the arguments. + | RecordServer FilePath FilePath + deriving (Show, Read) + +-- | The config file of the fake command at the path. +configPath :: FilePath -> FilePath +configPath exe = + base <.> "fake" + + where + + base = + if not (null exeExtension) && takeExtension exe == '.' : exeExtension + then dropExtension exe + else exe + +-- | @installFake testExe path fake@ copies the test executable @testExe@ to +-- @path@, with the executable extension of the OS added, and writes the +-- config file for @fake@. Returns the path of the fake command. +installFake :: FilePath -> FilePath -> Fake -> IO FilePath +installFake testExe path fake = do + let exe = path <.> exeExtension + copyFile testExe exe + p <- getPermissions exe + setPermissions exe (setOwnerExecutable True p) + -- show escapes the non-ASCII characters, the file is ASCII + writeFile (configPath exe) (show fake) + pure exe + +-- | The fake config of the running executable, if it is a fake command. +lookupFake :: IO (Maybe Fake) +lookupFake = do + cfg <- configPath <$> getExecutablePath + exists <- doesFileExist cfg + if exists + then Just . read <$> readFile cfg + else pure Nothing + +------------------------------------------------------------------------------- +-- Fake commands +------------------------------------------------------------------------------- + +-- | Append the command name and its arguments, each in brackets, as a line +-- to the file in @SIMPLE_RPC_FAKE_LOG@. +logCall :: String -> [String] -> IO () +logCall name args = do + logFile <- getEnv "SIMPLE_RPC_FAKE_LOG" + appendFileFs logFile + $ unwords (name : map (\a -> "[" ++ a ++ "]") args) ++ "\n" + +failWith :: Int -> String -> IO a +failWith code msg = do + hPutStr stderr (msg ++ "\n") + exitWith (ExitFailure code) + +-- | Run the command with the standard streams of this process and exit with +-- its exit code. +runAndExit :: FilePath -> [String] -> IO a +runAndExit exe args = rawSystem exe args >>= exitWith + +-- | Run @sh -c cmd shArgs@ in the fake home directory and exit with its exit +-- code. +runSh :: Maybe Handle -> String -> [String] -> IO a +runSh mIn cmd shArgs = do + home <- getEnv "SIMPLE_RPC_FAKE_HOME" + let cp = + (proc "sh" ("-c" : cmd : shArgs)) + { cwd = Just home + , std_in = maybe Inherit UseHandle mIn + } + (_, _, _, ph) <- createProcess cp + waitForProcess ph >>= exitWith + +-- | @ssh [-T] [-p PORT] [-o OPTION] HOST CMD...@ runs @CMD@ with @sh -c@ in +-- @SIMPLE_RPC_FAKE_HOME@. Like ssh, the words of @CMD@ are joined with +-- spaces. +fakeSsh :: [String] -> IO a +fakeSsh args0 = + go args0 + + where + + go ("-T" : rest) = go rest + go ("-p" : _ : rest) = go rest + go ("-o" : _ : rest) = go rest + go (opt@('-' : _) : _) = failWith 255 ("fake ssh: unsupported " ++ opt) + go (_host : cmd) = runSh Nothing (unwords cmd) [] + go [] = failWith 255 "fake ssh: no host" + +-- | @scp [-P PORT] SRC HOST:DST@ writes the contents of @SRC@ to @DST@ with +-- @sh@ in @SIMPLE_RPC_FAKE_HOME@. +fakeScp :: [String] -> IO a +fakeScp args0 = + case dropPort args0 of + [src, dst] -> + withFile src ReadMode $ \h -> + runSh (Just h) "cat > \"$1\"" ["sh", remotePath dst] + _ -> failWith 1 "fake scp: usage: scp [-P PORT] SRC HOST:DST" + + where + + dropPort ("-P" : _ : rest) = rest + dropPort args = args + + remotePath = drop 1 . dropWhile (/= ':') + +-- | @sudo [--] CMD ARGS...@ runs @CMD ARGS@ as the same user. +fakeSudo :: [String] -> IO a +fakeSudo args0 = + case args0 of + ("--" : cmd : args) -> runAndExit cmd args + (cmd : args) -> runAndExit cmd args + [] -> failWith 1 "fake sudo: no command" + +-- | @su USER -c CMD@ runs @sh -c CMD@ as the same user. +fakeSu :: [String] -> IO a +fakeSu args = + case args of + [_user, "-c", cmd] -> runAndExit "sh" ["-c", cmd] + _ -> failWith 1 "fake su: usage: su USER -c CMD" + +printVersion :: String -> IO a +printVersion version = do + hSetBinaryMode stdout True + hPutStr stdout version + exitWith ExitSuccess + +-- | Run the fake command. The arguments include the RTS options such as +-- @+RTS -A2m -RTS@: the test executable accepts RTS options, and a fake +-- command passes them on as the real command would. +runFake :: Fake -> IO a +runFake fake = do + -- The first one is the program name + args <- drop 1 <$> getFullArgs + case fake of + FakeSsh -> logCall "ssh" args >> fakeSsh args + FakeScp -> logCall "scp" args >> fakeScp args + FakeSudo -> logCall "sudo" args >> fakeSudo args + FakeSu -> logCall "su" args >> fakeSu args + FakeServer version output + | null args -> printVersion version + | otherwise -> do + hSetBinaryMode stdin True + hSetBinaryMode stdout True + _ <- BS.getContents + BS.readFile output >>= BS.putStr + exitWith ExitSuccess + ExitServer version code + | null args -> printVersion version + | otherwise -> exitWith (ExitFailure code) + ArgsServer exe serverArgs + | null args -> runAndExit exe [] + | otherwise -> runAndExit exe serverArgs + RecordServer exe file -> do + appendFileFs file (unlines ("call" : args)) + runAndExit exe args diff --git a/rpc/test/Harness.hs b/rpc/test/Harness.hs index 67f60b2..cc99a36 100644 --- a/rpc/test/Harness.hs +++ b/rpc/test/Harness.hs @@ -5,6 +5,7 @@ module Harness ( Test , test , expectFailure + , skipIf , runTests , assertEqual , assertBool @@ -98,6 +99,7 @@ property p = do data Test = Test String (IO ()) | ExpectFailure String String (IO ()) + | Skip String String -- | A named test case. test :: String -> IO () -> Test @@ -109,6 +111,16 @@ test = Test expectFailure :: String -> String -> IO () -> Test expectFailure reason name = ExpectFailure name reason +testName :: Test -> String +testName (Test name _) = name +testName (ExpectFailure name _ _) = name +testName (Skip name _) = name + +-- | @skipIf cond reason t@ does not run the test case @t@ if @cond@ is true, +-- and reports it as SKIP with @reason@. +skipIf :: Bool -> String -> Test -> Test +skipIf cond reason t = if cond then Skip (testName t) reason else t + -- | Seconds after which a test is reported as failed. testTimeout :: Int testTimeout = 120 @@ -120,11 +132,13 @@ runTests seed tests = do writeIORef seedRef seed putStrLn $ "QuickCheck seed: " ++ show seed results <- mapM runOne tests - let failed = [name | (name, False) <- results] + let failed = [name | (name, Just False) <- results] + skipped = [name | (name, Nothing) <- results] putStrLn "" putStrLn - $ show (length tests - length failed) ++ " passed, " - ++ show (length failed) ++ " failed" + $ show (length tests - length failed - length skipped) ++ " passed, " + ++ show (length failed) ++ " failed, " + ++ show (length skipped) ++ " skipped" mapM_ (putStrLn . ("FAILED: " ++)) failed when (not (null failed)) exitFailure @@ -144,11 +158,11 @@ runTests seed tests = do runOne (Test name action) = do r <- run name action case r of - Nothing -> putStrLn "OK" >> pure (name, True) + Nothing -> putStrLn "OK" >> pure (name, Just True) Just err -> do putStrLn "FAIL" putStrLn $ " " ++ err - pure (name, False) + pure (name, Just False) runOne (ExpectFailure name reason action) = do r <- run name action @@ -156,9 +170,14 @@ runTests seed tests = do Nothing -> do putStrLn "XPASS" putStrLn $ " expected to fail: " ++ reason - pure (name, False) + pure (name, Just False) Just err -> do putStrLn "XFAIL" putStrLn $ " " ++ reason putStrLn $ " " ++ err - pure (name, True) + pure (name, Just True) + + runOne (Skip name reason) = do + putStrLn $ name ++ " ... SKIP" + putStrLn $ " " ++ reason + pure (name, Nothing) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index f0549e5..47badda 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -8,26 +8,24 @@ module Main (main) where import Control.Exception (displayException, evaluate, finally, try) import Control.Monad (unless) -import Data.Bits ((.&.)) import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.Int (Int64) import Data.IORef (modifyIORef, newIORef, readIORef) import Data.List (isInfixOf, isPrefixOf, sort) import GHC.Clock (getMonotonicTime) -import Numeric (showOct) import Streamly.Internal.System.Process (ProcessFailure(..)) import System.Directory - ( createDirectory, createFileLink, doesFileExist, executable + ( copyFile, createDirectory, doesFileExist, executable, exeExtension , getPermissions ) import System.Environment (getArgs, lookupEnv) import System.Exit (ExitCode(..)) -import System.FilePath (()) +import System.FilePath ((<.>), ()) import System.IO (hClose, hPutStr) -import System.Posix.Files (fileMode, getFileStatus, setFileMode) +import System.Info (os) import System.Process - ( CreateProcess(std_in, std_out), StdStream(..), createProcess, proc - , waitForProcess ) + ( CreateProcess(std_in, std_out), StdStream(..), callProcess + , createProcess, proc, readProcess, waitForProcess ) import Test.QuickCheck (forAll, ioProperty, withMaxSuccess) import qualified Data.Aeson as Json @@ -39,6 +37,7 @@ import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream import qualified Test.QuickCheck as QC +import Fake import Harness import Simple.RPC import TestFunctions @@ -77,6 +76,21 @@ assertInvalidInput err = asciiString :: QC.Gen String asciiString = QC.listOf (QC.choose ('\0', '\127')) +isWindows :: Bool +isWindows = os == "mingw32" + +-- | The permission bits of a file as shown by @ls -l@, e.g. @rwxr-xr-x@. +-- Uses @sh@ for the same view of the file system as the fake ssh. +lsMode :: FilePath -> IO String +lsMode path = do + out <- readProcess "sh" ["-c", "ls -ld \"$1\"", "sh", path] "" + pure $ take 9 $ drop 1 out + +-- | Set the mode of a file to an octal mode such as @755@, using @sh@. +chmodSh :: String -> FilePath -> IO () +chmodSh mode path = + callProcess "sh" ["-c", "chmod " ++ mode ++ " \"$1\"", "sh", path] + ------------------------------------------------------------------------------- -- Simple.RPC.Common ------------------------------------------------------------------------------- @@ -347,12 +361,9 @@ clientTests env = "streamly-process 0.4.1 writes stdin after the process exits" "runAt raises ProcessFailure when the server ignores the input" $ do -- The input is larger than the pipe buffer - let path = envDir env "exit3-server" - writeScript path $ unlines - [ "#!/bin/sh" - , "if [ $# -eq 0 ]; then printf 1; exit 0; fi" - , "exit 3" - ] + path <- + installFake (envExe env) (envDir env "exit3-server") + (ExitServer "1" 3) assertThrows "exit 3" (\(ProcessFailure n) -> n == 3) (runAt (serverConfig env & setImage (Executable path "1")) @@ -361,12 +372,9 @@ clientTests env = , test "runAt raises ProcessFailure for an unknown endpoint" $ do -- A server that does not have the endpoint, the input is larger -- than the pipe buffer. - let path = envDir env "unknown-endpoint-server" - writeScript path $ unlines - [ "#!/bin/sh" - , "[ $# -eq 0 ] && exec '" ++ envExe env ++ "'" - , "exec '" ++ envExe env ++ "' TestFunctions.nope" - ] + path <- + installFake (envExe env) (envDir env "unknown-endpoint-server") + (ArgsServer (envExe env) ["TestFunctions.nope"]) (cfg, getLog) <- loggingConfig env assertThrows "unknown" (\(ProcessFailure n) -> n == 1) (runAt @@ -417,24 +425,20 @@ clientTests env = Right _ -> assertBool "runAt returned without an exception" False , test "runAt passes the setImageFlags flags to the executable" $ do - let wrapper = envDir env "flags-server" - argsFile = envDir env "flags-server.args" - writeScript wrapper $ unlines - [ "#!/bin/sh" - , "{ echo call; printf '%s\\n' \"$@\"; } >> '" ++ argsFile ++ "'" - , "exec '" ++ envExe env ++ "' \"$@\"" - ] + let argsFile = envDir env "flags-server.args" + wrapper <- + installFake (envExe env) (envDir env "flags-server") + (RecordServer (envExe env) argsFile) let cfg = serverConfig env & setImage (Executable wrapper testVersion) & setImageFlags "+RTS -A2m\t-RTS " r <- runAt cfg add 2 3 assertEqual "add" 5 r - calls <- lines <$> readFile argsFile - -- printf prints an empty line for the version check, which has - -- no arguments. + calls <- lines <$> readFileFs argsFile + -- The first call is the version check, without arguments assertEqual "arguments" - [ "call", "" + [ "call" , "call", "+RTS", "-A2m", "-RTS", "TestFunctions.add" ] calls @@ -500,7 +504,7 @@ installTests env = let destDir = envDir env "install2" dest = destDir "server" createDirectory destDir - setFileMode destDir 0o755 + chmodSh "755" destDir clearFakeLog env installOnRemote (Executable (envExe env) testVersion) ("u@h", "22") dest @@ -513,10 +517,10 @@ installTests env = tmpExists <- doesFileExist tmp assertBool ("temporary file removed: " ++ tmp) (not tmpExists) other -> assertBool ("one scp call: " ++ show other) False - dirMode <- fileMode <$> getFileStatus destDir - assertEqual "directory mode" "755" (showOct (dirMode .&. 0o777) "") - exeMode <- fileMode <$> getFileStatus dest - assertEqual "executable mode" "755" (showOct (exeMode .&. 0o777) "") + dirMode <- lsMode destDir + assertEqual "directory mode" "rwxr-xr-x" dirMode + exeMode <- lsMode dest + assertEqual "executable mode" "rwxr-xr-x" exeMode , test "installOnRemote with special characters in the path" $ do let dest = envDir env "install3" specialDirName "srv" @@ -553,8 +557,14 @@ installTests env = -- 'setupEnv' sets to the temporary directory. Do not use a variable that is -- set, such as @HOME@: a wrongly quoted @chmod@ on this path once changed -- the mode of the home directory to 777. +-- +-- Windows does not allow the double quote, the backslash and the glob in a +-- file name. specialDirName :: String -specialDirName = "dir with 'sq' \"dq\" $SIMPLE_RPC_UNSET `id` \\ * \233" +specialDirName = + if isWindows + then "dir with 'sq' $SIMPLE_RPC_UNSET `id` \233" + else "dir with 'sq' \"dq\" $SIMPLE_RPC_UNSET `id` \\ * \233" quotingTests :: Env -> [Test] quotingTests env = @@ -601,14 +611,15 @@ quotingTests env = cfgFor exe = serverConfig env & setImage (Executable exe testVersion) - -- A symbolic link to the test executable in specialDirName + -- A copy of the test executable in specialDirName. A symbolic link + -- needs extra privileges on Windows. specialExe = do let dir = envDir env specialDirName - exe = dir "server" + exe = dir "server" <.> exeExtension exists <- doesFileExist exe unless exists $ do createDirectory dir - createFileLink (envExe env) exe + copyFile (envExe env) exe pure exe ------------------------------------------------------------------------------- @@ -689,13 +700,20 @@ parseSeed args = main :: IO () main = do + fake <- lookupFake mode <- lookupEnv (fst serverMode) - if mode == Just (snd serverMode) - then do - v <- lookupEnv "SIMPLE_RPC_TEST_VERSION" - let version = if v == Just "unicode" then "1.0-\233" else testVersion - mainWith version rpcMap - else do + case fake of + Just f -> runFake f + Nothing | mode == Just (snd serverMode) -> do + v <- lookupEnv "SIMPLE_RPC_TEST_VERSION" + let version = + if v == Just "unicode" then "1.0-\233" else testVersion + mainWith version rpcMap + Nothing -> runAllTests + + where + + runAllTests = do seed <- parseSeed <$> getArgs env <- setupEnv let tests = @@ -703,7 +721,11 @@ main = do ++ serverTests env ++ configTests ++ clientTests env - ++ installTests env + ++ map + (skipIf isWindows + "the fake remote host is the local host, \ + \Windows is not a POSIX remote host") + (installTests env) ++ unicodeTests env ++ quotingTests env runTests seed tests `finally` cleanupEnv env diff --git a/rpc/test/TestUtil.hs b/rpc/test/TestUtil.hs index 10130e8..859c40f 100644 --- a/rpc/test/TestUtil.hs +++ b/rpc/test/TestUtil.hs @@ -8,7 +8,6 @@ module TestUtil , serverMode , readFakeLog , clearFakeLog - , writeScript , utf8 , fakeServer , runServerRaw @@ -22,22 +21,20 @@ module TestUtil import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) -import Control.Exception (IOException, catch, evaluate) +import Control.Exception (IOException, catch) import Control.Monad (forM_, when) import Data.Aeson (Value, toJSON) import System.Directory - ( Permissions, createDirectory, findExecutable, getCurrentDirectory - , getPermissions, getTemporaryDirectory, removeDirectoryRecursive - , setCurrentDirectory, setOwnerExecutable, setPermissions ) + ( createDirectory, findExecutable, getCurrentDirectory + , getTemporaryDirectory, removeDirectoryRecursive, setCurrentDirectory ) import System.Environment (getEnvironment, getExecutablePath, lookupEnv, setEnv, unsetEnv) import System.Exit (ExitCode) -import System.FilePath (()) +import System.FilePath (searchPathSeparator, ()) import System.IO (hClose, hSetBinaryMode) -import System.Posix.Process (getProcessID) import System.Process ( CreateProcess(std_err, std_in, std_out), StdStream(..), createProcess - , proc, waitForProcess ) + , getCurrentPid, proc, waitForProcess ) import Test.QuickCheck (Gen) import qualified Data.Aeson as Json @@ -48,6 +45,8 @@ import qualified Data.ByteString.Lazy as BSL import qualified System.Process as Process import qualified Test.QuickCheck as QC +import Fake + ------------------------------------------------------------------------------- -- Environment ------------------------------------------------------------------------------- @@ -65,90 +64,19 @@ data Env = , envFakeLog :: FilePath -- ^ invocations of the fake commands } -fakeSsh :: String -fakeSsh = unlines - [ "#!/bin/sh" - , "# Run the remote command with sh in $SIMPLE_RPC_FAKE_HOME." - , logArgs "ssh" - , "while [ $# -gt 0 ]; do" - , " case \"$1\" in" - , " -T) shift ;;" - , " -p|-o) shift 2 ;;" - , " -*) echo \"fake ssh: unsupported option $1\" >&2; exit 255 ;;" - , " *) break ;;" - , " esac" - , "done" - , "shift" - , "cd \"$SIMPLE_RPC_FAKE_HOME\" || exit 255" - , "exec sh -c \"$*\"" - ] - -fakeScp :: String -fakeScp = unlines - [ "#!/bin/sh" - , "# scp -P PORT SRC HOST:DST, copy locally." - , logArgs "scp" - , "[ \"$1\" = \"-P\" ] && shift 2" - , "src=$1" - , "dst=${2#*:}" - , "case \"$dst\" in" - , " /*) ;;" - , " *) dst=\"$SIMPLE_RPC_FAKE_HOME/$dst\" ;;" - , "esac" - , "exec cp \"$src\" \"$dst\"" - ] - -fakeSudo :: String -fakeSudo = unlines - [ "#!/bin/sh" - , logArgs "sudo" - , "[ \"$1\" = \"--\" ] && shift" - , "exec \"$@\"" - ] - -fakeSu :: String -fakeSu = unlines - [ "#!/bin/sh" - , "# su USER -c CMD" - , logArgs "su" - , "[ \"$2\" = \"-c\" ] || { echo \"fake su: usage\" >&2; exit 1; }" - , "exec sh -c \"$3\"" - ] - --- | Shell code to append the command name and its arguments, each in --- brackets, as a line to the fake log. -logArgs :: String -> String -logArgs name = - "{ printf '" ++ name ++ "'; for a in \"$@\"; do printf ' [%s]' \"$a\"; \ - \done; echo; } >> \"$SIMPLE_RPC_FAKE_LOG\"" - --- | Write an executable script. -writeScript :: FilePath -> String -> IO () -writeScript path content = do - writeFile path content - p :: Permissions <- getPermissions path - setPermissions path (setOwnerExecutable True p) - -- | Encode a String as UTF-8. utf8 :: String -> BS.ByteString utf8 = BSL.toStrict . BSB.toLazyByteString . BSB.stringUtf8 --- | @fakeServer env name version output@ creates a fake RPC server script --- named @name@ that prints @version@ when called without arguments. --- Otherwise it reads stdin and prints @output@ without a trailing newline. --- Returns the path of the script. +-- | @fakeServer env name version output@ creates a fake RPC server named +-- @name@ that prints @version@ when called without arguments. Otherwise it +-- reads stdin and prints @output@. Returns the path of the server. fakeServer :: Env -> String -> String -> BS.ByteString -> IO FilePath fakeServer env name version output = do let path = envDir env name outFile = path ++ ".out" BS.writeFile outFile output - writeScript path $ unlines - [ "#!/bin/sh" - , "if [ $# -eq 0 ]; then printf '%s' '" ++ version ++ "'; exit 0; fi" - , "cat > /dev/null" - , "cat '" ++ outFile ++ "'" - ] - pure path + installFake (envExe env) path (FakeServer version outFile) -- | Create the temporary directory and the fake commands, put the fake -- commands first in @PATH@, make the temporary directory the working @@ -166,7 +94,7 @@ setupEnv :: IO Env setupEnv = do origDir <- getCurrentDirectory tmp <- getTemporaryDirectory - pid <- getProcessID + pid <- getCurrentPid exe <- getExecutablePath let dir = tmp ("simple-rpc-test-" ++ show pid) bin = dir "bin" @@ -176,23 +104,25 @@ setupEnv = do createDirectory bin createDirectory home writeFile logFile "" - writeScript (bin "ssh") fakeSsh - writeScript (bin "scp") fakeScp - writeScript (bin "sudo") fakeSudo - writeScript (bin "su") fakeSu + fakes <- + mapM + (\(cmd, fake) -> (cmd,) <$> installFake exe (bin cmd) fake) + [ ("ssh", FakeSsh), ("scp", FakeScp) + , ("sudo", FakeSudo), ("su", FakeSu) + ] path <- maybe "" id <$> lookupEnv "PATH" - setEnv "PATH" (bin ++ ":" ++ path) + setEnv "PATH" (bin ++ searchPathSeparator : path) setEnv "SIMPLE_RPC_FAKE_HOME" home setEnv "SIMPLE_RPC_FAKE_LOG" logFile uncurry setEnv serverMode -- Used in a test path, must expand to an empty string unsetEnv "SIMPLE_RPC_UNSET" - forM_ ["ssh", "scp", "sudo", "su"] $ \cmd -> do + forM_ fakes $ \(cmd, fakeExe) -> do found <- findExecutable cmd - when (found /= Just (bin cmd)) + when (found /= Just fakeExe) $ ioError $ userError $ "setupEnv: PATH finds " ++ show found ++ " for " ++ cmd - ++ ", not the fake " ++ show (bin cmd) + ++ ", not the fake " ++ show fakeExe setCurrentDirectory dir pure $ Env dir origDir exe logFile @@ -203,13 +133,10 @@ cleanupEnv env = do -- | The lines of the fake command log. readFakeLog :: Env -> IO [String] -readFakeLog env = do - s <- readFile (envFakeLog env) - _ <- evaluate (length s) - pure (lines s) +readFakeLog env = lines <$> readFileFs (envFakeLog env) clearFakeLog :: Env -> IO () -clearFakeLog env = writeFile (envFakeLog env) "" +clearFakeLog env = writeFileFs (envFakeLog env) "" ------------------------------------------------------------------------------- -- Server process From b79106c39d7f8d462c527a09de5fa1f38a41d388 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 02:42:38 +0530 Subject: [PATCH 22/32] Add GitHub CI for Linux, macOS, Windows and FreeBSD Based on the streamly CI using packcheck. Add cabal.project.ci with streamly-coreutils from git and cabal.project.Werror. The docspec job exposes the other-modules because cabal-docspec checks only exposed modules. --- .github/workflows/freebsd.yml | 90 ++++++++ .github/workflows/haskell.yml | 383 ++++++++++++++++++++++++++++++++++ cabal.project.Werror | 12 ++ cabal.project.ci | 9 + cabal.project.doctest | 8 + 5 files changed, 502 insertions(+) create mode 100644 .github/workflows/freebsd.yml create mode 100644 .github/workflows/haskell.yml create mode 100644 cabal.project.Werror create mode 100644 cabal.project.ci create mode 100644 cabal.project.doctest diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml new file mode 100644 index 0000000..4e4443e --- /dev/null +++ b/.github/workflows/freebsd.yml @@ -0,0 +1,90 @@ +# FreeBSD CI +# +# FreeBSD is not a native GitHub Actions runner, so this workflow runs +# the build inside a VM via vmactions/freebsd-vm. It is kept separate +# from haskell.yml because the cache/restore step model in that +# workflow (hackage index, ghcup, deps caches) does not apply inside +# the VM. + +name: FREEBSD + +on: + workflow_dispatch: + pull_request: + push: + branches: + - master + +jobs: + build: + name: >- + freebsd-${{ matrix.release }} + ${{ matrix.command }} + ${{ matrix.ghc_version }} + runs-on: ubuntu-latest + continue-on-error: ${{ matrix.ignore_error }} + strategy: + fail-fast: false + matrix: + include: + - release: "14.5" + command: cabal + ghc_version: 9.12.4 + ignore_error: false + + steps: + - uses: actions/checkout@v4 + + - name: Build on FreeBSD + uses: vmactions/freebsd-vm@v1 + env: + PACKCHECK_COMMAND: ${{ matrix.command }} + GHCVER: ${{ matrix.ghc_version }} + # For updating see: https://downloads.haskell.org/~ghcup/ + GHCUP_VERSION: 0.1.50.2 + LC_ALL: C.UTF-8 + CABAL_REINIT_CONFIG: y + CABAL_CHECK_RELAX: y + CABAL_PROJECT: cabal.project.ci + # The VM has 6 GB of memory, limit the parallel dependency builds. + CABAL_BUILD_OPTIONS: "-j2" + DISABLE_BENCH: "y" + DISABLE_DOCS: "y" + DISABLE_SDIST_BUILD: "y" + DISABLE_DIST_CHECKS: "y" + PACKCHECK: "./packcheck.sh" + PACKCHECK_GITHUB_URL: "https://raw.githubusercontent.com/composewell/packcheck" + PACKCHECK_GITHUB_COMMIT: "20514de6ae27035b0406b4ed46d628c806e40b49" + with: + release: ${{ matrix.release }} + usesh: true + copyback: false + envs: >- + PACKCHECK_COMMAND GHCVER GHCUP_VERSION LC_ALL + CABAL_REINIT_CONFIG CABAL_CHECK_RELAX CABAL_PROJECT CABAL_BUILD_OPTIONS + DISABLE_BENCH DISABLE_DOCS DISABLE_SDIST_BUILD DISABLE_DIST_CHECKS + PACKCHECK PACKCHECK_GITHUB_URL PACKCHECK_GITHUB_COMMIT + prepare: | + pkg update + pkg install -y gmake + pkg install -y bash + pkg install -y git + pkg install -y gmp + run: | + if test ! -e "$PACKCHECK" + then + if test -z "$PACKCHECK_GITHUB_COMMIT" + then + echo "PACKCHECK_GITHUB_COMMIT is not specified." >&2 + exit 1 + fi + PACKCHECK_URL=${PACKCHECK_GITHUB_URL}/${PACKCHECK_GITHUB_COMMIT}/packcheck.sh + curl --fail -sL -o "$PACKCHECK" $PACKCHECK_URL || exit 1 + chmod +x $PACKCHECK + elif test ! -x "$PACKCHECK" + then + chmod +x $PACKCHECK + fi + # Use "bash -c" instead of invoking directly to preserve quoted + # arguments in PACKCHECK_COMMAND. + bash -c "$PACKCHECK $PACKCHECK_COMMAND" diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml new file mode 100644 index 0000000..162f34e --- /dev/null +++ b/.github/workflows/haskell.yml @@ -0,0 +1,383 @@ +# packcheck-0.7.1 +# You can use any of the options supported by packcheck as environment +# variables here. See https://github.com/composewell/packcheck for all +# options and their explanation. + +name: TEST + +#----------------------------------------------------------------------------- +# Events on which the build should be triggered +#----------------------------------------------------------------------------- + +on: + workflow_dispatch: + pull_request: + push: + branches: + - master + +#----------------------------------------------------------------------------- +# Build matrix +#----------------------------------------------------------------------------- + +jobs: + build: + name: >- + ${{ matrix.runner }} + ${{ matrix.command }} + ${{ matrix.ghc_version }} + ${{ matrix.name }} + env: + # ------------------------------------------------------------------------ + # Common options + # ------------------------------------------------------------------------ + + # Subdir + SUBDIR: ${{ matrix.subdir }} + + # If this option is enabled packcheck clears out the environment + # and only uses the options explicitly set on the command line, + # implicit environment won't affect the build. + CHECK_ENV: "y" + + # NOTE: by capturing the options in env variables here quotes + # are preserved, if we expand them directly into the script + # quotes are lost. + # + # WARNING! you cannot use comments in this + COMMON_OPTIONS: >- + LC_ALL=C.UTF-8 + BUILD_PREFETCH=y + GHCUP_VERSION=latest + GHCVER=${{ matrix.ghc_version }} + DISABLE_SDIST_BUILD="y" + DISABLE_BENCH="y" + DISABLE_DOCS="y" + + # WARNING! you cannot use comments in this + CABAL_OPTIONS: >- + CABAL_REINIT_CONFIG=y + CABAL_CHECK_RELAX=y + + MATRIX_OPTIONS: ${{ matrix.pack_options }} + + # ------------------------------------------------------------------------ + # Location of packcheck.sh (the shell script invoked to perform CI tests ). + # ------------------------------------------------------------------------ + PACKCHECK_GITHUB_URL: "https://raw.githubusercontent.com/composewell/packcheck" + PACKCHECK_GITHUB_COMMIT: "20514de6ae27035b0406b4ed46d628c806e40b49" + + runs-on: ${{ matrix.runner }} + continue-on-error: ${{ matrix.ignore_error }} + strategy: + fail-fast: false + matrix: + + # IMPORTANT NOTE: + # If runner, command, ghc version are identical then the name of + # CI is used to distinguish the cache key. + + include: + + # Builds all packages, tests, benchmarks and docs. + - name: werror + runner: ubuntu-latest + command: cabal + ghc_version: 9.10.3 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.Werror + DISABLE_DOCS="n" + DISABLE_BENCH="n" + ignore_error: false + + # Builds simple-rpc from its source distribution, without a + # project file, the same way hackage builds it. + - name: simple-rpc-sdist + runner: ubuntu-latest + command: cabal + ghc_version: 9.10.3 + subdir: rpc + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + DISABLE_SDIST_BUILD="n" + ignore_error: false + + - name: ci + runner: ubuntu-latest + command: cabal + ghc_version: 9.14.1 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.ci + ignore_error: false + + - name: ci + runner: ubuntu-latest + command: cabal + ghc_version: 9.12.4 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.ci + ignore_error: false + + - name: ci + runner: ubuntu-latest + command: cabal + ghc_version: 9.8.4 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.ci + ignore_error: false + + - name: ci + runner: macos-latest + command: cabal + ghc_version: 9.12.4 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.ci + ignore_error: false + + # The fake ssh of the test suite runs the remote commands with + # the sh of Git for Windows, /usr/bin in the PATH that packcheck + # sets. + - name: ci + runner: windows-latest + command: cabal + ghc_version: 9.12.4 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.ci + ignore_error: false + + # The "Expose hidden modules" step below changes other-modules to + # exposed-modules in the simple-rpc library, because cabal-docspec + # checks the exposed modules only. + - name: docspec + runner: ubuntu-latest + command: cabal + ghc_version: 9.10.3 + # WARNING! cannot use # comments inside pack_options. + pack_options: >- + CABAL_PROJECT=cabal.project.doctest + DISABLE_TEST="y" + DISABLE_DIST_CHECKS="y" + ENABLE_DOCSPEC="y" + DOCSPEC_URL=https://github.com/phadej/cabal-extras/releases/download/cabal-docspec-0.0.0.20250606/cabal-docspec-0.0.0.20250606-x86_64-linux.xz + DOCSPEC_OPTIONS="--timeout 60" + ignore_error: false + +#----------------------------------------------------------------------------- +# Usually you do not need to change anything below, this is generic code for +# caching and running packcheck on Linux/Mac/Windows. +#----------------------------------------------------------------------------- + + steps: + + - name: Enable long paths on Windows + if: runner.os == 'Windows' + shell: powershell + continue-on-error: true + run: | + # Enable long paths. Sometimes failures occur due to path + # length limitation. + Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -value 1 + + - uses: actions/checkout@v4 + + - name: Expose hidden modules (docspec) + if: matrix.name == 'docspec' + run: | + sed -i '/^library/,/^[a-z]/ s/other-modules:/exposed-modules:/' \ + rpc/simple-rpc.cabal + grep -n 'modules:' rpc/simple-rpc.cabal + + # The macOS image may ship Command Line Tools newer than the default + # Xcode. Linking against the CLT SDK then fails with "tapi error: + # malformed file ... unknown architecture arm64e.x1-macos". Select the + # default Xcode so that the compiler, linker and SDK come from the same + # toolchain, and point the CLT MacOSX.sdk symlink at the Xcode SDK + # because the GHC bindists hardcode the CLT SDK path. packcheck clears + # the environment, so SDKROOT or DEVELOPER_DIR cannot be used instead. + # + # The GHC and dependency cache keys include the Xcode version and build, + # so a runner image with a different Xcode installs GHC afresh. + - name: Select default Xcode (macOS) + id: xcode + if: runner.os == 'macOS' + run: | + sudo xcode-select -s /Applications/Xcode.app/Contents/Developer + xcode-select -p + sdk=$(xcrun --show-sdk-path) + echo "$sdk" + clt=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk + if test -L "$clt"; then + ls -ld "$clt" + sudo ln -sfn "$sdk" "$clt" + ls -ld "$clt" + fi + ver=$(xcodebuild -version | awk 'NR==1{v=$2} /Build version/{b=$3} END{print v "-" b}') + echo "toolchain=-xcode-$ver" >> "$GITHUB_OUTPUT" + + # This should happen before cache restore. + - name: Remove ~/.ghcup symlink (non-Windows) + if: runner.os != 'Windows' + run: | + rm -f ~/.ghcup + + # On Windows the hackage index is part of C:/cabal, see below. + - name: Restore hackage package index (non-Windows) + id: restore-hackage + uses: actions/cache/restore@v4 + if: runner.os != 'Windows' + with: + path: | + ~/.cache/cabal/packages + key: cabal-hackage-index + + # GHC is not test/options specific. On Windows restoring GHC from the + # cache takes longer than installing it, so it is not cached. + - name: Restore ghcup and ghc (non-Windows) + id: restore-ghcup + uses: actions/cache/restore@v4 + if: runner.os != 'Windows' + with: + path: | + ~/.ghcup + key: ghc-${{ matrix.ghc_version }}-${{ matrix.runner }}${{ steps.xcode.outputs.toolchain }} + + # Deps are test/options specific + - name: Restore build dependencies (non-Windows) + id: restore-deps-nonwin + uses: actions/cache/restore@v4 + if: runner.os != 'Windows' + with: + path: | + ~/.local/bin + ~/.local/state/cabal + key: ${{ matrix.command }}-deps-ghc-${{ matrix.ghc_version }}-${{ matrix.runner }}-${{ matrix.name }}${{ steps.xcode.outputs.toolchain }}-${{ hashFiles('cabal.project*') }} + + # Deps are test/options specific + - name: Restore build dependencies, hackage index (Windows) + id: restore-deps-win + uses: actions/cache/restore@v4 + if: runner.os == 'Windows' + with: + path: | + C:/cabal + key: ${{ matrix.command }}-deps-ghc-${{ matrix.ghc_version }}-${{ matrix.runner }}-${{ matrix.name }}-${{ hashFiles('cabal.project*') }} + + - name: Download packcheck + # on windows-latest GitHub Actions defaults to PowerShell + shell: bash + run: | + if test -n "$SUBDIR"; then + cd "$SUBDIR" + fi + if test -z "$PACKCHECK_GITHUB_COMMIT"; then + echo "PACKCHECK_GITHUB_COMMIT env var is not specified." >&2 + exit 1 + fi + curl --fail -sLO \ + "${PACKCHECK_GITHUB_URL}/${PACKCHECK_GITHUB_COMMIT}/packcheck.sh" + chmod +x packcheck.sh + + # Store the function in a file so that it can be reused across multiple + # steps. + - name: Setup packcheck + shell: bash + run: | + if test -n "$SUBDIR"; then + rm -f cabal.project + cd "$SUBDIR" + fi + cat << 'EOF' > packcheck-setup.sh + setup_packcheck_args() { + ARGS="${{ matrix.command }} $COMMON_OPTIONS" + if test "${{ matrix.command }}" = "cabal"; then + ARGS="$ARGS $CABAL_OPTIONS" + fi + + # Caution: do not use matrix.pack_options directly here + # quotes will get stripped. + ARGS="$ARGS $MATRIX_OPTIONS" + PATH_VAR=/bin:/usr/bin:/sbin:/usr/sbin + + case "$(uname)" in + Linux) + export GHCUP_INSTALL_BASE_PREFIX=$HOME + ;; + CYGWIN*|MINGW*|MSYS*) + for var in APPDATA CABAL_DIR; do + val="${!var}" + [ -n "$val" ] && ARGS="$ARGS $var=\"$(cygpath -u "$val")\"" + done + ARGS="$ARGS CABAL_BUILDDIR=\"/c/b\" WINVER=$WINVER" + ARGS="$ARGS NUMBER_OF_PROCESSORS=$NUMBER_OF_PROCESSORS" + ARGS="$ARGS PROCESSOR_IDENTIFIER=\"$PROCESSOR_IDENTIFIER\"" + # Git for Windows 2.56 moved /mingw64 to /ucrt64 + PATH_VAR="$PATH_VAR:/c/ghcup:/c/Program Files/7-Zip:/ucrt64/bin:/mingw64/bin" + ;; + esac + ARGS="$ARGS PATH=\"$PATH_VAR\"" + export ARGS + } + EOF + + - name: Run packcheck (dependencies only) + id: deps-only + if: | + (runner.os != 'Windows' && steps.restore-deps-nonwin.outputs.cache-hit != 'true') || + (runner.os == 'Windows' && steps.restore-deps-win.outputs.cache-hit != 'true') + shell: bash + run: | + if test -n "$SUBDIR"; then + cd "$SUBDIR" + fi + source packcheck-setup.sh + setup_packcheck_args + eval "./packcheck.sh $ARGS BUILD_DEPS_ONLY=y" + + - name: Save hackage package index (non-Windows) + uses: actions/cache/save@v4 + if: always() && steps.deps-only.outcome == 'success' && runner.os != 'Windows' && steps.restore-hackage.outputs.cache-hit != 'true' + with: + path: ~/.cache/cabal/packages + key: cabal-hackage-index + + - name: Save ghcup and ghc (non-Windows) + uses: actions/cache/save@v4 + if: always() && steps.deps-only.outcome == 'success' && runner.os != 'Windows' && steps.restore-ghcup.outputs.cache-hit != 'true' + with: + path: ~/.ghcup + key: ghc-${{ matrix.ghc_version }}-${{ matrix.runner }}${{ steps.xcode.outputs.toolchain }} + + # Deps are test/options specific, hence, matrix.name in the key + - name: Save build dependencies (non-Windows) + uses: actions/cache/save@v4 + if: always() && steps.deps-only.outcome == 'success' && runner.os != 'Windows' && steps.restore-deps-nonwin.outputs.cache-hit != 'true' + with: + path: | + ~/.local/bin + ~/.local/state/cabal + key: ${{ matrix.command }}-deps-ghc-${{ matrix.ghc_version }}-${{ matrix.runner }}-${{ matrix.name }}${{ steps.xcode.outputs.toolchain }}-${{ hashFiles('cabal.project*') }} + + # The hackage package index is part of C:/cabal + - name: Save build dependencies (Windows) + uses: actions/cache/save@v4 + if: always() && steps.deps-only.outcome == 'success' && runner.os == 'Windows' && steps.restore-deps-win.outputs.cache-hit != 'true' + with: + path: | + C:/cabal + key: ${{ matrix.command }}-deps-ghc-${{ matrix.ghc_version }}-${{ matrix.runner }}-${{ matrix.name }}-${{ hashFiles('cabal.project*') }} + + - name: Run packcheck (final build) + shell: bash + run: | + if test -n "$SUBDIR"; then + cd "$SUBDIR" + fi + source packcheck-setup.sh + setup_packcheck_args + eval "./packcheck.sh $ARGS BUILD_PACKAGE_ONLY=y" diff --git a/cabal.project.Werror b/cabal.project.Werror new file mode 100644 index 0000000..cdf30f3 --- /dev/null +++ b/cabal.project.Werror @@ -0,0 +1,12 @@ +-- Fail the build on any warning in the local packages. + +import: cabal.project.ci + +package simple-rpc + ghc-options: -Werror + +package simple-rpc-generate + ghc-options: -Werror + +package example + ghc-options: -Werror diff --git a/cabal.project.ci b/cabal.project.ci new file mode 100644 index 0000000..061d99d --- /dev/null +++ b/cabal.project.ci @@ -0,0 +1,9 @@ +-- Project file for the CI builds from Hackage. streamly-coreutils is not +-- on Hackage, use the commit pinned in the streamly-packages nix set. + +import: cabal.project + +source-repository-package + type: git + location: https://github.com/composewell/streamly-coreutils.git + tag: fa180060c7510c89d2767980ca6f7ec7011d04b9 diff --git a/cabal.project.doctest b/cabal.project.doctest new file mode 100644 index 0000000..a7030ff --- /dev/null +++ b/cabal.project.doctest @@ -0,0 +1,8 @@ +-- Project file for cabal-docspec. The docspec CI changes other-modules to +-- exposed-modules in rpc/simple-rpc.cabal before the build, because +-- cabal-docspec checks the exposed modules only. + +packages: rpc + +-- Cap GHC heap usage so that builds do not exhaust the machine memory +flags: +limit-build-mem From c177fd2c937097d58af09927e3f8b50901dc93b8 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 03:12:23 +0530 Subject: [PATCH 23/32] Write \n line ends on the server stdout on all OSes GHC translates \n to \r\n on the standard handles on Windows. Disable newline translation on stdout. --- rpc/CHANGELOG.md | 3 ++- rpc/lib/Simple/RPC/Server.hs | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/rpc/CHANGELOG.md b/rpc/CHANGELOG.md index 7adcb9e..beaa0b4 100644 --- a/rpc/CHANGELOG.md +++ b/rpc/CHANGELOG.md @@ -26,7 +26,8 @@ can break existing callers: directory. Before, the directory was made writable by all users and the file was owned by the ssh user. It needs `mktemp` and `install` on the remote host. -* The server sets the encoding of stdout to UTF-8. +* The server sets the encoding of stdout to UTF-8, and writes `\n` line + ends on all OSes. Before, it wrote `\r\n` on Windows. ### Additions diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index be94dbe..ed7ef60 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -19,7 +19,8 @@ import Control.Exception (throwIO) import Data.Function ((&)) import Streamly.Internal.Unicode.String (str) import System.Environment (getArgs) -import System.IO (hSetEncoding, stdin, stdout, utf8) +import System.IO + (hSetEncoding, hSetNewlineMode, noNewlineTranslation, stdin, stdout, utf8) import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Fold as Fold @@ -32,6 +33,13 @@ import Simple.RPC.Internal.Types -- Utils ------------------------------------------------------------------------------- +-- | Write stdout as UTF-8 with @\\n@ line ends, independent of the locale +-- and the OS. Without this, GHC writes @\\r\\n@ for @\\n@ on Windows. +setStdoutMode :: IO () +setStdoutMode = do + hSetEncoding stdout utf8 + hSetNewlineMode stdout noNewlineTranslation + -- XXX To reduce execution delays we should have this running as a server. Or -- at least make sure the executable is not swapped out. @@ -52,7 +60,8 @@ import Simple.RPC.Internal.Types -- The client takes the last line of the output as the result. -- -- The encoding of stdout is set to UTF-8, the client decodes the output as --- UTF-8 independent of the locale of the server. +-- UTF-8 independent of the locale of the server. A newline is written as +-- @\\n@ on all OSes, including Windows. -- -- Raise an 'EndpointNotFound' exception if the map does not have the -- function, and an 'InvalidInput' exception if the input is not valid JSON or @@ -74,7 +83,7 @@ invokeFunction actions actionName = do case lookupRpcSymbol actionName actions of Nothing -> throwIO (EndpointNotFound actionName) Just actFun -> do - hSetEncoding stdout utf8 + setStdoutMode let inputString = decodeUtf8Array inputBytes putStrLn $ showPair "SERVER" [str|#{actionName} #{inputString}|] r <- irFromArray inputBytes @@ -108,6 +117,6 @@ mainWith :: String -> RpcMap IntermediateRep -> IO () mainWith version actions = do args <- getArgs case args of - [] -> hSetEncoding stdout utf8 >> putStr version + [] -> setStdoutMode >> putStr version [actName] -> invokeFunction actions actName _ -> throwIO (InvalidUsage args) From 679af080d881e7bd34cb76d78117e9b5d859af1b Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 03:12:23 +0530 Subject: [PATCH 24/32] Document the Windows limits and the external commands needed Document that setRemote needs a POSIX remote shell, that local sudo and su do not work on Windows, and that installOnRemote needs a compatible remote host. Add a Dependencies paragraph to runAt, installOnRemote, setRemote, setUser and useSudo. --- rpc/lib/Simple/RPC/Client.hs | 23 +++++++++++++++++++++-- rpc/lib/Simple/RPC/Internal/Types.hs | 18 +++++++++++++++++- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 63e3cad..9e9280e 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -239,6 +239,12 @@ with (RunningConfig{..}) actionName input = do -- 'Streamly.Internal.System.Process.ProcessFailure' exception. The server -- reads the whole input before it raises an exception for an unknown -- endpoint. +-- +-- /Dependencies/: none for a local call as the current user. 'setRemote' +-- needs @ssh@ on the local host and a POSIX shell for the ssh user on the +-- remote host. 'setUser' needs @sudo@, @su@ and a POSIX shell for the user. +-- 'useSudo' needs @sudo@. With 'setRemote', @sudo@ and @su@ run on the +-- remote host, otherwise on the local host. runAt :: RunningConfig -> RpcSymbol IntermediateRep typ -> typ runAt cfg sym = call sym (with cfg) @@ -272,13 +278,26 @@ run = direct -- -- The permissions of an existing directory are not changed. @install@ -- creates a new file, therefore an instance of the executable that is --- running is not affected. Requires @sudo@ access, @mktemp@ and @install@ --- on the remote machine. +-- running is not affected. +-- +-- The local executable is copied as it is, the remote host must be able to +-- run the same file: the same OS and CPU architecture, and, unless the +-- executable is statically linked, compatible versions of the shared +-- libraries that it is linked with, e.g. glibc, libgmp and libffi. For +-- example, an executable built on macOS does not run on Linux, and one +-- built on a Linux distribution with a newer glibc may not run on another. +-- The version check runs the local executable, therefore it also has to +-- run on the local host. Not supported on a Windows client or a Windows +-- remote host. -- -- Raise a 'VersionMismatch' exception if the local executable prints a -- version other than 'executableVersion', and a -- 'Streamly.Internal.System.Process.ProcessFailure' exception if a command -- fails. +-- +-- /Dependencies/: @ssh@ and @scp@ on the local host. A POSIX shell for the +-- ssh user, @mktemp@, @rm@, @mkdir@, @install@ and @sudo@ access on the +-- remote host. installOnRemote :: Executable -> (String, String) -> FilePath -> IO () installOnRemote localExe sshConf@(addr, port) remoteExePath = do let exePath = executablePath localExe diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 03315e3..acca937 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -218,9 +218,14 @@ setImageFlags x rc = rc { rcImageFlags = x } -- address is passed to ssh as it is, e.g. @user\@host@. -- -- The remote command is run by the shell of the ssh user, the client quotes --- it for a POSIX shell. +-- it for a POSIX shell. The remote host must have a POSIX shell as the +-- shell of the ssh user, a Windows host is not supported. The client can be +-- on Windows, it runs @ssh.exe@. -- -- Default is 'Nothing', the executable is run on the local host without ssh. +-- +-- /Dependencies/: @ssh@ on the local host, a POSIX shell for the ssh user on +-- the remote host. setRemote :: (String, String) -> RunningConfig -> RunningConfig setRemote x rc = rc { rcRemote = Just x } @@ -230,7 +235,13 @@ setRemote x rc = rc { rcRemote = Just x } -- command with the shell of the user, the client quotes it for a POSIX -- shell. The version check is run as the current user. -- +-- Without 'setRemote', @sudo@ and @su@ are run on the local host, which is +-- not supported on Windows. +-- -- Default is 'Nothing', the endpoint is run as the current user. +-- +-- /Dependencies/: @sudo@ and @su@ on the host that runs the executable, a +-- POSIX shell for the user. setUser :: String -> RunningConfig -> RunningConfig setUser x rc = rc { rcUser = Just x } @@ -239,7 +250,12 @@ setUser x rc = rc { rcUser = Just x } -- executable ...@ is the command run by @su@, the user must be allowed to -- run @sudo@. -- +-- Without 'setRemote', @sudo@ is run on the local host, which is not +-- supported on Windows. +-- -- Default is 'False'. +-- +-- /Dependencies/: @sudo@ on the host that runs the executable. useSudo :: Bool -> RunningConfig -> RunningConfig useSudo x rc = rc { rcSudo = x } From 75ba7143626dc31d35577f7cd41a16ed66695008 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 05:19:16 +0530 Subject: [PATCH 25/32] Import public streamly modules instead of internal ones Use the public modules for the functions they export. Only compactEndByLn_, fromPtrN, unsafePinnedAsPtr and ordNub are still imported from internal modules. --- generate/app/Main.hs | 7 ++++--- rpc/lib/Simple/RPC/Client.hs | 6 +++--- rpc/lib/Simple/RPC/Server.hs | 2 +- rpc/test/Main.hs | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/generate/app/Main.hs b/generate/app/Main.hs index 511b949..0ffb4aa 100644 --- a/generate/app/Main.hs +++ b/generate/app/Main.hs @@ -9,10 +9,11 @@ import Data.Maybe (fromJust, fromMaybe) import Streamly.Unicode.String (str) import System.FilePath (()) -import qualified Streamly.Internal.Data.Parser as Parser -import qualified Streamly.Internal.Data.Stream as Stream +import qualified Streamly.Data.Parser as Parser +import qualified Streamly.Data.Stream as Stream +import qualified Streamly.Internal.Data.Stream as Stream (ordNub) import qualified Streamly.FileSystem.FileIO as File -import qualified Streamly.Internal.FileSystem.Path as Path +import qualified Streamly.FileSystem.Path as Path import qualified Streamly.Data.Fold as Fold import qualified Streamly.Unicode.Stream as Unicode diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 9e9280e..8c6da21 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -38,15 +38,15 @@ import Data.Char (isAsciiLower, isAsciiUpper, isDigit) import Data.Function ((&)) import Data.Word (Word8) import Streamly.Data.Array (Array) -import Streamly.Internal.Unicode.String (str) +import Streamly.Unicode.String (str) import System.FilePath (takeDirectory) import qualified Data.IORef as IORef import qualified Streamly.Internal.Data.Array as Array (compactEndByLn_) import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream -import qualified Streamly.Internal.System.Process as Proc -import qualified Streamly.Internal.Unicode.Stream as Unicode +import qualified Streamly.System.Process as Proc +import qualified Streamly.Unicode.Stream as Unicode import Simple.RPC.Internal.Types diff --git a/rpc/lib/Simple/RPC/Server.hs b/rpc/lib/Simple/RPC/Server.hs index ed7ef60..9db85e6 100644 --- a/rpc/lib/Simple/RPC/Server.hs +++ b/rpc/lib/Simple/RPC/Server.hs @@ -17,7 +17,7 @@ module Simple.RPC.Server import Control.Exception (throwIO) import Data.Function ((&)) -import Streamly.Internal.Unicode.String (str) +import Streamly.Unicode.String (str) import System.Environment (getArgs) import System.IO (hSetEncoding, hSetNewlineMode, noNewlineTranslation, stdin, stdout, utf8) diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 47badda..e66a6b3 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -14,7 +14,7 @@ import Data.Int (Int64) import Data.IORef (modifyIORef, newIORef, readIORef) import Data.List (isInfixOf, isPrefixOf, sort) import GHC.Clock (getMonotonicTime) -import Streamly.Internal.System.Process (ProcessFailure(..)) +import Streamly.System.Process (ProcessFailure(..)) import System.Directory ( copyFile, createDirectory, doesFileExist, executable, exeExtension , getPermissions ) From 0602e966475ddfe73b12b91b7bba828914d6c65b Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 05:46:10 +0530 Subject: [PATCH 26/32] Convert ByteString and Array with streamly-bytestring Replace the pointer-based copies in Types.hs with toArray and fromArray from streamly-bytestring. toArray does not copy the ByteString, and the internal fromPtrN and unsafePinnedAsPtr imports are no longer needed. Pin streamly-bytestring 0.2.3 revision 3, which allows streamly-core 0.3.3. --- rpc/lib/Simple/RPC/Internal/Types.hs | 20 ++++---------------- rpc/simple-rpc.cabal | 1 + sources.nix | 6 ++++++ 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index acca937..34e1e7f 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -69,7 +69,6 @@ import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.Vector ((!?)) import Data.Word (Word8) -import Foreign.Ptr (castPtr) import Streamly.Data.Array (Array) import Streamly.Data.Stream (Stream) @@ -78,7 +77,6 @@ import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Bifunctor import qualified Data.ByteString as BS -import qualified Data.ByteString.Unsafe as BS.Unsafe import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM import qualified Data.Text.Encoding.Error as Text @@ -88,8 +86,7 @@ import qualified Data.Vector as Vector import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream import qualified Streamly.Data.Unfold as Unfold -import qualified Streamly.Internal.Data.Array as Array - (fromPtrN, unsafePinnedAsPtr) +import qualified Streamly.External.ByteString as StreamlyBS import qualified Streamly.Unicode.Stream as Unicode ------------------------------------------------------------------------------- @@ -392,18 +389,12 @@ toBinStream input = Stream.fromList (BSL.toChunks (Json.encode input)) & Stream.unfoldEach (Unfold.lmap BS.unpack Unfold.fromList) --- | Copy a ByteString to an array. -byteStringToArray :: BS.ByteString -> IO (Array Word8) -byteStringToArray c = - BS.Unsafe.unsafeUseAsCStringLen c - $ \(p, n) -> Array.fromPtrN n (castPtr p) - -- | Convert the Haskell representation of IR (i.e. Json) to a stream of -- arrays of its JSON encoding, one array for each chunk of the lazy encoding. toChunkStream :: IntermediateRep -> Stream IO (Array Word8) toChunkStream input = Stream.fromList (BSL.toChunks (Json.encode input)) - & Stream.mapM byteStringToArray + & fmap StreamlyBS.toArray -- | Convert a byte stream of IR (i.e. Json) to its Haskell representation. fromBinStream :: Stream IO Word8 -> IO IntermediateRep @@ -422,11 +413,8 @@ decodeUtf8Array arr = -- | Decode the UTF-8 encoded JSON representation of IR in a byte array. -- Returns the decoding error message on failure. irFromArray :: Array Word8 -> IO (Either String IntermediateRep) -irFromArray arr = do - bs <- - Array.unsafePinnedAsPtr arr - $ \p n -> BS.packCStringLen (castPtr p, n) - pure $ Json.eitherDecodeStrict' bs +irFromArray arr = + pure $ Json.eitherDecodeStrict' (StreamlyBS.fromArray arr) -- | Convert the Haskell representation of IR (i.e. Json) to String. Used for -- logging. diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 7942138..562f89f 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -55,6 +55,7 @@ library other-modules: Simple.RPC.Internal.TH , Simple.RPC.Internal.Types build-depends: base + , streamly-bytestring , streamly-core , streamly-process , template-haskell diff --git a/sources.nix b/sources.nix index a5bbccb..4020ce8 100644 --- a/sources.nix +++ b/sources.nix @@ -12,6 +12,12 @@ layers = [ // { rev = "3"; cabalSha256 = "0xvx6vacr9vlss67qs5v25gbj6xvxjzx4f7w5ck9lr845g57k9ay"; }; + # Hackage revision 3 allows streamly-core < 0.3.4 + streamly-bytestring = hackage "0.2.3" + "05nnpcq7jqmpfzwv7giqi50i6mnzmfywxgy40d506vx2xr27n5b4" + // { rev = "3"; + cabalSha256 = "0ciq3zj3jqj482xhgz2rwyin9hiwci8cm852s8yv254yv6dzhkdn"; + }; simple-rpc = local ./rpc; simple-rpc-generate = local ./generate; example = local ./example; From d3cabc08052a46796b4ba9f9ec8e3c8e678968a4 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 05:57:59 +0530 Subject: [PATCH 27/32] Decode irToString with streamly-core instead of text Decode the UTF-8 JSON bytes from toBinStream with Unicode.decodeUtf8, which also replaces invalid bytes with U+FFFD. Drop the text dependency of the library. --- rpc/lib/Simple/RPC/Internal/Types.hs | 5 +---- rpc/simple-rpc.cabal | 1 - 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 34e1e7f..784951a 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -79,9 +79,6 @@ import qualified Data.Bifunctor import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM -import qualified Data.Text.Encoding.Error as Text -import qualified Data.Text.Lazy as TextL -import qualified Data.Text.Lazy.Encoding as TextL import qualified Data.Vector as Vector import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream @@ -420,7 +417,7 @@ irFromArray arr = -- logging. irToString :: IntermediateRep -> String irToString input = - TextL.unpack $ TextL.decodeUtf8With Text.lenientDecode $ Json.encode input + runIdentity $ Stream.toList $ Unicode.decodeUtf8 $ toBinStream input ------------------------------------------------------------------------------- -- Conerting Haskell values to/from IR diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 562f89f..5762919 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -63,7 +63,6 @@ library , bytestring , vector , filepath - , text , unordered-containers hs-source-dirs: lib From 09407979eb3c10e81720bafab0237de070f11dcc Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 06:01:16 +0530 Subject: [PATCH 28/32] Drop the bytestring dependency of the library Convert the lazy JSON encoding to a byte or chunk stream with Streamly.External.ByteString.Lazy, and fold the input bytes of fromBinStream into a strict ByteString with StreamlyBS.write instead of building a list and packing it. --- rpc/lib/Simple/RPC/Internal/Types.hs | 15 +++++---------- rpc/simple-rpc.cabal | 1 - 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 784951a..6f9e900 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -65,7 +65,6 @@ module Simple.RPC.Internal.Types import Control.Exception (Exception(..), throwIO) import Data.Aeson (ToJSON, FromJSON, toJSON, fromJSON) -import Data.Function ((&)) import Data.Functor.Identity (runIdentity) import Data.Vector ((!?)) import Data.Word (Word8) @@ -76,14 +75,12 @@ import qualified Data.Aeson as Json import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Bifunctor -import qualified Data.ByteString as BS -import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM import qualified Data.Vector as Vector import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream -import qualified Streamly.Data.Unfold as Unfold import qualified Streamly.External.ByteString as StreamlyBS +import qualified Streamly.External.ByteString.Lazy as StreamlyBSL import qualified Streamly.Unicode.Stream as Unicode ------------------------------------------------------------------------------- @@ -383,21 +380,19 @@ type IntermediateRep = Json.Value {-# INLINE toBinStream #-} toBinStream :: Monad m => IntermediateRep -> Stream m Word8 toBinStream input = - Stream.fromList (BSL.toChunks (Json.encode input)) - & Stream.unfoldEach (Unfold.lmap BS.unpack Unfold.fromList) + Stream.unfold StreamlyBSL.reader (Json.encode input) -- | Convert the Haskell representation of IR (i.e. Json) to a stream of -- arrays of its JSON encoding, one array for each chunk of the lazy encoding. toChunkStream :: IntermediateRep -> Stream IO (Array Word8) toChunkStream input = - Stream.fromList (BSL.toChunks (Json.encode input)) - & fmap StreamlyBS.toArray + StreamlyBSL.toChunks (Json.encode input) -- | Convert a byte stream of IR (i.e. Json) to its Haskell representation. fromBinStream :: Stream IO Word8 -> IO IntermediateRep fromBinStream input = do - res <- Stream.toList input - case Json.decode $ BSL.pack res of + res <- Stream.fold StreamlyBS.write input + case Json.decodeStrict res of Nothing -> error "Unable to decode" Just x -> pure x diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 5762919..199ae11 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -60,7 +60,6 @@ library , streamly-process , template-haskell , aeson - , bytestring , vector , filepath , unordered-containers From 8912c3508dd9a576f703b1c79d12095b03ea2250 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 06:08:49 +0530 Subject: [PATCH 29/32] Drop the vector dependency of the library irArgs checks the length of the aeson array with Foldable length, which takes constant time, and returns the arguments as a list. createArr builds the array with toJSON. Neither needs to name the Vector type. --- rpc/lib/Simple/RPC/Internal/Types.hs | 17 ++++++++--------- rpc/simple-rpc.cabal | 1 - 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 6f9e900..7e1d45c 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -65,8 +65,8 @@ module Simple.RPC.Internal.Types import Control.Exception (Exception(..), throwIO) import Data.Aeson (ToJSON, FromJSON, toJSON, fromJSON) +import Data.Foldable (toList) import Data.Functor.Identity (runIdentity) -import Data.Vector ((!?)) import Data.Word (Word8) import Streamly.Data.Array (Array) import Streamly.Data.Stream (Stream) @@ -76,7 +76,6 @@ import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Bifunctor import qualified Data.HashMap.Strict as HM -import qualified Data.Vector as Vector import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream import qualified Streamly.External.ByteString as StreamlyBS @@ -439,9 +438,9 @@ resultFromIR val = -- | @irArgs n ir@ returns the elements of the IR array @ir@. Raise an -- 'InvalidInput' exception if @ir@ is not an array of @n@ elements. -irArgs :: Int -> IntermediateRep -> IO (Vector.Vector IntermediateRep) +irArgs :: Int -> IntermediateRep -> IO [IntermediateRep] irArgs n (Json.Array vec) - | Vector.length vec == n = pure vec + | length vec == n = pure (toList vec) irArgs n ir = throwIO $ InvalidInput @@ -451,11 +450,11 @@ irArgs n ir = -- | @irArg args i@ decodes the element at index @i@ of the arguments returned -- by 'irArgs'. Raise an 'InvalidInput' exception if the index is out of -- bounds or the element cannot be decoded to the required type. -irArg :: FromJSON a => Vector.Vector IntermediateRep -> Int -> IO a +irArg :: FromJSON a => [IntermediateRep] -> Int -> IO a irArg args i = - case args !? i of - Nothing -> throwIO $ InvalidInput $ "missing argument " ++ show i - Just v -> + case drop i args of + [] -> throwIO $ InvalidInput $ "missing argument " ++ show i + v : _ -> case fromJSON v of Json.Error err -> throwIO @@ -465,7 +464,7 @@ irArg args i = -- | Create an array in IR from a list of IR Haskell values. createArr :: [IntermediateRep] -> IntermediateRep -createArr = Json.Array . Vector.fromList +createArr = toJSON ------------------------------------------------------------------------------- -- Key-value maps in IR diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 199ae11..f032afd 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -60,7 +60,6 @@ library , streamly-process , template-haskell , aeson - , vector , filepath , unordered-containers hs-source-dirs: lib From c02ee2ee35435400540e68e0e8a0a323491a6679 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 06:11:23 +0530 Subject: [PATCH 30/32] Use Data.Map instead of HashMap for RpcMap The endpoint table is looked up once per server process, so a Map from containers, which ships with GHC, does as well as a HashMap. Drop the unordered-containers dependency. RpcMap is exported, so record the type change in the changelog. --- rpc/CHANGELOG.md | 8 ++++++-- rpc/lib/Simple/RPC/Internal/Types.hs | 9 ++++----- rpc/simple-rpc.cabal | 4 ++-- rpc/test/Main.hs | 8 ++++---- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/rpc/CHANGELOG.md b/rpc/CHANGELOG.md index beaa0b4..13d5497 100644 --- a/rpc/CHANGELOG.md +++ b/rpc/CHANGELOG.md @@ -4,8 +4,12 @@ ### Breaking changes -No exported type signature has changed. The following behavior changes -can break existing callers: +* `RpcMap`, exported from `Simple.RPC.Server`, is a `Data.Map.Strict.Map` + instead of a `Data.HashMap.Strict.HashMap`. Code that builds it with + `createRpcMap` does not change; code that uses `HashMap` functions on it + must use the `Map` functions. + +The following behavior changes can break existing callers: * Errors are raised as an `RpcException` instead of an `ErrorCall`: an unknown endpoint (`EndpointNotFound`), an invalid server input diff --git a/rpc/lib/Simple/RPC/Internal/Types.hs b/rpc/lib/Simple/RPC/Internal/Types.hs index 7e1d45c..d9f0450 100644 --- a/rpc/lib/Simple/RPC/Internal/Types.hs +++ b/rpc/lib/Simple/RPC/Internal/Types.hs @@ -75,7 +75,7 @@ import qualified Data.Aeson as Json import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import qualified Data.Bifunctor -import qualified Data.HashMap.Strict as HM +import qualified Data.Map.Strict as Map import qualified Streamly.Data.Array as Array import qualified Streamly.Data.Stream as Stream import qualified Streamly.External.ByteString as StreamlyBS @@ -328,11 +328,10 @@ rpcServiceFunction = eval . evaluator rpcCallUsing :: RpcSymbol ir typ -> Runner ir -> typ rpcCallUsing = call --- XXX Map instead of HashMap? -- XXX rename to ServiceMap -- | A map of endpoint names and the corresponding server side wrappers. -type RpcMap ir = HM.HashMap String (ir -> IO ir) +type RpcMap ir = Map.Map String (ir -> IO ir) -- XXX serviceMapFromList @@ -340,13 +339,13 @@ type RpcMap ir = HM.HashMap String (ir -> IO ir) -- the wrapper of an t'RpcSymbol'. If two wrappers have the same endpoint name, -- the map has the one later in the list. createRpcMap :: [RpcEval ir] -> RpcMap ir -createRpcMap = HM.fromList . map (\x -> (symbol x, eval x)) +createRpcMap = Map.fromList . map (\x -> (symbol x, eval x)) -- XXX lookupService -- | Lookup a symbol in a map. lookupRpcSymbol :: String -> RpcMap ir -> Maybe (ir -> IO ir) -lookupRpcSymbol = HM.lookup +lookupRpcSymbol = Map.lookup ------------------------------------------------------------------------------- -- Pretty printing diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index f032afd..18cc84d 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -61,7 +61,7 @@ library , template-haskell , aeson , filepath - , unordered-containers + , containers hs-source-dirs: lib test-suite simple-rpc-test @@ -85,7 +85,7 @@ test-suite simple-rpc-test , process >= 1.6.12 , streamly-core , streamly-process - , unordered-containers + , containers benchmark simple-rpc-bench import: lib-options diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index e66a6b3..1fc4fc9 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -32,7 +32,7 @@ import qualified Data.Aeson as Json import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL -import qualified Data.HashMap.Strict as HM +import qualified Data.Map.Strict as Map import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream import qualified Test.QuickCheck as QC @@ -152,11 +152,11 @@ serverTests env = , "TestFunctions.replicateChar", "TestFunctions.three" , "TestFunctions.valRpc", "TestFunctions.writeMarker" ]) - (sort (HM.keys rpcMap)) + (Map.keys rpcMap) , test "evaluator in createRpcMap calls the function with IR" $ do let m = createRpcMap [evaluator add, evaluator constant] - case HM.lookup "TestFunctions.add" m of + case Map.lookup "TestFunctions.add" m of Nothing -> assertBool "add not found" False Just f -> do r <- f (toIntermediateRep [2, 3 :: Int]) @@ -166,7 +166,7 @@ serverTests env = InvalidInput _ -> True _ -> False) (f (toIntermediateRep [1 :: Int])) - case HM.lookup "TestFunctions.constant" m of + case Map.lookup "TestFunctions.constant" m of Nothing -> assertBool "constant not found" False Just f -> do r <- f (toIntermediateRep ([] :: [Int])) From 53c78191721d277d5eeb3dea2540e617ac43a8bb Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 06:15:47 +0530 Subject: [PATCH 31/32] Use streamly-core Path instead of filepath in installOnRemote Take the directory of the remote path with Streamly.FileSystem.Path and drop the filepath dependency of the library. An empty path or one with a NUL character now raises InvalidPath before connecting. --- rpc/CHANGELOG.md | 3 +++ rpc/lib/Simple/RPC/Client.hs | 11 +++++++---- rpc/simple-rpc.cabal | 1 - 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/rpc/CHANGELOG.md b/rpc/CHANGELOG.md index 13d5497..6e9e812 100644 --- a/rpc/CHANGELOG.md +++ b/rpc/CHANGELOG.md @@ -30,6 +30,9 @@ The following behavior changes can break existing callers: directory. Before, the directory was made writable by all users and the file was owned by the ssh user. It needs `mktemp` and `install` on the remote host. +* `installOnRemote` raises an `InvalidPath` exception, before it connects + to the remote host, if the remote path is empty or has a NUL character. + Before, the remote command failed with a `ProcessFailure` exception. * The server sets the encoding of stdout to UTF-8, and writes `\n` line ends on all OSes. Before, it wrote `\r\n` on Windows. diff --git a/rpc/lib/Simple/RPC/Client.hs b/rpc/lib/Simple/RPC/Client.hs index 8c6da21..c9ca9b4 100644 --- a/rpc/lib/Simple/RPC/Client.hs +++ b/rpc/lib/Simple/RPC/Client.hs @@ -39,12 +39,12 @@ import Data.Function ((&)) import Data.Word (Word8) import Streamly.Data.Array (Array) import Streamly.Unicode.String (str) -import System.FilePath (takeDirectory) import qualified Data.IORef as IORef import qualified Streamly.Internal.Data.Array as Array (compactEndByLn_) import qualified Streamly.Data.Fold as Fold import qualified Streamly.Data.Stream as Stream +import qualified Streamly.FileSystem.Path as Path import qualified Streamly.System.Process as Proc import qualified Streamly.Unicode.Stream as Unicode @@ -290,8 +290,10 @@ run = direct -- run on the local host. Not supported on a Windows client or a Windows -- remote host. -- --- Raise a 'VersionMismatch' exception if the local executable prints a --- version other than 'executableVersion', and a +-- Raise an @InvalidPath@ exception, of type @PathException@ from +-- streamly-core, if @remotePath@ is empty or has a NUL character, a +-- 'VersionMismatch' exception if the local executable prints a version +-- other than 'executableVersion', and a -- 'Streamly.Internal.System.Process.ProcessFailure' exception if a command -- fails. -- @@ -301,7 +303,8 @@ run = direct installOnRemote :: Executable -> (String, String) -> FilePath -> IO () installOnRemote localExe sshConf@(addr, port) remoteExePath = do let exePath = executablePath localExe - remoteExeDir = takeDirectory remoteExePath + remotePath <- Path.fromString remoteExePath + let remoteExeDir = maybe "." Path.toString (Path.takeDirectory remotePath) versionGuard putStrLn Nothing localExe tmpOut <- uncurry Proc.toString $ sshCommand sshConf ("mktemp", []) let tmp = takeWhile (/= '\n') tmpOut diff --git a/rpc/simple-rpc.cabal b/rpc/simple-rpc.cabal index 18cc84d..f760be0 100644 --- a/rpc/simple-rpc.cabal +++ b/rpc/simple-rpc.cabal @@ -60,7 +60,6 @@ library , streamly-process , template-haskell , aeson - , filepath , containers hs-source-dirs: lib From d960620350a7b6e6ddd47ab9f4224e18873acca1 Mon Sep 17 00:00:00 2001 From: Harendra Kumar Date: Thu, 5 Nov 2026 10:33:30 +0530 Subject: [PATCH 32/32] Fix the test failures on GHC 9.8, Windows and with -Werror Accept both the show and the displayException forms of an exception on the server stderr; GHC before 9.10 prints show. Expect CRLF on the endpoint stderr on Windows. Replace the deprecated withMaxSuccess by a propertyN harness function that sets maxSuccess. --- rpc/test/Harness.hs | 15 ++++++++++----- rpc/test/Main.hs | 37 ++++++++++++++++++++++++++----------- 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/rpc/test/Harness.hs b/rpc/test/Harness.hs index cc99a36..27ee9a6 100644 --- a/rpc/test/Harness.hs +++ b/rpc/test/Harness.hs @@ -11,6 +11,7 @@ module Harness , assertBool , assertThrows , property + , propertyN ) where ------------------------------------------------------------------------------- @@ -78,20 +79,24 @@ assertThrows msg p action = do seedRef :: IORef Int seedRef = unsafePerformIO (newIORef 0) --- | Check a QuickCheck property with the seed given to 'runTests', raise a --- 'TestFailure' exception if it fails. -property :: Testable p => p -> IO () -property p = do +-- | @propertyN n p@ checks the QuickCheck property @p@ on @n@ inputs with +-- the seed given to 'runTests', raise a 'TestFailure' exception if it fails. +propertyN :: Testable p => Int -> p -> IO () +propertyN n p = do seed <- readIORef seedRef let args = stdArgs { replay = Just (mkQCGen seed, 0) , chatty = False - , maxSuccess = 100 + , maxSuccess = n } r :: Result <- QC.quickCheckWithResult args p unless (isSuccess r) $ throwIO $ TestFailure (QC.output r) +-- | Check a QuickCheck property on 100 inputs, see 'propertyN'. +property :: Testable p => p -> IO () +property = propertyN 100 + ------------------------------------------------------------------------------- -- Running ------------------------------------------------------------------------------- diff --git a/rpc/test/Main.hs b/rpc/test/Main.hs index 1fc4fc9..e6b1f84 100644 --- a/rpc/test/Main.hs +++ b/rpc/test/Main.hs @@ -26,7 +26,7 @@ import System.Info (os) import System.Process ( CreateProcess(std_in, std_out), StdStream(..), callProcess , createProcess, proc, readProcess, waitForProcess ) -import Test.QuickCheck (forAll, ioProperty, withMaxSuccess) +import Test.QuickCheck (forAll, ioProperty) import qualified Data.Aeson as Json import qualified Data.ByteString as BS @@ -60,17 +60,25 @@ loggingConfig env = do let cfg = serverConfig env & setLogger (\s -> modifyIORef ref (s:)) pure (cfg, reverse <$> readIORef ref) +-- | The messages that the top level exception handler may print for an +-- exception. GHC 9.10 and later print 'displayException', earlier versions +-- print 'show'. +exceptionMessages :: RpcException -> [String] +exceptionMessages e = [displayException e, show e] + -- | Check that the stderr of the server has the message of the exception. assertStderr :: BS.ByteString -> RpcException -> IO () assertStderr err e = assertBool ("stderr: " ++ show err) - (utf8 (displayException e) `BS.isInfixOf` err) + (any ((`BS.isInfixOf` err) . utf8) (exceptionMessages e)) --- | Check that the stderr of the server has an 'InvalidInput' message. +-- | Check that the stderr of the server has an 'InvalidInput' message, in +-- the 'displayException' or the 'show' form. assertInvalidInput :: BS.ByteString -> IO () assertInvalidInput err = assertBool ("stderr: " ++ show err) - (utf8 "Invalid RPC input: " `BS.isInfixOf` err) + (any ((`BS.isInfixOf` err) . utf8) + ["Invalid RPC input: ", "InvalidInput \""]) -- | Print-able ASCII characters and the control characters. asciiString :: QC.Gen String @@ -79,6 +87,10 @@ asciiString = QC.listOf (QC.choose ('\0', '\127')) isWindows :: Bool isWindows = os == "mingw32" +-- | The line end that a handle in text mode writes for a '\n'. +newline :: String +newline = if isWindows then "\r\n" else "\n" + -- | The permission bits of a file as shown by @ls -l@, e.g. @rwxr-xr-x@. -- Uses @sh@ for the same view of the file system as the fake ssh. lsMode :: FilePath -> IO String @@ -206,7 +218,9 @@ serverTests env = (BSC.pack "[SERVER] TestFunctions.printPartial [\"abc\"]\nabc\n\"abc\"") out - assertEqual "stderr" (BSC.pack "printPartial on stderr\n") err + -- The endpoint writes stderr in text mode, CRLF on Windows. + assertEqual "stderr" + (BSC.pack ("printPartial on stderr" ++ newline)) err , test "invokeFunction reads the input up to the first newline" $ do (code, out, _) <- @@ -329,9 +343,9 @@ clientTests env = , test "runAt round trips Int and ASCII String arguments" $ do let cfg = serverConfig env - property $ withMaxSuccess 20 $ \(x :: Int) -> + propertyN 20 $ \(x :: Int) -> ioProperty $ (== x) <$> runAt cfg echoInt x - property $ withMaxSuccess 20 $ forAll asciiString $ \s -> + propertyN 20 $ forAll asciiString $ \s -> ioProperty $ (== s) <$> runAt cfg echoString s , test "runAt returns the result after partial endpoint output" $ do @@ -351,7 +365,7 @@ clientTests env = assertBool ("STDOUT: " ++ show logged) (has (== "[STDOUT] \"abc\"")) assertBool ("STDERR: " ++ show logged) - (has (== "[STDERR] printPartial on stderr")) + (has (== "[STDERR] printPartial on stderr" ++ init newline)) , test "runAt raises ProcessFailure when the endpoint fails" $ assertThrows "failing" (\(ProcessFailure n) -> n == 1) @@ -381,10 +395,11 @@ clientTests env = (cfg & setImage (Executable path testVersion)) echoString (replicate 1000000 'x')) logged <- getLog - let msg = displayException (EndpointNotFound "TestFunctions.nope") + let msgs = exceptionMessages (EndpointNotFound "TestFunctions.nope") isErr l = "[STDERR]" `isPrefixOf` l + hasMsg l = any (`isInfixOf` l) msgs assertBool ("stderr logged: " ++ show (filter isErr logged)) - (any (\l -> isErr l && msg `isInfixOf` l) logged) + (any (\l -> isErr l && hasMsg l) logged) , test "runAt raises VersionMismatch on a version mismatch" $ assertThrows "version" @@ -676,7 +691,7 @@ unicodeTests env = , test "runAt round trips Unicode String arguments" $ do let cfg = serverConfig env - property $ withMaxSuccess 20 $ forAll genUnicodeString $ \s -> + propertyN 20 $ forAll genUnicodeString $ \s -> ioProperty $ (== s) <$> runAt cfg echoString s , test "runAt logs the input as UTF-8 decoded text" $ do