401 invalid_signature * safe mode check -> 409 site_identity_mismatch * payload validation -> 400 invalid_payload * existing claim -> 200 duplicate / 409 order_in_progress / replay / recovery * SKU resolve -> 422 unknown_sku * stock gate -> 400 insufficient_stock * claim INSERT -> acquire, or handle a concurrent existing claim * create order -> 201 * * The claim is taken after the checks on purpose. A retry of an order that was * rejected for short stock must be able to succeed later, once the store has * stock again, so a stock failure must not leave a row behind. * * @package Aha_Is_Woocommerce */ defined( 'ABSPATH' ) || exit; /** * Handles order create requests. */ final class Aha_Is_Woocommerce_Orders_Controller { /** * True when a Connect order key signed the request. Its lines then * resolve by line_items[].product_id, not by SKU. * * @var bool */ private $connect = false; /** * Handle the request. * * @param WP_REST_Request $request Request. * @return WP_REST_Response */ public function handle( $request ) { $verdict = Aha_Is_Woocommerce_Rest_Auth::verify_request( $request ); if ( ! $verdict['ok'] ) { return Aha_Is_Woocommerce_Rest_Response::invalid_signature(); } $this->connect = ! empty( $verdict['connect'] ); if ( Aha_Is_Woocommerce_Site_Identity::is_safe_mode() ) { $reason = Aha_Is_Woocommerce_Site_Identity::safe_mode_reason(); Aha_Is_Woocommerce_Logger::warning( 'order_rejected_safe_mode', array( 'reason' => $reason ) ); return Aha_Is_Woocommerce_Rest_Response::site_identity_mismatch( $reason ); } $payload = $this->decode_and_validate( (string) $request->get_body() ); if ( isset( $payload['error'] ) ) { return Aha_Is_Woocommerce_Rest_Response::error( 'invalid_payload', $payload['error'], 400 ); } $data = $payload['data']; $aha_is_woocommerce_order_id = (string) $data['aha_order_id']; return $this->process( $data, $aha_is_woocommerce_order_id, false ); } /** * Handle existing claims before the resolve, gate, claim and create steps. * * @param array $data Validated payload. * @param string $aha_is_woocommerce_order_id Idempotency key. * @param bool $holds_claim True when the caller already owns the claim * (the lazy recovery path). * @return WP_REST_Response */ private function process( array $data, $aha_is_woocommerce_order_id, $holds_claim ) { // Replays must not depend on stock or products changed by the first // successful request. Fresh requests still validate before claiming. if ( ! $holds_claim && Aha_Is_Woocommerce_Order_Map::get( $aha_is_woocommerce_order_id ) ) { return $this->handle_existing_claim( $data, $aha_is_woocommerce_order_id ); } $resolved = Aha_Is_Woocommerce_Product_Resolver::resolve_lines( $data['line_items'], $this->connect ); if ( ! $resolved['ok'] ) { $message = 'SKU not found on this store, or more than one product carries it.'; // An unknown SKU is permanent: a retry of the same payload cannot // succeed. When this request owns a claim, store the error so the // next retry replays it without doing the work again. if ( $holds_claim ) { Aha_Is_Woocommerce_Order_Map::mark_failed( $aha_is_woocommerce_order_id, 'unknown_sku', $message, 422 ); } Aha_Is_Woocommerce_Logger::warning( 'order_rejected_unknown_sku', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'sku' => $resolved['unknown_sku'], ) ); return Aha_Is_Woocommerce_Rest_Response::error( 'unknown_sku', $message, 422, array( 'sku' => $resolved['unknown_sku'] ) ); } $gate = Aha_Is_Woocommerce_Stock_Gate::evaluate( Aha_Is_Woocommerce_Stock_Gate::merge_by_stock_unit( $resolved['lines'] ) ); if ( ! $gate['ok'] ) { // Short stock is temporary. Release any claim so a later retry of // the same aha_order_id gets a clean start. if ( $holds_claim ) { Aha_Is_Woocommerce_Order_Map::release( $aha_is_woocommerce_order_id ); } Aha_Is_Woocommerce_Logger::info( 'order_rejected_insufficient_stock', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'sku' => $gate['sku'], 'available' => $gate['available'], 'requested' => $gate['requested'], ) ); return Aha_Is_Woocommerce_Rest_Response::error( 'insufficient_stock', 'The store does not have enough stock for this order.', 400, array( 'sku' => $gate['sku'], 'available' => $gate['available'], 'requested' => $gate['requested'], ) ); } if ( ! $holds_claim && ! Aha_Is_Woocommerce_Order_Map::claim( $aha_is_woocommerce_order_id ) ) { return $this->handle_existing_claim( $data, $aha_is_woocommerce_order_id ); } return $this->create_order( $data, $aha_is_woocommerce_order_id, $resolved['lines'] ); } /** * Decide what an existing claim row means. * * @param array $data Validated payload. * @param string $aha_is_woocommerce_order_id Idempotency key. * @return WP_REST_Response */ private function handle_existing_claim( array $data, $aha_is_woocommerce_order_id ) { $row = Aha_Is_Woocommerce_Order_Map::get( $aha_is_woocommerce_order_id ); $decision = Aha_Is_Woocommerce_Claim_Decision::decide( $row, time() ); switch ( $decision['action'] ) { case Aha_Is_Woocommerce_Claim_Decision::ACTION_RETURN_EXISTING: return $this->respond_with_existing_order( (int) $row['wc_order_id'], $aha_is_woocommerce_order_id ); case Aha_Is_Woocommerce_Claim_Decision::ACTION_REPLAY_ERROR: return Aha_Is_Woocommerce_Rest_Response::error( (string) $row['error_code'], (string) $row['error_message'], $row['http_status'] ? (int) $row['http_status'] : 422 ); case Aha_Is_Woocommerce_Claim_Decision::ACTION_RECOVER: return $this->recover_stale_claim( $data, $aha_is_woocommerce_order_id, $row, $decision ); case Aha_Is_Woocommerce_Claim_Decision::ACTION_IN_PROGRESS: default: return Aha_Is_Woocommerce_Rest_Response::error( 'order_in_progress', 'Another request is creating this order. Retry with the same aha_order_id.', 409, array( 'retry_after' => $decision['retry_after'] ) ); } } /** * Lazy recovery of a claim that a stopped request left behind. * * There is no background sweep job, by decision. The repair happens here, * inside the retry that finds the stale row. * * @param array $data Validated payload. * @param string $aha_is_woocommerce_order_id Idempotency key. * @param array|null $row Claim row. * @param array $decision Decision from Aha_Is_Woocommerce_Claim_Decision. * @return WP_REST_Response */ private function recover_stale_claim( array $data, $aha_is_woocommerce_order_id, $row, array $decision ) { // The earlier request may have created the order and stopped before it // wrote the row. Look the order up by meta with a direct query. No // meta_query: it is slow and it differs between HPOS and the post store. $order_id = Aha_Is_Woocommerce_Order_Map::find_order_id_by_meta( $aha_is_woocommerce_order_id ); if ( $order_id > 0 ) { Aha_Is_Woocommerce_Order_Map::mark_created( $aha_is_woocommerce_order_id, $order_id ); Aha_Is_Woocommerce_Logger::info( 'stale_claim_completed', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'wc_order_id' => $order_id, ) ); return $this->respond_with_existing_order( $order_id, $aha_is_woocommerce_order_id ); } // No order exists. Take the claim over. The UPDATE repeats the // claimed_at value that this request read, so only one of two // concurrent recoverers wins. $seen_claimed_at = ( $row && isset( $row['claimed_at'] ) ) ? (int) $row['claimed_at'] : 0; if ( ! $row ) { // The row vanished. Claim it again from scratch. if ( ! Aha_Is_Woocommerce_Order_Map::claim( $aha_is_woocommerce_order_id ) ) { return Aha_Is_Woocommerce_Rest_Response::error( 'order_in_progress', 'Another request is creating this order. Retry with the same aha_order_id.', 409, array( 'retry_after' => Aha_Is_Woocommerce_Claim_Decision::MIN_RETRY_AFTER ) ); } } elseif ( ! Aha_Is_Woocommerce_Order_Map::reclaim( $aha_is_woocommerce_order_id, $seen_claimed_at ) ) { return Aha_Is_Woocommerce_Rest_Response::error( 'order_in_progress', 'Another request took this claim over. Retry with the same aha_order_id.', 409, array( 'retry_after' => Aha_Is_Woocommerce_Claim_Decision::MIN_RETRY_AFTER ) ); } Aha_Is_Woocommerce_Logger::warning( 'stale_claim_reclaimed', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'age_seconds' => $decision['age'], ) ); // Re-run the pipeline. The store may have changed while the claim sat // there, so the SKUs and the stock are checked again. return $this->process( $data, $aha_is_woocommerce_order_id, true ); } /** * Create the order and finish the claim. * * @param array $data Validated payload. * @param string $aha_is_woocommerce_order_id Idempotency key. * @param array $lines Resolved lines. * @return WP_REST_Response */ private function create_order( array $data, $aha_is_woocommerce_order_id, array $lines ) { $created = Aha_Is_Woocommerce_Order_Factory::create( $data, $lines ); if ( ! $created['ok'] ) { // A failure after save() (for example in payment_complete()) leaves a real order. // Keep it: releasing the claim would let the retry create a second one. $existing_id = Aha_Is_Woocommerce_Order_Map::find_order_id_by_meta( $aha_is_woocommerce_order_id ); if ( $existing_id ) { Aha_Is_Woocommerce_Order_Map::mark_created( $aha_is_woocommerce_order_id, $existing_id ); Aha_Is_Woocommerce_Logger::warning( 'order_create_partial', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'wc_order_id' => $existing_id, 'error' => $created['error'], ) ); // payment_complete() did not run: make the order visible and reserve stock. Never retried. try { $order = wc_get_order( $existing_id ); if ( $order && ! empty( $data['set_paid'] ) && 'pending' === $order->get_status() ) { $order->add_order_note( 'Aha order created, but payment completion failed: ' . $created['error'] ); $order->set_status( 'on-hold' ); $order->save(); } } catch ( Throwable $e ) { Aha_Is_Woocommerce_Logger::error( 'order_create_partial_recover_failed', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'error' => $e->getMessage() ) ); } return $this->respond_with_existing_order( $existing_id, $aha_is_woocommerce_order_id ); } // Release the claim so a retry can try again. The plugin cannot // tell a temporary store problem from a permanent one here, and a // retryable 500 is the safer answer: the claim table still stops a // duplicate if the order was in fact created. Aha_Is_Woocommerce_Order_Map::release( $aha_is_woocommerce_order_id ); Aha_Is_Woocommerce_Logger::error( 'order_create_failed', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'error' => $created['error'], ) ); return Aha_Is_Woocommerce_Rest_Response::error( 'internal_error', 'The store could not create the order.', 500 ); } Aha_Is_Woocommerce_Order_Map::mark_created( $aha_is_woocommerce_order_id, $created['order_id'] ); Aha_Is_Woocommerce_Logger::info( 'order_created', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'wc_order_id' => $created['order_id'], ) ); return Aha_Is_Woocommerce_Rest_Response::order_created( $created['order_id'], $created['number'], false ); } /** * Answer with an order that already exists. * * @param int $order_id Order id. * @param string $aha_is_woocommerce_order_id Idempotency key. * @return WP_REST_Response */ private function respond_with_existing_order( $order_id, $aha_is_woocommerce_order_id ) { $order = wc_get_order( $order_id ); if ( ! $order ) { // The row points at an order that a shop manager deleted. Nothing // safe can be returned, and creating a second order would break the // idempotency promise. Aha_Is_Woocommerce_Logger::error( 'claim_points_at_missing_order', array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'wc_order_id' => $order_id, ) ); return Aha_Is_Woocommerce_Rest_Response::error( 'internal_error', 'This order was created before and then deleted on the store.', 500 ); } return Aha_Is_Woocommerce_Rest_Response::order_created( $order_id, $order->get_order_number(), true ); } /** * Decode the body and check it against the frozen contract schema. * * @param string $raw_body Raw request body. * @return array Either array( 'data' => array ) or array( 'error' => string ). */ private function decode_and_validate( $raw_body ) { // Decode twice on purpose. The validator needs objects so it can tell an // empty object from an empty array; the business logic wants arrays. $as_object = json_decode( $raw_body ); if ( null === $as_object && JSON_ERROR_NONE !== json_last_error() ) { return array( 'error' => 'The body is not valid JSON.' ); } $schema = Aha_Is_Woocommerce_Contract::request_schema(); if ( ! $schema ) { return array( 'error' => 'The plugin could not load its contract schema.' ); } if ( ! $schema->is_valid( $as_object ) ) { return array( 'error' => $schema->get_first_error() ); } $data = json_decode( $raw_body, true ); if ( ! Aha_Is_Woocommerce_Contract::is_supported_version( $data['schema_version'] ) ) { return array( 'error' => 'This plugin does not support schema_version ' . $data['schema_version'] . '.', ); } return array( 'data' => $data ); } }