@gravito/echo 3.0.1 → 3.1.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 (223) hide show
  1. package/README.md +211 -0
  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/Application.d.ts +43 -17
  94. package/dist/core/src/CommandKernel.d.ts +33 -0
  95. package/dist/core/src/ConfigManager.d.ts +39 -0
  96. package/dist/core/src/Container/RequestScopeManager.d.ts +62 -0
  97. package/dist/core/src/Container/RequestScopeMetrics.d.ts +144 -0
  98. package/dist/core/src/Container.d.ts +123 -14
  99. package/dist/core/src/ErrorHandler.d.ts +3 -0
  100. package/dist/core/src/HookManager.d.ts +517 -8
  101. package/dist/core/src/PlanetCore.d.ts +141 -7
  102. package/dist/core/src/RequestContext.d.ts +97 -0
  103. package/dist/core/src/Router.d.ts +41 -7
  104. package/dist/core/src/ServiceProvider.d.ts +36 -8
  105. package/dist/core/src/adapters/GravitoEngineAdapter.d.ts +1 -0
  106. package/dist/core/src/adapters/PhotonAdapter.d.ts +5 -0
  107. package/dist/core/src/adapters/bun/BunContext.d.ts +4 -0
  108. package/dist/core/src/adapters/bun/BunNativeAdapter.d.ts +1 -0
  109. package/dist/core/src/adapters/types.d.ts +39 -0
  110. package/dist/core/src/cli/queue-commands.d.ts +6 -0
  111. package/dist/core/src/engine/AOTRouter.d.ts +7 -12
  112. package/dist/core/src/engine/FastContext.d.ts +27 -2
  113. package/dist/core/src/engine/Gravito.d.ts +1 -2
  114. package/dist/core/src/engine/MinimalContext.d.ts +25 -2
  115. package/dist/core/src/engine/types.d.ts +9 -1
  116. package/dist/core/src/error-handling/RequestScopeErrorContext.d.ts +126 -0
  117. package/dist/core/src/events/BackpressureManager.d.ts +215 -0
  118. package/dist/core/src/events/CircuitBreaker.d.ts +229 -0
  119. package/dist/core/src/events/DeadLetterQueue.d.ts +219 -0
  120. package/dist/core/src/events/EventBackend.d.ts +12 -0
  121. package/dist/core/src/events/EventOptions.d.ts +204 -0
  122. package/dist/core/src/events/EventPriorityQueue.d.ts +301 -0
  123. package/dist/core/src/events/FlowControlStrategy.d.ts +109 -0
  124. package/dist/core/src/events/IdempotencyCache.d.ts +60 -0
  125. package/dist/core/src/events/MessageQueueBridge.d.ts +184 -0
  126. package/dist/core/src/events/PriorityEscalationManager.d.ts +82 -0
  127. package/dist/core/src/events/RetryScheduler.d.ts +104 -0
  128. package/dist/core/src/events/WorkerPool.d.ts +98 -0
  129. package/dist/core/src/events/WorkerPoolConfig.d.ts +153 -0
  130. package/dist/core/src/events/WorkerPoolMetrics.d.ts +65 -0
  131. package/dist/core/src/events/aggregation/AggregationWindow.d.ts +77 -0
  132. package/dist/core/src/events/aggregation/DeduplicationManager.d.ts +135 -0
  133. package/dist/core/src/events/aggregation/EventAggregationManager.d.ts +108 -0
  134. package/dist/core/src/events/aggregation/EventBatcher.d.ts +99 -0
  135. package/dist/core/src/events/aggregation/types.d.ts +117 -0
  136. package/dist/core/src/events/index.d.ts +25 -0
  137. package/dist/core/src/events/observability/EventMetrics.d.ts +132 -0
  138. package/dist/core/src/events/observability/EventTracer.d.ts +68 -0
  139. package/dist/core/src/events/observability/EventTracing.d.ts +161 -0
  140. package/dist/core/src/events/observability/OTelEventMetrics.d.ts +332 -0
  141. package/dist/core/src/events/observability/ObservableHookManager.d.ts +108 -0
  142. package/dist/core/src/events/observability/StreamWorkerMetrics.d.ts +76 -0
  143. package/dist/core/src/events/observability/index.d.ts +24 -0
  144. package/dist/core/src/events/observability/metrics-types.d.ts +16 -0
  145. package/dist/core/src/events/types.d.ts +134 -0
  146. package/dist/core/src/exceptions/CircularDependencyException.d.ts +9 -0
  147. package/dist/core/src/exceptions/index.d.ts +1 -0
  148. package/dist/core/src/health/HealthProvider.d.ts +67 -0
  149. package/dist/core/src/http/cookie.d.ts +29 -0
  150. package/dist/core/src/http/types.d.ts +40 -0
  151. package/dist/core/src/index.d.ts +26 -4
  152. package/dist/core/src/instrumentation/index.d.ts +35 -0
  153. package/dist/core/src/instrumentation/opentelemetry.d.ts +178 -0
  154. package/dist/core/src/instrumentation/types.d.ts +182 -0
  155. package/dist/core/src/observability/Metrics.d.ts +244 -0
  156. package/dist/core/src/observability/QueueDashboard.d.ts +136 -0
  157. package/dist/core/src/reliability/DeadLetterQueueManager.d.ts +350 -0
  158. package/dist/core/src/reliability/RetryPolicy.d.ts +217 -0
  159. package/dist/core/src/reliability/index.d.ts +6 -0
  160. package/dist/core/src/router/ControllerDispatcher.d.ts +12 -0
  161. package/dist/core/src/router/RequestValidator.d.ts +20 -0
  162. package/dist/echo/src/OrbitEcho.d.ts +71 -16
  163. package/dist/echo/src/dlq/DeadLetterQueue.d.ts +94 -0
  164. package/dist/echo/src/dlq/MemoryDeadLetterQueue.d.ts +36 -0
  165. package/dist/echo/src/dlq/index.d.ts +2 -0
  166. package/dist/echo/src/index.d.ts +31 -15
  167. package/dist/echo/src/middleware/RequestBufferMiddleware.d.ts +62 -0
  168. package/dist/echo/src/middleware/index.d.ts +8 -0
  169. package/dist/echo/src/observability/index.d.ts +3 -0
  170. package/dist/echo/src/observability/logging/ConsoleEchoLogger.d.ts +37 -0
  171. package/dist/echo/src/observability/logging/EchoLogger.d.ts +38 -0
  172. package/dist/echo/src/observability/logging/index.d.ts +2 -0
  173. package/dist/echo/src/observability/metrics/MetricsProvider.d.ts +69 -0
  174. package/dist/echo/src/observability/metrics/NoopMetricsProvider.d.ts +17 -0
  175. package/dist/echo/src/observability/metrics/PrometheusMetricsProvider.d.ts +39 -0
  176. package/dist/echo/src/observability/metrics/index.d.ts +3 -0
  177. package/dist/echo/src/observability/tracing/NoopTracer.d.ts +33 -0
  178. package/dist/echo/src/observability/tracing/Tracer.d.ts +75 -0
  179. package/dist/echo/src/observability/tracing/index.d.ts +2 -0
  180. package/dist/echo/src/providers/GenericProvider.d.ts +37 -18
  181. package/dist/echo/src/providers/GitHubProvider.d.ts +21 -12
  182. package/dist/echo/src/providers/LinearProvider.d.ts +27 -0
  183. package/dist/echo/src/providers/PaddleProvider.d.ts +31 -0
  184. package/dist/echo/src/providers/ShopifyProvider.d.ts +27 -0
  185. package/dist/echo/src/providers/SlackProvider.d.ts +27 -0
  186. package/dist/echo/src/providers/StripeProvider.d.ts +20 -12
  187. package/dist/echo/src/providers/TwilioProvider.d.ts +31 -0
  188. package/dist/echo/src/providers/base/BaseProvider.d.ts +87 -0
  189. package/dist/echo/src/providers/base/HeaderUtils.d.ts +34 -0
  190. package/dist/echo/src/providers/index.d.ts +14 -3
  191. package/dist/echo/src/receive/SignatureValidator.d.ts +33 -0
  192. package/dist/echo/src/receive/WebhookReceiver.d.ts +139 -21
  193. package/dist/echo/src/replay/WebhookReplayService.d.ts +35 -0
  194. package/dist/echo/src/replay/index.d.ts +1 -0
  195. package/dist/echo/src/resilience/CircuitBreaker.d.ts +117 -0
  196. package/dist/echo/src/resilience/index.d.ts +10 -0
  197. package/dist/echo/src/rotation/KeyRotationManager.d.ts +127 -0
  198. package/dist/echo/src/rotation/index.d.ts +10 -0
  199. package/dist/echo/src/send/WebhookDispatcher.d.ts +159 -15
  200. package/dist/echo/src/storage/MemoryWebhookStore.d.ts +14 -0
  201. package/dist/echo/src/storage/WebhookStore.d.ts +236 -0
  202. package/dist/echo/src/storage/index.d.ts +2 -0
  203. package/dist/echo/src/types.d.ts +656 -64
  204. package/dist/index.js +1327 -189
  205. package/dist/index.js.map +28 -10
  206. package/dist/monitor/src/MonitorOrbit.d.ts +43 -0
  207. package/dist/monitor/src/config.d.ts +106 -0
  208. package/dist/monitor/src/health/HealthController.d.ts +28 -0
  209. package/dist/monitor/src/health/HealthRegistry.d.ts +80 -0
  210. package/dist/monitor/src/health/index.d.ts +36 -0
  211. package/dist/monitor/src/index.d.ts +13 -0
  212. package/dist/monitor/src/metrics/MetricsController.d.ts +22 -0
  213. package/dist/monitor/src/metrics/MetricsRegistry.d.ts +136 -0
  214. package/dist/monitor/src/metrics/index.d.ts +11 -0
  215. package/dist/monitor/src/tracing/TracingManager.d.ts +97 -0
  216. package/dist/monitor/src/tracing/index.d.ts +10 -0
  217. package/dist/photon/src/index.d.ts +74 -5
  218. package/dist/photon/src/middleware/binary.d.ts +12 -15
  219. package/dist/photon/src/middleware/htmx.d.ts +39 -0
  220. package/dist/photon/src/middleware/ratelimit-redis.d.ts +50 -0
  221. package/dist/photon/src/middleware/ratelimit.d.ts +161 -0
  222. package/dist/photon/src/openapi.d.ts +19 -0
  223. package/package.json +8 -6
