nika-engine 0.38.0

Nika workflow engine — embeddable runtime, provider, DAG, and binding logic
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! nika:css_select — CSS selector extraction from HTML content.
//!
//! Accepts a CAS hash or raw HTML string and a CSS selector.
//! Returns matching elements as text or HTML fragments.

use std::future::Future;
use std::pin::Pin;

use super::context::MediaToolContext;
use super::error::invalid_args;
use super::{MediaOp, MediaOpResult};
use crate::error::NikaError;

/// Maximum HTML input size: 10 MB.
const MAX_HTML_SIZE: usize = 10 * 1024 * 1024;

/// Maximum number of matches to return (prevents unbounded output).
const MAX_MATCHES: usize = 1000;

pub struct CssSelectOp;

impl MediaOp for CssSelectOp {
    fn name(&self) -> &'static str {
        "css_select"
    }

    fn description(&self) -> &'static str {
        "Extract elements from HTML using CSS selectors (returns text or HTML fragments)"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
          "type": "object",
          "properties": {
            "hash": {
              "type": "string",
              "description": "CAS hash of HTML content (blake3:...)"
            },
            "html": {
              "type": "string",
              "description": "Raw HTML string to query"
            },
            "selector": {
              "type": "string",
              "description": "CSS selector (e.g., 'div.product h2', '#main a')"
            },
            "output": {
              "type": "string",
              "enum": ["text", "html"],
              "description": "Output mode: 'text' (default) extracts text content, 'html' returns HTML fragments",
              "default": "text"
            },
            "limit": {
              "type": "integer",
              "description": "Maximum number of matches to return (default: 1000)",
              "default": 1000
            }
          },
          "required": ["selector"],
          "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        ctx: &'a MediaToolContext,
    ) -> Pin<Box<dyn Future<Output = Result<MediaOpResult, NikaError>> + Send + 'a>> {
        Box::pin(async move {
            ctx.check_cancelled()?;

            let selector_str = args
                .get("selector")
                .and_then(|v| v.as_str())
                .ok_or_else(|| invalid_args("css_select", "missing 'selector' parameter"))?
                .to_string();

            let output_mode = args
                .get("output")
                .and_then(|v| v.as_str())
                .unwrap_or("text")
                .to_string();

            if output_mode != "text" && output_mode != "html" {
                return Err(invalid_args(
                    "css_select",
                    format!("invalid output mode '{output_mode}', expected 'text' or 'html'"),
                ));
            }

            let limit = args
                .get("limit")
                .and_then(|v| v.as_u64())
                .unwrap_or(MAX_MATCHES as u64)
                .min(MAX_MATCHES as u64) as usize;

            let html = resolve_html(&args, ctx).await?;

            // Parse and select on the compute pool (can be CPU-intensive)
            let matches = ctx
                .compute
                .compute(move || -> Result<Vec<String>, NikaError> {
                    let document = scraper::Html::parse_document(&html);

                    let selector = scraper::Selector::parse(&selector_str).map_err(|e| {
                        invalid_args(
                            "css_select",
                            format!("invalid CSS selector '{selector_str}': {e}"),
                        )
                    })?;

                    let results: Vec<String> = document
                        .select(&selector)
                        .take(limit)
                        .map(|el| {
                            if output_mode == "html" {
                                el.html()
                            } else {
                                el.text().collect::<Vec<_>>().join("")
                            }
                        })
                        .collect();

                    Ok(results)
                })
                .await??;

            let count = matches.len();

            Ok(MediaOpResult::Metadata(serde_json::json!({
              "matches": matches,
              "count": count
            })))
        })
    }
}

