-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstore_id.rs
More file actions
254 lines (207 loc) · 7 KB
/
store_id.rs
File metadata and controls
254 lines (207 loc) · 7 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
use std::{io::ErrorKind, sync::Mutex};
#[cfg(test)]
use std::collections::HashMap;
use crate::{fs::json, prelude::*};
use ic_agent::export::Principal;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
/// Trait for accessing and managing canister ID storage.
pub trait Access: Sync + Send {
/// Register a canister ID for a given key.
fn register(&self, key: &Key, cid: &Principal) -> Result<(), RegisterError>;
/// Lookup a canister ID for a given key.
fn lookup(&self, key: &Key) -> Result<Principal, LookupIdError>;
/// Lookup all canister IDs for a given environment.
fn lookup_by_environment(
&self,
environment: &str,
) -> Result<Vec<(String, Principal)>, LookupIdError>;
}
/// An association-key, used for associating an existing canister to an ID on a network
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Key {
/// Environment name
pub environment: String,
/// Canister name
pub canister: String,
}
/// Association of a canister name and an ID
#[derive(Clone, Debug, Serialize, Deserialize)]
struct Association(Key, Principal);
#[derive(Debug, Snafu)]
pub enum RegisterError {
#[snafu(display("failed to load canister id store"))]
RegisterLoadStore { source: json::Error },
#[snafu(display(
"canister '{}' in environment '{}' is already registered with id '{id}'",
key.canister, key.environment,
))]
AlreadyRegistered { key: Key, id: Principal },
#[snafu(display("failed to save canister id store"))]
RegisterSaveStore { source: json::Error },
}
#[derive(Debug, Snafu)]
pub enum LookupIdError {
#[snafu(display("failed to load canister id store"))]
LookupLoadStore { source: json::Error },
#[snafu(display(
"could not find ID for canister '{}' in environment '{}'",
key.canister, key.environment
))]
IdNotFound { key: Key },
#[snafu(display("could not find canisters in environment '{}'", name))]
EnvironmentNotFound { name: String },
}
pub(crate) struct IdStore {
path: PathBuf,
lock: Mutex<()>,
}
impl IdStore {
pub(crate) fn new(path: &Path) -> Self {
Self {
path: path.to_owned(),
lock: Mutex::new(()),
}
}
}
impl Access for IdStore {
fn register(&self, key: &Key, cid: &Principal) -> Result<(), RegisterError> {
// Lock ID Store
let _g = self.lock.lock().expect("failed to acquire id store lock");
// Load JSON
let mut cs = json::load::<Vec<Association>>(&self.path)
.or_else(|err| match err {
// Default to empty
json::Error::Io(err) if err.kind() == ErrorKind::NotFound => Ok(vec![]),
// Other
_ => Err(err),
})
.context(RegisterLoadStoreSnafu)?;
// Check for existence
for Association(k, cid) in cs.iter() {
if k.canister == key.canister {
return Err(RegisterError::AlreadyRegistered {
key: key.to_owned(),
id: *cid,
});
}
}
// Append
cs.push(Association(key.to_owned(), cid.to_owned()));
// Store JSON
json::save(&self.path, &cs).context(RegisterSaveStoreSnafu)?;
Ok(())
}
fn lookup(&self, key: &Key) -> Result<Principal, LookupIdError> {
// Lock ID Store
let _g = self.lock.lock().expect("failed to acquire id store lock");
// Load JSON
let cs = json::load::<Vec<Association>>(&self.path)
.or_else(|err| match err {
// Default to empty
json::Error::Io(err) if err.kind() == ErrorKind::NotFound => Ok(vec![]),
// Other
_ => Err(err),
})
.context(LookupLoadStoreSnafu)?;
// Search for association
for Association(k, cid) in cs {
if k.canister == key.canister {
return Ok(cid.to_owned());
}
}
// Not Found
Err(LookupIdError::IdNotFound {
key: key.to_owned(),
})
}
fn lookup_by_environment(
&self,
environment: &str,
) -> Result<Vec<(String, Principal)>, LookupIdError> {
// Lock ID Store
let _g = self.lock.lock().expect("failed to acquire id store lock");
// Load JSON
let cs = json::load::<Vec<Association>>(&self.path)
.or_else(|err| match err {
// Default to empty
json::Error::Io(err) if err.kind() == ErrorKind::NotFound => Ok(vec![]),
// Other
_ => Err(err),
})
.context(LookupLoadStoreSnafu)?;
let filtered_associations: Vec<(String, Principal)> = cs
.into_iter()
.filter(|Association(k, _)| k.environment == *environment)
.map(|Association(k, cid)| (k.canister, cid))
.collect();
if filtered_associations.is_empty() {
return Err(LookupIdError::EnvironmentNotFound {
name: environment.to_owned(),
});
}
Ok(filtered_associations)
}
}
#[cfg(test)]
/// In-memory mock implementation of `Access`.
pub(crate) struct MockInMemoryIdStore {
store: Mutex<HashMap<Key, Principal>>,
}
#[cfg(test)]
impl MockInMemoryIdStore {
/// Creates a new empty in-memory ID store.
pub(crate) fn new() -> Self {
Self {
store: Mutex::new(HashMap::new()),
}
}
}
#[cfg(test)]
impl Default for MockInMemoryIdStore {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
impl Access for MockInMemoryIdStore {
fn register(&self, key: &Key, cid: &Principal) -> Result<(), RegisterError> {
let mut store = self.store.lock().unwrap();
// Check if canister already registered
if let Some(existing_cid) = store.get(key) {
return Err(RegisterError::AlreadyRegistered {
key: key.to_owned(),
id: *existing_cid,
});
}
// Store the association
store.insert(key.clone(), *cid);
Ok(())
}
fn lookup(&self, key: &Key) -> Result<Principal, LookupIdError> {
let store = self.store.lock().unwrap();
match store.get(key) {
Some(cid) => Ok(*cid),
None => Err(LookupIdError::IdNotFound {
key: key.to_owned(),
}),
}
}
fn lookup_by_environment(
&self,
environment: &str,
) -> Result<Vec<(String, Principal)>, LookupIdError> {
let store = self.store.lock().unwrap();
let filtered: Vec<(String, Principal)> = store
.iter()
.filter(|(k, _)| k.environment == environment)
.map(|(k, cid)| (k.canister.clone(), *cid))
.collect();
if filtered.is_empty() {
return Err(LookupIdError::EnvironmentNotFound {
name: environment.to_owned(),
});
}
Ok(filtered)
}
}