Skip to content

Commit

Permalink
android: lazily init app in Client (#563)
Browse files Browse the repository at this point in the history
-Lazily init app in Client to ensure that we aren't trying to make any local API calls before app has been initialized.
-Add @volatile to ensure that isInitialized is always visible across threads and uses the updated value

Updates tailscale/tailscale#14125

Signed-off-by: kari-ts <[email protected]>
  • Loading branch information
kari-ts authored Nov 21, 2024
1 parent ed8a1b3 commit c56420b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
13 changes: 12 additions & 1 deletion android/src/main/java/com/tailscale/ipn/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,13 @@ class App : UninitializedApp(), libtailscale.AppContext, ViewModelStoreOwner {
Log.d(s, s1)
}

fun getLibtailscaleApp(): libtailscale.Application {
if (!isInitialized) {
initOnce() // Calls the synchronized initialization logic
}
return app
}

override fun onCreate() {
super.onCreate()
appInstance = this
Expand Down Expand Up @@ -119,15 +126,19 @@ class App : UninitializedApp(), libtailscale.AppContext, ViewModelStoreOwner {
viewModelStore.clear()
}

private var isInitialized = false
@Volatile private var isInitialized = false

@Synchronized
private fun initOnce() {
if (isInitialized) {
return
}

initializeApp()
isInitialized = true
}

private fun initializeApp() {
val dataDir = this.filesDir.absolutePath

// Set this to enable direct mode for taildrop whereby downloads will be saved directly
Expand Down
6 changes: 6 additions & 0 deletions android/src/main/java/com/tailscale/ipn/ui/localapi/Client.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import com.tailscale.ipn.ui.model.StableNodeID
import com.tailscale.ipn.ui.model.Tailcfg
import com.tailscale.ipn.ui.util.InputStreamAdapter
import com.tailscale.ipn.util.TSLog
import com.tailscale.ipn.App
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
Expand Down Expand Up @@ -67,6 +68,11 @@ typealias PingResultHandler = (Result<IpnState.PingResult>) -> Unit
class Client(private val scope: CoroutineScope) {
private val TAG = Client::class.simpleName

// Access libtailscale.Application lazily
private val app: libtailscale.Application by lazy {
App.get().getLibtailscaleApp()
}

fun start(options: Ipn.Options, responseHandler: (Result<Unit>) -> Unit) {
val body = Json.encodeToString(options).toByteArray()
return post(Endpoint.START, body, responseHandler = responseHandler)
Expand Down

0 comments on commit c56420b

Please sign in to comment.