forked from ucan-wg/rs-ucan
/
update.rs
298 lines (255 loc) · 8.35 KB
/
update.rs
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
//! Update existing resources.
use crate::{
ability::{arguments, command::Command},
invocation::promise,
ipld,
};
use libipld_core::ipld::Ipld;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;
#[cfg_attr(doc, aquamarine::aquamarine)]
/// The executable/dispatchable variant of the `crud/create` ability.
///
/// # Lifecycle
///
/// The relevant hierarchy of CRUD abilities is as follows:
///
/// ```mermaid
/// flowchart LR
/// subgraph Delegations
/// top("*")
///
/// subgraph CRUD Abilities
/// any("crud/*")
///
/// mutate("crud/mutate")
///
/// subgraph Invokable
/// update("crud/update")
/// end
/// end
/// end
///
/// updatepromise("crud::update::Promised")
/// updateready("crud::update::Update")
///
/// top --> any --> mutate --> update
/// update -.->|invoke| updatepromise -.->|resolve| updateready -.-> exe{{execute}}
///
/// style updateready stroke:orange;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Update {
/// An optional path to a sub-resource that is to be updated.
#[serde(default, skip_serializing_if = "Option::is_none")]
path: Option<PathBuf>,
/// Optional arguments to be passed in the update.
#[serde(default, skip_serializing_if = "Option::is_none")]
args: Option<arguments::Named<Ipld>>,
}
#[cfg_attr(doc, aquamarine::aquamarine)]
/// An invoked `crud/update` ability (but possibly awaiting another
/// [`Invocation`][crate::invocation::Invocation]).
///
/// # Delegation Hierarchy
///
/// The hierarchy of CRUD abilities is as follows:
///
/// ```mermaid
/// flowchart LR
/// subgraph Delegations
/// top("*")
///
/// subgraph CRUD Abilities
/// any("crud/*")
///
/// mutate("crud/mutate")
///
/// subgraph Invokable
/// update("crud/update")
/// end
/// end
/// end
///
/// updatepromise("crud::update::Promised")
/// updateready("crud::update::Update")
///
/// top --> any --> mutate --> update
/// update -.->|invoke| updatepromise -.->|resolve| updateready -.-> exe{{execute}}
///
/// style updatepromise stroke:orange;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PromisedUpdate {
/// An optional path to a sub-resource that is to be updated.
#[serde(default, skip_serializing_if = "Option::is_none")]
path: Option<promise::Any<PathBuf>>,
/// Optional arguments to be passed in the update.
#[serde(default, skip_serializing_if = "Option::is_none")]
args: Option<promise::Any<arguments::Named<ipld::Promised>>>,
}
const COMMAND: &'static str = "/crud/update";
impl Command for Update {
const COMMAND: &'static str = COMMAND;
}
impl Command for PromisedUpdate {
const COMMAND: &'static str = COMMAND;
}
impl TryFrom<arguments::Named<ipld::Promised>> for PromisedUpdate {
type Error = FromPromisedArgsError;
fn try_from(named: arguments::Named<ipld::Promised>) -> Result<Self, Self::Error> {
let mut path = None;
let mut args = None;
for (key, prom) in named {
match key.as_str() {
"path" => match Ipld::try_from(prom) {
Err(pending) => {
path = Some(pending.into());
}
Ok(ipld) => match ipld {
Ipld::String(s) => path = Some(promise::Any::Resolved(PathBuf::from(s))),
other => return Err(FromPromisedArgsError::PathBodyNotAString(other)),
},
},
"args" => match prom {
ipld::Promised::Map(map) => {
args = Some(promise::Any::Resolved(arguments::Named(map)))
}
ipld::Promised::WaitOk(cid) => args = Some(promise::Any::PendingOk(cid)),
ipld::Promised::WaitErr(cid) => args = Some(promise::Any::PendingErr(cid)),
ipld::Promised::WaitAny(cid) => {
args = Some(promise::Any::PendingAny(cid));
}
_ => return Err(FromPromisedArgsError::InvalidArgs(prom)),
},
_ => return Err(FromPromisedArgsError::InvalidMapKey(key)),
}
}
Ok(PromisedUpdate { path, args })
}
}
#[derive(Error, Debug, PartialEq, Clone)]
pub enum FromPromisedArgsError {
#[error("Path body is not a string")]
PathBodyNotAString(Ipld),
#[error("Invalid args {0}")]
InvalidArgs(ipld::Promised),
#[error("Invalid map key {0}")]
InvalidMapKey(String),
}
impl TryFrom<arguments::Named<Ipld>> for Update {
type Error = ();
fn try_from(named: arguments::Named<Ipld>) -> Result<Self, Self::Error> {
let mut path = None;
let mut args = None;
for (key, ipld) in named {
match key.as_str() {
"path" => {
if let Ipld::String(s) = ipld {
path = Some(PathBuf::from(s));
} else {
return Err(());
}
}
"args" => {
if let Ipld::Map(map) = ipld {
args = Some(arguments::Named(map));
} else {
return Err(());
}
}
_ => return Err(()),
}
}
Ok(Update { path, args })
}
}
impl From<Update> for arguments::Named<Ipld> {
fn from(create: Update) -> Self {
let mut named = arguments::Named::<Ipld>::new();
if let Some(path) = create.path {
named.insert("path".to_string(), Ipld::String(path.display().to_string()));
}
if let Some(args) = create.args {
named.insert("args".to_string(), args.into());
}
named
}
}
impl TryFrom<Ipld> for Update {
type Error = TryFromIpldError;
fn try_from(ipld: Ipld) -> Result<Self, Self::Error> {
if let Ipld::Map(map) = ipld {
if map.len() > 2 {
return Err(TryFromIpldError::TooManyKeys);
}
Ok(Update {
path: map
.get("path")
.map(|ipld| {
(ipld::Newtype(ipld.clone()))
.try_into()
.map_err(TryFromIpldError::InvalidPath)
})
.transpose()?,
args: map
.get("args")
.map(|ipld| {
arguments::Named::<Ipld>::try_from(ipld.clone())
.map_err(|_| TryFromIpldError::InvalidArgs)
})
.transpose()?,
})
} else {
Err(TryFromIpldError::NotAMap)
}
}
}
#[derive(Error, Debug, PartialEq, Clone)]
pub enum TryFromIpldError {
#[error("Not a map")]
NotAMap,
#[error("Too many keys")]
TooManyKeys,
#[error("Invalid path: {0}")]
InvalidPath(ipld::newtype::NotAString),
#[error("Invalid args: not a map")]
InvalidArgs,
}
#[derive(Error, Debug, PartialEq, Clone)]
pub enum FromPromisedUpdateError {
#[error("Unresolved args")]
UnresolvedArgs(promise::Any<arguments::Named<ipld::Promised>>),
#[error("Args pending")]
ArgsPending(<Ipld as TryFrom<ipld::Promised>>::Error),
#[error("Invalid map key {0}")]
InvalidMapKey(String),
}
impl From<Update> for PromisedUpdate {
fn from(r: Update) -> PromisedUpdate {
PromisedUpdate {
path: r.path.map(|inner_path| promise::Any::Resolved(inner_path)),
args: r
.args
.map(|inner_args| promise::Any::Resolved(inner_args.into())),
}
}
}
impl promise::Resolvable for Update {
type Promised = PromisedUpdate;
}
impl From<PromisedUpdate> for arguments::Named<ipld::Promised> {
fn from(promised: PromisedUpdate) -> Self {
let mut named = arguments::Named::new();
if let Some(path) = promised.path {
named.insert("path".to_string(), path.to_promised_ipld());
}
if let Some(args) = promised.args {
named.insert("args".to_string(), args.to_promised_ipld());
}
named
}
}