1use crate::error::{err, ErrorCode, Result};
4use crate::json::{self, Value};
5use crate::keys::Keys;
6use crate::lexical::{self, limits};
7use crate::receipt::Receipt;
8use crate::schema;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12pub enum Outcome {
13 Ok,
17 Stale,
20 NotCovered,
23 Unlicensed,
25 PaymentRequired,
27 RateLimited,
29 BadRequest,
31 Error,
33}
34
35impl Outcome {
36 pub const fn as_str(self) -> &'static str {
38 match self {
39 Outcome::Ok => "ok",
40 Outcome::Stale => "stale",
41 Outcome::NotCovered => "not_covered",
42 Outcome::Unlicensed => "unlicensed",
43 Outcome::PaymentRequired => "payment_required",
44 Outcome::RateLimited => "rate_limited",
45 Outcome::BadRequest => "bad_request",
46 Outcome::Error => "error",
47 }
48 }
49}
50
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum Trust {
54 Primary,
56 Verified,
58 Unverified,
60}
61
62impl Trust {
63 pub const fn as_str(self) -> &'static str {
65 match self {
66 Trust::Primary => "primary",
67 Trust::Verified => "verified",
68 Trust::Unverified => "unverified",
69 }
70 }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
78#[non_exhaustive]
79pub enum Fault {
80 DivZero,
82 Domain,
84 Range,
86 Empty,
88 Absent,
90 Future,
92 Key,
95 DispatchKey,
97 WhatifNoSolution,
100}
101
102impl Fault {
103 pub const ALL: &'static [Fault] = &[
105 Fault::DivZero,
106 Fault::Domain,
107 Fault::Range,
108 Fault::Empty,
109 Fault::Absent,
110 Fault::Future,
111 Fault::Key,
112 Fault::DispatchKey,
113 Fault::WhatifNoSolution,
114 ];
115
116 pub const fn as_str(self) -> &'static str {
118 match self {
119 Fault::DivZero => "E_FORMULA_DIV_ZERO",
120 Fault::Domain => "E_FORMULA_DOMAIN",
121 Fault::Range => "E_FORMULA_RANGE",
122 Fault::Empty => "E_FORMULA_EMPTY",
123 Fault::Absent => "E_FORMULA_ABSENT",
124 Fault::Future => "E_FORMULA_FUTURE",
125 Fault::Key => "E_FORMULA_KEY",
126 Fault::DispatchKey => "E_FORMULA_DISPATCH_KEY",
127 Fault::WhatifNoSolution => "E_WHATIF_NO_SOLUTION",
128 }
129 }
130
131 pub fn from_code(text: &str) -> Option<Fault> {
134 Fault::ALL.iter().copied().find(|f| f.as_str() == text)
135 }
136}
137
138impl core::fmt::Display for Fault {
139 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140 f.write_str(self.as_str())
141 }
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
149#[non_exhaustive]
150pub enum ForeignDetail {
151 Offline,
153 Network,
155 Dns,
157 Tls,
159 Timeout,
161 Refused,
163}
164
165impl ForeignDetail {
166 pub const ALL: &'static [ForeignDetail] = &[
168 ForeignDetail::Offline,
169 ForeignDetail::Network,
170 ForeignDetail::Dns,
171 ForeignDetail::Tls,
172 ForeignDetail::Timeout,
173 ForeignDetail::Refused,
174 ];
175
176 pub const fn as_str(self) -> &'static str {
178 match self {
179 ForeignDetail::Offline => "offline",
180 ForeignDetail::Network => "network",
181 ForeignDetail::Dns => "dns",
182 ForeignDetail::Tls => "tls",
183 ForeignDetail::Timeout => "timeout",
184 ForeignDetail::Refused => "refused",
185 }
186 }
187
188 pub fn from_name(text: &str) -> Option<ForeignDetail> {
190 ForeignDetail::ALL.iter().copied().find(|d| d.as_str() == text)
191 }
192}
193
194impl core::fmt::Display for ForeignDetail {
195 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
196 f.write_str(self.as_str())
197 }
198}
199
200#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
203#[non_exhaustive]
204pub struct EnvelopeExtras {
205 pub fault: Option<Fault>,
207 pub fn_hash: Option<String>,
210 pub detail: Option<ForeignDetail>,
212}
213
214#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
216#[non_exhaustive]
217pub enum ResolutionKind {
218 Alias,
220 Default,
222 Lookup,
225 Method,
227}
228
229impl ResolutionKind {
230 pub const ALL: &'static [ResolutionKind] =
232 &[ResolutionKind::Alias, ResolutionKind::Default, ResolutionKind::Lookup, ResolutionKind::Method];
233
234 pub const fn as_str(self) -> &'static str {
236 match self {
237 ResolutionKind::Alias => "alias",
238 ResolutionKind::Default => "default",
239 ResolutionKind::Lookup => "lookup",
240 ResolutionKind::Method => "method",
241 }
242 }
243
244 pub fn from_name(text: &str) -> Option<ResolutionKind> {
246 ResolutionKind::ALL.iter().copied().find(|k| k.as_str() == text)
247 }
248}
249
250#[derive(Clone, Debug, PartialEq, Eq, Hash)]
253#[non_exhaustive]
254pub struct Resolution {
255 pub from: String,
257 pub kind: ResolutionKind,
259 pub to: String,
261 pub asof: Option<String>,
263}
264
265impl Resolution {
266 pub fn new(from: &str, kind: ResolutionKind, to: &str) -> Result<Resolution> {
269 if kind == ResolutionKind::Lookup {
270 return env_err("$.resolutions", "a lookup resolution carries its asof: Resolution::lookup");
271 }
272 Ok(Resolution { from: from.into(), kind, to: to.into(), asof: None })
273 }
274
275 pub fn lookup(label: &str, key: &str, asof: &str) -> Result<Resolution> {
278 lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
279 Ok(Resolution { from: label.into(), kind: ResolutionKind::Lookup, to: key.into(), asof: Some(asof.into()) })
280 }
281}
282
283#[derive(Clone, Debug, PartialEq, Eq, Hash)]
286#[non_exhaustive]
287pub struct Resolved {
288 pub call: String,
290 pub resolutions: Vec<Resolution>,
292 pub aliases_tx: Option<String>,
294}
295
296impl Resolved {
297 pub fn new(call: &str, resolutions: Vec<Resolution>) -> Result<Resolved> {
299 if call.is_empty() {
300 return env_err("$.resolved.call", "call is a non-empty string");
301 }
302 Ok(Resolved { call: call.into(), resolutions, aliases_tx: None })
303 }
304
305 pub fn with_aliases_tx(self, instant: &str) -> Result<Resolved> {
308 lexical::check_instant(instant, "$.resolved.aliases_tx").map_err(|e| e.recode(ErrorCode::Envelope))?;
309 Ok(Resolved { aliases_tx: Some(instant.into()), ..self })
310 }
311}
312
313#[derive(Clone, Debug, PartialEq, Eq, Hash)]
316#[non_exhaustive]
317pub struct Shadows {
318 pub class: String,
320 pub reference: String,
322}
323
324impl Shadows {
325 pub fn new(class: &str, reference: &str) -> Result<Shadows> {
328 lexical::check_function_name(class, "$.shadows.class").map_err(|e| e.recode(ErrorCode::Envelope))?;
329 lexical::check_hex(reference, 64, "$.shadows.reference").map_err(|e| e.recode(ErrorCode::Envelope))?;
330 Ok(Shadows { class: class.into(), reference: reference.into() })
331 }
332}
333
334#[derive(Clone, Debug, PartialEq, Eq, Hash)]
336pub struct Quote {
337 pub amount: String,
339 pub currency: String,
341 pub authorise: String,
343}
344
345#[derive(Clone, Debug)]
349pub(crate) struct Overrides(pub(crate) Value);
350
351impl PartialEq for Overrides {
352 fn eq(&self, other: &Overrides) -> bool {
353 self.0.to_jcs() == other.0.to_jcs()
354 }
355}
356
357impl Eq for Overrides {}
358
359impl core::hash::Hash for Overrides {
360 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
361 self.0.to_jcs().hash(state);
362 }
363}
364
365#[derive(Clone, Debug, PartialEq, Eq, Hash)]
367pub struct Request {
368 pub(crate) cell_id: String,
369 pub(crate) asof: Option<String>,
370 pub(crate) job: Option<String>,
371 pub(crate) pin: Option<String>,
372 pub(crate) mesh: Option<String>,
373 pub(crate) overrides: Option<Overrides>,
374 pub(crate) solve: Option<String>,
375}
376
377#[derive(Clone, Debug, PartialEq, Eq, Hash)]
379pub struct InvalidRequest(String);
380
381impl core::fmt::Display for InvalidRequest {
382 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
383 write!(f, "invalid request: {}", self.0)
384 }
385}
386
387impl std::error::Error for InvalidRequest {}
388
389impl Request {
390 pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
394 if lexical::check_hex(cell_id, 64, "").is_err() {
395 return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
396 }
397 if let Some(a) = asof {
398 if !lexical::is_instant(a) {
399 return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
400 }
401 }
402 Ok(Request {
403 cell_id: cell_id.into(),
404 asof: asof.map(String::from),
405 job: None,
406 pin: None,
407 mesh: None,
408 overrides: None,
409 solve: None,
410 })
411 }
412
413 pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
419 if !is_job(job) {
420 return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
421 }
422 let mut r = Request::new(cell_id, asof)?;
423 r.job = Some(job.into());
424 Ok(r)
425 }
426
427 pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
431 if lexical::check_hex(fn_hash, 64, "").is_err() {
432 return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
433 }
434 Ok(Request { pin: Some(fn_hash.into()), ..self })
435 }
436
437 pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
441 if lexical::check_dns_name(host, "").is_err() {
442 return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
443 }
444 Ok(Request { mesh: Some(host.into()), ..self })
445 }
446
447 pub fn with_whatif(self, overrides: &Value, solve: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
452 let Value::Array(items) = overrides else {
453 return Err(InvalidRequest("overrides is an array of overrides".into()));
454 };
455 if items.is_empty() && solve.is_none() {
457 return Err(InvalidRequest("empty overrides need solve".into()));
458 }
459 crate::answer::check_overrides(overrides).map_err(|e| InvalidRequest(e.to_string()))?;
460 if let Some(v) = solve {
461 if lexical::check_hex(v, 64, "").is_err() {
462 return Err(InvalidRequest(format!("solve must be 64 lowercase hex digits: {v:?}")));
463 }
464 }
465 Ok(Request { overrides: Some(Overrides(overrides.clone())), solve: solve.map(String::from), ..self })
466 }
467
468 pub fn overrides(&self) -> Option<&Value> {
470 self.overrides.as_ref().map(|o| &o.0)
471 }
472
473 pub fn solve(&self) -> Option<&str> {
475 self.solve.as_deref()
476 }
477
478 pub fn fn_hash(&self) -> Option<&str> {
480 self.pin.as_deref()
481 }
482
483 pub fn mesh(&self) -> Option<&str> {
485 self.mesh.as_deref()
486 }
487
488 pub fn job(&self) -> Option<&str> {
490 self.job.as_deref()
491 }
492
493 pub fn cell_id(&self) -> &str {
495 &self.cell_id
496 }
497
498 pub fn asof(&self) -> Option<&str> {
500 self.asof.as_deref()
501 }
502}
503
504#[derive(Clone, Debug, PartialEq, Eq)]
506pub struct Envelope {
507 pub outcome: Outcome,
509 pub receipt: Option<Receipt>,
511 pub trust: Option<Trust>,
513 pub age_seconds: Option<u64>,
515 pub superseded_by: Option<String>,
517 pub reason: Option<String>,
519 pub quote: Option<Quote>,
521 pub retry_after_seconds: Option<u64>,
523 pub error: Option<ErrorCode>,
525}
526
527pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
528 ErrorCode::ParseUri,
529 ErrorCode::CanonName,
530 ErrorCode::CanonArgName,
531 ErrorCode::CanonArgDuplicate,
532 ErrorCode::CanonArgOrder,
533 ErrorCode::CanonPercent,
534 ErrorCode::CanonType,
535 ErrorCode::CanonNumber,
536 ErrorCode::CanonDate,
537 ErrorCode::CanonInstant,
538 ErrorCode::CanonString,
539 ErrorCode::CanonBlob,
540 ErrorCode::CanonLimit,
541 ErrorCode::ArgUnknown,
542 ErrorCode::ArgMissing,
543];
544
545pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
546 err(ErrorCode::Envelope, path, detail)
547}
548
549pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
551 let Some(t) = v.as_number_text() else {
552 return env_err(path, "must be a non-negative integer");
553 };
554 let ok =
555 !t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
556 match (ok, t.parse::<u64>()) {
557 (true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
558 _ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
559 }
560}
561
562pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
572 check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
573}
574
575pub fn check_envelope_extras(
586 status: u16,
587 body: &[u8],
588 keys: &Keys,
589 request: &Request,
590) -> Result<(Envelope, EnvelopeExtras)> {
591 crate::answer::check_answer(status, body, keys, request)?.into_envelope()
592}
593
594pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
601 let a = crate::answer::check_answer(status, body, keys, request)?;
602 if let Some(p) = a.pending {
603 return Ok(AnyEnvelope::Pending(p));
604 }
605 a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
606}
607
608pub(crate) fn is_job(s: &str) -> bool {
610 (32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
611}
612
613#[allow(clippy::large_enum_variant)]
617#[derive(Clone, Debug, PartialEq, Eq)]
618#[non_exhaustive]
619pub enum AnyEnvelope {
620 Envelope(Envelope, EnvelopeExtras),
623 Pending(Pending),
625}
626
627impl AnyEnvelope {
628 pub fn outcome_str(&self) -> &'static str {
630 match self {
631 AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
632 AnyEnvelope::Pending(_) => "pending",
633 }
634 }
635}
636
637#[derive(Clone, Debug, PartialEq, Eq, Hash)]
641#[non_exhaustive]
642pub struct Pending {
643 pub job: String,
645 pub estimate_seconds: u64,
647 pub poll: String,
650 pub request: Request,
652}
653
654impl Pending {
655 pub const STATUS: u16 = 202;
657
658 pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
665 check_job_and_poll_for(job, poll, request.mesh())?;
666 if estimate_seconds > limits::BLOB_LENGTH {
667 return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
668 }
669 let request = Request { job: None, mesh: None, ..request };
670 Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
671 }
672
673 pub fn to_value(&self) -> Value {
675 json::parse(&self.to_json()).unwrap_or(Value::Null)
677 }
678
679 pub fn to_json(&self) -> Vec<u8> {
681 let mut out = String::new();
682 out.push_str("{\"estimate_seconds\":");
683 out.push_str(&self.estimate_seconds.to_string());
684 out.push_str(",\"job\":");
685 json::write_string(&self.job, &mut out);
686 out.push_str(",\"outcome\":\"pending\",\"poll\":");
687 json::write_string(&self.poll, &mut out);
688 out.push_str(",\"request\":{");
689 if let Some(a) = &self.request.asof {
690 out.push_str("\"asof\":");
691 json::write_string(a, &mut out);
692 out.push(',');
693 }
694 out.push_str("\"cell_id\":");
695 json::write_string(&self.request.cell_id, &mut out);
696 if let Some(p) = &self.request.pin {
697 out.push_str(",\"fn_hash\":");
698 json::write_string(p, &mut out);
699 }
700 out.push_str("}}");
701 out.into_bytes()
702 }
703}
704
705pub(crate) fn check_job_and_poll_for(job: &str, poll: &str, mesh: Option<&str>) -> Result<()> {
708 if !is_job(job) {
709 return env_err("$.job", "job is 32 to 64 lowercase hex digits");
710 }
711 if poll.starts_with("http://") {
712 if !mesh.is_some_and(lexical::is_unrooted) {
713 return env_err("$.poll", "a loopback poll is only for an unrooted mesh the request names");
714 }
715 if lexical::loopback_origin(poll).is_none() || !poll.ends_with(&format!("/jobs/{job}")) {
716 return env_err("$.poll", "poll is a loopback URL ending /jobs/<job>");
717 }
718 return Ok(());
719 }
720 let url_ok =
721 poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
722 && poll.len() <= limits::LICENCE_URL;
723 if !url_ok {
724 return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
725 }
726 let host = poll["https://".len()..].split('/').next().unwrap_or("");
728 if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
729 return env_err("$.poll", "poll's host is a DNS name");
730 }
731 if !poll.ends_with(&format!("/jobs/{job}")) {
732 return env_err("$.poll", "poll ends /jobs/<job>");
733 }
734 Ok(())
735}
736
737pub(crate) fn quote(q: &Value) -> Result<Quote> {
738 let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
739 schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
740 let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
741 let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
742 let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
743 if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
744 return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
745 }
746 let url_ok = authorise
747 .strip_prefix("https://")
748 .is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
749 && authorise.len() <= limits::LICENCE_URL;
750 if !url_ok {
751 return env_err("$.quote.authorise", "authorise is an https URL");
752 }
753 if !lexical::is_currency(currency) {
754 return env_err("$.quote.currency", "currency is a currency code from units.md");
755 }
756 Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
757}