Skip to content

Commit

Permalink
[YLS] 해시 함수 외부로 빼냄 (#13)
Browse files Browse the repository at this point in the history
* #5 feat: HashUtil

* #5 feat: flush 로직 추가

* #5 move: Retrofit.kt worker 패키지로 이동
  • Loading branch information
cometj03 authored Feb 18, 2024
1 parent 72c9a15 commit 04f9d4b
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 44 deletions.
30 changes: 30 additions & 0 deletions yls/src/main/kotlin/com/yourssu/logging/system/HashUtil.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.yourssu.logging.system

import java.lang.StringBuilder
import java.security.MessageDigest

object HashUtil {
// 캐싱
private var _id: String? = null
private var _hashedId: String? = null

fun hashId(id: String): String {
if (_id == id && _hashedId != null) {
return _hashedId!!
}

_hashedId = hashString(id)
_id = id
return _hashedId!!
}

internal fun hashString(origin: String, algorithm: String = "SHA-256"): String {
return MessageDigest.getInstance(algorithm)
.digest(origin.toByteArray())
.let { bytes ->
bytes.fold(StringBuilder(bytes.size * 2)) { str, it ->
str.append("%02x".format(it))
}
}.toString()
}
}
47 changes: 12 additions & 35 deletions yls/src/main/kotlin/com/yourssu/logging/system/YLS.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,14 @@ package com.yourssu.logging.system

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.util.Log
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.workDataOf
import com.google.gson.Gson
import com.yourssu.logging.system.HashUtil.hashId
import com.yourssu.logging.system.worker.RemoteLoggingWorker
import java.lang.StringBuilder
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.Date

class YLS private constructor() {
Expand All @@ -33,6 +28,7 @@ class YLS private constructor() {
}

open fun flush() {
if (queue.isEmpty()) return
log(queue)
queue.clear()
}
Expand Down Expand Up @@ -70,16 +66,18 @@ class YLS private constructor() {

fun init(
platform: String,
user: String?,
user: String,
logger: Logger,
) {
this.defaultEvent = mapOf("platform" to platform)
this.userID = user ?: generateRandomId(10)
this.userID = user
this.logger = logger
}

fun log(vararg events: Pair<String, Any>) {
if (!::logger.isInitialized) throw AssertionError("Not Initialized!")
if (!::logger.isInitialized) {
throw AssertionError("Not initialized! : YLS.init()을 먼저 호출해 주세요.")
}

val eventData = YLSEventData(
hashedID = hashId(userID),
Expand All @@ -90,40 +88,19 @@ class YLS private constructor() {
}

fun flush() {
if (!::logger.isInitialized) {
throw AssertionError("Not initialized! : YLS.init()을 먼저 호출해 주세요.")
}
logger.flush()
}

internal fun generateRandomId(length: Int): String {
fun generateRandomId(length: Int): String {
val charset = '!'..'~' // ASCII 33 ~ 126
return (1..length).map { charset.random() }.joinToString("")
}

// hashId() 메서드에서만 사용되는 변수
private var _id: String? = null
private var _hashedId: String? = null

internal fun hashId(id: String): String {
if (_id == id && _hashedId != null) {
return _hashedId!!
}
return id.hashString().also {
_id = id
_hashedId = it
}
}

@SuppressLint("SimpleDateFormat")
internal fun getTimestampISO8601(): String =
fun getTimestampISO8601(): String =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(Date())
}
}

internal fun String.hashString(algorithm: String = "SHA-256"): String {
return MessageDigest.getInstance(algorithm)
.digest(this.toByteArray())
.let { bytes ->
bytes.fold(StringBuilder(bytes.size * 2)) { str, it ->
str.append("%02x".format(it))
}
}.toString()
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.google.gson.Gson
import com.yourssu.logging.system.HttpService
import com.yourssu.logging.system.YLSEventData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.yourssu.logging.system
package com.yourssu.logging.system.worker

import com.yourssu.logging.system.YLSEventData
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.PUT
Expand Down
19 changes: 12 additions & 7 deletions yls/src/test/kotlin/com/yourssu/logging/system/LoggingTest.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.yourssu.logging.system

import com.yourssu.logging.system.HashUtil.hashId
import com.yourssu.logging.system.HashUtil.hashString
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
Expand Down Expand Up @@ -41,12 +43,15 @@ class LoggingTest {
"screen" to "LoginScreen",
)

testLogger.lastEventData?.let {
assertEquals("abc".hashString(), it.hashedID)
assertEquals("android", it.event["platform"])
assertEquals("ButtonClicked", it.event["event"])
assertEquals("LoginScreen", it.event["screen"])
} ?: assertTrue(false) // if null, then fail
val e = testLogger.lastEventData
if (e != null) {
assertEquals(hashString("abc"), e.hashedID)
assertEquals("android", e.event["platform"])
assertEquals("ButtonClicked", e.event["event"])
assertEquals("LoginScreen", e.event["screen"])
} else {
assertTrue(false) // always fail
}
}

@Test
Expand Down Expand Up @@ -74,6 +79,6 @@ class LoggingTest {
// 함수 테스트
println(YLS.generateRandomId(10))
println(YLS.getTimestampISO8601())
println(YLS.hashId("abc"))
println(hashId("abc"))
}
}

0 comments on commit 04f9d4b

Please sign in to comment.