Skip to content

feat(platform): add real-time platform event subscriptions via gRPC streaming - #2795

Closed
lklimek wants to merge 55 commits into
v4.2-devfrom
feat/drive-event-bus
Closed

lklimek wants to merge 55 commits into
v4.2-devfrom
feat/drive-event-bus

Conversation

@lklimek

@lklimek lklimek commented Oct 2, 2025 •

Copy link
Copy Markdown
Contributor

User Story

As a DAPI client developer,
I want to subscribe to real-time platform events (block commits and state transition results) via a gRPC server-streaming RPC,
So that I can react to on-chain changes instantly without polling, enabling responsive dashboards, transaction confirmation UIs, and event-driven integrations.

Acceptance Criteria

  • Clients can open a subscribePlatformEvents gRPC stream and receive events matching a chosen filter (AllEvents, BlockCommitted, or StateTransitionResult optionally scoped by tx_hash).
  • Each subscription begins with a handshake message carrying a server-generated subscription_id.
  • Configurable keepalive messages (25-300 s interval) prevent idle-timeout disconnects through proxies.
  • Dashmate config migrations add the new timeout settings automatically; no manual operator edits are required.
  • The Rust SDK exposes Sdk::subscribe_platform_events() returning a tonic::Streaming for ergonomic consumption.

Summary

This PR introduces preliminary scaffolding for a real-time platform event bus, enabling DAPI clients to consume Drive's block-commit and state-transition events via a gRPC server-streaming RPC instead of polling.

Key changes

1. Protobuf schema & gRPC contract (dapi-grpc)

  • New versioned messages: PlatformSubscriptionRequest / PlatformSubscriptionResponse, PlatformFilterV0 (with AllEvents, BlockCommitted, StateTransitionResultFilter variants), and PlatformEventV0 (with BlockCommitted, StateTransitionFinalized, Keepalive event types).
  • New server-streaming RPC: subscribePlatformEvents(PlatformSubscriptionRequest) returns (stream PlatformSubscriptionResponse).
  • Regenerated gRPC client stubs for Node.js, Python, Java, Objective-C, and Web.

2. In-process event bus (rs-dash-event-bus)

  • Generic EventBus<E, F> with pluggable Filter<E> trait, backed by per-subscriber tokio::mpsc channels (capacity 256).
  • RAII SubscriptionHandle auto-unsubscribes on drop; no_unsubscribe_on_drop() opt-out for manual lifecycle control.
  • notify_sync() fire-and-forget variant for non-async contexts (used in ABCI finalize_block).
  • Optional Prometheus metrics: active subscriptions gauge, subscribe/unsubscribe/published/delivered/dropped counters.

3. Drive ABCI event emission (rs-drive-abci)

  • finalize_block handler publishes BlockCommitted (with block metadata + tx count) and per-tx StateTransitionFinalized (with SHA-256 tx hash) events to the shared event bus after each committed block.
  • EventBusApplication trait added to the ABCI app hierarchy; event bus instance threaded from server startup through consensus and query services.
  • QueryService implements subscribe_platform_events directly on Drive: validates request version, filter, and keepalive range; creates a subscription; sends handshake; spawns a worker that forwards events or emits keepalive pings on timeout; cleans up finished workers.
  • PlatformFilterAdapter bridges the protobuf PlatformFilterV0 to the event bus Filter trait, always passing keepalives through.

4. DAPI proxy layer (rs-dapi)

  • subscribe_platform_events_impl in PlatformServiceImpl opens an upstream gRPC stream to Drive and forwards responses downstream with ActiveSessionGuard RAII tracking.
  • Prometheus counters: platform_events_active_sessions, platform_events_upstream_stream_started, platform_events_forwarded_event/error.
  • Configurable per-route timeouts via new SUBSCRIBE_PLATFORM_EVENTS_TIMEOUT and CORE_STREAMS_TIMEOUT env vars.

5. Dashmate operator tooling (dashmate)

  • New config keys under platform.dapi.envoy.rateLimiter.timeouts: subscribePlatformEvents (default 300s), coreStreams (default 600s), waitForStateTransitionResult (default 80s).
  • Envoy template updated with per-route max_stream_duration / grpc_timeout_header_max and a 5 s streaming grace period.
  • Config JSON schema extended; migration 2.2.0-dev.1 backfills new timeout keys from older configs.
  • dashmate restart --platform now also restarts rs-dapi and Envoy containers.

6. Rust SDK & WASM bindings (rs-sdk, wasm-sdk)

  • Sdk::subscribe_platform_events(filter) helper creates a dedicated gRPC channel with 1-hour timeout and auto-computed keepalive interval.
  • New Error::SubscriptionError variant mapped to WASM WasmError.
  • Example binary platform_events demonstrates subscribing and printing events.
  • Network integration test platform_events.rs validates the handshake flow.

7. Tests

  • rs-dash-event-bus: unit tests for subscribe/notify, filter, drop cleanup, manual unsubscribe.
  • rs-drive-abci: event_bus_tests.rs strategy test verifying event emission during block execution.
  • rs-sdk: network integration test for end-to-end subscription handshake.

Note

This is a preliminary implementation providing the necessary scaffolding to emit and deliver events. The implemented events (BlockCommitted, StateTransitionFinalized) are proof-of-concept. Further work is needed to emit richer, domain-specific events (e.g., document updates, identity changes).

Breaking Changes

  • None code-wise. The gRPC interface is purely additive, and dashmate migrations automatically backfill new timeout settings.
  • Some dashmate config keys were reorganized (especially timeout groupings under platform.dapi.envoy.rateLimiter.timeouts).

Test Plan

  • Verify rs-dash-event-bus unit tests pass (cargo test -p rs-dash-event-bus)
  • Verify rs-drive-abci event bus strategy tests pass (cargo test -p drive-abci --test strategy_tests event_bus)
  • Run the platform_events example against a local devnet to confirm handshake and event delivery
  • Deploy with dashmate and verify config migrations apply cleanly on upgrade
  • Confirm Envoy proxies the streaming RPC with correct timeout behavior

Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Oct 2, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds server-streaming Platform event subscriptions: new protobuf messages and RPC, event bus integration in ABCI and rs-dapi, subscription forwarding and client SDK support, per-method timeouts and config, generated language bindings, tests, and docs/config migrations.

Changes

