a4-cli 0.54.0

CLI tool for generating TypeScript SDKs from Arete stream specifications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! `a4 get`: read a view's current entities once and exit.
//!
//! Connects the way `a4 stream` does (same URL resolution and session
//! token), subscribes with a snapshot, waits for the snapshot to complete,
//! prints the entities as one JSON document and disconnects. For "what is
//! the current X" questions, where a stream that never ends is the wrong
//! tool.

use std::time::Duration;

use anyhow::{bail, Context, Result};
use arete_sdk::{Frame, ServerMessage, SnapshotEntity, Subscription, SubscriptionQuery};
use clap::Args;
use serde_json::{json, Value};

use super::filter::{self, Filter};
use super::session::{
    redeploy_marker, Notice, ReconnectPolicy, SessionHandler, StreamEnd, StreamSession,
};
use super::token;

#[derive(Args)]
pub struct GetArgs {
    /// View to read: EntityName/mode (e.g. OreRound/latest)
    pub view: String,

    /// Owned deployment or registry stack name (e.g. ore)
    #[arg(short, long)]
    pub stack: Option<String>,

    /// WebSocket URL override
    #[arg(long)]
    pub url: Option<String>,

    /// Read the one entity with this key (usually with an EntityName/state view)
    #[arg(short, long)]
    pub key: Option<String>,

    /// Filter expression: field=value, field>N, field~regex (repeatable, ANDed)
    #[arg(long = "where", visible_alias = "filter", value_name = "EXPR")]
    pub filters: Vec<String>,

    /// Fields to output (comma-separated dot paths, e.g. "id.round_id,state.motherlode").
    /// Each lands under its full path as a flat key; select a parent ("state" or
    /// "state.*") to keep its fields nested
    #[arg(long)]
    pub select: Option<String>,

    /// Most entities to print, in the view's order (`--limit 1` for the
    /// current entity of a sorted view like OreRound/latest)
    #[arg(long, default_value_t = 10, value_parser = clap::value_parser!(u32).range(1..))]
    pub limit: u32,

    /// Seconds to wait for the connection and snapshot before failing
    #[arg(long, value_name = "SECS", default_value_t = 15, value_parser = clap::value_parser!(u64).range(1..))]
    pub timeout: u64,
}

