1use std::path::Path;
6use std::sync::Arc;
7
8use adk_site::content::SiteProject;
9use adk_site::generator::{BuildReport, ChangeSet, SiteGenerator};
10use adk_site::{Result, SiteError};
11use async_trait::async_trait;
12use uuid::Uuid;
13
14use super::{Arm, ExperimentPlan, ExperimentStore, SCRIPT, SCRIPT_PATH, VARIANT_DIR};
15
16pub struct ExperimentGenerator {
40 inner: Arc<dyn SiteGenerator>,
41 store: Arc<dyn ExperimentStore>,
42 site: Uuid,
43 beacon: String,
44}
45
46impl std::fmt::Debug for ExperimentGenerator {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.debug_struct("ExperimentGenerator")
49 .field("site", &self.site)
50 .field("beacon", &self.beacon)
51 .finish_non_exhaustive()
52 }
53}
54
55impl ExperimentGenerator {
56 pub fn new(
59 inner: Arc<dyn SiteGenerator>,
60 store: Arc<dyn ExperimentStore>,
61 site: Uuid,
62 beacon: impl Into<String>,
63 ) -> Self {
64 Self { inner, store, site, beacon: beacon.into() }
65 }
66
67 async fn apply(&self, out: &Path, report: &mut BuildReport) -> Result<()> {
69 let records = self.store.list(self.site).await.map_err(|error| {
70 SiteError::Pipeline(format!("the experiment store could not be read: {error}"))
71 })?;
72 let mut running = false;
73 for record in &records {
74 let plan = &record.plan;
75 let (Ok(control), Ok(variant)) = (plan.control_file(), plan.variant_file()) else {
77 continue;
78 };
79 let goals: Vec<String> = plan
80 .goal_pages
81 .iter()
82 .filter_map(|page| super::page_file(&plan.id, page).ok())
83 .collect();
84 let mut pages = Vec::new();
86 for file in std::iter::once(&control).chain(&goals) {
87 if let Some(html) = read_html(out, file).await? {
88 pages.push((file.clone(), strip_tag(&html, &plan.id)));
89 }
90 }
91 let built = if record.status.is_running() {
92 self.variant_of(plan, &control, &pages)
93 } else {
94 None
95 };
96 match built {
97 Some(variant_html) => {
98 running = true;
99 for (file, html) in &mut pages {
100 let arm = if *file == control { Some(Arm::Control) } else { None };
101 *html =
102 insert_head(html, &self.tag(plan, arm)).unwrap_or_else(|| html.clone());
103 }
104 write_if_changed(out, &variant, &variant_html, report).await?;
105 }
106 None => remove_file(out, &variant, report).await?,
107 }
108 for (file, html) in &pages {
109 write_if_changed(out, file, html, report).await?;
110 }
111 }
112 let script = SCRIPT_PATH.trim_start_matches('/');
113 if running {
114 write_if_changed(out, script, SCRIPT, report).await?;
115 } else {
116 remove_file(out, script, report).await?;
117 }
118 Ok(())
119 }
120
121 fn variant_of(
123 &self,
124 plan: &ExperimentPlan,
125 control: &str,
126 pages: &[(String, String)],
127 ) -> Option<String> {
128 let Some((_, html)) = pages.iter().find(|(file, _)| file == control) else {
129 tracing::warn!(experiment = %plan.id, page = %plan.page, "experiment left out of the build: its control page was not built");
130 return None;
131 };
132 let mut variant = html.clone();
133 for change in &plan.variant {
134 if !variant.contains(&change.find) {
135 tracing::warn!(experiment = %plan.id, page = %plan.page, "experiment left out of the build: its control page no longer holds a change's text");
136 return None;
137 }
138 variant = variant.replace(&change.find, &change.replace);
139 }
140 let head = format!(
141 "<meta name=\"robots\" content=\"noindex\">\n{}",
142 self.tag(plan, Some(Arm::Variant))
143 );
144 let variant = insert_head(&variant, &head);
145 if variant.is_none() {
146 tracing::warn!(experiment = %plan.id, page = %plan.page, "experiment left out of the build: its control page has no </head>");
147 }
148 variant
149 }
150
151 fn tag(&self, plan: &ExperimentPlan, arm: Option<Arm>) -> String {
153 let mut tag = format!(
154 "<script src=\"{SCRIPT_PATH}\" data-awp-experiment=\"{}\" data-arm=\"{}\"",
155 plan.id,
156 arm.map_or("", Arm::letter)
157 );
158 if let Some(arm) = arm {
159 tag.push_str(&format!(" data-allocation=\"{}\"", plan.allocation));
160 if arm == Arm::Control {
161 tag.push_str(&format!(" data-variant=\"{}\"", escape(&plan.variant_url())));
162 }
163 }
164 tag.push_str(&format!(" data-beacon=\"{}\"></script>", escape(&self.beacon)));
165 tag
166 }
167}
168
169#[async_trait]
170impl SiteGenerator for ExperimentGenerator {
171 async fn build(&self, project: &SiteProject, out: &Path) -> Result<BuildReport> {
172 let mut report = self.inner.build(project, out).await?;
173 self.apply(out, &mut report).await?;
174 Ok(report)
175 }
176
177 async fn build_incremental(
178 &self,
179 project: &SiteProject,
180 out: &Path,
181 changes: &ChangeSet,
182 ) -> Result<BuildReport> {
183 let mut report = self.inner.build_incremental(project, out, changes).await?;
184 self.apply(out, &mut report).await?;
185 Ok(report)
186 }
187}
188
189fn escape(value: &str) -> String {
191 value.replace('&', "&").replace('"', """).replace('<', "<").replace('>', ">")
192}
193
194fn insert_head(html: &str, head: &str) -> Option<String> {
196 let at = html.to_ascii_lowercase().find("</head>")?;
197 Some(format!("{}{head}\n{}", &html[..at], &html[at..]))
198}
199
200fn strip_tag(html: &str, id: &str) -> String {
202 let start_marker = format!("<script src=\"{SCRIPT_PATH}\" data-awp-experiment=\"{id}\"");
203 let mut html = html.to_string();
204 while let Some(start) = html.find(&start_marker) {
205 let Some(close) = html[start..].find("</script>") else { break };
206 let mut end = start + close + "</script>".len();
207 if html[end..].starts_with('\n') {
208 end += 1;
209 }
210 html.replace_range(start..end, "");
211 }
212 html
213}
214
215async fn read_html(out: &Path, file: &str) -> Result<Option<String>> {
216 let path = out.join(file);
217 match tokio::fs::read(&path).await {
218 Ok(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
219 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
220 Err(source) => Err(SiteError::Io { path, source }),
221 }
222}
223
224async fn write_if_changed(
226 out: &Path,
227 file: &str,
228 content: &str,
229 report: &mut BuildReport,
230) -> Result<()> {
231 let path = out.join(file);
232 let same = matches!(tokio::fs::read(&path).await, Ok(bytes) if bytes == content.as_bytes());
233 if !same {
234 if let Some(parent) = path.parent() {
235 tokio::fs::create_dir_all(parent)
236 .await
237 .map_err(|source| SiteError::Io { path: parent.to_path_buf(), source })?;
238 }
239 tokio::fs::write(&path, content)
240 .await
241 .map_err(|source| SiteError::Io { path: path.clone(), source })?;
242 report.written.insert(file.to_string());
243 }
244 report.outputs.insert(file.to_string());
245 report.removed.remove(file);
246 Ok(())
247}
248
249async fn remove_file(out: &Path, file: &str, report: &mut BuildReport) -> Result<()> {
251 let path = out.join(file);
252 match tokio::fs::remove_file(&path).await {
253 Ok(()) => {
254 report.removed.insert(file.to_string());
255 if file.starts_with(VARIANT_DIR) {
256 let mut dir = path.parent();
258 while let Some(current) = dir.filter(|d| d.starts_with(out.join(VARIANT_DIR))) {
259 if tokio::fs::remove_dir(current).await.is_err() {
260 break;
261 }
262 dir = current.parent();
263 }
264 }
265 }
266 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
267 Err(source) => return Err(SiteError::Io { path, source }),
268 }
269 report.outputs.remove(file);
270 report.written.remove(file);
271 Ok(())
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 #[test]
279 fn tags_strip_cleanly() {
280 let html = "<html><head><title>x</title>\n</head><body></body></html>";
281 let tag = format!(
282 "<script src=\"{SCRIPT_PATH}\" data-awp-experiment=\"h\" data-arm=\"a\"></script>"
283 );
284 let with = insert_head(html, &tag).unwrap();
285 assert!(with.contains(&tag));
286 assert_eq!(strip_tag(&with, "h"), html);
287 assert_eq!(strip_tag(&with, "other"), with, "another experiment's tag stays");
288 assert_eq!(insert_head("<p>no head</p>", &tag), None);
289 }
290
291 #[test]
292 fn attribute_values_are_escaped() {
293 assert_eq!(
294 escape("https://e.example/b?a=1&b=\"2\""),
295 "https://e.example/b?a=1&b="2""
296 );
297 }
298}