tremor-script 0.12.4

Tremor Script Interpreter
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
// Copyright 2020-2021, The Tremor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub(crate) mod raw;

use super::{
    error_generic, error_no_locals,
    helper::Scope,
    node_id::NodeId,
    visitors::{ArgsRewriter, ConstFolder},
    walkers::QueryWalker,
    EventPath, HashMap, Helper, Ident, ImutExpr, InvokeAggrFn, NodeMeta, Path, Result, Script,
    Serialize, Stmts, Upable, Value,
};
use super::{raw::BaseExpr, Consts};
use crate::ast::{walkers::ImutExprWalker, Literal};
use crate::{errors::err_generic, impl_expr};
use raw::WindowName;
use simd_json::{Builder, Mutable, ValueAccess};

/// A Tremor query
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Query<'script> {
    /// Config for the query
    pub config: HashMap<String, Value<'script>>,
    /// Input Ports
    pub from: Vec<Ident<'script>>,
    /// Output Ports
    pub into: Vec<Ident<'script>>,
    /// Statements
    pub stmts: Stmts<'script>,
    /// Params if this is a modular query
    pub params: DefinitionalArgs<'script>,
    /// definitions
    pub scope: Scope<'script>,
    /// metadata
    pub(crate) mid: Box<NodeMeta>,
}
impl_expr!(Query);

/// Query statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum Stmt<'script> {
    /// A window definition
    WindowDefinition(Box<WindowDefinition<'script>>),
    /// An operator definition
    OperatorDefinition(OperatorDefinition<'script>),
    /// A script definition
    ScriptDefinition(Box<ScriptDefinition<'script>>),
    /// An pipeline definition
    PipelineDefinition(Box<PipelineDefinition<'script>>),
    /// A stream
    StreamStmt(StreamStmt),
    /// An operator creation
    OperatorCreate(OperatorCreate<'script>),
    /// A script creation
    ScriptCreate(ScriptCreate<'script>),
    /// An pipeline creation
    PipelineCreate(PipelineCreate<'script>),
    /// A select statement
    SelectStmt(SelectStmt<'script>),
}

// #[cfg_attr(coverage, no_coverage)] // this is a simple passthrough
impl<'script> BaseExpr for Stmt<'script> {
    fn meta(&self) -> &NodeMeta {
        match self {
            Stmt::WindowDefinition(s) => s.meta(),
            Stmt::StreamStmt(s) => s.meta(),
            Stmt::OperatorDefinition(s) => s.meta(),
            Stmt::ScriptDefinition(s) => s.meta(),
            Stmt::PipelineDefinition(s) => s.meta(),
            Stmt::PipelineCreate(s) => s.meta(),
            Stmt::OperatorCreate(s) => s.meta(),
            Stmt::ScriptCreate(s) => s.meta(),
            Stmt::SelectStmt(s) => s.meta(),
        }
    }
}

/// array of aggregate functions
pub type Aggregates<'f> = Vec<InvokeAggrFn<'f>>;
/// array of aggregate functions (as slice)
pub type AggrSlice<'f> = [InvokeAggrFn<'f>];

///
/// A Select statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct SelectStmt<'script> {
    /// The select statement
    pub stmt: Box<Select<'script>>,
    /// Aggregates
    pub aggregates: Aggregates<'script>,
    /// Constants
    pub consts: Consts<'script>,
    /// Number of locals
    pub locals: usize,
}
// #[cfg_attr(coverage, no_coverage)] // this is a simple passthrough
impl<'script> BaseExpr for SelectStmt<'script> {
    fn meta(&self) -> &NodeMeta {
        self.stmt.meta()
    }
}

/// The type of a select statement
pub enum SelectType {
    /// This select statement can be turned
    /// into a passthrough node
    Passthrough,
    /// This is a simple statement without grouping
    /// or windowing
    Simple,
    /// This is a full fledged select statement
    Normal,
}

impl SelectStmt<'_> {
    /// Determine how complex a select statement is
    #[must_use]
    pub fn complexity(&self) -> SelectType {
        if matches!(
            &self.stmt.target,
            ImutExpr::Path(Path::Event(EventPath {
                segments, ..
            })) if segments.is_empty()
        ) && self.stmt.maybe_group_by.is_none()
            && self.stmt.windows.is_empty()
        {
            if self.stmt.maybe_having.is_none() && self.stmt.maybe_where.is_none() {
                SelectType::Passthrough
            } else {
                SelectType::Simple
            }
        } else {
            SelectType::Normal
        }
    }
}

/// Operator kind identifier
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct OperatorKind {
    pub(crate) mid: Box<NodeMeta>,
    /// Module of the operator
    pub module: String,
    /// Operator name
    pub operation: String,
}

impl BaseExpr for OperatorKind {
    fn meta(&self) -> &NodeMeta {
        &self.mid
    }
}

/// An operator definition
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct OperatorDefinition<'script> {
    /// The ID and Module of the Operator
    pub id: String,
    /// metadata id
    pub(crate) mid: Box<NodeMeta>,
    /// Type of the operator
    pub kind: OperatorKind,
    /// Parameters for the operator
    pub params: DefinitionalArgsWith<'script>,
}
impl_expr!(OperatorDefinition);

/// An operator creation
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct OperatorCreate<'script> {
    /// The ID and Module of the Operator
    pub id: String,
    /// metadata id
    pub(crate) mid: Box<NodeMeta>,
    /// Target of the operator
    pub target: NodeId,
    /// parameters of the instance
    pub params: CreationalWith<'script>,
}
impl_expr!(OperatorCreate);

/// A script definition
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ScriptDefinition<'script> {
    pub(crate) mid: Box<NodeMeta>,
    /// The ID and Module of the Script
    pub id: String,
    /// Parameters of a script definition
    pub params: DefinitionalArgs<'script>,
    /// The script itself
    pub script: Script<'script>,
}
impl_expr!(ScriptDefinition);

/// A script creation
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct ScriptCreate<'script> {
    /// The ID and Module of the Script
    pub id: String,
    /// metadata id
    pub(crate) mid: Box<NodeMeta>,
    /// Target of the script
    pub target: NodeId,
    /// Parameters of the script statement
    pub params: CreationalWith<'script>,
}
impl_expr!(ScriptCreate);

