Skip to content

Commit

Permalink
Fixed start delta time calculations
Browse files Browse the repository at this point in the history
  • Loading branch information
Donal Byrne committed Nov 15, 2017
1 parent 219c1c3 commit fb82dda
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/NatsStreaming/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace NatsStreaming;

use Exception;
use Nats\Message;
use Nats\Php71RandomGenerator;
use NatsStreaming\Contracts\ConnectionContract;
Expand Down Expand Up @@ -212,6 +213,18 @@ public function queueSubscribe($subjects, $qGroup, callable $cb, $subscriptionOp
return $this->_subscribe($subjects, $qGroup, $cb, $subscriptionOptions);
}

/**
* Returns unix time in nanoseconds
* could use `date +%S` instead, need to benchmark
* @return int
*/
public static function unixTimeNanos(){
list ($micro, $secs) = explode(" ", microtime());
$nanosOffset = $micro * 1000000000;
$totalNanos = $secs * 1000000000 + $nanosOffset;
return (int) $totalNanos;
}


/**
*
Expand Down Expand Up @@ -258,7 +271,8 @@ private function _subscribe($subject, $qGroup, callable $cb, $subscriptionOption
$req->setStartSequence($subscriptionOptions->getStartSequence());
break;
case StartPosition::TimeDeltaStart_VALUE:
$nowNano = microtime() * 1000;

$nowNano = self::unixTimeNanos();
$req->setStartTimeDelta($nowNano - $subscriptionOptions->getStartMicroTime() * 1000);
break;
}
Expand Down
21 changes: 21 additions & 0 deletions tests/Unit/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,27 @@ public function setUp()
$this->c = new Connection($options);
//$this->c->connect();
}


public function testUnixNanos(){
$timeAsNanos = Connection::unixTimeNanos();

sleep(1);

$timeAsNanosAfter = Connection::unixTimeNanos();

$this->assertInternalType('int', $timeAsNanos);

$delta = $timeAsNanosAfter - $timeAsNanos;
$this->assertGreaterThanOrEqual(1000000000, $delta);
// margin of 10 microseconds
$this->assertLessThan(1001000000, $delta);

$timeNowNanos = Connection::unixTimeNanos();
$timeNowSeconds = time();
$this->assertEquals($timeNowSeconds,(int)($timeNowNanos / 1000000000));

}
/**
* Test Connection.
*
Expand Down

0 comments on commit fb82dda

Please sign in to comment.