@@ -1,56 +1,111 @@
1
1
  import type { GravitoOrbit, PlanetCore } from '@gravito/core';
2
2
  import { WebhookReceiver } from './receive/WebhookReceiver';
3
+ import { KeyRotationManager } from './rotation/KeyRotationManager';
3
4
  import { WebhookDispatcher } from './send/WebhookDispatcher';
4
- import type { EchoConfig } from './types';
5
+ import type { EchoConfig, ProviderKeyEntry } from './types';
5
6
  /**
6
- * OrbitEcho is the official webhook orchestration module for Gravito.
7
+ * OrbitEcho is the official webhook orchestration module for the Gravito ecosystem.
7
8
  *
8
- * It provides a secure way to receive incoming webhooks (e.g., from Stripe, GitHub)
9
- * and a reliable way to dispatch outgoing webhooks to third-party services.
9
+ * It serves as a comprehensive hub for managing the entire webhook lifecycle,
10
+ * including secure reception, signature verification across multiple providers,
11
+ * persistent storage for auditing, and reliable outgoing dispatch with
12
+ * exponential backoff and circuit breaking.
10
13
  *
11
- * @example
14
+ * @example Basic integration with PlanetCore
12
15
  * ```typescript
16
+ * import { PlanetCore } from '@gravito/core';
17
+ * import { OrbitEcho } from '@gravito/echo';
18
+ *
19
+ * const core = new PlanetCore();
13
20
  * const echo = new OrbitEcho({
14
21
  * providers: {
15
- * stripe: { name: 'stripe', secret: 'whsec_...' }
22
+ * stripe: { name: 'stripe', secret: process.env.STRIPE_SECRET }
23
+ * },
24
+ * dispatcher: {
25
+ * secret: process.env.APP_WEBHOOK_SECRET
16
26
  * }
17
27
  * });
18
- * core.addOrbit(echo);
28
+ *
29
+ * core.install(echo);
19
30
  * ```
20
31
  *
21
32
  * @public
22
- * @since 3.0.0
23
33
  */