/// A config
pub type Config<'script> = Vec<(String, ImutExpr<'script>)>;

/// A pipeline definition
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PipelineDefinition<'script> {
    /// The ID and Module of the PipelineDefinition
    pub id: String,
    /// metadata id
    pub(crate) mid: Box<NodeMeta>,
    /// Parameters of a subquery definition
    pub params: DefinitionalArgs<'script>,
    /// Input Ports
    pub from: Vec<Ident<'script>>,
    /// Output Ports
    pub into: Vec<Ident<'script>>,
    /// Raw config
    pub config: Config<'script>,
    /// The raw pipeline statements
    pub stmts: Stmts<'script>,
    /// The scope
    pub scope: Scope<'script>,
}
impl_expr!(PipelineDefinition);

impl<'script> PipelineDefinition<'script> {
    /// Converts a pipeline defintion into a query
    ///
    /// # Errors
    /// if translation to a query fails
    pub fn to_query<'registry>(
        &self,
        create: &CreationalWith<'script>,
        helper: &mut Helper<'script, 'registry>,
    ) -> Result<Query<'script>> {
        let mut create = create.clone();
        ConstFolder::new(helper).walk_creational_with(&mut create)?;
        let mut args = create.render()?;

        let mut config = HashMap::new();

        for (k, v) in &self.config {
            let v = v.clone();
            let v = v.try_into_value(helper)?;
            config.insert(k.to_string(), v);
        }

        let scope = self.scope.clone();
        helper.set_scope(scope);

        let mut params = self.params.clone();
        for (k, v) in &mut params.args.0 {
            if let Some(new) = args.remove(k.as_str())? {
                *v = Some(*Literal::boxed_expr(Box::new(k.meta().clone()), new));
            }
        }
        if let Some(k) = args.as_object().and_then(|o| o.keys().next()) {
            return error_generic(&create, &create, &format!("Unknown parameter {k}"));
        }
        ConstFolder::new(helper).walk_definitional_args(&mut params)?;
        let inner_args = params.render()?;
        let stmts = self
            .stmts
            .iter()
            .cloned()
            .map(|s| s.apply_args(&inner_args, helper, params.meta()))
            .collect::<Result<_>>()?;

        Ok(Query {
            config,
            stmts,
            from: self.from.clone(),
            into: self.into.clone(),
            params: self.params.clone(),
            scope: helper.leave_scope()?,
            mid: self.mid.clone(),
        })
    }
}

