22Custom Actor and Snapshot Resolvers Example
33
44Demonstrates how runtime context can be used to dynamically
5- resolve actor and system state.
5+ resolve actor identity and external system state.
6+
7+ Resolvers allow applications to supply policy inputs
8+ from runtime context such as:
9+
10+ - authenticated user identity
11+ - request metadata
12+ - system state
13+
614"""
715
8- from actra import Actra , ActraRuntime
16+ from actra import Actra , ActraRuntime , ActraPolicyError
917
18+ # ------------------------------------------------------------
19+ # 1. Schema
20+ # ------------------------------------------------------------
1021
1122schema_yaml = """
1223version: 1
2536 fraud_flag: boolean
2637"""
2738
39+ # ------------------------------------------------------------
40+ # 2. Policy
41+ # ------------------------------------------------------------
2842
2943policy_yaml = """
3044version: 1
5064 effect: block
5165"""
5266
67+ # ------------------------------------------------------------
68+ # 3. Compile policy
69+ # ------------------------------------------------------------
5370
5471policy = Actra .from_strings (schema_yaml , policy_yaml )
5572runtime = ActraRuntime (policy )
5673
57-
58- # Example request context
74+ # ------------------------------------------------------------
75+ # 4. Example request context
76+ # ------------------------------------------------------------
5977class RequestContext :
6078 def __init__ (self , role , fraud_flag ):
6179 self .role = role
6280 self .fraud_flag = fraud_flag
6381
6482
65- # Actor resolver
83+ # ------------------------------------------------------------
84+ # 5. Register resolvers
85+ # ------------------------------------------------------------
86+
87+ # Actor resolver extracts identity information
88+
6689runtime .set_actor_resolver (
6790 lambda ctx : {"role" : ctx .role }
6891)
6992
70- # Snapshot resolver
93+ # Snapshot resolver extracts system state
7194runtime .set_snapshot_resolver (
7295 lambda ctx : {"fraud_flag" : ctx .fraud_flag }
7396)
7497
98+ # ------------------------------------------------------------
99+ # 6. Create runtime context
100+ # ------------------------------------------------------------
75101
76102ctx = RequestContext (role = "support" , fraud_flag = False )
77103
104+ # ------------------------------------------------------------
105+ # 8. Build action
106+ # ------------------------------------------------------------
78107
79108action = runtime .build_action (
80109 action_type = "refund" ,
@@ -83,6 +112,9 @@ def __init__(self, role, fraud_flag):
83112 ctx = ctx
84113)
85114
86- decision = runtime .evaluate (action , ctx )
115+ # ------------------------------------------------------------
116+ # 9. Evaluate policy
117+ # ------------------------------------------------------------
87118
119+ decision = runtime .evaluate (action , ctx )
88120print (decision )
0 commit comments