Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions app/src/main/java/to/bitkit/repositories/PubkyRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,10 @@ class PubkyRepo @Inject constructor(
private val profileSaveEpoch = AtomicLong(0L)
private val profileSavesRunning = AtomicInteger(0)

// Orders each save's Paykit copy write after the one an earlier save left running.
private val copyWriteOrder = Mutex()
private var pendingCopyWrite: Job? = null

/** Revision of the loaded pubky.app profile, which a save must still match; null when none exists. */
@Volatile
private var ownProfileRevision: String? = null
Expand All @@ -245,6 +249,9 @@ class PubkyRepo @Inject constructor(
@Volatile
private var tagsUnavailable = false

// Moved on each time a load sets tagsUnavailable, so a save clears it only if no load set it since the save began.
private val tagsReadEpoch = AtomicLong(0L)

@Volatile
private var restoreBase: RestoreBase? = null
private val signInGeneration = AtomicLong(0L)
Expand Down Expand Up @@ -944,6 +951,7 @@ class PubkyRepo @Inject constructor(
restoreBase = RestoreBase(prefixedKey, it, revision = null)
}
}
tagsReadEpoch.incrementAndGet()
tagsUnavailable = paykitRead.isFailure
PubkyProfile.fromPubkyProfile(prefixedKey, snapshot.profile).copy(tags = paykitData?.tags.orEmpty()).also {
restoreBase = RestoreBase(prefixedKey, it, snapshot.revision)
Expand Down Expand Up @@ -1282,6 +1290,7 @@ class PubkyRepo @Inject constructor(
tagsUnread: Boolean,
): SavedProfile {
val generation = profileDeletionGeneration.get()
val readEpoch = tagsReadEpoch.get()
// Unread when the edit began or now: either way the form's tags are not the stored ones.
val copyUnread = tagsUnread || tagsUnavailable
// A profile written without a base is fitted to pubky.app's limits, as a move is.
Expand Down Expand Up @@ -1335,11 +1344,24 @@ class PubkyRepo @Inject constructor(
}
// Tags live only in the Paykit copy, so a changed tag that it does not take is reported.
val copyData = profile.toProfileData().toPaykitProfile()
val copyError = keptTags?.let {
val writeCopy = suspend {
runSuspendCatching { profileWrite(generation) { pubkyService.publishPaykitProfile(copyData, publicKey) } }
.onSuccess { tagsUnavailable = false }
.onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) }
.exceptionOrNull()
}
val copyError = keptTags?.let {
copyWriteOrder.withLock {
// A copy write left running by an earlier save lands first, so it never overwrites this one.
pendingCopyWrite?.join()
if (it == baseTags) {
// With no tag change to report, the save does not wait for the copy; a deletion refuses or waits
// for it. Its outcome leaves the unread flag alone, which a load may have set since.
pendingCopyWrite = scope.launch { writeCopy() }
markTagsRead(stored, readEpoch)
null
} else {
writeCopy().onSuccess { tagsUnavailable = false }.exceptionOrNull()
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}
}
}
val saved = if (keptTags != null && copyError == null) profile else profile.copy(tags = baseTags)
val tagsLost = (keptTags == null || copyError != null) && tags != baseTags
Expand All @@ -1361,6 +1383,15 @@ class PubkyRepo @Inject constructor(
return StoredCopy(tags = data?.tags.orEmpty(), image = data?.image)
}

/**
* Clears the unread flag after a save read the copy itself and kept its tags in the profile it stores, unless a
* load found the copy unreadable since [readEpoch]. A save that writes the copy at once clears it only once that
* write succeeds, since a failed one stores the profile without the copy's tags.
*/
private fun markTagsRead(stored: StoredCopy?, readEpoch: Long) {
if (stored?.tags != null && tagsReadEpoch.get() == readEpoch) tagsUnavailable = false
}

/** [name], [bio] and [links] fitted to pubky.app's limits: one line, cut to length, at most five valid links. */
private fun fitted(name: String, bio: String, links: List<PubkyProfileLink>) = FittedProfile(
name = name.singleLine().takeCodePoints(PUBKY_APP_NAME_MAX_LENGTH),
Expand All @@ -1379,6 +1410,7 @@ class PubkyRepo @Inject constructor(
val saveEpoch = profileSaveEpoch.get()
val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) }
.onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) }
tagsReadEpoch.incrementAndGet()
tagsUnavailable = paykitRead.isFailure
val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) }
val fetched = readRetryingOnce(publicKey) { pubkyService.fetchPubkyProfileWithRevision(publicKey) }
Expand Down
113 changes: 113 additions & 0 deletions app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,77 @@ class PubkyRepoTest : BaseUnitTest() {
assertEquals("New", sut.profile.value?.name)
}

