-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathcall.rs
More file actions
412 lines (364 loc) · 14.8 KB
/
call.rs
File metadata and controls
412 lines (364 loc) · 14.8 KB
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
use crate::api::ClientApi;
use crate::common_args;
use crate::config::Config;
use crate::edit_distance::{edit_distance, find_best_match_for_name};
use crate::subcommands::db_arg_resolution::{load_config_db_targets, resolve_optional_database_parts};
use crate::util::UNSTABLE_WARNING;
use crate::util::{database_identity, get_auth_header};
use anyhow::{bail, Context, Error};
use clap::{Arg, ArgMatches};
use convert_case::{Case, Casing};
use core::ops::Deref;
use itertools::Itertools;
use spacetimedb_lib::db::raw_def::v9::{RawMiscModuleExportV9, RawModuleDefV9, RawProcedureDefV9, RawReducerDefV9};
use spacetimedb_lib::sats::{self, AlgebraicType, Typespace};
use spacetimedb_lib::{Identity, ProductTypeElement};
use std::fmt::Write;
pub fn cli() -> clap::Command {
clap::Command::new("call")
.about(format!(
"Invokes a function (reducer or procedure) in a database. {UNSTABLE_WARNING}"
))
.arg(
Arg::new("call_parts")
.help("Call arguments: [DATABASE] <FUNCTION_NAME> [ARGUMENTS...]")
.num_args(1..),
)
.arg(common_args::server().help("The nickname, host name or URL of the server hosting the database"))
.arg(common_args::anonymous())
.arg(common_args::yes())
.arg(
Arg::new("no_config")
.long("no-config")
.action(clap::ArgAction::SetTrue)
.help("Ignore spacetime.json configuration"),
)
.after_help("Run `spacetime help call` for more detailed information.\n")
}
enum CallDef<'a> {
Reducer(&'a RawReducerDefV9),
Procedure(&'a RawProcedureDefV9),
}
impl<'a> CallDef<'a> {
fn params(&self) -> &'a sats::ProductType {
match self {
CallDef::Reducer(r) => &r.params,
CallDef::Procedure(p) => &p.params,
}
}
fn name(&self) -> &str {
match self {
CallDef::Reducer(r) => r.name.as_ref(),
CallDef::Procedure(p) => p.name.as_ref(),
}
}
fn kind(&self) -> &str {
match self {
CallDef::Reducer(_) => "reducer",
CallDef::Procedure(_) => "procedure",
}
}
}
pub async fn exec(config: Config, args: &ArgMatches) -> Result<(), Error> {
eprintln!("{UNSTABLE_WARNING}\n");
let server = args.get_one::<String>("server").map(|s| s.as_ref());
let force = args.get_flag("force");
let anon_identity = args.get_flag("anon_identity");
let no_config = args.get_flag("no_config");
let raw_parts: Vec<String> = args
.get_many::<String>("call_parts")
.map(|vals| vals.cloned().collect())
.unwrap_or_default();
let config_targets = load_config_db_targets(no_config)?;
let resolved = resolve_optional_database_parts(
&raw_parts,
config_targets.as_deref(),
"function_name",
"spacetime call [database] <function_name> <arguments>... (or --no-config for legacy behavior)",
)?;
let reducer_procedure_name = resolved
.remaining_args
.first()
.ok_or_else(|| anyhow::anyhow!("internal error: function_name should be present after argument resolution"))?;
let call_arguments = resolved.remaining_args.iter().skip(1);
let resolved_server = server.or(resolved.server.as_deref());
let mut config = config;
let conn = crate::api::Connection {
host: config.get_host_url(resolved_server)?,
auth_header: get_auth_header(&mut config, anon_identity, resolved_server, !force).await?,
database_identity: database_identity(&config, &resolved.database, resolved_server).await?,
database: resolved.database.clone(),
};
let api = ClientApi::new(conn);
let database_identity = api.con.database_identity;
let database = &api.con.database;
let raw = api.module_def().await?;
let call_def = match raw.reducers.iter().find(|r| r.name.as_ref() == reducer_procedure_name.as_str()) {
Some(reducer_def) => CallDef::Reducer(reducer_def),
None => {
let procedure = raw.misc_exports.iter().find_map(|e| match e {
RawMiscModuleExportV9::Procedure(p)
if p.name.as_ref() == reducer_procedure_name.as_str() =>
{
Some(p)
}
_ => None,
});
match procedure {
Some(procedure_def) => CallDef::Procedure(procedure_def),
None => {
return Err(anyhow::Error::msg(no_such_reducer_or_procedure(
&database_identity,
database,
reducer_procedure_name,
&raw,
)));
}
}
}
};
// String quote any arguments that should be quoted
let arguments = call_arguments
.zip(&call_def.params().elements)
.map(|(argument, element)| match &element.algebraic_type {
AlgebraicType::String if !argument.starts_with('\"') || !argument.ends_with('\"') => {
format!("\"{argument}\"")
}
_ => argument.to_string(),
});
let arg_json = format!("[{}]", arguments.format(", "));
let res = api.call(reducer_procedure_name, arg_json).await?;
if let Err(e) = res.error_for_status_ref() {
let Ok(response_text) = res.text().await else {
// Cannot give a better error than this if we don't know what the problem is.
bail!(e);
};
let error = Err(e).context(format!("Response text: {response_text}"));
let error_msg =
if response_text.starts_with("no such reducer") || response_text.starts_with("no such procedure") {
no_such_reducer_or_procedure(&database_identity, database, reducer_procedure_name, &raw)
} else if response_text.starts_with("invalid arguments") {
invalid_arguments(&database_identity, database, &response_text, &raw.typespace, call_def)
} else {
return error;
};
return error.context(error_msg);
}
if let CallDef::Procedure(_) = call_def {
let body = res.text().await?;
println!("{body}");
}
Ok(())
}
/// Returns an error message for when `reducer` is called with wrong arguments.
fn invalid_arguments(identity: &Identity, db: &str, text: &str, typespace: &Typespace, call_def: CallDef) -> String {
let mut error = format!(
"Invalid arguments provided for {} `{}` for database `{}` resolving to identity `{}`.",
call_def.kind(),
call_def.name(),
db,
identity
);
if let Some((actual, expected)) = find_actual_expected(text).filter(|(a, e)| a != e) {
write!(
error,
"\n\n{expected} parameters were expected, but {actual} were provided."
)
.unwrap();
}
write!(
error,
"\n\nThe {} has the following signature:\n\t{}",
call_def.kind(),
CallSignature(typespace.with_type(&call_def))
)
.unwrap();
error
}
/// Parse actual/expected parameter numbers from the invalid args response text.
fn find_actual_expected(text: &str) -> Option<(usize, usize)> {
let (_, x) = split_at_first_substring(text, "invalid length")?;
let (x, y) = split_at_first_substring(x, "args for test with")?;
let (x, _) = split_at_first_substring(x, ",")?;
let (y, _) = split_at_first_substring(y, "elements")?;
let actual: usize = x.trim().parse().ok()?;
let expected: usize = y.trim().parse().ok()?;
Some((actual, expected))
}
/// Returns a tuple with
/// - everything after the first `substring`
/// - and anything before it.
fn split_at_first_substring<'t>(text: &'t str, substring: &str) -> Option<(&'t str, &'t str)> {
text.find(substring)
.map(|pos| (&text[..pos], &text[pos + substring.len()..]))
}
/// Provided the `schema_json` for the database,
/// returns the signature for a reducer OR procedure with `name`.
struct CallSignature<'a>(sats::WithTypespace<'a, CallDef<'a>>);
impl std::fmt::Display for CallSignature<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let call_def = self.0.ty();
let typespace = self.0.typespace();
write!(f, "{}(", call_def.name())?;
// Print the arguments to `args`.
let mut comma = false;
for arg in &*call_def.params().elements {
if comma {
write!(f, ", ")?;
}
comma = true;
if let Some(name) = arg.name() {
write!(f, "{}: ", name.deref().to_case(Case::Snake))?;
}
write_type::write_type(typespace, f, &arg.algebraic_type)?;
}
write!(f, ")")
}
}
/// Returns an error message for when `reducer` or `procedure` does not exist in `db`.
fn no_such_reducer_or_procedure(database_identity: &Identity, db: &str, name: &str, raw: &RawModuleDefV9) -> String {
let mut error = format!(
"No such reducer OR procedure `{name}` for database `{db}` resolving to identity `{database_identity}`."
);
add_reducer_procedure_ctx_to_err(&mut error, raw, name);
error
}
const CALL_PRINT_LIMIT: usize = 10;
/// Provided the schema for the database,
/// decorate `error` with more helpful info about reducers and procedures.
fn add_reducer_procedure_ctx_to_err(error: &mut String, raw: &RawModuleDefV9, reducer_name: &str) {
let reducers = raw
.reducers
.iter()
.filter(|r| r.lifecycle.is_none())
.map(|r| r.name.as_ref())
.collect::<Vec<_>>();
let procedures = raw
.misc_exports
.iter()
.filter_map(|e| match e {
RawMiscModuleExportV9::Procedure(p) => Some(p.name.as_ref()),
_ => None,
})
.collect::<Vec<_>>();
if let Some(best) = find_best_match_for_name(&reducers, reducer_name, None) {
write!(error, "\n\nA reducer with a similar name exists: `{best}`").unwrap();
} else if let Some(best) = find_best_match_for_name(&procedures, reducer_name, None) {
write!(error, "\n\nA procedure with a similar name exists: `{best}`").unwrap();
} else {
let mut list_similar = |mut list: Vec<&str>, name: &str, kind: &str| {
if list.is_empty() {
write!(error, "\n\nThe database has no {kind}s.").unwrap();
return;
}
list.sort_by_key(|candidate| edit_distance(name, candidate, usize::MAX));
// Don't spam the user with too many entries.
let too_many_to_show = list.len() > CALL_PRINT_LIMIT;
let diff = list.len().abs_diff(CALL_PRINT_LIMIT);
list.truncate(CALL_PRINT_LIMIT);
// List them.
write!(error, "\n\nHere are some existing {kind}s:").unwrap();
for candidate in list {
write!(error, "\n- {candidate}").unwrap();
}
// When somewhere not listed, note that are more.
if too_many_to_show {
let plural = if diff == 1 { "" } else { "s" };
write!(error, "\n... ({diff} {kind}{plural} not shown)").unwrap();
}
};
list_similar(reducers, reducer_name, "reducer");
list_similar(procedures, reducer_name, "procedure");
}
}
// this is an old version of code in generate::rust that got
// refactored, but reducer_signature() was using it
// TODO: port reducer_signature() to use AlgebraicTypeUse et al, somehow.
mod write_type {
use super::*;
use sats::ArrayType;
use spacetimedb_lib::ProductType;
use std::fmt;
pub fn write_type<W: fmt::Write>(typespace: &Typespace, out: &mut W, ty: &AlgebraicType) -> fmt::Result {
match ty {
p if p.is_identity() => write!(out, "Identity")?,
p if p.is_connection_id() => write!(out, "ConnectionId")?,
p if p.is_schedule_at() => write!(out, "ScheduleAt")?,
AlgebraicType::Sum(sum_type) => {
if let Some(inner_ty) = sum_type.as_option() {
write!(out, "Option<")?;
write_type(typespace, out, inner_ty)?;
write!(out, ">")?;
} else {
write!(out, "enum ")?;
print_comma_sep_braced(out, &sum_type.variants, |out: &mut W, elem: &_| {
if let Some(name) = &elem.name {
write!(out, "{name}: ")?;
}
write_type(typespace, out, &elem.algebraic_type)
})?;
}
}
AlgebraicType::Product(ProductType { elements }) => {
print_comma_sep_braced(out, elements, |out: &mut W, elem: &ProductTypeElement| {
if let Some(name) = &elem.name {
write!(out, "{name}: ")?;
}
write_type(typespace, out, &elem.algebraic_type)
})?;
}
AlgebraicType::Bool => write!(out, "bool")?,
AlgebraicType::I8 => write!(out, "i8")?,
AlgebraicType::U8 => write!(out, "u8")?,
AlgebraicType::I16 => write!(out, "i16")?,
AlgebraicType::U16 => write!(out, "u16")?,
AlgebraicType::I32 => write!(out, "i32")?,
AlgebraicType::U32 => write!(out, "u32")?,
AlgebraicType::I64 => write!(out, "i64")?,
AlgebraicType::U64 => write!(out, "u64")?,
AlgebraicType::I128 => write!(out, "i128")?,
AlgebraicType::U128 => write!(out, "u128")?,
AlgebraicType::I256 => write!(out, "i256")?,
AlgebraicType::U256 => write!(out, "u256")?,
AlgebraicType::F32 => write!(out, "f32")?,
AlgebraicType::F64 => write!(out, "f64")?,
AlgebraicType::String => write!(out, "String")?,
AlgebraicType::Array(ArrayType { elem_ty }) => {
write!(out, "Vec<")?;
write_type(typespace, out, elem_ty)?;
write!(out, ">")?;
}
AlgebraicType::Ref(r) => {
write_type(typespace, out, &typespace[*r])?;
}
}
Ok(())
}
fn print_comma_sep_braced<W: fmt::Write, T>(
out: &mut W,
elems: &[T],
on: impl Fn(&mut W, &T) -> fmt::Result,
) -> fmt::Result {
write!(out, "{{")?;
let mut iter = elems.iter();
// First factor.
if let Some(elem) = iter.next() {
write!(out, " ")?;
on(out, elem)?;
}
// Other factors.
for elem in iter {
write!(out, ", ")?;
on(out, elem)?;
}
if !elems.is_empty() {
write!(out, " ")?;
}
write!(out, "}}")?;
Ok(())
}
}
#[cfg(test)]
mod tests {
// Resolution tests live in db_arg_resolution.rs
}