├── .github └── workflows │ └── maven.yml ├── .gitignore ├── LICENSE ├── README.md ├── pom.xml ├── src ├── main │ ├── examples │ │ └── com │ │ │ └── github │ │ │ └── forax │ │ │ └── loom │ │ │ └── actor │ │ │ └── examples │ │ │ ├── ChainMain.java │ │ │ ├── ChatRoomMain.java │ │ │ ├── HelloMain.java │ │ │ ├── HelloSpawnMain.java │ │ │ ├── HttpMain.java │ │ │ ├── PingPongMain.java │ │ │ └── RestartMain.java │ └── java │ │ └── com │ │ └── github │ │ └── forax │ │ └── loom │ │ └── actor │ │ ├── Actor.java │ │ └── http │ │ └── HttpServer.java └── test │ └── java │ └── com │ └── github │ └── forax │ └── loom │ └── actor │ └── ActorTest.java └── todo.html /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: [ master ] 4 | pull_request: 5 | branches: [ master ] 6 | schedule: 7 | - cron: '0 7 * * *' 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | java: [ '21' ] 15 | name: Java ${{ matrix.Java }} 16 | steps: 17 | - uses: actions/checkout@v3 18 | - name: setup 19 | uses: actions/setup-java@v3 20 | with: 21 | distribution: zulu 22 | java-version: ${{ matrix.java }} 23 | - name: build 24 | run: | 25 | mvn -B package 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | -------------------------------------------------------------------------------- /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 | # Loom Actor 2 | A small but fun actor framework based on loom 3 | 4 | Loom is now fully integrated into the jdk 21 5 | [https://jdk.java.net/](https://jdk.java.net/). 6 | 7 | ## How to use the API 8 | 9 | The class `Actor` defines an actor like an actor in Erlang or Akka. 10 | An actor uses a virtual thread (also called coroutine) to run, it consumes messages from dedicated message queue 11 | and can post messages to other actors. 12 | 13 | Unlike a traditional actor system, the messages are lambdas that do a method call so the actor API is 14 | a class (or an enum, a record or even a lambda). 15 | 16 | Moreover, the Actor API defines 3 different contexts 17 | - the startup context, inside the consumer of `Actor.run(actor, code)`, the actions available are 18 | `postTo(actor, message)` to post a message to an actor and `spawn(actor)` to spawn a new actor instance. 19 | - the actor context, inside the `actor.behavior(factory)` of an actor, the actions available are 20 | `currentActor(behaviorType)` to get the current actor, `panic(exception)` to report an exception, 21 | `postTo(actor, message)` to post a message to an actor, `spawn(actor)`to spawn a new actor instance and 22 | `shutdown()` to shutdown the current actor. 23 | - the handler context, inside the `àctor.onSignal(signalHandler)`, the actions available are 24 | `postTo(actor, message)` to post a message to an actor, `restart()` to restart an actor whith a fresh behavior 25 | and `signal(actor, signal)` to send a signal message (an exception or a shutdown) to another actor. 26 | 27 | During the development or tests, there is a debug mode `actor.debugMode(lookupMatcher, isImmutable)` that 28 | checks that all posted messages are immutable. It has a runtime cost that why it's not enable by default. 29 | 30 | ### A simple example 31 | 32 | Here is a simple example, `Actor.of()` create an actor, `behavior(factory)` defines the behavior, all the public 33 | methods are message entry points. `Actors.run(actors, code)` spawn all the actors, run the code and 34 | wait until all the actors are shutdown. In `Actor.run`, we post two messages to the actor, in response to the second 35 | message "end", the actor shutdown itself, unblocking the method `Actor.run`. 36 | 37 | ```java 38 | public class HelloMain { 39 | public static void main(String[] args) throws InterruptedException { 40 | record Hello(Context context) { 41 | public void say(String message) { 42 | System.out.println("Hello " + message); 43 | } 44 | 45 | public void end() { 46 | context.shutdown(); 47 | } 48 | } 49 | 50 | var hello = Actor.of(Hello.class); 51 | hello.behavior(Hello::new); 52 | 53 | Actor.run(List.of(hello), context -> { 54 | context.postTo(hello, $ -> $.say("actors using loom")); 55 | context.postTo(hello, $ -> $.end()); 56 | }); 57 | } 58 | } 59 | ``` 60 | 61 | ### A JSON server example 62 | 63 | Another example is an HTTP server using an actor to implement a REST API using JSON. 64 | The request body and the response body are JSON message that are automatically converted using Jackson. 65 | The annotations @RequestMapping, @RequestBody and @PathVariable works like their Spring Web counterparts. 66 | The last parameter is the actor that should receive a message corresponding to the HTTP response. 67 | 68 | [todo.html](todo.html) is the corresponding web application written in vanilla JavaScript. 69 | To see the application, run the main and use a browser to visit `http://localhost:8080/todo.html`. 70 | 71 | ```java 72 | public class HttpMain { 73 | public static void main(String[] args) throws IOException, InterruptedException { 74 | record Task(long id, String content) {} 75 | record TaskWithoutId(String content) {} 76 | 77 | record TaskController(Context context, List tasks) { 78 | public static TaskController behavior(Context context) { 79 | var tasks = new ArrayList(); 80 | // initial task 81 | tasks.add(new Task(0, "Hello from an http server powered by loom !")); 82 | return new TaskController(context, tasks); 83 | } 84 | 85 | @RequestMapping(path = "/tasks") 86 | public void getAllTasks(Actor>> reply) { 87 | System.err.println("getAllTasks"); 88 | context.postTo(reply, $ -> $.response(OK, tasks)); 89 | } 90 | 91 | @RequestMapping(path = "/tasks", method = POST) 92 | public void createTask(@RequestBody TaskWithoutId taskWithoutId, Actor> reply) { 93 | System.err.println("createTask " + taskWithoutId); 94 | var task = new Task(tasks.size(), taskWithoutId.content); 95 | tasks.add(task); 96 | context.postTo(reply, $ -> $.response(OK, task)); 97 | } 98 | 99 | @RequestMapping(path = "/tasks/{id}", method = DELETE) 100 | public void deleteTask(@PathVariable("id") String id, Actor> reply) { 101 | System.err.println("deleteTask " + id); 102 | var taskId = Integer.parseInt(id); 103 | var removed = tasks.removeIf(task -> task.id == taskId); 104 | if (!removed) { 105 | context.postTo(reply, $ -> $.response(NOT_FOUND, null)); 106 | return; 107 | } 108 | context.postTo(reply, $ -> $.response(OK, null)); 109 | } 110 | } 111 | 112 | var actor = Actor.of(TaskController.class) 113 | .behavior(TaskController::behavior) 114 | .onSignal((signal, context) -> { 115 | context.restart(); // restart if an error occurs 116 | }); 117 | 118 | new HttpServer() 119 | .routes(actor) 120 | .bind(new InetSocketAddress("localhost", 8080)); 121 | } 122 | } 123 | ``` 124 | 125 | There are more examples in the folder [examples](src/main/examples/com/github/forax/loom/actor/examples). 126 | 127 | ## How to build 128 | 129 | Download the latest early access build of jdk 21 [http://jdk.java.net/](http://jdk.java.net/) 130 | set the environment variable JAVA_HOME to point to that JDK and then use Maven. 131 | 132 | ``` 133 | export JAVA_HOME=/path/to/jdk 134 | mvn package 135 | ``` 136 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.forax.loom.actor 8 | loom-actor 9 | jar 10 | 1.0-SNAPSHOT 11 | 12 | 13 | UTF-8 14 | 15 | 16 | 17 | 18 | org.junit.jupiter 19 | junit-jupiter-api 20 | 5.9.3 21 | test 22 | 23 | 24 | org.junit.jupiter 25 | junit-jupiter-engine 26 | 5.9.3 27 | test 28 | 29 | 30 | 31 | com.fasterxml.jackson.core 32 | jackson-core 33 | 2.15.2 34 | 35 | 36 | com.fasterxml.jackson.core 37 | jackson-databind 38 | 2.15.2 39 | 40 | 41 | com.fasterxml.jackson.core 42 | jackson-annotations 43 | 2.15.2 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | org.apache.maven.plugins 52 | maven-compiler-plugin 53 | 3.11.0 54 | 55 | 21 56 | 57 | --enable-preview 58 | 59 | 60 | 61 | 62 | org.apache.maven.plugins 63 | maven-surefire-plugin 64 | 3.1.2 65 | 66 | --enable-preview 67 | 68 | 69 | 70 | org.codehaus.mojo 71 | build-helper-maven-plugin 72 | 3.4.0 73 | 74 | 75 | generate-sources 76 | 77 | add-source 78 | 79 | 80 | 81 | src/main/examples 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/ChainMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | 5 | import static java.util.stream.IntStream.range; 6 | 7 | public class ChainMain { 8 | interface Ping { 9 | void ping(int value); 10 | } 11 | 12 | public static void main(String[] args) throws InterruptedException { 13 | var actors = range(0, 100_000) 14 | .mapToObj(__ -> Actor.of(Ping.class)) 15 | .toList(); 16 | range(0, actors.size()) 17 | .forEach(i -> { 18 | var actor = actors.get(i); 19 | var next = (i == actors.size() - 1)? null: actors.get(i + 1); 20 | actor.behavior(context -> value -> { 21 | if (next == null) { 22 | System.out.println("value " + value); 23 | } else { 24 | context.postTo(next, $ -> $.ping(value + 1)); 25 | } 26 | context.shutdown(); 27 | }); 28 | }); 29 | 30 | Actor.run(actors, context -> { 31 | context.postTo(actors.get(0), $ -> $.ping(1)); 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/ChatRoomMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | import com.github.forax.loom.actor.Actor.Context; 5 | import com.github.forax.loom.actor.Actor.ShutdownSignal; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class ChatRoomMain { 11 | record ChatRoom(Context context, 12 | List> sessions) { 13 | public void getSession(String screenName, Actor client) { 14 | // create a child actor for further interaction with the client 15 | var room = context.currentActor(ChatRoom.class); 16 | var session = Actor.of(Session.class, screenName) 17 | .behavior(context -> new Session(context, room, screenName, client)); 18 | sessions.add(session); 19 | context.spawn(session); 20 | context.postTo(client, $ -> $.sessionGranted(session)); 21 | } 22 | 23 | public void publishSessionMessage(String screenName, String message) { 24 | for(var session: sessions) { 25 | context.postTo(session, $ -> $.notifyClient(screenName, message)); 26 | } 27 | } 28 | } 29 | 30 | record Gabbler(Context context) { 31 | public void sessionDenied(String reason) { 32 | System.err.println("cannot start chat room session: " + reason); 33 | context.shutdown(); 34 | } 35 | 36 | public void sessionGranted(Actor session) { 37 | context.postTo(session, $ -> $.postMessage("Hello World !")); 38 | } 39 | 40 | public void messagePosted(String screenName, String message) { 41 | System.out.println("message has been posted by " + screenName + " " + message); 42 | context.shutdown(); 43 | } 44 | } 45 | 46 | record Session(Context context, 47 | Actor room, String screenName, Actor client) { 48 | public void postMessage(String message) { 49 | context.postTo(room, $ -> $.publishSessionMessage(screenName, message)); 50 | } 51 | 52 | public void notifyClient(String screenName, String message) { 53 | // published from the room 54 | context.postTo(client, $ -> $.messagePosted(screenName, message)); 55 | } 56 | } 57 | 58 | public static void main(String[] args) throws InterruptedException { 59 | var chatRoom = Actor.of(ChatRoom.class) 60 | .behavior(context -> new ChatRoom(context, new ArrayList<>())); 61 | var gabbler = Actor.of(Gabbler.class) 62 | .behavior(Gabbler::new) 63 | .onSignal((signal, context) -> context.signal(chatRoom, ShutdownSignal.INSTANCE)); 64 | 65 | Actor.run(List.of(chatRoom, gabbler), context -> { 66 | context.postTo(chatRoom, $ -> $.getSession("ol’ Gabbler", gabbler)); 67 | }); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/HelloMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | import com.github.forax.loom.actor.Actor.Context; 5 | 6 | import java.util.List; 7 | 8 | public class HelloMain { 9 | public static void main(String[] args) throws InterruptedException { 10 | record Hello(Context context) { 11 | public void say(String message) { 12 | System.out.println("Hello " + message); 13 | } 14 | 15 | public void end() { 16 | context.shutdown(); 17 | } 18 | } 19 | 20 | var hello = Actor.of(Hello.class); 21 | hello.behavior(Hello::new); 22 | 23 | Actor.run(List.of(hello), context -> { 24 | context.postTo(hello, $ -> $.say("actors using loom")); 25 | context.postTo(hello, $ -> $.end()); 26 | }); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/HelloSpawnMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | import com.github.forax.loom.actor.Actor.Context; 5 | import com.github.forax.loom.actor.Actor.ShutdownSignal; 6 | 7 | import java.util.List; 8 | 9 | public class HelloSpawnMain { 10 | public static void main(String[] args) throws InterruptedException { 11 | record Hello(Context context) { 12 | public void say(String message) { 13 | System.out.println("Hello " + message); 14 | } 15 | } 16 | record Callback(Context context) { 17 | public void callHello(Actor hello) { 18 | context.postTo(hello, $ -> $.say("actor using loom")); 19 | } 20 | } 21 | record Manager(Context context) { 22 | public void createHello(Actor callback) { 23 | var hello = Actor.of(Hello.class) 24 | .behavior(Hello::new); 25 | context.spawn(hello); 26 | context.postTo(callback, $ -> $.callHello(hello)); 27 | } 28 | 29 | public void end() { 30 | context.shutdown(); 31 | } 32 | } 33 | 34 | var callback = Actor.of(Callback.class) 35 | .behavior(Callback::new); 36 | var manager = Actor.of(Manager.class) 37 | .behavior(Manager::new) 38 | .onSignal((signal, context) -> context.signal(callback, ShutdownSignal.INSTANCE)); 39 | 40 | Actor.run(List.of(manager, callback), context -> { 41 | context.postTo(manager, $ -> $.createHello(callback)); 42 | context.postTo(manager, $ -> $.end()); 43 | }); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/HttpMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | import com.github.forax.loom.actor.Actor.Context; 5 | import com.github.forax.loom.actor.http.HttpServer; 6 | import com.github.forax.loom.actor.http.HttpServer.PathVariable; 7 | import com.github.forax.loom.actor.http.HttpServer.RequestBody; 8 | import com.github.forax.loom.actor.http.HttpServer.RequestMapping; 9 | import com.github.forax.loom.actor.http.HttpServer.Response; 10 | 11 | import java.io.IOException; 12 | import java.net.InetSocketAddress; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | import static com.github.forax.loom.actor.http.HttpServer.HttpStatus.NOT_FOUND; 17 | import static com.github.forax.loom.actor.http.HttpServer.HttpStatus.OK; 18 | import static com.github.forax.loom.actor.http.HttpServer.RequestMethod.DELETE; 19 | import static com.github.forax.loom.actor.http.HttpServer.RequestMethod.POST; 20 | 21 | public class HttpMain { 22 | public static void main(String[] args) throws IOException, InterruptedException { 23 | record Task(long id, String content) {} 24 | record TaskWithoutId(String content) {} 25 | 26 | record TaskController(Context context, List tasks) { 27 | public static TaskController behavior(Context context) { 28 | var tasks = new ArrayList(); 29 | // initial task 30 | tasks.add(new Task(0, "Hello from an http server powered by loom !")); 31 | return new TaskController(context, tasks); 32 | } 33 | 34 | @RequestMapping(path = "/tasks") 35 | public void getAllTasks(Actor>> reply) { 36 | System.err.println("getAllTasks"); 37 | context.postTo(reply, $ -> $.response(OK, tasks)); 38 | } 39 | 40 | @RequestMapping(path = "/tasks", method = POST) 41 | public void createTask(@RequestBody TaskWithoutId taskWithoutId, Actor> reply) { 42 | System.err.println("createTask " + taskWithoutId); 43 | var task = new Task(tasks.size(), taskWithoutId.content); 44 | tasks.add(task); 45 | context.postTo(reply, $ -> $.response(OK, task)); 46 | } 47 | 48 | @RequestMapping(path = "/tasks/{id}", method = DELETE) 49 | public void deleteTask(@PathVariable("id") String id, Actor> reply) { 50 | System.err.println("deleteTask " + id); 51 | var taskId = Integer.parseInt(id); 52 | var removed = tasks.removeIf(task -> task.id == taskId); 53 | if (!removed) { 54 | context.postTo(reply, $ -> $.response(NOT_FOUND, null)); 55 | return; 56 | } 57 | context.postTo(reply, $ -> $.response(OK, null)); 58 | } 59 | } 60 | 61 | var actor = Actor.of(TaskController.class) 62 | .behavior(TaskController::behavior) 63 | .onSignal((signal, context) -> { 64 | context.restart(); // restart if an error occurs 65 | }); 66 | 67 | new HttpServer() 68 | .routes(actor) 69 | .bind(new InetSocketAddress("localhost", 8080)); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/PingPongMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | import com.github.forax.loom.actor.Actor.Context; 5 | 6 | import java.util.List; 7 | 8 | public class PingPongMain { 9 | record Ping(Context context, Actor pongActor) { 10 | public void ping(int value) { 11 | //System.out.println("actor1 ping " + value); 12 | if (value >= 10_000) { 13 | context.postTo(pongActor, $ -> $.end(value)); 14 | return; 15 | } 16 | context.postTo(pongActor, $ -> $.pong(value + 1)); 17 | } 18 | 19 | public void end() { 20 | System.out.println(context.currentActor(Ping.class) + " end"); 21 | context.shutdown(); 22 | } 23 | } 24 | 25 | record Pong(Context context, Actor pingActor) { 26 | public void pong(int value) { 27 | //System.out.println("actor2 pong " + value); 28 | context.postTo(pingActor, $ -> $.ping(value + 1)); 29 | } 30 | 31 | public void end(int value) { 32 | System.out.println("value " + value); 33 | context.postTo(pingActor, Ping::end); 34 | System.out.println(context.currentActor(Pong.class) + " end"); 35 | context.shutdown(); 36 | } 37 | } 38 | 39 | public static void main(String[] args) throws InterruptedException { 40 | var pingActor = Actor.of(Ping.class); 41 | var pongActor = Actor.of(Pong.class); 42 | 43 | pingActor.behavior(context -> new Ping(context, pongActor)); 44 | pongActor.behavior(context -> new Pong(context, pingActor)); 45 | 46 | Actor.run(List.of(pingActor, pongActor), ctx -> { 47 | ctx.postTo(pingActor, $ -> $.ping(0)); 48 | }); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/examples/com/github/forax/loom/actor/examples/RestartMain.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.examples; 2 | 3 | import com.github.forax.loom.actor.Actor; 4 | import com.github.forax.loom.actor.Actor.PanicSignal; 5 | 6 | import java.util.List; 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | 9 | public class RestartMain { 10 | private static void sleep(long time) { 11 | try { 12 | Thread.sleep(time); 13 | } catch (InterruptedException e) { 14 | throw new AssertionError(e); 15 | } 16 | } 17 | 18 | public static void main(String[] args) throws InterruptedException { 19 | interface Simple { 20 | void message(String text) throws Exception; 21 | } 22 | 23 | var retries = new AtomicInteger(1); 24 | 25 | var simple = Actor.of(Simple.class) 26 | .behavior(context -> new Simple() { 27 | int value; 28 | 29 | @Override 30 | public void message(String text) throws Exception { 31 | System.out.println(text); 32 | throw new Exception("database error " + value++); // always 0, the behavior is reset 33 | } 34 | }) 35 | .onSignal((signal, context) -> { 36 | if (signal instanceof PanicSignal panicSignal) { 37 | //can use signal.exception() here ! 38 | 39 | if (retries.getAndIncrement() < 3) { 40 | context.restart(); 41 | } 42 | } 43 | }); 44 | 45 | Actor.run(List.of(simple), context -> { 46 | context.postTo(simple, $ -> $.message("1")); 47 | sleep(1_000); 48 | context.postTo(simple, $ -> $.message("2")); 49 | sleep(1_000); 50 | context.postTo(simple, $ -> $.message("3")); 51 | sleep(1_000); 52 | context.postTo(simple, $ -> $.message("4")); 53 | }); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/github/forax/loom/actor/Actor.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor; 2 | 3 | import java.io.Serializable; 4 | import java.lang.invoke.MethodHandle; 5 | import java.lang.invoke.MethodHandles; 6 | import java.lang.invoke.MethodHandles.Lookup; 7 | import java.lang.invoke.MethodType; 8 | import java.lang.invoke.SerializedLambda; 9 | import java.lang.invoke.VarHandle; 10 | import java.util.List; 11 | import java.util.Objects; 12 | import java.util.concurrent.ConcurrentSkipListMap; 13 | import java.util.concurrent.LinkedBlockingQueue; 14 | import java.util.concurrent.locks.Condition; 15 | import java.util.concurrent.locks.ReentrantLock; 16 | import java.util.function.Function; 17 | import java.util.function.Predicate; 18 | 19 | /** 20 | * An actor library lika Akka or Erlang. 21 | *