@Test
fun `saveProfile without a tag change does not wait for the profile copy`() = test {
authenticateForTesting(publicKey = VALID_SELF_KEY)
val finishCopy = CompletableDeferred<Unit>()
whenever { pubkyService.publishPaykitProfile(any(), any()) }.doSuspendableAnswer {
finishCopy.await()
paykitRecord(it.getArgument(0))
}
clearInvocations(pubkyService)

val save = async {
sut.saveProfile(name = "Renamed", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null)
}
runCurrent()

assertTrue(save.isCompleted)
save.await().getOrThrow()
verifyBlocking(pubkyService) { publishPaykitProfile(any(), any()) }
finishCopy.complete(Unit)
}

@Test
fun `a background copy write keeps a later load's unread tags`() = test {
authenticateForTesting(publicKey = VALID_SELF_KEY)
val finishCopy = CompletableDeferred<Unit>()
whenever { pubkyService.publishPaykitProfile(any(), any()) }.doSuspendableAnswer {
finishCopy.await()
paykitRecord(it.getArgument(0))
}
sut.saveProfile(name = "Renamed", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null)
.getOrThrow()
runCurrent()
whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") }
sut.loadProfile()

finishCopy.complete(Unit)
runCurrent()

assertTrue(sut.profileEditBase().tagsUnread)
}

@Test
fun `a save that reads the copy itself lets the next edit remove a tag`() = test {
authenticateForTesting(publicKey = VALID_SELF_KEY)
var copy = PubkyProfileData(name = "Test", bio = "", tags = listOf("a", "b")).toPaykitProfile()
whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { paykitRecord(copy) }
whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer {
copy = it.getArgument(0)
paykitRecord(copy)
}
sut.loadProfile()
val editBase = sut.profileEditBase()
doAnswer { throw TestAppError("offline") }.whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY)
sut.loadProfile()
doAnswer { paykitRecord(copy) }.whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY)

sut.saveProfile(
name = "Test",
bio = "",
links = emptyList(),
tags = listOf("a"),
imageUrl = null,
editBase = editBase
).getOrThrow()
runCurrent()
sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("a"), imageUrl = null).getOrThrow()
runCurrent()

assertEquals(listOf("a"), PubkyProfileData.fromPaykitProfile(copy).tags)
}

@Test
fun `saveProfile signs in again once when the session lacks the pubky app scope`() = test {
val secretKey = "local_secret"
Expand Down Expand Up @@ -1228,6 +1299,48 @@ class PubkyRepoTest : BaseUnitTest() {
assertEquals(listOf("friend", "work", "vip"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags)
}

@Test
fun `a tag save after a failed read and write keeps the stored tags without the error's base`() = test {
authenticateForTesting(publicKey = VALID_SELF_KEY)
whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") }
sut.loadProfile()
doReturn(
paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = listOf("friend", "work")).toPaykitProfile())
)
.whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY)
whenever(pubkyService.publishPaykitProfile(any(), any()))
.thenAnswer { throw TestAppError("offline") }
.thenAnswer { paykitRecord(it.getArgument(0)) }

sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("vip"), imageUrl = null)
sut.saveProfile(name = "Test", bio = "", links = emptyList(), tags = listOf("vip"), imageUrl = null)

val copy = argumentCaptor<PaykitProfile>()
verifyBlocking(pubkyService, times(2)) { publishPaykitProfile(copy.capture(), any()) }
assertEquals(listOf("friend", "work", "vip"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags)
}

@Test
fun `a name save after a failed read and write keeps the stored tags`() = test {
authenticateForTesting(publicKey = VALID_SELF_KEY)
whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") }
sut.loadProfile()
doReturn(
paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = listOf("friend", "work")).toPaykitProfile())
)
.whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY)
whenever(pubkyService.publishPaykitProfile(any(), any()))
.thenAnswer { throw TestAppError("offline") }
.thenAnswer { paykitRecord(it.getArgument(0)) }

sut.saveProfile(name = "Renamed", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null)
sut.saveProfile(name = "Renamed Again", bio = "", links = emptyList(), tags = emptyList(), imageUrl = null)

val copy = argumentCaptor<PaykitProfile>()
verifyBlocking(pubkyService, times(2)) { publishPaykitProfile(copy.capture(), any()) }
assertEquals(listOf("friend", "work"), PubkyProfileData.fromPaykitProfile(copy.lastValue).tags)
}

@Test
fun `saveProfile keeps the stored tags when the edit began while they could not be read`() = test {
authenticateForTesting(publicKey = VALID_SELF_KEY)
Expand Down
Loading