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
//!
//! Tool's secrets.
//!
/// Internal namespace.
mod private
{
use crate::*;
use std::
{
env,
sync::OnceLock,
};
use error_tools::typed::Error;
use ser::DisplayFromStr;
/// Typed secret error.
#[ ser::serde_as ]
#[ derive( Debug, Error, ser::Serialize ) ]
#[ serde( tag = "type", content = "data" ) ]
pub enum Error
{
/// Secret file is illformed.
#[ error( "Secret file is illformed\n{0}" ) ]
SecretFileIllformed
(
#[ from ]
#[ serde_as( as = "DisplayFromStr" ) ]
dotenv::Error
),
/// Some variable in the secrets is missing.
#[ error( "Secret misssing the variable {0}" ) ]
VariableMissing( &'static str ),
/// Some variable in the secrets is illformed.
#[ error( "Secret error processing the variable {0}\n{1}" ) ]
VariableIllformed( &'static str, String ),
}
/// Result type for `Secret` methods.
pub type Result< R > = core::result::Result< R, Error >;
/// Represents the application secrets loaded from environment variables.
#[ derive( Debug ) ]
#[ allow( non_snake_case ) ]
pub struct Secret
{
/// OpenAI API key.
pub OPENAI_API_KEY : String,
}
impl Secret
{
/// Loads secrets from environment variables.
///
/// # Returns
///
/// * `Result< Self >` - On success, returns a `Secret` instance with values from environment variables.
/// * On failure, returns an error indicating which environment variable is missing or invalid.
#[ allow( non_snake_case ) ]
pub fn load() -> Result< Self >
{
let path = "./.key/-env.sh";
// Attempt to load environment variables from the specified file
let r = dotenv::from_filename( path );
if let Err( ref err ) = r
{
// Only return an error if it's not an Io error, and include the file path in the error message
if !matches!( err, dotenv::Error::Io( _ ) )
{
return Err( r.expect_err( &format!( "Failed to load {path}" ) ).into() );
}
}
let config = Self
{
OPENAI_API_KEY : var( "OPENAI_API_KEY", None )?,
};
Ok( config )
}
/// Reads the secrets, panicking with an explanation if loading fails.
///
/// # Returns
///
/// * `Secret` - The loaded secrets.
///
/// # Panics
///
/// * Panics with a detailed explanation if the secrets cannot be loaded.
pub fn read() -> Secret
{
Self::load().unwrap_or_else( | err |
{
let example = include_str!( "../.key/readme.md" );
let explanation = format!
(
r#" = Lack of secrets
Failed to load secret or some its parameters.
{err}
= Fix
Either define missing environment variable or make sure `./.key/-env.toml` file has it defined.
= More information
{example}
"#
);
panic!( "{}", explanation );
})
}
/// Retrieves a static reference to the secrets, initializing it if necessary.
///
/// # Returns
///
/// * `&'static Secret` - A static reference to the secrets.
///
/// # Warning
///
/// * Do not use this function unless absolutely necessary.
/// * Avoid using it in `lib.rs`.
pub fn get() -> &'static Secret
{
static INSTANCE : OnceLock< Secret > = OnceLock::new();
INSTANCE.get_or_init( || Self::read() )
}
}
/// Retrieves the value of an environment variable as a `String`.
///
/// This function attempts to fetch the value of the specified environment variable.
/// If the variable is not set, it returns a provided default value if available, or an error if not.
///
/// # Arguments
///
/// * `name` - The name of the environment variable to retrieve.
/// * `default` - An optional default value to return if the environment variable is not set.
///
/// # Returns
///
/// * `Result<String>` - On success, returns the value of the environment variable or the default value.
/// * On failure, returns an error indicating the missing environment variable.
fn var
(
name : &'static str,
default : Option< &'static str >,
) -> Result< String >
{
match env::var( name )
{
Ok( value ) => Ok( value ),
Err( _ ) =>
{
if let Some( default_value ) = default
{
Ok( default_value.to_string() )
}
else
{
Err( Error::VariableMissing( name ) )
}
}
}
}
/// Retrieves the value of an environment variable as an `AbsolutePath`.
///
/// This function attempts to fetch the value of the specified environment variable and convert it into an `AbsolutePath`.
/// If the variable is not set, it returns a provided default value if available, or an error if not.
///
/// # Arguments
///
/// * `name` - The name of the environment variable to retrieve.
/// * `default` - An optional default value to return if the environment variable is not set.
///
/// # Returns
///
/// * `Result<pth::AbsolutePath>` - On success, returns the parsed `AbsolutePath`.
/// * On failure, returns an error indicating the missing or ill-formed environment variable.
fn _var_path
(
name : &'static str,
default : Option< &'static str >,
) -> Result< pth::AbsolutePath >
{
let p = var( name, default )?;
pth::AbsolutePath::from_paths( ( pth::CurrentPath, p ) )
.map_err( |e| Error::VariableIllformed( name, e.to_string() ) )
}
}
crate::mod_interface!
{
own use
{
Error,
Result,
};
orphan use
{
Secret,
};
}