Skip to content

Commit

Permalink
hack to test coroutines TT
Browse files Browse the repository at this point in the history
  • Loading branch information
kaushikgopal committed Nov 26, 2020
1 parent 94b15cc commit de1045d
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 18 deletions.
14 changes: 14 additions & 0 deletions app/src/main/java/com/instacart/library/sample/SampleActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.instacart.library.truetime.TrueTime
import com.instacart.library.truetime.TrueTime2
import com.instacart.library.truetime.TrueTimeImpl
import com.instacart.library.truetime.TrueTimeParameters
import com.instacart.library.truetime.sntp.SntpClient
import kotlinx.android.synthetic.main.activity_sample.*
import java.text.SimpleDateFormat
import java.util.Date
Expand All @@ -13,6 +17,8 @@ import java.util.TimeZone

class SampleActivity : AppCompatActivity() {

val tt2: TrueTime2 = TrueTimeImpl(SntpClient())

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
Expand All @@ -33,6 +39,8 @@ class SampleActivity : AppCompatActivity() {
return
}

testing()

val trueTime = TrueTime.now()
val deviceTime = Date()

Expand All @@ -50,6 +58,12 @@ class SampleActivity : AppCompatActivity() {
)
}

private fun testing() {
tt2.initialize(TrueTimeParameters())
Toast.makeText(this, "tt2 ${tt2.nowSafely()}", Toast.LENGTH_SHORT)
.show()
}

