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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use terraphim_atomic_client::{store::Store, types::Config, Agent};
use terraphim_persistence::Persistable;
use terraphim_types::{Document, Index};
use crate::{indexer::IndexMiddleware, Result};
use terraphim_config::Haystack;
/// Middleware that uses an Atomic Server as a haystack.
#[derive(Default, Clone)]
pub struct AtomicHaystackIndexer {
// We can add configuration here, like the server URL
}
impl AtomicHaystackIndexer {
/// Normalize document ID to match persistence layer expectations
fn normalize_document_id(&self, original_id: &str) -> String {
// Create a dummy document to access the normalize_key method
let dummy_doc = Document {
id: "dummy".to_string(),
title: "dummy".to_string(),
body: "dummy".to_string(),
url: "dummy".to_string(),
description: None,
summarization: None,
stub: None,
tags: None,
rank: None,
source_haystack: None,
};
dummy_doc.normalize_key(original_id)
}
}
impl IndexMiddleware for AtomicHaystackIndexer {
/// Index the haystack using an Atomic Server and return an index of documents
///
/// # Errors
///
/// Returns an error if the middleware fails to index the haystack
async fn index(&self, needle: &str, haystack: &Haystack) -> Result<Index> {
let haystack_url = &haystack.location;
log::debug!(
"AtomicHaystackIndexer::index called with needle: '{}' haystack: {:?}",
needle,
haystack_url
);
log::info!("🔍 AtomicHaystackIndexer searching for: '{}'", needle);
if haystack_url.is_empty() {
log::warn!("Haystack location is empty");
return Ok(Index::default());
}
// Validate URL format before proceeding
if !is_valid_url(haystack_url) {
log::warn!(
"Invalid URL format: '{}', returning empty index",
haystack_url
);
return Ok(Index::default());
}
// Create agent from secret if provided
let agent = if let Some(secret) = &haystack.atomic_server_secret {
match Agent::from_base64(secret) {
Ok(agent) => {
log::debug!("Successfully created agent from secret");
Some(agent)
}
Err(e) => {
log::error!("Failed to create agent from secret: {}", e);
return Err(crate::Error::Indexation(format!(
"Invalid atomic server secret: {}",
e
)));
}
}
} else {
log::debug!("No atomic server secret provided, using anonymous access");
None
};
// Initialize the atomic store
let config = Config {
server_url: haystack_url.to_string(),
agent,
};
let store = match Store::new(config) {
Ok(store) => store,
Err(e) => {
log::warn!(
"Failed to create atomic store for URL '{}': {}, returning empty index",
haystack_url,
e
);
return Ok(Index::default());
}
};
// Perform a search
log::debug!("Performing search for: '{}'", needle);
let search_result = match store.search(needle).await {
Ok(result) => result,
Err(e) => {
log::warn!(
"Search failed for URL '{}': {}, returning empty index",
haystack_url,
e
);
return Ok(Index::default());
}
};
log::debug!(
"📊 Search result structure: {}",
serde_json::to_string_pretty(&search_result)
.unwrap_or_else(|_| format!("{:?}", search_result))
);
// Convert search results to documents
let mut index = Index::new();
// Handle Atomic Server search response format
// The response is an object with "https://atomicdata.dev/properties/endpoint/results" array
if let Some(obj) = search_result.as_object() {
log::debug!("📋 Search result is object format");
// Check for the endpoint/results property (standard Atomic Server search response)
if let Some(results) = obj
.get("https://atomicdata.dev/properties/endpoint/results")
.and_then(|v| v.as_array())
{
log::info!(
"📋 Found {} results in endpoint/results format",
results.len()
);
let server_prefix = store.config.server_url.trim_end_matches('/');
for result_val in results {
if let Some(subject) = result_val.as_str() {
// Skip external URLs that don't belong to our server
if !subject.starts_with(server_prefix) {
log::debug!(" ⏭️ Skipping external URL: {}", subject);
continue;
}
log::debug!(" 📄 Processing result: {}", subject);
match store.get_resource(subject).await {
Ok(resource) => {
// Try to extract meaningful body content from various properties
let body = extract_document_body(&resource.properties);
let original_id = resource.subject.clone();
let normalized_id = self.normalize_document_id(&original_id);
let document = Document {
id: normalized_id,
url: resource.subject.clone(),
title: resource
.properties
.get("https://atomicdata.dev/properties/name")
.and_then(|v| v.as_str())
.unwrap_or(&resource.subject)
.to_string(),
description: resource
.properties
.get("https://atomicdata.dev/properties/description")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
body,
summarization: None,
stub: None,
tags: None,
rank: None,
source_haystack: None,
};
log::debug!(
" ✅ Created document: {} ({})",
document.title,
document.id
);
index.insert(document.id.clone(), document);
}
Err(e) => {
log::warn!(" ❌ Failed to get resource {}: {}", subject, e);
continue;
}
}
} else {
log::warn!(" ❌ Result is not a string: {:?}", result_val);
}
}
} else {
log::debug!("❌ No 'endpoint/results' array found in object response");
// Fallback: check for simple array format or subjects array
if let Some(subjects) = obj.get("subjects").and_then(|v| v.as_array()) {
log::info!("📋 Found {} subjects in fallback format", subjects.len());
for subject_val in subjects {
if let Some(subject) = subject_val.as_str() {
log::debug!(" 📄 Processing subject: {}", subject);
match store.get_resource(subject).await {
Ok(resource) => {
let body = extract_document_body(&resource.properties);
let original_id = resource.subject.clone();
let normalized_id = self.normalize_document_id(&original_id);
let document = Document {
id: normalized_id,
url: resource.subject.clone(),
title: resource
.properties
.get("https://atomicdata.dev/properties/name")
.and_then(|v| v.as_str())
.unwrap_or(&resource.subject)
.to_string(),
description: resource
.properties
.get("https://atomicdata.dev/properties/description")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
body,
summarization: None,
stub: None,
tags: None,
rank: None,
source_haystack: None,
};
log::debug!(
" ✅ Created document: {} ({})",
document.title,
document.id
);
index.insert(document.id.clone(), document);
}
Err(e) => {
log::warn!(" ❌ Failed to get resource {}: {}", subject, e);
continue;
}
}
}
}
} else {
log::debug!("❌ No recognized result format found in response");
}
}
} else if let Some(results) = search_result.as_array() {
// Direct array format (legacy support)
log::info!("📋 Found {} results in direct array format", results.len());
for result in results {
if let Some(subject) = result.as_str() {
log::debug!(" 📄 Processing result: {}", subject);
match store.get_resource(subject).await {
Ok(resource) => {
let body = extract_document_body(&resource.properties);
let original_id = resource.subject.clone();
let normalized_id = self.normalize_document_id(&original_id);
let document = Document {
id: normalized_id,
url: resource.subject.clone(),
title: resource
.properties
.get("https://atomicdata.dev/properties/name")
.and_then(|v| v.as_str())
.unwrap_or(&resource.subject)
.to_string(),
description: resource
.properties
.get("https://atomicdata.dev/properties/description")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
body,
summarization: None,
stub: None,
tags: None,
rank: None,
source_haystack: None,
};
log::debug!(
" ✅ Created document: {} ({})",
document.title,
document.id
);
index.insert(document.id.clone(), document);
}
Err(e) => {
log::warn!(" ❌ Failed to get resource {}: {}", subject, e);
continue;
}
}
} else {
log::warn!(" ❌ Result is not a string: {:?}", result);
}
}
} else {
log::warn!(
"❌ Search result is neither array nor object: {:?}",
search_result
);
}
log::info!("🎯 Final index contains {} documents", index.len());
Ok(index)
}
}
/// Check if a URL is valid by parsing it
fn is_valid_url(url: &str) -> bool {
url::Url::parse(url).is_ok()
}
/// Extract meaningful document body from resource properties.
/// Tries multiple sources in order of preference.
fn extract_document_body(
properties: &std::collections::HashMap<String, serde_json::Value>,
) -> String {
// First try Terraphim-specific body property
if let Some(body) = properties
.get("http://localhost:9883/terraphim-drive/terraphim/property/body")
.and_then(|v| v.as_str())
{
return body.to_string();
}
// Then try standard atomic data description
if let Some(description) = properties
.get("https://atomicdata.dev/properties/description")
.and_then(|v| v.as_str())
{
return description.to_string();
}
// Try name as fallback
if let Some(name) = properties
.get("https://atomicdata.dev/properties/name")
.and_then(|v| v.as_str())
{
return name.to_string();
}
// Fallback to serialized properties
serde_json::to_string(properties).unwrap_or_default()
}