├── .gitignore ├── LICENSE ├── README.md ├── deps.edn ├── mvn-upload.sh ├── pom.xml ├── src └── vertx │ ├── core.clj │ ├── eventbus.clj │ ├── http.clj │ ├── util.clj │ ├── web.clj │ └── web │ └── interceptors.clj ├── test ├── user.clj └── vertx_tests │ ├── main.clj │ └── test_core.clj └── tools.clj /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | /.nrepl-port 10 | /*-init.clj 11 | /out 12 | /repl 13 | /.cpcache 14 | /.rebel* 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vertx-clojure 2 | 3 | **STATUS**: *Pre-alpha*, in design and prototyping phase. 4 | 5 | A lightweight clojure adapter for vertx toolkit. 6 | 7 | Example code on `resources/user.clj` file. 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /deps.edn: -------------------------------------------------------------------------------- 1 | {:deps {org.clojure/tools.logging {:mvn/version "0.5.0"} 2 | funcool/promesa {:mvn/version "5.0.0-SNAPSHOT"} 3 | metosin/reitit-core {:mvn/version "0.3.10"} 4 | metosin/sieppari {:mvn/version "0.0.0-alpha8"} 5 | com.cognitect/transit-clj {:mvn/version "0.8.319"} 6 | io.vertx/vertx-core {:mvn/version "3.8.1"} 7 | io.vertx/vertx-web {:mvn/version "3.8.1"}} 8 | :paths ["src" "resources"] 9 | :aliases 10 | {:dev 11 | {:extra-deps {com.bhauman/rebel-readline {:mvn/version "0.1.4"} 12 | metosin/jsonista {:mvn/version "0.2.5"} 13 | mount/mount {:mvn/version "0.1.16"} 14 | org.clojure/clojure {:mvn/version "1.10.1"} 15 | io.netty/netty-transport-native-epoll {:mvn/version "4.1.39.Final"} 16 | environ/environ {:mvn/version "1.1.0"} 17 | ;; integrant/integrant {:mvn/version "0.7.0"} 18 | metosin/pohjavirta {:mvn/version "0.0.1-alpha5"} 19 | org.clojure/tools.namespace {:mvn/version "0.3.1"}} 20 | :extra-paths ["test"]} 21 | :repl 22 | {:main-opts ["-m" "rebel-readline.main"]} 23 | 24 | :jar 25 | {:extra-deps {seancorfield/depstar {:mvn/version "0.3.4"}} 26 | :main-opts ["-m" "hf.depstar.jar", "target/vertx.jar"]} 27 | 28 | :ancient 29 | {:main-opts ["-m" "deps-ancient.deps-ancient"] 30 | :extra-deps {deps-ancient {:mvn/version "RELEASE"}}} 31 | }} 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /mvn-upload.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | mvn deploy:deploy-file -Dfile=target/vertx.jar -DpomFile=pom.xml -DrepositoryId=clojars -Durl=https://clojars.org/repo/ 3 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | funcool 5 | vertx-clojure 6 | 0.0.0-alpha1-0 7 | vertx-clojure 8 | Vert.x bindings for Clojure 9 | https://github.com/funcool/vertx-clojure 10 | 11 | scm:git:git://github.com/funcool/vertx-clojure.git 12 | scm:git:ssh://git@github.com/funcool/vertx-clojure.git 13 | https://github.com/funcool/vertx-clojure 14 | master 15 | 16 | 17 | src 18 | 19 | 20 | 21 | org.clojure 22 | clojure 23 | 1.10.1 24 | 25 | 26 | org.clojure 27 | tools.logging 28 | 0.5.0 29 | 30 | 31 | funcool 32 | promesa 33 | 4.0.2 34 | 35 | 36 | metosin 37 | reitit-core 38 | 0.3.10 39 | 40 | 41 | metosin 42 | sieppari 43 | 0.0.0-alpha7 44 | 45 | 46 | com.cognitect 47 | transit-clj 48 | 0.8.319 49 | 50 | 51 | io.vertx 52 | vertx-core 53 | 3.8.1 54 | 55 | 56 | io.vertx 57 | vertx-web 58 | 3.8.1 59 | 60 | 61 | 62 | 63 | clojars 64 | https://repo.clojars.org/ 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /src/vertx/core.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx.core 8 | (:require [clojure.spec.alpha :as s] 9 | [promesa.core :as p] 10 | [vertx.eventbus :as vxe] 11 | [vertx.util :as vu]) 12 | (:import 13 | io.vertx.core.Context 14 | io.vertx.core.DeploymentOptions 15 | io.vertx.core.Future 16 | io.vertx.core.Handler 17 | io.vertx.core.Verticle 18 | io.vertx.core.Vertx 19 | io.vertx.core.VertxOptions 20 | java.util.function.Supplier)) 21 | 22 | (declare opts->deployment-options) 23 | (declare opts->vertx-options) 24 | (declare build-verticle) 25 | (declare build-actor) 26 | (declare build-disposable) 27 | 28 | ;; --- Protocols 29 | 30 | (definterface IVerticleFactory) 31 | 32 | ;; --- Public Api 33 | 34 | (s/def :vertx.core$system/threads pos?) 35 | (s/def :vertx.core$system/on-error fn?) 36 | (s/def ::system-options 37 | (s/keys :opt-un [:vertx.core$system/threads 38 | :vertx.core$system/on-error])) 39 | 40 | (defn system 41 | "Creates a new vertx actor system instance." 42 | ([] (system {})) 43 | ([options] 44 | (s/assert ::system-options options) 45 | (let [^VertxOptions opts (opts->vertx-options options) 46 | ^Vertx vsm (Vertx/vertx opts)] 47 | (vxe/configure! vsm opts) 48 | vsm))) 49 | 50 | (defn get-or-create-context 51 | [vsm] 52 | (.getOrCreateContext ^Vertx (vu/resolve-system vsm))) 53 | 54 | (defn current-context 55 | [] 56 | (Vertx/currentContext)) 57 | 58 | (defn handle-on-context 59 | "Attaches the context (current if not explicitly provided) to the 60 | promise execution chain." 61 | ([prm] (handle-on-context prm (current-context))) 62 | ([prm ctx] 63 | (let [d (p/deferred)] 64 | (p/finally prm (fn [v e] 65 | (.runOnContext 66 | ^Context ctx 67 | ^Handler (reify Handler 68 | (handle [_ v'] 69 | (if e 70 | (p/reject! d e) 71 | (p/resolve! d v))))))) 72 | d))) 73 | 74 | (s/def :vertx.core$verticle/on-start fn?) 75 | (s/def :vertx.core$verticle/on-stop fn?) 76 | (s/def :vertx.core$verticle/on-error fn?) 77 | (s/def ::verticle-options 78 | (s/keys :req-un [:vertx.core$verticle/on-start] 79 | :opt-un [:vertx.core$verticle/on-stop 80 | :vertx.core$verticle/on-error])) 81 | 82 | (defn verticle 83 | "Creates a verticle instance (factory)." 84 | [options] 85 | (s/assert ::verticle-options options) 86 | (reify 87 | IVerticleFactory 88 | Supplier 89 | (get [_] (build-verticle options)))) 90 | 91 | (defn verticle? 92 | "Return `true` if `v` is instance of `IVerticleFactory`." 93 | [v] 94 | (instance? IVerticleFactory v)) 95 | 96 | (s/def :vertx.core$actor/on-message fn?) 97 | (s/def ::actor-options 98 | (s/keys :req-un [:vertx.core$actor/on-message] 99 | :opt-un [:vertx.core$verticle/on-start 100 | :vertx.core$verticle/on-error 101 | :vertx.core$verticle/on-stop])) 102 | 103 | (defn actor 104 | "A shortcut for create a verticle instance (factory) that consumes a 105 | specific topic." 106 | [topic options] 107 | (s/assert string? topic) 108 | (s/assert ::actor-options options) 109 | (reify 110 | IVerticleFactory 111 | Supplier 112 | (get [_] (build-actor topic options)))) 113 | 114 | (s/def :vertx.core$deploy/instances pos?) 115 | (s/def :vertx.core$deploy/worker boolean?) 116 | (s/def ::deploy-options 117 | (s/keys :opt-un [:vertx.core$deploy/worker 118 | :vertx.core$deploy/instances])) 119 | 120 | (defn deploy! 121 | "Deploy a verticle." 122 | ([vsm supplier] (deploy! vsm supplier nil)) 123 | ([vsm supplier options] 124 | (s/assert verticle? supplier) 125 | (s/assert ::deploy-options options) 126 | (let [d (p/deferred) 127 | o (opts->deployment-options options)] 128 | (.deployVerticle ^Vertx vsm 129 | ^Supplier supplier 130 | ^DeploymentOptions o 131 | ^Handler (vu/deferred->handler d)) 132 | (p/then' d (fn [id] (build-disposable vsm id)))))) 133 | 134 | (defn undeploy! 135 | "Undeploy the verticle, this function should be rarelly used because 136 | the easiest way to undeplo is executin the callable returned by 137 | `deploy!` function." 138 | [vsm id] 139 | (s/assert string? id) 140 | (let [d (p/deferred)] 141 | (.undeploy ^Vertx (vu/resolve-system vsm) 142 | ^String id 143 | ^Handler (vu/deferred->handler d)) 144 | d)) 145 | 146 | ;; --- Impl 147 | 148 | (defn- build-verticle 149 | [{:keys [on-start on-stop on-error] 150 | :or {on-error (constantly nil) 151 | on-stop (constantly nil)}}] 152 | (let [vsm (volatile! nil) 153 | ctx (volatile! nil) 154 | lst (volatile! nil)] 155 | (reify Verticle 156 | (init [_ instance context] 157 | (vreset! vsm instance) 158 | (vreset! ctx context)) 159 | (getVertx [_] @vsm) 160 | (^void start [_ ^Future o] 161 | (-> (p/do! (on-start @ctx)) 162 | (p/handle (fn [state error] 163 | (if error 164 | (do 165 | (.fail o error) 166 | (on-error @ctx error)) 167 | (do 168 | (when (map? state) 169 | (vswap! lst merge state)) 170 | (.complete o))))))) 171 | (^void stop [_ ^Future o] 172 | (p/handle (p/do! (on-stop @ctx @lst)) 173 | (fn [_ err] 174 | (if err 175 | (do (on-error err) 176 | (.fail o err)) 177 | (.complete o)))))))) 178 | 179 | (defn- build-actor 180 | [topic {:keys [on-message on-error on-stop on-start] 181 | :or {on-error (constantly nil) 182 | on-start (constantly {}) 183 | on-stop (constantly nil)}}] 184 | (letfn [(-on-start [ctx] 185 | (let [state (on-start ctx) 186 | state (if (map? state) state {}) 187 | consumer (vxe/consumer ctx topic on-message)] 188 | (assoc state ::consumer consumer)))] 189 | (build-verticle {:on-error on-error 190 | :on-stop on-stop 191 | :on-start -on-start}))) 192 | 193 | (defn- build-disposable 194 | [vsm id] 195 | (reify 196 | clojure.lang.IDeref 197 | (deref [_] id) 198 | 199 | clojure.lang.IFn 200 | (invoke [_] (undeploy! vsm id)) 201 | 202 | java.io.Closeable 203 | (close [_] 204 | @(undeploy! vsm id)))) 205 | 206 | (defn- opts->deployment-options 207 | [{:keys [instances worker]}] 208 | (let [opts (DeploymentOptions.)] 209 | (when instances (.setInstances opts (int instances))) 210 | (when worker (.setWorker opts worker)) 211 | opts)) 212 | 213 | (defn- opts->vertx-options 214 | [{:keys [threads on-error]}] 215 | (let [opts (VertxOptions.)] 216 | (when threads (.setEventLoopPoolSize opts (int threads))) 217 | (when on-error (.exceptionHandler (vu/fn->handler on-error))) 218 | opts)) 219 | 220 | 221 | 222 | -------------------------------------------------------------------------------- /src/vertx/eventbus.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx.eventbus 8 | (:require [promesa.core :as p] 9 | [vertx.util :as vu]) 10 | (:import io.vertx.core.Vertx 11 | io.vertx.core.Handler 12 | io.vertx.core.Context 13 | io.vertx.core.eventbus.Message 14 | io.vertx.core.eventbus.MessageConsumer 15 | io.vertx.core.eventbus.DeliveryOptions 16 | io.vertx.core.eventbus.EventBus 17 | io.vertx.core.eventbus.MessageCodec 18 | java.util.function.Supplier)) 19 | 20 | (declare opts->delivery-opts) 21 | (declare resolve-eventbus) 22 | (declare build-message-codec) 23 | (declare build-message) 24 | 25 | ;; --- Public Api 26 | 27 | (defn consumer 28 | [vsm topic f] 29 | (let [^EventBus bus (resolve-eventbus vsm) 30 | ^MessageConsumer consumer (.consumer bus ^String topic)] 31 | (.handler consumer (reify Handler 32 | (handle [_ msg] 33 | (.pause consumer) 34 | (-> (p/do! (f vsm (build-message msg))) 35 | (p/handle (fn [res err] 36 | (.resume consumer) 37 | (.reply msg (or res err) 38 | (opts->delivery-opts {})))))))) 39 | consumer)) 40 | 41 | (defn publish! 42 | ([vsm topic msg] (publish! vsm topic msg {})) 43 | ([vsm topic msg opts] 44 | (let [bus (resolve-eventbus vsm) 45 | opts (opts->delivery-opts opts)] 46 | (.publish ^EventBus bus 47 | ^String topic 48 | ^Object msg 49 | ^DeliveryOptions opts) 50 | nil))) 51 | 52 | (defn send! 53 | ([vsm topic msg] (send! vsm topic msg {})) 54 | ([vsm topic msg opts] 55 | (let [bus (resolve-eventbus vsm) 56 | opts (opts->delivery-opts opts)] 57 | (.send ^EventBus bus 58 | ^String topic 59 | ^Object msg 60 | ^DeliveryOptions opts) 61 | nil))) 62 | 63 | (defn request! 64 | ([vsm topic msg] (request! vsm topic msg {})) 65 | ([vsm topic msg opts] 66 | (let [bus (resolve-eventbus vsm) 67 | opts (opts->delivery-opts opts) 68 | d (p/deferred)] 69 | (.request ^EventBus bus 70 | ^String topic 71 | ^Object msg 72 | ^DeliveryOptions opts 73 | ^Handler (vu/deferred->handler d)) 74 | (p/then' d build-message)))) 75 | 76 | (defn configure! 77 | [vsm opts] 78 | (let [^EventBus bus (resolve-eventbus vsm)] 79 | (.registerCodec bus (build-message-codec)))) 80 | 81 | (defrecord Msg [body]) 82 | 83 | (defn message? 84 | [v] 85 | (instance? Msg v)) 86 | 87 | ;; --- Impl 88 | 89 | (defn- resolve-eventbus 90 | [o] 91 | (cond 92 | (instance? Vertx o) (.eventBus ^Vertx o) 93 | (instance? Context o) (resolve-eventbus (.owner ^Context o)) 94 | (instance? EventBus o) o 95 | :else (throw (ex-info "unexpected argument" {})))) 96 | 97 | (defn- build-message-codec 98 | [] 99 | ;; TODO: implement the wire encode/decode using transit+msgpack 100 | (reify MessageCodec 101 | (encodeToWire [_ buffer data]) 102 | (decodeFromWire [_ pos buffer]) 103 | (transform [_ data] data) 104 | (name [_] "clj:msgpack") 105 | (^byte systemCodecID [_] (byte -1)))) 106 | 107 | (defn- build-message 108 | [^Message msg] 109 | (let [metadata {::reply-to (.replyAddress msg) 110 | ::send? (.isSend msg) 111 | ::address (.address msg)} 112 | body (.body msg)] 113 | (Msg. body metadata nil))) 114 | 115 | (defn- opts->delivery-opts 116 | [{:keys [codec local?]}] 117 | (let [^DeliveryOptions opts (DeliveryOptions.)] 118 | (.setCodecName opts (or codec "clj:msgpack")) 119 | (when local? (.setLocalOnly opts true)) 120 | opts)) 121 | 122 | 123 | -------------------------------------------------------------------------------- /src/vertx/http.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx.http 8 | "Enables `raw` access to the http facilites of vertx. If you want more 9 | clojure idiomatic api, refer to the `vertx.web` namespace." 10 | (:require [clojure.spec.alpha :as s] 11 | [promesa.core :as p] 12 | [vertx.util :as vu]) 13 | (:import 14 | java.util.Map$Entry 15 | clojure.lang.MapEntry 16 | io.vertx.core.Vertx 17 | io.vertx.core.Verticle 18 | io.vertx.core.Handler 19 | io.vertx.core.Future 20 | io.vertx.core.MultiMap 21 | io.vertx.core.Context 22 | io.vertx.core.buffer.Buffer 23 | io.vertx.core.http.HttpServer 24 | io.vertx.core.http.HttpServerRequest 25 | io.vertx.core.http.HttpServerResponse 26 | io.vertx.core.http.HttpServerOptions)) 27 | 28 | (declare opts->http-server-options) 29 | (declare resolve-handler) 30 | 31 | ;; --- Public Api 32 | 33 | (declare -handle-response) 34 | (declare -handle-body) 35 | 36 | (defn ->headers 37 | [^HttpServerRequest request] 38 | (let [headers (.headers request) 39 | it (.iterator ^MultiMap headers)] 40 | (loop [m (transient {})] 41 | (if (.hasNext it) 42 | (let [^Map$Entry me (.next it) 43 | key (.toLowerCase (.getKey me)) 44 | val (.getValue me)] 45 | (recur (assoc! m key val))) 46 | (persistent! m))))) 47 | 48 | (defn- ->request 49 | [^HttpServerRequest request] 50 | {:method (-> request .rawMethod .toLowerCase keyword) 51 | :path (.path request) 52 | :headers (->headers request) 53 | ::request request 54 | ::response (.response request)}) 55 | 56 | (defn handler 57 | [vsm f] 58 | (reify Handler 59 | (handle [this request] 60 | (let [ctx (->request request)] 61 | (-handle-response (f ctx) ctx))))) 62 | 63 | (s/def :vertx.http/handler fn?) 64 | (s/def :vertx.http/host string?) 65 | (s/def :vertx.http/port pos?) 66 | (s/def ::server-options 67 | (s/keys :req-un [:vertx.http/handler] 68 | :opt-un [:vertx.http/host 69 | :vertx.http/port])) 70 | 71 | (defn server 72 | "Starts a vertx http server." 73 | [vsm {:keys [handler] :as options}] 74 | (s/assert ::server-options options) 75 | (let [^Vertx vsm (vu/resolve-system vsm) 76 | ^HttpServerOptions opts (opts->http-server-options options) 77 | ^HttpServer srv (.createHttpServer vsm opts) 78 | ^Handler handler (resolve-handler handler)] 79 | (doto srv 80 | (.requestHandler handler) 81 | (.listen)) 82 | srv)) 83 | 84 | ;; --- Impl 85 | 86 | (defn- opts->http-server-options 87 | [{:keys [host port]}] 88 | (let [opts (HttpServerOptions.)] 89 | (.setReuseAddress opts true) 90 | (.setReusePort opts true) 91 | (.setTcpNoDelay opts true) 92 | (.setTcpFastOpen opts true) 93 | (when host (.setHost opts host)) 94 | (when port (.setPort opts port)) 95 | opts)) 96 | 97 | (defn- resolve-handler 98 | [handler] 99 | (cond 100 | (fn? handler) (vu/fn->handler handler) 101 | (instance? Handler handler) handler 102 | :else (throw (ex-info "invalid handler" {})))) 103 | 104 | (defprotocol IAsyncResponse 105 | (-handle-response [_ _])) 106 | 107 | (defprotocol IAsyncBody 108 | (-handle-body [_ _])) 109 | 110 | (extend-protocol IAsyncResponse 111 | java.util.concurrent.CompletionStage 112 | (-handle-response [data ctx] 113 | (p/then' data #(-handle-response % ctx))) 114 | 115 | clojure.lang.IPersistentMap 116 | (-handle-response [data ctx] 117 | (let [status (or (:status data) 200) 118 | body (:body data) 119 | res (::response ctx)] 120 | (.setStatusCode ^HttpServerResponse res status) 121 | (-handle-body body res)))) 122 | 123 | (extend-protocol IAsyncBody 124 | (Class/forName "[B") 125 | (-handle-body [data res] 126 | (.end ^HttpServerResponse res (Buffer/buffer data))) 127 | 128 | Buffer 129 | (-handle-body [data res] 130 | (.end ^HttpServerResponse res ^Buffer data)) 131 | 132 | nil 133 | (-handle-body [data res] 134 | (.putHeader ^HttpServerResponse res "content-length" "0") 135 | (.end ^HttpServerResponse res)) 136 | 137 | String 138 | (-handle-body [data res] 139 | (let [length (count data)] 140 | (.putHeader ^HttpServerResponse res "content-length" (str length)) 141 | (.end ^HttpServerResponse res data)))) 142 | -------------------------------------------------------------------------------- /src/vertx/util.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx.util 8 | (:require [promesa.core :as p]) 9 | (:import io.vertx.core.Vertx 10 | io.vertx.core.Handler 11 | io.vertx.core.Context 12 | io.vertx.core.AsyncResult 13 | java.util.function.Supplier)) 14 | 15 | (defn resolve-system 16 | [o] 17 | (cond 18 | (instance? Vertx o) o 19 | (instance? Context o) (.owner ^Context o) 20 | :else (throw (ex-info "unexpected parameters" {})))) 21 | 22 | (defn fn->supplier 23 | [f] 24 | (reify Supplier 25 | (get [_] (f)))) 26 | 27 | (defn fn->handler 28 | [f] 29 | (reify Handler 30 | (handle [_ v] 31 | (f v)))) 32 | 33 | (defn deferred->handler 34 | [d] 35 | (reify Handler 36 | (handle [_ ar] 37 | (if (.failed ar) 38 | (p/reject! d (.cause ar)) 39 | (p/resolve! d (.result ar)))))) 40 | 41 | -------------------------------------------------------------------------------- /src/vertx/web.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx.web 8 | "High level api for http servers." 9 | (:require [clojure.spec.alpha :as s] 10 | [promesa.core :as p] 11 | [sieppari.core :as sp] 12 | [reitit.core :as rt] 13 | [vertx.http :as vh] 14 | [vertx.util :as vu]) 15 | (:import 16 | clojure.lang.Keyword 17 | clojure.lang.IPersistentMap 18 | io.vertx.core.Vertx 19 | io.vertx.core.Handler 20 | io.vertx.core.Future 21 | io.vertx.core.buffer.Buffer 22 | io.vertx.core.http.Cookie 23 | io.vertx.core.http.HttpServer 24 | io.vertx.core.http.HttpServerRequest 25 | io.vertx.core.http.HttpServerResponse 26 | io.vertx.core.http.HttpServerOptions 27 | io.vertx.ext.web.Route 28 | io.vertx.ext.web.Router 29 | io.vertx.ext.web.RoutingContext 30 | io.vertx.ext.web.handler.BodyHandler 31 | io.vertx.ext.web.handler.StaticHandler 32 | io.vertx.ext.web.handler.ResponseTimeHandler 33 | io.vertx.ext.web.handler.LoggerHandler)) 34 | 35 | ;; --- Public Api 36 | 37 | (s/def ::wrap-handler 38 | (s/or :fn fn? 39 | :vec (s/every fn? :kind vector?))) 40 | 41 | (defn- ->request 42 | [^RoutingContext routing-context] 43 | (let [^HttpServerRequest request (.request ^RoutingContext routing-context) 44 | ^HttpServerResponse response (.response ^RoutingContext routing-context) 45 | ^Vertx system (.vertx routing-context)] 46 | {:body (.getBody routing-context) 47 | :path (.path request) 48 | :method (-> request .rawMethod .toLowerCase keyword) 49 | ::request request 50 | ::response response 51 | ::execution-context (.getContext system) 52 | ::routing-context routing-context})) 53 | 54 | (defn handler 55 | "Wraps a user defined funcion based handler into a vertx-web aware 56 | handler (with support for multipart uploads. 57 | 58 | If the handler is a vector, the sieppari intercerptos engine will be used 59 | to resolve the execution of the interceptors + handler." 60 | [vsm & handlers] 61 | (let [^Vertx vsm (vu/resolve-system vsm) 62 | ^Router router (Router/router vsm)] 63 | (reduce #(%2 %1) router handlers))) 64 | 65 | (defn assets 66 | ([path] (assets path {})) 67 | ([path {:keys [root] :or {root "public"} :as options}] 68 | (fn [^Router router] 69 | (let [^Route route (.route router path) 70 | ^Handler handler (doto (StaticHandler/create) 71 | (.setWebRoot root) 72 | (.setDirectoryListing true))] 73 | (.handler route handler) 74 | router)))) 75 | 76 | (defn- default-handler 77 | [ctx] 78 | (if (::match ctx) 79 | {:status 405} 80 | {:status 404})) 81 | 82 | (defn- run-chain 83 | [ctx chain handler] 84 | (let [d (p/deferred)] 85 | (sp/execute (conj chain handler) ctx #(p/resolve! d %) #(p/reject! d %)) 86 | d)) 87 | 88 | (defn- router-handler 89 | [router {:keys [path method] :as ctx}] 90 | (let [{:keys [data path-params] :as match} (rt/match-by-path router path) 91 | handler-fn (or (get data method) 92 | (get data :all) 93 | default-handler) 94 | interceptors (get data :interceptors) 95 | ctx (assoc ctx ::match match :path-params path-params)] 96 | (if (empty? interceptors) 97 | (handler-fn ctx) 98 | (run-chain ctx interceptors handler-fn)))) 99 | 100 | (defn router 101 | ([routes] (router routes {})) 102 | ([routes {:keys [delete-uploads? 103 | upload-dir 104 | log-requests? 105 | time-response?] 106 | :or {delete-uploads? true 107 | upload-dir "/tmp/vertx.uploads" 108 | log-requests? false 109 | time-response? true} 110 | :as options}] 111 | (let [rtr (rt/router routes options) 112 | f #(router-handler rtr %)] 113 | (fn [^Router router] 114 | (let [^Route route (.route router)] 115 | (when time-response? (.handler route (ResponseTimeHandler/create))) 116 | (when log-requests? (.handler route (LoggerHandler/create))) 117 | (.handler route (doto (BodyHandler/create true) 118 | (.setDeleteUploadedFilesOnEnd delete-uploads?) 119 | (.setUploadsDirectory upload-dir))) 120 | (.handler route (reify Handler 121 | (handle [_ context] 122 | (let [req (->request context)] 123 | (-> (p/do! (f req)) 124 | (p/then' #(vh/-handle-response % req)) 125 | (p/catch #(.fail (::routing-context req) %)))))))) 126 | router)))) 127 | -------------------------------------------------------------------------------- /src/vertx/web/interceptors.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx.web.interceptors 8 | "High level api for http servers." 9 | (:require 10 | [clojure.spec.alpha :as s] 11 | [clojure.string :as str] 12 | [promesa.core :as p] 13 | [reitit.core :as r] 14 | [vertx.web :as vw] 15 | [sieppari.context :as spx] 16 | [sieppari.core :as sp]) 17 | (:import 18 | clojure.lang.Keyword 19 | clojure.lang.MapEntry 20 | java.util.Map 21 | java.util.Map$Entry 22 | io.vertx.core.Vertx 23 | io.vertx.core.Handler 24 | io.vertx.core.Future 25 | io.vertx.core.http.Cookie 26 | io.vertx.core.http.HttpServerRequest 27 | io.vertx.core.http.HttpServerResponse 28 | io.vertx.ext.web.FileUpload 29 | io.vertx.ext.web.RoutingContext)) 30 | 31 | ;; --- Cookies 32 | 33 | (defn- build-cookie 34 | [name data] 35 | (cond-> (Cookie/cookie ^String name ^String (:value data)) 36 | (:http-only data) (.setHttpOnly true) 37 | (:domain data) (.setDomain (:domain data)) 38 | (:path data) (.setPath (:path data)) 39 | (:secure data) (.setSecure true))) 40 | 41 | (defn cookies 42 | [] 43 | {:enter (fn [data] 44 | (let [^HttpServerRequest req (get-in data [:request ::vw/request]) 45 | parse-cookie (fn [^Cookie item] [(.getName item) (.getValue item)]) 46 | cookies (into {} (map parse-cookie) (vals (.cookieMap req)))] 47 | (update data :request assoc :cookies cookies))) 48 | :leave (fn [data] 49 | (let [cookies (get-in data [:response :cookies]) 50 | ^HttpServerResponse res (get-in data [:request ::vw/response])] 51 | (when (map? cookies) 52 | (reduce-kv #(.addCookie res (build-cookie %1 %2)) nil cookies)) 53 | data))}) 54 | ;; --- Headers 55 | 56 | (def ^:private lowercase-keys-t 57 | (map (fn [^Map$Entry entry] 58 | (MapEntry. (.toLowerCase (.getKey entry)) (.getValue entry))))) 59 | 60 | (defn- parse-headers 61 | [req] 62 | (let [^HttpServerRequest request (::vw/request req)] 63 | (into {} lowercase-keys-t (.headers request)))) 64 | 65 | (defn headers 66 | [] 67 | {:enter (fn [data] 68 | (update data :request assoc :headers (parse-headers (:request data)))) 69 | :leave (fn [data] 70 | (let [^HttpServerResponse res (get-in data [:request ::vw/response]) 71 | headers (get-in data [:response :headers])] 72 | (run! (fn [[key value]] 73 | (.putHeader ^HttpServerResponse res 74 | ^String (name key) 75 | ^String (str value))) 76 | headers) 77 | data))}) 78 | 79 | ;; --- Params 80 | 81 | (defn- parse-param-entry 82 | [acc ^Map$Entry item] 83 | (let [key (keyword (.toLowerCase (.getKey item))) 84 | prv (get acc key ::default)] 85 | (cond 86 | (= prv ::default) 87 | (assoc! acc key (.getValue item)) 88 | 89 | (vector? prv) 90 | (assoc! acc key (conj prv (.getValue item))) 91 | 92 | :else 93 | (assoc! acc key [prv (.getValue item)])))) 94 | 95 | (defn- parse-params 96 | [req] 97 | (let [request (::vw/request req)] 98 | (persistent! 99 | (reduce parse-param-entry 100 | (transient {}) 101 | (.params ^HttpServerResponse request))))) 102 | 103 | (defn params 104 | ([] (params nil)) 105 | ([{:keys [attr] :or {attr :params}}] 106 | {:enter (fn [data] 107 | (let [params (parse-params (:request data))] 108 | (update data :request assoc attr params)))})) 109 | 110 | ;; --- Uploads 111 | 112 | (defn uploads 113 | ([] (uploads nil)) 114 | ([{:keys [attr] :or {attr :uploads}}] 115 | {:enter (fn [data] 116 | (let [context (get-in data [:request ::vw/routing-context]) 117 | uploads (reduce (fn [acc ^FileUpload upload] 118 | (assoc acc 119 | (keyword (.name upload)) 120 | {:type :uploaded-file 121 | :mtype (.contentType upload) 122 | :path (.uploadedFileName upload) 123 | :name (.fileName upload) 124 | :size (.size upload)})) 125 | (transient {}) 126 | (.fileUploads ^RoutingContext context))] 127 | (update data :request assoc attr (persistent! uploads))))})) 128 | 129 | ;; --- CORS 130 | 131 | (s/def ::origin string?) 132 | (s/def ::allow-credentials boolean?) 133 | (s/def ::allow-methods (s/every keyword? :kind set?)) 134 | (s/def ::allow-headers (s/every keyword? :kind set?)) 135 | (s/def ::expose-headers (s/every keyword? :kind set?)) 136 | (s/def ::max-age number?) 137 | 138 | (s/def ::cors-opts 139 | (s/keys :req-un [::origin] 140 | :opt-un [::allow-headers 141 | ::allow-methods 142 | ::expose-headers 143 | ::max-age])) 144 | 145 | (defn cors 146 | [opts] 147 | (s/assert ::cors-opts opts) 148 | (letfn [(preflight? [{:keys [method headers] :as ctx}] 149 | (and (= method :options) 150 | (contains? headers "origin") 151 | (contains? headers "access-control-request-method"))) 152 | 153 | (normalize [data] 154 | (str/join ", " (map name data))) 155 | 156 | (allow-origin? [headers] 157 | (let [origin (:origin opts) 158 | value (get headers "origin")] 159 | (cond 160 | (nil? value) value 161 | (= origin "*") origin 162 | (set? origin) (origin value) 163 | (= origin value) origin))) 164 | 165 | (get-headers [{:keys [headers] :as ctx}] 166 | (when-let [origin (allow-origin? headers)] 167 | (cond-> {"access-control-allow-origin" origin 168 | "access-control-allow-methods" "GET, OPTIONS, HEAD"} 169 | 170 | (:allow-methods opts) 171 | (assoc "access-control-allow-methods" 172 | (-> (normalize (:allow-methods opts)) 173 | (str/upper-case))) 174 | 175 | (:allow-credentials opts) 176 | (assoc "access-control-allow-credentials" "true") 177 | 178 | (:expose-headers opts) 179 | (assoc "access-control-expose-headers" 180 | (-> (normalize (:expose-headers opts)) 181 | (str/lower-case))) 182 | 183 | (:max-age opts) 184 | (assoc "access-control-max-age" (:max-age opts)) 185 | 186 | (:allow-headers opts) 187 | (assoc "access-control-allow-headers" 188 | (-> (normalize (:allow-headers opts)) 189 | (str/lower-case)))))) 190 | 191 | (enter [data] 192 | (let [ctx (:request data)] 193 | (if (preflight? ctx) 194 | (spx/terminate (assoc data ::preflight true)) 195 | data))) 196 | 197 | (leave [data] 198 | (let [headers (get-headers (:request data))] 199 | (if (::preflight data) 200 | (assoc data :response {:status 204 :headers headers}) 201 | (update-in data [:response :headers] merge headers))))] 202 | 203 | {:enter enter 204 | :leave leave})) 205 | -------------------------------------------------------------------------------- /test/user.clj: -------------------------------------------------------------------------------- 1 | (ns user 2 | (:require 3 | [clojure.pprint :refer [pprint]] 4 | [clojure.test :as test] 5 | [clojure.tools.namespace.repl :as r] 6 | [clojure.walk :refer [macroexpand-all]] 7 | [mount.core :as mount :refer [defstate]] 8 | [pohjavirta.server :as pohjavirta] 9 | [promesa.core :as p] 10 | [reitit.core :as rt] 11 | [jsonista.core :as j] 12 | [vertx.core :as vc] 13 | [vertx.eventbus :as ve] 14 | [vertx.http :as vh] 15 | [vertx.web :as vw] 16 | [vertx.web.interceptors :as vwi]) 17 | (:import 18 | io.vertx.core.http.HttpServerRequest 19 | io.vertx.core.http.HttpServerResponse)) 20 | 21 | (declare thr-name) 22 | 23 | ;; --- System 24 | 25 | (defstate system 26 | :start (vc/system) 27 | :stop (.close system)) 28 | 29 | ;; --- Echo Verticle (using eventbus) 30 | 31 | ;; (def echo-verticle 32 | ;; (letfn [(on-message [message] 33 | ;; (println (pr-str "received:" message 34 | ;; "on" (thr-name))) 35 | ;; (:body message)) 36 | ;; (on-start [ctx] 37 | ;; (vxe/consumer ctx "test.echo" on-message))] 38 | 39 | ;; (vc/verticle {:on-start on-start}))) 40 | 41 | ;; (defstate echo-verticle 42 | ;; :start @(vc/deploy! system echo-verticle options)) 43 | 44 | ;; --- Echo Verticle Actor (using eventbus) 45 | 46 | ;; This is the same as the previous echo verticle, it just reduces the 47 | ;; boilerplate of creating the consumer. 48 | 49 | ;; (def echo-actor-verticle 50 | ;; (letfn [(on-message [message] 51 | ;; (println (pr-str "received:" (.body message) 52 | ;; "on" (thr-name))) 53 | ;; (.body message))] 54 | ;; (vc/actor "test.echo2" {:on-message on-message}))) 55 | 56 | ;; (defstate echo-actor-verticle 57 | ;; :start @(vc/deploy! system echo-actor-verticle options)) 58 | 59 | ;; --- Http Server Verticle 60 | 61 | (def http-verticle 62 | (letfn [(simple-handler [req] 63 | ;; (prn req) 64 | {:status 200 65 | :body (j/write-value-as-string 66 | {:method (:method req) 67 | :headers (:headers req) 68 | :path (:path req)})}) 69 | 70 | (on-start [ctx] 71 | (let [handler (vh/handler ctx simple-handler)] 72 | (vh/server ctx {:handler handler :port 2020})))] 73 | (vc/verticle {:on-start on-start}))) 74 | 75 | (defstate http-server-verticle 76 | :start @(vc/deploy! system http-verticle {:instances 2})) 77 | 78 | ;; --- Web Router Verticle 79 | 80 | (def web-router-verticle 81 | (letfn [(simple-handler [req] 82 | {:status 200 83 | :body (j/write-value-as-string 84 | {:method (:method req) 85 | :path (:path req)})}) 86 | 87 | (on-start [ctx] 88 | (let [routes [["/" {:all simple-handler}]] 89 | handler (vw/handler ctx (vw/router routes))] 90 | (vh/server ctx {:handler handler :port 2021})))] 91 | (vc/verticle {:on-start on-start}))) 92 | 93 | (defstate web-server-with-router-verticle 94 | :start @(vc/deploy! system web-router-verticle {:instances 2})) 95 | 96 | ;; --- pohjavirta 97 | 98 | (defn handler 99 | [req] 100 | {:status 200 101 | :body (j/write-value-as-string 102 | {:method (:request-method req) 103 | :headers (:headers req) 104 | :path (:uri req)})}) 105 | 106 | (defstate pohjavirta-server 107 | :start (let [instance (pohjavirta/create #'handler {:port 2022 :io-threads 2})] 108 | (pohjavirta/start instance) 109 | instance) 110 | :stop (pohjavirta/stop pohjavirta-server)) 111 | 112 | ;; --- Repl 113 | 114 | (defn start 115 | [] 116 | (mount/start)) 117 | 118 | (defn stop 119 | [] 120 | (mount/stop)) 121 | 122 | (defn restart 123 | [] 124 | (stop) 125 | (r/refresh :after 'user/start)) 126 | 127 | (defn- run-test 128 | ([] (run-test #"^vertx-tests.*")) 129 | ([o] 130 | (r/refresh) 131 | (cond 132 | (instance? java.util.regex.Pattern o) 133 | (test/run-all-tests o) 134 | 135 | (symbol? o) 136 | (if-let [sns (namespace o)] 137 | (do (require (symbol sns)) 138 | (test/test-vars [(resolve o)])) 139 | (test/test-ns o))))) 140 | 141 | ;; --- Helpers 142 | 143 | (defn thr-name 144 | [] 145 | (.getName (Thread/currentThread))) 146 | 147 | -------------------------------------------------------------------------------- /test/vertx_tests/main.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx-tests.main 8 | (:require [clojure.test :as t])) 9 | 10 | (defn -main 11 | [& args] 12 | (let [{:keys [fail]} (t/run-all-tests #"^vertx-tests.*")] 13 | (if (pos? fail) 14 | (System/exit fail) 15 | (System/exit 0)))) 16 | -------------------------------------------------------------------------------- /test/vertx_tests/test_core.clj: -------------------------------------------------------------------------------- 1 | ;; This Source Code Form is subject to the terms of the Mozilla Public 2 | ;; License, v. 2.0. If a copy of the MPL was not distributed with this 3 | ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. 4 | ;; 5 | ;; Copyright (c) 2019 Andrey Antukh 6 | 7 | (ns vertx-tests.test-core 8 | (:require [clojure.test :as t] 9 | [vertx.core :as vx] 10 | [vertx.eventbus :as vxe])) 11 | 12 | (def sleep #(Thread/sleep %)) 13 | 14 | (t/deftest start-stop-verticle 15 | (with-open [vsm (vx/system)] 16 | (let [state (atom {})] 17 | (let [on-start (fn [_] (swap! state assoc :start true) {:a 1}) 18 | on-stop (fn [_ s] (swap! state assoc :stop true :inner (:a s))) 19 | verticle (vx/verticle {:on-start on-start :on-stop on-stop})] 20 | ;; Start and stop verticle 21 | (.close @(vx/deploy! vsm verticle)) 22 | 23 | ;; Checks 24 | (t/is (:start @state)) 25 | (t/is (:stop @state)) 26 | (t/is (= (:inner @state) 1)))))) 27 | 28 | (t/deftest start-stop-actor 29 | (with-open [vsm (vx/system)] 30 | (let [state (atom {})] 31 | (let [on-start (fn [_] (swap! state assoc :start true) {:a 1}) 32 | on-stop (fn [_ s] (swap! state assoc :stop true :inner (:a s))) 33 | rcvlock (promise) 34 | on-message #(deliver rcvlock %2) 35 | verticle (vx/actor "test.topic" {:on-message on-message 36 | :on-start on-start 37 | :on-stop on-stop})] 38 | (with-open [vid @(vx/deploy! vsm verticle)] 39 | ;; Checks 40 | (t/is (true? (:start @state))) 41 | (t/is (nil? (:stop @state))) 42 | 43 | (vxe/send! vsm "test.topic" {:num 1}) 44 | 45 | ;; Checks 46 | (t/is (vxe/message? @rcvlock)) 47 | (t/is (= {:num 1} (:body @rcvlock)))) 48 | 49 | (t/is (= (:inner @state) 1)) 50 | (t/is (true? (:stop @state))))))) 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /tools.clj: -------------------------------------------------------------------------------- 1 | (require '[clojure.java.shell :as shell] 2 | '[clojure.main]) 3 | (require '[rebel-readline.core] 4 | '[rebel-readline.clojure.main] 5 | '[rebel-readline.clojure.line-reader] 6 | '[rebel-readline.clojure.service.local]) 7 | 8 | (defmulti task first) 9 | 10 | (defmethod task :default 11 | [args] 12 | (let [all-tasks (-> task methods (dissoc :default) keys sort) 13 | interposed (->> all-tasks (interpose ", ") (apply str))] 14 | (println "Unknown or missing task. Choose one of:" interposed) 15 | (System/exit 1))) 16 | 17 | (task *command-line-args*) 18 | --------------------------------------------------------------------------------