├── .dockerignore ├── Dockerfile ├── LICENSE ├── README.md ├── src ├── .gitignore ├── app │ ├── Actions │ │ ├── EnqueuePacketAction.php │ │ └── SavePacketAction.php │ ├── Contracts │ │ ├── Action │ │ │ └── PacketActionContract.php │ │ └── PacketParser │ │ │ └── Packet.php │ ├── Pool │ │ ├── DatabaseConnectionPool.php │ │ └── QueueConnectionPool.php │ ├── Server │ │ ├── EventHandler │ │ │ └── SwooleUdpServerEventHandler.php │ │ └── PacketParser │ │ │ └── UdpPacketParser.php │ └── Services │ │ └── BroadcastPacketService.php ├── bin │ ├── bootstrap.php │ └── server.php ├── composer.json ├── example │ ├── client.php │ └── concurent-clients.php └── tests │ ├── Integration │ └── SwooleUdpServerIntegrationTest.php │ └── Unit │ └── UdpPacketParserTest.php └── supervisor └── conf.d ├── server.conf └── swoole.conf.disabled /.dockerignore: -------------------------------------------------------------------------------- 1 | src/vendor 2 | src/vendor/ 3 | src/composer.lock 4 | src/config/pulse.php -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM phpswoole/swoole:5.0.1-php8.2-alpine 2 | ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/ 3 | RUN apk update && apk add --no-cache supervisor 4 | RUN apk add --no-cache libzip-dev 5 | RUN apk add --no-cache msgpack-c 6 | RUN chmod +x /usr/local/bin/install-php-extensions && sync 7 | RUN apk add --no-cache linux-headers 8 | RUN set -ex \ 9 | && apk --no-cache add \ 10 | postgresql14-dev=14.12-r0 11 | RUN set -ex \ 12 | && apk --no-cache add \ 13 | sqlite-dev=3.40.1-r1 14 | RUN docker-php-ext-install pdo pdo_mysql pdo_pgsql pdo_sqlite zip pcntl exif sockets opcache 15 | RUN docker-php-ext-enable pdo pdo_mysql pdo_pgsql pdo_sqlite zip pcntl exif sockets opcache 16 | RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer 17 | RUN apk add --update --virtual builds \ 18 | libc-dev \ 19 | yaml-dev \ 20 | autoconf \ 21 | re2c \ 22 | make \ 23 | gcc \ 24 | g++ \ 25 | gc 26 | RUN pecl channel-update pecl.php.net 27 | RUN pecl install msgpack 28 | RUN docker-php-ext-enable msgpack 29 | COPY src/ /var/www/html/ 30 | COPY supervisor/conf.d /etc/supervisor/conf.d 31 | WORKDIR /var/www/html/ 32 | COPY --from=composer /usr/bin/composer /usr/bin/composer 33 | ENV DISABLE_DEFAULT_SERVER=1 34 | ENV COMPOSER_ALLOW_SUPERUSER=1 35 | RUN composer install --no-interaction --prefer-dist --optimize-autoloader 36 | RUN apk add --no-cache bash 37 | CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/server.conf"] -------------------------------------------------------------------------------- /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 | # GeoPulse 2 | 3 | GeoPulse is a specialized server application designed to handle real-time geolocation data from clients via the UDP protocol. The server captures location coordinates and processes them for various uses, such as real-time tracking and historical data retrieval. GeoPulse is optimized utilizing [GeoJSON](https://geojson.org/) and [Swoole](https://github.com/swoole/swoole-src) to handle numerous simultaneous UDP connections. It integrates seamlessly with [Laravel](https://laravel.com/) queue system, allowing you to capture tracking events using Laravel jobs. 4 | 5 | ## Why GeoPulse? 6 | 7 | ### HTTP Location Updates (Slower) 8 | 9 | 1. **Client Sends HTTP Request:** The client sends periodic HTTP POST requests to update location. 10 | 2. **HTTP Request is Sent to Server:** The request is transmitted over HTTP. 11 | 3. **Server Receives HTTP Request:** The server processes the incoming HTTP request. 12 | 4. **Server Processes Request (Overhead):** The server processes the request with potential delays. 13 | 5. **Server Sends HTTP Response Back to Client:** The server sends a response back to the client. 14 | 6. **Client Receives HTTP Response (OK).** 15 | 16 | ### GeoPulse with UDP (Faster) 17 | 18 | 1. **Client Sends UDP Packet (Continuous):** The client continuously sends UDP packets. 19 | 2. **GeoPulse Server Processes UDP Packet Immediately:** Data is processed immediately. 20 | 3. **No Response Needed (Data Delivered Fast):** No acknowledgment (ACK) is required from the server. 21 | 22 | ## Protocol 23 | 24 | GeoPulse uses a JSON format to transmit data packets over UDP for real-time location tracking. The structure is designed to include all necessary information such as the application ID, client ID, and location data, making it easy to parse and process on the server side. 25 | 26 | ### Example JSON Structure 27 | 28 | ```json 29 | { 30 | "appId": "yourAppId123", 31 | "clientId": "client456", 32 | "data": { 33 | "type": "Point", 34 | "coordinates": [102.0, 0.5] 35 | } 36 | } 37 | ``` 38 | 39 | ### Data Compression 40 | 41 | For bandwidth efficiency, you might consider compressing the JSON payload using [MessagePack](https://msgpack.org/). GeoPulse already supports MessagePack as an alternative to JSON for smaller payload sizes. 42 | 43 | ## Benchmark 44 | 45 | - Kernel: x86_64 Linux 6.8.0-41-generic / Intel Core i5-4590T @ 4x 3GHz / 16GB of ram / Local network 46 | - Tools: Apache Jmeter with [udp plugin](https://jmeter-plugins.org/wiki/UDPRequest/) / number of threads 5000 in 1 second 47 | - pulse-config: open_cpu_affinity = true , 'cpu_affinity_ignore' => [0,1], 'worker_num' => 6 48 | - server responds with "OK" , in real life scenario the server will not responde to the client. 49 | 50 | ![photo_2024-09-08_19-31-14](https://github.com/user-attachments/assets/7aa6efb1-fc8d-44da-a00f-1eeb66299079) 51 | 52 | 53 | ## Installation 54 | 55 | ```bash 56 | docker pull laggounewalid/geopulse:1.0 57 | ``` 58 | 59 | ```bash 60 | docker run -d -p 9505:9505/udp -v ./pulse-config:/var/www/html/config laggounewalid/geopulse:1.0 61 | ``` 62 | 63 | The `pulse-config/` folder must contain a `pulse.php` config file. 64 | 65 | ### Requirements 66 | 67 | - Queue server supported by `illuminate/queue` 68 | - Database supported by `illuminate/database` (Oracle Database not supported by GeoPulse) 69 | 70 | ### Database Table 71 | 72 | ```sql 73 | CREATE TABLE `pulse_coordinates` ( 74 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 75 | `created_at` timestamp NOT NULL DEFAULT current_timestamp(), 76 | `appId` varchar(255) DEFAULT NULL, 77 | `clientId` varchar(255) DEFAULT NULL, 78 | `coordinate` point DEFAULT NULL, 79 | `updated_at` timestamp DEFAULT NULL, 80 | PRIMARY KEY (`id`) 81 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 82 | ``` 83 | 84 | ## Configuration 85 | 86 | Here is a boilerplate PHP code for configuration you can use in `pulse-config/pulse.php`: 87 | 88 | ```php 89 | 'your_app_id_here', 100 | 101 | /* 102 | * Configuration: port 103 | * 104 | * The application port number for the UDP server. 105 | * This port is used to receive incoming packets containing coordinate data. 106 | * Ensure that the specified port (default: 9505) is open and not blocked by a firewall. 107 | */ 108 | 'port' => 9505, 109 | 110 | /* 111 | * Configuration: use-msgPack 112 | * 113 | * A boolean flag to enable or disable MessagePack for data serialization and deserialization. 114 | * When set to true, the server will use MessagePack to unpack received data packets. 115 | * If set to false, the server will process data as raw strings. 116 | */ 117 | 'use-msgPack' => true, 118 | 119 | 'swoole' => [ 120 | 'debug_mode' => true, 121 | 'display_errors' => true, 122 | 'worker_num' => 4, 123 | 'enable_coroutine' => true, 124 | 'open_eof_check' => true, 125 | 'package_eof' => "\r\n", 126 | 'dispatch_mode' => 1, 127 | ], 128 | 129 | /* 130 | * Configuration: enable-queue 131 | * 132 | * Determines whether the server should use queues to process packets. 133 | */ 134 | 'enable-queue' => true, 135 | 136 | /* 137 | * Configuration: queue-pool-size 138 | * 139 | * Specifies the number of queue worker connections created and managed in the Swoole connection pool. 140 | * A larger pool size can help manage a higher volume of queue jobs concurrently, but it also increases memory and resource usage. 141 | * Default value: 10 142 | */ 143 | 'queue-pool-size' => 10, 144 | 145 | /* 146 | * Configuration: queue-connection 147 | * 148 | * Defines the connection settings for the queue driver. Follows the same configuration structure used by Laravel's queue system. 149 | */ 150 | 'queue-connection' => [ 151 | 'driver' => 'redis', 152 | 'connection' => 'default', 153 | 'queue' => 'geopulse', 154 | 'retry_after' => 90, 155 | 'block_for' => null, 156 | 'after_commit' => false, 157 | ], 158 | 159 | 'redis' => [ 160 | 'options' => [ 161 | 'cluster' => 'redis', 162 | 'prefix' => 'YOUR_APP_NAME_database_', 163 | ], 164 | 'default' => [ 165 | 'url' => '', 166 | 'host' => '', 167 | 'username' => '', 168 | 'password' => '', 169 | 'port' => 6379, 170 | 'database' => '0', 171 | ], 172 | ], 173 | 174 | /* 175 | * Configuration: enable-database 176 | * 177 | * Determines whether the server should use a database for storing location records. 178 | */ 179 | 'enable-database' => true, 180 | 181 | /* 182 | * Configuration: db-pool-size 183 | * 184 | * Defines the number of database connections created and added to the Swoole connection pool. 185 | * Increasing the pool size can improve performance when dealing with many concurrent database operations but will also increase resource consumption. 186 | * Default value: 10 187 | */ 188 | 'db-pool-size' => 10, 189 | 190 | /* 191 | * Configuration: database-connection 192 | * 193 | * Defines the database connection settings, following the same structure as Laravel's database configuration file. 194 | */ 195 | 'table-name' => 'pulse_coordinates', 196 | 'database-connection' => [ 197 | 'driver' => 'mariadb', 198 | 'url' => null, 199 | 'host' => 'YOUR_DATABASE_HOST', 200 | 'port' => '3306', 201 | 'database' => 'DB_NAME', 202 | 'username' => 'DB_USER', 203 | 'password' => 'DB_PASSWORD', 204 | 'unix_socket' => null, 205 | 'charset' => 'utf8mb4', 206 | 'collation' => 'utf8mb4_unicode_ci', 207 | 'prefix' => '', 208 | 'prefix_indexes' => true, 209 | 'strict' => false, 210 | 'engine' => null, 211 | ], 212 | ]; 213 | ``` 214 | 215 | ## Example Client in PHP (MessagePack Enabled) 216 | 217 | ```php 218 | connect('0.0.0.0', 9505, 0.5)) { 226 | echo "Connect failed. Error: {$client->errCode}\n"; 227 | } 228 | $data = ['appId' => 'your_app_id_here', 'clientId' => '22f8e456-93f2-4173-8f2d-8a010abcceb1', 'data' => ['type' => 'Point', 'coordinates' => [1, 1]]]; 229 | $data = msgpack_pack($data); 230 | $client->send($data); 231 | $client->close(); 232 | }); 233 | ``` 234 | 235 | ## Laravel Job 236 | 237 | ```php 238 | [ 268 | // "type" => "Point", 269 | // "coordinates" => [1, 1] 270 | // ], 271 | // "appId" => "your_app_id_here", 272 | // "clientId" => "22f8e456-93f2-4173-8f2d-8a010abcceb1" 273 | // ] 274 | $job->delete 275 | 276 | (); 277 | } 278 | } 279 | ``` 280 | 281 | ## Cloning and Implementing Your Own Broadcasters 282 | 283 | To implement your own broadcaster (e.g., Kafka or MongoDB), add the broadcaster in `bin/bootstrap.php`. Your broadcaster needs to be located in `src/app/Actions/` and must implement `PacketActionContract`. 284 | 285 | ```php 286 | add(BroadcastPacketService::class, function () use ($config) { 305 | $broadcaster = new BroadcastPacketService; 306 | $broadcaster->addAction(new PublishToKafkaTopic); 307 | return $broadcaster; 308 | }); 309 | ``` 310 | -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | vendor/* 2 | composer.lock 3 | config/pulse.php 4 | supervisord.* -------------------------------------------------------------------------------- /src/app/Actions/EnqueuePacketAction.php: -------------------------------------------------------------------------------- 1 | queueConnectionsPool->get(); 16 | $queueConnection::push('App\Jobs\PulseLocationUpdatedJob@handle', $packet->toArray()); 17 | $this->queueConnectionsPool->put($queueConnection); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/app/Actions/SavePacketAction.php: -------------------------------------------------------------------------------- 1 | databaseConnectionsPool->get(); 19 | 20 | $db->table($this->table)->insert([ 21 | 'appId' => $packet->getAppId(), 22 | 'clientId' => $packet->getClientId(), 23 | 'coordinate' => DB::raw($this->buildInsertPointQuery($packet->toPoint()->getCoordinates(), $db)), 24 | ]); 25 | $this->databaseConnectionsPool->put($db); 26 | } 27 | 28 | public function buildInsertPointQuery(array $point, Connection $connection): string 29 | { 30 | if ($connection instanceof PostgresConnection) { 31 | return "ST_GeomFromText('POINT(".implode(' ', $point).")')::POINT"; 32 | } 33 | return "ST_GeomFromText('POINT(".implode(' ', $point).")')"; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/app/Contracts/Action/PacketActionContract.php: -------------------------------------------------------------------------------- 1 | $data 24 | * @return bool if data is valide. 25 | */ 26 | public function dataIsValide(array $data): bool; 27 | 28 | /** 29 | * Retrieve the App ID included in the packet. 30 | * 31 | * This method extracts the App ID from the packet 32 | * 33 | * @return string Returns the App ID as a string. 34 | */ 35 | public function getAppId(): string; 36 | 37 | /** 38 | * Retrieve the Client ID included in the packet. 39 | * 40 | * This method extracts the Client ID from the packet 41 | * 42 | * @return string Returns the Client ID as a string. 43 | */ 44 | public function getClientId(): string; 45 | 46 | /** 47 | * Convert the Packet instance to a GeoJSON Point object. 48 | * 49 | * This method transforms the Packet data into a GeoJSON Point object, which represents 50 | * geographical coordinates and is used for spatial data. 51 | * 52 | * @return Point Returns a GeoJSON Point object if conversion is possible. 53 | */ 54 | public function toPoint(): Point; 55 | 56 | /** 57 | * Convert the Packet instance to a JSON string. 58 | * 59 | * This method serializes the Packet data into a JSON string format, which is suitable for transmission 60 | * or storage. This typically includes all relevant packet information in JSON format. 61 | * 62 | * @return string Returns the serialized Packet data as a JSON string. 63 | */ 64 | public function toJson(): string; 65 | 66 | /** 67 | * Convert the Packet instance to a php array. 68 | * 69 | * This method serializes the Packet data into a php array format 70 | * 71 | * @return array{ 72 | * point: \GeoJson\Geometry\Point, 73 | * appId: string, 74 | * clientId: string 75 | * } 76 | */ 77 | public function toArray(): array; 78 | } 79 | -------------------------------------------------------------------------------- /src/app/Pool/DatabaseConnectionPool.php: -------------------------------------------------------------------------------- 1 | get(DB::class); 15 | $db->getConnection()->getPdo(); 16 | return $db->connection('default'); 17 | }, $size); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/app/Pool/QueueConnectionPool.php: -------------------------------------------------------------------------------- 1 | get(Queue::class); 15 | }, $size); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/app/Server/EventHandler/SwooleUdpServerEventHandler.php: -------------------------------------------------------------------------------- 1 | udpPacketParser->fromString($data); 20 | 21 | if ($packet === null) { 22 | return false; 23 | } 24 | 25 | // Verify that the App ID sent from the client matches the server's configured App ID 26 | // This ensures that only authorized clients can send data to the server 27 | if ($this->appId !== $packet->getAppId()) { 28 | // Since UDP is connectionless protocol, we simply return false if the App ID does not match 29 | // No further action is needed for unauthorized packets 30 | return false; 31 | } 32 | $this->broadcastPacketService->dropAndPopPacket($packet); 33 | 34 | return true; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/app/Server/PacketParser/UdpPacketParser.php: -------------------------------------------------------------------------------- 1 | 17 | * } 18 | */ 19 | private array $payload; 20 | 21 | /** 22 | * The Application ID extracted from the packet data. 23 | */ 24 | private string $appId; 25 | 26 | /** 27 | * The Client ID extracted from the packet data. 28 | */ 29 | private string $clientId; 30 | 31 | public function __construct(private bool $usingMsgPack) {} 32 | 33 | public function fromString(string $data): ?Packet 34 | { 35 | try { 36 | if ($this->usingMsgPack) { 37 | $unpackedData = msgpack_unpack($data); 38 | } else { 39 | $unpackedData = json_decode($data, true); 40 | } 41 | } catch (\Throwable $th) { 42 | $unpackedData = []; 43 | } 44 | 45 | if ($unpackedData !== [] and $unpackedData !== null and is_array($unpackedData)) { 46 | if ($this->dataIsValide($unpackedData)) { 47 | $this->appId = $unpackedData['appId']; 48 | $this->clientId = $unpackedData['clientId']; 49 | $this->payload = $unpackedData['data']; 50 | return $this; 51 | } 52 | } 53 | 54 | return null; 55 | } 56 | 57 | public function dataIsValide(array $data): bool 58 | { 59 | return array_key_exists('appId', $data) and array_key_exists('clientId', $data) and array_key_exists('data', $data); 60 | } 61 | 62 | public function getAppId(): string 63 | { 64 | return $this->appId; 65 | } 66 | 67 | public function getClientId(): string 68 | { 69 | return $this->clientId; 70 | } 71 | 72 | public function toPoint(): Point 73 | { 74 | try { 75 | $point = GeoJson::jsonUnserialize($this->payload); 76 | } catch (\Throwable $th) { 77 | return GeoJson::jsonUnserialize(['type' => 'Point', 'coordinates' => [0, 0]]); 78 | } 79 | 80 | if (! ($point instanceof Point)) { 81 | return GeoJson::jsonUnserialize(['type' => 'Point', 'coordinates' => [0, 0]]); 82 | } 83 | 84 | return $point; 85 | } 86 | 87 | public function toJson(): string 88 | { 89 | $json = json_encode($this->toArray()); 90 | if (! $json) { 91 | return "{}"; 92 | } 93 | return $json; 94 | } 95 | 96 | public function toArray(): array 97 | { 98 | return [ 99 | 'point' => $this->toPoint(), 100 | 'appId' => $this->getAppId(), 101 | 'clientId' => $this->getClientId(), 102 | ]; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/app/Services/BroadcastPacketService.php: -------------------------------------------------------------------------------- 1 | actions[] = $action; 17 | } 18 | 19 | public function dropAndPopPacket(Packet $packet): void 20 | { 21 | foreach ($this->actions as $action) { 22 | // @phpstan-ignore-next-line 23 | go(function () use ($action, $packet) { 24 | $action->handle($packet); 25 | }); 26 | 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/bin/bootstrap.php: -------------------------------------------------------------------------------- 1 | add(Queue::class, function () use ($config) { 22 | $queue = new Queue; 23 | $queue->addConnection($config['queue-connection']); 24 | $queue->setAsGlobal(); 25 | 26 | if ($config['queue-connection']['driver'] === 'redis') { 27 | $laravelContainer = new LaravelContainer; 28 | $redisConfig = $config['redis']; 29 | $redisConfig['client'] = 'predis'; 30 | $redisManager = new RedisManager($laravelContainer, $redisConfig['client'], $redisConfig); 31 | $queue->getContainer()->singleton('redis', function () use ($redisManager) { 32 | return $redisManager; 33 | }); 34 | } 35 | 36 | return $queue; 37 | }); 38 | } 39 | 40 | if ($config['enable-database']) { 41 | $container->add(DB::class, function () use ($config) { 42 | $db = new DB; 43 | 44 | $db->addConnection($config['database-connection']); 45 | $db->setAsGlobal(); 46 | $db->bootEloquent(); 47 | 48 | return $db; 49 | }); 50 | } 51 | 52 | $container->add(BroadcastPacketService::class, function () use ($config, $container) { 53 | $broadcaster = new BroadcastPacketService; 54 | if ($config['enable-queue']) { 55 | $queueConnectionsPool = new QueueConnectionPool($container, $config['queue-pool-size']); 56 | $broadcaster->addAction(new EnqueuePacketAction($queueConnectionsPool)); 57 | } 58 | if ($config['enable-database']) { 59 | $databaseConnectionsPool = new DatabaseConnectionPool($container, $config['db-pool-size']); 60 | $broadcaster->addAction(new SavePacketAction($databaseConnectionsPool, $config['table-name'])); 61 | } 62 | 63 | return $broadcaster; 64 | }); 65 | 66 | $container->add(UdpPacketParser::class)->addArgument($config['use-msgPack']); 67 | $container->add(SwooleUdpServerEventHandler::class) 68 | ->addArgument(UdpPacketParser::class) 69 | ->addArgument(BroadcastPacketService::class) 70 | ->addArgument($config['appId']); 71 | $swooleUdpEventsHandler = $container->get(SwooleUdpServerEventHandler::class); 72 | -------------------------------------------------------------------------------- /src/bin/server.php: -------------------------------------------------------------------------------- 1 | set($config['swoole']); 12 | $server->on('Packet', [$swooleUdpEventsHandler, 'onPacket']); 13 | $server->start(); 14 | -------------------------------------------------------------------------------- /src/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "illuminate/queue": "^11.21", 4 | "illuminate/events": "^11.21", 5 | "illuminate/database": "^11.21", 6 | "aws/aws-sdk-php": "^3.320", 7 | "pda/pheanstalk": "^5.0", 8 | "predis/predis": "^2.0", 9 | "jmikola/geojson": "^1.0", 10 | "league/container": "^4.2", 11 | "illuminate/redis": "^11.21" 12 | }, 13 | "require-dev": { 14 | "laravel/pint": "^1.17", 15 | "phpunit/phpunit": "^11", 16 | "phpstan/phpstan": "^1.12" 17 | }, 18 | "autoload": { 19 | "psr-4": { 20 | "Pulse\\": "app/" 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/example/client.php: -------------------------------------------------------------------------------- 1 | connect('192.168.1.4', 9505, 0.5)) { 10 | echo "connect failed. Error: {$client->errCode}\n"; 11 | } 12 | $data = ['appId' => '123', 'clientId' => '22f8e456-93f2-4173-8f2d-8a010abcceb1', 'data' => ['type' => 'Point', 'coordinates' => [-14.80665, -140.22159]]]; 13 | // $data = msgpack_pack($data); 14 | $data = json_encode($data); 15 | $client->send($data); 16 | $client->close(); 17 | }); 18 | -------------------------------------------------------------------------------- /src/example/concurent-clients.php: -------------------------------------------------------------------------------- 1 | '123', 'clientId' => '22f8e456-93f2-4173-8f2d-8a010abcceb1', 'data' => ['type' => 'Point', 'coordinates' => [1, 1]]]; 13 | $jsonData = msgpack_pack($data); 14 | 15 | function simulateClient($host, $port, $jsonData, $sendInterval) 16 | { 17 | $client = new Client(SWOOLE_SOCK_UDP); 18 | 19 | if (! $client->connect($host, $port, 0.5)) { 20 | echo "Connect failed. Error: {$client->errCode}\n"; 21 | 22 | return; 23 | } 24 | while (true) { 25 | $client->send($jsonData); 26 | Coroutine::sleep($sendInterval / 1000); 27 | } 28 | 29 | $client->close(); 30 | } 31 | 32 | run(function () use ($numberOfClients, $jsonData, $sendInterval) { 33 | $host = '192.168.1.12'; 34 | $port = 9505; 35 | for ($i = 0; $i < $numberOfClients; $i++) { 36 | go(function () use ($host, $port, $jsonData, $sendInterval) { 37 | simulateClient($host, $port, $jsonData, $sendInterval); 38 | }); 39 | } 40 | 41 | echo "Load test with {$numberOfClients} clients sending messages every {$sendInterval}ms started.\n"; 42 | }); 43 | -------------------------------------------------------------------------------- /src/tests/Integration/SwooleUdpServerIntegrationTest.php: -------------------------------------------------------------------------------- 1 | 'validAppId', 23 | 'clientId' => 'client123', 24 | 'data' => [ 25 | 'type' => 'Point', 26 | 'coordinates' => [102.0, 0.5], 27 | ], 28 | ]); 29 | 30 | $serverStub = $this->getMockBuilder(Server::class)->disableOriginalConstructor()->getMock(); 31 | $serverStub->method('task') 32 | ->willReturn(1); 33 | $udpPacketParser = new UdpPacketParser(false); 34 | $broadcastService = $this->createMock(BroadcastPacketService::class); 35 | $enqueuePacketAction = $this->createMock(EnqueuePacketAction::class); 36 | $savePacketAction = $this->createMock(SavePacketAction::class); 37 | $broadcastService->addAction($enqueuePacketAction); 38 | $broadcastService->addAction($savePacketAction); 39 | 40 | $serverHandler = new SwooleUdpServerEventHandler($udpPacketParser, $broadcastService, 'validAppId'); 41 | $broadcastService->expects($this->once()) 42 | ->method('dropAndPopPacket'); 43 | $result = $serverHandler->onPacket($serverStub, $packetData, ['address' => '127.0.0.1', 'port' => 12345]); 44 | $this->assertTrue($result); 45 | $packet = $udpPacketParser->fromString($packetData); 46 | $this->assertNotNull($packet); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/tests/Unit/UdpPacketParserTest.php: -------------------------------------------------------------------------------- 1 | 123, 'clientId' => 123, 'data' => []]); 19 | $packet = $udpPacketParser->fromString($data); 20 | $this->assertEquals($packet->getAppId(), 123); 21 | } 22 | 23 | public function testThatMsgPackedDataIsNotUnpackedIfMsgpackDisabled(): void 24 | { 25 | $udpPacketParser = new UdpPacketParser(false); 26 | $data = json_encode(['appId' => 123, 'clientId' => 123, 'data' => []]); 27 | $packet = $udpPacketParser->fromString($data); 28 | $this->assertEquals($packet->getAppId(), 123); 29 | } 30 | 31 | public function testGettingAppId(): void 32 | { 33 | $udpPacketParser = new UdpPacketParser(false); 34 | $data = '{"data":{"type":"Point","coordinates":[1,1]},"appId":"22f8e456-93f2-4173-8f2d-8a010abcceb1","clientId":"22f8e456-93f2-4173-8f2d-8a010abcceb1"}'; 35 | $packet = $udpPacketParser->fromString($data); 36 | $this->assertEquals('22f8e456-93f2-4173-8f2d-8a010abcceb1', $packet->getAppId()); 37 | } 38 | 39 | public function testGettingPointFromData(): void 40 | { 41 | $udpPacketParser = new UdpPacketParser(false); 42 | $data = '{"data":{"type":"Point","coordinates":[1,1]},"appId":"22f8e456-93f2-4173-8f2d-8a010abcceb1","clientId":"22f8e456-93f2-4173-8f2d-8a010abcceb1"}'; 43 | $packet = $udpPacketParser->fromString($data); 44 | $this->assertTrue($packet->toPoint() instanceof Point); 45 | } 46 | 47 | public function testGettingNullPointFromDataThatDosentHaveJson(): void 48 | { 49 | $udpPacketParser = new UdpPacketParser(false); 50 | $data = ''; 51 | $packet = $udpPacketParser->fromString($data); 52 | $this->assertEquals(null, $packet); 53 | } 54 | 55 | public function testGettingNullPointFromData(): void 56 | { 57 | $udpPacketParser = new UdpPacketParser(false); 58 | $data = '{"data":{},"appId":"22f8e456-93f2-4173-8f2d-8a010abcceb1","clientId":"22f8e456-93f2-4173-8f2d-8a010abcceb1"}'; 59 | $packet = $udpPacketParser->fromString($data); 60 | $this->assertEquals([0,0], $packet->toPoint()->getCoordinates()); 61 | } 62 | 63 | public function testGettingEmptyJsonOfNonValidePoint(): void 64 | { 65 | $udpPacketParser = new UdpPacketParser(false); 66 | $data = '{"data":{"type":"Point"},"appId":"22f8e456-93f2-4173-8f2d-8a010abcceb1","clientId":"22f8e456-93f2-4173-8f2d-8a010abcceb1"}'; 67 | $packet = $udpPacketParser->fromString($data); 68 | $this->assertEquals($packet->toPoint()->getCoordinates(), [0, 0]); 69 | $this->assertEquals('{"point":{"type":"Point","coordinates":[0,0]},"appId":"22f8e456-93f2-4173-8f2d-8a010abcceb1","clientId":"22f8e456-93f2-4173-8f2d-8a010abcceb1"}', $packet->toJson()); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /supervisor/conf.d/server.conf: -------------------------------------------------------------------------------- 1 | [unix_http_server] 2 | file=/run/supervisord.sock 3 | chmod=0700 4 | 5 | [supervisord] 6 | nodaemon=true 7 | # logfile=/var/log/supervisor/supervisord.log 8 | # childlogdir=/var/log/supervisor 9 | 10 | [rpcinterface:supervisor] 11 | supervisor.rpcinterface_factory=supervisor.rpcinterface:make_main_rpcinterface 12 | 13 | [supervisorctl] 14 | serverurl=unix:///run/supervisord.sock 15 | [program:server] 16 | command = php /var/www/html/bin/server.php 17 | user = root 18 | autostart = true 19 | autorestart = true 20 | stdout_logfile=/proc/self/fd/1 21 | stdout_logfile_maxbytes=0 22 | stderr_logfile=/proc/self/fd/1 23 | stderr_logfile_maxbytes=0 24 | -------------------------------------------------------------------------------- /supervisor/conf.d/swoole.conf.disabled: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | user = root 3 | 4 | [program:swoole] 5 | command = php /var/www/server.php 6 | user = root 7 | autostart = true 8 | autorestart = true 9 | stdout_logfile=/proc/self/fd/1 10 | stdout_logfile_maxbytes=0 11 | stderr_logfile=/proc/self/fd/1 12 | stderr_logfile_maxbytes=0 13 | --------------------------------------------------------------------------------