/// A pipeline creation
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PipelineCreate<'script> {
    pub(crate) mid: Box<NodeMeta>,
    /// The node id of the pipeline definition we want to create
    pub target: NodeId,
    /// Map of pipeline ports and internal stream id
    pub port_stream_map: HashMap<String, String>,
    /// With arguments
    pub params: CreationalWith<'script>,
    /// local alias
    pub alias: String,
}
impl<'script> BaseExpr for PipelineCreate<'script> {
    fn meta(&self) -> &NodeMeta {
        &self.mid
    }
}

/// we're forced to make this pub because of lalrpop
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum WindowKind {
    /// we're forced to make this pub because of lalrpop
    Sliding,
    /// we're forced to make this pub because of lalrpop
    Tumbling,
}

/// A window definition
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct WindowDefinition<'script> {
    /// ID and Module of the Window
    pub id: String,
    /// metadata id
    pub(crate) mid: Box<NodeMeta>,
    /// The type of window
    pub kind: WindowKind,
    /// Parameters passed to the window
    pub params: CreationalWith<'script>,
    /// The script of the window
    pub script: Option<Script<'script>>,
}
impl_expr!(WindowDefinition);

impl<'script> WindowDefinition<'script> {
    /// `emit_empty_windows` setting
    pub const EMIT_EMPTY_WINDOWS: &'static str = "emit_empty_windows";
    /// `max_groups` setting
    pub const MAX_GROUPS: &'static str = "max_groups";
    /// `interval` setting
    pub const INTERVAL: &'static str = "interval";
    /// `size` setting
    pub const SIZE: &'static str = "size";
}

/// A select statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Select<'script> {
    /// MetadataID of the statement
    pub mid: Box<NodeMeta>,
    /// The from clause
    pub from: (Ident<'script>, Ident<'script>),
    /// The into claus
    pub into: (Ident<'script>, Ident<'script>),
    /// The target (select part)
    pub target: ImutExpr<'script>,
    /// Where clause
    pub maybe_where: Option<ImutExpr<'script>>,
    /// Having clause
    pub maybe_having: Option<ImutExpr<'script>>,
    /// Group-By clause
    pub maybe_group_by: Option<GroupBy<'script>>,
    /// Window
    pub windows: Vec<WindowName>,
}
impl_expr!(Select);

/// A group by clause
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum GroupBy<'script> {
    /// Expression based group by
    Expr {
        /// mid
        mid: Box<NodeMeta>,
        /// expr
        expr: ImutExpr<'script>,
    },
    /// `set` based group by
    Set {
        /// mid
        mid: Box<NodeMeta>,
        /// items
        items: Vec<GroupBy<'script>>,
    },
    /// `each` based group by
    Each {
        /// mid
        mid: Box<NodeMeta>,
        /// expr
        expr: ImutExpr<'script>,
    },
}

/// A stream statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StreamStmt {
    pub(crate) mid: Box<NodeMeta>,
    /// ID if the stream
    pub id: String,
}

