DbFactory.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. using System.Reflection;
  2. using InABox.Clients;
  3. using InABox.Configuration;
  4. using InABox.Core;
  5. using InABox.Scripting;
  6. namespace InABox.Database
  7. {
  8. public static class DbFactory
  9. {
  10. public static Dictionary<string, ScriptDocument> LoadedScripts = new();
  11. private static IProvider? _provider;
  12. public static IProvider Provider
  13. {
  14. get => _provider ?? throw new Exception("Provider is not set");
  15. set => _provider = value;
  16. }
  17. public static bool IsProviderSet => _provider is not null;
  18. public static string? ColorScheme { get; set; }
  19. public static byte[]? Logo { get; set; }
  20. // See notes in Request.DatabaseInfo class
  21. // Once RPC transport is stable, these settings need
  22. // to be removed
  23. public static int RestPort { get; set; }
  24. public static int RPCPort { get; set; }
  25. //public static Type[] Entities { get { return entities; } set { SetEntityTypes(value); } }
  26. public static IEnumerable<Type> Entities
  27. {
  28. get { return CoreUtils.Entities.Where(x => x.GetInterfaces().Contains(typeof(IPersistent))); }
  29. }
  30. public static Type[] Stores
  31. {
  32. get => stores;
  33. set => SetStoreTypes(value);
  34. }
  35. public static DateTime Expiry { get; set; }
  36. public static void Start()
  37. {
  38. CoreUtils.CheckLicensing();
  39. var status = ValidateSchema();
  40. if (status.Equals(SchemaStatus.New))
  41. try
  42. {
  43. Provider.CreateSchema(ConsolidatedObjectModel().ToArray());
  44. SaveSchema();
  45. }
  46. catch (Exception err)
  47. {
  48. throw new Exception(string.Format("Unable to Create Schema\n\n{0}", err.Message));
  49. }
  50. else if (status.Equals(SchemaStatus.Changed))
  51. try
  52. {
  53. Provider.UpgradeSchema(ConsolidatedObjectModel().ToArray());
  54. SaveSchema();
  55. }
  56. catch (Exception err)
  57. {
  58. throw new Exception(string.Format("Unable to Update Schema\n\n{0}", err.Message));
  59. }
  60. // Start the provider
  61. Provider.Types = ConsolidatedObjectModel();
  62. Provider.OnLog += LogMessage;
  63. Provider.Start();
  64. if (!DataUpdater.MigrateDatabase())
  65. {
  66. throw new Exception("Database migration failed. Aborting startup");
  67. }
  68. //Load up your custom properties here!
  69. // Can't use clients (b/c were inside the database layer already
  70. // but we can simply access the store directly :-)
  71. //CustomProperty[] props = FindStore<CustomProperty>("", "", "", "").Load(new Filter<CustomProperty>(x=>x.ID).IsNotEqualTo(Guid.Empty),null);
  72. var props = Provider.Query<CustomProperty>().Rows.Select(x => x.ToObject<CustomProperty>()).ToArray();
  73. DatabaseSchema.Load(props);
  74. AssertLicense();
  75. BeginLicenseCheckTimer();
  76. InitStores();
  77. LoadScripts();
  78. }
  79. #region License
  80. private enum LicenseValidation
  81. {
  82. Valid,
  83. Missing,
  84. Expired,
  85. Corrupt,
  86. Tampered
  87. }
  88. private static LicenseValidation CheckLicenseValidity(out License? license, out LicenseData? licenseData)
  89. {
  90. license = Provider.Load<License>().FirstOrDefault();
  91. if (license is null)
  92. {
  93. licenseData = null;
  94. return LicenseValidation.Missing;
  95. }
  96. if (!LicenseUtils.TryDecryptLicense(license.Data, out licenseData, out var error))
  97. return LicenseValidation.Corrupt;
  98. if (licenseData.Expiry < DateTime.Now)
  99. return LicenseValidation.Expired;
  100. var userTrackingItems = Provider.Query(
  101. new Filter<UserTracking>(x => x.ID).InList(licenseData.UserTrackingItems),
  102. new Columns<UserTracking>(x => x.ID), log: false).Rows.Select(x => x.Get<UserTracking, Guid>(x => x.ID));
  103. foreach(var item in licenseData.UserTrackingItems)
  104. {
  105. if (!userTrackingItems.Contains(item))
  106. {
  107. return LicenseValidation.Tampered;
  108. }
  109. }
  110. return LicenseValidation.Valid;
  111. }
  112. private static int _expiredLicenseCounter = 0;
  113. private static TimeSpan LicenseCheckInterval = TimeSpan.FromMinutes(10);
  114. private static bool _readOnly;
  115. public static bool IsReadOnly { get => _readOnly; }
  116. private static System.Timers.Timer LicenseTimer = new System.Timers.Timer(LicenseCheckInterval.TotalMilliseconds) { AutoReset = true };
  117. private static void LogRenew(string message)
  118. {
  119. LogImportant($"{message} Please renew your license before then, or your database will go into read-only mode; it will be locked for saving anything until you renew your license. For help with renewing your license, please see the documentation at https://prsdigital.com.au/wiki/index.php/License_Renewal.");
  120. }
  121. private static void LogLicenseExpiry(DateTime expiry)
  122. {
  123. if (expiry.Date == DateTime.Today)
  124. {
  125. LogRenew($"Your database license is expiring today at {expiry.TimeOfDay:HH:mm}!");
  126. return;
  127. }
  128. var diffInDays = (expiry - DateTime.Now).TotalDays;
  129. if(diffInDays < 1)
  130. {
  131. LogRenew($"Your database license will expire in less than a day, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  132. }
  133. else if(diffInDays < 3 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 1)
  134. {
  135. LogRenew($"Your database license will expire in less than three days, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  136. _expiredLicenseCounter = 0;
  137. }
  138. else if(diffInDays < 7 && (_expiredLicenseCounter * LicenseCheckInterval).TotalHours >= 2)
  139. {
  140. LogRenew($"Your database license will expire in less than a week, on the {expiry:dd MMM yyyy} at {expiry:hh:mm:tt}.");
  141. _expiredLicenseCounter = 0;
  142. }
  143. ++_expiredLicenseCounter;
  144. }
  145. public static void LogReadOnly()
  146. {
  147. LogError("Database is read-only because your license is invalid!");
  148. }
  149. private static void BeginReadOnly()
  150. {
  151. LogImportant("Your database is now in read-only mode, since your license is invalid; you will be unable to save any records to the database until you renew your license. For help with renewing your license, please see the documentation at https://prsdigital.com.au/wiki/index.php/License_Renewal.");
  152. _readOnly = true;
  153. }
  154. private static void EndReadOnly()
  155. {
  156. LogImportant("Valid license found; the database is no longer read-only.");
  157. _readOnly = false;
  158. }
  159. private static void BeginLicenseCheckTimer()
  160. {
  161. LicenseTimer.Elapsed += LicenseTimer_Elapsed;
  162. LicenseTimer.Start();
  163. }
  164. private static void LicenseTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
  165. {
  166. AssertLicense();
  167. }
  168. private static Random LicenseIDGenerate = new Random();
  169. private static void UpdateValidLicense(License license, LicenseData licenseData)
  170. {
  171. var ids = Provider.Query(
  172. new Filter<UserTracking>(x => x.Created).IsGreaterThanOrEqualTo(licenseData.LastRenewal),
  173. new Columns<UserTracking>(x => x.ID), log: false);
  174. var newIDList = new List<Guid>();
  175. if(ids.Rows.Count > 0)
  176. {
  177. for (int i = 0; i < 10; i++)
  178. {
  179. newIDList.Add(ids.Rows[LicenseIDGenerate.Next(0, ids.Rows.Count)].Get<UserTracking, Guid>(x => x.ID));
  180. }
  181. }
  182. licenseData.UserTrackingItems = newIDList.ToArray();
  183. if(LicenseUtils.TryEncryptLicense(licenseData, out var newData, out var error))
  184. {
  185. license.Data = newData;
  186. Provider.Save(license);
  187. }
  188. }
  189. private static void AssertLicense()
  190. {
  191. var result = CheckLicenseValidity(out var license, out var licenseData);
  192. if (IsReadOnly)
  193. {
  194. if(result == LicenseValidation.Valid)
  195. {
  196. EndReadOnly();
  197. }
  198. return;
  199. }
  200. // TODO: Switch to real system
  201. if(result != LicenseValidation.Valid)
  202. {
  203. var newLicense = LicenseUtils.GenerateNewLicense();
  204. if (LicenseUtils.TryEncryptLicense(newLicense, out var newData, out var error))
  205. {
  206. if (license == null)
  207. license = new License();
  208. license.Data = newData;
  209. Provider.Save(license);
  210. }
  211. else
  212. {
  213. Logger.Send(LogType.Error, "", $"Error updating license: {error}");
  214. }
  215. return;
  216. }
  217. else
  218. {
  219. return;
  220. }
  221. switch (result)
  222. {
  223. case LicenseValidation.Valid:
  224. LogLicenseExpiry(licenseData!.Expiry);
  225. UpdateValidLicense(license, licenseData);
  226. break;
  227. case LicenseValidation.Missing:
  228. LogImportant("Database is unlicensed!");
  229. BeginReadOnly();
  230. break;
  231. case LicenseValidation.Expired:
  232. LogImportant("Database license has expired!");
  233. BeginReadOnly();
  234. break;
  235. case LicenseValidation.Corrupt:
  236. LogImportant("Database license is corrupt - you will need to renew your license.");
  237. BeginReadOnly();
  238. break;
  239. case LicenseValidation.Tampered:
  240. LogImportant("Database license has been tampered with - you will need to renew your license.");
  241. BeginReadOnly();
  242. break;
  243. }
  244. }
  245. #endregion
  246. #region Logging
  247. private static void LogMessage(LogType type, string message)
  248. {
  249. Logger.Send(type, "", message);
  250. }
  251. private static void LogInfo(string message)
  252. {
  253. Logger.Send(LogType.Information, "", message);
  254. }
  255. private static void LogImportant(string message)
  256. {
  257. Logger.Send(LogType.Important, "", message);
  258. }
  259. private static void LogError(string message)
  260. {
  261. Logger.Send(LogType.Error, "", message);
  262. }
  263. #endregion
  264. public static void InitStores()
  265. {
  266. foreach (var storetype in stores)
  267. {
  268. var store = (Activator.CreateInstance(storetype) as IStore)!;
  269. store.Provider = Provider;
  270. store.Init();
  271. }
  272. }
  273. public static IStore FindStore(Type type, Guid userguid, string userid, Platform platform, string version)
  274. {
  275. var defType = typeof(Store<>).MakeGenericType(type);
  276. Type? subType = Stores.Where(myType => myType.IsSubclassOf(defType)).FirstOrDefault();
  277. var store = (Activator.CreateInstance(subType ?? defType) as IStore)!;
  278. store.Provider = Provider;
  279. store.UserGuid = userguid;
  280. store.UserID = userid;
  281. store.Platform = platform;
  282. store.Version = version;
  283. return store;
  284. }
  285. public static IStore<TEntity> FindStore<TEntity>(Guid userguid, string userid, Platform platform, string version)
  286. where TEntity : Entity, new()
  287. {
  288. return (FindStore(typeof(TEntity), userguid, userid, platform, version) as IStore<TEntity>)!;
  289. }
  290. private static CoreTable DoQueryMultipleQuery<TEntity>(
  291. IQueryDef query,
  292. Guid userguid, string userid, Platform platform, string version)
  293. where TEntity : Entity, new()
  294. {
  295. var store = FindStore<TEntity>(userguid, userid, platform, version);
  296. return store.Query(query.Filter as Filter<TEntity>, query.Columns as Columns<TEntity>, query.SortOrder as SortOrder<TEntity>);
  297. }
  298. public static Dictionary<string, CoreTable> QueryMultiple(
  299. Dictionary<string, IQueryDef> queries,
  300. Guid userguid, string userid, Platform platform, string version)
  301. {
  302. var result = new Dictionary<string, CoreTable>();
  303. var queryMethod = typeof(DbFactory).GetMethod(nameof(DoQueryMultipleQuery), BindingFlags.NonPublic | BindingFlags.Static)!;
  304. var tasks = new List<Task>();
  305. foreach (var item in queries)
  306. tasks.Add(Task.Run(() =>
  307. {
  308. result[item.Key] = (queryMethod.MakeGenericMethod(item.Value.Type).Invoke(Provider, new object[]
  309. {
  310. item.Value,
  311. userguid, userid, platform, version
  312. }) as CoreTable)!;
  313. }));
  314. Task.WaitAll(tasks.ToArray());
  315. return result;
  316. }
  317. #region Supported Types
  318. private class ModuleConfiguration : Dictionary<string, bool>, ILocalConfigurationSettings
  319. {
  320. }
  321. private static Type[]? _dbtypes;
  322. public static IEnumerable<string> SupportedTypes()
  323. {
  324. _dbtypes ??= LoadSupportedTypes();
  325. return _dbtypes.Select(x => x.EntityName().Replace(".", "_"));
  326. }
  327. private static Type[] LoadSupportedTypes()
  328. {
  329. var result = new List<Type>();
  330. var path = Provider.URL.ToLower();
  331. var config = new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Load();
  332. var bChanged = false;
  333. foreach (var type in Entities)
  334. {
  335. var key = type.EntityName();
  336. if (config.ContainsKey(key))
  337. {
  338. if (config[key])
  339. //Logger.Send(LogType.Information, "", String.Format("{0} is enabled", key));
  340. result.Add(type);
  341. else
  342. Logger.Send(LogType.Information, "", string.Format("Entity [{0}] is disabled", key));
  343. }
  344. else
  345. {
  346. //Logger.Send(LogType.Information, "", String.Format("{0} does not exist - enabling", key));
  347. config[key] = true;
  348. result.Add(type);
  349. bChanged = true;
  350. }
  351. }
  352. if (bChanged)
  353. new LocalConfiguration<ModuleConfiguration>(Path.GetDirectoryName(path) ?? "", Path.GetFileName(path)).Save(config);
  354. return result.ToArray();
  355. }
  356. public static bool IsSupported<T>() where T : Entity
  357. {
  358. _dbtypes ??= LoadSupportedTypes();
  359. return _dbtypes.Contains(typeof(T));
  360. }
  361. #endregion
  362. //public static void OpenSession(bool write)
  363. //{
  364. // Provider.OpenSession(write);
  365. //}
  366. //public static void CloseSession()
  367. //{
  368. // Provider.CloseSession();
  369. //}
  370. #region Private Methods
  371. public static void LoadScripts()
  372. {
  373. Logger.Send(LogType.Information, "", "Loading Script Cache...");
  374. LoadedScripts.Clear();
  375. var scripts = Provider.Load(
  376. new Filter<Script>
  377. (x => x.ScriptType).IsEqualTo(ScriptType.BeforeQuery)
  378. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterQuery)
  379. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeSave)
  380. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterSave)
  381. .Or(x => x.ScriptType).IsEqualTo(ScriptType.BeforeDelete)
  382. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterDelete)
  383. .Or(x => x.ScriptType).IsEqualTo(ScriptType.AfterLoad)
  384. );
  385. foreach (var script in scripts)
  386. {
  387. var key = string.Format("{0} {1}", script.Section, script.ScriptType.ToString());
  388. var doc = new ScriptDocument(script.Code);
  389. if (doc.Compile())
  390. {
  391. Logger.Send(LogType.Information, "",
  392. string.Format("- {0}.{1} Compiled Successfully", script.Section, script.ScriptType.ToString()));
  393. LoadedScripts[key] = doc;
  394. }
  395. else
  396. {
  397. Logger.Send(LogType.Error, "",
  398. string.Format("- {0}.{1} Compile Exception:\n{2}", script.Section, script.ScriptType.ToString(), doc.Result));
  399. }
  400. }
  401. Logger.Send(LogType.Information, "", "Loading Script Cache Complete");
  402. }
  403. //private static Type[] entities = null;
  404. //private static void SetEntityTypes(Type[] types)
  405. //{
  406. // foreach (Type type in types)
  407. // {
  408. // if (!type.IsSubclassOf(typeof(Entity)))
  409. // throw new Exception(String.Format("{0} is not a valid entity", type.Name));
  410. // }
  411. // entities = types;
  412. //}
  413. private static Type[] stores = { };
  414. private static void SetStoreTypes(Type[] types)
  415. {
  416. types = types.Where(
  417. myType => myType.IsClass
  418. && !myType.IsAbstract
  419. && !myType.IsGenericType).ToArray();
  420. foreach (var type in types)
  421. if (!type.GetInterfaces().Contains(typeof(IStore)))
  422. throw new Exception(string.Format("{0} is not a valid store", type.Name));
  423. stores = types;
  424. }
  425. private static Type[] ConsolidatedObjectModel()
  426. {
  427. // Add the core types from InABox.Core
  428. var types = new List<Type>();
  429. //var coreTypes = CoreUtils.TypeList(
  430. // new Assembly[] { typeof(Entity).Assembly },
  431. // myType =>
  432. // myType.IsClass
  433. // && !myType.IsAbstract
  434. // && !myType.IsGenericType
  435. // && myType.IsSubclassOf(typeof(Entity))
  436. // && myType.GetInterfaces().Contains(typeof(IRemotable))
  437. //);
  438. //types.AddRange(coreTypes);
  439. // Now add the end-user object model
  440. types.AddRange(Entities.Where(x =>
  441. x.GetTypeInfo().IsClass
  442. && !x.GetTypeInfo().IsGenericType
  443. && x.GetTypeInfo().IsSubclassOf(typeof(Entity))
  444. ));
  445. return types.ToArray();
  446. }
  447. private enum SchemaStatus
  448. {
  449. New,
  450. Changed,
  451. Validated
  452. }
  453. private static Dictionary<string, Type> GetSchema()
  454. {
  455. var model = new Dictionary<string, Type>();
  456. var objectmodel = ConsolidatedObjectModel();
  457. foreach (var type in objectmodel)
  458. {
  459. Dictionary<string, Type> thismodel = CoreUtils.PropertyList(type, x => true, true);
  460. foreach (var key in thismodel.Keys)
  461. model[type.Name + "." + key] = thismodel[key];
  462. }
  463. return model;
  464. //return Serialization.Serialize(model, Formatting.Indented);
  465. }
  466. private static SchemaStatus ValidateSchema()
  467. {
  468. var db_schema = Provider.GetSchema();
  469. if (db_schema.Count() == 0)
  470. return SchemaStatus.New;
  471. var mdl_json = Serialization.Serialize(GetSchema());
  472. var db_json = Serialization.Serialize(db_schema);
  473. return mdl_json.Equals(db_json) ? SchemaStatus.Validated : SchemaStatus.Changed;
  474. }
  475. private static void SaveSchema()
  476. {
  477. Provider.SaveSchema(GetSchema());
  478. }
  479. #endregion
  480. }
  481. }