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 Chain,
231}
232
233impl ResolutionKind {
234 pub const ALL: &'static [ResolutionKind] = &[
236 ResolutionKind::Alias,
237 ResolutionKind::Default,
238 ResolutionKind::Lookup,
239 ResolutionKind::Method,
240 ResolutionKind::Chain,
241 ];
242
243 pub const fn as_str(self) -> &'static str {
245 match self {
246 ResolutionKind::Alias => "alias",
247 ResolutionKind::Default => "default",
248 ResolutionKind::Lookup => "lookup",
249 ResolutionKind::Method => "method",
250 ResolutionKind::Chain => "chain",
251 }
252 }
253
254 pub fn from_name(text: &str) -> Option<ResolutionKind> {
256 ResolutionKind::ALL.iter().copied().find(|k| k.as_str() == text)
257 }
258}
259
260#[derive(Clone, Debug, PartialEq, Eq, Hash)]
263#[non_exhaustive]
264pub struct Resolution {
265 pub from: String,
267 pub kind: ResolutionKind,
269 pub to: String,
271 pub asof: Option<String>,
274}
275
276impl Resolution {
277 pub fn new(from: &str, kind: ResolutionKind, to: &str) -> Result<Resolution> {
280 if matches!(kind, ResolutionKind::Lookup | ResolutionKind::Chain) {
281 return env_err("$.resolutions", "a lookup or chain resolution carries its asof");
282 }
283 Ok(Resolution { from: from.into(), kind, to: to.into(), asof: None })
284 }
285
286 pub fn lookup(label: &str, key: &str, asof: &str) -> Result<Resolution> {
289 lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
290 Ok(Resolution { from: label.into(), kind: ResolutionKind::Lookup, to: key.into(), asof: Some(asof.into()) })
291 }
292
293 pub fn chain(from: &str, to: &str, asof: &str) -> Result<Resolution> {
296 lexical::check_instant(asof, "$.resolutions.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
297 Ok(Resolution { from: from.into(), kind: ResolutionKind::Chain, to: to.into(), asof: Some(asof.into()) })
298 }
299}
300
301#[derive(Clone, Debug, PartialEq, Eq, Hash)]
304#[non_exhaustive]
305pub struct Resolved {
306 pub call: String,
308 pub resolutions: Vec<Resolution>,
310 pub aliases_tx: Option<String>,
312}
313
314impl Resolved {
315 pub fn new(call: &str, resolutions: Vec<Resolution>) -> Result<Resolved> {
317 if call.is_empty() {
318 return env_err("$.resolved.call", "call is a non-empty string");
319 }
320 Ok(Resolved { call: call.into(), resolutions, aliases_tx: None })
321 }
322
323 pub fn with_aliases_tx(self, instant: &str) -> Result<Resolved> {
326 lexical::check_instant(instant, "$.resolved.aliases_tx").map_err(|e| e.recode(ErrorCode::Envelope))?;
327 Ok(Resolved { aliases_tx: Some(instant.into()), ..self })
328 }
329}
330
331#[derive(Clone, Debug, PartialEq, Eq, Hash)]
334#[non_exhaustive]
335pub struct Shadows {
336 pub class: String,
338 pub reference: String,
340}
341
342impl Shadows {
343 pub fn new(class: &str, reference: &str) -> Result<Shadows> {
346 lexical::check_function_name(class, "$.shadows.class").map_err(|e| e.recode(ErrorCode::Envelope))?;
347 lexical::check_hex(reference, 64, "$.shadows.reference").map_err(|e| e.recode(ErrorCode::Envelope))?;
348 Ok(Shadows { class: class.into(), reference: reference.into() })
349 }
350}
351
352#[derive(Clone, Debug, PartialEq, Eq, Hash)]
354pub struct Quote {
355 pub amount: String,
357 pub currency: String,
359 pub authorise: String,
361}
362
363#[derive(Clone, Debug)]
367pub(crate) struct Overrides(pub(crate) Value);
368
369impl PartialEq for Overrides {
370 fn eq(&self, other: &Overrides) -> bool {
371 self.0.to_jcs() == other.0.to_jcs()
372 }
373}
374
375impl Eq for Overrides {}
376
377impl core::hash::Hash for Overrides {
378 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
379 self.0.to_jcs().hash(state);
380 }
381}
382
383#[derive(Clone, Debug, PartialEq, Eq, Hash)]
385pub struct Request {
386 pub(crate) cell_id: String,
387 pub(crate) asof: Option<String>,
388 pub(crate) job: Option<String>,
389 pub(crate) pin: Option<String>,
390 pub(crate) mesh: Option<String>,
391 pub(crate) overrides: Option<Overrides>,
392 pub(crate) solve: Option<String>,
393}
394
395#[derive(Clone, Debug, PartialEq, Eq, Hash)]
397pub struct InvalidRequest(String);
398
399impl core::fmt::Display for InvalidRequest {
400 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401 write!(f, "invalid request: {}", self.0)
402 }
403}
404
405impl std::error::Error for InvalidRequest {}
406
407impl Request {
408 pub fn new(cell_id: &str, asof: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
412 if lexical::check_hex(cell_id, 64, "").is_err() {
413 return Err(InvalidRequest(format!("cell_id must be 64 lowercase hex digits: {cell_id:?}")));
414 }
415 if let Some(a) = asof {
416 if !lexical::is_instant(a) {
417 return Err(InvalidRequest(format!("asof must be an instant: {a:?}")));
418 }
419 }
420 Ok(Request {
421 cell_id: cell_id.into(),
422 asof: asof.map(String::from),
423 job: None,
424 pin: None,
425 mesh: None,
426 overrides: None,
427 solve: None,
428 })
429 }
430
431 pub fn with_job(cell_id: &str, asof: Option<&str>, job: &str) -> core::result::Result<Request, InvalidRequest> {
437 if !is_job(job) {
438 return Err(InvalidRequest(format!("job must be 32 to 64 lowercase hex digits: {job:?}")));
439 }
440 let mut r = Request::new(cell_id, asof)?;
441 r.job = Some(job.into());
442 Ok(r)
443 }
444
445 pub fn with_pin(self, fn_hash: &str) -> core::result::Result<Request, InvalidRequest> {
449 if lexical::check_hex(fn_hash, 64, "").is_err() {
450 return Err(InvalidRequest(format!("fn_hash must be 64 lowercase hex digits: {fn_hash:?}")));
451 }
452 Ok(Request { pin: Some(fn_hash.into()), ..self })
453 }
454
455 pub fn with_mesh(self, host: &str) -> core::result::Result<Request, InvalidRequest> {
459 if lexical::check_dns_name(host, "").is_err() {
460 return Err(InvalidRequest(format!("mesh must be a DNS name: {host:?}")));
461 }
462 Ok(Request { mesh: Some(host.into()), ..self })
463 }
464
465 pub fn with_whatif(self, overrides: &Value, solve: Option<&str>) -> core::result::Result<Request, InvalidRequest> {
470 let Value::Array(items) = overrides else {
471 return Err(InvalidRequest("overrides is an array of overrides".into()));
472 };
473 if items.is_empty() && solve.is_none() {
475 return Err(InvalidRequest("empty overrides need solve".into()));
476 }
477 crate::answer::check_overrides(overrides).map_err(|e| InvalidRequest(e.to_string()))?;
478 if let Some(v) = solve {
479 if lexical::check_hex(v, 64, "").is_err() {
480 return Err(InvalidRequest(format!("solve must be 64 lowercase hex digits: {v:?}")));
481 }
482 }
483 Ok(Request { overrides: Some(Overrides(overrides.clone())), solve: solve.map(String::from), ..self })
484 }
485
486 pub fn overrides(&self) -> Option<&Value> {
488 self.overrides.as_ref().map(|o| &o.0)
489 }
490
491 pub fn solve(&self) -> Option<&str> {
493 self.solve.as_deref()
494 }
495
496 pub fn fn_hash(&self) -> Option<&str> {
498 self.pin.as_deref()
499 }
500
501 pub fn mesh(&self) -> Option<&str> {
503 self.mesh.as_deref()
504 }
505
506 pub fn job(&self) -> Option<&str> {
508 self.job.as_deref()
509 }
510
511 pub fn cell_id(&self) -> &str {
513 &self.cell_id
514 }
515
516 pub fn asof(&self) -> Option<&str> {
518 self.asof.as_deref()
519 }
520}
521
522#[derive(Clone, Debug, PartialEq, Eq)]
524pub struct Envelope {
525 pub outcome: Outcome,
527 pub receipt: Option<Receipt>,
529 pub trust: Option<Trust>,
531 pub age_seconds: Option<u64>,
533 pub superseded_by: Option<String>,
535 pub reason: Option<String>,
537 pub quote: Option<Quote>,
539 pub retry_after_seconds: Option<u64>,
541 pub error: Option<ErrorCode>,
543}
544
545pub(crate) const BAD_REQUEST_CODES: [ErrorCode; 15] = [
546 ErrorCode::ParseUri,
547 ErrorCode::CanonName,
548 ErrorCode::CanonArgName,
549 ErrorCode::CanonArgDuplicate,
550 ErrorCode::CanonArgOrder,
551 ErrorCode::CanonPercent,
552 ErrorCode::CanonType,
553 ErrorCode::CanonNumber,
554 ErrorCode::CanonDate,
555 ErrorCode::CanonInstant,
556 ErrorCode::CanonString,
557 ErrorCode::CanonBlob,
558 ErrorCode::CanonLimit,
559 ErrorCode::ArgUnknown,
560 ErrorCode::ArgMissing,
561];
562
563pub(crate) fn env_err<T>(path: &str, detail: impl Into<String>) -> Result<T> {
564 err(ErrorCode::Envelope, path, detail)
565}
566
567pub(crate) fn integer_member(v: &Value, path: &str) -> Result<u64> {
569 let Some(t) = v.as_number_text() else {
570 return env_err(path, "must be a non-negative integer");
571 };
572 let ok =
573 !t.is_empty() && t.bytes().all(|c| c.is_ascii_digit()) && (t == "0" || !t.starts_with('0')) && t.len() <= 16;
574 match (ok, t.parse::<u64>()) {
575 (true, Ok(x)) if x <= limits::BLOB_LENGTH => Ok(x),
576 _ => env_err(path, format!("must be written 0|[1-9][0-9]* and at most 2^53 - 1, not {t}")),
577 }
578}
579
580pub fn check_envelope(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Envelope> {
590 check_envelope_extras(status, body, keys, request).map(|(env, _)| env)
591}
592
593pub fn check_envelope_extras(
604 status: u16,
605 body: &[u8],
606 keys: &Keys,
607 request: &Request,
608) -> Result<(Envelope, EnvelopeExtras)> {
609 crate::answer::check_answer(status, body, keys, request)?.into_envelope()
610}
611
612pub fn check_envelope_any(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<AnyEnvelope> {
619 let a = crate::answer::check_answer(status, body, keys, request)?;
620 if let Some(p) = a.pending {
621 return Ok(AnyEnvelope::Pending(p));
622 }
623 a.into_envelope().map(|(e, x)| AnyEnvelope::Envelope(e, x))
624}
625
626pub(crate) fn is_job(s: &str) -> bool {
628 (32..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
629}
630
631#[allow(clippy::large_enum_variant)]
635#[derive(Clone, Debug, PartialEq, Eq)]
636#[non_exhaustive]
637pub enum AnyEnvelope {
638 Envelope(Envelope, EnvelopeExtras),
641 Pending(Pending),
643}
644
645impl AnyEnvelope {
646 pub fn outcome_str(&self) -> &'static str {
648 match self {
649 AnyEnvelope::Envelope(e, _) => e.outcome.as_str(),
650 AnyEnvelope::Pending(_) => "pending",
651 }
652 }
653}
654
655#[derive(Clone, Debug, PartialEq, Eq, Hash)]
659#[non_exhaustive]
660pub struct Pending {
661 pub job: String,
663 pub estimate_seconds: u64,
665 pub poll: String,
668 pub request: Request,
670}
671
672impl Pending {
673 pub const STATUS: u16 = 202;
675
676 pub fn new(job: &str, estimate_seconds: u64, poll: &str, request: Request) -> Result<Pending> {
683 check_job_and_poll_for(job, poll, request.mesh())?;
684 if estimate_seconds > limits::BLOB_LENGTH {
685 return env_err("$.estimate_seconds", "estimate_seconds is at most 2^53 - 1");
686 }
687 let request = Request { job: None, mesh: None, ..request };
688 Ok(Pending { job: job.into(), estimate_seconds, poll: poll.into(), request })
689 }
690
691 pub fn to_value(&self) -> Value {
693 json::parse(&self.to_json()).unwrap_or(Value::Null)
695 }
696
697 pub fn to_json(&self) -> Vec<u8> {
699 let mut out = String::new();
700 out.push_str("{\"estimate_seconds\":");
701 out.push_str(&self.estimate_seconds.to_string());
702 out.push_str(",\"job\":");
703 json::write_string(&self.job, &mut out);
704 out.push_str(",\"outcome\":\"pending\",\"poll\":");
705 json::write_string(&self.poll, &mut out);
706 out.push_str(",\"request\":{");
707 if let Some(a) = &self.request.asof {
708 out.push_str("\"asof\":");
709 json::write_string(a, &mut out);
710 out.push(',');
711 }
712 out.push_str("\"cell_id\":");
713 json::write_string(&self.request.cell_id, &mut out);
714 if let Some(p) = &self.request.pin {
715 out.push_str(",\"fn_hash\":");
716 json::write_string(p, &mut out);
717 }
718 out.push_str("}}");
719 out.into_bytes()
720 }
721}
722
723pub(crate) fn check_job_and_poll_for(job: &str, poll: &str, mesh: Option<&str>) -> Result<()> {
726 if !is_job(job) {
727 return env_err("$.job", "job is 32 to 64 lowercase hex digits");
728 }
729 if poll.starts_with("http://") {
730 if !mesh.is_some_and(lexical::is_unrooted) {
731 return env_err("$.poll", "a loopback poll is only for an unrooted mesh the request names");
732 }
733 if lexical::loopback_origin(poll).is_none() || !poll.ends_with(&format!("/jobs/{job}")) {
734 return env_err("$.poll", "poll is a loopback URL ending /jobs/<job>");
735 }
736 return Ok(());
737 }
738 let url_ok =
739 poll.strip_prefix("https://").is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
740 && poll.len() <= limits::LICENCE_URL;
741 if !url_ok {
742 return env_err("$.poll", "poll is an https URL of printable ASCII, at most 512 characters");
743 }
744 let host = poll["https://".len()..].split('/').next().unwrap_or("");
746 if !poll["https://".len()..].contains('/') || lexical::check_dns_name(host, "").is_err() {
747 return env_err("$.poll", "poll's host is a DNS name");
748 }
749 if !poll.ends_with(&format!("/jobs/{job}")) {
750 return env_err("$.poll", "poll ends /jobs/<job>");
751 }
752 Ok(())
753}
754
755pub(crate) fn quote(q: &Value) -> Result<Quote> {
756 let m = schema::object_or(q, "$.quote", ErrorCode::Envelope, "quote")?;
757 schema::exact(m, &["amount", "authorise", "currency"], &[], "$.quote", ErrorCode::Envelope)?;
758 let amount = schema::string_or(m, "amount", "$.quote", ErrorCode::Envelope)?;
759 let authorise = schema::string_or(m, "authorise", "$.quote", ErrorCode::Envelope)?;
760 let currency = schema::string_or(m, "currency", "$.quote", ErrorCode::Envelope)?;
761 if lexical::check_number(amount, "").is_err() || amount.starts_with('-') || amount == "0" {
762 return env_err("$.quote.amount", "amount is a canonical decimal greater than zero");
763 }
764 let url_ok = authorise
765 .strip_prefix("https://")
766 .is_some_and(|r| !r.is_empty() && r.bytes().all(|c| (0x21..=0x7E).contains(&c)))
767 && authorise.len() <= limits::LICENCE_URL;
768 if !url_ok {
769 return env_err("$.quote.authorise", "authorise is an https URL");
770 }
771 if !lexical::is_currency(currency) {
772 return env_err("$.quote.currency", "currency is a currency code from units.md");
773 }
774 Ok(Quote { amount: amount.into(), currency: currency.into(), authorise: authorise.into() })
775}