@trap_stevo/ucr
Version:
The ultimate event routing solution for dynamic, filter-driven, TTL-enforced communication. Build intelligent, reactive communication layers across clients or processes โ with deep filter matching, TTL-based cleanup, customizable operators, and smart broa
212 lines (144 loc) โข 6.8 kB
Markdown
# ๐ก @trap_stevo/ucr
**The ultimate event routing solution for dynamic, filter-driven, TTL-enforced communication.**
Build intelligent, reactive communication layers across clients or processes โ with deep filter matching, TTL-based cleanup, customizable operators, and smart broadcast control.
## ๐งพ UCR?
**UCR (Universal Communication Router)** powers dynamic client coordination with a lightweight, framework-agnostic engine for managing connections and routing events using expressive, JSON-like filters.
Use cases:
- ๐งช **Real-time dashboards** โ deliver updates only to users matching roles or state
- ๐ **Multiplayer systems** โ notify players or devices that meet specific conditions
- ๐ง **AI routing layers** โ direct tasks to models or workers based on context
- ๐น๏ธ **IoT/twin networks** โ route events using location, status, or group metadata
## ๐ Networking Perspective
๐ง **UCR filters packets at the source** โ before they leave your system.
Instead of broadcasting to all connected clients, it emits only to those matching dynamic filter rules, avoiding unnecessary traffic by design.
This mirrors techniques like:
- **Interest Management** in multiplayer games
- **Selective Event Routing** in real-time systems
- **Application-layer Packet Filtering** for event-driven architectures
UCR routes **who receives what** โ plug into any transport and drive precise, rule-based event delivery.
## ๐ Features
- ๐ง **Deep Filter Matching** โ Match nested fields with advanced logic and operators
- โ **TTL Management** โ Auto-disconnect inactive clients based on time-to-live
- ๐งฉ **Custom Operators** โ Extend filter logic with your own rule definitions
- ๐ฃ **Conditional Broadcasting** โ Send to clients matching flexible filters or predicates
- ๐งญ **Filter Description Helper** โ Generate human-readable summaries of filter objects
- ๐งผ **Safe Socket Cleanup** โ Auto-handle socket disconnects to prevent memory leaks
- ๐งฐ **Composable Filters** โ Use `UCR.filter()` builder for reusable matching logic
## โ๏ธ Client Management
| Method | Description |
|-------------------------------|---------------------------------------------------------------|
| `registerClient(clientID, ttl, data)` | Register or renew a client with optional TTL and metadata |
| `updateClientData(clientID, updates)` | Merge updates into the client's existing metadata |
| `disconnectClient(clientID)` | Manually disconnect and remove a client |
| `handleSocketDisconnect(clientID)` | Alias for safe cleanup when socket closes or crashes |
## ๐ Broadcasting & Filtering
| Method | Description |
|-------------------------------------|-------------------------------------------------------------------|
| `broadcastWhere(filter, event, payload)` | Emit to all clients matching a filter or predicate function |
| `matchFilter(filter)` | Compile a reusable filter function based on operators |
| `registerOperator(name, fn)` | Define your own comparison operator (e.g., `$mod`, `$startswith`) |
## ๐งฎ Built-In Operators
| Operator | Description |
|------------|----------------------------------------------|
| `$eq` | Equals |
| `$ne` | Not equal |
| `$gt` | Greater than |
| `$lt` | Less than |
| `$gte` | Greater than or equal |
| `$lte` | Less than or equal |
| `$in` | Value is in list |
| `$nin` | Value is NOT in list |
| `$exists` | Key exists (or not) |
| `$test` | Custom function test |
## ๐ง Filter Description
| Method | Description |
|----------------------------|-----------------------------------------------------|
| `UCR.describeFilter(filter)` | Converts a filter into a human-readable sentence |
## ๐ฆ Installation
```bash
npm install @trap_stevo/ucr
```
```js
const filter = UCR
.filter("level").greaterThan(50)
.and("faction").equals("red");
console.log(UCR.describeFilter(filter)); // --> Level greater than 50 and faction equal to "red"
```
## ๐งฐ Filter Builder (Advanced)
| Method | Description |
|------------------------|----------------------------------------------|
| `UCR.filter(field)` | Returns a `UCRFilterManager` for chaining |
```js
const filter = UCR.filter("status").equals("online").and("region").in(["US", "EU"]).build();
```
## ๐ ๏ธ Constructor
```js
const { UCR } = require("@trap_stevo/ucr");
const ucr = new UCR((clientID, event, payload) => {
// Your send logic here (e.g., WebSocket, socket.io, IoTide, etc.)
});
```
## ๐ก Example Usage
### Registering a client
```js
ucr.registerClient("client-abc", 30000, {
role : "admin",
region : "US"
});
```
### Updating metadata
```js
ucr.updateClientData("client-abc", {
online : true
});
```
### Broadcasting
```js
ucr.broadcastWhere({ role : "admin" }, "admin-alert", { message : "System going down" });
```
### Using complex filters
```js
ucr.broadcastWhere({
$or : [
{ "region" : { $eq : "US" } },
{ "status" : { $eq : "critical" } }
]
}, "alert", { severity : "high" });
```
## ๐ Custom Operators
```js
ucr.registerOperator("$startswith", (a, b) => typeof a === "string" && a.startsWith(b));
ucr.broadcastWhere({
username : { $startswith : "admin_" }
}, "restricted-notice", {});
```
## โป๏ธ TTL Auto-Disconnect
Clients are auto-disconnected after their TTL (default `30000ms`) unless re-registered:
```js
ucr.registerClient("client-x", 10000); // disconnects in 10 seconds
```
You can manually disconnect or hook into socket closures:
```js
ucr.disconnectClient("client-x");
// or when a socket disconnects
socket.on("close", () => ucr.handleSocketDisconnect("client-x"));
```
## ๐ License
See [LICENSE.md](./LICENSE.md)
## ๐ Route Smart. Route Right.
**UCR** enables event-driven, resilient, and context-aware communication across distributed systems. With rich filter support and deep client control, you gain a powerful foundation for your next-gen messaging or coordination layer.