Cohort / File(s) Summary
Protobuf & generated clients
packages/dapi-grpc/protos/platform/v0/platform.proto, packages/dapi-grpc/clients/platform/v0/*
Added versioned subscription messages (PlatformSubscriptionRequest/Response, PlatformEventV0, PlatformFilterV0) and server-streaming RPC subscribePlatformEvents; regenerated JS/TS/Java/Python/Objective‑C client bindings and service descriptors.
rs-dapi: subscription handling & timeouts
packages/rs-dapi/src/services/platform_service/..., packages/rs-dapi/src/server/grpc.rs, packages/rs-dapi/src/config/*, packages/rs-dapi/src/main.rs, packages/rs-dapi/src/metrics.rs
Implemented upstream-forwarding subscribe_platform_events flow with ReceiverStream, ActiveSessionGuard and metrics; refactored TimeoutLayer to per-method timeouts (state_transition, platform_events, core_stream); added config fields platform_events_timeout and core_stream_timeout; removed obsolete platform metrics; minor server future ownership change.
Event bus core & integration
packages/rs-dash-event-bus/*, packages/rs-drive-abci/src/*, packages/rs-drive-abci/Cargo.toml
Introduced in-process EventBus usage, added EventBusApplication trait, wired EventBus into Full/Consensus ABci applications, published BlockCommitted and StateTransitionFinalized events at finalize_block, and exposed PlatformFilterAdapter for matching.
QueryService & streaming workers
packages/rs-drive-abci/src/query/service.rs, packages/rs-drive-abci/src/query/mod.rs, packages/rs-drive-abci/src/server.rs
QueryService now accepts EventBus and PlatformFilterAdapter, implements subscribe_platform_events server stream with worker tasks and buffer; adjusted constructors to accept EventBus.
SDK: subscriptions feature & examples/tests
packages/rs-sdk/Cargo.toml, packages/rs-sdk/src/platform/events.rs, packages/rs-sdk/src/sdk.rs, packages/rs-sdk/examples/platform_events.rs, packages/rs-sdk/tests/*
Added subscriptions feature, SubscriptionError variant, Sdk.subscribe_platform_events returning Streaming, worker tracking in Sdk, example and tests demonstrating handshake and event handling.
WASM & error mapping
packages/wasm-sdk/src/error.rs
Map new SubscriptionError to WasmSdkError translation.
Configuration, schema & dashmate changes
packages/dashmate/*, packages/dashmate/src/config/configJsonSchema.js
Migrated from legacy waitForStResultTimeout to structured platform.dapi.rsDapi.timeouts (waitForStateTransitionResult, subscribePlatformEvents, coreStreams); added env vars and docker-compose env mappings.
Docs & design
packages/rs-dapi/doc/DESIGN.md, packages/rs-dapi/README.md, packages/dashmate/docs/*
Documented subscription flow changes, timeouts, and new env vars; updated design notes to reflect per-subscription upstream connections.
Event bus test & miscellaneous cleanups
packages/rs-drive-abci/tests/*, packages/rs-dash-event-bus/src/event_bus.rs, packages/rs-sdk/tests/fetch/*, other small edits
Added an in-process event bus integration test; improved SubscriptionHandle drop removal behavior; small code simplifications and lint/attribute updates across tests and modules.
Repo tooling
.github/scripts/check-grpc-coverage.py, packages/dapi-grpc/src/lib.rs
Excluded subscribePlatformEvents from gRPC coverage check; added lint allow for non-camel-case types in dapi-grpc platform module.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant rsDapi as rs-dapi\nPlatformService
    participant Drive as Drive\n(upstream)
    participant EventBus as EventBus\n(in-process)
    participant ABci as rs-drive-abci\nConsensusApp

    Client->>rsDapi: PlatformSubscriptionRequest(filter, keepalive)
    activate rsDapi
    rsDapi->>Drive: open upstream subscription (filter)
    activate Drive
    Drive-->>rsDapi: upstream PlatformSubscriptionResponse events
    rsDapi-->>Client: stream PlatformSubscriptionResponse events

    ABci->>EventBus: publish BlockCommitted / StateTransitionFinalized
    EventBus-->>rsDapi: matched events delivered
    rsDapi-->>Client: forwarded PlatformSubscriptionResponse (BlockCommitted / StateTransitionFinalized)

    note over rsDapi: keepalive timer -> keepalive events
    rsDapi-->>Client: PlatformSubscriptionResponse(Keepalive)

    Client->>rsDapi: cancel / stream ends
    deactivate rsDapi
    deactivate Drive
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Key areas requiring attention:

  • EventBus integration and finalize_block publishers: correctness of metadata, tx hashing, and metrics.
  • TimeoutLayer mapping: ensure every gRPC path uses intended timeout and tests updated accordingly.
  • Subscription lifecycle: ActiveSessionGuard, channel buffering, task aborts, keepalive semantics and error handling.
  • Generated client bindings: verify language-specific generated code compiles and follows expected APIs (Objective‑C descriptors, Java stubs, JS/TS service clients).
  • Config migration and dashmate schema: ensure backward compatibility and environment variable mappings.

"I hopped through code with a twitchy ear,
Subscribed to events both far and near,
I buffered, forwarded, and kept time with care,
Now blocks and states dance through the air —
🐇✨"

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and specifically describes the main feature added: real-time platform event subscriptions via gRPC streaming. It directly reflects the core change across the codebase.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/drive-event-bus

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Oct 2, 2025 •

Copy link
Copy Markdown
Contributor

✅ gRPC Query Coverage Report

================================================================================
gRPC Query Coverage Report - NEW QUERIES ONLY
================================================================================

Total queries in proto: 54
Previously known queries: 47
New queries found: 7

================================================================================

New Query Implementation Status:
--------------------------------------------------------------------------------
✓ getAddressInfo                                /home/runner/work/platform/platform/packages/rs-sdk/src/platform/query.rs
✓ getAddressesBranchState                       /home/runner/work/platform/platform/packages/rs-sdk/src/platform/address_sync/mod.rs
✓ getAddressesInfos                             /home/runner/work/platform/platform/packages/rs-sdk/src/platform/fetch_many.rs
✓ getAddressesTrunkState                        /home/runner/work/platform/platform/packages/rs-sdk/src/platform/query.rs
✓ getRecentAddressBalanceChanges                /home/runner/work/platform/platform/packages/rs-sdk/src/platform/query.rs
✓ getRecentCompactedAddressBalanceChanges       /home/runner/work/platform/platform/packages/rs-sdk/src/platform/query.rs
⊘ subscribePlatformEvents                       EXCLUDED

================================================================================
Summary:
--------------------------------------------------------------------------------
New queries implemented: 6 (100.0%)
New queries missing: 0 (0.0%)

Total known queries: 54
  - Implemented: 50
  - Not implemented: 2
  - Excluded: 2

Not implemented queries:
  - getConsensusParams
  - getTokenPreProgrammedDistributions

@lklimek

lklimek commented Oct 2, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review all

@coderabbitai

coderabbitai Bot commented Oct 2, 2025

Copy link
Copy Markdown
Contributor

@lklimek: I'll perform a comprehensive review of all the changes in this PR.

✅ Actions performed

Full review triggered.

@pshenmic

pshenmic commented Oct 13, 2025 •

Copy link
Copy Markdown
Contributor

Client streaming and bi-directional streams are not available via GRPC Web, it is not supported by the Javascript libraries and most likely will not be supported, because all of them uses Fetch as underlying layer for transport.

Server streaming is supported though, it would be great to have a subscription RPC that we could use from Web, and I feel like it is rarely when you want to change your subscription conditions, it is much easier to just cancel an create new subscription, and passing a list of params for subscription should work too.

I recently received a question, how do one subscribe on new documents or transactions to his data contracts, because people would like to build applications like chats, or integrations in their backend already, for example for accepting tokens in payment gateways, so I'm looking forward to it!

@lklimek

lklimek commented Oct 13, 2025

Copy link
Copy Markdown
Contributor Author

Client streaming and bi-directional streams are not available via GRPC Web, it is not supported by the Javascript libraries and most likely will not be supported, because all of them uses Fetch as underlying layer for transport.

Thanks for that info! I'll refactor to unidirectional grpc-web.

@github-actions

github-actions Bot commented Oct 21, 2025 •

Copy link
Copy Markdown
Contributor

✅ DashSDKFFI.xcframework built for this PR.

SwiftPM (host the zip at a stable URL, then use):

.binaryTarget(
  name: "DashSDKFFI",
  url: "https://your.cdn.example/DashSDKFFI.xcframework.zip",
  checksum: "98c41c31f68504925d54794895bec3fa86272c4490dcd8e362eba13a5ab9318f"
)

Xcode manual integration:

  • Download 'DashSDKFFI.xcframework' artifact from the run link above.
  • Drag it into your app target (Frameworks, Libraries & Embedded Content) and set Embed & Sign.
  • If using the Swift wrapper package, point its binaryTarget to the xcframework location or add the package and place the xcframework at the expected path.

@lklimek

lklimek commented Oct 22, 2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review all

@coderabbitai

coderabbitai Bot commented Oct 22, 2025

Copy link
Copy Markdown
Contributor

@lklimek: I'll perform a comprehensive review of all the changes in this PR.

✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (14)
packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (1)

164-166: Nice refactor using let-chains.

The consolidated conditional using && let Ok(tx_data) = is more concise and idiomatic than nested if-let blocks, with no change in behavior.

packages/rs-dapi/src/services/platform_service/subscribe_platform_events.rs (2)

11-27: Good session tracking pattern with one consideration.

The ActiveSessionGuard with Arc and Drop ensures proper metric cleanup. The buffer size of 512 is used but lacks justification in comments.

Consider documenting why 512 was chosen for PLATFORM_EVENTS_STREAM_BUFFER (e.g., based on expected event rate, memory constraints, or latency requirements).


53-79: Forwarding loop is sound, but final return value appears unused.

The message forwarding logic correctly handles both success and error cases with proper metrics. However, the Err::<(), DapiError>(DapiError::ConnectionClosed) at line 78 serves no purpose since the spawned task's result is never awaited or checked.

Consider either:

  • Removing the return value entirely (just let the task complete without returning anything)
  • Or documenting why it's needed if there's a future plan to track task results
                }
                tracing::debug!("Platform events uplink response stream closed");
-               Err::<(), DapiError>(DapiError::ConnectionClosed)
            });
packages/rs-sdk/tests/fetch/platform_events.rs (1)

48-53: Make the “stream stays open” check non-flaky

Relying on “no message within 250ms” can intermittently fail if an event arrives quickly. Treat both “timeout” and “got a message” as success, and only fail on early close or error.

Apply:

-    let wait_result = timeout(Duration::from_millis(250), stream.message()).await;
-    assert!(
-        wait_result.is_err(),
-        "expected to time out waiting for initial platform event"
-    );
+    match timeout(Duration::from_millis(250), stream.message()).await {
+        // No message within window → stream is open; good.
+        Err(_elapsed) => {}
+        // Message arrived quickly → also fine; stream is open.
+        Ok(Ok(Some(_))) => {}
+        // Stream closed unexpectedly.
+        Ok(Ok(None)) => panic!("stream closed unexpectedly"),
+        // Transport error.
+        Ok(Err(status)) => panic!("stream errored early: {status}"),
+    }
packages/rs-drive-abci/src/abci/app/mod.rs (1)

21-27: Reduce cross-crate coupling of EventBusApplication

The trait hard-codes dapi_grpc::platform::v0 types, coupling ABCI app to gRPC schema. Consider a type alias exported from this crate (or make the trait generic) to decouple and ease future proto evolution.

Example:

pub type PlatformEvent = dapi_grpc::platform::v0::PlatformEventV0;
pub trait EventBusApplication {
    fn event_bus(&self) -> &EventBus<PlatformEvent, PlatformFilterAdapter>;
}
packages/rs-drive-abci/src/server.rs (1)

23-30: EventBus initialized and injected correctly; consider tunable capacity

Default per-subscription channel capacity comes from EventBus::new() (256). If high fan‑out or bursty publishers are expected, consider making capacity configurable via PlatformConfig and using with_capacity().

Also applies to: 79-80

packages/rs-dapi/doc/DESIGN.md (1)

267-291: Clarify gRPC‑Web limitation and client lifecycle

Explicitly note gRPC‑Web doesn’t support client/bidi streaming; only server streaming is exposed. Recommend “cancel and recreate” pattern when changing subscription parameters, as it’s simpler than dynamic updates.

packages/rs-sdk/src/sdk.rs (1)

607-625: Avoid panic on contested lock; use async lock for workers

try_lock() can spuriously panic under contention. Use lock().await and drop yield_now(). Also consider honoring Sdk::cancel_token inside spawned tasks to ensure graceful shutdown.

[Based on learnings]
Apply:

-    pub(crate) async fn spawn(
+    pub(crate) async fn spawn(
         &self,
         task: impl std::future::Future<Output = ()> + Send + 'static,
     ) -> tokio::sync::oneshot::Receiver<()> {
         let (done_tx, done_rx) = tokio::sync::oneshot::channel();
-        let mut workers = self
-            .workers
-            .try_lock()
-            .expect("workers lock is poisoned or in use");
-        workers.spawn(async move {
+        let mut workers = self.workers.lock().await;
+        let cancel = self.cancel_token.clone();
+        workers.spawn(async move {
+            tokio::select! {
+                _ = cancel.cancelled() => {},
+                _ = task => {},
+            }
             task.await;
             let _ = done_tx.send(());
         });
-        tokio::task::yield_now().await;
 
         done_rx
     }
packages/rs-sdk/src/platform/events.rs (2)

79-86: Streaming deadline: consider no overall timeout.

Setting timeout: Some(Duration::from_secs(3600)) will terminate long‑lived streams after 1 hour. For subscriptions, “no deadline” is usually preferable; rely on client cancel.

 let settings = self
     .dapi_client_settings
     .override_by(RequestSettings {
         connect_timeout: Some(Duration::from_secs(5)),
-        timeout: Some(Duration::from_secs(3600)),
+        // Streaming subscriptions typically shouldn't have a fixed deadline
+        timeout: None,
         ..Default::default()
     })
     .finalize();

16-28: Comment/typo fixes to avoid confusion.

  • “siginificant” → “significant”.
  • “ofprocess” → “of process”.
  • Display comment says “timepid” but code prints “pid_time”.
-/// ID generator with most siginificant bits based on local process info.
+/// ID generator with most significant bits based on local process info.
@@
-    // 32..47 bits: lower 16 bits ofprocess start time in seconds
+    // 32..47 bits: lower 16 bits of process start time in seconds
@@
-        // Write in format: timepid:counter
+        // Write in format: pid_time:counter

Also applies to: 40-46

packages/rs-drive-abci/src/abci/handler/finalize_block.rs (1)

115-146: DRY: duplicate BlockMetadata computation.

Factor out metadata creation to a helper to reduce duplication and keep event payloads consistent.

@@
-fn publish_block_committed_event(
+fn block_metadata_from(
+    request_finalize_block: &FinalizeBlockCleanedRequest,
+) -> platform_event_v0::BlockMetadata {
+    let header_time = request_finalize_block.block.header.time;
+    let seconds = header_time.seconds as i128;
+    let nanos = header_time.nanos as i128;
+    let time_ms = (seconds * 1000) + (nanos / 1_000_000);
+    platform_event_v0::BlockMetadata {
+        height: request_finalize_block.height,
+        time_ms: time_ms as u64,
+        block_id_hash: request_finalize_block.block_id.hash.to_vec(),
+    }
+}
+
+fn publish_block_committed_event(
     event_bus: &dash_event_bus::event_bus::EventBus<PlatformEventV0, PlatformFilterAdapter>,
     request_finalize_block: &FinalizeBlockCleanedRequest,
 ) -> Result<(), Error> {
-    // Publish BlockCommitted platform event to the global event bus (best-effort)
-    let header_time = request_finalize_block.block.header.time;
-    let seconds = header_time.seconds as i128;
-    let nanos = header_time.nanos as i128;
-    let time_ms = (seconds * 1000) + (nanos / 1_000_000);
-
-    let meta = platform_event_v0::BlockMetadata {
-        height: request_finalize_block.height,
-        time_ms: time_ms as u64,
-        block_id_hash: request_finalize_block.block_id.hash.to_vec(),
-    };
+    // Publish BlockCommitted platform event to the global event bus (best-effort)
+    let meta = block_metadata_from(request_finalize_block);
@@
-fn publish_state_transition_result_events(
+fn publish_state_transition_result_events(
     event_bus: &dash_event_bus::event_bus::EventBus<PlatformEventV0, PlatformFilterAdapter>,
     request_finalize_block: &FinalizeBlockCleanedRequest,
 ) -> Result<(), Error> {
-    // Prepare BlockMetadata once
-    let header_time = request_finalize_block.block.header.time;
-    let seconds = header_time.seconds as i128;
-    let nanos = header_time.nanos as i128;
-    let time_ms = (seconds * 1000) + (nanos / 1_000_000);
-
-    let meta = platform_event_v0::BlockMetadata {
-        height: request_finalize_block.height,
-        time_ms: time_ms as u64,
-        block_id_hash: request_finalize_block.block_id.hash.to_vec(),
-    };
+    // Prepare BlockMetadata once
+    let meta = block_metadata_from(request_finalize_block);

Also applies to: 148-179

packages/rs-sdk/examples/platform_events.rs (1)

87-96: Fail fast on invalid hex to avoid unintended “match all”.

.ok() swallows decode errors, turning an invalid hex filter into no filter (streaming all STRs).

-        let tx_hash_bytes = config
-            .state_transition_tx_hash_hex
-            .as_deref()
-            .and_then(|s| hex::decode(s).ok());
+        let tx_hash_bytes = config
+            .state_transition_tx_hash_hex
+            .as_deref()
+            .map(|s| hex::decode(s).expect("invalid DASH_SDK_STATE_TRANSITION_TX_HASH_HEX"));
packages/rs-drive-abci/src/query/service.rs (1)

271-310: Filter adapter logic looks correct and minimal.

Matching All/BlockCommitted/StateTransitionResult with optional tx_hash is clear and efficient.

Consider logging the filter summary once per subscription for observability.

packages/dapi-grpc/protos/platform/v0/platform.proto (1)

165-167: Clarify RPC streaming semantics in comment.

The comment states "Bi-directional stream" but the RPC signature is actually server-streaming only (request is unary, response is streamed). This is intentional for gRPC-Web compatibility, but the comment should reflect that. Update it to clarify the streaming direction and rationale.

  // Bi-directional stream for multiplexed platform events subscriptions
-  rpc SubscribePlatformEvents(PlatformSubscriptionRequest)
+  // Server-streaming RPC for multiplexed platform events subscriptions
+  // (Unidirectional; gRPC-Web compatible per RFC on client-streaming limitations)
+  rpc SubscribePlatformEvents(PlatformSubscriptionRequest)
       returns (stream PlatformSubscriptionResponse);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 146643b and 1d7ca2e.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (29)
  • packages/dapi-grpc/protos/platform/v0/platform.proto (2 hunks)
  • packages/rs-dapi/doc/DESIGN.md (2 hunks)
  • packages/rs-dapi/src/main.rs (2 hunks)
  • packages/rs-dapi/src/metrics.rs (0 hunks)
  • packages/rs-dapi/src/services/platform_service/mod.rs (2 hunks)
  • packages/rs-dapi/src/services/platform_service/subscribe_platform_events.rs (1 hunks)
  • packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (1 hunks)
  • packages/rs-dapi/src/services/streaming_service/bloom.rs (1 hunks)
  • packages/rs-dash-event-bus/Cargo.toml (1 hunks)
  • packages/rs-dash-event-bus/src/event_bus.rs (1 hunks)
  • packages/rs-dash-event-bus/src/lib.rs (1 hunks)
  • packages/rs-drive-abci/Cargo.toml (2 hunks)
  • packages/rs-drive-abci/src/abci/app/consensus.rs (3 hunks)
  • packages/rs-drive-abci/src/abci/app/full.rs (4 hunks)
  • packages/rs-drive-abci/src/abci/app/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/abci/handler/finalize_block.rs (4 hunks)
  • packages/rs-drive-abci/src/query/mod.rs (1 hunks)
  • packages/rs-drive-abci/src/query/service.rs (4 hunks)
  • packages/rs-drive-abci/src/server.rs (2 hunks)
  • packages/rs-drive-abci/tests/strategy_tests/main.rs (1 hunks)
  • packages/rs-sdk/Cargo.toml (4 hunks)
  • packages/rs-sdk/examples/platform_events.rs (1 hunks)
  • packages/rs-sdk/src/error.rs (1 hunks)
  • packages/rs-sdk/src/platform.rs (1 hunks)
  • packages/rs-sdk/src/platform/events.rs (1 hunks)
  • packages/rs-sdk/src/sdk.rs (7 hunks)
  • packages/rs-sdk/tests/fetch/mod.rs (1 hunks)
  • packages/rs-sdk/tests/fetch/platform_events.rs (1 hunks)
  • packages/wasm-sdk/src/error.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • packages/rs-dapi/src/metrics.rs
🧰 Additional context used
🧠 Learnings (6)
📚 Learning: 2024-10-22T10:51:16.910Z
Learnt from: shumkov
PR: dashpay/platform#2259
File: packages/rs-dapi-client/src/transport.rs:51-51
Timestamp: 2024-10-22T10:51:16.910Z
Learning: In implementations of `TransportClient`, only `DapiClientError` is used as the `Error` type, and it implements `std::error::Error`.

Applied to files:

  • packages/rs-sdk/src/error.rs
📚 Learning: 2025-09-03T16:37:11.605Z
Learnt from: QuantumExplorer
PR: dashpay/platform#2756
File: packages/rs-drive-abci/src/execution/platform_events/core_based_updates/update_masternode_list/update_state_masternode_list/v0/mod.rs:11-11
Timestamp: 2025-09-03T16:37:11.605Z
Learning: In packages/rs-dpp/Cargo.toml, the abci feature already includes core_rpc_client, and core_rpc_client is defined as ["dep:dashcore-rpc"]. This means rs-drive-abci can access dashcore-rpc types through dpp when using the abci feature.

Applied to files:

  • packages/rs-drive-abci/Cargo.toml
📚 Learning: 2024-12-05T09:29:38.918Z
Learnt from: shumkov
PR: dashpay/platform#2375
File: packages/rs-drive-abci/Cargo.toml:61-63
Timestamp: 2024-12-05T09:29:38.918Z
Learning: In the `drive-abci` package, avoid adding unused dependencies like `hashbrown` to `Cargo.toml`. The team relies on CI to detect dependency version issues.

Applied to files:

  • packages/rs-drive-abci/Cargo.toml
📚 Learning: 2024-10-10T10:30:25.283Z
Learnt from: lklimek
PR: dashpay/platform#2232
File: packages/rs-sdk/src/mock/sdk.rs:129-130
Timestamp: 2024-10-10T10:30:25.283Z
Learning: In the codebase `packages/rs-sdk/src/mock/sdk.rs`, `tokio::sync::Mutex` is used instead of `std::sync::Mutex` because `std::sync::MutexGuard` is not `Send` and cannot be used in async contexts.

Applied to files:

  • packages/rs-sdk/src/sdk.rs
📚 Learning: 2024-10-29T10:42:00.521Z
Learnt from: lklimek
PR: dashpay/platform#2277
File: packages/rs-dapi-client/Cargo.toml:22-22
Timestamp: 2024-10-29T10:42:00.521Z
Learning: In `packages/rs-dapi-client/Cargo.toml`, `backon` will not work without the `tokio-sleep` feature in our setup, so it's unnecessary to declare `tokio-sleep` as a separate feature in the `[features]` section.

Applied to files:

  • packages/rs-sdk/Cargo.toml
📚 Learning: 2024-10-09T00:22:57.778Z
Learnt from: lklimek
PR: dashpay/platform#2139
File: packages/rs-sdk/Cargo.toml:0-0
Timestamp: 2024-10-09T00:22:57.778Z
Learning: `bincode` is used in the `mocks` feature of the `rs-sdk`.

Applied to files:

  • packages/rs-sdk/Cargo.toml
🔇 Additional comments (27)
packages/rs-dapi/src/services/streaming_service/bloom.rs (1)

14-17: LGTM: Clean refactor using let-chains.

This simplification reduces nesting and is more idiomatic Rust. The logic remains functionally equivalent while improving readability.

packages/rs-drive-abci/src/query/mod.rs (1)

18-18: LGTM!

The public re-export of PlatformFilterAdapter follows the existing pattern and cleanly exposes the adapter for external use in platform event subscriptions.

packages/rs-dash-event-bus/src/lib.rs (1)

1-1: Documentation update aligns with architectural direction.

The simplified description removing the bi-directional gRPC multiplexer reference aligns with the PR discussion about refactoring to unidirectional gRPC-Web streaming for better web client compatibility.

packages/rs-dapi/src/services/platform_service/wait_for_state_transition_result.rs (1)

206-206: Consistent use of let-chains.

The same clean refactoring pattern applied here with let Some maintains consistency throughout the file.

packages/rs-dapi/src/services/platform_service/subscribe_platform_events.rs (2)

33-48: Upstream subscription and channel setup looks solid.

The method correctly establishes the upstream subscription before creating the forwarding channel, and errors from the drive client are properly propagated to the caller.


82-83: Correct gRPC streaming response pattern.

The ReceiverStream wrapper properly bridges the mpsc receiver to tonic's streaming response requirements.

packages/rs-sdk/Cargo.toml (3)

77-77: Consider whether preliminary subscriptions feature should be default.

The subscriptions feature is added to the default feature set for a draft PR with "preliminary support." For an incomplete feature, consider requiring opt-in (default = [] without subscriptions) until the feature is production-ready, to avoid exposing unstable APIs by default.

Is the subscriptions feature stable enough to be enabled by default, or should users explicitly opt-in until DAPI integration (PR #2716) is complete?

Also applies to: 102-102


72-73: Note: AI summary inconsistency.

The AI summary claims mocks feature was removed from defaults, but mocks is still present in the default features list (line 73). This appears to be a pre-existing TODO item not addressed in this PR.


55-55: The signal feature is correctly used and necessary.

The examples in packages/rs-sdk/examples/platform_events.rs use tokio::signal::ctrl_c() on line 128, which requires the "signal" feature. The addition is justified.

packages/rs-drive-abci/tests/strategy_tests/main.rs (1)

201-247: LGTM! Well-structured event bus test.

The test effectively validates the in-process event bus subscription and delivery mechanism. The 1-second timeout is appropriate, and the test clearly demonstrates the subscribe-publish-receive flow.

packages/rs-sdk/src/error.rs (1)

41-43: LGTM! Clear error variant addition.

The new SubscriptionError variant follows the existing error pattern conventions and provides a clear error message for subscription-related failures.

packages/rs-sdk/src/platform.rs (1)

21-22: LGTM! Appropriate feature gating.

The events module is correctly exposed only when the subscriptions feature is enabled, following the pattern established elsewhere in the codebase.

packages/wasm-sdk/src/error.rs (1)

172-177: LGTM! Consistent error translation.

The SubscriptionError mapping to WasmSdkError is consistent with other error translations. Using DapiClientError as the kind is reasonable since subscriptions are DAPI-related functionality.

packages/rs-drive-abci/Cargo.toml (1)

65-82: LGTM! Dependencies align with event bus functionality.

The dependency additions and updates are appropriate for the platform event streaming infrastructure:

  • tokio-stream for async streaming constructs
  • rs-dash-event-bus for in-process event bus
  • sha2 for cryptographic hashing in event metadata
  • metrics-exporter-prometheus update is a minor version bump
packages/rs-sdk/tests/fetch/mod.rs (1)

27-28: LGTM! Test module properly feature-gated.

The platform_events test module is correctly included only when the subscriptions feature is enabled, consistent with the feature gating pattern used throughout the test suite.

packages/rs-dapi/src/main.rs (2)

133-163: LGTM! Cleaner conditional flow.

The merged conditional logic using if let Some(result) = outcome && let Err(e) = result is more concise and readable than the previous nested approach.


114-134: The server_future handling is correct as implemented.

The code follows the proper pattern when using tokio::pin!():

  • The binding doesn't need mut because tokio::pin! internally manages the pinning and mutability
  • Polling with &mut server_future in the select! macro is the standard, correct approach for pinned futures
  • This combination is not an inconsistency but the idiomatic Rust pattern for this scenario

The original concern appears to have been based on a misunderstanding of how tokio::pin!() works with mutability.

packages/rs-dash-event-bus/Cargo.toml (1)

6-6: LGTM! Documentation refinement.

The simplified description accurately reflects the package's purpose while being more concise.

packages/rs-dapi/src/services/platform_service/mod.rs (1)

171-184: Server‑streaming RPC wiring looks correct

Associated stream type and subscribe_platform_events delegate are aligned with gRPC‑Web constraints (server streaming). LGTM.

Please confirm subscribe_platform_events_impl returns ReceiverStream<Result<PlatformSubscriptionResponse, Status>> and sets appropriate compression/limits for large events.

packages/rs-drive-abci/src/abci/app/consensus.rs (1)

31-46: LGTM: EventBus integration is clean

Field injection and EventBusApplication impl expose the bus without extra cloning; fits finalize_block publishers.

Also applies to: 62-66

packages/rs-dash-event-bus/src/event_bus.rs (1)

277-282: Compile blocker: invalid if let condition chaining

if let Ok(mut subs) = bus.subs.try_write() && subs.remove(&id).is_some() is not valid Rust and won’t compile. Split into nested conditionals.

Apply:

-                    if let Ok(mut subs) = bus.subs.try_write()
-                        && subs.remove(&id).is_some()
-                    {
-                        metrics_unsubscribe_inc();
-                        metrics_active_gauge_set(subs.len());
-                    }
+                    if let Ok(mut subs) = bus.subs.try_write() {
+                        if subs.remove(&id).is_some() {
+                            metrics_unsubscribe_inc();
+                            metrics_active_gauge_set(subs.len());
+                            tracing::debug!("event_bus: removed subscription id={} (no runtime)", id);
+                        }
+                    }

Likely an incorrect or invalid review comment.

packages/rs-drive-abci/src/abci/app/full.rs (1)

31-33: EventBus wiring looks good; confirm Send/Sync and clone behavior.

If EventBus clone is cheap (Arc underneath) and Send/Sync, this is fine. If not, consider wrapping in Arc<EventBus<...>> to avoid accidental heavy clones across threads.

Also applies to: 42-43, 59-63

packages/rs-drive-abci/src/query/service.rs (1)

894-901: Confirm unsubscribe semantics on drop.

We rely on dropping subscription to remove it from the bus when the client disconnects. Please confirm EventBus::add_subscription returns a handle with Drop that unsubscribes; otherwise we need an explicit removal path.

packages/rs-drive-abci/src/abci/handler/finalize_block.rs (2)

107-111: Review comment is based on incorrect assumptions about the event bus implementation.

The notify_sync() method is already designed as non-blocking fire-and-forget. It spawns a background Tokio task that invokes the async notify() method, returning immediately without blocking the ABCI handler path. No changes are required—the current implementation already provides the non-blocking behavior the review suggests pursuing.

Likely an incorrect or invalid review comment.


165-176: SHA-256 of raw tx bytes is the canonical state transition hash used consistently throughout the codebase.

Verification confirms this is correct. The code at lines 165-176 uses Sha256::digest(tx) on raw transaction bytes, which matches the canonical approach used elsewhere:

  1. DAPI broadcast layer (rs-dapi/broadcast_state_transition.rs:49) computes the same hash identically
  2. Query/filtering service (rs-drive-abci/query/service.rs:299-301) matches filters directly against this hash
  3. Client filtering (SDK examples, JS DAPI tests) all use the same hash for StateTransitionResult queries
  4. Protocol definition confirms bytes tx_hash is the standard field for both events and filters

No alternative hash function or helper exists; the raw tx bytes → SHA-256 pattern is uniform across all layers (ABCI, DAPI, query, clients). No divergence between platform components or risk of filter mismatch.

packages/dapi-grpc/protos/platform/v0/platform.proto (2)

9-24: Versioned message structure is clean and consistent.

The nested V0 + oneof version pattern aligns well with the rest of the proto file. The client_subscription_id field enables multiplexing multiple subscriptions over a single RPC stream, which is sound. The design will scale well if V1/V2 variants are introduced later.


26-64: Event and filter messages are well-structured; verify alignment with SDK implementations.

The filter design uses oneof (all, block_committed, state_transition_result) for flexibility, and PlatformEventV0 pairs BlockMetadata consistently across event types. A few items to confirm:

  • Optional tx_hash in StateTransitionResultFilter (line 30): Allows filtering by specific state transitions; good for subscribers interested in particular transactions.
  • BlockMetadata nesting (lines 44–48): Shared across BlockCommitted and StateTransitionFinalized, reducing duplication.
  • Extensibility: The oneof pattern in PlatformFilterV0 and PlatformEventV0 supports future event types (e.g., IdentityCreated, DocumentDeleted) without breaking existing subscriptions.

Verify that:

  1. Downstream Rust (rs-drive-abci) and WASM (rs-sdk) implementations correctly adapt these message definitions.
  2. Field semantics (e.g., block_id_hash, time_ms precision) are documented and match consensus layer definitions.

Comment thread packages/rs-sdk/src/platform/events.rs Resolved
@QuantumExplorer QuantumExplorer added this to the v3.1.0 milestone Jan 13, 2026
@lklimek

lklimek commented Feb 9, 2026

Copy link
Copy Markdown
Contributor Author

@copilot merge v3.1-dev into this branch and solve conflicts. If unsure, explicitly notify about problematic changes.

Copilot AI commented Feb 9, 2026

Copy link
Copy Markdown
Contributor

@lklimek I've opened a new pull request, #3075, to work on those changes. Once the pull request is ready, I'll request review from you.

Copilot AI and others added 3 commits February 9, 2026 18:14
- Resolved conflicts in platform.proto by combining both sets of RPC methods
- Resolved conflicts in Rust files by keeping both changes where appropriate
- Resolved dashmate config migrations by combining timeout and new config migrations
- Regenerated gRPC clients for all languages
- Updated Cargo.lock
@lklimek
lklimek changed the base branch from v3.0-dev to v3.1-dev February 9, 2026 18:39
@lklimek lklimek changed the title feat(drive-abci): preliminary support for event subscriptions in Platform feat(platform): add real-time platform event subscriptions via gRPC streaming Feb 18, 2026
@thepastaclaw

thepastaclaw commented Mar 30, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Final review complete — no blockers (commit 3f1ae7a)

@QuantumExplorer QuantumExplorer removed this from the v4.0.0 milestone Jun 1, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

PR adds an in-process event bus, streaming gRPC subscription RPC, DAPI proxy, and SDK helper. Validated five blocking issues: drive-abci default features were expanded to include mocks/console/grovedbg (touching production builds), client-disconnect lifecycle leaks at both Drive and DAPI layers, no cap on subscribers (DoS surface), and the new network test will not compile against the actual proto. Several quality/interop suggestions are also kept (JS uint64 precision, event ordering, envoy idle race).

🔴 5 blocking | 🟡 4 suggestion(s) | 💬 1 nitpick(s)

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `packages/rs-drive-abci/Cargo.toml`:
- [BLOCKING] packages/rs-drive-abci/Cargo.toml:120: drive-abci default features now include mocks, console, and grovedbg
  This PR (commit 5ff52de0346 "chore(drive-abci): lint and machete") changed the crate's default features from `["bls-signatures"]` to `["bls-signatures","mocks","console","grovedbg"]`. Because the production Dockerfile builds `--package drive-abci` without `--no-default-features`, the resulting binary now pulls in `mockall`, `drive/fixtures-and-mocks`, `console-subscriber`, `tokio/tracing`, and GroveDB debug support. Feature unification means downstream consumers also have to opt out explicitly. None of these features are required for event subscriptions; the change appears accidental and is unrelated to the PR goal.

In `packages/rs-drive-abci/src/query/service.rs`:
- [BLOCKING] packages/rs-drive-abci/src/query/service.rs:1025-1086: Drive subscription leaks indefinitely when client disconnects with keepalive=0
  With `keepalive_secs = 0`, `keepalive_duration` is `None` and the worker loop awaits only `handle.recv().await`. If the client disconnects while no matching event ever arrives (e.g. a narrow `StateTransitionResultFilter.tx_hash` for a tx that never lands), the worker never attempts a `downstream_tx.send`, so it never observes that the receiver was dropped. The `SubscriptionHandle` and the entry in `EventBus`'s `BTreeMap` stay alive forever, the spawned task remains in `self.workers`, and per-block `notify` work keeps iterating these zombie subscribers. Add a `tokio::select!` between `handle.recv()` and `downstream_tx.closed()` so downstream cancellation is observed promptly, or enforce a non-zero internal upper bound even when keepalive is disabled.
- [BLOCKING] packages/rs-drive-abci/src/query/service.rs:952-1102: subscribe_platform_events has no per-peer or global subscriber cap
  Every call to `subscribe_platform_events` allocates a 256-capacity bus channel, a 128-capacity downstream mpsc, and pushes a long-lived task into `self.workers`, with no per-peer accounting, no global cap, no rate limit, and no authentication on the RPC. The endpoint is reachable publicly via the DAPI proxy. A tiny request body (filter + integer) is enough for an attacker to open arbitrarily many streams against every masternode, exhausting memory and task slots and amplifying per-block `notify` work (the bus only evicts a subscriber when its channel is full, so an attacker that simply stops reading still ties up the full buffer). The DAPI proxy currently has the same problem (no cap on `ActiveSessionGuard`). Add a configurable hard cap on simultaneous subscribers on Drive (return `ResourceExhausted` when exceeded) and a per-peer/global cap at the DAPI proxy.

In `packages/rs-dapi/src/services/platform_service/subscribe_platform_events.rs`:
- [BLOCKING] packages/rs-dapi/src/services/platform_service/subscribe_platform_events.rs:53-79: DAPI proxy keeps upstream stream alive after downstream client disconnects
  The forwarder is `while let Some(msg) = uplink_resp_rx.next().await { ... }`. If the public client disconnects while the upstream stream is idle, `downlink_resp_rx` is dropped but this task remains blocked on `uplink_resp_rx.next()`, holding the upstream Drive subscription, its mpsc buffers, and the `ActiveSessionGuard`. Combined with the Drive-side leak above, this allows one abandoned request to pin resources on both processes indefinitely. Use `tokio::select!` on `uplink_resp_rx.next()` and `downlink_resp_tx.closed()` so the upstream stream is dropped as soon as the downstream client goes away.

In `packages/rs-sdk/tests/fetch/platform_events.rs`:
- [BLOCKING] packages/rs-sdk/tests/fetch/platform_events.rs:21-44: Subscription network test does not match the proto and will not compile
  The test constructs `Kind::All(true)`, but in the proto (`platform.proto:43-49`) the `all` variant wraps the empty `AllEvents` message, not a bool — the generated code expects `Kind::All(AllEvents {})`. The test also reads `v0.client_subscription_id`, but the response field is `subscription_id: u64` (see `platform.proto:23` and `service.rs:1010`). Under the advertised `network-testing,subscriptions` feature combination this file fails to compile, so the new handshake contract has no end-to-end coverage.

In `packages/dapi-grpc/protos/platform/v0/platform.proto`:
- [SUGGESTION] packages/dapi-grpc/protos/platform/v0/platform.proto:23: subscription_id uint64 missing jstype = JS_STRING — JS clients lose precision
  The server generates this value with `rand::random::<u64>()` (`service.rs:991`), uniformly across the full u64 range. Without `jstype = JS_STRING`, the protobuf-JS code generator emits the field as a JavaScript `number`, but values above `Number.MAX_SAFE_INTEGER` (2^53 − 1) silently round to the nearest double. The two other `uint64` fields in this file (`BlockMetadata.height`, `BlockMetadata.time_ms`) already use this annotation; the omission here means a JS client's reported subscription id will not match the server's, breaking any future server-side correlation or per-stream demultiplexing. Fixing now is cheap because only v0 stubs exist.

In `packages/rs-drive-abci/src/abci/handler/finalize_block.rs`:
- [SUGGESTION] packages/rs-drive-abci/src/abci/handler/finalize_block.rs:112-184: Per-event notify_sync spawn loses in-block event ordering
  `publish_block_committed_event` and `publish_state_transition_result_events` each call `EventBus::notify_sync` once per event, and `notify_sync` spawns an independent task per call (`event_bus.rs:120-129`). Each spawned task takes the `subs` read lock and `try_send`s into subscribers' mpsc channels in arbitrary order. Subscribers can therefore observe `StateTransitionFinalized` for tx N+1 before tx N of the same block, or before the `BlockCommitted` they belong to — exactly the wrong invariant for the stated transaction-confirmation UI use case. The `BlockMetadata` payload also has no per-tx index, so clients cannot resort. Either collect the block's events into a `Vec<PlatformEventV0>` and publish via one spawned task (keeping per-block ordering atomic), or add an explicit in-block index to the event payload so consumers can reorder.

In `packages/dashmate/templates/platform/gateway/envoy.yaml.dot`:
- [SUGGESTION] packages/dashmate/templates/platform/gateway/envoy.yaml.dot:3: Envoy stream idle timeout matches max keepalive interval — keepalives may not arrive in time
  `streamIdleTimeout = '300s'` is exactly the upper bound that `subscribe_platform_events` accepts for `keepalive_secs` (25..=300). The first keepalive is emitted only after the configured silence elapses, so with `keepalive_secs = 300` the keepalive event has zero margin against Envoy's idle timeout and routinely loses the race once you add scheduling and network latency. The stated goal of the keepalive is to prevent proxy idle-timeout disconnects; the timeout must therefore exceed the maximum allowable keepalive interval.

In `packages/rs-sdk/src/platform/events.rs`:
- [SUGGESTION] packages/rs-sdk/src/platform/events.rs:17-62: SDK subscription events are not proof-verified — trusts a single DAPI proxy
  Unlike other SDK fetches that go through `FromProof` and verify a Merkle proof against the platform root hash, `subscribe_platform_events` exposes the raw gRPC stream from `get_live_address` with no signature, no proof, and no cross-check. A malicious or compromised DAPI proxy can therefore fabricate `BlockCommitted` and `StateTransitionFinalized` events with arbitrary `tx_hash`/`block_id_hash` payloads. An SDK consumer driving a transaction-confirmation UI from this stream (a use case the PR description explicitly calls out) would treat unconfirmed transactions as confirmed. While the events are labeled preliminary, the helper's docstring should prominently flag this trust assumption and either require an explicit opt-in flag or cross-check key event fields against a proof-verified `get_status`/block header before raising them to application code.


[features]
default = ["bls-signatures"]
default = ["bls-signatures","mocks","console","grovedbg"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Blocking: drive-abci default features now include mocks, console, and grovedbg

This PR (commit 5ff52de "chore(drive-abci): lint and machete") changed the crate's default features from ["bls-signatures"] to ["bls-signatures","mocks","console","grovedbg"]. Because the production Dockerfile builds --package drive-abci without --no-default-features, the resulting binary now pulls in mockall, drive/fixtures-and-mocks, console-subscriber, tokio/tracing, and GroveDB debug support. Feature unification means downstream consumers also have to opt out explicitly. None of these features are required for event subscriptions; the change appears accidental and is unrelated to the PR goal.

Suggested change
default = ["bls-signatures","mocks","console","grovedbg"]
default = ["bls-signatures"]

source: ['codex']

Comment on lines +1025 to +1086
let worker = tokio::task::spawn(async move {
let handle = subscription;

loop {
// next_item is Some(Ok(event)) when an event is received
// next_item is Some(Err(e)) when keepalive timeout elapses
// next_item is None when the stream is closed
let next_item = if let Some(duration) = keepalive_duration {
match tokio::time::timeout(duration, handle.recv()).await {
Ok(Some(event)) => Some(Ok(event)),
Ok(None) => None,
Err(e) => Some(Err(e)),
}
} else {
handle.recv().await.map(Ok)
};

match next_item {
Some(Ok(event)) => {
let response = PlatformSubscriptionResponse {
version: Some(ResponseVersion::V0(PlatformSubscriptionResponseV0 {
subscription_id,
event: Some(event),
})),
};

if downstream_tx.send(Ok(response)).await.is_err() {
tracing::debug!(
subscription_id = %subscription_id,
"subscribe_platform_events: client stream closed"
);
break;
}
}
Some(Err(_)) => {
// timeout elapsed, emit keepalive event
let keepalive_event = PlatformEvent {
event: Some(
dapi_grpc::platform::v0::platform_event_v0::Event::Keepalive(
Keepalive {},
),
),
};

let response = PlatformSubscriptionResponse {
version: Some(ResponseVersion::V0(PlatformSubscriptionResponseV0 {
subscription_id,
event: Some(keepalive_event),
})),
};

if downstream_tx.send(Ok(response)).await.is_err() {
tracing::debug!(
subscription_id = %subscription_id,
"subscribe_platform_events: client stream closed"
);
break;
}
}
None => break,
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Blocking: Drive subscription leaks indefinitely when client disconnects with keepalive=0

With keepalive_secs = 0, keepalive_duration is None and the worker loop awaits only handle.recv().await. If the client disconnects while no matching event ever arrives (e.g. a narrow StateTransitionResultFilter.tx_hash for a tx that never lands), the worker never attempts a downstream_tx.send, so it never observes that the receiver was dropped. The SubscriptionHandle and the entry in EventBus's BTreeMap stay alive forever, the spawned task remains in self.workers, and per-block notify work keeps iterating these zombie subscribers. Add a tokio::select! between handle.recv() and downstream_tx.closed() so downstream cancellation is observed promptly, or enforce a non-zero internal upper bound even when keepalive is disabled.

source: ['claude', 'codex']

Comment on lines +53 to +79
self.workers.spawn(async move {
let _session_guard = session_handle;
while let Some(msg) = uplink_resp_rx.next().await {
match msg {
Ok(response) => {
metrics::platform_events_forwarded_event();
if downlink_resp_tx.send(Ok(response)).await.is_err() {
tracing::debug!(
"Platform events downlink response channel closed; stopping forward"
);
break;
}
}
Err(status) => {
metrics::platform_events_forwarded_error();
if downlink_resp_tx.send(Err(status)).await.is_err() {
tracing::debug!(
"Platform events downlink response channel closed while forwarding error"
);
break;
}
}
}
}
tracing::debug!("Platform events uplink response stream closed");
Err::<(), DapiError>(DapiError::ConnectionClosed)
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Blocking: DAPI proxy keeps upstream stream alive after downstream client disconnects

The forwarder is while let Some(msg) = uplink_resp_rx.next().await { ... }. If the public client disconnects while the upstream stream is idle, downlink_resp_rx is dropped but this task remains blocked on uplink_resp_rx.next(), holding the upstream Drive subscription, its mpsc buffers, and the ActiveSessionGuard. Combined with the Drive-side leak above, this allows one abandoned request to pin resources on both processes indefinitely. Use tokio::select! on uplink_resp_rx.next() and downlink_resp_tx.closed() so the upstream stream is dropped as soon as the downstream client goes away.

source: ['codex']

Comment on lines +952 to +1102
async fn subscribe_platform_events(
&self,
request: Request<PlatformSubscriptionRequest>,
) -> Result<Response<Self::subscribePlatformEventsStream>, Status> {
use dapi_grpc::platform::v0::platform_subscription_request::Version as RequestVersion;
use dapi_grpc::platform::v0::platform_subscription_response::{
PlatformSubscriptionResponseV0, Version as ResponseVersion,
};

let request = request.into_inner();
let req_v0 = match request.version {
Some(RequestVersion::V0(v0)) => v0,
_ => {
tracing::warn!("subscribe_platform_events: unsupported request version");
return Err(Status::invalid_argument("unsupported request version"));
}
};

let keepalive = req_v0.keepalive_secs;
let filter = req_v0.filter.unwrap_or_default();
if filter.kind.is_none() {
tracing::warn!("subscribe_platform_events: filter kind is not specified");
return Err(Status::invalid_argument("filter kind is not specified"));
}

let keepalive_duration = if keepalive == 0 {
None
} else if !(25..=300).contains(&keepalive) {
tracing::warn!(
interval = keepalive,
"subscribe_platform_events: keepalive interval out of range"
);
return Err(Status::invalid_argument(
"keepalive interval must be between 25 and 300 seconds",
));
} else {
Some(Duration::from_secs(keepalive as u64))
};

let subscription_id = rand::random::<u64>();
tracing::trace!(
subscription_id = %subscription_id,
"subscribe_platform_events: generated subscription id"
);

let subscription = self
.event_bus
.add_subscription(PlatformFilterAdapter::new(filter))
.await;

let (downstream_tx, rx) = mpsc::channel::<Result<PlatformSubscriptionResponse, Status>>(
PLATFORM_EVENTS_STREAM_BUFFER,
);

let handshake_tx = downstream_tx.clone();
{
let handshake = PlatformSubscriptionResponse {
version: Some(ResponseVersion::V0(PlatformSubscriptionResponseV0 {
subscription_id,
event: None,
})),
};

if let Err(err) = handshake_tx.send(Ok(handshake)).await {
tracing::debug!(
subscription_id = %subscription_id,
error = %err,
"subscribe_platform_events: client disconnected before handshake"
);
return Err(Status::cancelled("client disconnected before handshake"));
}
}

let worker = tokio::task::spawn(async move {
let handle = subscription;

loop {
// next_item is Some(Ok(event)) when an event is received
// next_item is Some(Err(e)) when keepalive timeout elapses
// next_item is None when the stream is closed
let next_item = if let Some(duration) = keepalive_duration {
match tokio::time::timeout(duration, handle.recv()).await {
Ok(Some(event)) => Some(Ok(event)),
Ok(None) => None,
Err(e) => Some(Err(e)),
}
} else {
handle.recv().await.map(Ok)
};

match next_item {
Some(Ok(event)) => {
let response = PlatformSubscriptionResponse {
version: Some(ResponseVersion::V0(PlatformSubscriptionResponseV0 {
subscription_id,
event: Some(event),
})),
};

if downstream_tx.send(Ok(response)).await.is_err() {
tracing::debug!(
subscription_id = %subscription_id,
"subscribe_platform_events: client stream closed"
);
break;
}
}
Some(Err(_)) => {
// timeout elapsed, emit keepalive event
let keepalive_event = PlatformEvent {
event: Some(
dapi_grpc::platform::v0::platform_event_v0::Event::Keepalive(
Keepalive {},
),
),
};

let response = PlatformSubscriptionResponse {
version: Some(ResponseVersion::V0(PlatformSubscriptionResponseV0 {
subscription_id,
event: Some(keepalive_event),
})),
};

if downstream_tx.send(Ok(response)).await.is_err() {
tracing::debug!(
subscription_id = %subscription_id,
"subscribe_platform_events: client stream closed"
);
break;
}
}
None => break,
}
}

tracing::debug!(
subscription_id = %subscription_id,
"subscribe_platform_events: event stream completed"
);
});

{
let mut workers = self.workers.lock().unwrap();
workers.push(worker);
// Clean up finished workers to prevent memory leak
workers.retain(|h| !h.is_finished());
}

Ok(Response::new(ReceiverStream::new(rx)))
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Blocking: subscribe_platform_events has no per-peer or global subscriber cap

Every call to subscribe_platform_events allocates a 256-capacity bus channel, a 128-capacity downstream mpsc, and pushes a long-lived task into self.workers, with no per-peer accounting, no global cap, no rate limit, and no authentication on the RPC. The endpoint is reachable publicly via the DAPI proxy. A tiny request body (filter + integer) is enough for an attacker to open arbitrarily many streams against every masternode, exhausting memory and task slots and amplifying per-block notify work (the bus only evicts a subscriber when its channel is full, so an attacker that simply stops reading still ties up the full buffer). The DAPI proxy currently has the same problem (no cap on ActiveSessionGuard). Add a configurable hard cap on simultaneous subscribers on Drive (return ResourceExhausted when exceeded) and a per-peer/global cap at the DAPI proxy.

source: ['claude', 'codex']

Comment on lines +21 to +44
let filter = PlatformFilterV0 {
kind: Some(dapi_grpc::platform::v0::platform_filter_v0::Kind::All(true)),
};
let mut subscription = sdk
.subscribe_platform_events(filter)
.await
.expect("subscribe should succeed");

let handshake = timeout(Duration::from_secs(1), subscription.message())
.await
.expect("handshake should arrive promptly")
.expect("handshake message")
.expect("handshake payload");

if let Some(ResponseVersion::V0(ref v0)) = handshake.version {
assert!(
!v0.client_subscription_id.is_empty(),
"handshake must include subscription id"
);

tracing::debug!(
?handshake,
"Received handshake with subscription id: {}",
v0.client_subscription_id

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Blocking: Subscription network test does not match the proto and will not compile

The test constructs Kind::All(true), but in the proto (platform.proto:43-49) the all variant wraps the empty AllEvents message, not a bool — the generated code expects Kind::All(AllEvents {}). The test also reads v0.client_subscription_id, but the response field is subscription_id: u64 (see platform.proto:23 and service.rs:1010). Under the advertised network-testing,subscriptions feature combination this file fails to compile, so the new handshake contract has no end-to-end coverage.

source: ['codex']

message PlatformSubscriptionResponse {
message PlatformSubscriptionResponseV0 {
// Server-generated ID for this subscription; not guaranteed to be unique
uint64 subscription_id = 1;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: subscription_id uint64 missing jstype = JS_STRING — JS clients lose precision

The server generates this value with rand::random::<u64>() (service.rs:991), uniformly across the full u64 range. Without jstype = JS_STRING, the protobuf-JS code generator emits the field as a JavaScript number, but values above Number.MAX_SAFE_INTEGER (2^53 − 1) silently round to the nearest double. The two other uint64 fields in this file (BlockMetadata.height, BlockMetadata.time_ms) already use this annotation; the omission here means a JS client's reported subscription id will not match the server's, breaking any future server-side correlation or per-stream demultiplexing. Fixing now is cheap because only v0 stubs exist.

Suggested change
uint64 subscription_id = 1;
// Server-generated ID for this subscription; not guaranteed to be unique
uint64 subscription_id = 1 [ jstype = JS_STRING ];

source: ['claude', 'codex']

Comment on lines +112 to +184
let bus = app.event_bus().clone();

publish_block_committed_event(&bus, &request_finalize_block)?;
publish_state_transition_result_events(&bus, &request_finalize_block)?;

Ok(proto::ResponseFinalizeBlock { retain_height: 0 })
}

fn publish_block_committed_event(
event_bus: &dash_event_bus::event_bus::EventBus<PlatformEventV0, PlatformFilterAdapter>,
request_finalize_block: &FinalizeBlockCleanedRequest,
) -> Result<(), Error> {
// Publish BlockCommitted platform event to the global event bus (best-effort)
let header_time = request_finalize_block.block.header.time;
let seconds = header_time.seconds as i128;
let nanos = header_time.nanos as i128;
let time_ms = (seconds * 1000) + (nanos / 1_000_000);

let meta = platform_event_v0::BlockMetadata {
height: request_finalize_block.height,
time_ms: time_ms as u64,
block_id_hash: request_finalize_block.block_id.hash.to_vec(),
};

// Number of txs in this block
let tx_count = request_finalize_block.block.data.txs.len() as u32;

let block_committed = platform_event_v0::BlockCommitted {
meta: Some(meta),
tx_count,
};

let event = PlatformEventV0 {
event: Some(platform_event_v0::Event::BlockCommitted(block_committed)),
};

event_bus.notify_sync(event);

Ok(())
}

fn publish_state_transition_result_events(
event_bus: &dash_event_bus::event_bus::EventBus<PlatformEventV0, PlatformFilterAdapter>,
request_finalize_block: &FinalizeBlockCleanedRequest,
) -> Result<(), Error> {
// Prepare BlockMetadata once
let header_time = request_finalize_block.block.header.time;
let seconds = header_time.seconds as i128;
let nanos = header_time.nanos as i128;
let time_ms = (seconds * 1000) + (nanos / 1_000_000);

let meta = platform_event_v0::BlockMetadata {
height: request_finalize_block.height,
time_ms: time_ms as u64,
block_id_hash: request_finalize_block.block_id.hash.to_vec(),
};

// For each tx in the block, compute hash and emit a StateTransitionResult
for tx in &request_finalize_block.block.data.txs {
let tx_hash = Sha256::digest(tx);
let event = PlatformEventV0 {
event: Some(platform_event_v0::Event::StateTransitionFinalized(
platform_event_v0::StateTransitionFinalized {
meta: Some(meta.clone()),
tx_hash: tx_hash.to_vec(),
},
)),
};
event_bus.notify_sync(event);
}

Ok(())
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: Per-event notify_sync spawn loses in-block event ordering

publish_block_committed_event and publish_state_transition_result_events each call EventBus::notify_sync once per event, and notify_sync spawns an independent task per call (event_bus.rs:120-129). Each spawned task takes the subs read lock and try_sends into subscribers' mpsc channels in arbitrary order. Subscribers can therefore observe StateTransitionFinalized for tx N+1 before tx N of the same block, or before the BlockCommitted they belong to — exactly the wrong invariant for the stated transaction-confirmation UI use case. The BlockMetadata payload also has no per-tx index, so clients cannot resort. Either collect the block's events into a Vec<PlatformEventV0> and publish via one spawned task (keeping per-block ordering atomic), or add an explicit in-block index to the event payload so consumers can reorder.

source: ['claude']

@@ -1,3 +1,9 @@
{{ const formatTimeout = (value) => `${Math.max(1, Math.ceil((Number(value ?? 0) + 5000) / 1000))}s`; }}
{{ const rsDapiTimeouts = it.platform?.dapi?.rsDapi?.timeouts ?? {}; }}
{{ const streamIdleTimeout = '300s'; }}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: Envoy stream idle timeout matches max keepalive interval — keepalives may not arrive in time

streamIdleTimeout = '300s' is exactly the upper bound that subscribe_platform_events accepts for keepalive_secs (25..=300). The first keepalive is emitted only after the configured silence elapses, so with keepalive_secs = 300 the keepalive event has zero margin against Envoy's idle timeout and routinely loses the race once you add scheduling and network latency. The stated goal of the keepalive is to prevent proxy idle-timeout disconnects; the timeout must therefore exceed the maximum allowable keepalive interval.

Suggested change
{{ const streamIdleTimeout = '300s'; }}
{{ const streamIdleTimeout = '310s'; }}

source: ['codex']

Comment on lines +77 to +78
tracing::debug!("Platform events uplink response stream closed");
Err::<(), DapiError>(DapiError::ConnectionClosed)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💬 Nitpick: Forwarder reports clean stream close as ConnectionClosed error

After the while let Some(msg) = uplink_resp_rx.next().await loop exits normally — either upstream EOF or downstream disconnect via the inner break — the task returns Err::<(), DapiError>(DapiError::ConnectionClosed). Normal stream termination is not an error: every successful unsubscribe will surface in self.workers' error metrics/logs, masking real upstream failures. Return Ok(()) for the clean-close paths and reserve Err for actual upstream forwarding failures.

Suggested change
tracing::debug!("Platform events uplink response stream closed");
Err::<(), DapiError>(DapiError::ConnectionClosed)
tracing::debug!("Platform events uplink response stream closed");
Ok::<(), DapiError>(())

source: ['claude', 'codex']

Comment on lines +17 to +62
pub async fn subscribe_platform_events(
&self,
filter: PlatformFilterV0,
) -> Result<Streaming<PlatformSubscriptionResponse>, crate::Error> {
let address = self
.address_list()
.get_live_address()
.ok_or_else(|| crate::Error::SubscriptionError("no live DAPI address".to_string()))?;
let uri: Uri = address.uri().clone();

tracing::debug!(
address = ?uri,
"creating gRPC client for platform events subscription"
);
let settings = self
.dapi_client_settings
.override_by(RequestSettings {
connect_timeout: Some(Duration::from_secs(5)),
timeout: Some(Duration::from_secs(3600)),
..Default::default()
})
.finalize();
let channel = create_channel(uri, Some(&settings))
.map_err(|e| crate::Error::SubscriptionError(format!("channel: {e}")))?;
let mut client: PlatformGrpcClient = PlatformClient::new(channel);

// Keepalive should be less than the timeout to avoid unintentional disconnects.
let keepalive_secs = (settings.timeout.saturating_sub(Duration::from_secs(5)))
.as_secs()
.clamp(25, 300) as u32;
let request = PlatformSubscriptionRequest {
version: Some(RequestVersion::V0(PlatformSubscriptionRequestV0 {
filter: Some(filter),
keepalive_secs,
})),
};

let response = client
.subscribe_platform_events(Request::new(request))
.await
.map_err(|e| crate::Error::SubscriptionError(format!("subscribe: {}", e)))?
.into_inner();

Ok(response)
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: SDK subscription events are not proof-verified — trusts a single DAPI proxy

Unlike other SDK fetches that go through FromProof and verify a Merkle proof against the platform root hash, subscribe_platform_events exposes the raw gRPC stream from get_live_address with no signature, no proof, and no cross-check. A malicious or compromised DAPI proxy can therefore fabricate BlockCommitted and StateTransitionFinalized events with arbitrary tx_hash/block_id_hash payloads. An SDK consumer driving a transaction-confirmation UI from this stream (a use case the PR description explicitly calls out) would treat unconfirmed transactions as confirmed. While the events are labeled preliminary, the helper's docstring should prominently flag this trust assumption and either require an explicit opt-in flag or cross-check key event fields against a proof-verified get_status/block header before raising them to application code.

source: ['claude']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants