/* Copyright (c) 2019 Ahmed Kh. Zamil Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import '../Data/AutoList.dart'; import 'Template/TemplateType.dart'; import 'Template/TypeTemplate.dart'; import '../Data/Guid.dart'; import '../Data/KeyList.dart'; import '../Data/Structure.dart'; import '../Security/Permissions/IPermissionsManager.dart'; import 'IResource.dart'; import 'Instance.dart'; import 'IStore.dart'; import '../Core/AsyncReply.dart'; import '../Core/AsyncBag.dart'; import 'ResourceTrigger.dart'; import '../Net/IIP/DistributedConnection.dart'; // Centeral Resource Issuer class Warehouse { static AutoList _stores = new AutoList(null); static Map _resources = new Map(); static int resourceCounter = 0; static KeyList> _templates = _initTemplates(); // static _initTemplates() { var rt = new KeyList>(); rt.add(TemplateType.Unspecified, new KeyList()); rt.add(TemplateType.Resource, new KeyList()); rt.add(TemplateType.Record, new KeyList()); rt.add(TemplateType.Wrapper, new KeyList()); return rt; } static KeyList _factory = _getBuiltInTypes(); static KeyList Function(String, dynamic)> protocols = _getSupportedProtocols(); static bool _warehouseIsOpen = false; static final _urlRegex = RegExp(r'^(?:([^\s|:]*):\/\/([^\/]*)\/?(.*))'); /// /// Get a store by its name. /// /// Store instance name /// static IStore getStore(String name) { for (var s in _stores) if (s.instance.name == name) return s; return null; } /// /// Get a resource by instance Id. /// /// Instance Id /// static AsyncReply getById(int id) { if (_resources.containsKey(id)) return new AsyncReply.ready(_resources[id]); else return new AsyncReply.ready(null); } /// /// Open the warehouse. /// This function issues the initialize trigger to all stores and resources. /// /// True, if no problem occurred. static AsyncReply open() { var bag = new AsyncBag(); for (var s in _stores) bag.add(s.trigger(ResourceTrigger.Initialize)); bag.seal(); var rt = new AsyncReply(); bag.then((x) { for (var b in x) if (!b) { rt.trigger(false); return; } var rBag = new AsyncBag(); for (var rk in _resources.keys) rBag.add(_resources[rk].trigger(ResourceTrigger.SystemInitialized)); rBag.seal(); rBag.then((y) { for (var b in y) if (!b) { rt.trigger(false); return; } rt.trigger(true); _warehouseIsOpen = true; }); }); return rt; } /// /// Close the warehouse. /// This function issues terminate trigger to all resources and stores. /// /// True, if no problem occurred. static AsyncReply close() { var bag = new AsyncBag(); for (var resource in _resources.values) if (!(resource is IStore)) bag.add(resource.trigger(ResourceTrigger.Terminate)); for (var s in _stores) bag.add(s.trigger(ResourceTrigger.Terminate)); for (var resource in _resources.values) if (!(resource is IStore)) bag.add(resource.trigger(ResourceTrigger.SystemTerminated)); for (var store in _stores) bag.add(store.trigger(ResourceTrigger.SystemTerminated)); bag.seal(); var rt = new AsyncReply(); bag.then((x) { for (var b in x) if (!b) { rt.trigger(false); return; } rt.trigger(true); }); return rt; } static List qureyIn( List path, int index, AutoList resources) { List rt = []; if (index == path.length - 1) { if (path[index] == "") for (var child in resources) rt.add(child); else for (var child in resources) if (child.instance.name == path[index]) rt.add(child); } else for (var child in resources) if (child.instance.name == path[index]) rt.addAll(qureyIn(path, index + 1, child.instance.children)); return rt; } static AsyncReply> query(String path) { if (path == null || path == "") { var roots = _stores.where((s) => s.instance.parents.length == 0).toList(); return new AsyncReply>.ready(roots); } else { var rt = new AsyncReply>(); get(path).then((x) { var p = path.split('/'); if (x == null) { rt.trigger(qureyIn(p, 0, _stores)); } else { var ar = qureyIn(p, 0, _stores).where((r) => r != x).toList(); ar.insert(0, x); rt.trigger(ar); } }); return rt; } } /// /// Get a resource by its path. /// Resource path is sperated by '/' character, e.g. "system/http". /// /// /// Resource instance. static AsyncReply get(String path, [attributes = null, IResource parent = null, IPermissionsManager manager = null]) { var rt = AsyncReply(); // Should we create a new store ? if (_urlRegex.hasMatch(path)) { var url = _urlRegex.allMatches(path).first; if (protocols.containsKey(url[1])) { var handler = protocols[url[1]]; var getFromStore = () { handler(url[2], attributes).then((store) { if (url[3].length > 0 && url[3] != "") store.get(url[3]).then((r) { rt.trigger(r); }).error((e) => rt.triggerError(e)); else rt.trigger(store as T); }).error((e) { rt.triggerError(e); //Warehouse.remove(store); }); }; if (!_warehouseIsOpen) open().then((v) { if (v) getFromStore(); else rt.trigger(null); }); else getFromStore(); return rt; } } query(path).then((rs) { if (rs != null && rs.length > 0) rt.trigger(rs[0]); else rt.trigger(null); }); return rt; /* var p = path.split('/'); IResource res; for(IStore d in _stores) if (p[0] == d.instance.name) { var i = 1; res = d; while(p.length > i) { var si = i; for (IResource r in res.instance.children) if (r.instance.name == p[i]) { i++; res = r; break; } if (si == i) // not found, ask the store return d.get(path.substring(p[0].length + 1)); } return new AsyncReply.ready(res); } // Should we create a new store ? if (path.contains("://")) { var url = path.split("://"); var hostname = url[1].split('/')[0]; var pathname = url[1].split('/').skip(1).join("/"); var rt = new AsyncReply(); if (protocols.containsKey(url[0])) { var handler = protocols[url[0]]; var store = handler(); put(store, url[0] + "://" + hostname, null, parent, null, 0, manager, attributes); store.trigger(ResourceTrigger.Open).then((x){ if (pathname.length > 0 && pathname != "") store.get(pathname).then((r) => rt.trigger(r) ).error((e) => rt.triggerError(e) ); else rt.trigger(store); }).error((e) { rt.triggerError(e); Warehouse.remove(store); }); } return rt; } return new AsyncReply.ready(null); */ } /// /// Put a resource in the warehouse. /// /// Resource instance. /// Resource name. /// IStore that manages the resource. Can be null if the resource is a store. /// Parent resource. if not presented the store becomes the parent for the resource. static AsyncReply put(String name, T resource, [IStore store = null, IResource parent = null, TypeTemplate customTemplate = null, int age = 0, IPermissionsManager manager = null, attributes = null]) { var rt = AsyncReply(); if (resource.instance != null) { rt.triggerError(Exception("Resource has a store.")); return rt; } // @TODO: Trim left '/' char // var path = name.trimLeft().split("/"); // if (path.length > 1) // { // if (parent != null) // rt.triggerError(Exception("Parent can't be set when using path in instance name")); // Warehouse.get(path.take(path.length - 1).join("/")).then((value){ // if (value == null) // rt.triggerError(Exception("Can't find parent")); // parent = value; // store = store ?? parent.instance.store; // var instanceName = path.last; // if (store == null) // { // // assign parent as a store // if (parent is IStore) // { // store = (IStore)parent; // stores // List> list; // if (stores.TryGetValue(store, out list)) // lock (((ICollection)list).SyncRoot) // list.Add(resourceReference); // //stores[store].Add(resourceReference); // } // // assign parent's store as a store // else if (parent != null) // { // store = parent.instance.store; // List> list; // if (stores.TryGetValue(store, out list)) // lock (((ICollection)list).SyncRoot) // list.Add(resourceReference); // //stores[store].Add(resourceReference); // } // // assign self as a store (root store) // else if (resource is IStore) // { // store = resource; // } // else // throw new Exception("Can't find a store for the resource."); // } // }); // } resource.instance = new Instance( resourceCounter++, name, resource, store, customTemplate, age); if (attributes != null) resource.instance.setAttributes(Structure.fromMap(attributes)); if (manager != null) resource.instance.managers.add(manager); if (store == parent) parent = null; if (parent == null) { if (!(resource is IStore)) store.instance.children.add(resource); } else parent.instance.children.add(resource); var initResource = () { _resources[resource.instance.id] = resource; if (_warehouseIsOpen) { resource.trigger(ResourceTrigger.Initialize).then((value) { if (resource is IStore) resource.trigger(ResourceTrigger.Open).then((value) { rt.trigger(resource); }).error((ex) { Warehouse.remove(resource); rt.triggerError(ex); }); else rt.trigger(resource); }).error((ex) { Warehouse.remove(resource); rt.triggerError(ex); }); } }; if (resource is IStore) { _stores.add(resource); initResource(); } else { store.put(resource).then((value) { if (value) initResource(); else rt.trigger(null); }).error((ex) { Warehouse.remove(resource); rt.triggerError(ex); }); } // return new name return rt; } static T createInstance(Type T) { return _factory[T].call(); } static AsyncReply newResource(String name, [IStore store = null, IResource parent = null, IPermissionsManager manager = null, attributes = null, properties = null]) { var resource = _factory[T].call(); if (properties != null) { dynamic d = resource; for (var i = 0; i < properties.length; i++) d[properties.keys.elementAt(i)] = properties.at(i); //setProperty(resource, properties.keys.elementAt(i), properties.at(i)); } var rt = AsyncReply(); put(name, resource, store, parent, null, 0, manager, attributes) .then((value) { if (value != null) rt.trigger(resource); else rt.trigger(null); }).error((ex) => rt.triggerError(ex)); return rt; /* var type = ResourceProxy.GetProxy(); var res = Activator.CreateInstance(type) as IResource; put(res, name, store, parent, null, 0, manager, attributes); return (T)res; */ } /// /// Put a resource template in the templates warehouse. /// /// Resource template. static void putTemplate(TypeTemplate template) { _templates[template.type][template.classId] = template; } /// /// Get a template by type from the templates warehouse. If not in the warehouse, a new TypeTemplate is created and added to the warehouse. /// /// .Net type. /// Resource template. static TypeTemplate getTemplateByType(Type type) { // loaded ? for (var tmps in _templates.values) for (var tmp in tmps.values) if (tmp.className == type.toString()) return tmp; var template = new TypeTemplate.fromType(type, true); return template; } /// /// Get a template by class Id from the templates warehouse. If not in the warehouse, a new TypeTemplate is created and added to the warehouse. /// /// Class Id. /// Resource template. static TypeTemplate getTemplateByClassId(Guid classId, [TemplateType templateType = TemplateType.Unspecified]) { if (templateType == TemplateType.Unspecified) { // look in resources var template = _templates[TemplateType.Resource][classId]; if (template != null) return template; // look in records template = _templates[TemplateType.Record][classId]; if (template != null) return template; // look in wrappers template = _templates[TemplateType.Wrapper][classId]; return template; } else { return _templates[templateType][classId]; } } /// /// Get a template by class name from the templates warehouse. If not in the warehouse, a new TypeTemplate is created and added to the warehouse. /// /// Class name. /// Resource template. static TypeTemplate getTemplateByClassName(String className, [TemplateType templateType = TemplateType.Unspecified]) { if (templateType == TemplateType.Unspecified) { // look in resources var template = _templates[TemplateType.Resource].values.firstWhere((x) => x.className == className); if (template != null) return template; // look in records template = _templates[TemplateType.Record].values.firstWhere((x) => x.className == className); if (template != null) return template; // look in wrappers template = _templates[TemplateType.Wrapper].values.firstWhere((x) => x.className == className); return template; } else { return _templates[templateType].values.firstWhere((x) => x.className == className); } } static bool remove(IResource resource) { if (resource.instance == null) return false; if (_resources.containsKey(resource.instance.id)) _resources.remove(resource.instance.id); else return false; if (resource is IStore) { _stores.remove(resource); // remove all objects associated with the store var toBeRemoved = _resources.values.where((x) => x.instance.store == resource); for (var o in toBeRemoved) remove(o); // StoreDisconnected?.Invoke(resource as IStore); } if (resource.instance.store != null) resource.instance.store.remove(resource); resource.destroy(); return true; } static KeyList Function(String, dynamic)> _getSupportedProtocols() { var rt = new KeyList Function(String, dynamic)>(); rt.add( "iip", (String name, attributes) => Warehouse.newResource( name, null, null, null, attributes)); return rt; } static KeyList _getBuiltInTypes() { var rt = KeyList(); rt.add(DistributedConnection, () => DistributedConnection()); return rt; } }