Merge "Revert "Adding sanity check to Title::isRedirect().""
[lhc/web/wiklou.git] / includes / filerepo / backend / SwiftFileBackend.php
index f40c323..36d4334 100644 (file)
@@ -41,12 +41,14 @@ class SwiftFileBackend extends FileBackendStore {
        protected $auth; // Swift authentication handler
        protected $authTTL; // integer seconds
        protected $swiftAnonUser; // string; username to handle unauthenticated requests
+       protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
        protected $maxContCacheSize = 300; // integer; max containers with entries
 
        /** @var CF_Connection */
        protected $conn; // Swift connection handle
        protected $connStarted = 0; // integer UNIX timestamp
        protected $connContainers = array(); // container object cache
+       protected $connException; // CloudFiles exception
 
        /**
         * @see FileBackendStore::__construct()
@@ -56,6 +58,7 @@ class SwiftFileBackend extends FileBackendStore {
         *    swiftKey           : Swift authentication key for the above user
         *    swiftAuthTTL       : Swift authentication TTL (seconds)
         *    swiftAnonUser      : Swift user used for end-user requests (account:username)
+        *    swiftUseCDN        : Whether a Cloud Files Content Delivery Network is set up
         *    shardViaHashLevels : Map of container names to sharding config with:
         *                         'base'   : base of hash characters, 16 or 36
         *                         'levels' : the number of hash levels (and digits)
@@ -64,6 +67,9 @@ class SwiftFileBackend extends FileBackendStore {
         */
        public function __construct( array $config ) {
                parent::__construct( $config );
+               if ( !MWInit::classExists( 'CF_Constants' ) ) {
+                       throw new MWException( 'SwiftCloudFiles extension not installed.' );
+               }
                // Required settings
                $this->auth = new CF_Authentication(
                        $config['swiftUser'],
@@ -81,6 +87,9 @@ class SwiftFileBackend extends FileBackendStore {
                $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
                        ? $config['shardViaHashLevels']
                        : '';
+               $this->swiftUseCDN = isset( $config['swiftUseCDN'] )
+                       ? $config['swiftUseCDN']
+                       : false;
                // Cache container info to mask latency
                $this->memCache = wfGetMainCache();
        }
@@ -110,9 +119,8 @@ class SwiftFileBackend extends FileBackendStore {
                        $this->getContainer( $container );
                        return true; // container exists
                } catch ( NoSuchContainerException $e ) {
-               } catch ( InvalidResponseException $e ) {
-               } catch ( Exception $e ) { // some other exception?
-                       $this->logException( $e, __METHOD__, array( 'path' => $storagePath ) );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, null, __METHOD__, array( 'path' => $storagePath ) );
                }
 
                return false;
@@ -143,12 +151,8 @@ class SwiftFileBackend extends FileBackendStore {
                } catch ( NoSuchContainerException $e ) {
                        $status->fatal( 'backend-fail-create', $params['dst'] );
                        return $status;
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
@@ -167,20 +171,36 @@ class SwiftFileBackend extends FileBackendStore {
                        $obj->set_etag( md5( $params['content'] ) );
                        // Use the same content type as StreamFile for security
                        $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
-                       // Actually write the object in Swift
-                       $obj->write( $params['content'] );
+                       if ( !empty( $params['async'] ) ) { // deferred
+                               $handle = $obj->write_async( $params['content'] );
+                               $status->value = new SwiftFileOpHandle( $this, $params, 'Create', $handle );
+                               $status->value->affectedObjects[] = $obj;
+                       } else { // actually write the object in Swift
+                               $obj->write( $params['content'] );
+                               $this->purgeCDNCache( array( $obj ) );
+                       }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
                } catch ( BadContentTypeException $e ) {
                        $status->fatal( 'backend-fail-contenttype', $params['dst'] );
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                }
 
                return $status;
        }
 
+       /**
+        * @see SwiftFileBackend::doExecuteOpHandlesInternal()
+        */
+       protected function _getResponseCreate( CF_Async_Op $cfOp, Status $status, array $params ) {
+               try {
+                       $cfOp->getLastResponse();
+               } catch ( BadContentTypeException $e ) {
+                       $status->fatal( 'backend-fail-contenttype', $params['dst'] );
+               }
+       }
+
        /**
         * @see FileBackendStore::doStoreInternal()
         * @return Status
@@ -206,12 +226,8 @@ class SwiftFileBackend extends FileBackendStore {
                } catch ( NoSuchContainerException $e ) {
                        $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
                        return $status;
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
@@ -234,22 +250,48 @@ class SwiftFileBackend extends FileBackendStore {
                        $obj->set_etag( md5_file( $params['src'] ) );
                        // Use the same content type as StreamFile for security
                        $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
-                       // Actually write the object in Swift
-                       $obj->load_from_filename( $params['src'], True ); // calls $obj->write()
+                       if ( !empty( $params['async'] ) ) { // deferred
+                               wfSuppressWarnings();
+                               $fp = fopen( $params['src'], 'rb' );
+                               wfRestoreWarnings();
+                               if ( !$fp ) {
+                                       $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
+                               } else {
+                                       $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
+                                       $status->value = new SwiftFileOpHandle( $this, $params, 'Store', $handle );
+                                       $status->value->resourcesToClose[] = $fp;
+                                       $status->value->affectedObjects[] = $obj;
+                               }
+                       } else { // actually write the object in Swift
+                               $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
+                               $this->purgeCDNCache( array( $obj ) );
+                       }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
                } catch ( BadContentTypeException $e ) {
                        $status->fatal( 'backend-fail-contenttype', $params['dst'] );
                } catch ( IOException $e ) {
                        $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                }
 
                return $status;
        }
 
+       /**
+        * @see SwiftFileBackend::doExecuteOpHandlesInternal()
+        */
+       protected function _getResponseStore( CF_Async_Op $cfOp, Status $status, array $params ) {
+               try {
+                       $cfOp->getLastResponse();
+               } catch ( BadContentTypeException $e ) {
+                       $status->fatal( 'backend-fail-contenttype', $params['dst'] );
+               } catch ( IOException $e ) {
+                       $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
+               }
+       }
+
        /**
         * @see FileBackendStore::doCopyInternal()
         * @return Status
@@ -282,30 +324,116 @@ class SwiftFileBackend extends FileBackendStore {
                } catch ( NoSuchContainerException $e ) {
                        $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
                        return $status;
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
                // (b) Actually copy the file to the destination
                try {
-                       $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
+                       $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
+                       if ( !empty( $params['async'] ) ) { // deferred
+                               $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
+                               $status->value = new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
+                               $status->value->affectedObjects[] = $dstObj;
+                       } else { // actually write the object in Swift
+                               $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
+                               $this->purgeCDNCache( array( $dstObj ) );
+                       }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
                } catch ( NoSuchObjectException $e ) { // source object does not exist
                        $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
+               }
+
+               return $status;
+       }
+
+       /**
+        * @see SwiftFileBackend::doExecuteOpHandlesInternal()
+        */
+       protected function _getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
+               try {
+                       $cfOp->getLastResponse();
+               } catch ( NoSuchObjectException $e ) { // source object does not exist
+                       $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
+               }
+       }
+
+       /**
+        * @see FileBackendStore::doMoveInternal()
+        * @return Status
+        */
+       protected function doMoveInternal( array $params ) {
+               $status = Status::newGood();
+
+               list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
+               if ( $srcRel === null ) {
+                       $status->fatal( 'backend-fail-invalidpath', $params['src'] );
+                       return $status;
+               }
+
+               list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
+               if ( $dstRel === null ) {
+                       $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
+                       return $status;
+               }
+
+               // (a) Check the source/destination containers and destination object
+               try {
+                       $sContObj = $this->getContainer( $srcCont );
+                       $dContObj = $this->getContainer( $dstCont );
+                       if ( empty( $params['overwrite'] ) &&
+                               $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
+                       {
+                               $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
+                               return $status;
+                       }
+               } catch ( NoSuchContainerException $e ) {
+                       $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
+                       return $status;
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
+                       return $status;
+               }
+
+               // (b) Actually move the file to the destination
+               try {
+                       $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
+                       $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
+                       if ( !empty( $params['async'] ) ) { // deferred
+                               $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
+                               $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $handle );
+                               $status->value->affectedObjects[] = $srcObj;
+                               $status->value->affectedObjects[] = $dstObj;
+                       } else { // actually write the object in Swift
+                               $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
+                               $this->purgeCDNCache( array( $srcObj, $dstObj ) );
+                       }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
+               } catch ( NoSuchObjectException $e ) { // source object does not exist
+                       $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                }
 
                return $status;
        }
 
+       /**
+        * @see SwiftFileBackend::doExecuteOpHandlesInternal()
+        */
+       protected function _getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
+               try {
+                       $cfOp->getLastResponse();
+               } catch ( NoSuchObjectException $e ) { // source object does not exist
+                       $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
+               }
+       }
+
        /**
         * @see FileBackendStore::doDeleteInternal()
         * @return Status
@@ -321,23 +449,45 @@ class SwiftFileBackend extends FileBackendStore {
 
                try {
                        $sContObj = $this->getContainer( $srcCont );
-                       $sContObj->delete_object( $srcRel );
+                       $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
+                       if ( !empty( $params['async'] ) ) { // deferred
+                               $handle = $sContObj->delete_object_async( $srcRel );
+                               $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
+                               $status->value->affectedObjects[] = $srcObj;
+                       } else { // actually write the object in Swift
+                               $sContObj->delete_object( $srcRel );
+                               $this->purgeCDNCache( array( $srcObj ) );
+                       }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
                } catch ( NoSuchContainerException $e ) {
                        $status->fatal( 'backend-fail-delete', $params['src'] );
                } catch ( NoSuchObjectException $e ) {
                        if ( empty( $params['ignoreMissingSource'] ) ) {
                                $status->fatal( 'backend-fail-delete', $params['src'] );
                        }
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                }
 
                return $status;
        }
 
+       /**
+        * @see SwiftFileBackend::doExecuteOpHandlesInternal()
+        */
+       protected function _getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
+               try {
+                       $cfOp->getLastResponse();
+               } catch ( NoSuchContainerException $e ) {
+                       $status->fatal( 'backend-fail-delete', $params['src'] );
+               } catch ( NoSuchObjectException $e ) {
+                       if ( empty( $params['ignoreMissingSource'] ) ) {
+                               $status->fatal( 'backend-fail-delete', $params['src'] );
+                       }
+               }
+       }
+
        /**
         * @see FileBackendStore::doPrepareInternal()
         * @return Status
@@ -352,32 +502,29 @@ class SwiftFileBackend extends FileBackendStore {
                        return $status; // already exists
                } catch ( NoSuchContainerException $e ) {
                        // NoSuchContainerException thrown: container does not exist
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
                // (b) Create container as needed
                try {
                        $contObj = $this->createContainer( $fullCont );
+                       // Make container public to end-users...
                        if ( $this->swiftAnonUser != '' ) {
-                               // Make container public to end-users...
                                $status->merge( $this->setContainerAccess(
                                        $contObj,
                                        array( $this->auth->username, $this->swiftAnonUser ), // read
                                        array( $this->auth->username ) // write
                                ) );
                        }
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+                       if ( $this->swiftUseCDN ) { // Rackspace style CDN
+                               $contObj->make_public();
+                       }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
@@ -391,29 +538,31 @@ class SwiftFileBackend extends FileBackendStore {
        protected function doSecureInternal( $fullCont, $dir, array $params ) {
                $status = Status::newGood();
 
-               if ( $this->swiftAnonUser != '' ) {
-                       // Restrict container from end-users...
-                       try {
-                               // doPrepareInternal() should have been called,
-                               // so the Swift container should already exist...
-                               $contObj = $this->getContainer( $fullCont ); // normally a cache hit
-                               // NoSuchContainerException not thrown: container must exist
-                               if ( !isset( $contObj->mw_wasSecured ) ) {
-                                       $status->merge( $this->setContainerAccess(
-                                               $contObj,
-                                               array( $this->auth->username ), // read
-                                               array( $this->auth->username ) // write
-                                       ) );
-                                       // @TODO: when php-cloudfiles supports container
-                                       // metadata, we can make use of that to avoid RTTs
-                                       $contObj->mw_wasSecured = true; // avoid useless RTTs
-                               }
-                       } catch ( InvalidResponseException $e ) {
-                               $status->fatal( 'backend-fail-connect', $this->name );
-                       } catch ( Exception $e ) { // some other exception?
-                               $status->fatal( 'backend-fail-internal', $this->name );
-                               $this->logException( $e, __METHOD__, $params );
+               // Restrict container from end-users...
+               try {
+                       // doPrepareInternal() should have been called,
+                       // so the Swift container should already exist...
+                       $contObj = $this->getContainer( $fullCont ); // normally a cache hit
+                       // NoSuchContainerException not thrown: container must exist
+
+                       // Make container private to end-users...
+                       if ( $this->swiftAnonUser != '' && !isset( $contObj->mw_wasSecured ) ) {
+                               $status->merge( $this->setContainerAccess(
+                                       $contObj,
+                                       array( $this->auth->username ), // read
+                                       array( $this->auth->username ) // write
+                               ) );
+                               // @TODO: when php-cloudfiles supports container
+                               // metadata, we can make use of that to avoid RTTs
+                               $contObj->mw_wasSecured = true; // avoid useless RTTs
+                       }
+                       if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
+                               $contObj->make_private();
                        }
+               } catch ( CDNNotEnabledException $e ) {
+                       // CDN not enabled; nothing to see here
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                }
 
                return $status;
@@ -436,12 +585,8 @@ class SwiftFileBackend extends FileBackendStore {
                        $contObj = $this->getContainer( $fullCont, true );
                } catch ( NoSuchContainerException $e ) {
                        return $status; // ok, nothing to do
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-internal', $this->name );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
@@ -451,12 +596,10 @@ class SwiftFileBackend extends FileBackendStore {
                                $this->deleteContainer( $fullCont );
                        } catch ( NoSuchContainerException $e ) {
                                return $status; // race?
-                       } catch ( InvalidResponseException $e ) {
-                               $status->fatal( 'backend-fail-connect', $this->name );
-                               return $status;
-                       } catch ( Exception $e ) { // some other exception?
-                               $status->fatal( 'backend-fail-internal', $this->name );
-                               $this->logException( $e, __METHOD__, $params );
+                       } catch ( NonEmptyContainerException $e ) {
+                               return $status; // race? consistency delay?
+                       } catch ( CloudFilesException $e ) { // some other exception?
+                               $this->handleException( $e, $status, __METHOD__, $params );
                                return $status;
                        }
                }
@@ -487,11 +630,9 @@ class SwiftFileBackend extends FileBackendStore {
                        );
                } catch ( NoSuchContainerException $e ) {
                } catch ( NoSuchObjectException $e ) {
-               } catch ( InvalidResponseException $e ) {
+               } catch ( CloudFilesException $e ) { // some other exception?
                        $stat = null;
-               } catch ( Exception $e ) { // some other exception?
-                       $stat = null;
-                       $this->logException( $e, __METHOD__, $params );
+                       $this->handleException( $e, null, __METHOD__, $params );
                }
 
                return $stat;
@@ -512,7 +653,8 @@ class SwiftFileBackend extends FileBackendStore {
                $status = Status::newGood();
                $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
                if ( $status->isOK() ) {
-                       $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
+                       # Do not stat the file in getLocalCopy() to avoid infinite loops
+                       $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
                        if ( $tmpFile ) {
                                $hash = $tmpFile->getSha1Base36();
                                if ( $hash !== false ) {
@@ -543,12 +685,11 @@ class SwiftFileBackend extends FileBackendStore {
                $data = false;
                try {
                        $sContObj = $this->getContainer( $srcCont );
-                       $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD request
+                       $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
                        $data = $obj->read( $this->headersFromParams( $params ) );
                } catch ( NoSuchContainerException $e ) {
-               } catch ( InvalidResponseException $e ) {
-               } catch ( Exception $e ) { // some other exception?
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, null, __METHOD__, $params );
                }
 
                return $data;
@@ -565,9 +706,9 @@ class SwiftFileBackend extends FileBackendStore {
                        return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
                } catch ( NoSuchContainerException $e ) {
                        return false;
-               } catch ( InvalidResponseException $e ) {
-               } catch ( Exception $e ) { // some other exception?
-                       $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, null, __METHOD__,
+                               array( 'cont' => $fullCont, 'dir' => $dir ) );
                }
 
                return null; // error
@@ -601,6 +742,10 @@ class SwiftFileBackend extends FileBackendStore {
         */
        public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
                $dirs = array();
