diff --git a/includes/commerce.controller.inc b/includes/commerce.controller.inc index 1cdd605..ac8165b 100644 --- a/includes/commerce.controller.inc +++ b/includes/commerce.controller.inc @@ -7,7 +7,47 @@ * A full fork of Entity API's controller, with support for revisions. */ -class DrupalCommerceEntityController extends DrupalDefaultEntityController implements EntityAPIControllerInterface { +interface DrupalCommerceEntityControllerInterface extends EntityAPIControllerInterface { + + /** + * Determines whether the provided entity is locked. + * + * @param $entity + * The entity to check. + * + * @return + * True if the entity is locked, false otherwise. + */ + public function isLocked($entity); + + /** + * Determines whether the provided entity is cached. + * + * @param $entity + * The entity to check. + * + * @return + * True if the entity is cached, false otherwise. + */ + public function isCached($entity); + + /** + * Request that locking be skipped, + * actually skipping locking may or may not be possible. + * + * @param $skip_locking + * The boolean indicating whether locking should be skipped. + */ + public function requestSkipLocking($skip_locking); + + /** + * releases locking on all entities, use with caution + */ + public function releaseLocking(); + +} + +class DrupalCommerceEntityController extends DrupalDefaultEntityController implements DrupalCommerceEntityControllerInterface { /** * Stores our transaction object, necessary for pessimistic locking to work. @@ -21,6 +61,102 @@ class DrupalCommerceEntityController extends DrupalDefaultEntityController imple protected $lockedEntities = array(); /** + * Stores the flag for if a condition has been passed for requesting locking. + * By default, locking is always requested unless it is specifically set to false + */ + protected $requestLocking = TRUE; + + /** + * Stores whether a request for skipping locking has been set. + * If locking has been requested as well it will take preference and the entity + * load will default to locking + */ + protected $requestSkipLocking = FALSE; + + /** + * Implements DrupalCommerceEntityControllerInterface::isLocked(). + */ + public function isLocked($entity) { + return isset($this->lockedEntities[$entity->{$this->idKey}]); + } + + /** + * Implements DrupalCommerceEntityControllerInterface::isLocked(). + */ + public function isCached($entity) { + return isset($this->entityCache[$entity->{$this->idKey}]); + } + + /** + * Implements DrupalCommerceEntityControllerInterface::requestSkipLocking(). + */ + public function requestSkipLocking($skip_locking = TRUE) { + $this->requestSkipLocking = $skip_locking; + + return $this; + } + + /** + * Determines whether the current entity type requires or requested pessimistic locking. + * + * @return + * True if locking is required, false otherwise. + */ + protected function requireLocking() { + $enabled = isset($this->entityInfo['locking mode']) && $this->entityInfo['locking mode'] == 'pessimistic'; + $not_skipped = empty($this->requestSkipLocking); + + return $enabled && $not_skipped && $this->requestLocking; + } + + /** + * Checks the list of tracked locked entities, and if it's empty, commits + * the transaction in order to remove the acquired locks. + * + * The transaction is not necessarily committed immediately. Drupal will + * commit it as soon as possible given the state of the transaction stack. + */ + protected function releaseLock() { + if (empty($this->lockedEntities)) { + unset($this->controllerTransaction); + } + } + + /** + * Removes all locking for the controller, mostly used for testing + * if you want to stop locking and run something else, or you want to cancel locking + * on all entities at once, although be cautious with this. + */ + public function releaseLocking() { + unset($this->controllerTransaction); + $this->lockedEntities = array(); + } + + /** + * Overrides DrupalDefaultEntityController::load(). + * + * Accepts a condition of locking request, may not necessarily take effect + * as other options can override locking. If anything conflicts, locking always + * take precedence over not locking. + */ + public function load($ids = array(), $conditions = array()) { + // Lock by default if the caller didn't indicate a preference. + $conditions += array('_lock' => TRUE); + $this->requestLocking = $conditions["_lock"]; + unset($conditions['_lock']); + + // If locking has been required, then bypass the internal cache for any + // entities that are not already locked. + if ($this->requireLocking()) { + foreach (array_diff_key(array_flip($ids), $this->lockedEntities) as $id => $value) { + unset($this->entityCache[$id]); + } + } + + return parent::load($ids, $conditions); + } + + /** * Override of DrupalDefaultEntityController::buildQuery(). * * Handle pessimistic locking. @@ -28,7 +164,7 @@ class DrupalCommerceEntityController extends DrupalDefaultEntityController imple protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) { $query = parent::buildQuery($ids, $conditions, $revision_id); - if (isset($this->entityInfo['locking mode']) && $this->entityInfo['locking mode'] == 'pessimistic') { + if ($this->requireLocking()) { // In pessimistic locking mode, we issue the load query with a FOR UPDATE // clause. This will block all other load queries to the loaded objects // but requires us to start a transaction. @@ -48,41 +184,6 @@ class DrupalCommerceEntityController extends DrupalDefaultEntityController imple return $query; } - public function resetCache(array $ids = NULL) { - parent::resetCache($ids); - - // Maintain the list of locked entities, so that the releaseLock() method - // can know when it's time to commit the transaction. - if (!empty($this->lockedEntities)) { - if (isset($ids)) { - foreach ($ids as $id) { - unset($this->lockedEntities[$id]); - } - } - else { - $this->lockedEntities = array(); - } - } - - // Try to release the lock, if possible. - $this->releaseLock(); - } - - /** - * Checks the list of tracked locked entities, and if it's empty, commits - * the transaction in order to remove the acquired locks. - * - * The transaction is not necessarily committed immediately. Drupal will - * commit it as soon as possible given the state of the transaction stack. - */ - protected function releaseLock() { - if (isset($this->entityInfo['locking mode']) && $this->entityInfo['locking mode'] == 'pessimistic') { - if (empty($this->lockedEntities)) { - unset($this->controllerTransaction); - } - } - } - /** * (Internal use) Invokes a hook on behalf of the entity. * @@ -228,9 +329,9 @@ class DrupalCommerceEntityController extends DrupalDefaultEntityController imple if (!empty($update_base_table)) { // Go back to the base table and update the pointer to the revision ID. db_update($this->entityInfo['base table']) - ->fields(array($this->revisionKey => $entity->{$this->revisionKey})) - ->condition($this->idKey, $entity->{$this->idKey}) - ->execute(); + ->fields(array($this->revisionKey => $entity->{$this->revisionKey})) + ->condition($this->idKey, $entity->{$this->idKey}) + ->execute(); } // Update the static cache so that the next entity_load() will return this diff --git a/modules/cart/tests/commerce_cart.test b/modules/cart/tests/commerce_cart.test index da87246..0a63177 100644 --- a/modules/cart/tests/commerce_cart.test +++ b/modules/cart/tests/commerce_cart.test @@ -511,8 +511,7 @@ class CommerceCartTestCaseAnonymousToAuthenticated extends CommerceCartTestCase // Get the order just created. $orders = commerce_order_load_multiple(array(), array('uid' => $user->uid, 'status' => 'cart'), TRUE); $order_anonymous = reset($orders); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // Access to the cart and check if the product is in it. $this->drupalGet($this->getCommerceUrl('cart')); @@ -533,7 +532,7 @@ class CommerceCartTestCaseAnonymousToAuthenticated extends CommerceCartTestCase $orders = commerce_order_load_multiple(array(), array('uid' => $this->store_customer->uid, 'status' => 'cart'), TRUE); $order_authenticated = reset($orders); // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // Access to the cart and check if the product is in it. $this->drupalGet($this->getCommerceUrl('cart')); diff --git a/modules/checkout/tests/commerce_checkout.test b/modules/checkout/tests/commerce_checkout.test index 56351cc..fa81eb1 100644 --- a/modules/checkout/tests/commerce_checkout.test +++ b/modules/checkout/tests/commerce_checkout.test @@ -78,8 +78,7 @@ class CommerceCheckoutTestProcess extends CommerceBaseTestCase { // Get the order for the anonymous user. $orders = commerce_order_load_multiple(array(), array('uid' => $user->uid, 'status' => 'cart'), TRUE); $this->order = reset($orders); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); } /** @@ -163,8 +162,7 @@ class CommerceCheckoutTestProcess extends CommerceBaseTestCase { // Load the order to check the status. $order = commerce_order_load_multiple(array($this->order->order_id), array(), TRUE); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // At this point we should be in Checkout Review. $this->assertEqual(reset($order)->status, 'checkout_review', t('Order status is \'Checkout Review\' in the review phase.')); @@ -325,8 +323,7 @@ class CommerceCheckoutTestProcess extends CommerceBaseTestCase { // Load the order to check the status. $order = commerce_order_load_multiple(array($this->order->order_id), array(), TRUE); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // At this point we should be in Checkout Review. $this->assertEqual(reset($order)->status, 'checkout_review', t('Order status is \'Checkout Review\' in the review phase.')); diff --git a/modules/order/commerce_order.module b/modules/order/commerce_order.module index 26071c8..f16f5dd 100644 --- a/modules/order/commerce_order.module +++ b/modules/order/commerce_order.module @@ -746,17 +746,27 @@ function commerce_order_save($order) { /** * Loads an order by ID. + * + * @param $order_id + * The order id. + * @param $lock + * Whether to lock the loaded order. */ -function commerce_order_load($order_id) { - $orders = commerce_order_load_multiple(array($order_id), array()); +function commerce_order_load($order_id, $lock = TRUE) { + $orders = commerce_order_load_multiple(array($order_id), array('_lock' => $lock), FALSE); return $orders ? reset($orders) : FALSE; } /** * Loads an order by number. + * + * @param $order_number + * The order number. + * @param $lock + * Whether to lock the loaded order. */ -function commerce_order_load_by_number($order_number) { - $orders = commerce_order_load_multiple(array(), array('order_number' => $order_number)); +function commerce_order_load_by_number($order_number, $lock = TRUE) { + $orders = commerce_order_load_multiple(array(), array('order_number' => $order_number, '_lock' => $lock), FALSE); return $orders ? reset($orders) : FALSE; } @@ -782,6 +792,32 @@ function commerce_order_load_multiple($order_ids = array(), $conditions = array( return entity_load('commerce_order', $order_ids, $conditions, $reset); } + /** + * Determines whether or not the given order object is locked. + * + * @param $order + * A fully loaded order object. + * + * @return + * Boolean indicating whether or not the order object is locked. + */ +function commerce_order_is_locked($order) { + return entity_get_controller('commerce_order')->isLocked($order); +} + +/** + * Determines whether or not the given order object is cached. + * + * @param $order + * A fully loaded order object. + * + * @return + * Boolean indicating whether or not the order object is cached. + */ +function commerce_order_is_cached($order) { + return entity_get_controller('commerce_order')->isCached($order); +} + /** * Determines whether or not the given order object represents the latest * revision of the order. @@ -1472,6 +1508,34 @@ function commerce_order_entity_query_alter($query) { } /** + * Implements hook_views_pre_execute(). + * + * Ensures that order views don't lock the loaded orders if not necessary. + */ +function commerce_order_views_pre_execute(&$view) { + if ($view->base_table != 'commerce_order') { + return; + } + + $previous_result = &drupal_static(__FUNCTION__); + if ($previous_result === FALSE) { + // The previous order view needed locking, which means that locking can't + // be skipped in this request. No need to evaluate other views. + return; + } + + // Locking can't be skipped if the view has form elements, except VBO. + // VBO modifies orders in a multi-step process, so locking is only needed + // after that process is initiated by the user submitting the VBO selection. + $has_form_elements = views_view_has_form_elements($view); + $has_vbo_field = isset($view->field['views_bulk_operations']); + $submitted = isset($_POST['operation']); + $skip_locking = (!$has_form_elements || ($has_vbo_field && !$submitted)); + entity_get_controller('commerce_order')->requestSkipLocking($skip_locking); + $previous_result = $skip_locking; +} + +/** * Implements hook_preprocess_views_view(). * * When the line item summary and order total area handlers are present on Views diff --git a/modules/order/commerce_order_ui.module b/modules/order/commerce_order_ui.module index 6c3a964..9b89198 100644 --- a/modules/order/commerce_order_ui.module +++ b/modules/order/commerce_order_ui.module @@ -33,6 +33,8 @@ function commerce_order_ui_menu() { ); $items['admin/commerce/orders/%commerce_order'] = array( + // Load the order unlocked, the view page won't modify it. + 'load arguments' => array(FALSE), 'title callback' => 'commerce_order_ui_order_title', 'title arguments' => array(3), 'page callback' => 'commerce_order_ui_order_view', @@ -41,12 +43,14 @@ function commerce_order_ui_menu() { 'access arguments' => array(3), ); $items['admin/commerce/orders/%commerce_order/view'] = array( + 'load arguments' => array(FALSE), 'title' => 'View', 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10, 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE, ); $items['admin/commerce/orders/%commerce_order/edit'] = array( + 'load arguments' => array(TRUE), 'title' => 'Edit', 'page callback' => 'commerce_order_ui_order_form_wrapper', 'page arguments' => array(3), @@ -58,6 +62,7 @@ function commerce_order_ui_menu() { 'file' => 'includes/commerce_order_ui.orders.inc', ); $items['admin/commerce/orders/%commerce_order/delete'] = array( + 'load arguments' => array(TRUE), 'title' => 'Delete', 'page callback' => 'commerce_order_ui_order_delete_form_wrapper', 'page arguments' => array(3), @@ -84,6 +89,8 @@ function commerce_order_ui_menu() { ); $items['user/%user/orders/%commerce_order'] = array( + // Load the order unlocked, since it won't be modified. + 'load arguments' => array(FALSE), 'title callback' => 'commerce_order_ui_order_title', 'title arguments' => array(3), 'page callback' => 'commerce_order_ui_order_view', diff --git a/modules/order/tests/commerce_order.test b/modules/order/tests/commerce_order.test index 1164634..5d46587 100644 --- a/modules/order/tests/commerce_order.test +++ b/modules/order/tests/commerce_order.test @@ -97,6 +97,54 @@ class CommerceOrderCRUDTestCase extends CommerceBaseTestCase { } /** + * Test order locking. + */ + function testCommerceOrderLocking() { + $created_order = $this->createDummyOrder(); + entity_get_controller('commerce_order')->releaseLocking(); + entity_get_controller('commerce_order')->resetCache(); + + // Ensure that loading locked and unlocked orders works. + $unlocked_order = commerce_order_load($created_order->order_id, FALSE); + $this->assertFalse(commerce_order_is_locked($unlocked_order), 'commerce_order_load() returned an unlocked order.'); + $this->assertTrue(commerce_order_is_cached($unlocked_order), 'commerce_order_load() cached the order.'); + $locked_order = commerce_order_load($created_order->order_id); + $this->assertTrue(commerce_order_is_locked($locked_order), 'commerce_order_load() returned a locked order.'); + $this->assertTrue(commerce_order_is_cached($locked_order), 'commerce_order_load() cached the order.'); + entity_get_controller('commerce_order')->releaseLocking(); + $this->assertTrue(commerce_order_is_cached($locked_order), 'commerce_order_load() cached the order.'); + + // Ensure that skipLocking() works. + entity_get_controller('commerce_order')->releaseLocking(); + entity_get_controller('commerce_order')->requestSkipLocking(); + $unlocked_order = commerce_order_load($created_order->order_id); + $this->assertFalse(commerce_order_is_locked($unlocked_order), 'commerce_order_load() returned an unlocked order.'); + + // Simulate an order view that has a non-VBO form field. + $fake_view = new stdClass(); + $fake_view->base_table = 'commerce_order'; + $fake_view->field = array(); + $fake_view->field['test'] = new StdClass(); + $fake_view->field['test']->views_form_callback = 'test_callback'; + commerce_order_views_pre_execute($fake_view); + $result = drupal_static('commerce_order_views_pre_execute', NULL); + $this->assertFalse($result, 'commerce_order_views_pre_execute() did not skip locking.'); + + // Simulate a VBO order view. Since the previous view required locking, + // locking should still not be skipped. + $fake_view->field['views_bulk_operations'] = $fake_view->field['test']; + commerce_order_views_pre_execute($fake_view); + $result = drupal_static('commerce_order_views_pre_execute', NULL); + $this->assertFalse($result, 'commerce_order_views_pre_execute() did not skip locking.'); + + // Start from scratch, test just the VBO order view. + drupal_static_reset('commerce_order_views_pre_execute'); + commerce_order_views_pre_execute($fake_view); + $result = drupal_static('commerce_order_views_pre_execute', NULL); + $this->assertTrue($result, 'commerce_order_views_pre_execute() skipped locking.'); + } + + /** * Test order Token replacement. */ function testCommerceOrderTokens() { diff --git a/modules/order/tests/commerce_order_ui.test b/modules/order/tests/commerce_order_ui.test index 9a023f7..6ac1783 100644 --- a/modules/order/tests/commerce_order_ui.test +++ b/modules/order/tests/commerce_order_ui.test @@ -63,8 +63,7 @@ class CommerceOrderUIAdminTest extends CommerceBaseTestCase { $orders = commerce_order_load_multiple(array(), array('uid' => $this->store_customer->uid)); $this->order = reset($orders); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // Enable an additional currency. $this->enableCurrencies(array('EUR')); @@ -152,8 +151,7 @@ class CommerceOrderUIAdminTest extends CommerceBaseTestCase { // Reload the order directly from db. $order = commerce_order_load_multiple(array($this->order->order_id), array(), TRUE); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // Check if the product has been added to the order. foreach (entity_metadata_wrapper('commerce_order', reset($order))->commerce_line_items as $delta => $line_item_wrapper) { @@ -190,8 +188,7 @@ class CommerceOrderUIAdminTest extends CommerceBaseTestCase { $order = reset($orders); $order_wrapper = entity_metadata_wrapper('commerce_order', $order); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // Also wrap the product to access easier to its price. $product_wrapper = entity_metadata_wrapper('commerce_product', $this->product); @@ -264,8 +261,7 @@ class CommerceOrderUIAdminTest extends CommerceBaseTestCase { // Check if the links for editing the order are present. $links = menu_contextual_links('commerce-order', 'admin/commerce/orders', array($this->order->order_id)); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); $this->assertRaw((theme('links', array('links' => $links, 'attributes' => array('class' => array('links', 'inline', 'operations'))))), t('Links for orders are present')); $this->drupalGet('admin/commerce/orders/'. $this->order->order_id . '/view'); diff --git a/modules/payment/commerce_payment_ui.module b/modules/payment/commerce_payment_ui.module index bd728ae..db45ef8 100644 --- a/modules/payment/commerce_payment_ui.module +++ b/modules/payment/commerce_payment_ui.module @@ -13,6 +13,7 @@ function commerce_payment_ui_menu() { // Payment tab on orders. $items['admin/commerce/orders/%commerce_order/payment'] = array( + 'load arguments' => array(TRUE), 'title' => 'Payment', 'page callback' => 'commerce_payment_ui_order_tab', 'page arguments' => array(3), diff --git a/modules/payment/tests/commerce_payment_ui.test b/modules/payment/tests/commerce_payment_ui.test index b59e657..7fd6448 100644 --- a/modules/payment/tests/commerce_payment_ui.test +++ b/modules/payment/tests/commerce_payment_ui.test @@ -144,8 +144,7 @@ class CommercePaymentUITest extends CommerceBaseTestCase { // Reload the order. $order = commerce_order_load_multiple(array($this->order->order_id), array(), TRUE); - // Reset the cache as we don't want to keep the lock. - entity_get_controller('commerce_order')->resetCache(); + entity_get_controller('commerce_order')->releaseLocking(); // Check order balance, it should be half of total now. $new_balance = commerce_payment_order_balance(reset($order));