1use crate::{AsCrn, Crn, Region};
2use arrayvec::ArrayString;
3#[cfg(feature = "server")]
4use http::HeaderValue;
5use miette::Diagnostic;
6use serde::{Deserialize, Deserializer, Serialize};
7use std::{fmt::Display, str::FromStr};
8use thiserror::Error;
9use utoipa::ToSchema;
10use vitaminc::encrypt::{Aad, IntoAad};
11use vitaminc::random::{Generatable, SafeRand};
12
13const WORKSPACE_ID_BYTE_LEN: usize = 10;
14const WORKSPACE_ID_ENCODED_LEN: usize = 16;
15const ALPHABET: base32::Alphabet = base32::Alphabet::Rfc4648 { padding: false };
16
17type WorkspaceIdArrayString = ArrayString<WORKSPACE_ID_ENCODED_LEN>;
18
19#[derive(Error, Debug, Diagnostic)]
20#[error("Invalid workspace ID: {0}")]
21#[diagnostic(help = "Workspace IDs are 10-byte random strings formatted in base32.")]
22pub struct InvalidWorkspaceId(String);
23
24#[derive(Error, Debug)]
25#[error("Failed to generate workspace ID")]
26pub struct WorkspaceIdGenerationError(#[from] vitaminc::random::RandomError);
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub struct Workspace {
31 id: WorkspaceId,
32 region: Region,
33 #[serde(default = "default_workspace_name")]
34 #[serde(deserialize_with = "deserialize_workspace_name")]
35 name: String,
36}
37
38impl AsCrn for Workspace {
39 fn as_crn(&self) -> crate::Crn {
40 Crn::new(self.region, self.id)
41 }
42}
43
44fn deserialize_workspace_name<'d, D>(deserializer: D) -> Result<String, D::Error>
45where
46 D: Deserializer<'d>,
47{
48 let opt = Option::deserialize(deserializer)?;
49 Ok(opt.unwrap_or("unnamed workspace".to_string()))
50}
51
52impl Workspace {
53 pub fn new(id: WorkspaceId, region: Region, name: impl Into<String>) -> Self {
54 Self {
55 id,
56 region,
57 name: name.into(),
58 }
59 }
60
61 pub fn id(&self) -> WorkspaceId {
64 self.id
65 }
66
67 pub fn crn(&self) -> Crn {
68 Crn::new(self.region, self.id)
69 }
70
71 pub fn name(&self) -> &str {
72 self.name.as_str()
73 }
74
75 pub fn region(&self) -> Region {
76 self.region
77 }
78}
79
80fn default_workspace_name() -> String {
81 "Default".to_string()
82}
83
84#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
125#[serde(transparent)]
126#[cfg_attr(
127 feature = "server",
128 derive(diesel::expression::AsExpression, diesel::deserialize::FromSqlRow)
129)]
130#[schema(value_type = String, example = "JBSWY3DPEHPK3PXP")]
131#[cfg_attr(feature = "server", diesel(sql_type = diesel::sql_types::Text))]
132pub struct WorkspaceId(WorkspaceIdArrayString);
133
134impl WorkspaceId {
135 pub fn generate() -> Result<Self, WorkspaceIdGenerationError> {
138 let mut rng = SafeRand::from_entropy()?;
139 Ok(Self::random(&mut rng)?)
140 }
141
142 pub fn as_str(&self) -> &str {
143 self.0.as_str()
144 }
145}
146
147impl<'a> IntoAad<'a> for WorkspaceId {
155 fn into_aad(self) -> Aad<'a> {
156 Aad::new_owned(self.as_str().bytes())
157 }
158}
159
160impl PartialEq<&str> for WorkspaceId {
161 fn eq(&self, other: &&str) -> bool {
162 self.0.as_str() == *other
163 }
164}
165
166impl PartialEq<String> for WorkspaceId {
167 fn eq(&self, other: &String) -> bool {
168 self.0.as_str() == other.as_str()
169 }
170}
171
172impl TryFrom<String> for WorkspaceId {
173 type Error = InvalidWorkspaceId;
174
175 fn try_from(value: String) -> Result<Self, Self::Error> {
176 value.as_str().try_into()
177 }
178}
179
180impl TryFrom<&str> for WorkspaceId {
181 type Error = InvalidWorkspaceId;
182
183 fn try_from(value: &str) -> Result<Self, Self::Error> {
184 if is_valid_workspace_id(value) {
185 let mut array_str = WorkspaceIdArrayString::new();
186 array_str.push_str(value);
187 Ok(Self(array_str))
188 } else {
189 Err(InvalidWorkspaceId(value.to_string()))
190 }
191 }
192}
193
194impl FromStr for WorkspaceId {
195 type Err = InvalidWorkspaceId;
196
197 fn from_str(value: &str) -> Result<Self, Self::Err> {
198 Self::try_from(value)
199 }
200}
201
202impl From<WorkspaceId> for String {
203 fn from(value: WorkspaceId) -> Self {
204 value.0.to_string()
205 }
206}
207
208impl Generatable for WorkspaceId {
209 fn random(rng: &mut vitaminc::random::SafeRand) -> Result<Self, vitaminc::random::RandomError> {
210 let buf: [u8; WORKSPACE_ID_BYTE_LEN] = Generatable::random(rng)?;
211 let id = base32::encode(ALPHABET, &buf);
212 let mut array_str = WorkspaceIdArrayString::new();
213 array_str.push_str(&id);
214 Ok(Self(array_str))
215 }
216}
217
218impl Display for WorkspaceId {
219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
220 write!(f, "{}", self.0)
221 }
222}
223
224#[cfg(feature = "server")]
226impl TryInto<HeaderValue> for WorkspaceId {
227 type Error = http::header::InvalidHeaderValue;
228
229 fn try_into(self) -> Result<HeaderValue, Self::Error> {
230 HeaderValue::from_str(self.0.as_str())
231 }
232}
233
234fn is_valid_workspace_id(workspace_id: &str) -> bool {
237 if let Some(bytes) = base32::decode(ALPHABET, workspace_id) {
238 bytes.len() == WORKSPACE_ID_BYTE_LEN
239 } else {
240 false
241 }
242}
243
244#[cfg(feature = "test_utils")]
245mod testing {
246 use super::*;
247 use fake::Faker;
248 use rand::Rng;
249
250 impl fake::Dummy<Faker> for WorkspaceId {
251 fn dummy_with_rng<R: Rng + ?Sized>(_: &Faker, _: &mut R) -> Self {
252 WorkspaceId::generate().unwrap()
253 }
254 }
255}
256
257#[cfg(feature = "server")]
258mod sql_types {
259 use super::WorkspaceId;
260 use diesel::{
261 backend::Backend,
262 deserialize::{self, FromSql},
263 serialize::{self, Output, ToSql},
264 sql_types::Text,
265 };
266
267 impl<DB> ToSql<Text, DB> for WorkspaceId
268 where
269 DB: Backend,
270 str: ToSql<Text, DB>,
271 {
272 fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
273 self.0.to_sql(out)
274 }
275 }
276
277 impl<DB> FromSql<Text, DB> for WorkspaceId
278 where
279 DB: Backend,
280 String: FromSql<Text, DB>,
281 {
282 fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
283 let raw = String::from_sql(bytes)?;
284 let workspace_id = WorkspaceId::try_from(raw)?;
285
286 Ok(workspace_id)
287 }
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 mod workspace_id {
296 use super::*;
297
298 #[test]
299 fn generation_is_valid() {
300 let mut rng = vitaminc::random::SafeRand::from_entropy().unwrap();
301 let id = WorkspaceId::random(&mut rng).unwrap();
302 assert!(WorkspaceId::try_from(id.to_string()).is_ok());
303 }
304
305 #[test]
306 fn invalid_id() {
307 assert!(WorkspaceId::try_from("invalid-id").is_err());
308 }
309 }
310
311 mod workspace {
312 use super::*;
313
314 #[test]
315 fn serialize() -> anyhow::Result<()> {
316 let workspace = Workspace {
317 id: WorkspaceId::generate()?,
318 region: Region::new("us-west-1.aws")?,
319 name: "test-workspace".to_string(),
320 };
321
322 let serialized = serde_json::to_string(&workspace)?;
323 assert_eq!(
324 serialized,
325 format!(
326 "{{\"id\":\"{}\",\"region\":\"us-west-1.aws\",\"name\":\"test-workspace\"}}",
327 workspace.id
328 )
329 );
330
331 Ok(())
332 }
333
334 #[test]
335 fn desirialise_with_null_workspace_name() {
336 let mut rng = vitaminc::random::SafeRand::from_entropy().unwrap();
337 let id = WorkspaceId::random(&mut rng).unwrap();
338 let serialised =
339 format!("{{\"id\":\"{id}\",\"region\":\"us-west-1.aws\",\"name\":null}}",);
340
341 let deserialized: Workspace = serde_json::from_str(&serialised).unwrap();
342 assert_eq!("unnamed workspace".to_string(), deserialized.name,);
343 }
344 }
345}