+               if ( $after === INF ) {
+                       return $dirs; // nothing more
+               }
+               wfProfileIn( __METHOD__ . '-' . $this->name );
 
                try {
                        $container = $this->getContainer( $fullCont );
@@ -612,7 +757,6 @@ class SwiftFileBackend extends FileBackendStore {
                                        if ( substr( $object, -1 ) === '/' ) {
                                                $dirs[] = $object; // directories end in '/'
                                        }
-                                       $after = $object; // update last item
                                }
                        // Recursive: list all dirs under $dir and its subdirs
                        } else {
@@ -638,15 +782,20 @@ class SwiftFileBackend extends FileBackendStore {
                                                }
                                                $lastDir = $objectDir;
                                        }
-                                       $after = $object; // update last item
                                }
                        }
+                       if ( count( $objects ) < $limit ) {
+                               $after = INF; // avoid a second RTT
+                       } else {
+                               $after = end( $objects ); // update last item
+                       }
                } catch ( NoSuchContainerException $e ) {
-               } catch ( InvalidResponseException $e ) {
-               } catch ( Exception $e ) { // some other exception?
-                       $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, null, __METHOD__,
+                               array( 'cont' => $fullCont, 'dir' => $dir ) );
                }
 
+               wfProfileOut( __METHOD__ . '-' . $this->name );
                return $dirs;
        }
 
