Skip to content

Commit 2539704

Browse files
authored
Merge pull request #348 from alyssaruth/sync-fixes
Attempt to make file steps of sync more resilient
2 parents 70b8bda + f762219 commit 2539704

9 files changed

Lines changed: 196 additions & 15 deletions

File tree

‎src/main/kotlin/dartzee/core/util/FileUtil.kt‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,18 @@ object FileUtil {
2727
val newFile = File(newFilePath)
2828
val zzOldFile = File(oldFile.parent, "zz$oldFileName")
2929

30+
logger.info(CODE_SWITCHING_FILES, "Pre-delete [$zzOldFile] in case it exists already")
31+
if (!zzOldFile.deleteRecursively()) {
32+
return "Failed to tidy up before move."
33+
}
34+
3035
logger.info(CODE_SWITCHING_FILES, "Rename current out of the way [$oldFile -> $zzOldFile]")
31-
if (oldFile.exists() && !oldFile.renameTo(zzOldFile)) {
36+
if (oldFile.exists() && !oldFile.renameToWithRetries(zzOldFile)) {
3237
return "Failed to rename old out of the way."
3338
}
3439

3540
logger.info(CODE_SWITCHING_FILES, "Rename new to current [$newFile -> $oldFile]")
36-
if (!newFile.renameTo(File(oldFile.parent, oldFileName))) {
41+
if (!newFile.renameToWithRetries(File(oldFile.parent, oldFileName))) {
3742
return "Failed to rename new file to $oldFileName"
3843
}
3944

@@ -45,6 +50,38 @@ object FileUtil {
4550
return null
4651
}
4752

53+
tailrec fun File.renameToWithRetries(newFile: File, attempt: Int = 1): Boolean {
54+
if (!exists()) {
55+
logger.error(
56+
CODE_FILE_ERROR,
57+
"Trying to rename [$this] to [$newFile] but it does not exist",
58+
)
59+
return false
60+
}
61+
62+
if (newFile.exists()) {
63+
logger.error(
64+
CODE_FILE_ERROR,
65+
"Trying to rename [$this] to [$newFile] but [$newFile] already exists",
66+
)
67+
return false
68+
}
69+
70+
val success = renameTo(newFile)
71+
return if (success) {
72+
true
73+
} else if (attempt == 5) {
74+
false
75+
} else {
76+
logger.warn(
77+
CODE_FILE_ERROR,
78+
"Failed to rename [$this] to [$newFile] on attempt $attempt, will retry.",
79+
)
80+
Thread.sleep(500)
81+
renameToWithRetries(newFile, attempt + 1)
82+
}
83+
}
84+
4885
fun getImageDim(file: File): Dimension? {
4986
val iter = ImageIO.getImageReadersBySuffix(file.extension)
5087
val reader = if (iter.hasNext()) iter.next() else null

‎src/main/kotlin/dartzee/logging/LoggingConsole.kt‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ import dartzee.core.util.setMargins
66
import dartzee.db.SqlStatementType
77
import dartzee.screen.FocusableWindow
88
import dartzee.utils.DartsDatabaseUtil
9+
import dartzee.utils.InjectedThings
910
import java.awt.BorderLayout
1011
import java.awt.Color
1112
import java.awt.Component
13+
import java.io.File
1214
import javax.swing.JLabel
1315
import javax.swing.JPanel
1416
import javax.swing.JScrollPane
@@ -94,6 +96,21 @@ class LoggingConsole : FocusableWindow(), ILogDestination {
9496
}
9597
}
9698

99+
@Suppress("SwallowedException")
100+
fun getText(): String =
101+
try {
102+
doc.getText(0, doc.length)
103+
} catch (_: Throwable) {
104+
""
105+
}
106+
107+
fun dumpLogs() {
108+
val f =
109+
File("${System.getProperty("user.dir")}/logdump-${InjectedThings.clock.instant()}.txt")
110+
f.createNewFile()
111+
f.writeText(getText())
112+
}
113+
97114
private fun factoryLabelForContext(field: Map.Entry<String, Any?>): Component {
98115
val label = JLabel("${field.key}: ${field.value}")
99116
label.foreground = Color.GREEN

‎src/main/kotlin/dartzee/screen/DartsApp.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ private const val CMD_CLEAR_CONSOLE = "cls"
3636
private const val CMD_EMPTY_SCREEN_CACHE = "emptyscr"
3737
private const val CMD_GUID = "guid"
3838
private const val CMD_TEST = "test"
39+
private const val CMD_DUMP_LOGS = "dump logs"
3940

4041
val APP_SIZE = Dimension(1000, 700)
4142

@@ -166,6 +167,8 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList
166167
} else if (cmd == CMD_TEST) {
167168
val window = TestWindow()
168169
window.isVisible = true
170+
} else if (cmd == CMD_DUMP_LOGS) {
171+
InjectedThings.loggingConsole.dumpLogs()
169172
}
170173

171174
return textToShow

‎src/main/kotlin/dartzee/sync/SyncManager.kt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import dartzee.utils.Database
2323
import dartzee.utils.DatabaseMigrations
2424
import dartzee.utils.InjectedThings.databaseDirectory
2525
import dartzee.utils.InjectedThings.logger
26+
import dartzee.utils.InjectedThings.loggingConsole
2627
import dartzee.utils.InjectedThings.mainDatabase
2728
import java.io.File
2829
import java.io.InterruptedIOException
@@ -136,6 +137,7 @@ class SyncManager(private val dbStore: IRemoteDatabaseStore) {
136137
SyncProgressDialog.dispose()
137138

138139
if (!success) {
140+
loggingConsole.dumpLogs()
139141
return null
140142
}
141143

‎src/main/kotlin/dartzee/utils/DartsDatabaseUtil.kt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,6 @@ object DartsDatabaseUtil {
190190
}
191191

192192
fun swapInDatabase(otherDatabase: Database): Boolean {
193-
// Now switch it in
194193
try {
195194
mainDatabase.shutDown()
196195
otherDatabase.shutDown()

src/test/kotlin/dartzee/core/util/TestFileUtil.kt renamed to src/test/kotlin/dartzee/core/util/FileUtilTest.kt

Lines changed: 100 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
package dartzee.core.util
22

3+
import dartzee.core.util.FileUtil.renameToWithRetries
34
import dartzee.helper.AbstractTest
45
import dartzee.logging.CODE_FILE_ERROR
56
import dartzee.logging.Severity
67
import io.kotest.matchers.collections.shouldContainExactly
8+
import io.kotest.matchers.file.shouldExist
9+
import io.kotest.matchers.file.shouldNotExist
710
import io.kotest.matchers.shouldBe
811
import io.kotest.matchers.types.shouldBeInstanceOf
12+
import io.mockk.every
13+
import io.mockk.mockk
914
import java.awt.Dimension
1015
import java.io.File
1116
import java.nio.file.DirectoryNotEmptyException
@@ -14,7 +19,7 @@ import org.junit.jupiter.api.AfterEach
1419
import org.junit.jupiter.api.BeforeEach
1520
import org.junit.jupiter.api.Test
1621

17-
class TestFileUtil : AbstractTest() {
22+
class FileUtilTest : AbstractTest() {
1823
private val testDirectory = File("Test/")
1924

2025
@BeforeEach
@@ -67,7 +72,7 @@ class TestFileUtil : AbstractTest() {
6772
new.createNewFile()
6873
new.writeText("New")
6974

70-
FileUtil.swapInFile(current.path, new.path)
75+
FileUtil.swapInFile(current.path, new.path) shouldBe null
7176

7277
new.exists() shouldBe false
7378
current.exists() shouldBe true
@@ -87,13 +92,105 @@ class TestFileUtil : AbstractTest() {
8792
new.createNewFile()
8893
new.writeText("New")
8994

90-
FileUtil.swapInFile("Test/Current", "Test/New")
95+
FileUtil.swapInFile("Test/Current", "Test/New") shouldBe null
9196

9297
new.exists() shouldBe false
9398
current.exists() shouldBe true
9499
current.readLines().shouldContainExactly("New")
95100
}
96101

102+
@Test
103+
fun `Should pre-clean for when a move has previously failed`() {
104+
val zzDir = File("Test/zzCurrent")
105+
zzDir.mkdir()
106+
107+
val inTheWay = File("Test/zzCurrent/Bad.txt")
108+
inTheWay.createNewFile()
109+
inTheWay.writeText("muahaha")
110+
111+
val currentDir = File("Test/Current")
112+
currentDir.mkdir()
113+
val newDir = File("Test/New")
114+
newDir.mkdir()
115+
116+
val current = File("Test/Current/File.txt")
117+
current.createNewFile()
118+
current.writeText("Current")
119+
120+
val new = File("Test/New/File.txt")
121+
new.createNewFile()
122+
new.writeText("New")
123+
124+
FileUtil.swapInFile("Test/Current", "Test/New") shouldBe null
125+
126+
zzDir.shouldNotExist()
127+
inTheWay.shouldNotExist()
128+
newDir.shouldNotExist()
129+
new.shouldNotExist()
130+
131+
currentDir.shouldExist()
132+
current.shouldExist()
133+
current.readLines().shouldContainExactly("New")
134+
}
135+
136+
@Test
137+
fun `Rename should fail for non-existent file`() {
138+
val f = File("Test/Test.txt")
139+
140+
f.renameToWithRetries(File("Test/New.txt")) shouldBe false
141+
142+
val error = verifyLog(CODE_FILE_ERROR, Severity.ERROR)
143+
error.message shouldBe
144+
"Trying to rename [Test/Test.txt] to [Test/New.txt] but it does not exist"
145+
}
146+
147+
@Test
148+
fun `Rename should fail if destination already exists`() {
149+
val f = File("Test/Test.txt")
150+
f.createNewFile()
151+
val new = File("Test/New.txt")
152+
new.createNewFile()
153+
154+
f.renameToWithRetries(new) shouldBe false
155+
156+
val error = verifyLog(CODE_FILE_ERROR, Severity.ERROR)
157+
error.message shouldBe
158+
"Trying to rename [Test/Test.txt] to [Test/New.txt] but [Test/New.txt] already exists"
159+
}
160+
161+
@Test
162+
fun `Rename should succeed on retry`() {
163+
val f = mockk<File>()
164+
every { f.exists() } returns true
165+
166+
var counter = 0
167+
every { f.renameTo(any()) } answers
168+
{
169+
if (counter < 2) {
170+
counter++
171+
false
172+
} else {
173+
true
174+
}
175+
}
176+
177+
val new = File("Test/New.txt")
178+
f.renameToWithRetries(new) shouldBe true
179+
180+
verifyLog(CODE_FILE_ERROR, Severity.WARN)
181+
}
182+
183+
@Test
184+
fun `Rename should give up on persistent failure`() {
185+
val f = mockk<File>()
186+
every { f.exists() } returns true
187+
every { f.renameTo(any()) } returns false
188+
189+
val new = File("Test/New.txt")
190+
191+
f.renameToWithRetries(new) shouldBe false
192+
}
193+
97194
@Test
98195
fun `Should read image dimensions correctly`() {
99196
val bean = javaClass.getResource("/Bean.png")!!.toURI()

‎src/test/kotlin/dartzee/helper/AbstractTest.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package dartzee.helper
22

33
import com.github.alyssaburlton.swingtest.SwingTestCleanupExtension
4+
import dartzee.CURRENT_TIME
45
import dartzee.core.helper.TestMessageDialogFactory
56
import dartzee.core.util.DialogUtil
67
import dartzee.logging.LogDestinationSystemOut
@@ -20,6 +21,7 @@ import io.kotest.matchers.nulls.shouldNotBeNull
2021
import io.kotest.matchers.shouldBe
2122
import io.mockk.clearAllMocks
2223
import io.mockk.mockk
24+
import java.io.File
2325
import java.time.LocalDate
2426
import java.time.Month
2527
import org.junit.jupiter.api.AfterEach
@@ -32,6 +34,7 @@ private var checkedForExceptions = false
3234

3335
const val TEST_ROOT = "Test/"
3436
const val TEST_DB_DIRECTORY = "Test/Databases"
37+
val LOG_DUMP_FILE = File("logdump-${CURRENT_TIME}.txt")
3538

3639
@ExtendWith(BeforeAllTestsExtension::class)
3740
@ExtendWith(SwingTestCleanupExtension::class)

src/test/kotlin/dartzee/logging/TestLoggingConsole.kt renamed to src/test/kotlin/dartzee/logging/LoggingConsoleTest.kt

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,26 @@ package dartzee.logging
33
import com.github.alyssaburlton.swingtest.flushEdt
44
import dartzee.core.util.getAllChildComponentsForType
55
import dartzee.helper.AbstractTest
6+
import dartzee.helper.LOG_DUMP_FILE
67
import dartzee.makeLogRecord
78
import io.kotest.matchers.collections.shouldBeEmpty
89
import io.kotest.matchers.collections.shouldContainExactly
910
import io.kotest.matchers.comparables.shouldBeGreaterThan
11+
import io.kotest.matchers.file.shouldExist
1012
import io.kotest.matchers.shouldBe
1113
import io.kotest.matchers.string.shouldContain
1214
import java.awt.Color
1315
import javax.swing.JLabel
1416
import javax.swing.text.StyleConstants
17+
import org.junit.jupiter.api.AfterEach
1518
import org.junit.jupiter.api.Test
1619

17-
class TestLoggingConsole : AbstractTest() {
20+
class LoggingConsoleTest : AbstractTest() {
21+
@AfterEach
22+
fun afterEach() {
23+
LOG_DUMP_FILE.delete()
24+
}
25+
1826
@Test
1927
fun `Should separate log records with a new line`() {
2028
val recordOne = makeLogRecord(loggingCode = LoggingCode("foo"), message = "log one")
@@ -172,12 +180,19 @@ class TestLoggingConsole : AbstractTest() {
172180
newLabels.map { it.text }.shouldContainExactly("appVersion: 4.1.1", "devMode: false")
173181
}
174182

175-
private fun LoggingConsole.getText(): String =
176-
try {
177-
doc.getText(0, doc.length)
178-
} catch (t: Throwable) {
179-
""
180-
}
183+
@Test
184+
fun `Should dump logs to file`() {
185+
val recordOne = makeLogRecord(loggingCode = LoggingCode("foo"), message = "log one")
186+
val recordTwo = makeLogRecord(loggingCode = LoggingCode("bar"), message = "log two")
187+
188+
val console = LoggingConsole()
189+
console.log(recordOne)
190+
console.log(recordTwo)
191+
console.dumpLogs()
192+
193+
LOG_DUMP_FILE.shouldExist()
194+
LOG_DUMP_FILE.readText() shouldBe "\n$recordOne\n$recordTwo"
195+
}
181196

182197
private fun LoggingConsole.getTextColour(position: Int = 0): Color {
183198
val style = doc.getCharacterElement(position)

0 commit comments

Comments
 (0)