├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .mergify.yml ├── .sbtopts ├── .scalafmt.conf ├── LICENSE ├── README.md ├── build.sbt ├── devnotes.md ├── modules ├── core │ └── src │ │ ├── main │ │ └── scala │ │ │ └── jsonrpclib │ │ │ ├── CallId.scala │ │ │ ├── Channel.scala │ │ │ ├── Codec.scala │ │ │ ├── ConflictingMethodError.scala │ │ │ ├── Endpoint.scala │ │ │ ├── ErrorCodec.scala │ │ │ ├── ErrorPayload.scala │ │ │ ├── ErrorReport.scala │ │ │ ├── Message.scala │ │ │ ├── Monadic.scala │ │ │ ├── Payload.scala │ │ │ ├── ProtocolError.scala │ │ │ ├── StubTemplate.scala │ │ │ ├── internals │ │ │ ├── Constants.scala │ │ │ ├── FutureBaseChannel.scala │ │ │ ├── LSPHeaders.scala │ │ │ ├── MessageDispatcher.scala │ │ │ └── RawMessage.scala │ │ │ └── package.scala │ │ └── test │ │ ├── scala │ │ └── jsonrpclib │ │ │ ├── CallIdSpec.scala │ │ │ └── RawMessageSpec.scala │ │ └── scalajvm-native │ │ └── jsonrpclib │ │ └── internals │ │ └── HeaderSpec.scala ├── examples │ ├── client │ │ └── src │ │ │ └── main │ │ │ └── scala │ │ │ └── examples │ │ │ └── client │ │ │ └── ClientMain.scala │ └── server │ │ └── src │ │ └── main │ │ └── scala │ │ └── examples │ │ └── server │ │ └── ServerMain.scala └── fs2 │ └── src │ ├── main │ └── scala │ │ └── jsonrpclib │ │ └── fs2 │ │ ├── CancelTemplate.scala │ │ ├── FS2Channel.scala │ │ ├── lsp.scala │ │ └── package.scala │ └── test │ └── scala │ └── jsonrpclib │ └── fs2 │ └── FS2ChannelSpec.scala └── project ├── build.properties └── plugins.sbt /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | branches: ["*"] 6 | push: 7 | branches: ["main"] 8 | tags: ["v*"] 9 | 10 | concurrency: 11 | group: ci-${{ github.ref }} 12 | cancel-in-progress: true 13 | 14 | jobs: 15 | build: 16 | strategy: 17 | fail-fast: false 18 | runs-on: ubuntu-latest 19 | steps: 20 | - uses: actions/checkout@v3 21 | with: 22 | fetch-depth: 0 23 | 24 | - uses: actions/setup-java@v3 25 | with: 26 | distribution: "temurin" 27 | java-version: "21" 28 | cache: "sbt" 29 | 30 | - name: Setup sbt 31 | uses: sbt/setup-sbt@v1 32 | 33 | - name: Test 34 | run: sbt ci 35 | 36 | - name: Publish ${{ github.ref }} 37 | # todo: uncomment 38 | # if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || (github.ref == 'refs/heads/main')) 39 | run: sbt ci-release 40 | env: 41 | PGP_PASSPHRASE: ${{ secrets.PGP_PASSPHRASE }} 42 | PGP_SECRET: ${{ secrets.PGP_SECRET }} 43 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 44 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #mill 2 | out 3 | 4 | # sbt 5 | lib_managed 6 | project/project 7 | target 8 | 9 | # Eclipse 10 | .cache* 11 | .classpath 12 | .project 13 | .scala_dependencies 14 | .settings 15 | .target 16 | .worksheet 17 | 18 | # IntelliJ 19 | .idea 20 | .idea_modules 21 | *.iml 22 | 23 | # ENSIME 24 | .ensime 25 | .ensime_lucene 26 | .ensime_cache 27 | 28 | # Mac 29 | .DS_Store 30 | 31 | # Akka Persistence 32 | journal 33 | snapshots 34 | 35 | # Log files 36 | *.log 37 | 38 | #Floobits 39 | .floo 40 | 41 | # Local Dynamo DB 42 | dynamodb_lib 43 | *.db 44 | 45 | # Node 46 | node_modules 47 | website/translated_docs 48 | website/build/ 49 | website/yarn.lock 50 | website/node_modules 51 | website/i18n/* 52 | 53 | .bloop 54 | .vscode 55 | .history 56 | .metals 57 | project/metals.sbt 58 | .ammonite 59 | 60 | # Version file 61 | version 62 | 63 | # BSP files 64 | .bsp 65 | 66 | .direnv 67 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: automatically merge scala-steward's PRs 3 | conditions: 4 | - author=neanderward[bot] 5 | - or: 6 | - body~=labels:.*semver-patch.* 7 | - body~=labels:.*semver-spec-patch.* 8 | - check-success=build 9 | actions: 10 | merge: 11 | method: merge -------------------------------------------------------------------------------- /.sbtopts: -------------------------------------------------------------------------------- 1 | -J-Xmx6g 2 | -------------------------------------------------------------------------------- /.scalafmt.conf: -------------------------------------------------------------------------------- 1 | version = "3.8.0" 2 | runner.dialect = scala213 3 | maxColumn = 120 4 | fileOverride { 5 | "glob:**/fs2/src/**" { 6 | runner.dialect = scala213source3 7 | } 8 | "glob:**/fs2/test/src/**" { 9 | runner.dialect = scala213source3 10 | } 11 | "glob:**/core/test/src-jvm-native/**" { 12 | runner.dialect = scala213source3 13 | } 14 | "glob:**/core/src/**" { 15 | runner.dialect = scala213source3 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CI](https://github.com/neandertech/jsonrpclib/actions/workflows/ci.yml/badge.svg)](https://github.com/neandertech/jsonrpclib/actions/workflows/ci.yml) 2 | 3 | [![jsonrpclib-fs2 Scala version support](https://index.scala-lang.org/neandertech/jsonrpclib/jsonrpclib-fs2/latest-by-scala-version.svg?platform=jvm)](https://index.scala-lang.org/neandertech/jsonrpclib/jsonrpclib-fs2) 4 | 5 | [![jsonrpclib-fs2 Scala version support](https://index.scala-lang.org/neandertech/jsonrpclib/jsonrpclib-fs2/latest-by-scala-version.svg?platform=sjs1)](https://index.scala-lang.org/neandertech/jsonrpclib/jsonrpclib-fs2) 6 | 7 | 8 | # jsonrpclib 9 | 10 | This is a cross-platform, cross-scala-version library that provides construct for bidirectional communication using the [jsonrpc](https://www.jsonrpc.org/) protocol. It is built on top of [fs2](https://fs2.io/#/) and [jsoniter-scala](https://github.com/plokhotnyuk/jsoniter-scala) 11 | 12 | This library does not enforce any transport, and can work on top of stdin/stdout or other channels. 13 | 14 | ## Installation 15 | 16 | The dependencies below are following [cross-platform semantics](http://youforgotapercentagesignoracolon.com/). 17 | Adapt according to your needs 18 | 19 | ### SBT 20 | 21 | ```scala 22 | libraryDependencies += "tech.neander" %%% "jsonrpclib-fs2" % version 23 | ``` 24 | 25 | ### Mill 26 | 27 | ```scala 28 | override def ivyDeps = super.ivyDeps() ++ Agg(ivy"tech.neander::jsonrpclib-fs2::$version") 29 | ``` 30 | 31 | ### Scala-cli 32 | 33 | ```scala 34 | //> using lib "tech.neander::jsonrpclib-fs2:" 35 | ``` 36 | 37 | ## Usage 38 | 39 | **/!\ Please be aware that this library is in its early days and offers strictly no guarantee with regards to backward compatibility** 40 | 41 | See the modules/examples folder. 42 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | import org.typelevel.sbt.tpolecat.DevMode 2 | import org.typelevel.sbt.tpolecat.OptionsMode 3 | import java.net.URI 4 | 5 | inThisBuild( 6 | List( 7 | organization := "tech.neander", 8 | homepage := Some(url("https://github.com/neandertech/jsonrpclib")), 9 | licenses := List(License.Apache2), 10 | developers := List( 11 | Developer("Baccata", "Olivier Mélois", "baccata64@gmail.com", URI.create("https://github.com/baccata").toURL) 12 | ), 13 | sonatypeCredentialHost := "s01.oss.sonatype.org", 14 | sonatypeRepository := "https://s01.oss.sonatype.org/service/local" 15 | ) 16 | ) 17 | 18 | val scala213 = "2.13.16" 19 | val scala3 = "3.3.5" 20 | val allScalaVersions = List(scala213, scala3) 21 | val jvmScalaVersions = allScalaVersions 22 | val jsScalaVersions = allScalaVersions 23 | val nativeScalaVersions = allScalaVersions 24 | 25 | val fs2Version = "3.12.0" 26 | 27 | ThisBuild / tpolecatOptionsMode := DevMode 28 | 29 | val commonSettings = Seq( 30 | libraryDependencies ++= Seq( 31 | "com.disneystreaming" %%% "weaver-cats" % "0.8.4" % Test 32 | ), 33 | mimaPreviousArtifacts := Set( 34 | organization.value %%% name.value % "0.0.7" 35 | ), 36 | scalacOptions += "-java-output-version:8" 37 | ) 38 | 39 | val core = projectMatrix 40 | .in(file("modules") / "core") 41 | .jvmPlatform( 42 | jvmScalaVersions, 43 | Test / unmanagedSourceDirectories ++= Seq( 44 | (projectMatrixBaseDirectory.value / "src" / "test" / "scalajvm-native").getAbsoluteFile 45 | ) 46 | ) 47 | .jsPlatform(jsScalaVersions) 48 | .nativePlatform( 49 | nativeScalaVersions, 50 | Test / unmanagedSourceDirectories ++= Seq( 51 | (projectMatrixBaseDirectory.value / "src" / "test" / "scalajvm-native").getAbsoluteFile 52 | ) 53 | ) 54 | .disablePlugins(AssemblyPlugin) 55 | .settings( 56 | name := "jsonrpclib-core", 57 | commonSettings, 58 | libraryDependencies ++= Seq( 59 | "com.github.plokhotnyuk.jsoniter-scala" %%% "jsoniter-scala-macros" % "2.30.2" 60 | ) 61 | ) 62 | 63 | val fs2 = projectMatrix 64 | .in(file("modules") / "fs2") 65 | .jvmPlatform(jvmScalaVersions) 66 | .jsPlatform(jsScalaVersions) 67 | .nativePlatform(nativeScalaVersions) 68 | .disablePlugins(AssemblyPlugin) 69 | .dependsOn(core) 70 | .settings( 71 | name := "jsonrpclib-fs2", 72 | commonSettings, 73 | libraryDependencies ++= Seq( 74 | "co.fs2" %%% "fs2-core" % fs2Version 75 | ) 76 | ) 77 | 78 | val exampleServer = projectMatrix 79 | .in(file("modules") / "examples/server") 80 | .jvmPlatform(List(scala213)) 81 | .dependsOn(fs2) 82 | .settings( 83 | commonSettings, 84 | publish / skip := true, 85 | libraryDependencies ++= Seq( 86 | "co.fs2" %%% "fs2-io" % fs2Version 87 | ) 88 | ) 89 | .disablePlugins(MimaPlugin) 90 | 91 | val exampleClient = projectMatrix 92 | .in(file("modules") / "examples/client") 93 | .jvmPlatform( 94 | List(scala213), 95 | Seq( 96 | fork := true, 97 | envVars += "SERVER_JAR" -> (exampleServer.jvm(scala213) / assembly).value.toString 98 | ) 99 | ) 100 | .disablePlugins(AssemblyPlugin) 101 | .dependsOn(fs2) 102 | .settings( 103 | commonSettings, 104 | publish / skip := true, 105 | libraryDependencies ++= Seq( 106 | "co.fs2" %%% "fs2-io" % fs2Version 107 | ) 108 | ) 109 | .disablePlugins(MimaPlugin) 110 | 111 | val root = project 112 | .in(file(".")) 113 | .settings( 114 | publish / skip := true 115 | ) 116 | .disablePlugins(MimaPlugin, AssemblyPlugin) 117 | .aggregate(List(core, fs2, exampleServer, exampleClient).flatMap(_.projectRefs): _*) 118 | 119 | // The core compiles are a workaround for https://github.com/plokhotnyuk/jsoniter-scala/issues/564 120 | // when we switch to SN 0.5, we can use `makeWithSkipNestedOptionValues` instead: https://github.com/plokhotnyuk/jsoniter-scala/issues/564#issuecomment-2787096068 121 | val compileCoreModules = { 122 | for { 123 | scalaVersionSuffix <- List("", "3") 124 | platformSuffix <- List("", "JS", "Native") 125 | task <- List("compile", "package") 126 | } yield s"core$platformSuffix$scalaVersionSuffix/$task" 127 | }.mkString(";") 128 | 129 | addCommandAlias( 130 | "ci", 131 | s"$compileCoreModules;test;scalafmtCheckAll;mimaReportBinaryIssues" 132 | ) 133 | -------------------------------------------------------------------------------- /devnotes.md: -------------------------------------------------------------------------------- 1 | # Dev Notes 2 | 3 | In case somebody wants to implement future-based channels, here are some source of inspiration : 4 | 5 | ### Scala-native 6 | 7 | See 8 | * https://github.com/scala-native/scala-native/blob/63d07093f6d0a6e9de28cd8f9fb6bc1d6596c6ec/test-interface/src/main/scala/scala/scalanative/testinterface/NativeRPC.scala 9 | 10 | 11 | ### Scala-js 12 | 13 | See 14 | * https://github.com/scala-js/scala-js-js-envs/blob/main/nodejs-env/src/main/scala/org/scalajs/jsenv/nodejs/ComSupport.scala#L245 15 | * https://github.com/scala-js/scala-js/blob/0708917912938714d52be1426364f78a3d1fd269/test-bridge/src/main/scala/org/scalajs/testing/bridge/JSRPC.scala 16 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/CallId.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import com.github.plokhotnyuk.jsoniter_scala.core._ 4 | import scala.annotation.switch 5 | 6 | sealed trait CallId 7 | object CallId { 8 | final case class NumberId(long: Long) extends CallId 9 | final case class StringId(string: String) extends CallId 10 | case object NullId extends CallId 11 | 12 | implicit val callIdRW: JsonValueCodec[CallId] = new JsonValueCodec[CallId] { 13 | def decodeValue(in: JsonReader, default: CallId): CallId = { 14 | val nt = in.nextToken() 15 | 16 | (nt: @switch) match { 17 | case 'n' => in.readNullOrError(default, "expected null") 18 | case '"' => in.rollbackToken(); StringId(in.readString(null)) 19 | case _ => in.rollbackToken(); NumberId(in.readLong()) 20 | 21 | } 22 | } 23 | 24 | def encodeValue(x: CallId, out: JsonWriter): Unit = x match { 25 | case NumberId(long) => out.writeVal(long) 26 | case StringId(string) => out.writeVal(string) 27 | case NullId => out.writeNull() 28 | } 29 | 30 | def nullValue: CallId = CallId.NullId 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/Channel.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | trait Channel[F[_]] { 4 | def mountEndpoint(endpoint: Endpoint[F]): F[Unit] 5 | def unmountEndpoint(method: String): F[Unit] 6 | 7 | def notificationStub[In: Codec](method: String): In => F[Unit] 8 | def simpleStub[In: Codec, Out: Codec](method: String): In => F[Out] 9 | def stub[In: Codec, Err: ErrorCodec, Out: Codec](method: String): In => F[Either[Err, Out]] 10 | def stub[In, Err, Out](template: StubTemplate[In, Err, Out]): In => F[Either[Err, Out]] 11 | } 12 | 13 | object Channel { 14 | 15 | protected[jsonrpclib] abstract class MonadicChannel[F[_]](implicit F: Monadic[F]) extends Channel[F] { 16 | 17 | final def stub[In, Err, Out](template: StubTemplate[In, Err, Out]): In => F[Either[Err, Out]] = 18 | template match { 19 | case StubTemplate.RequestResponseTemplate(method, inCodec, errCodec, outCodec) => 20 | stub(method)(inCodec, errCodec, outCodec) 21 | case nt: StubTemplate.NotificationTemplate[in] => 22 | val method = nt.method 23 | val inCodec = nt.inCodec 24 | val stub = notificationStub(method)(inCodec) 25 | (in: In) => F.doFlatMap(stub(in))(unit => F.doPure(Right(unit))) 26 | } 27 | 28 | final def simpleStub[In: Codec, Out: Codec](method: String): In => F[Out] = { 29 | val s = stub[In, ErrorPayload, Out](method) 30 | (in: In) => 31 | F.doFlatMap(s(in)) { 32 | case Left(e) => F.doRaiseError(e) 33 | case Right(a) => F.doPure(a) 34 | } 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/Codec.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import com.github.plokhotnyuk.jsoniter_scala.core._ 4 | 5 | trait Codec[A] { 6 | 7 | def encode(a: A): Payload 8 | def decode(payload: Option[Payload]): Either[ProtocolError, A] 9 | 10 | } 11 | 12 | object Codec { 13 | 14 | def encode[A](a: A)(implicit codec: Codec[A]): Payload = codec.encode(a) 15 | def decode[A](payload: Option[Payload])(implicit codec: Codec[A]): Either[ProtocolError, A] = codec.decode(payload) 16 | 17 | implicit def fromJsonCodec[A](implicit jsonCodec: JsonValueCodec[A]): Codec[A] = new Codec[A] { 18 | def encode(a: A): Payload = { 19 | Payload(writeToArray(a)) 20 | } 21 | 22 | def decode(payload: Option[Payload]): Either[ProtocolError, A] = { 23 | try { 24 | payload match { 25 | case Some(Payload.Data(payload)) => Right(readFromArray(payload)) 26 | case Some(Payload.NullPayload) => Right(readFromArray(nullArray)) 27 | case None => Left(ProtocolError.ParseError("Expected to decode a payload")) 28 | } 29 | } catch { case e: JsonReaderException => Left(ProtocolError.ParseError(e.getMessage())) } 30 | } 31 | } 32 | 33 | private val nullArray = "null".getBytes() 34 | 35 | } 36 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/ConflictingMethodError.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | final case class ConflictingMethodError(name: String) extends Exception { 4 | override def getMessage(): String = s"Method $name is already handled" 5 | } 6 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/Endpoint.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | sealed trait Endpoint[F[_]] { 4 | def method: String 5 | } 6 | 7 | object Endpoint { 8 | 9 | type MethodPattern = String 10 | type Method = String 11 | 12 | def apply[F[_]](method: Method): PartiallyAppliedEndpoint[F] = new PartiallyAppliedEndpoint[F](method) 13 | 14 | class PartiallyAppliedEndpoint[F[_]](method: MethodPattern) { 15 | def apply[In, Err, Out]( 16 | run: In => F[Either[Err, Out]] 17 | )(implicit inCodec: Codec[In], errCodec: ErrorCodec[Err], outCodec: Codec[Out]): Endpoint[F] = 18 | RequestResponseEndpoint(method, (_: InputMessage, in: In) => run(in), inCodec, errCodec, outCodec) 19 | 20 | def full[In, Err, Out]( 21 | run: (InputMessage, In) => F[Either[Err, Out]] 22 | )(implicit inCodec: Codec[In], errCodec: ErrorCodec[Err], outCodec: Codec[Out]): Endpoint[F] = 23 | RequestResponseEndpoint(method, run, inCodec, errCodec, outCodec) 24 | 25 | def simple[In, Out]( 26 | run: In => F[Out] 27 | )(implicit F: Monadic[F], inCodec: Codec[In], outCodec: Codec[Out]) = 28 | apply[In, ErrorPayload, Out](in => 29 | F.doFlatMap(F.doAttempt(run(in))) { 30 | case Left(error) => F.doPure(Left(ErrorPayload(0, error.getMessage(), None))) 31 | case Right(value) => F.doPure(Right(value)) 32 | } 33 | ) 34 | 35 | def notification[In](run: In => F[Unit])(implicit inCodec: Codec[In]): Endpoint[F] = 36 | NotificationEndpoint(method, (_: InputMessage, in: In) => run(in), inCodec) 37 | 38 | def notificationFull[In](run: (InputMessage, In) => F[Unit])(implicit inCodec: Codec[In]): Endpoint[F] = 39 | NotificationEndpoint(method, run, inCodec) 40 | 41 | } 42 | 43 | final case class NotificationEndpoint[F[_], In]( 44 | method: MethodPattern, 45 | run: (InputMessage, In) => F[Unit], 46 | inCodec: Codec[In] 47 | ) extends Endpoint[F] 48 | 49 | final case class RequestResponseEndpoint[F[_], In, Err, Out]( 50 | method: Method, 51 | run: (InputMessage, In) => F[Either[Err, Out]], 52 | inCodec: Codec[In], 53 | errCodec: ErrorCodec[Err], 54 | outCodec: Codec[Out] 55 | ) extends Endpoint[F] 56 | 57 | } 58 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/ErrorCodec.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | trait ErrorCodec[E] { 4 | 5 | def encode(a: E): ErrorPayload 6 | def decode(error: ErrorPayload): Either[ProtocolError, E] 7 | 8 | } 9 | 10 | object ErrorCodec { 11 | implicit val errorPayloadCodec: ErrorCodec[ErrorPayload] = new ErrorCodec[ErrorPayload] { 12 | def encode(a: ErrorPayload): ErrorPayload = a 13 | def decode(error: ErrorPayload): Either[ProtocolError, ErrorPayload] = Right(error) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/ErrorPayload.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec 4 | import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker 5 | 6 | case class ErrorPayload(code: Int, message: String, data: Option[Payload]) extends Throwable { 7 | override def getMessage(): String = s"JsonRPC Error $code: $message" 8 | } 9 | 10 | object ErrorPayload { 11 | 12 | implicit val rawMessageStubJsonValueCodecs: JsonValueCodec[ErrorPayload] = 13 | JsonCodecMaker.make 14 | 15 | } 16 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/ErrorReport.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | /** Errors that should not be sent back through the json rpc channel (such as invalid notifications) 4 | */ 5 | case class ErrorReport(method: String, payload: Payload, error: ProtocolError) 6 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/Message.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonReader 4 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec 5 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonWriter 6 | 7 | sealed trait Message { def maybeCallId: Option[CallId] } 8 | sealed trait InputMessage extends Message { def method: String } 9 | sealed trait OutputMessage extends Message { 10 | def callId: CallId; final override def maybeCallId: Option[CallId] = Some(callId) 11 | } 12 | 13 | object InputMessage { 14 | case class RequestMessage(method: String, callId: CallId, params: Option[Payload]) extends InputMessage { 15 | def maybeCallId: Option[CallId] = Some(callId) 16 | } 17 | case class NotificationMessage(method: String, params: Option[Payload]) extends InputMessage { 18 | def maybeCallId: Option[CallId] = None 19 | } 20 | } 21 | object OutputMessage { 22 | def errorFrom(callId: CallId, protocolError: ProtocolError): OutputMessage = 23 | ErrorMessage(callId, ErrorPayload(protocolError.code, protocolError.getMessage(), None)) 24 | 25 | case class ErrorMessage(callId: CallId, payload: ErrorPayload) extends OutputMessage 26 | case class ResponseMessage(callId: CallId, data: Payload) extends OutputMessage 27 | } 28 | 29 | object Message { 30 | 31 | implicit val messageJsonValueCodecs: JsonValueCodec[Message] = new JsonValueCodec[Message] { 32 | val rawMessageCodec = implicitly[JsonValueCodec[internals.RawMessage]] 33 | def decodeValue(in: JsonReader, default: Message): Message = 34 | rawMessageCodec.decodeValue(in, null).toMessage match { 35 | case Left(error) => throw error 36 | case Right(value) => value 37 | } 38 | def encodeValue(x: Message, out: JsonWriter): Unit = 39 | rawMessageCodec.encodeValue(internals.RawMessage.from(x), out) 40 | def nullValue: Message = null 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/Monadic.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import scala.concurrent.Future 4 | import scala.concurrent.ExecutionContext 5 | 6 | trait Monadic[F[_]] { 7 | def doFlatMap[A, B](fa: F[A])(f: A => F[B]): F[B] 8 | def doPure[A](a: A): F[A] 9 | def doAttempt[A](fa: F[A]): F[Either[Throwable, A]] 10 | def doRaiseError[A](e: Throwable): F[A] 11 | } 12 | 13 | object Monadic { 14 | implicit def monadicFuture(implicit ec: ExecutionContext): Monadic[Future] = new Monadic[Future] { 15 | def doFlatMap[A, B](fa: Future[A])(f: A => Future[B]): Future[B] = fa.flatMap(f) 16 | 17 | def doPure[A](a: A): Future[A] = Future.successful(a) 18 | 19 | def doAttempt[A](fa: Future[A]): Future[Either[Throwable, A]] = fa.map(Right(_)).recover(Left(_)) 20 | 21 | def doRaiseError[A](e: Throwable): Future[A] = Future.failed(e) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/Payload.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonReader 4 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec 5 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonWriter 6 | 7 | import java.util.Base64 8 | import jsonrpclib.Payload.Data 9 | import jsonrpclib.Payload.NullPayload 10 | 11 | sealed trait Payload extends Product with Serializable { 12 | def stripNull: Option[Payload.Data] = this match { 13 | case d @ Data(_) => Some(d) 14 | case NullPayload => None 15 | } 16 | } 17 | 18 | object Payload { 19 | def apply(value: Array[Byte]) = { 20 | if (value == null) NullPayload 21 | else Data(value) 22 | } 23 | final case class Data(array: Array[Byte]) extends Payload { 24 | override def equals(other: Any) = other match { 25 | case bytes: Data => java.util.Arrays.equals(array, bytes.array) 26 | case _ => false 27 | } 28 | 29 | override lazy val hashCode: Int = java.util.Arrays.hashCode(array) 30 | 31 | override def toString = Base64.getEncoder.encodeToString(array) 32 | } 33 | 34 | case object NullPayload extends Payload 35 | 36 | implicit val payloadJsonValueCodec: JsonValueCodec[Payload] = new JsonValueCodec[Payload] { 37 | def decodeValue(in: JsonReader, default: Payload): Payload = { 38 | Data(in.readRawValAsBytes()) 39 | } 40 | 41 | def encodeValue(bytes: Payload, out: JsonWriter): Unit = 42 | bytes match { 43 | case Data(array) => out.writeRawVal(array) 44 | case NullPayload => out.writeNull() 45 | 46 | } 47 | 48 | def nullValue: Payload = null 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/ProtocolError.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | sealed abstract class ProtocolError(val code: Int, message: String) extends Throwable { 4 | override def getMessage(): String = message 5 | } 6 | 7 | object ProtocolError { 8 | final case class ParseError(message: String) extends ProtocolError(-32700, message) 9 | final case class InvalidRequest(message: String) extends ProtocolError(-32600, message) 10 | final case class MethodNotFound(method: String) extends ProtocolError(-32601, s"Method $method not found") 11 | final case class InvalidParams(message: String) extends ProtocolError(-32602, message) 12 | final case class InternalError(message: String) extends ProtocolError(-32603, message) 13 | final case class ServerError(override val code: Int, message: String) extends ProtocolError(code, message) 14 | } 15 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/StubTemplate.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | sealed trait StubTemplate[In, Err, Out] 4 | object StubTemplate { 5 | def notification[In](method: String)(implicit inCodec: Codec[In]): StubTemplate[In, Nothing, Unit] = 6 | NotificationTemplate[In](method, inCodec) 7 | 8 | def simple[In, Out]( 9 | method: String 10 | )(implicit inCodec: Codec[In], outCodec: Codec[Out]): StubTemplate[In, ErrorPayload, Out] = 11 | RequestResponseTemplate[In, ErrorPayload, Out](method, inCodec, ErrorCodec.errorPayloadCodec, outCodec) 12 | 13 | final case class NotificationTemplate[In]( 14 | method: String, 15 | inCodec: Codec[In] 16 | ) extends StubTemplate[In, Nothing, Unit] 17 | 18 | final case class RequestResponseTemplate[In, Err, Out]( 19 | method: String, 20 | inCodec: Codec[In], 21 | errCodec: ErrorCodec[Err], 22 | outCodec: Codec[Out] 23 | ) extends StubTemplate[In, Err, Out] 24 | } 25 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/internals/Constants.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib.internals 2 | 3 | private[jsonrpclib] object Constants { 4 | 5 | val JSONRPC_VERSION: String = "2.0" 6 | val CONTENT_LENGTH_HEADER: String = "Content-Length" 7 | val CONTENT_TYPE_HEADER: String = "Content-Type" 8 | val JSON_MIME_TYPE: String = "application/json" 9 | val CRLF: String = "\r\n" 10 | 11 | } 12 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/internals/FutureBaseChannel.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import jsonrpclib.internals._ 4 | 5 | import java.util.concurrent.atomic.AtomicLong 6 | import scala.concurrent.ExecutionContext 7 | import scala.concurrent.Future 8 | import scala.concurrent.Promise 9 | import scala.util.Try 10 | 11 | abstract class FutureBasedChannel(endpoints: List[Endpoint[Future]])(implicit ec: ExecutionContext) 12 | extends MessageDispatcher[Future] { 13 | 14 | override def createPromise[A](callId: CallId): Future[(Try[A] => Future[Unit], () => Future[A])] = Future.successful { 15 | val promise = Promise[A]() 16 | val fulfill: Try[A] => Future[Unit] = (a: Try[A]) => Future.successful(promise.complete(a)) 17 | val future: () => Future[A] = () => promise.future 18 | (fulfill, future) 19 | } 20 | 21 | protected def storePendingCall(callId: CallId, handle: OutputMessage => Future[Unit]): Future[Unit] = 22 | Future.successful { val _ = pending.put(callId, handle) } 23 | protected def removePendingCall(callId: CallId): Future[Option[OutputMessage => Future[Unit]]] = 24 | Future.successful { Option(pending.remove(callId)) } 25 | protected def getEndpoint(method: String): Future[Option[Endpoint[Future]]] = 26 | Future.successful(endpointsMap.get(method)) 27 | protected def sendMessage(message: Message): Future[Unit] = { 28 | sendPayload(Codec.encode(message)).map(_ => ()) 29 | } 30 | protected def nextCallId(): Future[CallId] = Future.successful(CallId.NumberId(nextID.incrementAndGet())) 31 | 32 | private[this] val endpointsMap: Map[String, Endpoint[Future]] = endpoints.map(ep => ep.method -> ep).toMap 33 | private[this] val pending = new java.util.concurrent.ConcurrentHashMap[CallId, OutputMessage => Future[Unit]] 34 | private[this] val nextID = new AtomicLong(0L) 35 | // @volatile 36 | // private[this] var closeReason: Throwable = _ 37 | 38 | def sendPayload(msg: Payload): Future[Unit] = ??? 39 | def reportError(params: Option[Payload], error: ProtocolError, method: String): Future[Unit] = ??? 40 | 41 | } 42 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/internals/LSPHeaders.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | package internals 3 | 4 | import java.io.InputStream 5 | import java.io.OutputStream 6 | import java.nio.charset.StandardCharsets 7 | 8 | // Content-Length: ...\r\n 9 | // \r\n 10 | private[jsonrpclib] final case class LSPHeaders(contentLength: Int, mimeType: String, charset: String) 11 | 12 | private[jsonrpclib] object LSPHeaders { 13 | 14 | def readNext(input: InputStream): Either[ProtocolError.ParseError, LSPHeaders] = { 15 | var keepRunning = true 16 | var newline = false 17 | var headerStringBuilder: StringBuilder = null 18 | val headerBuilder = new Builder( 19 | contentLength = -1, 20 | mimeType = Constants.JSON_MIME_TYPE, 21 | charset = StandardCharsets.UTF_8.displayName() 22 | ) 23 | var result: Either[ProtocolError.ParseError, LSPHeaders] = null 24 | while (keepRunning) { 25 | val c = input.read() 26 | if (c == -1) { 27 | keepRunning = false 28 | } else if (c == '\n') { 29 | if (newline) { 30 | // two consecutive newlines have been read, which signals the starts of the message content 31 | if (headerBuilder.contentLength < 0) { 32 | result = Left(ProtocolError.ParseError(s"Missing ${Constants.CONTENT_LENGTH_HEADER} header")) 33 | } else { 34 | result = Right(LSPHeaders(headerBuilder.contentLength, headerBuilder.mimeType, headerBuilder.charset)) 35 | } 36 | keepRunning = false 37 | } else if (headerStringBuilder != null) { 38 | parseHeader(headerStringBuilder.result(), headerBuilder) 39 | headerStringBuilder = null 40 | } 41 | newline = true 42 | } else if (c != '\r') { 43 | // Add the input to the current header line 44 | if (headerStringBuilder == null) { 45 | headerStringBuilder = new StringBuilder() 46 | } 47 | headerStringBuilder.append(c.toChar) 48 | newline = false; 49 | } 50 | } 51 | if (result == null) { 52 | Left(ProtocolError.ParseError("Could not parse LSP headers")) 53 | } else result 54 | } 55 | 56 | def write(x: LSPHeaders, out: OutputStream): Unit = { 57 | val dataOutputStream = new java.io.DataOutputStream(out) 58 | dataOutputStream.write(s"Content-Length: ${x.contentLength}\r\n".getBytes()) 59 | dataOutputStream.write("\r\n".getBytes()) 60 | } 61 | 62 | private class Builder(var contentLength: Int, var mimeType: String, var charset: String) 63 | 64 | private def parseHeader(line: String, headerBuilder: Builder): Unit = line match { 65 | case s"Content-Length: ${integer(length)}" => headerBuilder.contentLength = length 66 | case s"Content-type: ${mimeType}; charset=${charset}" => 67 | headerBuilder.mimeType = mimeType; 68 | headerBuilder.charset = charset 69 | case _ => sys.error(s"Invalid header: $line") 70 | } 71 | 72 | object integer { 73 | def unapply(string: String): Option[Int] = try { Some(string.toInt) } 74 | catch { case _: Throwable => None } 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/internals/MessageDispatcher.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | package internals 3 | 4 | import jsonrpclib.Endpoint.NotificationEndpoint 5 | import jsonrpclib.Endpoint.RequestResponseEndpoint 6 | import jsonrpclib.OutputMessage.ErrorMessage 7 | import jsonrpclib.OutputMessage.ResponseMessage 8 | import scala.util.Try 9 | 10 | private[jsonrpclib] abstract class MessageDispatcher[F[_]](implicit F: Monadic[F]) extends Channel.MonadicChannel[F] { 11 | 12 | import F._ 13 | 14 | protected def background[A](maybeCallId: Option[CallId], fa: F[A]): F[Unit] 15 | protected def reportError(params: Option[Payload], error: ProtocolError, method: String): F[Unit] 16 | protected def getEndpoint(method: String): F[Option[Endpoint[F]]] 17 | protected def sendMessage(message: Message): F[Unit] 18 | protected def nextCallId(): F[CallId] 19 | protected def createPromise[A](callId: CallId): F[(Try[A] => F[Unit], () => F[A])] 20 | protected def storePendingCall(callId: CallId, handle: OutputMessage => F[Unit]): F[Unit] 21 | protected def removePendingCall(callId: CallId): F[Option[OutputMessage => F[Unit]]] 22 | 23 | def notificationStub[In](method: String)(implicit inCodec: Codec[In]): In => F[Unit] = { (input: In) => 24 | val encoded = inCodec.encode(input) 25 | val message = InputMessage.NotificationMessage(method, Some(encoded)) 26 | sendMessage(message) 27 | } 28 | 29 | def stub[In, Err, Out]( 30 | method: String 31 | )(implicit inCodec: Codec[In], errCodec: ErrorCodec[Err], outCodec: Codec[Out]): In => F[Either[Err, Out]] = { 32 | (input: In) => 33 | val encoded = inCodec.encode(input) 34 | doFlatMap(nextCallId()) { callId => 35 | val message = InputMessage.RequestMessage(method, callId, Some(encoded)) 36 | doFlatMap(createPromise[Either[Err, Out]](callId)) { case (fulfill, future) => 37 | val pc = createPendingCall(errCodec, outCodec, fulfill) 38 | doFlatMap(storePendingCall(callId, pc))(_ => doFlatMap(sendMessage(message))(_ => future())) 39 | } 40 | } 41 | } 42 | 43 | protected[jsonrpclib] def handleReceivedMessage(message: Message): F[Unit] = { 44 | message match { 45 | case im: InputMessage => 46 | doFlatMap(getEndpoint(im.method)) { 47 | case Some(ep) => background(im.maybeCallId, executeInputMessage(im, ep)) 48 | case None => 49 | im.maybeCallId match { 50 | case None => 51 | // notification : do nothing 52 | doPure(()) 53 | case Some(callId) => 54 | val error = ProtocolError.MethodNotFound(im.method) 55 | sendProtocolError(callId, error) 56 | } 57 | } 58 | case om: OutputMessage => 59 | doFlatMap(removePendingCall(om.callId)) { 60 | case Some(pendingCall) => pendingCall(om) 61 | case None => doPure(()) // TODO do something 62 | } 63 | } 64 | } 65 | 66 | protected def sendProtocolError(callId: CallId, pError: ProtocolError): F[Unit] = 67 | sendMessage(OutputMessage.errorFrom(callId, pError)) 68 | protected def sendProtocolError(pError: ProtocolError): F[Unit] = 69 | sendProtocolError(CallId.NullId, pError) 70 | 71 | private def executeInputMessage(input: InputMessage, endpoint: Endpoint[F]): F[Unit] = { 72 | (input, endpoint) match { 73 | case (InputMessage.NotificationMessage(_, params), ep: NotificationEndpoint[F, in]) => 74 | ep.inCodec.decode(params) match { 75 | case Right(value) => ep.run(input, value) 76 | case Left(value) => reportError(params, value, ep.method) 77 | } 78 | case (InputMessage.RequestMessage(_, callId, params), ep: RequestResponseEndpoint[F, in, err, out]) => 79 | ep.inCodec.decode(params) match { 80 | case Right(value) => 81 | doFlatMap(ep.run(input, value)) { 82 | case Right(data) => 83 | val responseData = ep.outCodec.encode(data) 84 | sendMessage(OutputMessage.ResponseMessage(callId, responseData)) 85 | case Left(error) => 86 | val errorPayload = ep.errCodec.encode(error) 87 | sendMessage(OutputMessage.ErrorMessage(callId, errorPayload)) 88 | } 89 | case Left(pError) => 90 | sendProtocolError(callId, pError) 91 | } 92 | case (InputMessage.NotificationMessage(_, _), ep: RequestResponseEndpoint[F, in, err, out]) => 93 | val message = s"This ${ep.method} endpoint cannot process notifications, request is missing callId" 94 | val pError = ProtocolError.InvalidRequest(message) 95 | sendProtocolError(pError) 96 | case (InputMessage.RequestMessage(_, _, _), ep: NotificationEndpoint[F, in]) => 97 | val message = s"This ${ep.method} endpoint expects notifications and cannot return a result" 98 | val pError = ProtocolError.InvalidRequest(message) 99 | sendProtocolError(pError) 100 | } 101 | } 102 | 103 | private def createPendingCall[Err, Out]( 104 | errCodec: ErrorCodec[Err], 105 | outCodec: Codec[Out], 106 | fulfill: Try[Either[Err, Out]] => F[Unit] 107 | ): OutputMessage => F[Unit] = { (message: OutputMessage) => 108 | message match { 109 | case ErrorMessage(_, errorPayload) => 110 | errCodec.decode(errorPayload) match { 111 | case Left(_) => fulfill(scala.util.Failure(errorPayload)) 112 | case Right(value) => fulfill(scala.util.Success(Left(value))) 113 | } 114 | case ResponseMessage(_, data) => 115 | outCodec.decode(Some(data)) match { 116 | case Left(decodeError) => fulfill(scala.util.Failure(decodeError)) 117 | case Right(value) => fulfill(scala.util.Success(Right(value))) 118 | } 119 | } 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/internals/RawMessage.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | package internals 3 | 4 | import com.github.plokhotnyuk.jsoniter_scala.core._ 5 | import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker 6 | import com.github.plokhotnyuk.jsoniter_scala.macros.CodecMakerConfig 7 | 8 | private[jsonrpclib] case class RawMessage( 9 | jsonrpc: String, 10 | method: Option[String] = None, 11 | result: Option[Option[Payload]] = None, 12 | error: Option[ErrorPayload] = None, 13 | params: Option[Payload] = None, 14 | id: Option[CallId] = None 15 | ) { 16 | 17 | def toMessage: Either[ProtocolError, Message] = (id, method) match { 18 | case (Some(callId), Some(method)) => 19 | Right(InputMessage.RequestMessage(method, callId, params)) 20 | case (None, Some(method)) => 21 | Right(InputMessage.NotificationMessage(method, params)) 22 | case (Some(callId), None) => 23 | (error, result) match { 24 | case (Some(error), _) => Right(OutputMessage.ErrorMessage(callId, error)) 25 | case (_, Some(data)) => Right(OutputMessage.ResponseMessage(callId, data.getOrElse(Payload.NullPayload))) 26 | case (None, None) => 27 | Left( 28 | ProtocolError.InvalidRequest( 29 | "call id was set and method unset, but neither result, nor error fields were present" 30 | ) 31 | ) 32 | } 33 | case (None, None) => 34 | Left( 35 | ProtocolError.InvalidRequest( 36 | "neither call id nor method were set" 37 | ) 38 | ) 39 | } 40 | } 41 | 42 | private[jsonrpclib] object RawMessage { 43 | 44 | val `2.0` = "2.0" 45 | 46 | def from(message: Message): RawMessage = message match { 47 | case InputMessage.NotificationMessage(method, params) => RawMessage(`2.0`, method = Some(method), params = params) 48 | case InputMessage.RequestMessage(method, callId, params) => 49 | RawMessage(`2.0`, method = Some(method), params = params, id = Some(callId)) 50 | case OutputMessage.ErrorMessage(callId, errorPayload) => 51 | RawMessage(`2.0`, error = Some(errorPayload), id = Some(callId)) 52 | case OutputMessage.ResponseMessage(callId, data) => 53 | RawMessage(`2.0`, result = Some(data.stripNull), id = Some(callId)) 54 | } 55 | 56 | implicit val rawMessageJsonValueCodecs: JsonValueCodec[RawMessage] = 57 | JsonCodecMaker.make(CodecMakerConfig.withSkipNestedOptionValues(true)) 58 | 59 | } 60 | -------------------------------------------------------------------------------- /modules/core/src/main/scala/jsonrpclib/package.scala: -------------------------------------------------------------------------------- 1 | package object jsonrpclib { 2 | 3 | type ErrorCode = Int 4 | type ErrorMessage = String 5 | 6 | } 7 | -------------------------------------------------------------------------------- /modules/core/src/test/scala/jsonrpclib/CallIdSpec.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import weaver._ 4 | import com.github.plokhotnyuk.jsoniter_scala.core._ 5 | 6 | object CallIdSpec extends FunSuite { 7 | test("json parsing") { 8 | val strJson = """ "25" """.trim 9 | 10 | val intJson = "25" 11 | 12 | val longJson = Long.MaxValue.toString 13 | 14 | val nullJson = "null" 15 | assert.same(readFromString[CallId](strJson), CallId.StringId("25")) && 16 | assert.same(readFromString[CallId](intJson), CallId.NumberId(25)) && 17 | assert.same(readFromString[CallId](longJson), CallId.NumberId(Long.MaxValue)) && 18 | assert.same(readFromString[CallId](nullJson), CallId.NullId) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /modules/core/src/test/scala/jsonrpclib/RawMessageSpec.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import weaver._ 4 | import jsonrpclib.internals._ 5 | import com.github.plokhotnyuk.jsoniter_scala.core._ 6 | import jsonrpclib.CallId.NumberId 7 | import jsonrpclib.OutputMessage.ResponseMessage 8 | 9 | object RawMessageSpec extends FunSuite { 10 | test("json parsing with null result") { 11 | // This is a perfectly valid response object, as result field has to be present, 12 | // but can be null: https://www.jsonrpc.org/specification#response_object 13 | val rawMessage = readFromString[RawMessage](""" {"jsonrpc":"2.0","result":null,"id":3} """.trim) 14 | 15 | // This, on the other hand, is an invalid response message, as result field is missing 16 | val invalidRawMessage = readFromString[RawMessage](""" {"jsonrpc":"2.0","id":3} """.trim) 17 | 18 | assert.same( 19 | rawMessage, 20 | RawMessage(jsonrpc = "2.0", result = Some(None), id = Some(NumberId(3))) 21 | ) && 22 | assert.same(rawMessage.toMessage, Right(ResponseMessage(NumberId(3), Payload.NullPayload))) && 23 | assert.same( 24 | invalidRawMessage, 25 | RawMessage(jsonrpc = "2.0", result = None, id = Some(NumberId(3))) 26 | ) && 27 | assert(invalidRawMessage.toMessage.isLeft, invalidRawMessage.toMessage.toString) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /modules/core/src/test/scalajvm-native/jsonrpclib/internals/HeaderSpec.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib.internals 2 | 3 | import weaver._ 4 | import java.io.ByteArrayInputStream 5 | import java.io.BufferedReader 6 | import java.io.InputStreamReader 7 | import jsonrpclib.ProtocolError 8 | import java.io.IOException 9 | import java.io.UncheckedIOException 10 | 11 | object HeaderSpec extends FunSuite { 12 | test("headers (all)") { 13 | val result = read( 14 | "Content-Length: 123\r", 15 | "Content-type: application/vscode-jsonrpc; charset=utf-8\r", 16 | "\r", 17 | "foo..." 18 | ) 19 | val expected = Result(LSPHeaders(123, "application/vscode-jsonrpc", "utf-8"), "foo...") 20 | assert.same(result, Right(expected)) 21 | } 22 | 23 | test("headers (only content-)") { 24 | val result = read( 25 | "Content-Length: 123\r", 26 | "\r", 27 | "foo..." 28 | ) 29 | val expected = Result(LSPHeaders(123, "application/json", "UTF-8"), "foo...") 30 | assert.same(result, Right(expected)) 31 | } 32 | 33 | test("no header)") { 34 | val result = read( 35 | "foo" 36 | ) 37 | val expected = ProtocolError.ParseError("Could not parse LSP headers") 38 | assert.same(result, Left(expected)) 39 | } 40 | 41 | test("missing content-length") { 42 | val result = read( 43 | "Content-type: application/vscode-jsonrpc; charset=utf-8\r", 44 | "\r", 45 | "foo..." 46 | ) 47 | val expected = ProtocolError.ParseError("Missing Content-Length header") 48 | assert.same(result, Left(expected)) 49 | } 50 | 51 | case class Result(header: LSPHeaders, rest: String) 52 | def read(lines: String*): Either[ProtocolError.ParseError, Result] = { 53 | val inputStream = new ByteArrayInputStream(lines.mkString("\n").getBytes()); 54 | try { 55 | val maybeHeaders = LSPHeaders.readNext(inputStream) 56 | maybeHeaders.map { headers => 57 | // Consuming the rest to check that the header parsing did not read more of the input stream than it should 58 | val bufferedReader = new BufferedReader(new InputStreamReader(inputStream)) 59 | val iter = new Iterator[String] { 60 | var nextLine: String = null; 61 | 62 | def hasNext: Boolean = { 63 | if (nextLine != null) { 64 | true; 65 | } else { 66 | try { 67 | nextLine = bufferedReader.readLine(); 68 | nextLine != null 69 | } catch { 70 | case e: IOException => throw new UncheckedIOException(e) 71 | } 72 | } 73 | } 74 | 75 | def next(): String = { 76 | if (nextLine != null || hasNext) { 77 | val line = nextLine; 78 | nextLine = null; 79 | return line; 80 | } else { 81 | throw new NoSuchElementException() 82 | } 83 | } 84 | }; 85 | val rest = iter.mkString("\n") 86 | Result(headers, rest) 87 | } 88 | } finally { 89 | inputStream.close() 90 | } 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /modules/examples/client/src/main/scala/examples/client/ClientMain.scala: -------------------------------------------------------------------------------- 1 | package examples.client 2 | 3 | import cats.effect._ 4 | import cats.syntax.all._ 5 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec 6 | import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker 7 | import fs2.Stream 8 | import fs2.io._ 9 | import fs2.io.process.Processes 10 | import jsonrpclib.CallId 11 | import jsonrpclib.fs2._ 12 | 13 | object ClientMain extends IOApp.Simple { 14 | 15 | // Reserving a method for cancelation. 16 | val cancelEndpoint = CancelTemplate.make[CallId]("$/cancel", identity, identity) 17 | 18 | // Creating a datatype that'll serve as a request (and response) of an endpoint 19 | case class IntWrapper(value: Int) 20 | object IntWrapper { 21 | implicit val jcodec: JsonValueCodec[IntWrapper] = JsonCodecMaker.make 22 | } 23 | 24 | type IOStream[A] = fs2.Stream[IO, A] 25 | def log(str: String): IOStream[Unit] = Stream.eval(IO.consoleForIO.errorln(str)) 26 | 27 | def run: IO[Unit] = { 28 | // Using errorln as stdout is used by the RPC channel 29 | val run = for { 30 | _ <- log("Starting client") 31 | serverJar <- sys.env.get("SERVER_JAR").liftTo[IOStream](new Exception("SERVER_JAR env var does not exist")) 32 | // Starting the server 33 | rp <- fs2.Stream.resource(Processes[IO].spawn(process.ProcessBuilder("java", "-jar", serverJar))) 34 | // Creating a channel that will be used to communicate to the server 35 | fs2Channel <- FS2Channel[IO](cancelTemplate = cancelEndpoint.some) 36 | _ <- Stream(()) 37 | .concurrently(fs2Channel.output.through(lsp.encodeMessages).through(rp.stdin)) 38 | .concurrently(rp.stdout.through(lsp.decodeMessages).through(fs2Channel.inputOrBounce)) 39 | .concurrently(rp.stderr.through(fs2.io.stderr[IO])) 40 | // Creating a `IntWrapper => IO[IntWrapper]` stub that can call the server 41 | increment = fs2Channel.simpleStub[IntWrapper, IntWrapper]("increment") 42 | result1 <- Stream.eval(increment(IntWrapper(0))) 43 | _ <- log(s"Client received $result1") 44 | result2 <- Stream.eval(increment(result1)) 45 | _ <- log(s"Client received $result2") 46 | _ <- log("Terminating client") 47 | } yield () 48 | run.compile.drain 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /modules/examples/server/src/main/scala/examples/server/ServerMain.scala: -------------------------------------------------------------------------------- 1 | package examples.server 2 | 3 | import jsonrpclib.CallId 4 | import jsonrpclib.fs2._ 5 | import cats.effect._ 6 | import fs2.io._ 7 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec 8 | import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker 9 | import jsonrpclib.Endpoint 10 | 11 | object ServerMain extends IOApp.Simple { 12 | 13 | // Reserving a method for cancelation. 14 | val cancelEndpoint = CancelTemplate.make[CallId]("$/cancel", identity, identity) 15 | 16 | // Creating a datatype that'll serve as a request (and response) of an endpoint 17 | case class IntWrapper(value: Int) 18 | object IntWrapper { 19 | implicit val jcodec: JsonValueCodec[IntWrapper] = JsonCodecMaker.make 20 | } 21 | 22 | // Implementing an incrementation endpoint 23 | val increment = Endpoint[IO]("increment").simple { in: IntWrapper => 24 | IO.consoleForIO.errorln(s"Server received $in") >> 25 | IO.pure(in.copy(value = in.value + 1)) 26 | } 27 | 28 | def run: IO[Unit] = { 29 | // Using errorln as stdout is used by the RPC channel 30 | IO.consoleForIO.errorln("Starting server") >> 31 | FS2Channel[IO](cancelTemplate = Some(cancelEndpoint)) 32 | .flatMap(_.withEndpointStream(increment)) // mounting an endpoint onto the channel 33 | .flatMap(channel => 34 | fs2.Stream 35 | .eval(IO.never) // running the server forever 36 | .concurrently(stdin[IO](512).through(lsp.decodeMessages).through(channel.inputOrBounce)) 37 | .concurrently(channel.output.through(lsp.encodeMessages).through(stdout[IO])) 38 | ) 39 | .compile 40 | .drain 41 | .guarantee(IO.consoleForIO.errorln("Terminating server")) 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /modules/fs2/src/main/scala/jsonrpclib/fs2/CancelTemplate.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib.fs2 2 | 3 | import jsonrpclib.Codec 4 | import jsonrpclib.CallId 5 | 6 | /** A cancelation template that represents the RPC method by which cancelation 7 | * 8 | * @param template 9 | * : the notification template for the cancelation method 10 | * @param fromCallId 11 | * : a function to create a cancelation request out of a call id 12 | * @param toCallId 13 | * : a function to extract a call id from a cancelation request 14 | */ 15 | trait CancelTemplate { 16 | type C 17 | def method: String 18 | def codec: Codec[C] 19 | def fromCallId(callId: CallId): C 20 | def toCallId(cancelRequest: C): CallId 21 | 22 | } 23 | 24 | object CancelTemplate { 25 | 26 | def make[CancelRequest: Codec]( 27 | cancelMethod: String, 28 | toId: CancelRequest => CallId, 29 | fromId: CallId => CancelRequest 30 | ): CancelTemplate = 31 | new CancelTemplate { 32 | type C = CancelRequest 33 | 34 | def method: String = cancelMethod 35 | 36 | def codec: Codec[CancelRequest] = implicitly[Codec[CancelRequest]] 37 | 38 | def fromCallId(callId: CallId): CancelRequest = fromId(callId) 39 | 40 | def toCallId(cancelRequest: CancelRequest): CallId = toId(cancelRequest) 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /modules/fs2/src/main/scala/jsonrpclib/fs2/FS2Channel.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | package fs2 3 | 4 | import _root_.fs2.Pipe 5 | import _root_.fs2.Stream 6 | import cats.Applicative 7 | import cats.Functor 8 | import cats.Monad 9 | import cats.MonadThrow 10 | import cats.effect.Fiber 11 | import cats.effect.kernel._ 12 | import cats.effect.std.Supervisor 13 | import cats.syntax.all._ 14 | import cats.effect.syntax.all._ 15 | import jsonrpclib.internals.MessageDispatcher 16 | 17 | import scala.util.Try 18 | import java.util.regex.Pattern 19 | 20 | trait FS2Channel[F[_]] extends Channel[F] { 21 | 22 | def input: Pipe[F, Message, Unit] 23 | def inputOrBounce: Pipe[F, Either[ProtocolError, Message], Unit] 24 | def output: Stream[F, Message] 25 | 26 | def withEndpoint(endpoint: Endpoint[F])(implicit F: Functor[F]): Resource[F, FS2Channel[F]] = 27 | Resource.make(mountEndpoint(endpoint))(_ => unmountEndpoint(endpoint.method)).map(_ => this) 28 | 29 | def withEndpointStream(endpoint: Endpoint[F])(implicit F: MonadCancelThrow[F]): Stream[F, FS2Channel[F]] = 30 | Stream.resource(withEndpoint(endpoint)) 31 | 32 | def withEndpoints(endpoint: Endpoint[F], rest: Endpoint[F]*)(implicit F: Monad[F]): Resource[F, FS2Channel[F]] = 33 | withEndpoints(endpoint +: rest) 34 | 35 | def withEndpoints(endpoints: Seq[Endpoint[F]])(implicit F: Monad[F]): Resource[F, FS2Channel[F]] = 36 | endpoints.toList.traverse_(withEndpoint).as(this) 37 | 38 | def withEndpointStream(endpoint: Endpoint[F], rest: Endpoint[F]*)(implicit 39 | F: MonadCancelThrow[F] 40 | ): Stream[F, FS2Channel[F]] = 41 | Stream.resource(withEndpoints(endpoint, rest: _*)) 42 | 43 | def withEndpointsStream(endpoints: Seq[Endpoint[F]])(implicit F: MonadCancelThrow[F]): Stream[F, FS2Channel[F]] = 44 | Stream.resource(withEndpoints(endpoints)) 45 | 46 | } 47 | 48 | object FS2Channel { 49 | 50 | def apply[F[_]: Concurrent]( 51 | bufferSize: Int = 2048, 52 | cancelTemplate: Option[CancelTemplate] = None 53 | ): Stream[F, FS2Channel[F]] = { 54 | for { 55 | supervisor <- Stream.resource(Supervisor[F]) 56 | ref <- Ref[F].of(State[F](Map.empty, Map.empty, Map.empty, Vector.empty, 0)).toStream 57 | queue <- cats.effect.std.Queue.bounded[F, Message](bufferSize).toStream 58 | impl = new Impl(queue, ref, supervisor, cancelTemplate) 59 | 60 | // Creating a bespoke endpoint to receive cancelation requests 61 | maybeCancelEndpoint: Option[Endpoint[F]] = cancelTemplate.map { ct => 62 | implicit val codec: Codec[ct.C] = ct.codec 63 | Endpoint[F](ct.method).notification[ct.C] { request => 64 | val callId = ct.toCallId(request) 65 | impl.cancel(callId) 66 | } 67 | } 68 | // mounting the cancelation endpoint 69 | _ <- maybeCancelEndpoint.traverse_(ep => impl.mountEndpoint(ep)).toStream 70 | } yield impl 71 | } 72 | 73 | private case class State[F[_]]( 74 | runningCalls: Map[CallId, Fiber[F, Throwable, Unit]], 75 | pendingCalls: Map[CallId, OutputMessage => F[Unit]], 76 | endpoints: Map[String, Endpoint[F]], 77 | globEndpoints: Vector[(Pattern, Endpoint[F])], 78 | counter: Long 79 | ) { 80 | def nextCallId: (State[F], CallId) = (this.copy(counter = counter + 1), CallId.NumberId(counter)) 81 | def storePendingCall(callId: CallId, handle: OutputMessage => F[Unit]): State[F] = 82 | this.copy(pendingCalls = pendingCalls + (callId -> handle)) 83 | def removePendingCall(callId: CallId): (State[F], Option[OutputMessage => F[Unit]]) = { 84 | val result = pendingCalls.get(callId) 85 | (this.copy(pendingCalls = pendingCalls.removed(callId)), result) 86 | } 87 | def mountEndpoint(endpoint: Endpoint[F]): Either[ConflictingMethodError, State[F]] = { 88 | import endpoint.method 89 | if (method.contains("*")) { 90 | val parts = method 91 | .split("\\*", -1) 92 | .map { // Don't discard trailing empty string, if any. 93 | case "" => "" 94 | case str => Pattern.quote(str) 95 | } 96 | val glob = Pattern.compile(parts.mkString(".*")) 97 | Right(this.copy(globEndpoints = globEndpoints :+ (glob -> endpoint))) 98 | } else { 99 | endpoints.get(endpoint.method) match { 100 | case None => Right(this.copy(endpoints = endpoints + (endpoint.method -> endpoint))) 101 | case Some(_) => Left(ConflictingMethodError(endpoint.method)) 102 | } 103 | } 104 | } 105 | def getEndpoint(method: String): Option[Endpoint[F]] = { 106 | endpoints.get(method).orElse(globEndpoints.find(_._1.matcher(method).matches()).map(_._2)) 107 | } 108 | def removeEndpoint(method: String): State[F] = 109 | copy(endpoints = endpoints.removed(method)) 110 | 111 | def addRunningCall(callId: CallId, fiber: Fiber[F, Throwable, Unit]): State[F] = 112 | copy(runningCalls = runningCalls + (callId -> fiber)) 113 | 114 | def removeRunningCall(callId: CallId): State[F] = 115 | copy(runningCalls = runningCalls - callId) 116 | } 117 | 118 | private class Impl[F[_]]( 119 | private val queue: cats.effect.std.Queue[F, Message], 120 | private val state: Ref[F, FS2Channel.State[F]], 121 | supervisor: Supervisor[F], 122 | maybeCancelTemplate: Option[CancelTemplate] 123 | )(implicit F: Concurrent[F]) 124 | extends MessageDispatcher[F] 125 | with FS2Channel[F] { 126 | 127 | def output: Stream[F, Message] = Stream.fromQueueUnterminated(queue) 128 | def inputOrBounce: Pipe[F, Either[ProtocolError, Message], Unit] = _.evalMap { 129 | case Left(error) => sendProtocolError(error) 130 | case Right(message) => handleReceivedMessage(message) 131 | } 132 | def input: Pipe[F, Message, Unit] = _.evalMap(handleReceivedMessage) 133 | 134 | def mountEndpoint(endpoint: Endpoint[F]): F[Unit] = state 135 | .modify(s => 136 | s.mountEndpoint(endpoint) match { 137 | case Left(error) => (s, MonadThrow[F].raiseError[Unit](error)) 138 | case Right(value) => (value, Applicative[F].unit) 139 | } 140 | ) 141 | .flatMap(identity) 142 | 143 | def unmountEndpoint(method: String): F[Unit] = state.update(_.removeEndpoint(method)) 144 | 145 | protected[fs2] def cancel(callId: CallId): F[Unit] = state.get.map(_.runningCalls.get(callId)).flatMap { 146 | case None => F.unit 147 | case Some(fiber) => fiber.cancel 148 | } 149 | 150 | protected def background[A](maybeCallId: Option[CallId], fa: F[A]): F[Unit] = 151 | maybeCallId match { 152 | case None => supervisor.supervise(fa).void 153 | case Some(callId) => 154 | val runAndClean = fa.void.guarantee(state.update(_.removeRunningCall(callId))) 155 | supervisor.supervise(runAndClean).flatMap { fiber => 156 | state.update(_.addRunningCall(callId, fiber)) 157 | } 158 | } 159 | protected def reportError(params: Option[Payload], error: ProtocolError, method: String): F[Unit] = ??? 160 | protected def getEndpoint(method: String): F[Option[Endpoint[F]]] = state.get.map(_.getEndpoint(method)) 161 | protected def sendMessage(message: Message): F[Unit] = queue.offer(message) 162 | 163 | protected def nextCallId(): F[CallId] = state.modify(_.nextCallId) 164 | protected def createPromise[A](callId: CallId): F[(Try[A] => F[Unit], () => F[A])] = Deferred[F, Try[A]].map { 165 | promise => 166 | def compile(trya: Try[A]): F[Unit] = promise.complete(trya).void 167 | def get(): F[A] = promise.get.flatMap(_.liftTo[F]) 168 | (compile(_), () => get().onCancel(cancelRequest(callId))) 169 | } 170 | protected def storePendingCall(callId: CallId, handle: OutputMessage => F[Unit]): F[Unit] = 171 | state.update(_.storePendingCall(callId, handle)) 172 | protected def removePendingCall(callId: CallId): F[Option[OutputMessage => F[Unit]]] = 173 | state.modify(_.removePendingCall(callId)) 174 | 175 | private val cancelRequest: CallId => F[Unit] = maybeCancelTemplate 176 | .map { cancelTemplate => 177 | val stub = notificationStub(cancelTemplate.method)(cancelTemplate.codec) 178 | stub.compose(cancelTemplate.fromCallId(_)) 179 | } 180 | .getOrElse((_: CallId) => F.unit) 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /modules/fs2/src/main/scala/jsonrpclib/fs2/lsp.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib.fs2 2 | 3 | import cats.MonadThrow 4 | import fs2.Chunk 5 | import fs2.Stream 6 | import fs2.Pipe 7 | import jsonrpclib.Payload 8 | import jsonrpclib.Codec 9 | 10 | import java.nio.charset.Charset 11 | import java.nio.charset.StandardCharsets 12 | import jsonrpclib.Message 13 | import jsonrpclib.ProtocolError 14 | import jsonrpclib.Payload.Data 15 | import jsonrpclib.Payload.NullPayload 16 | import scala.annotation.tailrec 17 | 18 | object lsp { 19 | 20 | def encodeMessages[F[_]]: Pipe[F, Message, Byte] = 21 | (_: Stream[F, Message]).map(Codec.encode(_)).through(encodePayloads) 22 | 23 | def encodePayloads[F[_]]: Pipe[F, Payload, Byte] = 24 | (_: Stream[F, Payload]).map(writeChunk).flatMap(Stream.chunk(_)) 25 | 26 | def decodeMessages[F[_]: MonadThrow]: Pipe[F, Byte, Either[ProtocolError, Message]] = 27 | (_: Stream[F, Byte]).through(decodePayloads).map { payload => 28 | Codec.decode[Message](Some(payload)) 29 | } 30 | 31 | /** Split a stream of bytes into payloads by extracting each frame based on information contained in the headers. 32 | * 33 | * See https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#contentPart 34 | */ 35 | def decodePayloads[F[_]: MonadThrow]: Pipe[F, Byte, Payload] = 36 | (_: Stream[F, Byte]) 37 | .scanChunks(ScanState.starting) { case (state, chunk) => 38 | val (ns, maybeResult) = loop(state.concatChunk(chunk)) 39 | (ns, Chunk(maybeResult)) 40 | } 41 | .flatMap { 42 | case Right(acc) => Stream.iterable(acc).map(c => Payload(c.toArray)) 43 | case Left(error) => Stream.raiseError[F](error) 44 | } 45 | 46 | private def writeChunk(payload: Payload): Chunk[Byte] = { 47 | val bytes = payload match { 48 | case Data(array) => array 49 | case NullPayload => nullArray 50 | } 51 | val header = s"Content-Length: ${bytes.size}" + "\r\n" * 2 52 | Chunk.array(header.getBytes()) ++ Chunk.array(bytes) 53 | } 54 | 55 | private val nullArray = "null".getBytes() 56 | private val returnByte = '\r'.toByte 57 | private val newlineByte = '\n'.toByte 58 | 59 | private final case class LSPHeaders( 60 | contentLength: Int, 61 | mimeType: String, 62 | charset: Charset 63 | ) 64 | 65 | private final case class ParseError(message: String) extends Throwable { 66 | override def getMessage(): String = message 67 | } 68 | 69 | private def parseHeader( 70 | line: String, 71 | headers: LSPHeaders 72 | ): Either[ParseError, LSPHeaders] = 73 | line.trim() match { 74 | case s"Content-Length: ${integer(length)}" => 75 | Right(headers.copy(contentLength = length)) 76 | case s"Content-Type: ${mimeType}; charset=${charset}" => 77 | Right( 78 | headers.copy(mimeType = mimeType, charset = Charset.forName(charset)) 79 | ) 80 | case _ => Left(ParseError(s"Couldn't parse header: $line")) 81 | } 82 | 83 | private object integer { 84 | def unapply(string: String): Option[Int] = string.toIntOption 85 | } 86 | 87 | private final case class ScanState(status: Status, currentHeaders: LSPHeaders, buffered: Chunk[Byte]) { 88 | def concatChunk(other: Chunk[Byte]) = copy(buffered = buffered ++ other) 89 | } 90 | 91 | private object ScanState { 92 | def readingHeader(storedChunk: Chunk[Byte]) = ScanState( 93 | Status.ReadingHeader, 94 | LSPHeaders(-1, "application/json", StandardCharsets.UTF_8), 95 | storedChunk 96 | ) 97 | 98 | val starting: ScanState = readingHeader(Chunk.empty) 99 | } 100 | 101 | private sealed trait Status 102 | 103 | private object Status { 104 | case object ReadingHeader extends Status 105 | case object FinishedReadingHeader extends Status 106 | case object ReadingBody extends Status 107 | } 108 | 109 | @tailrec 110 | private def loop( 111 | state: ScanState, 112 | acc: Seq[Chunk[Byte]] = Seq.empty 113 | ): (ScanState, Either[ParseError, Seq[Chunk[Byte]]]) = 114 | state match { 115 | case ScanState(Status.ReadingBody, headers, buffered) => 116 | if (headers.contentLength <= buffered.size) { 117 | // We have a full payload to emit 118 | val (payload, tail) = buffered.splitAt(headers.contentLength) 119 | val newState = ScanState.readingHeader(tail) 120 | loop(newState, acc.appended(payload)) 121 | } else { 122 | (state, Right(acc)) 123 | } 124 | case ScanState(Status.ReadingHeader, headers, buffered) => 125 | val bb = java.nio.ByteBuffer.allocate(buffered.size) 126 | val iterator = buffered.iterator 127 | var continue = true 128 | var newState: ScanState = null 129 | var error: ParseError = null 130 | while (iterator.hasNext && continue) { 131 | val byte = iterator.next() 132 | if (byte == newlineByte) { 133 | parseHeader(new String(bb.array, StandardCharsets.US_ASCII), headers) match { 134 | case Right(newHeader) => 135 | newState = ScanState(Status.FinishedReadingHeader, newHeader, Chunk.iterator(iterator)) 136 | case Left(e) => 137 | error = e 138 | } 139 | continue = false 140 | } else { 141 | bb.put(byte) 142 | } 143 | } 144 | if (newState != null) { 145 | loop(newState, acc) 146 | } else if (error != null) { 147 | (state, Left(error)) 148 | } else { 149 | (state, Right(acc)) 150 | } 151 | 152 | case ScanState(Status.FinishedReadingHeader, headers, buffered) => 153 | if (buffered.size >= 2) { 154 | if (buffered.startsWith(Seq(returnByte, newlineByte))) { 155 | // We have read two `\r\n` in a row, starting to scan a body 156 | loop(ScanState(Status.ReadingBody, headers, buffered.drop(2)), acc) 157 | } else { 158 | loop(ScanState(Status.ReadingHeader, headers, buffered), acc) 159 | } 160 | } else { 161 | (state, Right(acc)) 162 | } 163 | } 164 | 165 | } 166 | -------------------------------------------------------------------------------- /modules/fs2/src/main/scala/jsonrpclib/fs2/package.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib 2 | 3 | import _root_.fs2.Stream 4 | import cats.MonadThrow 5 | import cats.Monad 6 | import cats.effect.kernel.Resource 7 | import cats.effect.kernel.MonadCancel 8 | 9 | package object fs2 { 10 | 11 | private[jsonrpclib] implicit class EffectOps[F[_], A](private val fa: F[A]) extends AnyVal { 12 | def toStream: Stream[F, A] = Stream.eval(fa) 13 | } 14 | 15 | private[jsonrpclib] implicit class ResourceOps[F[_], A](private val fa: Resource[F, A]) extends AnyVal { 16 | def asStream(implicit F: MonadCancel[F, Throwable]): Stream[F, A] = Stream.resource(fa) 17 | } 18 | 19 | implicit def catsMonadic[F[_]: MonadThrow]: Monadic[F] = new Monadic[F] { 20 | def doFlatMap[A, B](fa: F[A])(f: A => F[B]): F[B] = Monad[F].flatMap(fa)(f) 21 | 22 | def doPure[A](a: A): F[A] = Monad[F].pure(a) 23 | 24 | def doAttempt[A](fa: F[A]): F[Either[Throwable, A]] = MonadThrow[F].attempt(fa) 25 | 26 | def doRaiseError[A](e: Throwable): F[A] = MonadThrow[F].raiseError(e) 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /modules/fs2/src/test/scala/jsonrpclib/fs2/FS2ChannelSpec.scala: -------------------------------------------------------------------------------- 1 | package jsonrpclib.fs2 2 | 3 | import cats.effect.IO 4 | import cats.syntax.all._ 5 | import com.github.plokhotnyuk.jsoniter_scala.core.JsonValueCodec 6 | import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker 7 | import fs2.Stream 8 | import jsonrpclib._ 9 | import weaver._ 10 | 11 | import scala.concurrent.duration._ 12 | 13 | object FS2ChannelSpec extends SimpleIOSuite { 14 | 15 | case class IntWrapper(int: Int) 16 | object IntWrapper { 17 | implicit val jcodec: JsonValueCodec[IntWrapper] = JsonCodecMaker.make 18 | } 19 | 20 | case class CancelRequest(callId: CallId) 21 | object CancelRequest { 22 | implicit val jcodec: JsonValueCodec[CancelRequest] = JsonCodecMaker.make 23 | } 24 | 25 | def testRes(name: TestName)(run: Stream[IO, Expectations]): Unit = 26 | test(name)(run.compile.lastOrError.timeout(10.second)) 27 | 28 | type ClientSideChannel = FS2Channel[IO] 29 | def setup(endpoints: Endpoint[IO]*) = setupAux(endpoints, None) 30 | def setup(cancelTemplate: CancelTemplate, endpoints: Endpoint[IO]*) = setupAux(endpoints, Some(cancelTemplate)) 31 | def setupAux(endpoints: Seq[Endpoint[IO]], cancelTemplate: Option[CancelTemplate]): Stream[IO, ClientSideChannel] = { 32 | for { 33 | serverSideChannel <- FS2Channel[IO](cancelTemplate = cancelTemplate) 34 | clientSideChannel <- FS2Channel[IO](cancelTemplate = cancelTemplate) 35 | _ <- serverSideChannel.withEndpointsStream(endpoints) 36 | _ <- Stream(()) 37 | .concurrently(clientSideChannel.output.through(serverSideChannel.input)) 38 | .concurrently(serverSideChannel.output.through(clientSideChannel.input)) 39 | } yield { 40 | clientSideChannel 41 | } 42 | } 43 | 44 | testRes("Round trip") { 45 | val endpoint: Endpoint[IO] = Endpoint[IO]("inc").simple((int: IntWrapper) => IO(IntWrapper(int.int + 1))) 46 | 47 | for { 48 | clientSideChannel <- setup(endpoint) 49 | remoteFunction = clientSideChannel.simpleStub[IntWrapper, IntWrapper]("inc") 50 | result <- remoteFunction(IntWrapper(1)).toStream 51 | } yield { 52 | expect.same(result, IntWrapper(2)) 53 | } 54 | } 55 | 56 | testRes("Round trip (glob)") { 57 | val endpoint: Endpoint[IO] = Endpoint[IO]("**").simple((int: IntWrapper) => IO(IntWrapper(int.int + 1))) 58 | 59 | for { 60 | clientSideChannel <- setup(endpoint) 61 | remoteFunction = clientSideChannel.simpleStub[IntWrapper, IntWrapper]("inc/test") 62 | result <- remoteFunction(IntWrapper(1)).toStream 63 | } yield { 64 | expect.same(result, IntWrapper(2)) 65 | } 66 | } 67 | 68 | testRes("Globs have lower priority than strict endpoints") { 69 | val endpoint: Endpoint[IO] = Endpoint[IO]("inc").simple((int: IntWrapper) => IO(IntWrapper(int.int + 1))) 70 | val globEndpoint: Endpoint[IO] = 71 | Endpoint[IO]("**").simple((_: IntWrapper) => IO.raiseError[IntWrapper](new Throwable("Boom"))) 72 | 73 | for { 74 | clientSideChannel <- setup(globEndpoint, endpoint) 75 | remoteFunction = clientSideChannel.simpleStub[IntWrapper, IntWrapper]("inc") 76 | result <- remoteFunction(IntWrapper(1)).toStream 77 | } yield { 78 | expect.same(result, IntWrapper(2)) 79 | } 80 | } 81 | 82 | testRes("Endpoint not mounted") { 83 | 84 | for { 85 | clientSideChannel <- setup() 86 | remoteFunction = clientSideChannel.simpleStub[IntWrapper, IntWrapper]("inc") 87 | result <- remoteFunction(IntWrapper(1)).attempt.toStream 88 | } yield { 89 | expect.same(result, Left(ErrorPayload(-32601, "Method inc not found", None))) 90 | } 91 | } 92 | 93 | testRes("Concurrency") { 94 | 95 | val endpoint: Endpoint[IO] = 96 | Endpoint[IO]("inc").simple { (int: IntWrapper) => 97 | IO.sleep((1000 - int.int * 100).millis) >> IO(IntWrapper(int.int + 1)) 98 | } 99 | 100 | for { 101 | clientSideChannel <- setup(endpoint) 102 | remoteFunction = clientSideChannel.simpleStub[IntWrapper, IntWrapper]("inc") 103 | timedResults <- (1 to 10).toList.map(IntWrapper(_)).parTraverse(remoteFunction).timed.toStream 104 | } yield { 105 | val (time, results) = timedResults 106 | expect.same(results, (2 to 11).toList.map(IntWrapper(_))) && 107 | expect(time < 2.seconds) 108 | } 109 | } 110 | 111 | testRes("cancelation propagates") { 112 | val cancelTemplate = CancelTemplate.make[CancelRequest]("$/cancel", _.callId, CancelRequest(_)) 113 | 114 | for { 115 | canceledPromise <- IO.deferred[IntWrapper].toStream 116 | endpoint: Endpoint[IO] = Endpoint[IO]("never").simple((int: IntWrapper) => 117 | IO.never.as(int).onCancel(canceledPromise.complete(int).void) 118 | ) 119 | 120 | clientSideChannel <- setup(cancelTemplate, endpoint) 121 | remoteFunction = clientSideChannel.simpleStub[IntWrapper, IntWrapper]("never") 122 | // Timeing-out client-call to verify cancelation progagates to server 123 | _ <- IO.race(remoteFunction(IntWrapper(23)), IO.sleep(1.second)).toStream 124 | result <- canceledPromise.get.toStream 125 | } yield { 126 | expect.same(result, IntWrapper(23)) 127 | } 128 | } 129 | 130 | } 131 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.10.11 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("com.github.sbt" % "sbt-ci-release" % "1.5.11") 2 | 3 | addSbtPlugin("org.typelevel" % "sbt-tpolecat" % "0.5.2") 4 | 5 | addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.1.1") 6 | 7 | addSbtPlugin("com.eed3si9n" % "sbt-projectmatrix" % "0.10.0") 8 | 9 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.18.2") 10 | 11 | addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.17") 12 | 13 | addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.3.1") 14 | 15 | addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.4") 16 | 17 | addDependencyTreePlugin 18 | --------------------------------------------------------------------------------