@@ -666,6 +815,10 @@ class SwiftFileBackend extends FileBackendStore {
         */
        public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
                $files = array();
+               if ( $after === INF ) {
+                       return $files; // nothing more
+               }
+               wfProfileIn( __METHOD__ . '-' . $this->name );
 
                try {
                        $container = $this->getContainer( $fullCont );
@@ -680,16 +833,21 @@ class SwiftFileBackend extends FileBackendStore {
                                }
                        // Recursive: list all files under $dir and its subdirs
                        } else { // files
-                               $files = $container->list_objects( $limit, $after, $prefix );
+                               $objects = $container->list_objects( $limit, $after, $prefix );
+                               $files = $objects;
+                       }
+                       if ( count( $objects ) < $limit ) {
+                               $after = INF; // avoid a second RTT
+                       } else {
+                               $after = end( $objects ); // update last item
                        }
-                       $after = end( $files ); // update last item
-                       reset( $files ); // reset pointer
                } catch ( NoSuchContainerException $e ) {
-               } catch ( InvalidResponseException $e ) {
-               } catch ( Exception $e ) { // some other exception?
-                       $this->logException( $e, __METHOD__, array( 'cont' => $fullCont, 'dir' => $dir ) );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, null, __METHOD__,
+                               array( 'cont' => $fullCont, 'dir' => $dir ) );
                }
 