impl BaseExpr for StreamStmt {
    fn meta(&self) -> &NodeMeta {
        &self.mid
    }
}

/// A with block in a creational statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct CreationalWith<'script> {
    /// `with` seection
    pub with: WithExprs<'script>,
    pub(crate) mid: Box<NodeMeta>,
}
impl_expr!(CreationalWith);

impl<'script> CreationalWith<'script> {
    pub(crate) fn substitute_args<'registry>(
        &mut self,
        args: &Value<'script>,
        helper: &mut Helper<'script, 'registry>,
    ) -> Result<()> {
        self.with.substitute_args(args, helper, &self.mid)
    }

    /// Renders a with clause into a k/v pair
    /// # Errors
    /// when a value can't be evaluated intoa literal
    pub fn render(&self) -> Result<Value<'script>> {
        let mut res = Value::object();
        for (k, v) in &self.with.0 {
            res.try_insert(k.id.clone(), v.try_as_lit()?.clone());
        }
        Ok(res)
    }
}

/// A args / with block in a definitional statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct DefinitionalArgsWith<'script> {
    /// `args` section
    pub args: ArgsExprs<'script>,
    /// With section
    pub with: WithExprs<'script>,
    /// node meta
    pub mid: Box<NodeMeta>,
}

impl<'script> DefinitionalArgsWith<'script> {
    /// Combines the definitional args and with block along with the creational with block
    /// here the following happens:
    /// 1) The creational with is merged into the definitial with, overwriting defaults
    /// 2) We check if all mandatory fiends defined in the creational-args are set
    /// 3) we incoperate the merged args into the creational with - this results in the final map
    /// in the with section
    ///
    /// # Errors
    /// for unknown keys
    pub fn ingest_creational_with(&mut self, creational: &CreationalWith<'script>) -> Result<()> {
        // Ingest creational `with` into definitional `args` and error if `with` contains
        // a unknown key
        for (k, v) in &creational.with.0 {
            if let Some((_, arg_v)) = self
                .args
                .0
                .iter_mut()
                .find(|(arg_key, _)| arg_key.id == k.id)
            {
                *arg_v = Some(v.clone());
            } else {
                return error_generic(creational, k, &"Unknown key");
            }
        }

        if let Some((k, _)) = self.args.0.iter_mut().find(|(_, v)| v.is_none()) {
            error_generic(creational, k, &"Missing key")
        } else {
            Ok(())
        }
    }

    /// Generates the config
    ///
    /// # Errors
    ///   * If the config could not be generated
    pub fn generate_config<'registry>(
        &self,
        helper: &mut Helper<'script, 'registry>,
    ) -> Result<Value<'script>> {
        let args = self
            .args
            .0
            .iter()
            .map(|(k, expr)| {
                let expr = expr
                    .clone()
                    .ok_or_else(|| format!("Missing configuration variable {}", k))?;
                Ok((k.id.clone(), ConstFolder::reduce_to_val(helper, expr)?))
            })
            .collect::<Result<Value>>()?;

        let config = self
            .with
            .0
            .iter()
            .map(|(k, v)| {
                let mut expr = v.clone();
                ArgsRewriter::new(args.clone(), helper, &self.mid).rewrite_expr(&mut expr)?;
                Ok((k.id.to_string(), ConstFolder::reduce_to_val(helper, expr)?))
            })
            .collect();
        config
    }
}

/// A args block in a definitional statement
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct DefinitionalArgs<'script> {
    /// `args` seection
    pub(crate) args: ArgsExprs<'script>,
    pub(crate) mid: Box<NodeMeta>,
}
impl_expr!(DefinitionalArgs);

