Skip to main content

fabric_shim/
iterators.rs

1use std::collections::VecDeque;
2use std::sync::Arc;
3
4use fabric_shim_protos::peer as pb;
5use fabric_shim_protos::peer::chaincode_message::Type as MsgType;
6use fabric_shim_protos::queryresult;
7use prost::Message;
8
9use crate::stub::StubCore;
10use crate::Result;
11
12/// Shared paging machinery for state/history iterators: drains the current
13/// `QueryResponse` batch, then fetches more with QUERY_STATE_NEXT.
14struct QueryIter {
15    core: Arc<StubCore>,
16    id: String,
17    batch: VecDeque<pb::QueryResultBytes>,
18    has_more: bool,
19    closed: bool,
20}
21
22impl QueryIter {
23    fn new(core: Arc<StubCore>, resp: pb::QueryResponse) -> Self {
24        Self {
25            core,
26            id: resp.id,
27            batch: resp.results.into(),
28            has_more: resp.has_more,
29            closed: false,
30        }
31    }
32
33    async fn next_raw(&mut self) -> Result<Option<Vec<u8>>> {
34        loop {
35            if let Some(qrb) = self.batch.pop_front() {
36                return Ok(Some(qrb.result_bytes.to_vec()));
37            }
38            if !self.has_more || self.closed {
39                return Ok(None);
40            }
41            let payload = pb::QueryStateNext {
42                id: self.id.clone(),
43            }
44            .encode_to_vec();
45            let reply = self.core.request(MsgType::QueryStateNext, payload).await?;
46            let resp = pb::QueryResponse::decode(reply.payload.as_ref())?;
47            self.batch = resp.results.into();
48            self.has_more = resp.has_more;
49        }
50    }
51
52    async fn close(&mut self) -> Result<()> {
53        if self.closed {
54            return Ok(());
55        }
56        self.closed = true;
57        let payload = pb::QueryStateClose {
58            id: self.id.clone(),
59        }
60        .encode_to_vec();
61        self.core.request(MsgType::QueryStateClose, payload).await?;
62        Ok(())
63    }
64}
65
66/// Iterator over `queryresult::Kv` records from range, partial-composite-key,
67/// and rich queries.
68///
69/// Call [`close`](Self::close) when done; the peer also cleans up open
70/// iterators when the transaction completes.
71pub struct StateQueryIterator {
72    inner: QueryIter,
73}
74
75impl StateQueryIterator {
76    pub(crate) fn new(core: Arc<StubCore>, resp: pb::QueryResponse) -> Self {
77        Self {
78            inner: QueryIter::new(core, resp),
79        }
80    }
81
82    pub async fn next(&mut self) -> Result<Option<queryresult::Kv>> {
83        match self.inner.next_raw().await? {
84            Some(bytes) => Ok(Some(queryresult::Kv::decode(bytes.as_slice())?)),
85            None => Ok(None),
86        }
87    }
88
89    /// Drain the remaining records into a vector (and close the iterator).
90    pub async fn collect_remaining(mut self) -> Result<Vec<queryresult::Kv>> {
91        let mut out = Vec::new();
92        while let Some(kv) = self.next().await? {
93            out.push(kv);
94        }
95        self.close().await?;
96        Ok(out)
97    }
98
99    pub async fn close(&mut self) -> Result<()> {
100        self.inner.close().await
101    }
102}
103
104/// Iterator over `queryresult::KeyModification` records from
105/// [`crate::ChaincodeStub::get_history_for_key`].
106pub struct HistoryQueryIterator {
107    inner: QueryIter,
108}
109
110impl HistoryQueryIterator {
111    pub(crate) fn new(core: Arc<StubCore>, resp: pb::QueryResponse) -> Self {
112        Self {
113            inner: QueryIter::new(core, resp),
114        }
115    }
116
117    pub async fn next(&mut self) -> Result<Option<queryresult::KeyModification>> {
118        match self.inner.next_raw().await? {
119            Some(bytes) => Ok(Some(queryresult::KeyModification::decode(
120                bytes.as_slice(),
121            )?)),
122            None => Ok(None),
123        }
124    }
125
126    pub async fn close(&mut self) -> Result<()> {
127        self.inner.close().await
128    }
129}