24
34
  export declare class OrbitEcho implements GravitoOrbit {
25
35
  private receiver;
26
36
  private dispatcher?;
27
37
  private echoConfig;
38
+ private keyRotationManager?;
28
39
  /**
29
- * Create a new OrbitEcho instance.
40
+ * Constructs a new OrbitEcho instance with the specified configuration.
30
41
  *
31
- * @param config - The configuration object for providers and dispatcher.
42
+ * This constructor initializes the core receiver component, sets up key rotation
43
+ * orchestration if enabled, registers defined providers, and connects the
44
+ * observability stack (metrics, tracing, logging).
45
+ *
46
+ * @param config - The global configuration defining providers, dispatchers, and infrastructure.
32
47
  */
33
48
  constructor(config?: EchoConfig);
34
49
  /**
35
- * Install into PlanetCore
50
+ * Integrates the Echo module into the Gravito application lifecycle.
36
51
  *
37
- * Registers the OrbitEcho instance and its components into the service container.
52
+ * This method performs the following setup tasks:
53
+ * 1. Installs request buffering middleware (if enabled) to preserve raw bodies.
54
+ * 2. Binds Echo components to the service container (`echo`, `echo.receiver`).
55
+ * 3. Injects the Echo instance into the request context for easy access in handlers.
38
56
  *
39
- * @param core - The PlanetCore instance.
57
+ * @param core - The PlanetCore instance managing the application.
58
+ * @throws {Error} If the core adapter is missing or improperly configured.
40
59
  */
41
60
  install(core: PlanetCore): void;
42
61
  /**
43
- * Get webhook receiver
62
+ * Retrieves the underlying receiver instance for manual webhook processing.
63
+ *
64
+ * Use this when you need fine-grained control over how incoming webhooks
65
+ * are routed or verified outside of the standard middleware flow.
66
+ *
67
+ * @returns The active WebhookReceiver instance.
44
68
  */
45
69
  getReceiver(): WebhookReceiver;
46
70
  /**
47
- * Get webhook dispatcher
71
+ * Retrieves the dispatcher instance for sending outgoing webhooks.
72
+ *
73
+ * @returns The configured WebhookDispatcher, or undefined if dispatch is disabled.
48
74
  */
49
75
  getDispatcher(): WebhookDispatcher | undefined;
50
76
  /**
51
- * Get configuration
77
+ * Accesses the active configuration used by this OrbitEcho instance.
78
+ *
79
+ * @returns The immutable EchoConfig object.
52
80
  */
53
81
  getConfig(): EchoConfig;
82
+ /**
83
+ * Retrieves the key rotation manager responsible for secret lifecycle.
84
+ *
85
+ * @returns The manager instance, or undefined if key rotation is disabled.
86
+ */
87
+ getKeyRotationManager(): KeyRotationManager | undefined;
88
+ /**
89
+ * Initiates a zero-downtime primary key rotation for a specific provider.
90
+ *
91
+ * This method promotes a new key to primary status while maintaining valid old keys
92
+ * for a grace period, ensuring that webhooks signed with either key are accepted
93
+ * during the transition.
94
+ *
95
+ * @param providerName - The identifier of the provider to update.
96
+ * @param newKey - Metadata and value for the replacement key.
97
+ * @throws {Error} If key rotation is not enabled in the global configuration.
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * await echo.rotateProviderKey('stripe', {
102
+ * key: 'whsec_new_secret',
103
+ * version: 'v2',
104
+ * activeFrom: new Date()
105
+ * });
106
+ * ```
107
+ */
108
+ rotateProviderKey(providerName: string, newKey: Omit<ProviderKeyEntry, 'isPrimary'>): Promise<void>;
54
109
  }
