1use crate::discovery::read_source;
27use crate::paths::{ProjectPathsError, did_you_mean};
28use std::collections::{BTreeMap, HashMap};
29use std::path::{Path, PathBuf};
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct VectorizeDeploy {
34 pub index: BTreeMap<String, String>,
37}
38
39pub type VectorizeDeployConfig = BTreeMap<String, VectorizeDeploy>;
41
42pub const DEPLOY_ENTRY_KEYS: &[&str] = &["index"];
44
45fn bad(table: &'static str, capability: &str, reason: String) -> ProjectPathsError {
46 ProjectPathsError::BadVectorize {
47 table,
48 capability: capability.to_string(),
49 reason,
50 }
51}
52
53pub fn is_index_name(name: &str) -> bool {
57 (1..=64).contains(&name.len())
58 && name
59 .bytes()
60 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
61 && !name.starts_with('-')
62 && !name.ends_with('-')
63}
64
65pub fn deploy_vectorize_from(
67 deploy: &toml::Table,
68) -> Result<VectorizeDeployConfig, ProjectPathsError> {
69 let mut out = VectorizeDeployConfig::new();
70 let Some(value) = deploy.get("vectorize") else {
71 return Ok(out);
72 };
73 let all = value.as_table().ok_or_else(|| {
74 bad(
75 "deploy",
76 "…",
77 "`vectorize` must be a table of capabilities, like `[deploy.vectorize.Docs]`"
78 .to_string(),
79 )
80 })?;
81 for (capability, value) in all {
82 let table = "deploy.vectorize";
83 let entry = value
84 .as_table()
85 .ok_or_else(|| bad(table, capability, "must be a table".to_string()))?;
86 for key in entry.keys() {
87 if !DEPLOY_ENTRY_KEYS.contains(&key.as_str()) {
88 let hint = did_you_mean(key, DEPLOY_ENTRY_KEYS.iter().copied())
89 .map(|k| format!(" — did you mean `{k}`?"))
90 .unwrap_or_default();
91 return Err(bad(
92 table,
93 capability,
94 format!("has no key named `{key}`{hint} (its key is `index`)"),
95 ));
96 }
97 }
98 let Some(index) = entry.get("index") else {
99 return Err(bad(
100 table,
101 capability,
102 "needs an `index`, like `index = { production = \"docs-prod\" }`".to_string(),
103 ));
104 };
105 let names = index.as_table().ok_or_else(|| {
106 bad(
107 table,
108 capability,
109 "`index` must be a table of environment to index name, like `index = { production = \"docs-prod\" }`"
110 .to_string(),
111 )
112 })?;
113 let mut deploy = VectorizeDeploy::default();
114 for (environment, name) in names {
115 let name = name.as_str().filter(|n| is_index_name(n)).ok_or_else(|| {
116 bad(
117 table,
118 capability,
119 format!(
120 "`index.{environment}` must be a Vectorize index name: 1 to 64 lowercase letters, digits or `-`, not starting or ending with `-`, as `wrangler vectorize list` shows"
121 ),
122 )
123 })?;
124 deploy.index.insert(environment.clone(), name.to_string());
125 }
126 if deploy.index.is_empty() {
127 return Err(bad(
128 table,
129 capability,
130 "`index` names no environment".to_string(),
131 ));
132 }
133 out.insert(capability.clone(), deploy);
134 }
135 Ok(out)
136}
137
138pub fn try_read_vectorize_deploy_with(
141 project_root: &Path,
142 overlay: &HashMap<PathBuf, String>,
143) -> Result<VectorizeDeployConfig, ProjectPathsError> {
144 let Ok(content) = read_source(&project_root.join("bynk.toml"), overlay) else {
145 return Ok(VectorizeDeployConfig::new());
146 };
147 let doc = content
148 .parse::<toml::Table>()
149 .map_err(|_| ProjectPathsError::Malformed)?;
150 match doc.get("deploy").and_then(|v| v.as_table()) {
151 Some(t) => deploy_vectorize_from(t),
152 None => Ok(VectorizeDeployConfig::new()),
153 }
154}
155
156pub fn try_read_vectorize_deploy(
158 project_root: &Path,
159) -> Result<VectorizeDeployConfig, ProjectPathsError> {
160 let path = project_root.join("bynk.toml");
161 let overlay = match std::fs::read_to_string(&path) {
162 Ok(text) => HashMap::from([(path, text)]),
163 Err(_) => HashMap::new(),
164 };
165 try_read_vectorize_deploy_with(project_root, &overlay)
166}
167
168pub type VectorizeDevIndexes = BTreeMap<String, String>;
171
172pub fn dev_vectorize_index_from(
174 dev: &toml::Table,
175) -> Result<VectorizeDevIndexes, ProjectPathsError> {
176 let mut out = VectorizeDevIndexes::new();
177 let Some(value) = dev.get("vectorize-index") else {
178 return Ok(out);
179 };
180 let table = "dev.vectorize-index";
181 let all = value.as_table().ok_or_else(|| {
182 bad(
183 table,
184 "…",
185 "must be a table of capability to index name, like `Docs = \"docs-dev\"`".to_string(),
186 )
187 })?;
188 for (capability, name) in all {
189 let name = name.as_str().filter(|n| is_index_name(n)).ok_or_else(|| {
190 bad(
191 table,
192 capability,
193 "must be the name of a Vectorize index of your own: 1 to 64 lowercase letters, digits or `-`, not starting or ending with `-`, as `wrangler vectorize list` shows".to_string(),
194 )
195 })?;
196 out.insert(capability.clone(), name.to_string());
197 }
198 Ok(out)
199}
200
201pub fn try_read_vectorize_dev_with(
204 project_root: &Path,
205 overlay: &HashMap<PathBuf, String>,
206) -> Result<VectorizeDevIndexes, ProjectPathsError> {
207 let Ok(content) = read_source(&project_root.join("bynk.toml"), overlay) else {
208 return Ok(VectorizeDevIndexes::new());
209 };
210 let doc = content
211 .parse::<toml::Table>()
212 .map_err(|_| ProjectPathsError::Malformed)?;
213 match doc.get("dev").and_then(|v| v.as_table()) {
214 Some(t) => dev_vectorize_index_from(t),
215 None => Ok(VectorizeDevIndexes::new()),
216 }
217}
218
219pub fn try_read_vectorize_dev(
221 project_root: &Path,
222) -> Result<VectorizeDevIndexes, ProjectPathsError> {
223 let path = project_root.join("bynk.toml");
224 let overlay = match std::fs::read_to_string(&path) {
225 Ok(text) => HashMap::from([(path, text)]),
226 Err(_) => HashMap::new(),
227 };
228 try_read_vectorize_dev_with(project_root, &overlay)
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn a_dev_index_is_named_per_capability() {
237 let dev = |text: &str| {
238 let doc: toml::Table = text.parse().unwrap();
239 dev_vectorize_index_from(doc["dev"].as_table().unwrap()).map_err(|e| e.to_string())
240 };
241 let read = dev("[dev.vectorize-index]\nDocs = \"docs-dev\"\n").unwrap();
242 assert_eq!(read["Docs"], "docs-dev");
243 assert!(dev("[dev]\n").unwrap().is_empty());
244 let err = dev("[dev.vectorize-index]\nDocs = \"Docs_Dev\"\n").unwrap_err();
245 assert!(
246 err.contains("Docs") && err.contains("name of a Vectorize index"),
247 "{err}"
248 );
249 assert!(
250 dev("[dev]\nvectorize-index = 3\n")
251 .unwrap_err()
252 .contains("table of capability")
253 );
254 }
255
256 fn deploy(text: &str) -> Result<VectorizeDeployConfig, String> {
257 let doc: toml::Table = text.parse().unwrap();
258 deploy_vectorize_from(doc["deploy"].as_table().unwrap()).map_err(|e| e.to_string())
259 }
260
261 #[test]
262 fn an_environment_names_an_existing_index() {
263 let read = deploy(
264 "[deploy.vectorize.Docs]\nindex = { production = \"docs-prod\", default = \"docs\" }\n",
265 )
266 .unwrap();
267 assert_eq!(read["Docs"].index["production"], "docs-prod");
268 assert_eq!(read["Docs"].index["default"], "docs");
269 assert!(deploy("[deploy]\n").unwrap().is_empty());
270 }
271
272 #[test]
273 fn a_malformed_entry_is_refused_naming_the_capability() {
274 let err = |text: &str| deploy(text).unwrap_err();
275 assert!(err("[deploy.vectorize.Docs]\n").contains("needs an `index`"));
276 assert!(
277 err("[deploy.vectorize.Docs]\nindex = \"docs\"\n").contains("table of environment")
278 );
279 assert!(err("[deploy.vectorize.Docs]\nindex = {}\n").contains("names no environment"));
280 assert!(
281 err("[deploy.vectorize.Docs]\nindex = { production = \"Docs_Prod\" }\n")
282 .contains("`index.production` must be a Vectorize index name")
283 );
284 let unknown = err("[deploy.vectorize.Docs]\nindexes = { a = \"b\" }\n");
285 assert!(
286 unknown.contains("no key named `indexes`") && unknown.contains("did you mean `index`"),
287 "{unknown}"
288 );
289 assert!(err("[deploy]\nvectorize = 3\n").contains("table of capabilities"));
290 }
291
292 #[test]
293 fn an_index_name_is_kebab_case_of_at_most_64_bytes() {
294 assert!(is_index_name("docs-prod"));
295 assert!(is_index_name(&"a".repeat(64)));
296 assert!(!is_index_name(&"a".repeat(65)));
297 for bad in ["", "-a", "a-", "A", "a_b", "a b", "a/b", "a..b"] {
298 assert!(!is_index_name(bad), "{bad}");
299 }
300 }
301}