Event.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. using Comal.Classes;
  2. using Expressive;
  3. using InABox.Core;
  4. using InABox.Database;
  5. using Org.BouncyCastle.Asn1.X509.Qualified;
  6. using System;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using System.Diagnostics.CodeAnalysis;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace PRS.Shared.Events;
  15. public interface IEventData : ISerializeBinary
  16. {
  17. IEvent Event { get; }
  18. }
  19. public class EventData<T, TDataModel> : IEventData
  20. where T : IEvent<TDataModel>
  21. where TDataModel : IEventDataModel
  22. {
  23. public T Event { get; set; }
  24. /// <summary>
  25. /// A list of triggers for this event. If any of the triggers match, the event runs.
  26. /// </summary>
  27. public List<ITrigger<T, TDataModel>> Triggers { get; set; }
  28. public List<IEventAction<T>> Actions { get; set; }
  29. IEvent IEventData.Event => Event;
  30. public EventData(T eventData)
  31. {
  32. Event = eventData;
  33. Triggers = new List<ITrigger<T, TDataModel>>();
  34. Actions = new List<IEventAction<T>>();
  35. }
  36. public Notification GenerateNotification(TDataModel model) => Event.GenerateNotification(model);
  37. public void SerializeBinary(CoreBinaryWriter writer)
  38. {
  39. Event.SerializeBinary(writer);
  40. writer.Write(Triggers.Count);
  41. foreach(var trigger in Triggers)
  42. {
  43. EventUtils.SerializeObject(trigger, writer);
  44. }
  45. writer.Write(Actions.Count);
  46. foreach(var action in Actions)
  47. {
  48. EventUtils.SerializeObject(action, writer);
  49. }
  50. }
  51. public void DeserializeBinary(CoreBinaryReader reader)
  52. {
  53. Event.DeserializeBinary(reader);
  54. var nTriggers = reader.ReadInt32();
  55. for(int i = 0; i < nTriggers; ++i)
  56. {
  57. var trigger = EventUtils.DeserializeObject<ITrigger<T, TDataModel>>(EventUtils.GetTriggerType, reader);
  58. Triggers.Add(trigger);
  59. }
  60. var nActions = reader.ReadInt32();
  61. for(int i = 0; i < nActions; ++i)
  62. {
  63. var action = EventUtils.DeserializeObject<IEventAction<T>>(EventUtils.GetTriggerType, reader);
  64. Actions.Add(action);
  65. }
  66. }
  67. }
  68. public static class EventUtils
  69. {
  70. #region Serialisation
  71. public static void SerializeObject(ISerializeBinary obj, CoreBinaryWriter writer)
  72. {
  73. writer.Write(obj.GetType().Name);
  74. foreach(var arg in obj.GetType().GenericTypeArguments)
  75. {
  76. writer.Write(CoreUtils.EntityName(arg));
  77. }
  78. obj.SerializeBinary(writer);
  79. }
  80. public static T DeserializeObject<T>(Func<string, Type> typeSource, CoreBinaryReader reader)
  81. where T : class, ISerializeBinary
  82. {
  83. var eventTypeName = reader.ReadString();
  84. var objType = typeSource(eventTypeName);
  85. var typeParams = objType.GetTypeInfo().GenericTypeParameters;
  86. var typeArgs = new Type[typeParams.Length];
  87. for(int i = 0; i < typeParams.Length; ++i)
  88. {
  89. var entityType = CoreUtils.GetEntity(reader.ReadString());
  90. typeArgs[i] = entityType;
  91. }
  92. if(typeArgs.Length > 0)
  93. {
  94. objType = objType.MakeGenericType(typeArgs);
  95. }
  96. var obj = (Activator.CreateInstance(objType) as T)!;
  97. obj.DeserializeBinary(reader);
  98. return obj;
  99. }
  100. public static void Serialize(IEventData data, CoreBinaryWriter writer)
  101. {
  102. writer.Write(data.Event.GetType().Name);
  103. foreach(var arg in data.Event.GetType().GenericTypeArguments)
  104. {
  105. writer.Write(CoreUtils.EntityName(arg));
  106. }
  107. data.SerializeBinary(writer);
  108. }
  109. public static IEventData Deserialize(CoreBinaryReader reader)
  110. {
  111. var eventTypeName = reader.ReadString();
  112. var eventType = EventUtils.GetEventType(eventTypeName);
  113. var typeParams = eventType.GetTypeInfo().GenericTypeParameters;
  114. var typeArgs = new Type[typeParams.Length];
  115. for(int i = 0; i < typeParams.Length; ++i)
  116. {
  117. var entityType = CoreUtils.GetEntity(reader.ReadString());
  118. typeArgs[i] = entityType;
  119. }
  120. if(typeArgs.Length > 0)
  121. {
  122. eventType = eventType.MakeGenericType(typeArgs);
  123. }
  124. var ev = (Activator.CreateInstance(eventType) as IEvent)!;
  125. var dataModelType = ev.GetType().GetInterfaceDefinition(typeof(IEvent<>))!.GenericTypeArguments[0];
  126. var eventDataType = typeof(EventData<,>).MakeGenericType(ev.GetType(), dataModelType);
  127. var eventData = (Activator.CreateInstance(eventDataType, ev) as IEventData)!;
  128. eventData.DeserializeBinary(reader);
  129. return eventData;
  130. }
  131. #endregion
  132. #region Event Types
  133. private static Dictionary<string, Type>? _eventTypes;
  134. private static Dictionary<string, Type>? _triggerTypes;
  135. private static Dictionary<string, Type>? _actionTypes;
  136. [MemberNotNullWhen(true, nameof(_eventTypes), nameof(_triggerTypes), nameof(_actionTypes))]
  137. private static bool _loadedTypes { get; set; }
  138. [MemberNotNull(nameof(_eventTypes), nameof(_triggerTypes), nameof(_actionTypes))]
  139. private static void LoadTypes()
  140. {
  141. if (_loadedTypes) return;
  142. _loadedTypes = true;
  143. _eventTypes = new();
  144. _triggerTypes = new();
  145. _actionTypes = new();
  146. foreach(var type in CoreUtils.TypeList(x => true))
  147. {
  148. if (type.HasInterface(typeof(IEvent<>)))
  149. {
  150. if (type.GetConstructor([]) is not null)
  151. {
  152. _eventTypes[type.Name] = type;
  153. }
  154. }
  155. else if (type.HasInterface(typeof(ITrigger<,>)))
  156. {
  157. if (type.GetConstructor([]) is not null)
  158. {
  159. _triggerTypes[type.Name] = type;
  160. }
  161. }
  162. else if (type.HasInterface(typeof(IEventAction<>)))
  163. {
  164. if (type.GetConstructor([]) is not null)
  165. {
  166. _triggerTypes[type.Name] = type;
  167. }
  168. }
  169. }
  170. }
  171. public static Type GetEventType(string type)
  172. {
  173. LoadTypes();
  174. return _eventTypes[type]; // Force exception if not a valid type name.
  175. }
  176. public static Type GetTriggerType(string type)
  177. {
  178. LoadTypes();
  179. return _triggerTypes[type]; // Force exception if not a valid type name.
  180. }
  181. public static Type GetActionType(string type)
  182. {
  183. LoadTypes();
  184. return _actionTypes[type]; // Force exception if not a valid type name.
  185. }
  186. #endregion
  187. #region Execution
  188. private static bool Check<T, TDataModel>(EventData<T, TDataModel> ev, TDataModel dataModel)
  189. where T : IEvent<TDataModel>
  190. where TDataModel : IEventDataModel
  191. {
  192. return ev.Triggers.Any(x => x.Check(dataModel));
  193. }
  194. public static void Run<T, TDataModel>(IStore store, Event ev, EventData<T, TDataModel> evData, TDataModel dataModel)
  195. where T : IEvent<TDataModel>
  196. where TDataModel : IEventDataModel
  197. {
  198. if (!Check(evData, dataModel)) return;
  199. foreach(var action in evData.Actions)
  200. {
  201. IEvent.RunAction(evData.Event, dataModel, action);
  202. }
  203. NotifySubscribers(store, ev, evData, dataModel);
  204. }
  205. private static void NotifySubscribers<T, TDataModel>(IStore store, Event ev, EventData<T, TDataModel> evData, TDataModel dataModel)
  206. where T : IEvent<TDataModel>
  207. where TDataModel : IEventDataModel
  208. {
  209. string? description;
  210. if (ev.NotificationExpression.IsNullOrWhiteSpace())
  211. {
  212. description = null;
  213. }
  214. else
  215. {
  216. var descriptionExpr = new CoreExpression(ev.NotificationExpression, typeof(string));
  217. if(!descriptionExpr.TryEvaluate<string>(dataModel).Get(out description, out var error))
  218. {
  219. CoreUtils.LogException(store.UserID, error, extra: "Error notifying subscribers", store.Logger);
  220. return;
  221. }
  222. }
  223. var subscribers = store.Provider.Query(
  224. new Filter<EventSubscriber>(x => x.Event.ID).IsEqualTo(ev.ID),
  225. Columns.None<EventSubscriber>().Add(x => x.Employee.ID))
  226. .ToArray<EventSubscriber>();
  227. var notifications = new List<Notification>();
  228. foreach(var subscriber in subscribers)
  229. {
  230. var notification = evData.GenerateNotification(dataModel);
  231. notification.Employee.CopyFrom(subscriber.Employee);
  232. if(description is not null)
  233. {
  234. notification.Description = description;
  235. }
  236. notifications.Add(notification);
  237. }
  238. store.Provider.Save(notifications);
  239. }
  240. #endregion
  241. }
  242. #region DataModel Definition
  243. public interface IEventVariable
  244. {
  245. string Name { get; set; }
  246. Type Type { get; set; }
  247. }
  248. public class StandardEventVariable : IEventVariable
  249. {
  250. public string Name { get; set; }
  251. public Type Type { get; set; }
  252. public StandardEventVariable(string name, Type type)
  253. {
  254. Name = name;
  255. Type = type;
  256. }
  257. }
  258. public class ListEventVariable : IEventVariable
  259. {
  260. public string Name { get; set; }
  261. public Type Type { get; set; }
  262. public ListEventVariable(string name, Type type)
  263. {
  264. Name = name;
  265. Type = type;
  266. }
  267. }
  268. public interface IEventDataModelDefinition
  269. {
  270. IEnumerable<IEventVariable> GetVariables();
  271. IEventVariable? GetVariable(string name);
  272. }
  273. #endregion
  274. #region DataModel
  275. public interface IEventDataModel : IVariableProvider
  276. {
  277. bool TryGetVariable(string name, out object? value);
  278. bool IVariableProvider.TryGetValue(string variableName, out object? value)
  279. {
  280. return TryGetVariable(variableName, out value);
  281. }
  282. T RootModel<T>()
  283. where T : IEventDataModel
  284. {
  285. if(this is IChildEventDataModel child)
  286. {
  287. return child.Parent.RootModel<T>();
  288. }
  289. else if(this is T root)
  290. {
  291. return root;
  292. }
  293. else
  294. {
  295. throw new Exception($"Root model of wrong type; expected {typeof(T).FullName}; got {GetType().FullName}");
  296. }
  297. }
  298. }
  299. public interface ITypedEventDataModel : IEventDataModel
  300. {
  301. public Type EntityType { get; }
  302. }
  303. public interface IChildEventDataModel : IEventDataModel
  304. {
  305. IEventDataModel Parent { get; }
  306. }
  307. public class ChildEventDataModel : IChildEventDataModel
  308. {
  309. public IEventDataModel Parent { get; set; }
  310. public Dictionary<string, object?> Values { get; set; } = new Dictionary<string, object?>();
  311. public ChildEventDataModel(IEventDataModel parent)
  312. {
  313. Parent = parent;
  314. }
  315. public bool TryGetVariable(string name, out object? value)
  316. {
  317. return Values.TryGetValue(name, out value)
  318. || Parent.TryGetVariable(name, out value);
  319. }
  320. }
  321. #endregion
  322. public interface IEvent : ISerializeBinary
  323. {
  324. IEventDataModelDefinition DataModelDefinition();
  325. public static void RunAction(IEvent ev, IEventDataModel model, IEventAction action)
  326. {
  327. var dataModelDef = ev.DataModelDefinition();
  328. var values = new List<(string name, object? value)[]>() { Array.Empty<(string, object?)>() };
  329. var vars = action.ReferencedVariables();
  330. foreach(var variable in vars)
  331. {
  332. var varDef = dataModelDef.GetVariable(variable);
  333. if(varDef is ListEventVariable)
  334. {
  335. if (model.TryGetVariable(varDef.Name, out var list) && list is IEnumerable enumerable)
  336. {
  337. var oldValues = values;
  338. values = new List<(string name, object? value)[]>();
  339. foreach(var item in enumerable)
  340. {
  341. foreach(var valueList in oldValues)
  342. {
  343. values.Add(valueList.Concatenate(new (string name, object? value)[]
  344. {
  345. (varDef.Name, item)
  346. }));
  347. }
  348. }
  349. }
  350. else
  351. {
  352. values.Clear();
  353. break;
  354. }
  355. }
  356. }
  357. if(values.Count > 0 && (values.Count > 1 || values[0].Length > 0))
  358. {
  359. var subModel = new ChildEventDataModel(model);
  360. foreach(var valueSet in values)
  361. {
  362. subModel.Values.Clear();
  363. foreach(var (name, value) in valueSet)
  364. {
  365. subModel.Values[name] = value;
  366. }
  367. action.Execute(subModel);
  368. }
  369. }
  370. else
  371. {
  372. action.Execute(model);
  373. }
  374. }
  375. }
  376. public interface IEvent<TDataModel> : IEvent
  377. {
  378. Notification GenerateNotification(TDataModel model);
  379. }
  380. public interface ITrigger<TEvent, TDataModel> : ISerializeBinary
  381. where TEvent : IEvent<TDataModel>
  382. where TDataModel : IEventDataModel
  383. {
  384. bool Check(TDataModel dataModel);
  385. }
  386. public interface IEventAction : ISerializeBinary
  387. {
  388. IEnumerable<string> ReferencedVariables();
  389. object? Execute(IEventDataModel dataModel);
  390. }
  391. public interface IEventAction<TEvent> : IEventAction
  392. where TEvent : IEvent
  393. {
  394. }