/* 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/ResourceTemplate.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 = new KeyList(); static bool storeIsOpen = false; //public delegate void StoreConnectedEvent(IStore store, string name); //public delegate void StoreDisconnectedEvent(IStore store); //public static event StoreConnectedEvent StoreConnected; ///public static event StoreDisconnectedEvent StoreDisconnected; static KeyList protocols = getProtocols(); /// /// 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); storeIsOpen = 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) { var rt = new List(); 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 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 void put(IResource resource, String name, [IStore store = null, IResource parent = null, ResourceTemplate customTemplate = null, int age = 0, IPermissionsManager manager = null, attributes = null]) { 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); if (resource is IStore) { _stores.add(resource); //StoreConnected?.Invoke(resource as IStore, name); } else store.put(resource); _resources[resource.instance.id] = resource; //if (!storeIsOpen) // resource.trigger(ResourceTrigger.Initialize); } static T New(String name, [IStore store = null, IResource parent = null, IPermissionsManager manager = null, Structure attributes = null]) { /* 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(ResourceTemplate template) { if (!_templates.containsKey(template.classId)) _templates.add(template.classId, template); } /// /// Get a template by type from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse. /// /// .Net type. /// Resource template. static ResourceTemplate getTemplateByType(Type type) { // loaded ? for (var t in _templates.values) if (t.className == type.toString()) return t; var template = new ResourceTemplate.fromType(type); _templates.add(template.classId, template); return template; } /// /// Get a template by class Id from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse. /// /// Class Id. /// Resource template. static AsyncReply getTemplateByClassId(Guid classId) { if (_templates.containsKey(classId)) return new AsyncReply.ready(_templates[classId]); return null; } /// /// Get a template by class name from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse. /// /// Class name. /// Resource template. static AsyncReply getTemplateByClassName(String className) { for (var t in _templates.values) if (t.className == className) return new AsyncReply.ready(t); return null; } 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; } } KeyList getProtocols() { var rt = new KeyList(); rt.add("iip", () => new DistributedConnection()); return rt; }