Skip to content

Commit

Permalink
refactor: search query
Browse files Browse the repository at this point in the history
  • Loading branch information
faustoq committed Jul 8, 2024
1 parent 933576e commit a5d4369
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 184 deletions.
73 changes: 1 addition & 72 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use GuzzleHttp\Client as HttpClient;
use OramaCloud\Client\Query;
use OramaCloud\Telemetry\Collector;
use OramaCloud\Traits\GeneratesUniqueId;
use OramaCloud\Traits\ValidatesParams;

Expand All @@ -24,31 +23,17 @@ public function __construct(array $params, HttpClient $http = null)
{
$params = $this->validate($params, [
'api_key' => ['required', 'string'],
'endpoint' => ['required', 'string'],
'telemetry' => ['optional', 'boolean'],
'answersApiBaseURL' => ['optional', 'string']
'endpoint' => ['required', 'string']
]);

$this->id = $this->generateUniqueId();
$this->http = !is_null($http) ? $http : new HttpClient();
$this->apiKey = $params['api_key'];
$this->endpoint = $params['endpoint'];
$this->answersApiBaseURL = $params['answersApiBaseURL'];

// Telemetry is enabled by default
if ($params['telemetry'] !== false) {
$this->collector = Collector::create([
'id' => $this->id,
'api_key' => $this->apiKey
], $this->http);
}

$this->init();
}

public function search(Query $query)
{
$startTime = microtime(true);
$endpoint = "{$this->endpoint}/search?api-key={$this->apiKey}";
$response = $this->http->request('POST', $endpoint, [
'form_params' => [
Expand All @@ -58,62 +43,6 @@ public function search(Query $query)

$results = json_decode($response->getBody()->getContents(), true);

$endTime = microtime(true);
$roundTripTime = ($endTime - $startTime) * 1000;

if ($this->collector !== null) {
$this->collector->add([
'rawSearchString' => $query->toArray()['term'],
'resultsCount' => $results['count'] ?? 0,
'roundTripTime' => $roundTripTime,
'query' => $query->toJson(),
'cached' => false,
'searchedAt' => time()
]);
}

return $results;
}

private function init()
{
$response = $this->fetch('init', 'POST');
$response = json_decode($response, true);

if (
$this->collector !== null &&
isset($response['collectUrl']) &&
isset($response['deploymentID']) &&
isset($response['index'])
) {
$this->collector->setParams(
$response['collectUrl'],
$response['deploymentID'],
$response['index']
);
}
}

private function fetch($path, $method, $body = [])
{
$endpoint = "{$this->endpoint}/{$path}?api-key={$this->apiKey}";

$requestOptions = [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded'
]
];

if ($method === 'POST' && $body !== []) {
$b = $body;
$b['version'] = 'php-sdk-1.0.0';
$b['id'] = $this->id;

$requestOptions['body'] = http_build_query($body);
}

$response = $this->http->request('POST', $endpoint, $requestOptions);

return $response->getBody();
}
}
8 changes: 6 additions & 2 deletions src/Client/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,18 @@ public function __construct($term = '', $mode = 'fulltext')
$this->mode = $mode;
}

public function term($term)
public function term(string $term)
{
$this->term = $term;
return $this;
}

public function mode($mode)
public function mode(string $mode)
{
if (!in_array($mode, ['fulltext', 'vector', 'hybrid'])) {
throw new QueryException('Invalid search mode. Must be one of: fulltext, vector, hybrid.');
}

$this->mode = $mode;
return $this;
}
Expand Down
11 changes: 11 additions & 0 deletions src/Client/QueryException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace OramaCloud\Client;

class QueryException extends \Exception
{
public function __construct($message)
{
parent::__construct($message);
}
}
92 changes: 0 additions & 92 deletions src/Telemetry/Collector.php

This file was deleted.

45 changes: 28 additions & 17 deletions tests/Feature/ClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,42 @@ class ClientTest extends TestCase
const API_ENDPOINT = 'mock-endpoint';
const PUBLIC_API_KEY = 'mock-api-key';

public function testBasicFulltextSearch()
protected $capturedRequests;
protected $httpClient;

protected function setUp(): void
{
// Create a mock handler and queue a response.
$mock = new MockHandler([
// initial request to get the collect URL
new Response(200, [], json_encode([
'collectUrl' => 'mock-url',
'deploymentID' => 'mock-deployment-id',
'index' => 'mock-index',
])),
// Reset capturedRequests before each test
$this->capturedRequests = [];

// Middleware to capture requests
$captureMiddleware = function ($handler) {
return function ($request, $options) use ($handler) {
$this->capturedRequests[] = $request;
return $handler($request, $options);
};
};

$mockResponse = new MockHandler([
// search request
new Response(200, [], json_encode([
'hits' => [['id' => 2]],
'elapsed' => 0.2,
'count' => 1,
])),
// telemetry data collection
new Response(200, [], json_encode([
'message' => 'Telemetry data collected successfully',
])),
]))
]);

$handlerStack = HandlerStack::create($mock);
$mockClient = new GuzzleClient(['handler' => $handlerStack]);
$handlerStack = HandlerStack::create($mockResponse);
$handlerStack->push($captureMiddleware, 'capture_middleware');
$this->httpClient = new GuzzleClient(['handler' => $handlerStack]);
}

public function testBasicFulltextSearch()
{
$client = new Client([
'api_key' => self::PUBLIC_API_KEY,
'endpoint' => self::API_ENDPOINT,
], $mockClient);
], $this->httpClient);

$result = $client->search(
(new Query())
Expand All @@ -58,5 +65,9 @@ public function testBasicFulltextSearch()

$this->assertGreaterThan(0, $result['count']);
$this->assertLessThanOrEqual(10, count($result['hits']));

$lastRequest = end($this->capturedRequests);
$this->assertEquals('POST', $lastRequest->getMethod());
$this->assertEquals(self::API_ENDPOINT . '/search', $lastRequest->getUri()->getPath());
}
}
2 changes: 1 addition & 1 deletion tests/Unit/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function testQueryParamsFromArray()
{
$params = [
'term' => 'mock-term',
'mode' => 'mock-mode',
'mode' => 'vector',
'where' => [
'foo' => [
'eq' => 99
Expand Down

0 comments on commit a5d4369

Please sign in to comment.