impl<'script> DefinitionalArgs<'script> {
    /// Combines the definitional args and with block along with the creational with block
    /// here the following happens:
    /// 1) The creational with is merged into the definitial with, overwriting defaults
    /// 2) We check if all mandatory fiends defined in the creational-args are set
    /// 3) we incoperate the merged args into the creational with - this results in the final map
    /// in the with section
    ///
    /// # Errors
    /// for unknown keys
    pub fn ingest_creational_with(&mut self, creational: &CreationalWith<'script>) -> Result<()> {
        // Ingest creational `with` into definitional `args` and error if `with` contains
        // a unknown key
        for (k, v) in &creational.with.0 {
            if let Some((_, arg_v)) = self
                .args
                .0
                .iter_mut()
                .find(|(arg_key, _)| arg_key.id == k.id)
            {
                *arg_v = Some(v.clone());
            } else {
                return error_generic(self, k, &"Unknown key");
            }
        }

        if let Some((k, _)) = self.args.0.iter_mut().find(|(_, v)| v.is_none()) {
            Err(format!("missing key: {}", k).into())
        } else {
            Ok(())
        }
    }

    /// Renders a with clause into a k/v pair
    /// # Errors
    /// on missing keys
    pub fn render(&self) -> Result<Value<'script>> {
        let mut res = Value::object();
        for (k, v) in &self.args.0 {
            let v = v
                .as_ref()
                .ok_or_else(|| err_generic(k, k, &"Required key not provided"))?
                .try_as_lit()?
                .clone();
            res.try_insert(k.id.clone(), v);
        }
        Ok(res)
    }
}

/// a With key value pair.
pub type WithExpr<'script> = (Ident<'script>, ImutExpr<'script>);
/// list of arguments in a `with` section
#[derive(Clone, Debug, PartialEq, Serialize, Default)]
pub struct WithExprs<'script>(pub Vec<WithExpr<'script>>);

impl<'script> WithExprs<'script> {
    pub(crate) fn substitute_args<'registry>(
        &mut self,
        args: &Value<'script>,
        helper: &mut Helper<'script, 'registry>,
        mid: &NodeMeta,
    ) -> Result<()> {
        let mut old = Vec::new();
        std::mem::swap(&mut old, &mut self.0);
        self.0 = old
            .into_iter()
            .map(|(name, mut value_expr)| {
                ArgsRewriter::new(args.clone(), helper, mid).rewrite_expr(&mut value_expr)?;
                ImutExprWalker::walk_expr(&mut ConstFolder::new(helper), &mut value_expr)?;
                Ok((name, value_expr))
            })
            .collect::<Result<_>>()?;
        Ok(())
    }
}

/// a Args key value pair.
pub type ArgsExpr<'script> = (Ident<'script>, Option<ImutExpr<'script>>);

/// list of arguments in a `args` section
#[derive(Clone, Debug, PartialEq, Serialize, Default)]
pub struct ArgsExprs<'script>(pub Vec<ArgsExpr<'script>>);

impl<'script> Stmt<'script> {
    fn apply_args(
        mut self,
        args: &Value<'script>,
        helper: &mut Helper<'script, '_>,
        mid: &NodeMeta,
    ) -> Result<Self> {
        match &mut self {
            // For definitions, select andstreams we do not substitute incomming args
            // their args are handled via the create statements
            Stmt::WindowDefinition(_)
            | Stmt::OperatorDefinition(_)
            | Stmt::ScriptDefinition(_)
            | Stmt::PipelineDefinition(_)
            | Stmt::StreamStmt(_) => (),
            Stmt::SelectStmt(s) => {
                ArgsRewriter::new(args.clone(), helper, mid).walk_select_stmt(s)?;
                ConstFolder::new(helper).walk_select_stmt(s)?;
            }
            Stmt::OperatorCreate(d) => d.params.substitute_args(args, helper)?,
            Stmt::ScriptCreate(d) => d.params.substitute_args(args, helper)?,
            Stmt::PipelineCreate(d) => d.params.substitute_args(args, helper)?,
        };
        Ok(self)
    }
}