@gravito/ripple 3.1.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/README.md +260 -19
  2. package/dist/atlas/src/DB.d.ts +348 -0
  3. package/dist/atlas/src/OrbitAtlas.d.ts +9 -0
  4. package/dist/atlas/src/config/defineConfig.d.ts +14 -0
  5. package/dist/atlas/src/config/index.d.ts +7 -0
  6. package/dist/atlas/src/config/loadConfig.d.ts +41 -0
  7. package/dist/atlas/src/connection/Connection.d.ts +112 -0
  8. package/dist/atlas/src/connection/ConnectionManager.d.ts +180 -0
  9. package/dist/atlas/src/connection/ReplicaConnectionPool.d.ts +54 -0
  10. package/dist/atlas/src/drivers/BunSQLDriver.d.ts +32 -0
  11. package/dist/atlas/src/drivers/BunSQLPreparedStatement.d.ts +118 -0
  12. package/dist/atlas/src/drivers/MongoDBDriver.d.ts +36 -0
  13. package/dist/atlas/src/drivers/MySQLDriver.d.ts +79 -0
  14. package/dist/atlas/src/drivers/PostgresDriver.d.ts +96 -0
  15. package/dist/atlas/src/drivers/RedisDriver.d.ts +43 -0
  16. package/dist/atlas/src/drivers/SQLiteDriver.d.ts +45 -0
  17. package/dist/atlas/src/drivers/types.d.ts +260 -0
  18. package/dist/atlas/src/errors/index.d.ts +45 -0
  19. package/dist/atlas/src/grammar/Grammar.d.ts +342 -0
  20. package/dist/atlas/src/grammar/MongoGrammar.d.ts +47 -0
  21. package/dist/atlas/src/grammar/MySQLGrammar.d.ts +54 -0
  22. package/dist/atlas/src/grammar/NullGrammar.d.ts +35 -0
  23. package/dist/atlas/src/grammar/PostgresGrammar.d.ts +62 -0
  24. package/dist/atlas/src/grammar/SQLiteGrammar.d.ts +32 -0
  25. package/dist/atlas/src/index.d.ts +79 -0
  26. package/dist/atlas/src/migration/Migration.d.ts +64 -0
  27. package/dist/atlas/src/migration/MigrationRepository.d.ts +65 -0
  28. package/dist/atlas/src/migration/Migrator.d.ts +110 -0
  29. package/dist/atlas/src/migration/index.d.ts +6 -0
  30. package/dist/atlas/src/observability/AtlasMetrics.d.ts +33 -0
  31. package/dist/atlas/src/observability/AtlasObservability.d.ts +15 -0
  32. package/dist/atlas/src/observability/AtlasTracer.d.ts +12 -0
  33. package/dist/atlas/src/observability/index.d.ts +9 -0
  34. package/dist/atlas/src/orm/Repository.d.ts +247 -0
  35. package/dist/atlas/src/orm/index.d.ts +6 -0
  36. package/dist/atlas/src/orm/model/DirtyTracker.d.ts +121 -0
  37. package/dist/atlas/src/orm/model/Model.d.ts +458 -0
  38. package/dist/atlas/src/orm/model/ModelRegistry.d.ts +20 -0
  39. package/dist/atlas/src/orm/model/concerns/HasAttributes.d.ts +150 -0
  40. package/dist/atlas/src/orm/model/concerns/HasEvents.d.ts +36 -0
  41. package/dist/atlas/src/orm/model/concerns/HasPersistence.d.ts +92 -0
  42. package/dist/atlas/src/orm/model/concerns/HasRelationships.d.ts +117 -0
  43. package/dist/atlas/src/orm/model/concerns/HasSerialization.d.ts +64 -0
  44. package/dist/atlas/src/orm/model/concerns/applyMixins.d.ts +15 -0
  45. package/dist/atlas/src/orm/model/concerns/index.d.ts +12 -0
  46. package/dist/atlas/src/orm/model/decorators.d.ts +138 -0
  47. package/dist/atlas/src/orm/model/errors.d.ts +52 -0
  48. package/dist/atlas/src/orm/model/index.d.ts +10 -0
  49. package/dist/atlas/src/orm/model/relationships.d.ts +207 -0
  50. package/dist/atlas/src/orm/model/types.d.ts +12 -0
  51. package/dist/atlas/src/orm/schema/SchemaRegistry.d.ts +124 -0
  52. package/dist/atlas/src/orm/schema/SchemaSniffer.d.ts +54 -0
  53. package/dist/atlas/src/orm/schema/index.d.ts +6 -0
  54. package/dist/atlas/src/orm/schema/types.d.ts +85 -0
  55. package/dist/atlas/src/pool/AdaptivePoolManager.d.ts +98 -0
  56. package/dist/atlas/src/pool/PoolHealthChecker.d.ts +91 -0
  57. package/dist/atlas/src/pool/PoolStrategy.d.ts +129 -0
  58. package/dist/atlas/src/pool/PoolWarmer.d.ts +92 -0
  59. package/dist/atlas/src/query/Expression.d.ts +60 -0
  60. package/dist/atlas/src/query/NPlusOneDetector.d.ts +10 -0
  61. package/dist/atlas/src/query/QueryBuilder.d.ts +643 -0
  62. package/dist/atlas/src/query/RelationshipResolver.d.ts +23 -0
  63. package/dist/atlas/src/query/clauses/GroupByClause.d.ts +51 -0
  64. package/dist/atlas/src/query/clauses/HavingClause.d.ts +70 -0
  65. package/dist/atlas/src/query/clauses/JoinClause.d.ts +87 -0
  66. package/dist/atlas/src/query/clauses/LimitClause.d.ts +82 -0
  67. package/dist/atlas/src/query/clauses/OrderByClause.d.ts +69 -0
  68. package/dist/atlas/src/query/clauses/SelectClause.d.ts +71 -0
  69. package/dist/atlas/src/query/clauses/WhereClause.d.ts +167 -0
  70. package/dist/atlas/src/query/clauses/index.d.ts +11 -0
  71. package/dist/atlas/src/schema/Blueprint.d.ts +276 -0
  72. package/dist/atlas/src/schema/ColumnDefinition.d.ts +154 -0
  73. package/dist/atlas/src/schema/ForeignKeyDefinition.d.ts +37 -0
  74. package/dist/atlas/src/schema/MigrationGenerator.d.ts +45 -0
  75. package/dist/atlas/src/schema/Schema.d.ts +131 -0
  76. package/dist/atlas/src/schema/SchemaDiff.d.ts +73 -0
  77. package/dist/atlas/src/schema/TypeGenerator.d.ts +57 -0
  78. package/dist/atlas/src/schema/TypeWriter.d.ts +42 -0
  79. package/dist/atlas/src/schema/grammars/MySQLSchemaGrammar.d.ts +23 -0
  80. package/dist/atlas/src/schema/grammars/PostgresSchemaGrammar.d.ts +26 -0
  81. package/dist/atlas/src/schema/grammars/SQLiteSchemaGrammar.d.ts +28 -0
  82. package/dist/atlas/src/schema/grammars/SchemaGrammar.d.ts +97 -0
  83. package/dist/atlas/src/schema/grammars/index.d.ts +7 -0
  84. package/dist/atlas/src/schema/index.d.ts +8 -0
  85. package/dist/atlas/src/seed/Factory.d.ts +90 -0
  86. package/dist/atlas/src/seed/Seeder.d.ts +28 -0
  87. package/dist/atlas/src/seed/SeederRunner.d.ts +74 -0
  88. package/dist/atlas/src/seed/index.d.ts +6 -0
  89. package/dist/atlas/src/sharding/ShardingManager.d.ts +59 -0
  90. package/dist/atlas/src/types/index.d.ts +1182 -0
  91. package/dist/atlas/src/utils/CursorEncoding.d.ts +63 -0
  92. package/dist/atlas/src/utils/levenshtein.d.ts +9 -0
  93. package/dist/core/src/CommandKernel.d.ts +33 -0
  94. package/dist/core/src/ConfigManager.d.ts +39 -0
  95. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  96. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  97. package/dist/core/src/Container.d.ts +86 -11
  98. package/dist/core/src/ErrorHandler.d.ts +3 -0
  99. package/dist/core/src/HookManager.d.ts +511 -4
  100. package/dist/core/src/PlanetCore.d.ts +89 -0
  101. package/dist/core/src/RequestContext.d.ts +97 -0
  102. package/dist/core/src/Router.d.ts +1 -5
  103. package/dist/core/src/ServiceProvider.d.ts +22 -0
  104. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +1 -0
  105. package/dist/core/src/adapters/PhotonAdapter.d.ts +5 -0
  106. package/dist/core/src/adapters/bun/BunContext.d.ts +4 -0
  107. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +1 -0
  108. package/dist/core/src/adapters/types.d.ts +27 -0
  109. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  110. package/dist/core/src/engine/AOTRouter.d.ts +7 -12
  111. package/dist/core/src/engine/FastContext.d.ts +27 -2
  112. package/dist/core/src/engine/Gravito.d.ts +0 -1
  113. package/dist/core/src/engine/MinimalContext.d.ts +25 -2
  114. package/dist/core/src/engine/types.d.ts +9 -1
  115. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  116. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  117. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  118. package/dist/core/src/events/DeadLetterQueue.d.ts +219 -0
  119. package/dist/core/src/events/EventBackend.d.ts +12 -0
  120. package/dist/core/src/events/EventOptions.d.ts +204 -0
  121. package/dist/core/src/events/EventPriorityQueue.d.ts +301 -0
  122. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  123. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  124. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  125. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  126. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  127. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  128. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  129. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  130. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  131. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  132. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  133. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  134. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  135. package/dist/core/src/events/index.d.ts +25 -0
  136. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  137. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  138. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  139. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +332 -0
  140. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  141. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  142. package/dist/core/src/events/observability/index.d.ts +24 -0
  143. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  144. package/dist/core/src/events/types.d.ts +134 -0
  145. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  146. package/dist/core/src/exceptions/index.d.ts +1 -0
  147. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  148. package/dist/core/src/http/types.d.ts +40 -0
  149. package/dist/core/src/index.d.ts +25 -4
  150. package/dist/core/src/instrumentation/index.d.ts +35 -0
  151. package/dist/core/src/instrumentation/opentelemetry.d.ts +178 -0
  152. package/dist/core/src/instrumentation/types.d.ts +182 -0
  153. package/dist/core/src/observability/Metrics.d.ts +244 -0
  154. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  155. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +350 -0
  156. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  157. package/dist/core/src/reliability/index.d.ts +6 -0
  158. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  159. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  160. package/dist/index.js +6709 -9888
  161. package/dist/index.js.map +64 -62
  162. package/dist/photon/src/index.d.ts +19 -0
  163. package/dist/photon/src/middleware/ratelimit-redis.d.ts +50 -0
  164. package/dist/photon/src/middleware/ratelimit.d.ts +161 -0
  165. package/dist/photon/src/openapi.d.ts +19 -0
  166. package/dist/proto/ripple.proto +120 -0
  167. package/dist/ripple/src/RippleServer.d.ts +64 -445
  168. package/dist/ripple/src/channels/ChannelManager.d.ts +25 -10
  169. package/dist/ripple/src/drivers/NATSDriver.d.ts +87 -0
  170. package/dist/ripple/src/drivers/RedisDriver.d.ts +30 -1
  171. package/dist/ripple/src/drivers/index.d.ts +1 -0
  172. package/dist/ripple/src/engines/BunEngine.d.ts +98 -0
  173. package/dist/ripple/src/engines/IRippleEngine.d.ts +205 -0
  174. package/dist/ripple/src/engines/UWebSocketsEngine.d.ts +97 -0
  175. package/dist/ripple/src/engines/WsEngine.d.ts +69 -0
  176. package/dist/ripple/src/engines/index.d.ts +15 -0
  177. package/dist/ripple/src/index.d.ts +2 -0
  178. package/dist/ripple/src/middleware/InterceptorManager.d.ts +21 -0
  179. package/dist/ripple/src/observability/RippleMetrics.d.ts +24 -0
  180. package/dist/ripple/src/reliability/AckManager.d.ts +48 -0
  181. package/dist/ripple/src/serializers/ISerializer.d.ts +39 -0
  182. package/dist/ripple/src/serializers/JsonSerializer.d.ts +19 -0
  183. package/dist/ripple/src/serializers/ProtobufSerializer.d.ts +41 -0
  184. package/dist/ripple/src/serializers/index.d.ts +3 -0
  185. package/dist/ripple/src/tracking/SessionManager.d.ts +104 -0
  186. package/dist/ripple/src/tracking/index.d.ts +1 -0
  187. package/dist/ripple/src/types.d.ts +188 -12
  188. package/dist/ripple/src/utils/MessageSerializer.d.ts +33 -23
  189. package/dist/ripple/src/utils/TokenBucket.d.ts +25 -0
  190. package/package.json +25 -8
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @fileoverview NATS driver for @gravito/ripple
3
+ *
4
+ * @module @gravito/ripple/drivers
5
+ */
6
+ import type { ConnectionOptions } from 'nats';
7
+ import type { RippleLogger } from '../logging/Logger';
8
+ import type { DriverStatus, PresenceUserInfo, RippleDriver } from '../types';
9
+ /**
10
+ * Configuration for the NATSDriver.
11
+ */
12
+ export interface NATSDriverConfig {
13
+ /** NATS server URL (default: 'nats://localhost:4222') */
14
+ servers?: string | string[];
15
+ /** Credentials for authentication */
16
+ user?: string;
17
+ password?: string;
18
+ token?: string;
19
+ /** Prefix for Ripple NATS subjects (default: 'ripple.') */
20
+ subjectPrefix?: string;
21
+ /** Custom logger instance */
22
+ logger?: RippleLogger;
23
+ /** Optional NATS connection options */
24
+ connectionOptions?: ConnectionOptions;
25
+ }
26
+ /**
27
+ * NATS driver for Ripple, offering high-performance distributed broadcasting.
28
+ *
29
+ * @example
30
+ * ```typescript
31
+ * import { RippleServer, NATSDriver } from '@gravito/ripple'
32
+ *
33
+ * const server = new RippleServer({
34
+ * driver: 'nats',
35
+ * nats: {
36
+ * servers: 'nats://localhost:4222'
37
+ * }
38
+ * })
39
+ * ```
40
+ */
41
+ export declare class NATSDriver implements RippleDriver {
42
+ private config;
43
+ readonly name = "nats";
44
+ private nats?;
45
+ private subjectPrefix;
46
+ private subscriptions;
47
+ private callbacks;
48
+ private _initialized;
49
+ private _connected;
50
+ private _lastError?;
51
+ private logger;
52
+ constructor(config?: NATSDriverConfig);
53
+ get isInitialized(): boolean;
54
+ init(): Promise<void>;
55
+ publish(channel: string, event: string, data: unknown): Promise<void>;
56
+ subscribe(channel: string, callback: (event: string, data: unknown) => void): Promise<void>;
57
+ unsubscribe(channel: string): Promise<void>;
58
+ shutdown(): Promise<void>;
59
+ getStatus(): DriverStatus;
60
+ /**
61
+ * Track presence member using NATS KV Store.
62
+ *
63
+ * Creates or updates a bucket for the channel and stores user info with TTL.
64
+ *
65
+ * @param channel - Presence channel name
66
+ * @param userInfo - User information to store
67
+ * @since 4.0.0-alpha
68
+ */
69
+ trackPresence(channel: string, userInfo: PresenceUserInfo): Promise<void>;
70
+ /**
71
+ * Remove presence member from NATS KV Store.
72
+ *
73
+ * @param channel - Presence channel name
74
+ * @param userId - User ID to remove
75
+ * @since 4.0.0-alpha
76
+ */
77
+ untrackPresence(channel: string, userId: string | number): Promise<void>;
78
+ /**
79
+ * Get all presence members from NATS KV Store.
80
+ *
81
+ * @param channel - Presence channel name
82
+ * @returns Array of presence user information
83
+ * @since 4.0.0-alpha
84
+ */
85
+ getPresenceMembers(channel: string): Promise<PresenceUserInfo[]>;
86
+ private handleError;
87
+ }
@@ -4,7 +4,7 @@
4
4
  * @module @gravito/ripple/drivers
