Repository navigation
Conversation
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Key areas requiring attention:
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
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. Comment |
✅ gRPC Query Coverage Report |
|
@coderabbitai review all |
|
@lklimek: I'll perform a comprehensive review of all the changes in this PR. ✅ Actions performedFull review triggered. |
|
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! |
Thanks for that info! I'll refactor to unidirectional grpc-web. |
|
✅ 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:
|
|
@coderabbitai review all |
|
@lklimek: I'll perform a comprehensive review of all the changes in this PR. ✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
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
ActiveSessionGuardwithArcandDropensures 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-flakyRelying 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 EventBusApplicationThe 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 capacityDefault 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 lifecycleExplicitly 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 workerstry_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:counterAlso 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
⛔ Files ignored due to path filters (1)
Cargo.lockis 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
PlatformFilterAdapterfollows 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 Somemaintains 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
ReceiverStreamwrapper 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
subscriptionsfeature 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
mocksis 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: Thesignalfeature is correctly used and necessary.The examples in
packages/rs-sdk/examples/platform_events.rsusetokio::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
SubscriptionErrorvariant 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
eventsmodule is correctly exposed only when thesubscriptionsfeature is enabled, following the pattern established elsewhere in the codebase.packages/wasm-sdk/src/error.rs (1)
172-177: LGTM! Consistent error translation.The
SubscriptionErrormapping toWasmSdkErroris consistent with other error translations. UsingDapiClientErroras 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-streamfor async streaming constructsrs-dash-event-busfor in-process event bussha2for cryptographic hashing in event metadatametrics-exporter-prometheusupdate is a minor version bumppackages/rs-sdk/tests/fetch/mod.rs (1)
27-28: LGTM! Test module properly feature-gated.The
platform_eventstest module is correctly included only when thesubscriptionsfeature 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) = resultis more concise and readable than the previous nested approach.
114-134: Theserver_futurehandling is correct as implemented.The code follows the proper pattern when using
tokio::pin!():
- The binding doesn't need
mutbecausetokio::pin!internally manages the pinning and mutability- Polling with
&mut server_futurein theselect!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 correctAssociated 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 cleanField 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: invalidif letcondition 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
EventBusclone is cheap (Arc underneath) and Send/Sync, this is fine. If not, consider wrapping inArc<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
subscriptionto remove it from the bus when the client disconnects. Please confirmEventBus::add_subscriptionreturns a handle withDropthat 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 asyncnotify()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:
- DAPI broadcast layer (
rs-dapi/broadcast_state_transition.rs:49) computes the same hash identically- Query/filtering service (
rs-drive-abci/query/service.rs:299-301) matches filters directly against this hash- Client filtering (SDK examples, JS DAPI tests) all use the same hash for StateTransitionResult queries
- Protocol definition confirms
bytes tx_hashis the standard field for both events and filtersNo 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_idfield 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:
- Downstream Rust (rs-drive-abci) and WASM (rs-sdk) implementations correctly adapt these message definitions.
- Field semantics (e.g., block_id_hash, time_ms precision) are documented and match consensus layer definitions.
|
@copilot merge v3.1-dev into this branch and solve conflicts. If unsure, explicitly notify about problematic changes. |
- 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
Co-authored-by: lklimek <[email protected]>
|
✅ Final review complete — no blockers (commit 3f1ae7a) |
thepastaclaw
left a comment
There was a problem hiding this comment.
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"] |
There was a problem hiding this comment.
🔴 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.
| default = ["bls-signatures","mocks","console","grovedbg"] | |
| default = ["bls-signatures"] |
source: ['codex']
| 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, | ||
| } | ||
| } |
There was a problem hiding this comment.
🔴 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']
| 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) | ||
| }); |
There was a problem hiding this comment.
🔴 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']
| 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))) | ||
| } |
There was a problem hiding this comment.
🔴 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']
| 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 |
There was a problem hiding this comment.
🔴 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; |
There was a problem hiding this comment.
🟡 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.
| 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']
| 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(()) | ||
| } |
There was a problem hiding this comment.
🟡 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'; }} | |||
There was a problem hiding this comment.
🟡 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.
| {{ const streamIdleTimeout = '300s'; }} | |
| {{ const streamIdleTimeout = '310s'; }} |
source: ['codex']
| tracing::debug!("Platform events uplink response stream closed"); | ||
| Err::<(), DapiError>(DapiError::ConnectionClosed) |
There was a problem hiding this comment.
💬 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.
| 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']
| 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) | ||
| } | ||
| } |
There was a problem hiding this comment.
🟡 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']
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
subscribePlatformEventsgRPC stream and receive events matching a chosen filter (AllEvents,BlockCommitted, orStateTransitionResultoptionally scoped bytx_hash).subscription_id.Sdk::subscribe_platform_events()returning atonic::Streamingfor 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)PlatformSubscriptionRequest/PlatformSubscriptionResponse,PlatformFilterV0(withAllEvents,BlockCommitted,StateTransitionResultFiltervariants), andPlatformEventV0(withBlockCommitted,StateTransitionFinalized,Keepaliveevent types).subscribePlatformEvents(PlatformSubscriptionRequest) returns (stream PlatformSubscriptionResponse).2. In-process event bus (
rs-dash-event-bus)EventBus<E, F>with pluggableFilter<E>trait, backed by per-subscribertokio::mpscchannels (capacity 256).SubscriptionHandleauto-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 ABCIfinalize_block).3. Drive ABCI event emission (
rs-drive-abci)finalize_blockhandler publishesBlockCommitted(with block metadata + tx count) and per-txStateTransitionFinalized(with SHA-256 tx hash) events to the shared event bus after each committed block.EventBusApplicationtrait added to the ABCI app hierarchy; event bus instance threaded from server startup through consensus and query services.QueryServiceimplementssubscribe_platform_eventsdirectly 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.PlatformFilterAdapterbridges the protobufPlatformFilterV0to the event busFiltertrait, always passing keepalives through.4. DAPI proxy layer (
rs-dapi)subscribe_platform_events_implinPlatformServiceImplopens an upstream gRPC stream to Drive and forwards responses downstream withActiveSessionGuardRAII tracking.platform_events_active_sessions,platform_events_upstream_stream_started,platform_events_forwarded_event/error.SUBSCRIBE_PLATFORM_EVENTS_TIMEOUTandCORE_STREAMS_TIMEOUTenv vars.5. Dashmate operator tooling (
dashmate)platform.dapi.envoy.rateLimiter.timeouts:subscribePlatformEvents(default 300s),coreStreams(default 600s),waitForStateTransitionResult(default 80s).max_stream_duration/grpc_timeout_header_maxand a 5 s streaming grace period.2.2.0-dev.1backfills new timeout keys from older configs.dashmate restart --platformnow 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.Error::SubscriptionErrorvariant mapped to WASMWasmError.platform_eventsdemonstrates subscribing and printing events.platform_events.rsvalidates 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.rsstrategy 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
platform.dapi.envoy.rateLimiter.timeouts).Test Plan
rs-dash-event-busunit tests pass (cargo test -p rs-dash-event-bus)rs-drive-abcievent bus strategy tests pass (cargo test -p drive-abci --test strategy_tests event_bus)platform_eventsexample against a local devnet to confirm handshake and event deliveryChecklist
For repository code-owners and collaborators only
🤖 Generated with Claude Code