Event.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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<IEventTrigger<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<IEventTrigger<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<IEventTrigger<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. private static Dictionary<Type, List<Type>>? _eventTriggerTypes;
  137. private static Dictionary<Type, List<Type>>? _eventActionTypes;
  138. [MemberNotNullWhen(true, nameof(_eventTypes), nameof(_triggerTypes), nameof(_actionTypes), nameof(_eventTriggerTypes), nameof(_eventActionTypes))]
  139. private static bool _loadedTypes { get; set; }
  140. [MemberNotNull(nameof(_eventTypes), nameof(_triggerTypes), nameof(_actionTypes), nameof(_eventTriggerTypes), nameof(_eventActionTypes))]
  141. private static void LoadTypes()
  142. {
  143. if (_loadedTypes) return;
  144. _loadedTypes = true;
  145. _eventTypes = new();
  146. _triggerTypes = new();
  147. _actionTypes = new();
  148. _eventTriggerTypes = new();
  149. _eventActionTypes = new();
  150. foreach(var type in CoreUtils.TypeList(x => true))
  151. {
  152. if (type.HasInterface(typeof(IEvent<>)))
  153. {
  154. if (type.GetConstructor([]) is not null)
  155. {
  156. _eventTypes[type.Name] = type;
  157. }
  158. }
  159. else if (type.GetInterfaceDefinition(typeof(IEventTrigger<,>)) is Type eventTriggerInterface)
  160. {
  161. if (type.GetConstructor([]) is not null)
  162. {
  163. _triggerTypes[type.Name] = type;
  164. var eventType = eventTriggerInterface.GenericTypeArguments[0];
  165. eventType = eventType.IsGenericType ? eventType.GetGenericTypeDefinition() : eventType;
  166. _eventTriggerTypes.GetValueOrAdd(eventType).Add(type);
  167. }
  168. }
  169. else if (type.GetInterfaceDefinition(typeof(IEventAction<>)) is Type eventActionInterface)
  170. {
  171. if (type.GetConstructor([]) is not null)
  172. {
  173. _actionTypes[type.Name] = type;
  174. var eventType = eventActionInterface.GenericTypeArguments[0];
  175. eventType = eventType.IsGenericType ? eventType.GetGenericTypeDefinition() : eventType;
  176. _eventActionTypes.GetValueOrAdd(eventType).Add(type);
  177. }
  178. }
  179. }
  180. }
  181. public static IEnumerable<Type> GetEventTriggerTypes(Type eventType)
  182. {
  183. LoadTypes();
  184. eventType = eventType.IsGenericType ? eventType.GetGenericTypeDefinition() : eventType;
  185. return _eventTriggerTypes.GetValueOrDefault(eventType) ?? Enumerable.Empty<Type>();
  186. }
  187. public static IEnumerable<Type> GetEventActionTypes(Type eventType)
  188. {
  189. LoadTypes();
  190. eventType = eventType.IsGenericType ? eventType.GetGenericTypeDefinition() : eventType;
  191. return _eventActionTypes.GetValueOrDefault(eventType) ?? Enumerable.Empty<Type>();
  192. }
  193. public static Type GetEventType(string type)
  194. {
  195. LoadTypes();
  196. return _eventTypes[type]; // Force exception if not a valid type name.
  197. }
  198. public static Type GetTriggerType(string type)
  199. {
  200. LoadTypes();
  201. return _triggerTypes[type]; // Force exception if not a valid type name.
  202. }
  203. public static Type GetActionType(string type)
  204. {
  205. LoadTypes();
  206. return _actionTypes[type]; // Force exception if not a valid type name.
  207. }
  208. #endregion
  209. #region Execution
  210. private static bool Check<T, TDataModel>(EventData<T, TDataModel> ev, TDataModel dataModel)
  211. where T : IEvent<TDataModel>
  212. where TDataModel : IEventDataModel
  213. {
  214. return ev.Triggers.Any(x => x.Check(dataModel));
  215. }
  216. public static void Run<T, TDataModel>(IStore store, Event ev, EventData<T, TDataModel> evData, TDataModel dataModel)
  217. where T : IEvent<TDataModel>
  218. where TDataModel : IEventDataModel
  219. {
  220. if (!Check(evData, dataModel)) return;
  221. foreach(var action in evData.Actions)
  222. {
  223. IEvent.RunAction(evData.Event, dataModel, action);
  224. }
  225. NotifySubscribers(store, ev, evData, dataModel);
  226. }
  227. private static void NotifySubscribers<T, TDataModel>(IStore store, Event ev, EventData<T, TDataModel> evData, TDataModel dataModel)
  228. where T : IEvent<TDataModel>
  229. where TDataModel : IEventDataModel
  230. {
  231. string? description;
  232. if (ev.NotificationExpression.IsNullOrWhiteSpace())
  233. {
  234. description = null;
  235. }
  236. else
  237. {
  238. var descriptionExpr = new CoreExpression(ev.NotificationExpression, typeof(string));
  239. if(!descriptionExpr.TryEvaluate<string>(dataModel).Get(out description, out var error))
  240. {
  241. CoreUtils.LogException(store.UserID, error, extra: "Error notifying subscribers", store.Logger);
  242. return;
  243. }
  244. }
  245. var subscribers = store.Provider.Query(
  246. new Filter<EventSubscriber>(x => x.Event.ID).IsEqualTo(ev.ID),
  247. Columns.None<EventSubscriber>().Add(x => x.Employee.ID))
  248. .ToArray<EventSubscriber>();
  249. var notifications = new List<Notification>();
  250. foreach(var subscriber in subscribers)
  251. {
  252. var notification = evData.GenerateNotification(dataModel);
  253. notification.Employee.CopyFrom(subscriber.Employee);
  254. if(description is not null)
  255. {
  256. notification.Description = description;
  257. }
  258. notifications.Add(notification);
  259. }
  260. store.Provider.Save(notifications);
  261. }
  262. #endregion
  263. }
  264. #region DataModel Definition
  265. public interface IEventVariable
  266. {
  267. string Name { get; set; }
  268. Type Type { get; set; }
  269. }
  270. public class StandardEventVariable : IEventVariable
  271. {
  272. public string Name { get; set; }
  273. public Type Type { get; set; }
  274. public StandardEventVariable(string name, Type type)
  275. {
  276. Name = name;
  277. Type = type;
  278. }
  279. }
  280. public class ListEventVariable : IEventVariable
  281. {
  282. public string Name { get; set; }
  283. public Type Type { get; set; }
  284. public ListEventVariable(string name, Type type)
  285. {
  286. Name = name;
  287. Type = type;
  288. }
  289. }
  290. public interface IEventDataModelDefinition
  291. {
  292. IEnumerable<IEventVariable> GetVariables();
  293. IEventVariable? GetVariable(string name);
  294. }
  295. #endregion
  296. #region DataModel
  297. public interface IEventDataModel : IVariableProvider
  298. {
  299. bool TryGetVariable(string name, out object? value);
  300. bool IVariableProvider.TryGetValue(string variableName, out object? value)
  301. {
  302. return TryGetVariable(variableName, out value);
  303. }
  304. T RootModel<T>()
  305. where T : IEventDataModel
  306. {
  307. if(this is IChildEventDataModel child)
  308. {
  309. return child.Parent.RootModel<T>();
  310. }
  311. else if(this is T root)
  312. {
  313. return root;
  314. }
  315. else
  316. {
  317. throw new Exception($"Root model of wrong type; expected {typeof(T).FullName}; got {GetType().FullName}");
  318. }
  319. }
  320. }
  321. public interface ITypedEventDataModel : IEventDataModel
  322. {
  323. public Type EntityType { get; }
  324. }
  325. public interface IChildEventDataModel : IEventDataModel
  326. {
  327. IEventDataModel Parent { get; }
  328. }
  329. public class ChildEventDataModel : IChildEventDataModel
  330. {
  331. public IEventDataModel Parent { get; set; }
  332. public Dictionary<string, object?> Values { get; set; } = new Dictionary<string, object?>();
  333. public ChildEventDataModel(IEventDataModel parent)
  334. {
  335. Parent = parent;
  336. }
  337. public bool TryGetVariable(string name, out object? value)
  338. {
  339. return Values.TryGetValue(name, out value)
  340. || Parent.TryGetVariable(name, out value);
  341. }
  342. }
  343. #endregion
  344. public interface IEvent : ISerializeBinary
  345. {
  346. IEventDataModelDefinition DataModelDefinition();
  347. public static void RunAction(IEvent ev, IEventDataModel model, IEventAction action)
  348. {
  349. var dataModelDef = ev.DataModelDefinition();
  350. var values = new List<(string name, object? value)[]>() { Array.Empty<(string, object?)>() };
  351. var vars = action.ReferencedVariables();
  352. foreach(var variable in vars)
  353. {
  354. var varDef = dataModelDef.GetVariable(variable);
  355. if(varDef is ListEventVariable)
  356. {
  357. if (model.TryGetVariable(varDef.Name, out var list) && list is IEnumerable enumerable)
  358. {
  359. var oldValues = values;
  360. values = new List<(string name, object? value)[]>();
  361. foreach(var item in enumerable)
  362. {
  363. foreach(var valueList in oldValues)
  364. {
  365. values.Add(valueList.Concatenate(new (string name, object? value)[]
  366. {
  367. (varDef.Name, item)
  368. }));
  369. }
  370. }
  371. }
  372. else
  373. {
  374. values.Clear();
  375. break;
  376. }
  377. }
  378. }
  379. if(values.Count > 0 && (values.Count > 1 || values[0].Length > 0))
  380. {
  381. var subModel = new ChildEventDataModel(model);
  382. foreach(var valueSet in values)
  383. {
  384. subModel.Values.Clear();
  385. foreach(var (name, value) in valueSet)
  386. {
  387. subModel.Values[name] = value;
  388. }
  389. action.Execute(subModel);
  390. }
  391. }
  392. else
  393. {
  394. action.Execute(model);
  395. }
  396. }
  397. }
  398. public interface IEvent<TDataModel> : IEvent
  399. {
  400. Notification GenerateNotification(TDataModel model);
  401. }
  402. public interface IEventTrigger
  403. {
  404. string GetDescription();
  405. }
  406. public interface IEventTrigger<TEvent, TDataModel> : ISerializeBinary, IEventTrigger
  407. where TEvent : IEvent<TDataModel>
  408. where TDataModel : IEventDataModel
  409. {
  410. bool Check(TDataModel dataModel);
  411. }
  412. public interface IEventAction : ISerializeBinary
  413. {
  414. IEnumerable<string> ReferencedVariables();
  415. object? Execute(IEventDataModel dataModel);
  416. string GetDescription();
  417. }
  418. public interface IEventAction<TEvent> : IEventAction
  419. where TEvent : IEvent
  420. {
  421. }