home_url(), 'kid' => 'local', 'secret' => Secrets::b64url_encode( random_bytes( 32 ) ), 'transport' => 'local', ) ); } /** * Runs one operation here. * * @param string $op Operation. * @param array $args Arguments. * @param array $budget {ms, bytes}. * @return array{frames: array[], end: array} * @throws Remote_Exception On failure. */ public function call( $op, array $args, array $budget ) { $nonce = Secrets::b64url_encode( random_bytes( 16 ) ); $env = array( 'v' => ACCESSNOW_REPLICA_PROTOCOL, 'kid' => 'local', 'ts' => time(), 'nonce' => $nonce, 'op' => $op, 'args' => $args, 'budget' => $budget, ); $key = array( 'kid' => 'local', 'label' => 'This site', 'expires' => 0, 'secret_raw' => $this->secret, ); $body = Api::handle_local( $env, $key ); $this->received += strlen( $body ); try { $frames = Frame_Codec::decode( $body, Signer::enc_key( $this->secret ), Signer::sign_key( $this->secret ), $nonce ); } catch ( \RuntimeException $e ) { throw new Remote_Exception( 'bad_response', $e->getMessage(), true, 1 ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Shown with esc_html(). } foreach ( $frames as $frame ) { if ( 'X' === $frame[0] ) { $error = json_decode( $frame[1], true ); throw new Remote_Exception( 'remote_error', is_array( $error ) ? (string) $error['error'] : 'unknown' ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Shown with esc_html(). } } $end = json_decode( $frames[ count( $frames ) - 1 ][1], true ); return array( 'frames' => $frames, 'end' => is_array( $end ) ? $end : array(), ); } /** * Runs several operations, one after another (no network to parallelise). * * @param array[] $calls key => array( op, args, budget ). * @return array */ public function call_multi( array $calls ) { $out = array(); foreach ( $calls as $k => $c ) { try { $out[ $k ] = $this->call( $c[0], $c[1], $c[2] ); } catch ( Remote_Exception $e ) { $out[ $k ] = $e; } } return $out; } }