
    ZTh/                    *   d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlZd dlmZmZ d dlmZ d dlmZ d dlmZmZ d d	lmZmZ  ej4                  d
      ZddZddZddZddZddZ ddZ! G d de      Z" G d de      Z# G d de      Z$y)    )annotationsN)Path)AnyDictListLiteralUnioncast)NotRequired	TypedDict)YamlConfigError)RuleActionAnnotationKind)ChannelConfigYamlSpec_validate_channel_reference)_handle_subdir	_type_fqnz^\$[a-zA-Z_]+$c                    i }| D ]=  }t        |      }|j                         D ]  \  }}||v rt        d| d      |||<    ? |S )a  
    Takes in a list of paths to YAML files which contains named expressions and processes them into a `dict`.
    The key is the name of the expression and the value is the expression itself. For more information on
    named expression modules see `sift_py/yaml/rule.py`.
    z<Encountered expressions with identical names being loaded, ''.)"_read_named_expression_module_yamlitemsr   )pathsnamed_expressionspathnamed_expr_modulenameexprs         V/home/www/backend.miabetepe.com/venv/lib/python3.12/site-packages/sift_py/yaml/rule.pyload_named_expression_modulesr      sz      +>tD+113 	+JD$((%RSWRXXZ[  '+d#	++     c                    g dfd}| D ]8  }|j                         rt        ||        |j                         s1 ||       : S )z
    Takes in a list of paths which may either be directories or files containing rule module YAML files,
    and processes them into a `list`. For more information on rule modules see
    RulemoduleYamlSpec in `sift_py/yaml/rule.py`.
    c                >    t        |       }j                  |       y )N)_read_rule_module_yamlextend)rule_module_pathrule_modulerule_moduless     r   update_rule_modulesz.load_rule_modules.<locals>.update_rule_modules4   s    ,-=>K(r   )r$   r   )is_dirr   is_file)r   r'   r   r&   s      @r   load_rule_modulesr*   +   sM     (*L)  &;;=4!45\\^%	& r   c           	        t        | d      5 }t        t        t        t        f   t	        j
                  |j                                     }|j                         D ]I  \  }}t        |t              st        d| d|  d      t        |t              r9t        d| d|  d       t        t        t        t        f   |      cd d d        S # 1 sw Y   y xY w)Nr
Expected 'z-' to be a string in named expression module 'r   zExpected expression of ')openr
   r   r   yaml	safe_loadreadr   
isinstancestrr   )r   fr   keyvalues        r   r   r   A   s    	dC 7A c3h1IJ+113 	JCc3'% %RSWRXXZ[  eS)%.se3`ae`ffhi 	 DcN$567 7 7s   BC/CCc                   t        | d      5 }t        t        t        t        f   t	        j
                  |j                                     }|j                  d      }t        |t              s!t        d| d|  dt        t                     t        t        t           |      D ]  }t        |        t        t        t           |      cd d d        S # 1 sw Y   y xY w)Nr,   rulesr-   z%' to be a list in rule module yaml: '')r.   r
   r   r   r/   r0   r1   getr2   listr   r   RuleYamlSpecr   _validate_rule)r   r4   module_rulesr8   rules        r   r"   r"   R   s    	dC /ADcNDNN1668,DE  )%&!UG#Ha\*+- 
 cE* 	!D4 	! D&./ / /s   B>CCc                   t        t        t        t        f   |       }|j                  d      }t	        |t
              st        j                  |dddg      |j                  d      }|at	        |t              s*t        j                  |ddt        t               ddg      t        t        t           |      D ]  }t        |        |j                  d	      }|Yt	        |t              st        j                  |d
ddg      |D ]+  }t	        |t
              rt        j                  |dddg       |j                  d      }|j                  d      }|j                  d      }	|j                  d      }
|j                  d      }|j                  d      }|j                  d      }|j                  d      }|j                  d      }|)t	        |t
              st        j                  |dddg      |)t	        |t
              st        j                  |dddg      t	        |	t              rVt        t        t        t        f   |	      j                  d      }t	        |t
              sCt        j                  |ddddg      t	        |	t
              st        j                  |	dddg      t        D cg c]  }|j                   }}|
|vr(t        j                  |
ddj!                  |      dg      |)t	        |t
              st        j                  |dddg      |)t	        |t              st        j                  |dddg      |Pt	        |t              st        j                  |dddg      t        t        t           |      D ]  }t#        |        |)t	        |t              st        j                  |d ddg      |*t	        |t              st        j                  |d!ddg      y y c c}w )"Nr   z- namer3   r8   channel_referencesz- channel_referenceszList[Dict[str, z]]contextual_channelsz- contextual_channelsz	List[str]z- contextual_channels[]rule_client_keydescription
expressiontypeassigneetagssub_expressionsasset_names	tag_namesz- rule_client_keyz- descriptionz- expressionz<class 'str'> | <class 'dict'>z- typez | z
- assigneez- tags- sub_expressionsz%List[Dict[str, List[Dict[str, str]]]]z- asset_namesz- tag_names)r
   r   r   r:   r2   r3   r   _invalid_propertyr;   r   r   r   r   dictr   r6   join_validate_sub_expression)valr?   r   rA   channel_referencerB   channelrC   rD   rE   	rule_typerG   rH   rI   rJ   rK   expression_namekindvalid_rule_typessub_expressions                       r   r=   r=   b   s   S#X$D88FDdC //hyQQ"67%,d3!33"&!),A"B!C2F		  "&d3i1C!D 	;'(9:	; ((#89&-t4!33#'		  + 	Ggs+%77-I	 	 hh01O((=)K,'J Ixx