+               wfProfileOut( __METHOD__ . '-' . $this->name );
                return $files;
        }
 
@@ -723,24 +881,17 @@ class SwiftFileBackend extends FileBackendStore {
                } catch ( NoSuchContainerException $e ) {
                        $status->fatal( 'backend-fail-stream', $params['src'] );
                        return $status;
-               } catch ( InvalidResponseException $e ) {
-                       $status->fatal( 'backend-fail-connect', $this->name );
-                       return $status;
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-stream', $params['src'] );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                        return $status;
                }
 
                try {
                        $output = fopen( 'php://output', 'wb' );
-                       $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
+                       $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
                        $obj->stream( $output, $this->headersFromParams( $params ) );
-               } catch ( InvalidResponseException $e ) { // 404? connection problem?
-                       $status->fatal( 'backend-fail-stream', $params['src'] );
-               } catch ( Exception $e ) { // some other exception?
-                       $status->fatal( 'backend-fail-stream', $params['src'] );
-                       $this->logException( $e, __METHOD__, $params );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, $status, __METHOD__, $params );
                }
 
                return $status;
@@ -756,7 +907,8 @@ class SwiftFileBackend extends FileBackendStore {
                        return null;
                }
 
-               if ( !$this->fileExists( $params ) ) {
+               # Check the recursion guard to avoid loops when filling metadata
+               if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
                        return null;
                }
 