private fun formatDate(date: Date, pattern: String, timeZone: TimeZone): String {
val format = SimpleDateFormat(pattern, Locale.ENGLISH)
format.timeZone = timeZone
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,8 @@ class TrueTimeRx : TrueTime() {
"---- requestTime from: $singleIpHostAddress"
)
try {
o.onNext(requestTime(singleIpHostAddress))
val testing = requestTime(singleIpHostAddress)
o.onNext(testing)
o.onComplete()
} catch (e: IOException) {
o.tryOnError(e)
Expand All @@ -194,7 +195,7 @@ class TrueTimeRx : TrueTime() {
private fun filterLeastRoundTripDelay(): Function<List<LongArray>, LongArray> {
return Function { responseTimeList ->
val sorted = responseTimeList.sortedBy {
SntpClient.getRoundTripDelay(it)
SNTP_CLIENT.getRoundTripDelay(it)
}

TrueLog.d(TAG, "---- filterLeastRoundTrip: $sorted")
Expand All @@ -206,7 +207,7 @@ class TrueTimeRx : TrueTime() {
private fun filterMedianResponse(): Function<List<LongArray>, LongArray> {
return Function { bestResponses ->
val sorted = bestResponses.sortedBy {
SntpClient.getClockOffset(it)
SNTP_CLIENT.getClockOffset(it)
}

TrueLog.d(TAG, "---- bestResponse: " + Arrays.toString(sorted[sorted.size / 2]))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ open class TrueTime {

private val INSTANCE = TrueTime()
private val DISK_CACHE_CLIENT = DiskCacheClient()
private val SNTP_CLIENT = SntpClient()
val SNTP_CLIENT = SntpClient()

private var rootDelayMax = 100f
private var rootDispersionMax = 100f
Expand All @@ -38,7 +38,7 @@ open class TrueTime {
return Date(now)
}

@JvmStatic fun isInitialized(): Boolean = SNTP_CLIENT.wasInitialized() || DISK_CACHE_CLIENT.isTrueTimeCachedFromAPreviousBoot()
@JvmStatic fun isInitialized(): Boolean = SNTP_CLIENT.wasInitialized() // || DISK_CACHE_CLIENT.isTrueTimeCachedFromAPreviousBoot()

@JvmStatic fun build(): TrueTime {
return INSTANCE
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.instacart.library.truetime.sntp

import com.instacart.library.truetime.TrueTimeParameters
import java.io.IOException

interface Sntp {
/**
Expand All @@ -20,7 +21,8 @@ interface Sntp {
*
* @param ntpHostAddress host name of the server.
*/
suspend fun requestTime(
@Throws(IOException::class)
fun requestTime(
with: TrueTimeParameters,
ntpHostAddress: String? = null,
): LongArray = requestTime(
Expand All @@ -31,11 +33,14 @@ interface Sntp {
with.connectionTimeoutInMillis
)

suspend fun requestTime(
@Throws(IOException::class)
fun requestTime(
ntpHostAddress: String,
rootDelayMax: Float,
rootDispersionMax: Float,
serverResponseDelayMax: Int,
timeoutInMillis: Int,
): LongArray

fun sntpTime(ntpTimeResult: LongArray): Long
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,24 @@
import android.os.SystemClock;
import com.instacart.library.truetime.InvalidNtpServerResponseException;
import com.instacart.library.truetime.TrueLog;
import com.instacart.library.truetime.TrueTimeParameters;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import kotlin.coroutines.Continuation;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Simple SNTP client class for retrieving network time.
* Original source: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/net/SntpClient.java
*
* Intentionally keeping this Java for easier diffing and keeping up to date with platform
*/
public class SntpClient {
public class SntpClient implements Sntp {

public static final int RESPONSE_INDEX_ORIGINATE_TIME = 0;
public static final int RESPONSE_INDEX_RECEIVE_TIME = 1;
Expand Down Expand Up @@ -70,7 +74,8 @@ public class SntpClient {
* See δ :
* https://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_synchronization_algorithm
*/
public static long getRoundTripDelay(long[] response) {
@Override
public long getRoundTripDelay(long[] response) {
return (response[RESPONSE_INDEX_RESPONSE_TIME] - response[RESPONSE_INDEX_ORIGINATE_TIME]) -
(response[RESPONSE_INDEX_TRANSMIT_TIME] - response[RESPONSE_INDEX_RECEIVE_TIME]);
}
Expand All @@ -79,23 +84,41 @@ public static long getRoundTripDelay(long[] response) {
* See θ :
* https://en.wikipedia.org/wiki/Network_Time_Protocol#Clock_synchronization_algorithm
*/
public static long getClockOffset(long[] response) {
@Override
public long getClockOffset(long[] response) {
return ((response[RESPONSE_INDEX_RECEIVE_TIME] - response[RESPONSE_INDEX_ORIGINATE_TIME]) +
(response[RESPONSE_INDEX_TRANSMIT_TIME] - response[RESPONSE_INDEX_RESPONSE_TIME])) / 2;
}

@NotNull
@Override
public long[] requestTime(@NotNull TrueTimeParameters with, @Nullable String ntpHostAddress) throws IOException {
String hostAdd = with.getNtpHostPool();
if (ntpHostAddress != null || !ntpHostAddress.isEmpty()) {
hostAdd = ntpHostAddress;
}

return requestTime(
hostAdd,
with.getRootDelayMax(),
with.getRootDispersionMax(),
with.getServerResponseDelayMax(),
with.getConnectionTimeoutInMillis()
);
}

/**
* Sends an NTP request to the given host and processes the response.
*
* @param ntpHost host name of the server.
*/
synchronized long[] requestTime(String ntpHost,
@NotNull
public synchronized long[] requestTime(String ntpHost,
float rootDelayMax,
float rootDispersionMax,
int serverResponseDelayMax,
int timeoutInMillis
)
throws IOException {
) throws IOException {

DatagramSocket socket = null;

Expand Down Expand Up @@ -217,32 +240,37 @@ synchronized long[] requestTime(String ntpHost,
}
}

void cacheTrueTimeInfo(long[] response) {
// TODO
public void cacheTrueTimeInfo(long[] response) {
_cachedSntpTime.set(sntpTime(response));
_cachedDeviceUptime.set(response[RESPONSE_INDEX_RESPONSE_TICKS]);
}

long sntpTime(long[] response) {
@Override
public long sntpTime(long[] response) {
long clockOffset = getClockOffset(response);
long responseTime = response[RESPONSE_INDEX_RESPONSE_TIME];
return responseTime + clockOffset;
}

boolean wasInitialized() {
// TODO
public boolean wasInitialized() {
return _sntpInitialized.get();
}

/**
* TODO
* @return time value computed from NTP server response
*/
long getCachedSntpTime() {
public long getCachedSntpTime() {
return _cachedSntpTime.get();
}

/**
* TODO
* @return device uptime computed at time of executing the NTP request
*/
long getCachedDeviceUptime() {
public long getCachedDeviceUptime() {
return _cachedDeviceUptime.get();
}

Expand Down Expand Up @@ -343,4 +371,5 @@ private int ui(byte b) {
private double doubleMillis(long fix) {
return fix / 65.536D;
}

}

0 comments on commit de1045d

Please sign in to comment.