22 | * This library supports either a static description of the actor graph using the method 23 | * {@link #run(List, StartupConsumer)} or a more dynamic approach by {@link Context#spawn(Actor) spawning} 24 | * actors from a parent actor. 25 | * 26 | *

27 | * This actor library has a special API, it uses an interface to describe the 28 | * {@link #behavior(Function) behavior} of an actor i.e all the possible messages that can be received 29 | * and the implementations of those {@link Message messages} are lambdas. 30 | * 31 | *

32 | * An actor is defined by 33 | *

    34 | *
  • a {@link Actor#name() name}
  • 35 | *
  • a {@link Actor#state() state}, either {@link State#CREATED CREATED}, 36 | * {@link State#RUNNING RUNNING} or {@link State#SHUTDOWN SHUTDOWN}.
  • 37 | *
  • a restartable {@link Actor#behavior(Function) behavior}.
  • 38 | *
  • {@link Actor#onSignal(SignalHandler) signal handlers} to react to a {@link Signal signal} that stop 39 | * the actor, either a {@link ShutdownSignal shutdown signal} or a {@link PanicSignal panic exception}.
  • 40 | *
41 | * 42 | * The library defines 3 different contexts 43 | *
    44 | *
  1. the startup context, inside the consumer of {@link Actor#run(List, StartupConsumer) run}, the actions 45 | * available are {@link StartupContext#postTo(Actor, Message) postTo} and {@link Context#spawn(Actor) spawn}.
  2. 46 | *
  3. the actor context, inside the {@link Actor#behavior(Function) behavior} of an actor, the actions available 47 | * are {@link Context#currentActor(Class) currentActor}, {@link Context#panic(Exception) panic}, 48 | * {@link Context#postTo(Actor, Message) postTo}, {@link Context#spawn(Actor) spawn} and 49 | * {@link Context#shutdown() shutdown}.
  4. 50 | *
  5. the handler context, inside the {@link Actor#onSignal(SignalHandler) signal handler}, the actions available 51 | * are {@link HandlerContext#postTo(Actor, Message) postTo}, {@link HandlerContext#restart() restart} and 52 | * {@link HandlerContext#signal(Actor, Signal) signal}.
  6. 53 | *
54 | * 55 | * During the development or tests, there is a debug mode {@link #debugMode(Function, Predicate)} that 56 | * checks that all posted messages are immutable. It has a runtime cost that why it's not enable by default. 57 | *

58 | * The actor and its behavior are declared separately. {@link #of(Class, String) Actor.of()} creates an actor, 59 | * and {@link #behavior(Function) behavior(factory)} associates the behavior to an actor. 60 | *

 61 |  * record Hello(Context context) {
 62 |  *   public void say(String message) {
 63 |  *    System.out.println("Hello " + message);
 64 |  *   }
 65 |  *
 66 |  *   public void end() {
 67 |  *     context.shutdown();
 68 |  *   }
 69 |  * }
 70 |  *
 71 |  * var hello = Actor.of(Hello.class);
 72 |  * hello.behavior(Hello::new);
 73 |  * 
74 | * 75 | * To run as a static configuration, the method {@link #run(List, StartupConsumer)} takes a list of 76 | * actors and start them. Here, we send a message "say" to the actor "hello" and message "end" 77 | * to ask the actor "hello" to gently shutdown itself. 78 | *
 79 |  * Actor.run(List.of(hello), context -> {
 80 |  *     context.postTo(hello, $ -> $.say("actors using loom"));
 81 |  *     context.postTo(hello, $ -> $.end());
 82 |  * });
 83 |  * 
84 | * 85 | * We may also want to spawn the actor "hello" dynamically, for that let's define two others actors, 86 | * the actor "manager" that will create an actor "hello" dynamically and the actor "callback" that will 87 | * receive as parameter the actor "hello" and call it with a message "say". 88 | *
 89 |  * record Manager(Context context) {
 90 |  *   public void createHello(Actor<Callback> callback) {
 91 |  *     var hello = Actor.of(Hello.class)
 92 |  *           .behavior(Hello::new);
 93 |  *     context.spawn(hello);
 94 |  *     context.postTo(callback, $ -> $.callHello(hello));
 95 |  *   }
 96 |  *
 97 |  *   public void end() {
 98 |  *     context.shutdown();
 99 |  *   }
100 |  * }
101 |  *
102 |  * record Callback(Context context) {
103 |  *   public void callHello(Actor<Hello> hello) {
104 |  *     context.postTo(hello, $ -> $.say("actor using loom"));
105 |  *   }
106 |  * }
107 |  * 
108 | * 109 | * In the method "createHello", we create the actor "hello", spawn it and calls the callback with the actor. 110 | * We also register with {@link #onSignal(SignalHandler) onSignal(handler)} the fact that if the actor "manager" 111 | * is shutdown, the actor "callback" should be shutdown too. 112 | *
113 |  * var callback = Actor.of(Callback.class)
114 |  *     .behavior(Callback::new);
115 |  * var manager = Actor.of(Manager.class)
116 |  *     .behavior(Manager::new)
117 |  *     .onSignal((signal, context) -> context.signal(callback, ShutdownSignal.INSTANCE));
118 |  * 
119 | * 120 | * To finish, we run the two actors "manager" and "callback", post a message "createHello" and 121 | * then ask to shut down the manager. This will shut down the actor "hello" because it's a child of "manager" 122 | * and the actor "callback" because we have registered a signal handler to shut down it. 123 | *
124 |  * Actor.run(List.of(manager, callback), context -> {
125 |  *     context.postTo(manager, $ -> $.createHello(callback));
126 |  *     context.postTo(manager, $ -> $.end());
127 |  * });
128 |  * 
129 | * 130 | * @param type of the behavior 131 | */ 132 | public final class Actor { 133 | private static final VarHandle ACTOR_COUNTER, UNCAUGHT_EXCEPTION_HANDLER, STATE, SIGNAL_COUNTER; 134 | static { 135 | var lookup = MethodHandles.lookup(); 136 | try { 137 | ACTOR_COUNTER = lookup.findStaticVarHandle(Actor.class, "actorCounter", int.class); 138 | UNCAUGHT_EXCEPTION_HANDLER = lookup.findStaticVarHandle(Actor.class, "uncaughtExceptionHandler", UncaughtExceptionHandler.class); 139 | STATE = lookup.findVarHandle(Actor.class, "state", State.class); 140 | SIGNAL_COUNTER = lookup.findVarHandle(Actor.class, "signalCounter", int.class); 141 | } catch (NoSuchFieldException | IllegalAccessException e) { 142 | throw new AssertionError(e); 143 | } 144 | } 145 | private static final UncaughtExceptionHandler DEFAULT_UNCAUGHT_EXCEPTION_HANDLER = (actor, exception) -> { 146 | System.err.println("In actor " + actor.name + ":"); 147 | //noinspection CallToPrintStackTrace 148 | exception.printStackTrace(); 149 | }; 150 | @SuppressWarnings("FieldMayBeFinal") 151 | private static volatile UncaughtExceptionHandler uncaughtExceptionHandler = DEFAULT_UNCAUGHT_EXCEPTION_HANDLER; 152 | @SuppressWarnings("FieldMayBeFinal") 153 | private static volatile int actorCounter = 1; 154 | private static final StackLocal> CURRENT_ACTOR = StackLocal.newInstance(); 155 | private final Thread ownerThread; 156 | private final Class behaviorType; 157 | private final String name; 158 | private final LinkedBlockingQueue> mailbox = new LinkedBlockingQueue<>(); 159 | @SuppressWarnings("unused") 160 | private volatile int signalCounter; // grow monotonically so the registered handlers are in the right order 161 | private final ConcurrentSkipListMap signalHandlers = new ConcurrentSkipListMap<>(); 162 | private /*stable*/ Function behaviorFactory; 163 | private volatile State state = State.CREATED; 164 | 165 | // use jdk.incubator.concurrent.ScopeLocal if available at runtime or java.lang.ThreadLocal otherwise 166 | private record StackLocal(Object stackLocal) { 167 | private static final boolean SCOPE_LOCAL_AVAILABLE; 168 | static { 169 | boolean scopeLocalAvailable; 170 | try { 171 | Class.forName("jdk.incubator.concurrent.ScopeLocal"); 172 | scopeLocalAvailable = true; 173 | } catch(ClassNotFoundException e) { 174 | scopeLocalAvailable = false; 175 | } 176 | SCOPE_LOCAL_AVAILABLE = scopeLocalAvailable; 177 | } 178 | 179 | @SuppressWarnings("unchecked") 180 | public boolean isBound() { 181 | if (SCOPE_LOCAL_AVAILABLE) { 182 | return ((ScopedValue) stackLocal).isBound(); 183 | } 184 | return ((ThreadLocal) stackLocal).get() != null; 185 | } 186 | 187 | @SuppressWarnings("unchecked") 188 | public T get() { 189 | if (SCOPE_LOCAL_AVAILABLE) { 190 | return ((ScopedValue) stackLocal).get(); 191 | } 192 | return ((ThreadLocal) stackLocal).get(); 193 | } 194 | 195 | @SuppressWarnings("unchecked") 196 | public static void where(StackLocal stackLocal, T value, Runnable runnable) { 197 | if (SCOPE_LOCAL_AVAILABLE) { 198 | ScopedValue.where((ScopedValue) stackLocal.stackLocal, value).run(runnable); 199 | } else { 200 | var threadLocal = (ThreadLocal) stackLocal.stackLocal; 201 | threadLocal.set(value); 202 | try { 203 | runnable.run(); 204 | } finally { 205 | threadLocal.remove(); 206 | } 207 | } 208 | } 209 | 210 | public static StackLocal newInstance() { 211 | if (SCOPE_LOCAL_AVAILABLE) { 212 | return new StackLocal<>(ScopedValue.newInstance()); 213 | } 214 | return new StackLocal<>(new ThreadLocal<>()); 215 | } 216 | } 217 | 218 | /** 219 | * State of an actor 220 | */ 221 | public enum State { 222 | /** 223 | * state of the actor after calling {@link #of(Class, String)} 224 | */ 225 | CREATED, 226 | /** 227 | * state of the actor when running either after calling {@link #run(List, StartupConsumer)} 228 | * or {@link Context#spawn(Actor)}. 229 | */ 230 | RUNNING, 231 | /** 232 | * state of the actor after calling {@link Context#shutdown()}. 233 | */ 234 | SHUTDOWN 235 | } 236 | 237 | /** 238 | * Used when the state of the actor is incompatible with the operation. 239 | */ 240 | public static class IllegalActorStateException extends RuntimeException { 241 | /** 242 | * Create an IllegalActorStateException with a message 243 | * @param message a message 244 | */ 245 | public IllegalActorStateException(String message) { 246 | super(message); 247 | } 248 | 249 | /** 250 | * Create an IllegalActorStateException with a cause 251 | * @param cause a cause 252 | */ 253 | public IllegalActorStateException(Throwable cause) { 254 | super(cause); 255 | } 256 | 257 | /** 258 | * Create an IllegalActorStateException with a message and a cause 259 | * @param message a message 260 | * @param cause a cause 261 | */ 262 | public IllegalActorStateException(String message, Throwable cause) { 263 | super(message, cause); 264 | } 265 | } 266 | 267 | /** 268 | * A message that can be post to the mailbox of an actor. 269 | * @param type of behavior of an actor 270 | * 271 | * @see Context#postTo(Actor, Message) 272 | */ 273 | @FunctionalInterface 274 | public interface Message extends Serializable { 275 | void accept(B behavior) throws Exception; 276 | } 277 | 278 | public interface StartupConsumer { 279 | void accept(StartupContext context) throws X; 280 | } 281 | 282 | /** 283 | * A signal with two possible implementation {@link ShutdownSignal} and {@link PanicSignal}. 284 | */ 285 | public sealed interface Signal { } 286 | 287 | /** 288 | * A shutdown signal 289 | */ 290 | public enum ShutdownSignal implements Signal { 291 | /** 292 | * The singleton instance of a ShutdownSignal. 293 | */ 294 | INSTANCE 295 | } 296 | 297 | /** 298 | * A signal containing an exception 299 | */ 300 | public record PanicSignal(Exception exception) implements Signal { 301 | public PanicSignal { 302 | Objects.requireNonNull(exception); 303 | } 304 | } 305 | 306 | /** 307 | * Method called when an exception or a shutdown signal is raised. 308 | * 309 | * @see #onSignal(SignalHandler) 310 | */ 311 | @FunctionalInterface 312 | public interface SignalHandler { 313 | /** 314 | * Method called with a signal and a context that can be used to try to recover on the signal. 315 | * @param signal the signal 316 | * @param context the context 317 | */ 318 | void handle(Signal signal, HandlerContext context); 319 | } 320 | 321 | /** 322 | * Actions that can be done at startup after the first actors are running 323 | * @see #run(List, StartupConsumer) 324 | */ 325 | public sealed interface StartupContext { 326 | /** 327 | * Post a new message to an actor. 328 | * @param actor the actor that will receive the message 329 | * @param message the message 330 | * @param the type of the behavior 331 | * 332 | * @throws IllegalStateException if the message is not immutable and the debug mode is on 333 | * 334 | * @see #debugMode(Function, Predicate) 335 | */ 336 | void postTo(Actor actor, Message message); 337 | 338 | /** 339 | * Dynamically spawn an actor. 340 | * 341 | * @param actor the actor 342 | * @throws IllegalActorStateException if the actor was created by another thread 343 | */ 344 | void spawn(Actor actor); 345 | } 346 | 347 | /** 348 | * Context used by a signal handler. 349 | * 350 | * @see SignalHandler 351 | */ 352 | public sealed interface HandlerContext { 353 | /** 354 | * Post a new message to an actor. 355 | * @param actor the actor that will receive the message 356 | * @param message the message 357 | * @param the type of the behavior 358 | * 359 | * @throws IllegalStateException if the message is not immutable and the debug mode is on 360 | * 361 | * @see #debugMode(Function, Predicate) 362 | */ 363 | void postTo(Actor actor, Message message); 364 | 365 | /** 366 | * Restart the current actor, cleaning the message queue and resetting the behavior 367 | * to a fresh one. 368 | * 369 | * @see Actor#behavior(Function) 370 | */ 371 | void restart(); 372 | 373 | /** 374 | * Signal a terminaison event to another actor. 375 | * @param actor the actor to signal 376 | * @param signal the signal to send 377 | * @throws IllegalActorStateException if there is no current actor or 378 | * if the current actor is the actor that should receive the signal 379 | */ 380 | void signal(Actor actor, Signal signal); 381 | } 382 | 383 | /** 384 | * Actions that can be done inside the behavior of an actor. 385 | * @see #behavior(Function) 386 | */ 387 | public sealed interface Context { 388 | /** 389 | * Returns the current actor. 390 | * @param behaviorType the type of the behavior 391 | * @return the current actor 392 | * @param the type of the behavior 393 | * @throws IllegalActorStateException if there is no current actor 394 | */ 395 | Actor currentActor(Class behaviorType); 396 | 397 | /** 398 | * Stop the execution of the actor with an exception. 399 | * This method pretend to return an error so it can be used in front of a "throw" 400 | * to explain to the compiler that the control flow stop. 401 | *
402 |      *   DatabaseException exception = ...
403 |      *   throw context.panic(exception);
404 |      * 
405 | * @param exception the exception 406 | */ 407 | Error panic(Exception exception); 408 | 409 | /** 410 | * Post a new message to an actor. 411 | * @param actor the actor that will receive the message 412 | * @param message the message 413 | * @param the type of the behavior 414 | * 415 | * @throws IllegalStateException if the message is not immutable and the debug mode is on 416 | * 417 | * @see #debugMode(Function, Predicate) 418 | */ 419 | void postTo(Actor actor, Message message); 420 | 421 | /** 422 | * Dynamically spawn a new child actor of the current actor. 423 | * When shutdown, the current actor will shut down all children actors first. 424 | * 425 | * @param actor the child actor 426 | * @throws IllegalActorStateException if the child actor was not created by the current actor 427 | */ 428 | void spawn(Actor actor); 429 | 430 | /** 431 | * Process all messages of the mailbox, shutdown the children of the current actor and 432 | * then itself. 433 | * @throws IllegalActorStateException if there is no current actor 434 | */ 435 | void shutdown(); 436 | } 437 | 438 | /** 439 | * Called when an exception occurs. 440 | * This handler should be used for logging purpose only. 441 | * 442 | * @see #uncaughtExceptionHandler(UncaughtExceptionHandler) 443 | */ 444 | @FunctionalInterface 445 | public interface UncaughtExceptionHandler { 446 | /** 447 | * @param actor the actor generating the exception 448 | * @param exception the exception 449 | */ 450 | void uncaughtException(Actor actor, Exception exception); 451 | } 452 | 453 | private static final class SignalMessage implements Message { 454 | private final Signal signal; 455 | private volatile boolean done; 456 | private final ReentrantLock lock = new ReentrantLock(); 457 | private final Condition condition = lock.newCondition(); 458 | 459 | public SignalMessage(Signal signal, boolean done) { 460 | this.signal = signal; 461 | this.done = done; 462 | } 463 | 464 | public void done() { 465 | if (!done) { 466 | lock.lock(); 467 | try { 468 | done = true; 469 | condition.signal(); 470 | } finally { 471 | lock.unlock(); 472 | } 473 | } 474 | } 475 | 476 | public void join() { 477 | InterruptedException interrupted = null; 478 | lock.lock(); 479 | try { 480 | while(!done) { 481 | try { 482 | condition.await(); 483 | } catch (InterruptedException e) { 484 | interrupted = e; 485 | } 486 | } 487 | } finally { 488 | lock.unlock(); 489 | } 490 | if (interrupted != null) { 491 | Thread.currentThread().interrupt(); 492 | } 493 | } 494 | 495 | @Override 496 | public void accept(Object o) { 497 | throw new AssertionError("shutdown"); 498 | } 499 | } 500 | 501 | private static final class PanicError extends Error { 502 | public PanicError(Exception cause) { 503 | super(cause); 504 | } 505 | 506 | @Override 507 | public Exception getCause() { 508 | return (Exception) super.getCause(); 509 | } 510 | } 511 | 512 | private static final class RestartError extends Error { 513 | public RestartError() { 514 | super(null, null, false, false); 515 | } 516 | } 517 | 518 | private static final class ContextImpl implements Context, StartupContext, HandlerContext { 519 | public Actor currentActor(Class behaviorType) { 520 | return currentActor().asActor(behaviorType); 521 | } 522 | 523 | private Actor currentActor() { 524 | if (!CURRENT_ACTOR.isBound()) { 525 | throw new IllegalActorStateException("no current actor"); 526 | } 527 | return CURRENT_ACTOR.get(); 528 | } 529 | 530 | @Override 531 | public Error panic(Exception exception) { 532 | Objects.requireNonNull(exception); 533 | throw new PanicError(exception); 534 | } 535 | 536 | @Override 537 | public void postTo(Actor actor, Message message) { 538 | Objects.requireNonNull(actor); 539 | Objects.requireNonNull(message); 540 | if (Debug.MODE != null) { 541 | Debug.checkMessage(message); 542 | } 543 | actor.mailbox.offer(message); 544 | } 545 | 546 | @Override 547 | public void spawn(Actor actor) { 548 | Objects.requireNonNull(actor); 549 | actor.checkOwner(); 550 | if (actor.behaviorFactory == null) { 551 | throw new IllegalActorStateException(actor.name + " behavior is not defined"); 552 | } 553 | if (CURRENT_ACTOR.isBound()) { 554 | var currentActor = CURRENT_ACTOR.get(); 555 | // shutdown all children 556 | var key = currentActor.addSignalHandler((__, handlerContext) -> handlerContext.signal(actor, ShutdownSignal.INSTANCE)); 557 | // remove the handler if the child is shutdown 558 | actor.addSignalHandler((_1, _2) -> currentActor.removeSignalHandler(key)); 559 | } 560 | startThread(this, actor); 561 | } 562 | 563 | @Override 564 | public void shutdown() { 565 | var currentActor = currentActor(); 566 | var shutdownConsumer = new SignalMessage(ShutdownSignal.INSTANCE, true); // async 567 | currentActor.mailbox.offer(shutdownConsumer); 568 | } 569 | 570 | @Override 571 | public void restart() { 572 | throw new RestartError(); 573 | } 574 | 575 | @Override 576 | public void signal(Actor actor, Signal signal) { 577 | Objects.requireNonNull(actor); 578 | Objects.requireNonNull(signal); 579 | var currentActor = currentActor(); 580 | if (actor == currentActor) { 581 | throw new IllegalActorStateException("an actor can not signal itself"); 582 | } 583 | var signalConsumer = new SignalMessage(signal, false); // synchronous 584 | actor.mailbox.offer(signalConsumer); 585 | signalConsumer.join(); 586 | } 587 | } 588 | 589 | private Actor(Thread ownerThread, Class behaviorType, String name) { 590 | this.ownerThread = ownerThread; 591 | this.behaviorType = behaviorType; 592 | this.name = name; 593 | } 594 | 595 | /** 596 | * Creates an actor with a name. 597 | * @param behaviorType the type of the behavior 598 | * @param name the actor name 599 | * @param the type of the behavior. 600 | * @return a new actor 601 | */ 602 | public static Actor of(Class behaviorType, String name) { 603 | Objects.requireNonNull(behaviorType); 604 | Objects.requireNonNull(name); 605 | return new Actor<>(Thread.currentThread(), behaviorType, name); 606 | } 607 | 608 | /** 609 | * Creates an actor with a name derived from the name of the behavior type. 610 | * @param behaviorType the type of the behavior 611 | * @param the type of the behavior. 612 | * @return a new actor 613 | */ 614 | public static Actor of(Class behaviorType) { 615 | return of(behaviorType, behaviorType.getSimpleName() + (int) ACTOR_COUNTER.getAndAdd(1)); 616 | } 617 | 618 | /** 619 | * Returns the name of the actor. 620 | * The name can be any arbitrary name and is only useful for debugging purpose. 621 | * @return the name of the actor. 622 | * 623 | * @see Actor#of(Class, String) 624 | */ 625 | public String name() { 626 | return name; 627 | } 628 | 629 | /** 630 | * Returns the behavior type. 631 | * @return the behavior type 632 | * 633 | * @see Actor#of(Class, String) 634 | */ 635 | public Class behaviorType() { 636 | return behaviorType; 637 | } 638 | 639 | @Override 640 | public String toString() { 641 | return "Actor(" + name + ")"; 642 | } 643 | 644 | /** 645 | * Returns the state of the actor 646 | * @return the state of the actor 647 | */ 648 | public State state() { 649 | return state; 650 | } 651 | 652 | @SuppressWarnings("unchecked") 653 | private Actor asActor(Class behaviorType) { 654 | Objects.requireNonNull(behaviorType); 655 | if (!behaviorType.isAssignableFrom(this.behaviorType)) { 656 | throw new IllegalActorStateException(name + " does not allow behavior " + behaviorType.getName()); 657 | } 658 | return (Actor) this; 659 | } 660 | 661 | private int addSignalHandler(SignalHandler signalHandler) { 662 | var key = (int) SIGNAL_COUNTER.getAndAdd(this, 1); 663 | signalHandlers.put(key, signalHandler); 664 | return key; 665 | } 666 | 667 | private void removeSignalHandler(int key) { 668 | signalHandlers.remove(key); 669 | } 670 | 671 | private static void logException(Actor actor, Exception exception) { 672 | try { 673 | uncaughtExceptionHandler.uncaughtException(actor, exception); 674 | } catch (Exception e) { 675 | // the global exception handler fails ! 676 | e.addSuppressed(exception); 677 | //noinspection CallToPrintStackTrace 678 | e.printStackTrace(); 679 | } 680 | } 681 | 682 | private static void signalNow(Signal signal, ContextImpl context, Actor actor) { 683 | actor.state = State.SHUTDOWN; 684 | for (var handler : actor.signalHandlers.values()) { 685 | try { 686 | handler.handle(signal, context); 687 | } catch (Exception e) { 688 | logException(actor, new IllegalActorStateException("error in signal handler", e)); 689 | } 690 | } 691 | actor.signalHandlers.clear(); 692 | } 693 | 694 | private static Thread startThread(ContextImpl context, Actor actor) { 695 | if (!STATE.compareAndSet(actor, State.CREATED, State.RUNNING)) { 696 | throw new IllegalActorStateException("actor is already running/shutdown"); 697 | } 698 | //return Thread.ofPlatform().name(actor.name).start(() -> { 699 | return Thread.ofVirtual().name(actor.name).start(() -> { 700 | StackLocal.where(CURRENT_ACTOR, actor, () -> { 701 | var behavior = actor.behaviorFactory.apply(context); 702 | for (;;) { 703 | try { 704 | Message message; 705 | try { 706 | message = actor.mailbox.take(); 707 | } catch (InterruptedException interruptedException) { 708 | signalNow(new PanicSignal(interruptedException), context, actor); 709 | return; 710 | } 711 | if (message instanceof SignalMessage signalMessage) { 712 | try { 713 | signalNow(signalMessage.signal, context, actor); 714 | } finally { 715 | signalMessage.done(); 716 | } 717 | return; 718 | } 719 | try { 720 | message.accept(behavior); 721 | } catch (Exception | PanicError e) { 722 | var exception = e instanceof PanicError panicError ? panicError.getCause() : (Exception) e; 723 | logException(actor, exception); 724 | signalNow(new PanicSignal(exception), context, actor); 725 | return; 726 | } 727 | } catch(@SuppressWarnings("ErrorNotRethrown") RestartError restartError) { 728 | actor.mailbox.clear(); 729 | behavior = actor.behaviorFactory.apply(context); 730 | } 731 | } 732 | }); 733 | }); 734 | } 735 | 736 | private static void joinAll(List threads) throws InterruptedException { 737 | for (var thread : threads) { 738 | thread.join(); 739 | } 740 | } 741 | 742 | private void checkOwner() { 743 | if (ownerThread != Thread.currentThread()) { 744 | throw new IllegalActorStateException(name + " is not created by the current thread"); 745 | } 746 | } 747 | 748 | private void checkStateCreated() { 749 | if (state != State.CREATED) { 750 | throw new IllegalActorStateException(name + " is already running/shutdown"); 751 | } 752 | } 753 | 754 | /** 755 | * Set the behavior of an actor. 756 | * @param behavior the actor's behavior 757 | * @return the current actor so method calls can be chained 758 | * @throws IllegalActorStateException if the current thread is not the one that have created the actor, 759 | * if the actor is already running/shutdown or if the actor's behavior is already set 760 | */ 761 | public Actor behavior(Function behavior) { 762 | Objects.requireNonNull(behavior); 763 | checkOwner(); 764 | checkStateCreated(); 765 | if (this.behaviorFactory != null) { 766 | throw new IllegalActorStateException("behavior() can only called once"); 767 | } 768 | this.behaviorFactory = behavior; 769 | return this; 770 | } 771 | 772 | /** 773 | * Register a code to execute when a signal occurs 774 | * @param handler the code to execute 775 | * @return the current actor so method calls can be chained 776 | * @throws IllegalActorStateException if the current thread is not the owner thread of the actor or 777 | * if the actor is already running/shutdown 778 | * 779 | * @see Context#shutdown() 780 | * @see HandlerContext#signal(Actor, Signal) 781 | */ 782 | public Actor onSignal(SignalHandler handler) { 783 | Objects.requireNonNull(handler); 784 | checkOwner(); 785 | checkStateCreated(); 786 | addSignalHandler(handler); 787 | return this; 788 | } 789 | 790 | /** 791 | * Starts all the actors, {@link StartupContext#postTo(Actor, Message) post} some messages 792 | * and wait until all actors have been shutdown. 793 | * @param actors a list of actors to start 794 | * @param consumer a code that can post messages 795 | * @throws InterruptedException if the current thread is interrupted 796 | * @throws IllegalActorStateException if the current thread is not the one that have created the actors 797 | * if an actor is already running/shutdown or if an actor has no behavior 798 | */ 799 | public static void run(List> actors, StartupConsumer consumer) 800 | throws InterruptedException, X { 801 | Objects.requireNonNull(actors); 802 | Objects.requireNonNull(consumer); 803 | for(Actor actor: actors) { 804 | actor.checkOwner(); 805 | if (actor.behaviorFactory == null) { 806 | throw new IllegalActorStateException(actor.name + " behavior is not defined"); 807 | } 808 | } 809 | var context = new ContextImpl(); 810 | var threads = actors.stream() 811 | .map(actor -> startThread(context, actor)) 812 | .toList(); 813 | consumer.accept(context); 814 | joinAll(threads); 815 | } 816 | 817 | /** 818 | * Set the global exception handler. 819 | * This handler should be used to log exceptions, not to try to recover exception 820 | * @param uncaughtExceptionHandler exception handler called when an actor behavior throw an exception 821 | * @throws IllegalActorStateException if the global exception handler has already been set 822 | * 823 | * @see #onSignal(SignalHandler) 824 | */ 825 | public static void uncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) { 826 | Objects.requireNonNull(uncaughtExceptionHandler); 827 | if (!UNCAUGHT_EXCEPTION_HANDLER.compareAndSet(DEFAULT_UNCAUGHT_EXCEPTION_HANDLER, uncaughtExceptionHandler)) { 828 | throw new IllegalActorStateException("uncaught exception handler already set"); 829 | } 830 | } 831 | 832 | private static class Debug { 833 | private record Mode(Function lookupMatcher, 834 | Predicate> isImmutable) { } 835 | 836 | private static final Mode MODE = Actor.debugModeCandidate; 837 | 838 | private static void checkImmutable(Class type, Predicate> isImmutable) { 839 | // default immutable classes 840 | if (type.isPrimitive() || type.isEnum() || type == String.class || type == Class.class) { 841 | return; 842 | } 843 | // record are only unmodifiable, check if components type are immutable 844 | if (type.isRecord()) { 845 | for(var component: type.getRecordComponents()) { 846 | checkImmutable(component.getType(), isImmutable); 847 | } 848 | } 849 | // immutable collections 850 | var enclosingClass = type.getEnclosingClass(); 851 | if (enclosingClass != null && enclosingClass.getName().equals("java.util.ImmutableCollections")) { 852 | return; 853 | } 854 | // user defined immutable 855 | if (isImmutable.test(type)) { 856 | return; 857 | } 858 | throw new IllegalStateException(type.getName() + " is not immutable"); 859 | } 860 | 861 | public static void checkMessage(Message message) { 862 | var debugMode = MODE; 863 | Class messageClass = message.getClass(); 864 | if (!messageClass.isHidden()) { 865 | throw new IllegalStateException("the message " + message + " is not a lambda ?"); 866 | } 867 | var module = messageClass.getModule(); 868 | var lookup = debugMode.lookupMatcher.apply(module); 869 | Objects.requireNonNull(lookup, "the lookup returned by the lookupMatcher is null"); 870 | SerializedLambda lambda; 871 | try { 872 | Lookup privateLookup = MethodHandles.privateLookupIn(messageClass, lookup); 873 | MethodHandle writeReplace = privateLookup.findVirtual(messageClass, "writeReplace", MethodType.methodType((Object.class))); 874 | lambda = (SerializedLambda) writeReplace.invoke(message); 875 | } catch (RuntimeException | Error e) { 876 | throw e; 877 | } catch(Throwable e) { 878 | throw new IllegalStateException("cracking lambda failed", e); 879 | } 880 | 881 | for(var i = 0; i < lambda.getCapturedArgCount(); i++) { 882 | var argument = lambda.getCapturedArg(i); 883 | if (argument != null) { 884 | checkImmutable(argument.getClass(), debugMode.isImmutable); 885 | } 886 | } 887 | } 888 | } 889 | 890 | private static volatile Debug.Mode debugModeCandidate; 891 | 892 | /** 893 | * Set the debug mode to on so all messages are checked to verify that they are immutable. 894 | * This method can only be called once and before any messages is posted. 895 | * 896 | * @param lookupMatcher a function called to provide a lookup for a module 897 | * used to open the lambdas used as messages in that module 898 | * @param isImmutable a function that returns true if a class is immutable 899 | * 900 | * @see Context#postTo(Actor, Message) 901 | * @see StartupContext#postTo(Actor, Message) 902 | * @see HandlerContext#postTo(Actor, Message) 903 | */ 904 | public static void debugMode(Function lookupMatcher, 905 | Predicate> isImmutable) { 906 | Objects.requireNonNull(lookupMatcher); 907 | Objects.requireNonNull(isImmutable); 908 | var debugMode = new Debug.Mode(lookupMatcher, isImmutable); 909 | debugModeCandidate = debugMode; 910 | try { 911 | if (Debug.MODE != debugMode) { 912 | throw new IllegalStateException("debug mode already set or a least one message was already sent"); 913 | } 914 | } finally { 915 | debugModeCandidate = null; 916 | } 917 | } 918 | } 919 | 920 | -------------------------------------------------------------------------------- /src/main/java/com/github/forax/loom/actor/http/HttpServer.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor.http; 2 | 3 | import com.fasterxml.jackson.databind.JavaType; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import com.sun.net.httpserver.Headers; 6 | import com.sun.net.httpserver.HttpExchange; 7 | import com.github.forax.loom.actor.Actor; 8 | 9 | import java.io.IOException; 10 | import java.io.UncheckedIOException; 11 | import java.lang.annotation.Annotation; 12 | import java.lang.annotation.ElementType; 13 | import java.lang.annotation.Retention; 14 | import java.lang.annotation.RetentionPolicy; 15 | import java.lang.annotation.Target; 16 | import java.lang.reflect.Method; 17 | import java.lang.reflect.Modifier; 18 | import java.lang.reflect.ParameterizedType; 19 | import java.lang.reflect.Type; 20 | import java.net.InetSocketAddress; 21 | import java.nio.file.Files; 22 | import java.nio.file.Path; 23 | import java.util.ArrayList; 24 | import java.util.Arrays; 25 | import java.util.List; 26 | import java.util.Map; 27 | import java.util.Objects; 28 | import java.util.concurrent.Executors; 29 | import java.util.regex.Matcher; 30 | import java.util.regex.Pattern; 31 | 32 | import static java.util.stream.Collectors.groupingBy; 33 | import static java.util.stream.Collectors.toMap; 34 | 35 | /** 36 | * An HTTP server that uses actors to handle HTTP request / response seen as JSON objects/arrays. 37 | * 38 | * 39 | */ 40 | public class HttpServer { 41 | /** 42 | * HTTP request method. 43 | * 44 | * see HTTP Methods 45 | */ 46 | public enum RequestMethod { 47 | GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH 48 | } 49 | 50 | /** 51 | * HTTP response status. 52 | * 53 | * see HTTP Status 54 | */ 55 | public enum HttpStatus { 56 | CONTINUE(100), 57 | SWITCHING_PROTOCOLS(101), 58 | EARLY_HINTS(103), 59 | 60 | OK(200), 61 | CREATED(201), 62 | ACCEPTED(202), 63 | NON_AUTTHORITATIVE_INFORMATION(203), 64 | NO_CONTENT(204), 65 | RESET_CONTENT(205), 66 | PARTIAL_CONTENT(206), 67 | 68 | MULTIPLE_CHOICES(300), 69 | MOVED_PERMANENTLY(301), 70 | FOUND(302), 71 | SEE_OTHER(303), 72 | NOT_MODIFIER(304), 73 | TEMPORARY_REDIRECT(307), 74 | PERMANENT_REDIRECT(308), 75 | 76 | BAD_REQUEST(400), 77 | UNAUTHORIZED(401), 78 | PAYMENT_REQUIRED(402), 79 | FORBIDDEN(403), 80 | NOT_FOUND(404), 81 | METHOD_NOT_ALLOWED(405), 82 | NOT_ACCEPTABLE(406), 83 | PROXY_AUTHENTICATION_REQUIRED(407), 84 | REQUEST_TIMEOUT(408), 85 | CONFLICT5(409), 86 | GONE(410), 87 | LENGTH_REQUIRED(411), 88 | PRECONDITION_FAILED(412), 89 | PAYLOAD_TOO_LARGE(413), 90 | URI_TOO_LONG(414), 91 | UNSUPPORTED_MEDIA_TYPE(415), 92 | RANGE_NOT_SATISFIABLE(416), 93 | EXPECTATION_FAILED(417), 94 | I_M_A_TEAPOT(418), 95 | UNPROCESSABLE_ENTITY(422), 96 | TOO_EARLY(425), 97 | UPGRADE_REQUIRED(426), 98 | PRECONDITION_REQUIRED(428), 99 | TOO_MANY_REQUESTS(429), 100 | REQUEST_HEADER_FIELDS_TOO_LARGE(431), 101 | UNAVAILABLE_FOR_LEGAL_REASONS(451), 102 | 103 | INTERNAL_SERVER_ERROR(500), 104 | NOT_IMPLEMENTED(501), 105 | BAD_GATEWAY(502), 106 | SERVICE_UNAVAILABLE(503), 107 | GATEWAY_TIMEOUT(504), 108 | HTTP_VERSION_NOT_SUPPORTED(505), 109 | VARIANT_ALSO_NEGOTIATES(506), 110 | INSUFFICIENT_STORAGE(507), 111 | LOOP_DETECTED(508), 112 | NOT_EXTENDED(510), 113 | NETWORK_AUTHENTICATION_REQUIRED(511) 114 | ; 115 | 116 | private final int code; 117 | 118 | HttpStatus(int code) { 119 | this.code = code; 120 | } 121 | } 122 | 123 | /** 124 | * The method annotated by this annotation defines a route. 125 | * 126 | * The semantics is similar to the Spring Web Annotation with the same name. 127 | * see Spring MVC annotations 128 | * 129 | * @see #routes(Actor) 130 | */ 131 | @Target(ElementType.METHOD) 132 | @Retention(RetentionPolicy.RUNTIME) 133 | public @interface RequestMapping { 134 | String path(); 135 | RequestMethod method() default RequestMethod.GET; 136 | } 137 | 138 | /** 139 | * The parameter annotated by this annotation will be injected with 140 | * the request body as a JSON object/array. 141 | * 142 | * The semantics is similar to the Spring Web Annotation with the same name. 143 | * see Spring MVC annotations 144 | * 145 | * @see #routes(Actor) 146 | */ 147 | @Target(ElementType.PARAMETER) 148 | @Retention(RetentionPolicy.RUNTIME) 149 | public @interface RequestBody { } 150 | 151 | /** 152 | * The parameter annotated by this annotation will be injected with 153 | * the value captured from the request URI. 154 | * 155 | * The semantics is similar to the Spring Web Annotation with the same name. 156 | * see Spring MVC annotations 157 | * 158 | * @see #routes(Actor) 159 | */ 160 | @Target(ElementType.PARAMETER) 161 | @Retention(RetentionPolicy.RUNTIME) 162 | public @interface PathVariable { 163 | String value(); 164 | } 165 | 166 | /** 167 | * The parameter annotated by this annotation will be injected with 168 | * the value of the request header or the default value if 169 | * the header does not exist. 170 | * 171 | * The semantics is similar to the Spring Web Annotation with the same name. 172 | * see Spring MVC annotations 173 | * 174 | * @see #routes(Actor) 175 | */ 176 | @Target(ElementType.PARAMETER) 177 | @Retention(RetentionPolicy.RUNTIME) 178 | public @interface RequestParam { 179 | String value(); 180 | String defaultValue() default ""; 181 | } 182 | 183 | /** 184 | * API of the actor able to send a HTTP response. 185 | * 186 | * @param type of the result, can be java.lang.Void if the value is null. 187 | */ 188 | public interface Response { 189 | /** 190 | * Send a response with a HTTP status and a result as a JSON object. 191 | * @param status the response status 192 | * @param result an object that will be converted to JSON or null 193 | */ 194 | void response(HttpStatus status, T result); 195 | 196 | /** 197 | * Send a response with a HTTP status, some header key/value pairs and a result as a JSON object. 198 | * @param status the response status 199 | * @param headerMap the response headers 200 | * @param result an object that will be converted to JSON or null 201 | */ 202 | void response(HttpStatus status, Map headerMap, T result); 203 | } 204 | 205 | private record PathInfo(Map pathVariableMap, Pattern regex) {} 206 | 207 | private record InjectorInfo(ArgumentInjector.RequestBodyInjector requestBodyInjector, ArgumentInjector.ResponseActorInjector responseActorInjector, ArgumentInjector[] injectors) {} 208 | 209 | private record Route(String requestMethod, PathInfo pathInfo, InjectorInfo injectorInfo, Method method, Actor actor) {} 210 | 211 | private record RouteResult(Route route, Matcher pathMatcher) {} 212 | 213 | private sealed interface ArgumentInjector { 214 | record PathVariableInjector(int groupIndex) implements ArgumentInjector {} 215 | record RequestParamInjector(String key, String defaultValue) implements ArgumentInjector {} 216 | record RequestBodyInjector(JavaType javaType) implements ArgumentInjector {} 217 | record ResponseActorInjector(JavaType javaType) implements ArgumentInjector {} 218 | 219 | private static String firstValue(Headers requestHeaders, String key, String defaultValue) { 220 | var values = requestHeaders.get(key); 221 | return values == null? defaultValue: values.get(0); 222 | } 223 | 224 | static Object[] inject(ArgumentInjector[] argumentInjectors, Matcher pathMatcher, Headers requestHeaders, Object requestBody, Actor> responseActor) { 225 | var arguments = new Object[argumentInjectors.length]; 226 | for(var i = 0; i < arguments.length; i++) { 227 | var argumentInjector = argumentInjectors[i]; 228 | /*arguments[i] = switch (argumentInjectors[i]) { 229 | case PathVariableInjector pathVariable -> pathMatcher.group(pathVariable.groupIndex); 230 | case RequestParamInjector requestParam -> firstValue(requestHeaders, requestParam.key, requestParam.defaultValue); 231 | case RequestBodyInjector __ -> requestBody; 232 | case ResponseActorInjector __ -> responseActor; 233 | };*/ 234 | Object argument; 235 | if (argumentInjector instanceof PathVariableInjector pathVariable) { 236 | argument = pathMatcher.group(pathVariable.groupIndex); 237 | } else if (argumentInjector instanceof RequestParamInjector requestParam) { 238 | argument = firstValue(requestHeaders, requestParam.key, requestParam.defaultValue); 239 | } else if (argumentInjector instanceof RequestBodyInjector) { 240 | argument = requestBody; 241 | } else if (argumentInjector instanceof ResponseActorInjector) { 242 | argument = responseActor; 243 | } else { 244 | throw new AssertionError("invalid injector " + argumentInjector); 245 | } 246 | arguments[i] = argument; 247 | } 248 | return arguments; 249 | } 250 | 251 | private static PathVariableInjector createPathVariableInjector(Type parameterType, PathVariable pathVariable, PathInfo pathInfo) { 252 | if (parameterType != String.class) { 253 | throw new IllegalStateException("a parameter annotated by @PathVariable should be of type String (" + parameterType + ")"); 254 | } 255 | var pathVariableName = pathVariable.value(); 256 | var groupIndex = pathInfo.pathVariableMap.get(pathVariableName); 257 | if (groupIndex == null) { 258 | throw new IllegalStateException("annotation @PathVariable unknown name " + pathVariableName); 259 | } 260 | return new PathVariableInjector(groupIndex); 261 | } 262 | 263 | private static RequestParamInjector createRequestParamInjector(Type parameterType, RequestParam requestParam) { 264 | if (parameterType != String.class) { 265 | throw new IllegalStateException("a parameter annotated by @RequestParam should be of type String"); 266 | } 267 | return new RequestParamInjector(requestParam.value(), requestParam.defaultValue()); 268 | } 269 | 270 | private static RequestBodyInjector createRequestBodyInjector(Type parameterType) { 271 | return new RequestBodyInjector(OBJECT_MAPPER.constructType(parameterType)); 272 | } 273 | 274 | private static ResponseActorInjector createResponseActorInjector(Type parameterType) { 275 | if (!(parameterType instanceof ParameterizedType parameterizedType) 276 | || parameterizedType.getRawType() != Actor.class 277 | || !(parameterizedType.getActualTypeArguments()[0] instanceof ParameterizedType responseParameterizedType) 278 | || responseParameterizedType.getRawType() != Response.class) { 279 | throw new IllegalStateException("the response actor should be typed Actor> (" + parameterType + ")"); 280 | } 281 | var responseArgumentType = responseParameterizedType.getActualTypeArguments()[0]; 282 | return new ResponseActorInjector(OBJECT_MAPPER.constructType(responseArgumentType)); 283 | } 284 | 285 | private static ArgumentInjector findInjector(Type parameterType, Annotation[] annotations, PathInfo pathInfo) { 286 | ArgumentInjector foundInjector = null; 287 | Annotation foundAnnotation = null; 288 | for (Annotation annotation : annotations) { 289 | /*var injector = switch (annotation) { 290 | case PathVariable pathVariable -> createPathVariableInjector(parameterType, pathVariable, pathInfo); 291 | case RequestParam requestParam -> createRequestParamInjector(parameterType, requestParam); 292 | case RequestBody __ -> createRequestBodyInjector(parameterType); 293 | default -> null; 294 | };*/ 295 | ArgumentInjector injector; 296 | if (annotation instanceof PathVariable pathVariable) { 297 | injector = createPathVariableInjector(parameterType, pathVariable, pathInfo); 298 | } else if (annotation instanceof RequestParam requestParam) { 299 | injector = createRequestParamInjector(parameterType, requestParam); 300 | } else if (annotation instanceof RequestBody) { 301 | injector = createRequestBodyInjector(parameterType); 302 | } else { 303 | injector = null; 304 | } 305 | 306 | if (injector == null) { 307 | continue; 308 | } 309 | if (foundInjector != null) { 310 | throw new IllegalStateException("several incompatible annotations " + annotation + " " + foundAnnotation); 311 | } 312 | foundInjector = injector; 313 | foundAnnotation = annotation; 314 | } 315 | return foundInjector != null? foundInjector: createResponseActorInjector(parameterType); 316 | } 317 | 318 | private static InjectorInfo validateInjectors(ArgumentInjector[] injectors) { 319 | var group = Arrays.stream(injectors) 320 | .collect(groupingBy(Object::getClass)); 321 | var requestBodyInjectors = group.getOrDefault(RequestBodyInjector.class, List.of()); 322 | if (requestBodyInjectors.size() > 1) { 323 | throw new IllegalStateException("multiple @RequestBody annotation found"); 324 | } 325 | var responseActorInjectors = group.getOrDefault(ResponseActorInjector.class, List.of()); 326 | if (responseActorInjectors.isEmpty()) { 327 | throw new IllegalStateException("no response actor declared"); 328 | } 329 | return new InjectorInfo( 330 | (RequestBodyInjector) requestBodyInjectors.stream().findFirst().orElse(null), 331 | (ResponseActorInjector) responseActorInjectors.get(0), 332 | injectors); 333 | } 334 | 335 | static InjectorInfo findInjectorInfo(Type[] parameterTypes, Annotation[][] parameterAnnotations, PathInfo pathInfo) { 336 | var injectors = new ArgumentInjector[parameterTypes.length]; 337 | for (int i = 0; i < parameterTypes.length; i++) { 338 | var parameterType = parameterTypes[i]; 339 | var annotations = parameterAnnotations[i]; 340 | injectors[i] = findInjector(parameterType, annotations, pathInfo); 341 | } 342 | return validateInjectors(injectors); 343 | } 344 | } 345 | 346 | private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); 347 | 348 | //@RequestMapping(method = GET|POST, path=/path/to/somewhere/{id}) 349 | //void method(@PathVariable("id") path_variable, @RequestParam("param") request_parameter, @RequestBody request_body_record, reply_actor) 350 | 351 | private static final Pattern PATH_PATTERN = Pattern.compile("\\{(\\w+)\\}"); 352 | 353 | private final ArrayList routes = new ArrayList<>(); 354 | private final ArrayList> actors = new ArrayList<>(); 355 | 356 | private static PathInfo createPathInfo(String path) { 357 | if (path.endsWith("/")) { 358 | throw new IllegalStateException("invalid path " + path + " ends with '/'"); 359 | } 360 | var matcher = PATH_PATTERN.matcher(path); 361 | var box = new Object() { int counter = 1; }; 362 | var pathVariableMap = matcher.results() 363 | .map(result -> result.group(1)) 364 | .collect(toMap(k -> k, __ -> box.counter++)); 365 | if (pathVariableMap.isEmpty()) { 366 | return new PathInfo(Map.of(), Pattern.compile(path)); 367 | } 368 | var regex = matcher.replaceAll(matchResult -> "(\\\\w+)"); 369 | return new PathInfo(pathVariableMap, Pattern.compile(regex)); 370 | } 371 | 372 | /** 373 | * Add the routes defined by the actor behavior to the server. 374 | * When a HTTP request calls the server, it redirects the call to the actors dependening on the routes 375 | * they declared. 376 | *

377 | * A method of the actor behavior annotated with {@link RequestMapping} declares a new route. 378 | * The annotation {@link RequestMapping} defines 379 | *

    380 | *
  • 381 | * {@link RequestMapping#method()} the HTTP request method of the route 382 | *
  • 383 | *
  • 384 | * {@link RequestMapping#path()} define a regular expression to match the HTTP request URI. 385 | * A path should never ends with a slash '/' and can include request parameter name "{foo}" in between 386 | * curly braces. 387 | *

    388 | * By example: {@code /users} match the URI "/users" while {@code /users/{id}} match any URIs that starts 389 | * with "/users". The value matched by {@code {if}} is available using the annotation {@link RequestParam}. 390 | *

  • 391 | *
392 | * 393 | * The parameters of a method defining a route can be annotated by 394 | *
    395 | *
  • {@link PathVariable)} to match an argument is extracted from the URI, the type of the parameter 396 | * is String
  • 397 | *
  • {@link RequestBody}, the argument is a JSON encoded record containing the body of the request, 398 | * the type of the argument is a record or a list/map of records
  • 399 | *
  • {@link RequestParam}, the argument is the value of an header of the request, the type of the parameter 400 | * is a String
  • 401 | *
402 | * 403 | * Moreover, the method should define the actor that will receive the response. 404 | * The type of the actor is {@code Actor} with @code X} being a record, a list of record 405 | * or java.lang.Void if the result is null. 406 | * 407 | * @param actor the actor defining the routes 408 | * @return the current server so calls can be chained 409 | */ 410 | public HttpServer routes(Actor actor) { 411 | Objects.requireNonNull(actor); 412 | for(var method: actor.behaviorType().getMethods()) { 413 | if (Modifier.isStatic(method.getModifiers())) { 414 | continue; 415 | } 416 | var requestMapping = method.getAnnotation(RequestMapping.class); 417 | if (requestMapping == null) { 418 | continue; 419 | } 420 | var pathInfo = createPathInfo(requestMapping.path()); 421 | var injectorInfo = ArgumentInjector.findInjectorInfo(method.getGenericParameterTypes(), method.getParameterAnnotations(), pathInfo); 422 | var requestMethod = requestMapping.method().name(); 423 | var route = new Route(requestMethod, pathInfo, injectorInfo, method, actor); 424 | routes.add(route); 425 | } 426 | actors.add(actor); 427 | return this; 428 | } 429 | 430 | private RouteResult findRoute(HttpExchange exchange) { 431 | var uri = exchange.getRequestURI().toString(); 432 | var requestMethod = exchange.getRequestMethod(); 433 | for(var route: routes) { 434 | if (!requestMethod.equals(route.requestMethod)) { 435 | continue; 436 | } 437 | var pathMatcher = route.pathInfo.regex.matcher(uri); 438 | if (pathMatcher.matches()) { 439 | return new RouteResult(route, pathMatcher); 440 | } 441 | } 442 | return null; 443 | } 444 | 445 | private void serveStaticContent(HttpExchange exchange) throws IOException { 446 | if (!exchange.getRequestMethod().equals("GET")) { 447 | exchange.sendResponseHeaders(500, 0); 448 | exchange.close(); 449 | return; 450 | } 451 | 452 | var path = Path.of(".", exchange.getRequestURI().toString()); 453 | System.out.println(" try to serve static content from " + path); 454 | 455 | long fileSize; 456 | try { 457 | fileSize = Files.size(path); 458 | } catch (IOException e) { 459 | exchange.sendResponseHeaders(404, 0); 460 | exchange.close(); 461 | System.out.println(" nof found " + path); 462 | return; 463 | } 464 | exchange.sendResponseHeaders(200, fileSize); 465 | try (var outputStream = exchange.getResponseBody(); 466 | var inputStream = Files.newInputStream(path)) { 467 | inputStream.transferTo(outputStream); 468 | } 469 | exchange.close(); 470 | System.out.println(" served " + fileSize + " bytes from " + path); 471 | } 472 | 473 | /** 474 | * Bind the server to a specific name and local port and start the server. 475 | * The server spawns all actors,. Then for each request, it spawns a new actor to handle the response 476 | * and then it redirects the request to an actor using the routes. 477 | * The spawned actor is shutdown when the response is fully sent or if an error occurs. 478 | * 479 | * @param address the name and local port 480 | * @throws IOException if the server can not be bound to the address 481 | * @throws InterruptedException if the current thread is interrupted 482 | */ 483 | public void bind(InetSocketAddress address) throws IOException, InterruptedException { 484 | Objects.requireNonNull(address); 485 | if (routes.isEmpty()) { 486 | throw new IllegalStateException("no route registered"); 487 | } 488 | Actor.run(actors, startupContext -> { 489 | var server = com.sun.net.httpserver.HttpServer.create(address, 0); 490 | server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); 491 | server.createContext("/", exchange -> { 492 | System.out.println("request " + exchange.getRequestMethod() + " " + exchange.getRequestURI()); 493 | 494 | var routeResult = findRoute(exchange); 495 | if (routeResult == null) { 496 | serveStaticContent(exchange); 497 | return; 498 | } 499 | 500 | var pathMatcher = routeResult.pathMatcher; 501 | var route = routeResult.route; 502 | var injectorInfo = route.injectorInfo; 503 | 504 | Object requestBody = null; 505 | var requestBodyInjector = injectorInfo.requestBodyInjector; 506 | if (requestBodyInjector != null) { 507 | requestBody = OBJECT_MAPPER.readValue(exchange.getRequestBody(), requestBodyInjector.javaType); 508 | } 509 | 510 | @SuppressWarnings("unchecked") 511 | var responseActor = (Actor>) (Actor) Actor.of(Response.class) 512 | .behavior(context -> new Response<>() { 513 | @Override 514 | public void response(HttpStatus status, Object result) { 515 | response(status, Map.of(), result); 516 | } 517 | 518 | @Override 519 | public void response(HttpStatus status, Map headerMap, Object result) { 520 | try { 521 | exchange.sendResponseHeaders(status.code, 0); 522 | var headers = exchange.getResponseHeaders(); 523 | headerMap.forEach(headers::add); 524 | headers.add("Content-Type", "application/json"); 525 | try(var outputStream = exchange.getResponseBody()) { 526 | OBJECT_MAPPER.writeValue(outputStream, result); 527 | } 528 | } catch(IOException e) { 529 | throw new UncheckedIOException(e); 530 | } 531 | context.shutdown(); 532 | } 533 | }); 534 | startupContext.spawn(responseActor); 535 | 536 | var method = route.method; 537 | var actor = route.actor; 538 | var args = ArgumentInjector.inject(injectorInfo.injectors, pathMatcher, exchange.getRequestHeaders(), requestBody, responseActor); 539 | startupContext.postTo(actor, behavior -> method.invoke(behavior, args)); 540 | }); 541 | server.start(); 542 | System.out.println("server started at " + server.getAddress()); 543 | }); 544 | } 545 | } 546 | -------------------------------------------------------------------------------- /src/test/java/com/github/forax/loom/actor/ActorTest.java: -------------------------------------------------------------------------------- 1 | package com.github.forax.loom.actor; 2 | 3 | import com.github.forax.loom.actor.Actor.IllegalActorStateException; 4 | import com.github.forax.loom.actor.Actor.PanicSignal; 5 | import com.github.forax.loom.actor.Actor.ShutdownSignal; 6 | import com.github.forax.loom.actor.Actor.State; 7 | import org.junit.jupiter.api.Test; 8 | import org.junit.jupiter.api.Timeout; 9 | 10 | import java.lang.invoke.MethodHandles; 11 | import java.util.List; 12 | import java.util.concurrent.atomic.AtomicBoolean; 13 | 14 | import static java.util.concurrent.TimeUnit.MILLISECONDS; 15 | import static org.junit.jupiter.api.Assertions.assertAll; 16 | import static org.junit.jupiter.api.Assertions.assertEquals; 17 | import static org.junit.jupiter.api.Assertions.assertSame; 18 | import static org.junit.jupiter.api.Assertions.assertThrows; 19 | import static org.junit.jupiter.api.Assertions.assertTrue; 20 | 21 | public class ActorTest { 22 | static { 23 | Actor.uncaughtExceptionHandler((actor, exception) -> { 24 | // ignore exceptions 25 | }); 26 | // checks that all messages are immutable 27 | Actor.debugMode(__ -> MethodHandles.lookup(), __ -> false); 28 | } 29 | 30 | @Test 31 | public void stateCreated() { 32 | interface Empty { } 33 | assertAll( 34 | () -> assertEquals(State.CREATED, Actor.of(Empty.class).state()), 35 | () -> assertEquals(State.CREATED, Actor.of(Empty.class, "empty").state()) 36 | ); 37 | } 38 | 39 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 40 | public void stateRunning() throws InterruptedException { 41 | interface Simple { 42 | void message(); 43 | } 44 | var actor = Actor.of(Simple.class); 45 | actor.behavior(context -> () -> { 46 | assertEquals(State.RUNNING, actor.state()); 47 | context.shutdown(); 48 | }); 49 | Actor.run(List.of(actor), startContext -> startContext.postTo(actor, Simple::message)); 50 | } 51 | 52 | @Test @Timeout(value = 500, unit = MILLISECONDS) 53 | public void stateShutdown() throws InterruptedException { 54 | interface Simple { 55 | void message(); 56 | } 57 | var actor = Actor.of(Simple.class) 58 | .behavior(context -> context::shutdown); 59 | Actor.run(List.of(actor), startContext -> startContext.postTo(actor, Simple::message)); 60 | assertEquals(State.SHUTDOWN, actor.state()); 61 | } 62 | 63 | @Test 64 | public void ofName() { 65 | interface Empty { } 66 | assertAll( 67 | () -> assertEquals("hello", Actor.of(Empty.class, "hello").name()), 68 | () -> assertThrows(NullPointerException.class, () -> Actor.of(Empty.class, null)) 69 | ); 70 | } 71 | 72 | @Test 73 | public void ofBehaviorTypeNull() { 74 | assertAll( 75 | () -> assertThrows(NullPointerException.class, () -> Actor.of(null)), 76 | () -> assertThrows(NullPointerException.class, () -> Actor.of(null, "hello")) 77 | ); 78 | } 79 | 80 | @Test 81 | public void behaviorNull() { 82 | var actor = Actor.of(Runnable.class); 83 | assertThrows(NullPointerException.class, () -> actor.behavior(null)); 84 | } 85 | 86 | @Test 87 | public void noBehaviorDefined() { 88 | var actor = Actor.of(Runnable.class); 89 | assertThrows(IllegalActorStateException.class, () -> Actor.run(List.of(actor), startContext -> {})); 90 | } 91 | 92 | @Test 93 | public void behaviorWrongThread() { 94 | var actor = Actor.of(Runnable.class); 95 | new Thread(() -> assertThrows(IllegalActorStateException.class, () -> actor.behavior(context -> () -> {}))).start(); 96 | } 97 | 98 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 99 | public void behaviorSeveralMessages() throws InterruptedException { 100 | interface Dummy { 101 | void foo(String message); 102 | void bar(int value); 103 | void stop(); 104 | } 105 | var actor = Actor.of(Dummy.class) 106 | .behavior(context -> new Dummy() { 107 | @Override 108 | public void foo(String message) { 109 | assertEquals("hello", message); 110 | } 111 | 112 | @Override 113 | public void bar(int value) { 114 | assertEquals(42, value); 115 | } 116 | 117 | @Override 118 | public void stop() { 119 | context.shutdown(); 120 | } 121 | }); 122 | Actor.run(List.of(actor), context -> { 123 | context.postTo(actor, $ -> $.foo("hello")); 124 | context.postTo(actor, $ -> $.bar(42)); 125 | context.postTo(actor, Dummy::stop); 126 | }); 127 | } 128 | 129 | @Test 130 | public void onSignalNull() { 131 | var actor = Actor.of(Runnable.class) 132 | .behavior(context -> () -> {}); 133 | assertThrows(NullPointerException.class, () -> actor.onSignal(null)); 134 | } 135 | 136 | @Test 137 | public void onSignalWrongThread() { 138 | var actor = Actor.of(Runnable.class) 139 | .behavior(context -> () -> {}); 140 | new Thread(() -> assertThrows(IllegalActorStateException.class, () -> actor.onSignal((signal, context) -> {}))).start(); 141 | } 142 | 143 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 144 | public void onSignalException() throws InterruptedException { 145 | interface Transparent { 146 | void message(Exception exception) throws Exception; 147 | } 148 | var exceptionSeen = new AtomicBoolean(); 149 | var actor = Actor.of(Transparent.class) 150 | .behavior(context -> exception -> { throw exception; }) 151 | .onSignal((signal, context) -> { 152 | exceptionSeen.set(true); 153 | assertTrue(signal instanceof PanicSignal); 154 | var panicSignal = (PanicSignal) signal; 155 | var exception = panicSignal.exception(); 156 | assertAll( 157 | () -> assertEquals(Exception.class, exception.getClass()), 158 | () -> assertEquals("foo", exception.getMessage()) 159 | ); 160 | }); 161 | Actor.run(List.of(actor), context -> context.postTo(actor, $ -> $.message(new Exception("foo")))); 162 | assertAll( 163 | () -> assertEquals(State.SHUTDOWN, actor.state()), 164 | () -> assertTrue(exceptionSeen.get()) 165 | ); 166 | } 167 | 168 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 169 | public void onSignalRuntimeException() throws InterruptedException { 170 | var exceptionSeen = new AtomicBoolean(); 171 | var actor = Actor.of(Runnable.class) 172 | .behavior(context -> () -> { throw new IllegalStateException("foo"); }) 173 | .onSignal((signal, context) -> { 174 | exceptionSeen.set(true); 175 | assertTrue(signal instanceof PanicSignal); 176 | var panicSignal = (PanicSignal) signal; 177 | var exception = panicSignal.exception(); 178 | assertAll( 179 | () -> assertEquals(IllegalStateException.class, exception.getClass()), 180 | () -> assertEquals("foo", exception.getMessage()) 181 | ); 182 | }); 183 | Actor.run(List.of(actor), context -> context.postTo(actor, Runnable::run)); 184 | assertAll( 185 | () -> assertEquals(State.SHUTDOWN, actor.state()), 186 | () -> assertTrue(exceptionSeen.get()) 187 | ); 188 | } 189 | 190 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 191 | public void onSignalInterrupted() throws InterruptedException { 192 | var exceptionSeen = new AtomicBoolean(); 193 | var actor = Actor.of(Runnable.class) 194 | .behavior(context -> () -> Thread.currentThread().interrupt()) 195 | .onSignal((signal, context) -> { 196 | exceptionSeen.set(true); 197 | assertTrue(signal instanceof PanicSignal); 198 | var panicSignal = (PanicSignal) signal; 199 | var exception = panicSignal.exception(); 200 | assertEquals(InterruptedException.class, exception.getClass()); 201 | }); 202 | Actor.run(List.of(actor), context -> context.postTo(actor, Runnable::run)); 203 | assertAll( 204 | () -> assertEquals(State.SHUTDOWN, actor.state()), 205 | () -> assertTrue(exceptionSeen.get()) 206 | ); 207 | } 208 | 209 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 210 | public void onSignalInterruptedExplicitException() throws InterruptedException { 211 | interface Action { 212 | void run() throws InterruptedException; 213 | } 214 | var exceptionSeen = new AtomicBoolean(); 215 | var actor = Actor.of(Action.class) 216 | .behavior(context -> () -> { 217 | throw new InterruptedException(); 218 | }) 219 | .onSignal((signal, context) -> { 220 | exceptionSeen.set(true); 221 | assertTrue(signal instanceof PanicSignal); 222 | var panicSignal = (PanicSignal) signal; 223 | var exception = panicSignal.exception(); 224 | assertEquals(InterruptedException.class, exception.getClass()); 225 | }); 226 | Actor.run(List.of(actor), context -> context.postTo(actor, Action::run)); 227 | assertAll( 228 | () -> assertEquals(State.SHUTDOWN, actor.state()), 229 | () -> assertTrue(exceptionSeen.get()) 230 | ); 231 | } 232 | 233 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 234 | public void onSignalExceptionInSignalHandler() throws InterruptedException { 235 | var exceptionSeen = new AtomicBoolean(); 236 | var actor = Actor.of(Runnable.class) 237 | .behavior(context -> () -> { throw new RuntimeException(); }) 238 | .onSignal((signal, context) -> { 239 | exceptionSeen.set(true); 240 | assertTrue(signal instanceof PanicSignal); 241 | throw new IllegalStateException("error in signal handler"); 242 | }); 243 | Actor.run(List.of(actor), context -> context.postTo(actor, Runnable::run)); 244 | assertAll( 245 | () -> assertEquals(State.SHUTDOWN, actor.state()), 246 | () -> assertTrue(exceptionSeen.get()) 247 | ); 248 | } 249 | 250 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 251 | public void currentActor() throws InterruptedException { 252 | var box = new Object() { Actor actor; }; 253 | var actor = Actor.of(Runnable.class); 254 | actor.behavior(context -> () -> { 255 | box.actor = context.currentActor(Runnable.class); 256 | context.shutdown(); 257 | }); 258 | Actor.run(List.of(actor), context -> context.postTo(actor, Runnable::run)); 259 | assertSame(actor, box.actor); 260 | } 261 | 262 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 263 | public void currentActorWrongBehaviorClass() throws InterruptedException { 264 | var box = new Object() { Exception exception; }; 265 | var actor = Actor.of(Runnable.class) 266 | .behavior(context -> () -> { 267 | context.currentActor(String.class); // oops 268 | }) 269 | .onSignal((signal, context) -> box.exception = ((PanicSignal) signal).exception()); 270 | Actor.run(List.of(actor), context -> context.postTo(actor, Runnable::run)); 271 | assertEquals(IllegalActorStateException.class, box.exception.getClass()); 272 | } 273 | 274 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 275 | public void escapeActorContext() throws InterruptedException { 276 | var box = new Object() { Actor.Context context; }; 277 | var actor = Actor.of(Runnable.class); 278 | actor.behavior(context -> () -> { 279 | box.context = context; 280 | context.shutdown(); 281 | }); 282 | Actor.run(List.of(actor), context -> context.postTo(actor, Runnable::run)); 283 | var context = box.context; 284 | assertAll( 285 | () -> assertThrows(IllegalActorStateException.class, () -> context.currentActor(Runnable.class)), 286 | //() -> assertThrows(IllegalActorStateException.class, () -> context.spawn(Actor.of(Runnable.class).behavior(ctx -> () -> {}))), 287 | () -> assertThrows(IllegalActorStateException.class, context::shutdown) 288 | ); 289 | } 290 | 291 | @Test 292 | public void runNull() { 293 | var actor = Actor.of(Runnable.class) 294 | .behavior(context -> context::shutdown); 295 | assertAll( 296 | () -> assertThrows(NullPointerException.class, () -> Actor.run(List.of(actor), null)), 297 | () -> assertThrows(NullPointerException.class, () -> Actor.run(null, context -> {})) 298 | ); 299 | } 300 | 301 | @Test 302 | public void runAllWrongThread() { 303 | var actor = Actor.of(Runnable.class) 304 | .behavior(context -> () -> {}); 305 | new Thread(() -> assertThrows(IllegalActorStateException.class, () -> Actor.run(List.of(actor), startContext -> {}))).start(); 306 | } 307 | 308 | @Test 309 | public void uncaughtExceptionHandlerNull() { 310 | assertThrows(NullPointerException.class, () -> Actor.uncaughtExceptionHandler(null)); 311 | } 312 | 313 | @Test 314 | public void uncaughtExceptionHandlerAlreadySet() { 315 | assertThrows(IllegalActorStateException.class, () -> Actor.uncaughtExceptionHandler((actor, exception) -> {})); 316 | } 317 | 318 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 319 | public void runWithTwoActorsWithSignal() throws InterruptedException { 320 | interface Dummy { 321 | void execute(); 322 | } 323 | var actor1 = Actor.of(Dummy.class); 324 | var actor2 = Actor.of(Dummy.class); 325 | actor1.behavior(context -> () -> context.postTo(actor2, Dummy::execute)); 326 | actor2 327 | .behavior(context -> context::shutdown) 328 | .onSignal((signal, context) -> context.signal(actor1, ShutdownSignal.INSTANCE)); 329 | Actor.run(List.of(actor1, actor2), context -> context.postTo(actor1, Dummy::execute)); 330 | } 331 | 332 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 333 | public void runWithTwoActorsWithPostTo() throws InterruptedException { 334 | interface Ops1 { 335 | void execute(); 336 | void stop(); 337 | } 338 | interface Ops2 { 339 | void execute(); 340 | } 341 | var actor1 = Actor.of(Ops1.class); 342 | var actor2 = Actor.of(Ops2.class); 343 | actor1.behavior(context -> new Ops1() { 344 | @Override 345 | public void execute() { 346 | context.postTo(actor2, Ops2::execute); 347 | } 348 | 349 | @Override 350 | public void stop() { 351 | context.shutdown(); 352 | } 353 | }); 354 | actor2 355 | .behavior(context -> context::shutdown) 356 | .onSignal((signal, context) -> context.postTo(actor1, Ops1::stop)); 357 | Actor.run(List.of(actor1, actor2), context -> context.postTo(actor1, Ops1::execute)); 358 | } 359 | 360 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 361 | public void runAndRestart() throws InterruptedException { 362 | interface Ops { 363 | void execute(int value); 364 | void checkEquals(int expected); 365 | } 366 | var shouldRestart = new AtomicBoolean(true); 367 | var actor = Actor.of(Ops.class) 368 | .behavior(context -> new Ops() { 369 | private int sum; 370 | 371 | @Override 372 | public void execute(int value) { 373 | if (value < 0) { 374 | throw context.panic(new Exception("oops")); 375 | } 376 | sum += value; 377 | } 378 | 379 | @Override 380 | public void checkEquals(int expected) { 381 | assertEquals(expected, sum); 382 | } 383 | }) 384 | .onSignal((signal, context) -> { 385 | if (shouldRestart.get()) { 386 | shouldRestart.set(false); 387 | context.restart(); 388 | } 389 | }); 390 | Actor.run(List.of(actor), context -> { 391 | context.postTo(actor, $ -> $.execute(10)); 392 | context.postTo(actor, $ -> $.execute(-13)); 393 | try { 394 | Thread.sleep(500); 395 | } catch (InterruptedException e) { 396 | throw new AssertionError(e); 397 | } 398 | context.postTo(actor, $ -> $.execute(32)); 399 | context.postTo(actor, $ -> $.checkEquals(32)); 400 | context.postTo(actor, $ -> $.execute(-101)); 401 | }); 402 | } 403 | 404 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 405 | public void runAndSpawnFromActor() throws InterruptedException { 406 | interface Behavior { 407 | void execute(); 408 | void done(); 409 | } 410 | interface Behavior2 { 411 | void execute(int value); 412 | } 413 | var actor = Actor.of(Behavior.class) 414 | .behavior(context -> new Behavior() { 415 | @Override 416 | public void execute() { 417 | var actor2 = Actor.of(Behavior2.class) 418 | .behavior(context -> value -> assertEquals(42, value)); 419 | context.spawn(actor2); 420 | context.postTo(actor2, $ -> $.execute(42)); 421 | } 422 | 423 | @Override 424 | public void done() { 425 | context.shutdown(); // should also shutdown actor2 ! 426 | } 427 | }); 428 | Actor.run(List.of(actor), context -> { 429 | context.postTo(actor, Behavior::execute); 430 | context.postTo(actor, Behavior::done); 431 | }); 432 | } 433 | 434 | @Test @Timeout(value = 5_000, unit = MILLISECONDS) 435 | public void runAndSpawn() throws InterruptedException { 436 | var actor1 = Actor.of(Runnable.class); 437 | var actor2 = Actor.of(Runnable.class); 438 | actor1.behavior(context -> context::shutdown); 439 | actor2 440 | .behavior(context -> () -> { 441 | context.postTo(actor1, Runnable::run); 442 | context.shutdown(); 443 | }); 444 | Actor.run(List.of(actor1), context -> { 445 | context.spawn(actor2); 446 | context.postTo(actor2, Runnable::run); 447 | }); 448 | } 449 | } -------------------------------------------------------------------------------- /todo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 69 | 131 | 132 | 133 |
134 | 135 | 136 |
137 |
138 |
139 | 140 | --------------------------------------------------------------------------------