@@ -779,11 +931,9 @@ class SwiftFileBackend extends FileBackendStore {
                        }
                } catch ( NoSuchContainerException $e ) {
                        $tmpFile = null;
-               } catch ( InvalidResponseException $e ) {
-                       $tmpFile = null;
-               } catch ( Exception $e ) { // some other exception?
+               } catch ( CloudFilesException $e ) { // some other exception?
                        $tmpFile = null;
-                       $this->logException( $e, __METHOD__, $params );
+                       $this->handleException( $e, null, __METHOD__, $params );
                }
 
                return $tmpFile;
@@ -813,6 +963,36 @@ class SwiftFileBackend extends FileBackendStore {
                return $hdrs;
        }
 
+       /**
+        * @see FileBackendStore::doExecuteOpHandlesInternal()
+        * @return Array List of corresponding Status objects
+        */
+       protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
+               $statuses = array();
+
+               $cfOps = array(); // list of CF_Async_Op objects
+               foreach ( $fileOpHandles as $index => $fileOpHandle ) {
+                       $cfOps[$index] = $fileOpHandle->cfOp;
+               }
+               $batch = new CF_Async_Op_Batch( $cfOps );
+
+               $cfOps = $batch->execute();
+               foreach ( $cfOps as $index => $cfOp ) {
+                       $status = Status::newGood();
+                       try { // catch exceptions; update status
+                               $function = '_getResponse' . $fileOpHandles[$index]->call;
+                               $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
+                               $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
+                       } catch ( CloudFilesException $e ) { // some other exception?
+                               $this->handleException( $e, $status,
+                                       __CLASS__ . ":$function", $fileOpHandles[$index]->params );
+                       }
+                       $statuses[$index] = $status;
+               }
+
+               return $statuses;
+       }
+
        /**
         * Set read/write permissions for a Swift container
         *
@@ -837,15 +1017,36 @@ class SwiftFileBackend extends FileBackendStore {
                return $req->execute(); // should return 204
        }
 
+       /**
+        * Purge the CDN cache of affected objects if CDN caching is enabled
+        *
+        * @param $objects Array List of CF_Object items
+        * @return void
+        */
+       public function purgeCDNCache( array $objects ) {
+               if ( $this->swiftUseCDN ) { // Rackspace style CDN
+                       foreach ( $objects as $object ) {
+                               try {
+                                       $object->purge_from_cdn();
+                               } catch ( CDNNotEnabledException $e ) {
+                                       // CDN not enabled; nothing to see here
+                               } catch ( CloudFilesException $e ) {
+                                       $this->handleException( $e, null, __METHOD__,
+                                               array( 'cont' => $object->container->name, 'obj' => $object->name ) );
+                               }
+                       }
+               }
+       }
+
        /**
         * Get a connection to the Swift proxy
         *
         * @return CF_Connection|bool False on failure
-        * @throws InvalidResponseException
+        * @throws CloudFilesException
         */
        protected function getConnection() {
-               if ( $this->conn === false ) {
-                       throw new InvalidResponseException; // failed last attempt
+               if ( $this->connException instanceof Exception ) {
+                       throw $this->connException; // failed last attempt
                }
                // Session keys expire after a while, so we renew them periodically
                if ( $this->conn && ( time() - $this->connStarted ) > $this->authTTL ) {
@@ -853,21 +1054,18 @@ class SwiftFileBackend extends FileBackendStore {
                        $this->conn = null;
                }
                // Authenticate with proxy and get a session key...
-               if ( $this->conn === null ) {
+               if ( !$this->conn ) {
+                       $this->connStarted = 0;
                        $this->connContainers = array();
                        try {
                                $this->auth->authenticate();
                                $this->conn = new CF_Connection( $this->auth );
                                $this->connStarted = time();
-                       } catch ( AuthenticationException $e ) {
-                               $this->conn = false; // don't keep re-trying
-                       } catch ( InvalidResponseException $e ) {
-                               $this->conn = false; // don't keep re-trying
+                       } catch ( CloudFilesException $e ) {
+                               $this->connException = $e; // don't keep re-trying
+                               throw $e; // throw it back
                        }
                }
-               if ( !$this->conn ) {
-                       throw new InvalidResponseException; // auth/connection problem
-               }
                return $this->conn;
        }
 
@@ -885,7 +1083,7 @@ class SwiftFileBackend extends FileBackendStore {
         * @param $container string Container name
         * @param $bypassCache bool Bypass all caches and load from Swift
         * @return CF_Container
-        * @throws InvalidResponseException
+        * @throws CloudFilesException
         */
        protected function getContainer( $container, $bypassCache = false ) {
                $conn = $this->getConnection(); // Swift proxy connection
@@ -954,31 +1152,56 @@ class SwiftFileBackend extends FileBackendStore {
                                        $info['bytes']
                                );
                        }
-               } catch ( InvalidResponseException $e ) {
-               } catch ( Exception $e ) { // some other exception?
-                       $this->logException( $e, __METHOD__, array() );
+               } catch ( CloudFilesException $e ) { // some other exception?
+                       $this->handleException( $e, null, __METHOD__, array() );
                }
        }
 
        /**
-        * Log an unexpected exception for this backend
+        * Log an unexpected exception for this backend.
+        * This also sets the Status object to have a fatal error.
         *
         * @param $e Exception
+        * @param $status Status|null
         * @param $func string
         * @param $params Array
         * @return void
         */
-       protected function logException( Exception $e, $func, array $params ) {
+       protected function handleException( Exception $e, $status, $func, array $params ) {
+               if ( $status instanceof Status ) {
+                       if ( $e instanceof AuthenticationException ) {
+                               $status->fatal( 'backend-fail-connect', $this->name );
+                       } else {
+                               $status->fatal( 'backend-fail-internal', $this->name );
+                       }
+               }
+               if ( $e->getMessage() ) {
+                       trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
+               }
                wfDebugLog( 'SwiftBackend',
                        get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
-                       ( $e instanceof InvalidResponseException
-                               ? ": {$e->getMessage()}"
-                               : ""
-                       )
+                       ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
                );
        }
 }
 
+/**
+ * @see FileBackendStoreOpHandle
+ */
+class SwiftFileOpHandle extends FileBackendStoreOpHandle {
+       /** @var CF_Async_Op */
+       public $cfOp;
+       /** @var Array */
+       public $affectedObjects = array();
+
+       public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
+               $this->backend = $backend;
+               $this->params = $params;
+               $this->call = $call;
+               $this->cfOp = $cfOp;
+       }
+}
+
 /**
  * SwiftFileBackend helper class to page through listings.
  * Swift also has a listing limit of 10,000 objects for sanity.