/// Units and the output shape, for `a4 get --help`.
pub const GET_HELP: &str = "\
Output:
  One JSON document on stdout:
    {\"view\", \"key\"?, \"total\", \"matching\", \"returned\", \"truncated\", \"entities\": [...]}
  \"entities\" holds at most --limit entities in the view's order. Without
  --where the server sends only --limit of them, so \"total\" is at most
  --limit; with --where, \"total\" counts the whole snapshot and \"matching\"
  the entities it kept. With --key, an entity that does not exist is an
  error.

Selecting fields:
  --select a.b,c prints each path's value under its full path as one flat
  key: {\"a.b\": ..., \"c\": ...}. For nested entities, select the parent
  object instead of many leaves: --select state (or state.*) prints
  {\"state\": {...}} with its fields nested as in a full read. `*` can only
  end a path.

Token amounts:
  Float fields a stack derives with ui_amount are whole token units; the
  integer fields they come from are raw base units (often string-encoded
  u64; for SOL, lamports). `a4 explore stack <stack> --views <view>` shows
  each scaled field's scale and decimals.

Examples:
  a4 get OreRound/latest --stack ore --limit 1
  a4 get OreRound/latest --stack ore --limit 1 --select id.round_id,state.total_deployed,treasury.motherlode
  a4 get OreRound/latest --stack ore --limit 1 --select id,state.*
  a4 get OreMiner/state --stack ore --key <authority>";

pub fn run(args: GetArgs) -> Result<()> {
    let view = args.view.trim();
    if !view.contains('/') {
        bail!("<VIEW> must be EntityName/mode (e.g. OreRound/latest), got '{view}'");
    }
    let filter = Filter::parse(&args.filters)?;
    let select = args
        .select
        .as_deref()
        .map(filter::parse_select)
        .transpose()?;

    let url = super::resolve_ws_url(args.url.as_deref(), args.stack.as_deref())?;
    let (url, refresh) = token::ensure_hosted_ws_token(url)?;

    let rt = tokio::runtime::Runtime::new().context("Failed to create async runtime")?;
    let timeout = Duration::from_secs(args.timeout);
    // Without filters the server can cut the snapshot to --limit; with them
    // the whole snapshot is needed to find the matches.
    let take = (args.key.is_none() && filter.is_empty()).then_some(args.limit as usize);
    let rows = rt.block_on(read_snapshot(
        url,
        refresh,
        view,
        args.key.clone(),
        take,
        timeout,
    ))?;

    let output = shape_output(
        view,
        args.key.as_deref(),
        rows,
        &filter,
        select.as_deref(),
        args.limit as usize,
    )?;
    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

/// Subscribe to `view` and return its first complete snapshot.
async fn read_snapshot(
    url: String,
    refresh: Option<token::SessionRefresh>,
    view: &str,
    key: Option<String>,
    take: Option<usize>,
    timeout: Duration,
) -> Result<Vec<SnapshotEntity>> {
    let deadline = tokio::time::Instant::now() + timeout;
    let subscription_id = format!("a4-get:{}", uuid::Uuid::new_v4().simple());
    let mut query = SubscriptionQuery::new(view);
    if let Some(key) = key {
        query = query.with_key(key);
    }
    if let Some(take) = take {
        query = query.with_take(take);
    }
    let subscription = Subscription::new(subscription_id.clone(), query).with_snapshot(true);
    // A dropped connection is retried a couple of times inside the timeout:
    // the new subscription takes a fresh snapshot.
    let policy = ReconnectPolicy::new(true, Some(2));
    let mut session = StreamSession::new(url, refresh, subscription, policy)?;

    let socket = tokio::time::timeout_at(deadline, session.connect())
        .await
        .map_err(|_| {
            anyhow::anyhow!(
                "Timed out after {}s connecting to {}",
                timeout.as_secs(),
                session.display_url()
            )
        })??;

    let mut collector = Collector::new(subscription_id);
    let stop = tokio::time::sleep_until(deadline);
    tokio::pin!(stop);
    let end = session.run(socket, &mut collector, stop).await?;

    if let Some(rows) = collector.snapshot {
        return Ok(rows);
    }
    if let Some(error) = collector.error {
        bail!("{error}");
    }
    match end {
        StreamEnd::Stopped => bail!(
            "Timed out after {}s waiting for the snapshot of {view}. Check the view id with \
             `a4 explore stack <stack>`, or raise --timeout.",
            timeout.as_secs()
        ),
        StreamEnd::Failed(failure) => bail!("{failure}"),
        StreamEnd::Lost(loss) => bail!("{loss}"),
        StreamEnd::Finished => {
            bail!("The server ended the subscription to {view} before its snapshot")
        }
    }
}

/// Collects one complete snapshot, across batches.
struct Collector {
    subscription_id: String,
    pending: Option<(String, Vec<SnapshotEntity>)>,
    snapshot: Option<Vec<SnapshotEntity>>,
    error: Option<String>,
}

impl Collector {
    fn new(subscription_id: String) -> Self {
        Self {
            subscription_id,
            pending: None,
            snapshot: None,
            error: None,
        }
    }
}

impl SessionHandler for Collector {
    fn on_message(&mut self, message: ServerMessage) -> Result<bool> {
        match message {
            ServerMessage::Error(error) => {
                let ours = error.subscription_id.as_deref() == Some(self.subscription_id.as_str());
                let text = format!("Server error [{}]: {}", error.code, error.message);
                if error.fatal || ours {
                    self.error = Some(text);
                    return Ok(true);
                }
                eprintln!("{text}");
                Ok(false)
            }
            ServerMessage::Frame(Frame::Snapshot {
                snapshot_id,
                data,
                complete,
                ..
            }) => {
                let (id, rows) = self
                    .pending
                    .get_or_insert_with(|| (snapshot_id.clone(), Vec::new()));
                if *id != snapshot_id {
                    // A new snapshot replaces one left incomplete.
                    *id = snapshot_id;
                    rows.clear();
                }
                for row in data {
                    match rows.iter_mut().find(|item| item.key == row.key) {
                        Some(existing) => *existing = row,
                        None => rows.push(row),
                    }
                }
                if complete {
                    self.snapshot = self.pending.take().map(|(_, rows)| rows);
                    return Ok(true);
                }
                Ok(false)
            }
            ServerMessage::Frame(Frame::Unsubscribed { .. }) => Ok(true),
            ServerMessage::Frame(_) => Ok(false),
        }
    }

    fn on_notice(&mut self, notice: Notice<'_>) {
        match notice {
            Notice::Reconnecting(reconnecting) => eprintln!("{reconnecting}"),
            Notice::Unparsed { binary, error } => eprintln!(
                "Warning: failed to parse {} frame: {error}",
                if binary { "binary" } else { "text" }
            ),
            Notice::Redeployed { from, to } => eprintln!("{}", redeploy_marker(from, to)),
            Notice::RefreshRefused(_) | Notice::RefreshFailed(_) => {}
        }
    }

    fn on_reconnected(&mut self, _url: &str) -> Result<()> {
        self.pending = None;
        Ok(())
    }
}

/// The JSON document `a4 get` prints.
fn shape_output(
    view: &str,
    key: Option<&str>,
    rows: Vec<SnapshotEntity>,
    filter: &Filter,
    select: Option<&[Vec<String>]>,
    limit: usize,
) -> Result<Value> {
    let total = rows.len();
    if let Some(key) = key {
        if !rows.iter().any(|row| row.key == key) {
            bail!(
                "No entity with key '{key}' in {view}. Keyed reads usually need the entity's \
                 /state view; list keys with `a4 get <Entity>/list --stack <stack>`."
            );
        }
    }
    let matched: Vec<Value> = rows
        .into_iter()
        .filter(|row| key.is_none_or(|key| row.key == key))
        .map(|row| row.data)
        .filter(|data| filter.is_empty() || filter.matches(data))
        .collect();
    let matching = matched.len();
    let entities: Vec<Value> = matched
        .into_iter()
        .take(limit)
        .map(|data| match select {
            Some(fields) => filter::select_fields(&data, fields),
            None => data,
        })
        .collect();
    let mut output = json!({
        "view": view,
        "total": total,
        "matching": matching,
        "returned": entities.len(),
        "truncated": matching > entities.len(),
        "entities": entities,
    });
    if let Some(key) = key {
        output["key"] = json!(key);
    }
    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use arete_sdk::Mode;

    fn snapshot(id: &str, complete: bool, keys: &[(&str, u64)]) -> ServerMessage {
        ServerMessage::Frame(Frame::Snapshot {
            protocol_version: 2,
            subscription_id: "a4-get:test".to_string(),
            snapshot_id: id.to_string(),
            authoritative: true,
            mode: Mode::List,
            entity: "Round/latest".to_string(),
            key: None,
            data: keys
                .iter()
                .map(|(key, n)| SnapshotEntity {
                    key: (*key).to_string(),
                    data: json!({"id": key, "n": n}),
                })
                .collect(),
            complete,
        })
    }

    #[test]
    fn collects_every_batch_of_the_first_complete_snapshot() {
        let mut collector = Collector::new("a4-get:test".into());
        assert!(!collector
            .on_message(snapshot("s1", false, &[("a", 1), ("b", 2)]))
            .unwrap());
        assert!(collector
            .on_message(snapshot("s1", true, &[("b", 3), ("c", 4)]))
            .unwrap());
        let rows = collector.snapshot.unwrap();
        let keys: Vec<_> = rows.iter().map(|row| row.key.as_str()).collect();
        assert_eq!(keys, ["a", "b", "c"]);
        assert_eq!(rows[1].data["n"], 3);
    }

    #[test]
    fn an_empty_snapshot_completes_the_read() {
        let mut collector = Collector::new("a4-get:test".into());
        assert!(collector.on_message(snapshot("s1", true, &[])).unwrap());
        assert_eq!(collector.snapshot.unwrap().len(), 0);
    }

    #[test]
    fn a_reconnect_drops_a_partial_snapshot() {
        let mut collector = Collector::new("a4-get:test".into());
        collector
            .on_message(snapshot("s1", false, &[("a", 1)]))
            .unwrap();
        collector.on_reconnected("wss://example.test").unwrap();
        collector
            .on_message(snapshot("s2", true, &[("b", 2)]))
            .unwrap();
        let rows = collector.snapshot.unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].key, "b");
    }

    fn rows() -> Vec<SnapshotEntity> {
        (1..=3)
            .map(|n| SnapshotEntity {
                key: n.to_string(),
                data: json!({"id": {"n": n}, "state": {"v": n * 10}}),
            })
            .collect()
    }

    #[test]
    fn output_filters_selects_and_limits() {
        let filter = Filter::parse(&["state.v>10".to_string()]).unwrap();
        let select = filter::parse_select("id.n").unwrap();
        let output = shape_output("T/list", None, rows(), &filter, Some(&select), 1).unwrap();
        assert_eq!(
            output,
            json!({
                "view": "T/list",
                "total": 3,
                "matching": 2,
                "returned": 1,
                "truncated": true,
                "entities": [{"id.n": 2}],
            })
        );
    }

    #[test]
    fn a_missing_key_is_an_error() {
        let filter = Filter::parse(&[]).unwrap();
        let error = shape_output("T/state", Some("9"), rows(), &filter, None, 20).unwrap_err();
        assert!(error.to_string().contains("No entity with key '9'"));
        let found = shape_output("T/state", Some("2"), rows(), &filter, None, 20).unwrap();
        assert_eq!(found["entities"][0]["state"]["v"], 20);
        assert_eq!(found["key"], "2");
    }
}