5
5
  */
6
6
  import type { RippleLogger } from '../logging/Logger';
7
- import type { DriverStatus, RippleDriver } from '../types';
7
+ import type { DriverStatus, PresenceUserInfo, RippleDriver } from '../types';
8
8
  /**
9
9
  * Configuration for the RedisDriver.
10
10
  */
@@ -122,6 +122,35 @@ export declare class RedisDriver implements RippleDriver {
122
122
  * Get the current status of the Redis driver.
123
123
  */
124
124
  getStatus(): DriverStatus;
125
+ /**
126
+ * Track a presence member in a channel.
127
+ *
128
+ * Stores presence information in Redis Hash for cross-node sharing.
129
+ * Sets TTL on the hash to prevent stale data.
130
+ *
131
+ * @param channel - Presence channel name
132
+ * @param userInfo - User information to track
133
+ * @since 3.6.0
134
+ */
135
+ trackPresence(channel: string, userInfo: PresenceUserInfo): Promise<void>;
136
+ /**
137
+ * Remove a presence member from a channel.
138
+ *
139
+ * @param channel - Presence channel name
140
+ * @param userId - User ID to remove
141
+ * @since 3.6.0
142
+ */
143
+ untrackPresence(channel: string, userId: string | number): Promise<void>;
144
+ /**
145
+ * Get all presence members for a channel.
146
+ *
147
+ * Retrieves all members from the Redis Hash.
148
+ *
149
+ * @param channel - Presence channel name
150
+ * @returns Array of presence user information
151
+ * @since 3.6.0
152
+ */
153
+ getPresenceMembers(channel: string): Promise<PresenceUserInfo[]>;
125
154
  /**
126
155
  * Handle an incoming message from Redis Pub/Sub.
127
156
  *
@@ -1,2 +1,3 @@
1
1
  export * from './LocalDriver';
2
+ export * from './NATSDriver';
2
3
  export * from './RedisDriver';
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @fileoverview Bun native WebSocket engine implementation
3
+ *
4
+ * Wraps Bun's native WebSocket API to implement the IRippleEngine interface.
5
+ * This is the default and highest-performance engine for Ripple.
6
+ *
7
+ * @module @gravito/ripple/engines
8
+ * @since 5.0.0
9
+ */
10
+ import type { Server, ServerWebSocket } from 'bun';
11
+ import type { ClientData } from '../types';
12
+ import type { IRippleEngine, RippleSocket } from './IRippleEngine';
13
+ /**
14
+ * Wrapper around Bun's ServerWebSocket to implement RippleSocket interface.
15
+ *
16
+ * This is a zero-overhead wrapper that delegates all operations to the native
17
+ * Bun WebSocket object. No proxies or additional allocations.
18
+ */
19
+ export declare class BunRippleSocket implements RippleSocket {
20
+ private ws;
21
+ constructor(ws: ServerWebSocket<ClientData>);
22
+ get id(): string;
23
+ get data(): ClientData;
24
+ send(data: string | Uint8Array, compress?: boolean): void;
25
+ close(code?: number, reason?: string): void;
26
+ getBufferedAmount(): number;
27
+ subscribe(topic: string): void;
28
+ unsubscribe(topic: string): void;
29
+ publish(topic: string, data: string | Uint8Array): void;
30
+ get raw(): ServerWebSocket<ClientData>;
31
+ }
32
+ /**
33
+ * Configuration for BunEngine.
34
+ */
35
+ export interface BunEngineConfig {
36
+ /** Port to listen on */
37
+ port?: number;
38
+ /** Hostname to bind to */
39
+ hostname?: string;
40
+ /** TLS configuration */
41
+ tls?: {
42
+ cert: string;
43
+ key: string;
44
+ };
45
+ /** Development mode (enables verbose logging) */
46
+ development?: boolean;
47
+ }
48
+ /**
49
+ * Bun native WebSocket engine.
50
+ *
51
+ * Leverages Bun's high-performance WebSocket implementation with native pub/sub support.
52
+ * This engine provides the best performance and is the default choice for Bun runtime.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const engine = new BunEngine({ port: 3000 })
57
+ *
58
+ * engine.onConnection((socket) => {
59
+ * console.log('Client connected:', socket.id)
60
+ * })
61
+ *
62
+ * await engine.listen(3000)
63
+ * ```
64
+ */
65
+ export declare class BunEngine implements IRippleEngine {
66
+ private config;
67
+ readonly name = "bun";
68
+ private server?;
69
+ private connectionHandler?;
70
+ private disconnectionHandler?;
71
+ private messageHandler?;
72
+ private sockets;
73
+ constructor(config?: BunEngineConfig);
74
+ onConnection(handler: (socket: RippleSocket) => void): void;
75
+ onDisconnection(handler: (socket: RippleSocket, code: number, reason: string) => void): void;
76
+ onMessage(handler: (socket: RippleSocket, message: string | Uint8Array) => void): void;
77
+ listen(port: number): Promise<void>;
78
+ close(): Promise<void>;
79
+ broadcast(topic: string, data: string | Uint8Array, excludeSocketId?: string): void;
80
+ /**
81
+ * Upgrade an HTTP request to a WebSocket connection.
82
+ *
83
+ * This method is called by RippleServer to handle WebSocket upgrade requests.
84
+ *
85
+ * @param req - HTTP request
86
+ * @param options - Upgrade options (userId, reconnectionToken)
87
+ * @returns true if upgrade succeeded, false otherwise
88
+ */
89
+ upgrade(req: Request, options?: {
90
+ userId?: string;
91
+ reconnectionToken?: string;
92
+ }): boolean;
93
+ /**
94
+ * Get the underlying Bun server instance.
95
+ * Useful for advanced use cases.
96
+ */
97
+ getServer(): Server<ClientData> | undefined;
98
+ }
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @fileoverview Core abstraction layer for Ripple WebSocket engines
3
+ *
4
+ * Defines the interface that all WebSocket engines must implement to work with Ripple.
5
+ * This abstraction allows Ripple to run on different runtimes (Bun, Node.js with uWS, Node.js with ws).
6
+ *
7
+ * @module @gravito/ripple/engines
8
+ * @since 5.0.0
9
+ */
10
+ import type { ClientData } from '../types';
11
+ /**
12
+ * Runtime-agnostic WebSocket connection interface.
13
+ *
14
+ * Provides a unified API across different WebSocket implementations (Bun, uWS, ws).
15
+ * Each engine wraps its native WebSocket type to implement this interface.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // Engine implementations wrap their native WebSocket
20
+ * class BunRippleSocket implements RippleSocket {
21
+ * constructor(private ws: ServerWebSocket<ClientData>) {}
22
+ *
23
+ * send(data: string | Uint8Array) {
24
+ * this.ws.send(data)
25
+ * }
26
+ *
27
+ * get data() {
28
+ * return this.ws.data
29
+ * }
30
+ * }
31
+ * ```
32
+ */
33
+ export interface RippleSocket {
34
+ /** Unique socket identifier */
35
+ id: string;
36
+ /** Client session data */
37
+ data: ClientData;
38
+ /**
39
+ * Send data to the client.
40
+ *
41
+ * @param data - Message payload (string or binary)
42
+ * @param compress - Whether to compress the message (optional, engine-dependent)
43
+ */
44
+ send(data: string | Uint8Array, compress?: boolean): void;
45
+ /**
46
+ * Close the WebSocket connection.
47
+ *
48
+ * @param code - WebSocket close code (default: 1000)
49
+ * @param reason - Human-readable close reason
50
+ */
51
+ close(code?: number, reason?: string): void;
52
+ /**
53
+ * Get the number of bytes buffered for sending.
54
+ * Used for backpressure management.
55
+ *
56
+ * @returns Buffered bytes count
57
+ */
58
+ getBufferedAmount(): number;
59
+ /**
60
+ * Subscribe to a pub/sub topic.
61
+ *
62
+ * For engines with native pub/sub (Bun, uWS), this uses the native API.
63
+ * For engines without (ws), this is tracked in-memory by the engine.
64
+ *
65
+ * @param topic - Topic name to subscribe to
66
+ */
67
+ subscribe(topic: string): void;
68
+ /**
69
+ * Unsubscribe from a pub/sub topic.
70
+ *
71
+ * @param topic - Topic name to unsubscribe from
72
+ */
73
+ unsubscribe(topic: string): void;
74
+ /**
75
+ * Publish a message to a topic.
76
+ *
77
+ * For engines with native pub/sub, this broadcasts at the C++ layer.
78
+ * For engines without, this is handled by the engine's broadcast logic.
79
+ *
80
+ * @param topic - Topic name
81
+ * @param data - Message payload
82
+ */
83
+ publish(topic: string, data: string | Uint8Array): void;
84
+ /**
85
+ * Access to the underlying native WebSocket object.
86
+ *
87
+ * This is an escape hatch for engine-specific features not covered by the interface.
88
+ * Use with caution as it breaks runtime portability.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * // Access Bun-specific features
93
+ * if (socket.raw && 'remoteAddress' in socket.raw) {
94
+ * console.log('Client IP:', socket.raw.remoteAddress)
95
+ * }
96
+ * ```
97
+ */
98
+ raw?: any;
99
+ }
100
+ /**
101
+ * WebSocket engine interface for Ripple.
102
+ *
103
+ * Engines handle the low-level WebSocket I/O and lifecycle management.
104
+ * RippleServer delegates all runtime-specific operations to the engine.
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * // Example: Custom engine implementation
109
+ * class MyCustomEngine implements IRippleEngine {
110
+ * private server?: any
111
+ * private connectionHandler?: (socket: RippleSocket) => void
112
+ *
113
+ * async listen(port: number): Promise<void> {
114
+ * this.server = createServer(port)
115
+ * this.server.on('connection', (ws) => {
116
+ * const socket = new MyRippleSocket(ws)
117
+ * this.connectionHandler?.(socket)
118
+ * })
119
+ * }
120
+ *
121
+ * onConnection(handler: (socket: RippleSocket) => void): void {
122
+ * this.connectionHandler = handler
123
+ * }
124
+ *
125
+ * // ... implement other methods
126
+ * }
127
+ * ```
128
+ */
129
+ export interface IRippleEngine {
130
+ /** Engine name for logging and debugging */
131
+ readonly name: string;
132
+ /**
133
+ * Start the WebSocket server.
134
+ *
135
+ * @param port - Port number to listen on
136
+ * @throws If the port is already in use or binding fails
137
+ */
138
+ listen(port: number): Promise<void>;
139
+ /**
140
+ * Stop the WebSocket server and close all connections.
141
+ */
142
+ close(): Promise<void>;
143
+ /**
144
+ * Register handler for new WebSocket connections.
145
+ *
146
+ * Called by RippleServer to hook into the connection lifecycle.
147
+ * The engine should call this handler whenever a new WebSocket connection is established.
148
+ *
149
+ * @param handler - Callback invoked when a client connects
150
+ */
151
+ onConnection(handler: (socket: RippleSocket) => void): void;
152
+ /**
153
+ * Register handler for WebSocket disconnections.
154
+ *
155
+ * Called by RippleServer to hook into the disconnection lifecycle.
156
+ * The engine should call this handler whenever a WebSocket connection closes.
157
+ *
158
+ * @param handler - Callback invoked when a client disconnects
159
+ */
160
+ onDisconnection(handler: (socket: RippleSocket, code: number, reason: string) => void): void;
161
+ /**
162
+ * Register handler for incoming WebSocket messages.
163
+ *
164
+ * Called by RippleServer to hook into the message lifecycle.
165
+ * The engine should call this handler whenever a message is received.
166
+ *
167
+ * @param handler - Callback invoked when a message is received
168
+ */
169
+ onMessage(handler: (socket: RippleSocket, message: string | Uint8Array) => void): void;
170
+ /**
171
+ * Broadcast a message to all subscribers of a topic.
172
+ *
173
+ * For engines with native pub/sub (Bun, uWS), this should use the native broadcast API
174
+ * for maximum performance (C++ layer broadcast, no JS callback overhead).
175
+ *
176
+ * For engines without native pub/sub (ws), this should iterate over subscribers
177
+ * and send the message to each.
178
+ *
179
+ * @param topic - Topic/channel name
180
+ * @param data - Message payload
181
+ * @param excludeSocketId - Optional socket ID to exclude from broadcast
182
+ */
183
+ broadcast(topic: string, data: string | Uint8Array, excludeSocketId?: string): void;
184
+ /**
185
+ * Upgrade an HTTP request to a WebSocket connection.
186
+ *
187
+ * This is optional and only needed for engines that integrate with HTTP servers
188
+ * (Bun, uWS). For standalone WebSocket servers, this can be omitted.
189
+ *
190
+ * @param req - HTTP request object
191
+ * @param options - Upgrade options (e.g., user ID for authentication)
192
+ * @returns true if upgrade was successful, false otherwise
193
+ */
194
+ upgrade?(req: Request, options?: {
195
+ userId?: string;
196
+ reconnectionToken?: string;
197
+ }): boolean;
198
+ }
199
+ /**
200
+ * Factory function type for creating engine instances.
201
+ *
202
+ * @param config - Engine-specific configuration
203
+ * @returns Engine instance
204
+ */
205
+ export type EngineFactory = (config: any) => IRippleEngine;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * @fileoverview uWebSockets.js engine implementation for Node.js
3
+ *
4
+ * Wraps uWebSockets.js API to implement the IRippleEngine interface.
5
+ * This engine provides high performance on Node.js, close to Bun's native performance.
6
+ *
7
+ * @module @gravito/ripple/engines
8
+ * @since 5.0.0
9
+ */
10
+ import type { ClientData } from '../types';
11
+ import type { IRippleEngine, RippleSocket } from './IRippleEngine';
12
+ interface WebSocket {
13
+ send(message: string | ArrayBuffer, isBinary?: boolean, compress?: boolean): number;
14
+ close(): void;
15
+ getBufferedAmount(): number;
16
+ subscribe(topic: string): void;
17
+ unsubscribe(topic: string): void;
18
+ publish(topic: string, message: string | ArrayBuffer, isBinary?: boolean, compress?: boolean): boolean;
19
+ getUserData(): ClientData;
20
+ }
21
+ /**
22
+ * Wrapper around uWebSockets.js WebSocket to implement RippleSocket interface.
23
+ *
24
+ * This is a zero-overhead wrapper that delegates all operations to the uWebSockets.js
25
+ * WebSocket object.
26
+ */
27
+ export declare class UWebSocketsRippleSocket implements RippleSocket {
28
+ private ws;
29
+ constructor(ws: WebSocket);
30
+ get id(): string;
31
+ get data(): ClientData;
32
+ send(data: string | Uint8Array, compress?: boolean): void;
33
+ close(_code?: number, _reason?: string): void;
34
+ getBufferedAmount(): number;
35
+ subscribe(topic: string): void;
36
+ unsubscribe(topic: string): void;
37
+ publish(topic: string, data: string | Uint8Array): void;
38
+ get raw(): WebSocket;
39
+ }
40
+ /**
41
+ * Configuration for uWebSocketsEngine.
42
+ */
43
+ export interface UWebSocketsEngineConfig {
44
+ /** Port to listen on */
45
+ port?: number;
46
+ /** Hostname to bind to */
47
+ hostname?: string;
48
+ /** TLS configuration */
49
+ tls?: {
50
+ cert: string;
51
+ key: string;
52
+ };
53
+ /** Compression mode (0 = disabled, 1 = shared, 3 = dedicated 3KB) */
54
+ compression?: number;
55
+ /** Maximum payload length in bytes (default: 16MB) */
56
+ maxPayloadLength?: number;
57
+ /** Idle timeout in seconds (default: 120) */
58
+ idleTimeout?: number;
59
+ /** Maximum backpressure in bytes (default: 1MB) */
60
+ maxBackpressure?: number;
61
+ /** Development mode (enables verbose logging) */
62
+ development?: boolean;
63
+ }
64
+ /**
65
+ * uWebSockets.js engine for Node.js.
66
+ *
67
+ * Leverages uWebSockets.js high-performance WebSocket implementation with native pub/sub support.
68
+ * This engine provides excellent performance on Node.js (~90% of Bun's performance).
69
+ */
70
+ export declare class UWebSocketsEngine implements IRippleEngine {
71
+ private config;
72
+ readonly name = "node-uws";
73
+ private app?;
74
+ private uws?;
75
+ private connectionHandler?;
76
+ private disconnectionHandler?;
77
+ private messageHandler?;
78
+ private sockets;
79
+ private listenSocket?;
80
+ constructor(config?: UWebSocketsEngineConfig);
81
+ onConnection(handler: (socket: RippleSocket) => void): void;
82
+ onDisconnection(handler: (socket: RippleSocket, code: number, reason: string) => void): void;
83
+ onMessage(handler: (socket: RippleSocket, message: string | Uint8Array) => void): void;
84
+ listen(port: number): Promise<void>;
85
+ close(): Promise<void>;
86
+ broadcast(topic: string, data: string | Uint8Array, excludeSocketId?: string): void;
87
+ getConnectedSockets(): RippleSocket[];
88
+ getSocket(id: string): RippleSocket | undefined;
89
+ /**
90
+ * Upgrade an HTTP request to WebSocket.
91
+ *
92
+ * Note: This method is not used in the engine-based architecture.
93
+ * uWebSockets.js handles upgrades internally via the ws() route.
94
+ */
95
+ upgrade(_req: Request, _data?: Record<string, unknown>): boolean;
96
+ }
97
+ export {};
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @fileoverview Node.js ws engine implementation
3
+ *
4
+ * Wraps the 'ws' library to implement the IRippleEngine interface.
5
+ * Implements in-memory pub/sub since the ws library does not support it natively.
6
+ *
7
+ * @module @gravito/ripple/engines
8
+ * @since 5.0.0
9
+ */
10
+ import { type WebSocket } from 'ws';
11
+ import type { ClientData } from '../types';
12
+ import type { IRippleEngine, RippleSocket } from './IRippleEngine';
13
+ /**
14
+ * Wrapper around 'ws' WebSocket to implement RippleSocket interface.
15
+ */
16
+ export declare class WsRippleSocket implements RippleSocket {
17
+ private ws;
18
+ private clientData;
19
+ private engine;
20
+ constructor(ws: WebSocket, clientData: ClientData, engine: WsEngine);
21
+ get id(): string;
22
+ get data(): ClientData;
23
+ send(data: string | Uint8Array, compress?: boolean): void;
24
+ close(code?: number, reason?: string): void;
25
+ getBufferedAmount(): number;
26
+ subscribe(topic: string): void;
27
+ unsubscribe(topic: string): void;
28
+ publish(topic: string, data: string | Uint8Array): void;
29
+ get raw(): WebSocket;
30
+ }
31
+ /**
32
+ * Configuration for WsEngine.
33
+ */
34
+ export interface WsEngineConfig {
35
+ /** Port to listen on */
36
+ port?: number;
37
+ /** Hostname to bind to */
38
+ hostname?: string;
39
+ /** Development mode */
40
+ development?: boolean;
41
+ /** WebSocket path */
42
+ path?: string;
43
+ }
44
+ /**
45
+ * Node.js ws engine.
46
+ *
47
+ * Uses the popular 'ws' library. Provides standard compatibility but
48
+ * uses application-layer pub/sub.
49
+ */
50
+ export declare class WsEngine implements IRippleEngine {
51
+ private config;
52
+ readonly name = "node-ws";
53
+ private wss?;
54
+ private connectionHandler?;
55
+ private disconnectionHandler?;
56
+ private messageHandler?;
57
+ private sockets;
58
+ private subscriptions;
59
+ constructor(config?: WsEngineConfig);
60
+ onConnection(handler: (socket: RippleSocket) => void): void;
61
+ onDisconnection(handler: (socket: RippleSocket, code: number, reason: string) => void): void;
62
+ onMessage(handler: (socket: RippleSocket, message: string | Uint8Array) => void): void;
63
+ listen(port: number): Promise<void>;
64
+ close(): Promise<void>;
65
+ subscribe(socketId: string, topic: string): void;
66
+ unsubscribe(socketId: string, topic: string): void;
67
+ private cleanupSocket;
68
+ broadcast(topic: string, data: string | Uint8Array, excludeSocketId?: string): void;
69
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @fileoverview Ripple WebSocket Engine exports
3
+ *
4
+ * Provides runtime-agnostic WebSocket engine implementations for Ripple.
5
+ *
6
+ * @module @gravito/ripple/engines
7
+ * @since 5.0.0
8
+ */
9
+ export type { BunEngineConfig } from './BunEngine';
10
+ export { BunEngine, BunRippleSocket } from './BunEngine';
11
+ export type { EngineFactory, IRippleEngine, RippleSocket } from './IRippleEngine';
12
+ export type { UWebSocketsEngineConfig } from './UWebSocketsEngine';
13
+ export { UWebSocketsEngine, UWebSocketsRippleSocket } from './UWebSocketsEngine';
14
+ export type { WsEngineConfig } from './WsEngine';
15
+ export { WsEngine, WsRippleSocket } from './WsEngine';
@@ -53,7 +53,9 @@ export { HealthChecker } from './health/HealthChecker';
53
53
  export type { LogContext, LogLevel, RippleLogger } from './logging/Logger';
54
54
  export { ConsoleLogger, createLogger } from './logging/Logger';
55
55
  export { OrbitRipple } from './OrbitRipple';
56
+ export { RippleMetrics } from './observability/RippleMetrics';
56
57
  export { RippleServer } from './RippleServer';
58
+ export { AckManager } from './reliability/AckManager';
57
59
  export type { ConnectionEvent, ConnectionTracker } from './tracking/ConnectionTracker';
58
60
  export { DefaultConnectionTracker } from './tracking/ConnectionTracker';
59
61
  export type { BroadcastEventInterface, Channel, ChannelAuthorizer, ChannelType, ClientData, ClientMessage, DriverStatus, ErrorServerMessage, PresenceUserInfo, RippleBunServer, RippleConfig, RippleDriver, RippleErrorCode, RippleWebSocket, ServerMessage, WebSocketHandlerConfig, } from './types';
@@ -0,0 +1,21 @@
1
+ import type { RippleContext, RippleInterceptor } from '../types';
2
+ /**
3
+ * Manages the execution of message interceptors in an onion model.
4
+ *
5
+ * @since 4.0.0
6
+ */
7
+ export declare class InterceptorManager {
8
+ private interceptors;
9
+ constructor(interceptors?: RippleInterceptor[]);
10
+ /**
11
+ * Execute the interceptor pipeline for a given context.
12
+ *
13
+ * @param ctx - The ripple message context
14
+ * @param finalHandler - The final handler to run after all interceptors
15
+ */
16
+ execute(ctx: RippleContext, finalHandler: () => Promise<void> | void): Promise<void>;
17
+ /**
18
+ * Add a new interceptor to the end of the pipeline.
19
+ */
20
+ use(interceptor: RippleInterceptor): void;
21
+ }
@@ -0,0 +1,24 @@
1
+ import type { AckManager } from '../reliability/AckManager';
2
+ import type { ConnectionTracker } from '../tracking/ConnectionTracker';
3
+ /**
4
+ * Prometheus metrics exporter for Ripple.
5
+ *
6
+ * @since 3.7.0
7
+ */
8
+ export declare class RippleMetrics {
9
+ private prefix;
10
+ private tracker;
11
+ private ackManager?;
12
+ private slowClients;
13
+ constructor(tracker: ConnectionTracker, prefix?: string, ackManager?: AckManager);
14
+ /**
15
+ * Increment the counter for slow clients isolated or disconnected.
16
+ */
17
+ incrementSlowClients(): void;
18
+ /**
19
+ * Export metrics in Prometheus text format.
20
+ *
21
+ * @returns String containing Prometheus metrics
22
+ */
23
+ export(): string;
24
+ }