1 module elasticsearch.transport.connections.collection; 2 3 public import elasticsearch.transport.connections.connection; 4 public import elasticsearch.transport.connections.selector; 5 6 import std.algorithm; 7 import std.array; 8 9 class Collection { 10 private { 11 Connection[] _connections; 12 SelectorInterface _selector; 13 } 14 15 this() { 16 _selector = new RandomSelector(); 17 } 18 19 this(SelectorType)() { 20 _selector = new SelectorType(); 21 } 22 23 /// Returns an Array of all connections, both dead and alive 24 ref Connection[] all() { 25 return _connections; 26 } 27 28 /// Returns an Array of alive connections. 29 Connection[] alive() { 30 return array(_connections.filter!((connection) => !connection.dead)); 31 } 32 33 /// Returns an Array of dead connections. 34 Connection[] dead() { 35 return array(_connections.filter!((connection) => connection.dead)); 36 } 37 38 /** 39 * Returns a connection. 40 * 41 * If there are no alive connections, resurrects a connection with least failures. 42 * Delegates to selector's `*select` method to get the connection. 43 * 44 */ 45 Connection getConnection() { 46 if (all.length == 0) return null; 47 48 if (alive.length == 0) { 49 auto sortedDead = array(dead.sort!((a, b) => a.deadSince < b.deadSince)()); 50 sortedDead[0].makeAlive(); 51 } 52 53 return alive[_selector.select(this)]; 54 } 55 56 /// By default this returns an array of all the alive connections 57 alias alive this; 58 } 59 60 unittest { 61 auto c = new Collection(); 62 }