/// Resolve HTML content from either a CAS hash or raw HTML string.
async fn resolve_html(
    args: &serde_json::Value,
    ctx: &MediaToolContext,
) -> Result<String, NikaError> {
    if let Some(hash) = args.get("hash").and_then(|v| v.as_str()) {
        let data = ctx.read_media(hash).await?;
        if data.len() > MAX_HTML_SIZE {
            return Err(invalid_args(
                "css_select",
                format!(
                    "HTML content too large ({} bytes, max {} bytes)",
                    data.len(),
                    MAX_HTML_SIZE
                ),
            ));
        }
        String::from_utf8(data).map_err(|_| {
            invalid_args(
                "css_select",
                "CAS content is not valid UTF-8 (expected HTML)",
            )
        })
    } else if let Some(html) = args.get("html").and_then(|v| v.as_str()) {
        if html.len() > MAX_HTML_SIZE {
            return Err(invalid_args(
                "css_select",
                format!(
                    "HTML string too large ({} bytes, max {} bytes)",
                    html.len(),
                    MAX_HTML_SIZE
                ),
            ));
        }
        Ok(html.to_string())
    } else {
        Err(invalid_args(
            "css_select",
            "missing 'hash' or 'html' parameter",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::media::CasStore;
    use std::sync::Arc;

    async fn setup() -> (tempfile::TempDir, Arc<MediaToolContext>) {
        let dir = tempfile::tempdir().unwrap();
        let ctx = Arc::new(MediaToolContext::new(CasStore::new(dir.path())));
        (dir, ctx)
    }

    const SAMPLE_HTML: &str = r#"
        <html>
        <body>
            <h1 id="title">Main Title</h1>
            <div class="product">
                <h2>Product A</h2>
                <p class="price">$10</p>
            </div>
            <div class="product">
                <h2>Product B</h2>
                <p class="price">$20</p>
            </div>
            <ul>
                <li>Item 1</li>
                <li>Item 2</li>
            </ul>
        </body>
        </html>
    "#;

    #[tokio::test]
    async fn select_by_tag() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": SAMPLE_HTML, "selector": "h2"}),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 2);
            assert_eq!(matches[0], "Product A");
            assert_eq!(matches[1], "Product B");
            assert_eq!(v["count"], 2);
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_by_class() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": SAMPLE_HTML, "selector": ".price"}),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 2);
            assert_eq!(matches[0], "$10");
            assert_eq!(matches[1], "$20");
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_by_id() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": SAMPLE_HTML, "selector": "#title"}),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 1);
            assert_eq!(matches[0], "Main Title");
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_nested() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": SAMPLE_HTML, "selector": "div.product h2"}),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 2);
            assert_eq!(matches[0], "Product A");
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_text_mode() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({
                    "html": SAMPLE_HTML,
                    "selector": ".product",
                    "output": "text"
                }),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 2);
            let text = matches[0].as_str().unwrap();
            assert!(
                text.contains("Product A"),
                "text should contain title: {text}"
            );
            assert!(text.contains("$10"), "text should contain price: {text}");
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_html_mode() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({
                    "html": SAMPLE_HTML,
                    "selector": "li",
                    "output": "html"
                }),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 2);
            let html = matches[0].as_str().unwrap();
            assert!(
                html.contains("<li>"),
                "html mode should include tags: {html}"
            );
            assert!(html.contains("Item 1"), "html should contain text: {html}");
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_invalid_selector() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": SAMPLE_HTML, "selector": "!!!invalid"}),
                &ctx,
            )
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("NIKA-294"));
    }

    #[tokio::test]
    async fn select_no_matches() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": SAMPLE_HTML, "selector": "span.nonexistent"}),
                &ctx,
            )
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert!(matches.is_empty());
            assert_eq!(v["count"], 0);
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_missing_selector_param() {
        let (_dir, ctx) = setup().await;
        let op = CssSelectOp;
        let result = op
            .execute(serde_json::json!({"html": "<p>test</p>"}), &ctx)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("NIKA-294"));
    }

    #[tokio::test]
    async fn select_from_cas_hash() {
        let (_dir, ctx) = setup().await;
        let sr = ctx.cas.store(SAMPLE_HTML.as_bytes()).await.unwrap();

        let op = CssSelectOp;
        let result = op
            .execute(serde_json::json!({"hash": sr.hash, "selector": "h1"}), &ctx)
            .await
            .unwrap();

        if let MediaOpResult::Metadata(v) = result {
            let matches = v["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 1);
            assert_eq!(matches[0], "Main Title");
        } else {
            panic!("expected Metadata result");
        }
    }

    #[tokio::test]
    async fn select_cancelled() {
        let (_dir, ctx) = setup().await;
        ctx.cancel.cancel();
        let op = CssSelectOp;
        let result = op
            .execute(
                serde_json::json!({"html": "<p>x</p>", "selector": "p"}),
                &ctx,
            )
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("cancelled"));
    }
}