1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.datastore.core
18 
19 import kotlin.contracts.ExperimentalContracts
20 import kotlinx.coroutines.flow.Flow
21 import kotlinx.coroutines.flow.flow
22 import kotlinx.coroutines.sync.Mutex
23 import kotlinx.coroutines.sync.withLock
24 
25 /**
26  * SingleProcessCoordinator does coordination within a single process. It is used as the default
27  * [InterProcessCoordinator] immplementation unless otherwise specified.
28  */
29 internal class SingleProcessCoordinator(
30     /** The canonical file path of the file managed by [SingleProcessCoordinator]. */
31     private val filePath: String
32 ) : InterProcessCoordinator {
33     private val mutex = Mutex()
34     private val version = AtomicInt(0)
35 
<lambda>null36     override val updateNotifications: Flow<Unit> = flow {}
37 
38     // run block with the exclusive lock
locknull39     override suspend fun <T> lock(block: suspend () -> T): T {
40         return mutex.withLock { block() }
41     }
42 
43     // run block with an attempt to get the exclusive lock, still run even if
44     // attempt fails. Pass a boolean to indicate if the attempt succeeds.
45     @OptIn(ExperimentalContracts::class) // withTryLock
tryLocknull46     override suspend fun <T> tryLock(block: suspend (Boolean) -> T): T {
47         return mutex.withTryLock { block(it) }
48     }
49 
50     // get the current version
getVersionnull51     override suspend fun getVersion(): Int = version.get()
52 
53     // increment version and return the new one
54     override suspend fun incrementAndGetVersion(): Int = version.incrementAndGet()
55 }
56