55
110
  declare module '@gravito/core' {
56
111
  interface GravitoVariables {
@@ -0,0 +1,94 @@
1
+ import type { IncomingWebhookRecord, OutgoingWebhookRecord } from '../storage/WebhookStore';
2
+ /**
3
+ * Interface for a Dead Letter Queue (DLQ) implementation.
4
+ *
5
+ * A DLQ serves as a safety net for webhook events that have permanently failed
6
+ * all processing or delivery attempts. It enables manual inspection, diagnostic
7
+ * analysis, and eventual re-processing of high-value events that would otherwise
8
+ * be lost due to transient or permanent failures.
9
+ *
10
+ * @example Inspected failed events
11
+ * ```typescript
12
+ * const dlq: DeadLetterQueue = new MyPersistentDlq();
13
+ *
14
+ * // Retrieve recent failures for manual triage
15
+ * const failedEvents = await dlq.peek(10);
16
+ * for (const event of failedEvents) {
17
+ * console.log(`Event ${event.id} failed after ${event.retryCount} attempts: ${event.failureReason}`);
18
+ * }
19
+ * ```
20
+ *
21
+ * @public
22
+ */
23
+ export interface DeadLetterQueue {
24
+ /**
25
+ * Appends a permanently failed event to the queue for later inspection.
26
+ *
27
+ * @param event - The dead letter event metadata and original record.
28
+ * @returns A promise resolving to a unique identifier for the event within the queue.
29
+ * @throws {Error} If the underlying storage fails to persist the event.
30
+ */
31
+ enqueue(event: DeadLetterEvent): Promise<string>;
32
+ /**
33
+ * Retrieves a snapshot of failed events from the queue without removing them.
34
+ *
35
+ * @param limit - Maximum number of events to retrieve (ordered by failure time).
36
+ * @returns A collection of dead letter events.
37
+ */
38
+ peek(limit?: number): Promise<DeadLetterEvent[]>;
39
+ /**
40
+ * Permanently removes an event from the queue after successful manual resolution.
41
+ *
42
+ * @param id - The unique identifier assigned during the `enqueue` process.
43
+ * @throws {Error} If the event ID is invalid or not found in the queue.
44
+ */
45
+ dequeue(id: string): Promise<void>;
46
+ /**
47
+ * Calculates the total number of events currently residing in the queue.
48
+ *
49
+ * @returns The total count of dead letter events.
50
+ */
51
+ size(): Promise<number>;
52
+ /**
53
+ * Removes all events from the queue, resetting it to an empty state.
54
+ */
55
+ clear(): Promise<void>;
56
+ }
57
+ /**
58
+ * Metadata and payload for a failed webhook event stored in the Dead Letter Queue.
59
+ *
60
+ * This structure captures the complete context of a failure, including the original
61
+ * data and the diagnostic reason for the final failure.
62
+ *
63
+ * @public
64
+ */
65
+ export interface DeadLetterEvent {
66
+ /**
67
+ * A unique identifier for the entry within the DLQ storage.
68
+ */
69
+ id?: string;
70
+ /**
71
+ * Indicates whether the failure occurred during reception or dispatch.
72
+ */
73
+ type: 'incoming' | 'outgoing';
74
+ /**
75
+ * The complete original record of the webhook at the moment of failure.
76
+ */
77
+ originalEvent: IncomingWebhookRecord | OutgoingWebhookRecord;
78
+ /**
79
+ * A descriptive diagnostic message explaining why the event was sent to the DLQ.
80
+ */
81
+ failureReason: string;
82
+ /**
83
+ * The exact timestamp when the event reached its maximum retry limit or terminal error.
84
+ */
85
+ failedAt: Date;
86
+ /**
87
+ * The total number of automated attempts made before giving up on the event.
88
+ */
89
+ retryCount: number;
90
+ /**
91
+ * The timestamp of the final attempted processing or delivery action.
92
+ */
93
+ lastRetryAt?: Date;
94
+ }
@@ -0,0 +1,36 @@
1
+ import type { DeadLetterEvent, DeadLetterQueue } from './DeadLetterQueue';
2
+ /**
3
+ * An in-memory implementation of {@link DeadLetterQueue}.
4
+ * Suitable for development, testing, or small-scale applications where persistence is not required.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const dlq = new MemoryDeadLetterQueue();
9
+ * await dlq.enqueue(failedEvent);
10
+ * const size = await dlq.size();
11
+ * ```
12
+ */
13
+ export declare class MemoryDeadLetterQueue implements DeadLetterQueue {
14
+ private queue;
15
+ /**
16
+ * Stores the event in an internal Map.
17
+ * Generates a UUID if the event does not have an ID.
18
+ */
19
+ enqueue(event: DeadLetterEvent): Promise<string>;
20
+ /**
21
+ * Returns events sorted by failure timestamp.
22
+ */
23
+ peek(limit?: number): Promise<DeadLetterEvent[]>;
24
+ /**
25
+ * Removes the event from the internal Map.
26
+ */
27
+ dequeue(id: string): Promise<void>;
28
+ /**
29
+ * Returns the number of items in the internal Map.
30
+ */
31
+ size(): Promise<number>;
32
+ /**
33
+ * Clears the internal Map.
34
+ */
35
+ clear(): Promise<void>;
36
+ }
@@ -0,0 +1,2 @@
1
+ export * from './DeadLetterQueue';
2
+ export * from './MemoryDeadLetterQueue';
@@ -1,48 +1,64 @@
1
1
  /**
2
- * @fileoverview @gravito/echo - Enterprise Webhook Module
2
+ * @fileoverview \@gravito/echo - Enterprise Webhook Orchestration
3
3
  *
4
- * Secure webhook receiving and reliable webhook sending for Gravito.
4
+ * Echo provides a secure, reliable, and observable layer for handling webhooks
5
+ * in Gravito applications. It standardizes incoming webhook reception with
6
+ * signature verification and dynamic key rotation, while ensuring reliable
7
+ * outgoing delivery via exponential backoff and circuit breaking.
5
8
  *
6
- * @example Receiving webhooks
9
+ * @example Receiving webhooks from Stripe
7
10
  * ```typescript
8
11
  * import { OrbitEcho, WebhookReceiver } from '@gravito/echo'
9
12
  *
10
13
  * const core = new PlanetCore()
11
- *
12
14
  * core.install(new OrbitEcho({
13
15
  * providers: {
14
- * stripe: { name: 'stripe', secret: process.env.STRIPE_WEBHOOK_SECRET! }
16
+ * stripe: { name: 'stripe', secret: process.env.STRIPE_SECRET! }
15
17
  * }
16
18
  * }))
17
19
  *
18
20
  * const receiver = core.container.make<WebhookReceiver>('echo.receiver')
19
21
  * receiver.on('stripe', 'payment_intent.succeeded', async (event) => {
20
- * console.log('Payment:', event.payload)
22
+ * // Securely process validated payment
21
23
  * })
22
24
  * ```
23
25
  *
24
- * @example Sending webhooks
26
+ * @example Dispatching reliable outgoing webhooks
25
27
  * ```typescript
26
28
  * import { WebhookDispatcher } from '@gravito/echo'
27
29
  *
28
- * const dispatcher = new WebhookDispatcher({
29
- * secret: 'my-secret'
30
- * })
31
- *
30
+ * const dispatcher = new WebhookDispatcher({ secret: 'app-secret' })
32
31
  * await dispatcher.dispatch({
33
- * url: 'https://example.com/webhook',
32
+ * url: 'https://consumer.com/hook',
34
33
  * event: 'order.created',
35
- * data: { orderId: 123 }
34
+ * data: { id: 123 }
36
35
  * })
37
36
  * ```
38
37
  *
39
38
  * @module @gravito/echo
40
39
  */
40
+ export type { DeadLetterEvent, DeadLetterQueue } from './dlq/DeadLetterQueue';
41
+ export { MemoryDeadLetterQueue } from './dlq/MemoryDeadLetterQueue';
42
+ export { createRequestBufferMiddleware, RequestBufferMiddleware } from './middleware';
41
43
  export { OrbitEcho } from './OrbitEcho';
44
+ export type { EchoLogEvent, EchoLogger } from './observability/logging';
45
+ export { ConsoleEchoLogger } from './observability/logging';
46
+ export type { MetricsProvider, WebhookMetricLabels } from './observability/metrics';
47
+ export { EchoMetrics, NoopMetricsProvider, PrometheusMetricsProvider, } from './observability/metrics';
48
+ export type { Span, SpanOptions, Tracer } from './observability/tracing';
49
+ export { NoopSpan, NoopTracer, SpanStatusCode } from './observability/tracing';
50
+ export { BaseProvider, type ProviderOptions } from './providers/base/BaseProvider';
42
51
  export { GenericProvider } from './providers/GenericProvider';
43
52
  export { GitHubProvider } from './providers/GitHubProvider';
53
+ export { LinearProvider } from './providers/LinearProvider';
54
+ export { PaddleProvider } from './providers/PaddleProvider';
55
+ export { ShopifyProvider } from './providers/ShopifyProvider';
56
+ export { SlackProvider } from './providers/SlackProvider';
44
57
  export { StripeProvider } from './providers/StripeProvider';
58
+ export { TwilioProvider } from './providers/TwilioProvider';
45
59
  export { computeHmacSha1, computeHmacSha256, parseStripeSignature, timingSafeEqual, validateTimestamp, } from './receive/SignatureValidator';
46
60
  export { WebhookReceiver } from './receive/WebhookReceiver';
47
- export { WebhookDispatcher } from './send/WebhookDispatcher';
48
- export type { EchoConfig, RetryConfig, WebhookDeliveryResult, WebhookDispatcherConfig, WebhookEvent, WebhookHandler, WebhookPayload, WebhookProvider, WebhookProviderConfig, WebhookVerificationResult, } from './types';
61
+ export { WebhookReplayService } from './replay/WebhookReplayService';
62
+ export { CircuitBreaker } from './resilience';
63
+ export { KeyRotationManager } from './rotation';
64
+ export type { BufferedRequest, CircuitBreakerConfig, CircuitBreakerMetrics, CircuitBreakerState, EchoConfig, EchoObservabilityConfig, KeyRotationConfig, ProviderKeyEntry, ReplayOptions, ReplayResult, RequestBufferConfig, RetryConfig, WebhookDeliveryResult, WebhookDispatcherConfig, WebhookEvent, WebhookHandler, WebhookPayload, WebhookProvider, WebhookProviderConfig, WebhookProviderConfigWithRotation, WebhookVerificationResult, } from './types';
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Request Buffer Middleware
3
+ *
4
+ * 在驗證前緩存原始 Request Body,防止框架自動解析 JSON 導致簽章驗證失敗。
5
+ * 這個中介軟體會在請求處理鏈的早期階段攔截並緩存原始內容。
6
+ *
7
+ * @module @gravito/echo/middleware
8
+ * @since v1.1
9
+ */
10
+ import type { GravitoContext } from '@gravito/core';
11
+ import type { BufferedRequest, RequestBufferConfig } from '../types';
12
+ /**
13
+ * Request Buffer 中介軟體類別
14
+ *
15
+ * 提供原始 Body 緩存功能,確保簽章驗證使用正確的未解析內容。
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const middleware = new RequestBufferMiddleware({
20
+ * maxBodySize: 5 * 1024 * 1024, // 5MB
21
+ * })
22
+ *
23
+ * core.adapter.use('*', middleware.handler())
24
+ * ```
25
+ */
26
+ export declare class RequestBufferMiddleware {
27
+ private config;
28
+ constructor(config?: RequestBufferConfig);
29
+ /**
30
+ * 建立中介軟體處理函式
31
+ *
32
+ * @returns 中介軟體處理函式
33
+ */
34
+ handler(): (c: GravitoContext, next: () => Promise<Response | undefined>) => Promise<Response | undefined>;
35
+ /**
36
+ * 從請求中讀取原始 body
37
+ *
38
+ * @param c - Gravito Context
39
+ * @returns 原始 body(string 或 Buffer)
40
+ */
41
+ private readRawBody;
42
+ }
43
+ /**
44
+ * 便捷工廠函式,用於建立 Request Buffer 中介軟體
45
+ *
46
+ * @param config - 中介軟體配置
47
+ * @returns 中介軟體處理函式
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * core.adapter.use('*', createRequestBufferMiddleware({
52
+ * maxBodySize: 5 * 1024 * 1024
53
+ * }))
54
+ * ```
55
+ */
56
+ export declare function createRequestBufferMiddleware(config?: RequestBufferConfig): (c: GravitoContext, next: () => Promise<Response | undefined>) => Promise<Response | undefined>;
57
+ declare module '@gravito/core' {
58
+ interface GravitoVariables {
59
+ /** Buffered request for signature verification */
60
+ bufferedRequest?: BufferedRequest;
61
+ }
62
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Echo Middleware
3
+ *
4
+ * @module @gravito/echo/middleware
5
+ * @since v1.1
6
+ */
7
+ export type { BufferedRequest, RequestBufferConfig } from '../types';
8
+ export { createRequestBufferMiddleware, RequestBufferMiddleware } from './RequestBufferMiddleware';
@@ -0,0 +1,3 @@
1
+ export * from './logging';
2
+ export * from './metrics';
3
+ export * from './tracing';
@@ -0,0 +1,37 @@
1
+ import type { EchoLogger } from './EchoLogger';
2
+ /**
3
+ * A basic implementation of {@link EchoLogger} that outputs logs to the system console.
4
+ * Logs are formatted as JSON strings to facilitate integration with log aggregators.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const logger = new ConsoleEchoLogger();
9
+ * logger.info('Service started');
10
+ * ```
11
+ */
12
+ export declare class ConsoleEchoLogger implements EchoLogger {
13
+ /**
14
+ * Enriches the log context with default module information and timestamps.
15
+ *
16
+ * @param base - The base context object.
17
+ * @param extra - Additional metadata to include.
18
+ * @returns A merged context object.
19
+ */
20
+ private formatContext;
21
+ /**
22
+ * Outputs a debug-level log entry.
23
+ */
24
+ debug(message: string, context?: Record<string, unknown>): void;
25
+ /**
26
+ * Outputs an info-level log entry.
27
+ */
28
+ info(message: string, context?: Record<string, unknown>): void;
29
+ /**
30
+ * Outputs a warn-level log entry.
31
+ */
32
+ warn(message: string, context?: Record<string, unknown>): void;
33
+ /**
34
+ * Outputs an error-level log entry.
35
+ */
36
+ error(message: string, context?: Record<string, unknown>): void;
37
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Represents a structured log event within the Echo module.
3
+ * Used to ensure consistency across different logging implementations.
4
+ */
5
+ export interface EchoLogEvent {
6
+ /** Severity level of the log entry. */
7
+ level: 'debug' | 'info' | 'warn' | 'error';
8
+ /** Human-readable message describing the event. */
9
+ message: string;
10
+ /** Contextual metadata for better traceability. */
11
+ context: {
12
+ /** Always 'echo' to identify the source module. */
13
+ module: 'echo';
14
+ /** The specific sub-component triggering the log. */
15
+ component: 'receiver' | 'dispatcher' | 'dlq' | 'replay';
16
+ [key: string]: unknown;
17
+ };
18
+ }
19
+ /**
20
+ * Defines the standard logging interface for the Echo module.
21
+ * Implementations should handle structured data for observability.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const logger: EchoLogger = new ConsoleEchoLogger();
26
+ * logger.info('Webhook received', { provider: 'stripe' });
27
+ * ```
28
+ */
29
+ export interface EchoLogger {
30
+ /** Logs fine-grained informational events that are most useful to debug an application. */
31
+ debug(message: string, context?: Record<string, unknown>): void;
32
+ /** Logs informational messages that highlight the progress of the application at coarse-grained level. */
33
+ info(message: string, context?: Record<string, unknown>): void;
34
+ /** Logs potentially harmful situations. */
35
+ warn(message: string, context?: Record<string, unknown>): void;
36
+ /** Logs error events that might still allow the application to continue running. */
37
+ error(message: string, context?: Record<string, unknown>): void;
38
+ }
@@ -0,0 +1,2 @@
1
+ export * from './ConsoleEchoLogger';
2
+ export * from './EchoLogger';
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Defines the interface for collecting application metrics.
3
+ * Implementations can bridge to Prometheus, StatsD, or other monitoring systems.
4
+ *
5
+ * @example
6
+ * ```typescript
7
+ * const metrics: MetricsProvider = getMetrics();
8
+ * metrics.increment(EchoMetrics.INCOMING_TOTAL, { provider: 'stripe' });
9
+ * ```
10
+ */
11
+ export interface MetricsProvider {
12
+ /**
13
+ * Increments a counter by 1.
14
+ * Counters are used for values that only increase (e.g., total requests).
15
+ */
16
+ increment(name: string, labels?: Record<string, string>): void;
17
+ /**
18
+ * Records a value in a histogram.
19
+ * Histograms are used to track the distribution of values (e.g., request latency).
20
+ */
21
+ histogram(name: string, value: number, labels?: Record<string, string>): void;
22
+ /**
23
+ * Sets a gauge to a specific value.
24
+ * Gauges are used for values that can go up and down (e.g., current queue size).
25
+ */
26
+ gauge(name: string, value: number, labels?: Record<string, string>): void;
27
+ }
28
+ /**
29
+ * Common labels used for webhook-related metrics.
30
+ */
31
+ export interface WebhookMetricLabels {
32
+ /** The webhook provider name (e.g., 'stripe', 'github'). */
33
+ provider?: string;
34
+ /** The type of event received or sent. */
35
+ event_type?: string;
36
+ /** The outcome of the operation. */
37
+ status?: 'success' | 'failure';
38
+ /** The HTTP status code returned by the remote server. */
39
+ status_code?: string;
40
+ /** A category for the error if the operation failed. */
41
+ error_type?: string;
42
+ [key: string]: string | undefined;
43
+ }
44
+ /**
45
+ * Standard metric names used across the Echo module.
46
+ * Use these constants to ensure consistency in dashboards and alerts.
47
+ */
48
+ export declare const EchoMetrics: {
49
+ /** Total number of incoming webhooks received. */
50
+ readonly INCOMING_TOTAL: "echo_incoming_webhooks_total";
51
+ /** Time taken to process an incoming webhook. */
52
+ readonly INCOMING_DURATION: "echo_incoming_duration_seconds";
53
+ /** Total number of incoming webhooks that failed signature verification. */
54
+ readonly INCOMING_VERIFICATION_FAILURES: "echo_incoming_verification_failures_total";
55
+ /** Total number of outgoing webhooks dispatched. */
56
+ readonly OUTGOING_TOTAL: "echo_outgoing_webhooks_total";
57
+ /** Time taken to deliver an outgoing webhook. */
58
+ readonly OUTGOING_DURATION: "echo_outgoing_duration_seconds";
59
+ /** Total number of retry attempts for outgoing webhooks. */
60
+ readonly OUTGOING_RETRIES: "echo_outgoing_retries_total";
61
+ /** Total number of outgoing webhooks that failed after all retries. */
62
+ readonly OUTGOING_FAILURES: "echo_outgoing_failures_total";
63
+ /** Current number of items in the Dead Letter Queue. */
64
+ readonly DLQ_SIZE: "echo_dlq_size";
65
+ /** Total number of items added to the DLQ. */
66
+ readonly DLQ_ENQUEUED: "echo_dlq_enqueued_total";
67
+ /** Total number of items successfully processed from the DLQ. */
68
+ readonly DLQ_PROCESSED: "echo_dlq_processed_total";
69
+ };
@@ -0,0 +1,17 @@
1
+ import type { MetricsProvider } from './MetricsProvider';
2
+ /**
3
+ * A non-operational implementation of {@link MetricsProvider}.
4
+ * Used as the default provider to ensure the application remains functional
5
+ * even if no monitoring system is configured.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const metrics = new NoopMetricsProvider();
10
+ * metrics.increment('any_metric'); // Does nothing
11
+ * ```
12
+ */
13
+ export declare class NoopMetricsProvider implements MetricsProvider {
14
+ increment(): void;
15
+ histogram(): void;
16
+ gauge(): void;
17
+ }
@@ -0,0 +1,39 @@
1
+ import type { MetricsProvider } from './MetricsProvider';
2
+ /**
3
+ * A Prometheus-compatible metrics provider.
4
+ * Collects and formats metrics in the Prometheus text-based format.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * const provider = new PrometheusMetricsProvider();
9
+ * provider.increment('http_requests_total', { method: 'POST' });
10
+ * console.log(provider.export());
11
+ * ```
12
+ */
13
+ export declare class PrometheusMetricsProvider implements MetricsProvider {
14
+ private counters;
15
+ private histograms;
16
+ private gauges;
17
+ /**
18
+ * Increments a counter for the given name and labels.
19
+ */
20
+ increment(name: string, labels?: Record<string, string>): void;
21
+ /**
22
+ * Records a value in a histogram for the given name and labels.
23
+ */
24
+ histogram(name: string, value: number, labels?: Record<string, string>): void;
25
+ /**
26
+ * Sets a gauge to a specific value for the given name and labels.
27
+ */
28
+ gauge(name: string, value: number, labels?: Record<string, string>): void;
29
+ /**
30
+ * Exports all collected metrics in Prometheus text format.
31
+ *
32
+ * @returns A string containing the formatted metrics.
33
+ */
34
+ export(): string;
35
+ /**
36
+ * Builds a Prometheus-compatible metric key with labels.
37
+ */
38
+ private buildKey;
39
+ }
@@ -0,0 +1,3 @@
1
+ export * from './MetricsProvider';
2
+ export * from './NoopMetricsProvider';
3
+ export * from './PrometheusMetricsProvider';
@@ -0,0 +1,33 @@
1
+ import type { Span, Tracer } from './Tracer';
2
+ /**
3
+ * A non-operational implementation of {@link Span}.
4
+ * Used as a fallback when tracing is disabled to avoid null checks.
5
+ */
6
+ export declare class NoopSpan implements Span {
7
+ setAttribute(): this;
8
+ setAttributes(): this;
9
+ addEvent(): this;
10
+ setStatus(): this;
11
+ end(): void;
12
+ }
13
+ /**
14
+ * A non-operational implementation of {@link Tracer}.
15
+ * Ensures the application can run without a tracing backend.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * const tracer = new NoopTracer();
20
+ * const span = tracer.startSpan('test');
21
+ * span.end();
22
+ * ```
23
+ */
24
+ export declare class NoopTracer implements Tracer {
25
+ /**
26
+ * Returns a {@link NoopSpan} that does nothing.
27
+ */
28
+ startSpan(): Span;
29
+ /**
30
+ * Executes the function with a {@link NoopSpan}.
31
+ */
32
+ withSpan<T>(_name: string, fn: (span: Span) => T | Promise<T>): Promise<T>;
33
+ }