#H88FDhh01O((=)K%I":os+K//0%'
 	
 z+s'C//_eV]U^__*d#tCH~z:>>vF/3/!33.)	  
C(//,I	
 	
 0HHt

HH((//JJ'(I	
 	
 Jx$=//I	
 	
 
4 6//I	
 	
 ",d3!33"#7		  #49o> 	5N$^4	5 z+t'D//I	
 	
 Z	4%@//I	
 	
 &A] Is   >O?c                   t        t        t        t        f   |       }|j                         D ]P  }t	        |t
              st        j                  |ddddg      t        j                  |      Ct        d| d       y )Nz- <str>zDict[str, Any]r8   rL   zInvalid sub-expression key, 'zM'. Characters must be in the character set [a-zA-Z_] and prefixed with a '$'.)
r
   r   r   keysr2   r3   r   rM   _SUB_EXPRESSION_REGEXmatch)rQ   rX   r5   s      r   rP   rP      s    $sCx.#.N""$ #s#!33 -.	  !&&s+3!/u  5B  C r   c                      e Zd ZU dZded<   y)RuleModuleYamlSpecz
    The formal definition of what a rule module looks like in YAML.

    `rules`: A list of rules that belong to the module.
    List[RuleYamlSpec]r8   N__name__
__module____qualname____doc____annotations__ r   r   r^   r^      s     r   r^   c                      e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   ded<   ded<   ded<   ded<   ded<   ded<   ded<   y)r<   a
  
    The formal definition of what a single rule looks like in YAML.

    `name`: Name of the rule.
    `rule_client_key`: User-defined string-key that uniquely identifies this rule config.
    `description`: Description of rule.
    `expression`:
        Either an expression-string or a `sift_py.ingestion.config.yaml.spec.NamedExpressionYamlSpec` referencing a named expression.
    `type`: Determines the action to perform if a rule gets evaluated to true.
    `assignee`: If `type` is `review`, determines who to notify. Expects an email.
    `tags`: Tags to associate with the rule.
    `channel_references`: A list of channel references that maps to an actual channel. More below.
    `contextual_channels`: A list of channel configs that provide context but aren't directly used in the expression.
    `sub_expressions`: A list of sub-expressions which is a mapping of place-holders to sub-expressions. Only used if using named expressions.
    `asset_names`: A list of asset names that this rule should be applied to. ONLY VALID if defining rules outside of a telemetry config.
    `tag_names`: A list of tag names that this rule should be applied to. ONLY VALID if defining rules outside of a telemetry config.

    Channel references:
    A channel reference is a string containing a numerical value prefixed with "$". Examples include "$1", "$2", "$11", and so on.
    The channel reference is mapped to an actual channel config. In YAML it would look something like this:

    ```yaml
    channel_references:
      - $1: *vehicle_state_channel
      - $2: *voltage_channel
    contextual_channels:
      - name: log
    ```

    Sub-expressions:
    A sub-expression is made up of two components: A reference and the actual sub-expression. The sub-expression reference is
    a string with a "$" prepended to another string comprised of characters in the following character set: `[a-zA-Z0-9_]`.
    This reference should be mapped to the actual sub-expression. For example, say you have kinematic equations in `kinematics.yml`,
    and the equation you're interested in using looks like the following:

    ```yaml
    kinetic_energy_gt:
      0.5 * $mass * $1 * $1 > $threshold
    ```

    To properly use `kinetic_energy_gt` in your rule, it would look like the following:

    ```yaml
    rules:
      - name: kinetic_energy
        description: Tracks high energy output while in motion
        type: review
        assignee: bob@example.com
        expression:
          name: kinetic_energy_gt
        channel_references:
          - $1: *velocity_channel
        sub_expressions:
          - $mass: 10
          - $threshold: 470
        tags:
            - nostromo
    ```
    r3   r   zNotRequired[str]rC   rD   z#Union[str, NamedExpressionYamlSpec]rE   z*Union[Literal['phase'], Literal['review']]rF   rG   zNotRequired[List[str]]rH   z3NotRequired[List[Dict[str, ChannelConfigYamlSpec]]]rA   rB   z!NotRequired[List[Dict[str, str]]]rI   rJ   rK   Nr`   rf   r   r   r<   r<     sQ    :x I%%!!33
44
  KK//66''%%r   r<   c                      e Zd ZU dZded<   y)NamedExpressionYamlSpecah  
    A named expression. This class is the formal definition of what a named expression
    should look like in YAML. The value of `name` may contain a mix of channel references
    and channel identifiers.

    For a formal definition of channel references and channel identifiers see the following:
    `sift_py.ingestion.config.yaml.spec.RuleYamlSpec`.
    r3   r   Nr`   rf   r   r   ri   ri   N  s     Ir   ri   )r   
List[Path]returnDict[str, str])r   rj   rk   r_   )r   r   rk   rl   )r   r   rk   r_   )rQ   r   )%
__future__r   repathlibr   typingr   r   r   r   r	   r
   r/   typing_extensionsr   r   #sift_py.ingestion.config.yaml.errorr   sift_py.rule.configr   sift_py.yaml.channelr   r   sift_py.yaml.utilsr   r   compiler[   r   r*   r   r"   r=   rP   r^   r<   ri   rf   r   r   <module>rw      s    " 	  8 8  4 ? 8 9"

#45 ,,7"/ B
J$ H&9 H&V
i 
r   