<?php
    /*   a
     Copyright (c) 2012, Paul G Talaga
     All rights reserved.
     
     Redistribution and use in source and binary forms, with or without
     modification, are permitted provided that the following conditions are met:
     * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     DISCLAIMED. IN NO EVENT SHALL Paul G Talaga BE LIABLE FOR ANY
     DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
     SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
	 
    
    // Wrapper class to memcache, provides snooping based cache locality using
	//	notes distributed to all other memcache clusters.  No data redundancy!
    // Due to this being in PHP, we can't issue simultaneous requests to all 
	//	racks at once.  Thus, we'll just have to deal with the slowdown until a 
    //  C implementation is done.
    include_once('Mem_RackAware.php');
    class Memcache_Snoop extends Memcache_RackAware{
        // constructor function
        function __construct(){
            // A note is stored under the appropriate key, with data 
			//	'<secret><rack id>', where rack id is where to find the 
			//	actual data.
            $this->secret = 'S!';  // Should be complex enough to prevent 
								   //collisions with acutal data.
            $this->rackConstruct(); // constructor for RackAware, 
					// provides $this->local which is the rack number this 
					// machine should use, and $this->racks which
                    // is an array of Memcache instances indexed by rack number.  
					// So $this->racks[$this->local] would be the closest 
					// memcache instance.
                                    //echo 'Snoop';
        }
        
        // addServer     provided by Memcache_RackAware
 /**************************************************************/    
        function add($key,$value,$flag = 0,$expire = 0){
            // Add item with key
            // Add note to all other racks
            $return = $this->racks[$this->local]->add($key,$value,$flag,$expire);
            if(!$return){return false;} // Fail if data or note already there.
            foreach($this->racks as $k => &$r){
                if($k != $this->local){ // Don't overwrite actual data!
                    $r->set($key,$this->secret . $this->local,$flag,$expire); 
						// We do a set just to be sure we don't fail somewhere else.
                }
            }
            return true;
        }
/**************************/         
        function connect($host,$port,$timeout = 1){
            return self::addServer($host,$port,TRUE,1,$timeout);
        } 
/**************************/         
        function delete($key,$timeout = 0){
            // Delete data with key.  We'll only return failure if local failed
            foreach($this->racks as $k => &$r){
                if($k != $this->local){ 
                    $r->delete($key,$timeout);
                }
            }
            return $this->racks[$this->local]->delete($key,$timeout);
        }
/**************************/         
        function flush(){
            // flush all racks!
           foreach($this->racks as &$r){
                $r->flush();
            }
        }
/**************************/         
        function get($key,$flags = ''){
            // Get local, and if note found go get actual.
            $ret = $this->racks[$this->local]->get($key,$flags);
            $len = strlen($this->secret);
            if($ret != FALSE && is_string($ret) && strlen($ret) > $len && substr($ret,0,strlen($this->secret)) == $this->secret){
                $ret = $this->racks[substr($ret,$len)]->get($key,$flags);
                if($ret === FALSE){
                    // Data not where it should be! remove all notes!
                    foreach($this->racks as $k => &$r){
                            $r->delete($key);
                    }
                }
            }
            return $ret; 
        }
/**************************/ 
        function replace($key, $value, $flags = '',$expire = 0){
            // Replace should return false if the item doesn't already exist.
            // But, so that we don't error to early (new rack being brought up), 
			//	we'll only error if the local copy doesn't exist
            // and use sets otherwise
            $return =  $this->racks[$this->local]->replace($key,$value,$flags,$expire);
            if(!$return){return false;}
            // unfortunatly we must update the expire times on all notes
            foreach($this->racks as $k => &$r){
                if($k != $this->local){ // Don't update twice!
                    $r->set($key,$this->secret . $this->local,$flags,$expire);
                }
            }
            return true;
        }
/**************************/ 
        function decrement($key, $amt = 1){
            // Decrement wherever it is, if local re-set all notes
            // Return value should be result after decrement, but possibility 
			//	exists for inconsistent result.
            $ret = $this->racks[$this->local]->get($key);
            $len = strlen($this->secret);
            if($ret != FALSE && is_string($ret) && strlen($ret) > $len && substr($ret,0,strlen($this->secret)) == $this->secret){
                //its somewhere else! decrement that!
                $ret = $this->racks[substr($ret,$len)]->decrement($key,$flags);
                if($ret === FALSE){
                    // Data not where it should be! remove all notes!
                    foreach($this->racks as $k => &$r){
                            $r->delete($key);
                    }
                }
            }else if($ret != FALSE){
                // must be local, try to decrement
                $ret = $this->racks[$this->local]->decrement($key,$amt);
                $flags = 0;
                $expire = 0; // PGT FIX
                // Touch notes to premote in LRU
                foreach($this->racks as $k => &$r){
                    if($k != $this->local){
                        $r->set($key,$this->secret . $this->local,$flags,$expire);
                    }
                }
            }
            return $ret;
        }
/**************************/        
        function increment($key, $amt = 1){
            // Increment on all racks
            // Return value should be result after increment, but possibility 
			//	exists for inconsistent result.
            // Here we return the local value, though we could also return 
			//	false if ANY returned a non-consistent value.
            $ret = $this->racks[$this->local]->get($key);
            $len = strlen($this->secret);
            if($ret != FALSE && is_string($ret) && strlen($ret) > $len && substr($ret,0,strlen($this->secret)) == $this->secret){
                //its somewhere else! decrement that!
                $ret = $this->racks[substr($ret,$len)]->increment($key,$flags);
                if($ret === FALSE){
                    // Data not where it should be! remove all notes!
                    foreach($this->racks as $k => &$r){
                            $r->delete($key);
                    }
                }
            }else if($ret != FALSE){
                // must be local, try to decrement
                $ret = $this->racks[$this->local]->increment($key,$amt);
                $flags = 0;
                $expire = 0; // PGT FIX
                // Touch notes to premote in LRU
                foreach($this->racks as $k => &$r){
                    if($k != $this->local){
                        $r->set($key,$this->secret . $this->local,$flags,$expire);
                    }
                }
            }
            return $ret;
        }
/**************************/         
        function set($key,&$value,$flag = 0,$expire = 0){
            // Set data on local, and note on all others
            $return = $this->racks[$this->local]->set($key,$value,$flag,$expire);
            if($return == FALSE){return FALSE;}
            foreach($this->racks as $k => $r){
                if($k != $this->local){ // Don't update twice!
                    $this->racks[$k]->set($key,$this->secret . $this->local,$flag,$expire);
                }
            }
            return true;
        }
/**************************/         
        function setCompressThreshold($limit){
            // Set limit in all racks
            foreach($this->racks as &$r){
                $r->setCompressThreshold($limit);
            }
        }
/**************************/         
        function getStats($type, $slabid, $limit = 100){
            return $this->racks[$this->local]->getStats($type,$slabid,$limig);
        }
/**************************/         
        function findServer($key){
            return $this->racks[$this->local]->findServer($key);
        }
}
?>
